| Title: | Development Version |
|---|---|
| Description: | Development version |
| Authors: | Amanda Bradford [aut, cre] |
| Maintainer: | Amanda Bradford <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.60 |
| Built: | 2026-07-16 20:40:35 UTC |
| Source: | https://github.com/PIFSC-Protected-Species-Division/LTabundR |
This function is typically not called by the user (though it certainly can be);
instead, it is called as a subroutine within lta().
This function estimates density/abundance for Wincruz data,
as processed by LTabundR::process_surveys().
abundance( segments, sightings, das, strata, truncation_distance, use_g0 = TRUE, g0 = c(1, 1), g0_threshold = 20, region_pool = FALSE, region_pool_name = "Regions pooled", region_pool_area = NA, year_pool = FALSE, forced_effort = NULL, verbose = TRUE )abundance( segments, sightings, das, strata, truncation_distance, use_g0 = TRUE, g0 = c(1, 1), g0_threshold = 20, region_pool = FALSE, region_pool_name = "Regions pooled", region_pool_area = NA, year_pool = FALSE, forced_effort = NULL, verbose = TRUE )
segments |
Effort segments dataframe, drawn from a |
sightings |
Sightings dataframe, drawn from a |
das |
Dataframe of DAS data, drawn from a |
strata |
A dataframe, drawn from a |
truncation_distance |
The truncation distance to apply to sightings. |
use_g0 |
A Boolean, with default |
g0 |
A numeric vector of length 2: the |
g0_threshold |
The school size threshold between small and large groups. |
region_pool |
Accepts a Boolean; if |
region_pool_name |
A character string indicating a custom name to use in the |
region_pool_area |
A numeric indicating the area, in square km, of the pooled region.
Only used in the event that |
year_pool |
A Boolean indicating whether or not to pool years (set |
forced_effort |
If this is a single numeric value instead of |
verbose |
Boolean, with default |
A data.frame with a row for each density/abundance estimate.
You may expect multiple rows if multiple regions or years are contained within the datasets provided.
This data.frame contains the following fields:
Region: Name(s) of geostrata represented in this estimate.
Area: Area of geostratum / region, in square km.
year: Years represented in this estimate.
segments: The number of effort segments used to estimate density/abundance.
km: The km of trackline effort contained in these segments.
Area_covered: The Area surveyed, according to km and ESW_mean (see next column).
ESW_mean: Mean effective strip width, in kw, calculated as the truncation distance multiplied by the mean probability of detection for all detections.
n: The number of detections in the data.
g0_mean: The mean g(0) estimate.
ER_clusters: The encounter rate for detections (schools) (n / km)
D_clusters: The density of detections (schools).
N_clusters: The abundance of schools.
size_mean: Average school size.
size_sd: Standard deviation of school size.
ER: Animal encounter rate.
D: Animal density.
N: Animal abundance.
Relative trackline detection probabilities from Barlow (2015).
barlow_2015barlow_2015
An object of class data.frame with 168 rows and 9 columns.
This dataset holds the results from Barlow (2015), "Inferring trackline detection probabilities, g(0), for cetaceans from apparent densities in different survey conditions" (Marine Mammal Science), which used NOAA/NMFS cruise data from 1986 to 2010.
Replicated from the coxed package, which has been archived on CRAN.
Moving code here so that LTabundR can still use this function.
bca(theta, conf.level = 0.95)bca(theta, conf.level = 0.95)
theta |
Expectation. |
conf.level |
Confidence level. |
A two-element vector with the lower and upper confidence interval calculated using the BCA method.
Cruise data processed for the CNP, 1986 - 2020 (150 km segment lengths)
cnp_150km_1986_2020cnp_150km_1986_2020
An object of class list of length 3.
This dataset was processed with the following code:
data(group_size_coefficients)
survey <- load_survey_settings(
out_handling = 'remove',
max_row_interval = Inf,
segment_method = "equallength",
segment_target_km = 150,
segment_max_interval = 24,
segment_remainder_handling = c("segment"),
ship_list = NULL, # use package list
species_codes = NULL, # use package codes
group_size_coefficients = group_size_coefficients, # use package coefficients
smear_angles = FALSE)
data(strata_cnp)
strata <- strata_cnp
all_species <- load_cohort_settings(
id = "all",
species = NULL, #spp_codes,
strata = c('MHI', 'WHICEAS', 'HI_EEZ', 'OtherCNP'),
probable_species = FALSE,
sighting_method = 0,
cue_range = 0:7,
school_size_range = c(0, 10000),
school_size_calibrate = TRUE,
calibration_floor = 0,
use_low_if_na = TRUE,
io_sightings = 0,
geometric_mean_group = TRUE,
truncation_km = 7.5,
beaufort_range = 0:6,
abeam_sightings = FALSE,
strata_overlap_handling = c("smallest"),
distance_types = c('S','F','N'),
distance_modes = c('P','C'),
distance_on_off = TRUE
)
bottlenose <- load_cohort_settings(
id = "bottlenose",
species = '018',
strata = c('MHI', 'WHICEAS', 'HI_EEZ', 'OtherCNP', 'Bottlenose_BI', 'Bottlenose_OUFI', 'Bottlenose_KaNi'),
probable_species = FALSE,
sighting_method = 0,
cue_range = 0:7,
school_size_range = c(0, 10000),
school_size_calibrate = TRUE,
calibration_floor = 0,
use_low_if_na = TRUE,
io_sightings = 0,
geometric_mean_group = TRUE,
truncation_km = 7.5,
beaufort_range = 0:6,
abeam_sightings = FALSE,
strata_overlap_handling = c("smallest"),
distance_types = c('S','F','N'),
distance_modes = c('P','C'),
distance_on_off = TRUE
)
spotted <- load_cohort_settings(
id = "spotted",
species = '002',
strata = c('MHI', 'WHICEAS', 'HI_EEZ', 'OtherCNP','Spotted_OU','Spotted_FI','Spotted_BI'),
probable_species = FALSE,
sighting_method = 0,
cue_range = 0:7,
school_size_range = c(0, 10000),
school_size_calibrate = TRUE,
calibration_floor = 0,
use_low_if_na = TRUE,
io_sightings = 0,
geometric_mean_group = TRUE,
truncation_km = 7.5,
beaufort_range = 0:6,
abeam_sightings = FALSE,
strata_overlap_handling = c("smallest"),
distance_types = c('S','F','N'),
distance_modes = c('P','C'),
distance_on_off = TRUE
)
fkw <- load_cohort_settings(
id = "pseudorca",
species = '033',
strata = c('MHI', 'WHICEAS', 'HI_EEZ', 'OtherCNP','NHWI'),
probable_species = FALSE,
sighting_method = 0,
cue_range = 0:7,
school_size_range = c(0, 10000),
school_size_calibrate = TRUE,
calibration_floor = 0,
use_low_if_na = TRUE,
io_sightings = 0,
geometric_mean_group = TRUE,
truncation_km = 7.5,
beaufort_range = 0:6,
abeam_sightings = FALSE,
strata_overlap_handling = c("smallest"),
distance_types = c('S','F','N'),
distance_modes = c('P','C'),
distance_on_off = TRUE
)
settings <- load_settings(strata = strata,
survey = survey,
cohorts = list(all_species,
bottlenose,
spotted,
fkw))
das_file = '../test_code/CNP/CenPac1986-2020_Final_alb.das'
cnp_150km_1986_2020 <- process_surveys(das_file = das_file,
settings = settings)
cruz object.Example of coded edits to cruz object.
cnp_1986_2020_editscnp_1986_2020_edits
An object of class list of length 4.
This is an example of the kind of object that can be passed to the edits input in process_surveys().
Coastline
coastlinecoastline
An object of class sf (inherits from data.frame) with 4133 rows and 4 columns.
World coastline, downloadeded from Natural Earth.
This is an internal function typically not called by a user directly.
coordinates_in_strata(lon, lat, poli)coordinates_in_strata(lon, lat, poli)
lon |
Longitude coordinates in decimal degrees, in which West coordinates are negative. |
lat |
Latitude coordinates in decimal degrees, in which South coordinates are negative. Must be the same length as |
poli |
A dataframe of polygon coordinates. |
A logical vector, the same length as the lon,
indicating whether or not the coordinate falls within the polygon.
If the coordinate falls exactly on the polygon boundary, it will be counted as in.
cruz objectsThis function combines processed cruz objects
(the outputs of LTabundR::process_surveys()),
under the assumption that the survey settings in both objects are the exact same.
If the same cohort name occurs in multiple cruz objects, the contents of the instances of the cohort
are checked for redundancy (using Cruise number - date combinations),
and only non-redundant content is combined.
If different cohorts occur in the supplied cruz objects,
the cohorts are added without modification.
cruz_combine(cruzes)cruz_combine(cruzes)
cruzes |
A |
A single cruz object.
Launch a data explorer app for WinCruz surveys
cruz_explorer(cruz, cohort = 1)cruz_explorer(cruz, cohort = 1)
cruz |
Your |
cohort |
The cohort whose data you would like to map, provided as a number indicating which slot in |
A Shiny app for interactive data exploration.
This app allows you to filter the cruz object according to various fields,
then explore summary tables of effort, sightings, and detection distances.
There are also tabs for reviewing the data in tabular form and exploring an interactive leaflet map
of survey tracks, geostrata, and sightings.
cruz object structureThis function prints an overview of the list structure and sample sizes
within your cruz object, which is produced from LTabundR::process_surveys().
cruz_structure(cruz)cruz_structure(cruz)
cruz |
Your |
Nothing; messages are printed to the Console.
DAS file......without modifying the original data. Edits are provided as a list, which the
user can store as a RData object or simply prepare with an R script. This
function loops through each edit and applies them to the respective DAS file.
This allows survey data to be modified reproducibly before being processed
with LTabundR::process_surveys(), without touching the original DAS data files or
requiring analysts to duplicate files and make one-off modifications manually.
das_editor(edits)das_editor(edits)
edits |
A list of sublists, each being a staged edit. Each sublist requires the following named slots:
This |
A list with two named slots:
das: A data.frame containing the modified DAS data (with one column: $das).
log: The edits input, with each sublist augmented with a results slot that shows the results of the edit.
DAS files and save edited versionsThis function is basically a wrapper for the function das_editor(), but this function saves the edited DAS data to new files.
It takes a set of DAS files and a set of editing instructions (provided as a list – see das_editor() documentation),
applies the edits to each DAS file, and saves new versions of the DAS file. It does NOT replace the original DAS file.
das_editor_tofile(das_file, edits, suffix = "_edited", verbose = TRUE)das_editor_tofile(das_file, edits, suffix = "_edited", verbose = TRUE)
das_file |
A vector of |
edits |
A list of sublists, each being instructions for a staged edit. See |
suffix |
The suffix to append to |
verbose |
Boolean. Printed updates to the Console? |
At the end of the process, the function returns a vector of DAS filenames that should be passed to processing functions such as process_surveys() or das_load().
DAS objectThis function removes invalid rows of data (due to missing Cruise numbers, timestamps, location coordinates, etc.),
calculates the distance, in kilometers, between each row of data,
adds a ship column with the ship name associated with the cruise number,
and initiates the cruz object structure, with a new cohorts slot.
This is an internal function typically not called by a user directly.
It is the third subroutine called within process_surveys(); after process_strata() and before segmentize().
das_format(cruz, verbose = FALSE)das_format(cruz, verbose = FALSE)
cruz |
The list produced by |
verbose |
Boolean, with default |
A list with nascent cruz object structure, with these slots:
settings holds your settings object;
strata holds a dataframe summarizing the name and area (square km) of each geo-stratum, if any are provided;
cohorts holds a list with slots for each cohort of species as specified in settings.
Each cohort slot has a copy of the DAS data with a new stratum column,
with a stratum assignment tailored to its cohort-specific settings (specifically, the setting stratum_overlap_handling).
This list structure will be expanded upon in subsequent steps of process_surveys().
Shiny app to explore a DAS file and build up a list of edits. Those edits
will be saved as a list of instructions, which can subsequently be provided as an argument to
LTabundR::process_surveys(), which will apply your list of edits before processing the data.
This framework allows you to record details of required edits reproducibly without ever
modifying the original dataset or producing modified versions of the original.Use a Shiny app to explore a DAS file and build up a list of edits. Those edits
will be saved as a list of instructions, which can subsequently be provided as an argument to
LTabundR::process_surveys(), which will apply your list of edits before processing the data.
This framework allows you to record details of required edits reproducibly without ever
modifying the original dataset or producing modified versions of the original.
das_inspector(das_file)das_inspector(das_file)
das_file |
Path to your |
A Shiny app is launched, where the user explores and builds up a list of staged edits.
Once the user closes that app, this function returns that list of edits. We recommend saving that return
in an object for easy call back later. To understand the structure of the list of edits, see LTabundR::das_editor().
This function is not typically called by the user directly; it is called during process_surveys().
The user can instruct LTabundR to interpolate DAS data in load_survey_settings().
das_interpolate(das, new_interval = 120, max_ignore = 3600, verbose = FALSE)das_interpolate(das, new_interval = 120, max_ignore = 3600, verbose = FALSE)
das |
A |
new_interval |
The interpolation interval, in seconds. |
max_ignore |
The maximum interval (seconds) between two rows of survey data that will be interpolated; if the time gap exceeds this value, interpolation will not occur for these two rows. The default is 3600 seconds (1 hour). |
verbose |
Print updates to the Console? |
This function allows you to interpolate the DAS position data
at the onset of processing if your position updates are separated
by large time intervals, which would make spatial effort and stratum assignments less exact.
LTabundR will interpolate the data using simple-linear methods (i.e., no great-circle calculations), such that
position updates occur every new_interval seconds or less. If adjacent DAS rows are from different dates or cruises,
or if the interval between rows exceeds the input max_ignore,
the interpolation routine will skip to the next pair of related rows. Interpolation will only occur for On-Effort rows.
An interpolated data.frame of the DAS data. No formatting has been changed.
DAS fileThis is an internal function typically not called by a user directly.
It is the first subroutine called within process_surveys().
This function is essentially a wrapper for swfscDAS::das_read(), which reads in a raw
DAS file (or a URL to an DAS file in an online repository), and swfscDAS::das_process(), which formats each row into columns,
with survey status, sighting conditions, and observer positions added to each row as new columns.
das_load(das_file, perform_checks = FALSE, print_glimpse = FALSE)das_load(das_file, perform_checks = FALSE, print_glimpse = FALSE)
das_file |
Filepath to WinCruz |
perform_checks |
Boolean, with default of |
print_glimpse |
Boolean, with default of |
A data.frame of the DAS file, with fields parsed into columns and with new columns for survey status,
sighting conditions, and observer positions.
In contrast to swfscDAS::das_read(), this function reads the DAS text in, saving
each line of data to a single row of a one-column data.frame (no column parsing).
This is useful if you wish to edit and save an altered version of the data using
LTabundR::das_inspector() and LTabundR::das_editor(). This function relies upon
the readtext package.
das_readtext(das_file)das_readtext(das_file)
das_file |
Filepath to |
A one-column data.frame (column name is das).
DAS fileThis function is typically called within LTabundR::das_inspector() as a way of
staging an edit that adjusts the timestamps of certain rows. Not typically called directly by a user.
das_time(das, tz_adjust = "from utc")das_time(das, tz_adjust = "from utc")
das |
A row of |
tz_adjust |
One of two options: (1) a single numeric value indicating
the hours to add to or subtract from the date-time in each |
A two-slot list: [[1]] dt returns the revised date-time characters.
[[2]] das returns the revised row in full (if a full row was originally provided).
This is an internal function, typically not called by the user. It returns a single detection function curve based on one or more detection function models. If multiple models are provided, their curves will be averaged together to provide a single curve, weighting the average based upon the model AIC.
df_curve(models, covariates = NULL, truncation_distance)df_curve(models, covariates = NULL, truncation_distance)
models |
A list of best-fitting detection function model(s) (produced by |
covariates |
If |
truncation_distance |
Truncation distance used, in km. |
This function is adapted from code in mrds::plot.ds() and mrds::detfct().
A data.frame of length 101, with two columns:
km is distance from the trackline, and p is the average detection probability at that distance,
based on the data's covariates.
WinCruz dataThis function is not typically called by the user (though it can be);
instead it is called as a subroutine from within the function lta().
This function is a wrapper for the detection function fitting routine in the package
mrds (function mrds::ddf()). As a wrapper, this function conducts
automated stepwise model-fitting, trying all candidate function keys and covariates,
then selecting the best model(s) based upon AICc.
df_fit( sightings, truncation_distance = Inf, covariates = NULL, detection_function_base = "hn", base_model = "~1", delta_aic = 2, toplot = TRUE, verbose = TRUE )df_fit( sightings, truncation_distance = Inf, covariates = NULL, detection_function_base = "hn", base_model = "~1", delta_aic = 2, toplot = TRUE, verbose = TRUE )
sightings |
Sightings dataframe, drawn from a |
truncation_distance |
The truncation distance to apply to sightings before model fitting. |
covariates |
Covariates you wish to include as candidates in detection function models,
provided as a character vector. The covariates must match columns existing within |
detection_function_base |
The base key for the deteion function, provided as a character vector.
Accepted values are |
base_model |
The initial model formula, upon which to build using candidate covariates,
provided as a character vector. The default is |
delta_aic |
The AIC difference between the model yielding the lowest AICc and other candidate models, used to define the best-fitting models. Typically, AICc differences of less than 2 indicate effectively equal model performance. |
toplot |
Boolean, with default |
verbose |
Boolean, with default |
Model fitting is done in a forward stepwise procedure, starting fresh with each base key
provided. In the first round, the base model (no covariates) is fit first.
In the second round, each covariate is added one at a time; the covariate, if any, that produces the lowest AICc
below the AIC from the previous round is added to the formula.
This process is repeated in subsequent rounds until the AICc no longer improves.
All models within delta_aic of the model with the lowest AICc qualify as best-fitting models.
A named list:
best_models: A data.frame summary of the best-fitting models,
based upon the table produced by Distance::summarize_ds_models().
See that function's documentation for details.
all_models: Similar to the preceding slot, a tabular summary of all models tested.
best_objects: A list containing the ds objects (produced by package Distance)
for each of the best-fitting models.
sample_size: A data.frame with the detections for each species within the species pool
used to fit the detection function.
Ntot is total detections for each species; Ndet is total detections within the truncation distance
and therefore used in the detection function fitting routine; TD is the truncation distance.
tables: A list of the data tables passed to Distance::ds() during model fitting.
sightings: The sightings data.frame provided, now with an esw columns provided estimated Effective Strip half-Width for each sighting.
This function adapts mrds::plot.ds() to plot the detection functions fit and
provided by the output of lta() and lta_multistock(). Arguments allow for stylizing
the plot as well as displaying multiple best-fitting models on the same histogram.
df_plot( lta_result, model_colors = "black", model_pch = 1, hist_bars = 15, hist_col = "grey90", hist_border = "grey60", pt_show = 1, pt_cex = 0.8, pt_alpha = 0.3, line_col = "darkblue", line_lty = 1, line_lwd = 2.5, line_alpha = 0.7, bootstrap_show = TRUE, bootstrap_col = "steelblue4", bootstrap_alpha = 0.2, bootstrap_lwd = 0.5, main_show = TRUE, main = NULL, main_cex = 1.25, legend_show = FALSE, ymax = NULL, legend_x = 3.2, legend_y = 1.2, legend_cex = 0.8, xlab = "Distance (km) from trackline" )df_plot( lta_result, model_colors = "black", model_pch = 1, hist_bars = 15, hist_col = "grey90", hist_border = "grey60", pt_show = 1, pt_cex = 0.8, pt_alpha = 0.3, line_col = "darkblue", line_lty = 1, line_lwd = 2.5, line_alpha = 0.7, bootstrap_show = TRUE, bootstrap_col = "steelblue4", bootstrap_alpha = 0.2, bootstrap_lwd = 0.5, main_show = TRUE, main = NULL, main_cex = 1.25, legend_show = FALSE, ymax = NULL, legend_x = 3.2, legend_y = 1.2, legend_cex = 0.8, xlab = "Distance (km) from trackline" )
lta_result |
The result of |
model_colors |
A vector of colors; if more than one is provided,
the vector must be the same length as the number of best-fitting models
( |
model_pch |
A vector of point |
hist_bars |
Number of histogram bars to show. |
hist_col |
Color of histogram bars. |
hist_border |
Border color of histogram bars. |
pt_show |
If |
pt_cex |
The size of detection points, if shown. |
pt_alpha |
The transparency (0 = transparent; 1=solid) of points, if shown. |
line_col |
Color of detection function line. |
line_lty |
The line type for the detection function, following conventional base plot |
line_lwd |
Detection function line thickness. |
line_alpha |
Detection function line transparency, as a fraction between 0 and 1. |
bootstrap_show |
Show detection function curves for all bootstrap iterations? Default is |
bootstrap_col |
Color of bootstrap detection function curves, if shown. |
bootstrap_alpha |
Transparency of bootstrap detection function curves, if shown. |
bootstrap_lwd |
Thickness of bootstrap detection function curves, if shown. |
main_show |
Show a main title? |
main |
The text for the main title; if |
main_cex |
Size of main title. |
legend_show |
Show a legend, indicating the line/point/color for each best-fitting model?
|
ymax |
Maximum of y-axis (can be helpful when making space for the legend). Can be |
legend_x |
Left-right position of legend, if shown. |
legend_y |
Up-down position of legend, if shown. |
legend_cex |
Size of legend text, if shown. |
xlab |
Text for x axis label, if shown. |
A plot is printed.
EEZ (all US EEZ boundaries)
eezeez
An object of class sf (inherits from data.frame) with 260 rows and 17 columns.
World dataset of geopolitical Exclusive Economic Zones (EEZ), downloaded from Natural Earth.
EEZ - California Current System (formatted for sf / tmap mapping)
eez_ccseez_ccs
An object of class sfc_MULTILINESTRING (inherits from sfc) of length 17.
The EEZ relevant to the California Current System only, formatted for sf-compatibility.
EEZ - Hawaii (formatted for sf / tmap mapping)
eez_hawaiieez_hawaii
An object of class sfc_MULTILINESTRING (inherits from sfc) of length 25.
The EEZ relevant to the Hawai'ian area only, formatted for sf-compatibility.
Test for the probability that year-to-year changes observed in a species' encounter rate are due to random sampling variation instead of an actual change in the encounter rate. This function uses bootstrap sampling of survey segments to see if random variation in sampling could possibly produce an apparent but immaterial change in encounter rate across years.
er_simulator( spp, cohort = 1, cruz, iterations = 1000, seed = NULL, verbose = FALSE )er_simulator( spp, cohort = 1, cruz, iterations = 1000, seed = NULL, verbose = FALSE )
spp |
Species code |
cohort |
The cohort whose data you would like to analyze, provided as a number indicating which slot in |
cruz |
Your |
iterations |
Number of iterations |
seed |
Set a seed (any integer) to ensure that the result is reproducible.
If left |
verbose |
Boolean; print updates to the console? |
See the Appendix to Bradford et al. (2020) for analytical details, but briefly:
in each bootstrap iteration, survey segments are resampled in a way that preserves
the proportion of effort occurring within each geostratum in the data.
The resampled data are used to calculate the overall encounter rate across all years,
since the null hypothesis is that the encounter rate does not change across years.
This overall encounter rate is used to predict the number of sightings in each year,
based on the distance covered by the resampled segments in each year.
This process is repeated (iterations times) to produce a distribution of predicted sighting counts
in each year. This distribution is compared to the actual number of sightings observed in each year.
The number of simulated sightings counts that exceed the observed count reflects
the probability that the observed count is due to random sample variation alone.
A dataframe with a row for each year. Columns provide the number of observations of
the species of interest during systematic effort, and the p-value of the test.
The p-value represents the fraction of simulated encounter rates that exceed the observed encounter rate.
Example cruz object (WHICEAS 2020)
example_cruzexample_cruz
An object of class list of length 3.
This example cruz object was prepared with the following code:
data(example_settings)
example_cruz <- process_surveys('data-raw/data/HICEASwinter2020.das',
settings = example_settings)
LTabundR vignette (WHICEAS 2020)Example settings used in LTabundR vignette (WHICEAS 2020)
example_settingsexample_settings
An object of class list of length 3.
This example settings object was prepared with the following code:
data(strata_cnp)
data(study_cnp)
data(group_size_coefficients)
survey <- load_survey_settings()
cohort1 <- load_cohort_settings(strata = c('OtherCNP', 'HI_EEZ', 'WHICEAS'))
example_settings <- load_settings(strata = strata_cnp,
study_area = study_cnp,
survey = survey,
cohorts=list(cohort1))
This is an internal function, usually not called directly by analysts,
but it certainly can be. Rather than calling a cruz object, as filter_cruz does,
this function just calls for the three relevant constituent tables:
segments, sightings, and the full das dataset.
filter_cohort( segments, sightings, das, analysis_only = FALSE, spp = NULL, years = NULL, not_years = NULL, cruises = NULL, not_cruises = NULL, regions = NULL, not_regions = NULL, bft_range = NULL, eff_types = NULL, on_off = NULL, lat_range = NULL, lon_range = NULL, verbose = TRUE )filter_cohort( segments, sightings, das, analysis_only = FALSE, spp = NULL, years = NULL, not_years = NULL, cruises = NULL, not_cruises = NULL, regions = NULL, not_regions = NULL, bft_range = NULL, eff_types = NULL, on_off = NULL, lat_range = NULL, lon_range = NULL, verbose = TRUE )
segments |
Effort segments dataframe, drawn from a |
sightings |
Sightings dataframe, drawn from a |
das |
Dataframe of DAS data, drawn from a |
analysis_only |
If |
spp |
A character vector of species codes, used to filter |
years |
A numeric vector of years, used to filter both |
not_years |
A numeric vector of years, used to filter both |
cruises |
A numeric vector of cruise numbers, used to filter a la |
not_cruises |
A numeric vector of cruise numbers, used to filter a la |
regions |
A character vector of geostratum names, used to filter both |
not_regions |
A character vector of geostratum names, similar to above.
Any segment or sighting occurring within any of these |
bft_range |
The Beaufort Sea State values to filter to, provided as a numeric vector. |
eff_types |
The effort types ('S' = Systematic, 'F' = Fine-scale, 'N' = Non-systematic) to filter to, provided as a character vector. |
on_off |
The |
lat_range |
If not |
lon_range |
If not |
verbose |
Boolean, with default |
This function works by using the filter arguments to determine which rows of DAS data
meet all criteria; since that DAS dataframe is drawn from a processed cruz object,
it has a seg_id column indicating the segment IDs pertaining to eligible rows of data.
Those segment IDs are then used to filter segments and sightings.
Note that when arguments are NULL, they are ignored and no filtering by the associated variable occurs.
A list with two objects: segments and sightings. These are filtered
versions of the same objects contained within the cruz object.
See process_surveys() documentation for details.
cruz objects by species/region/year, etc.Subsets a cruz object according to a variety of filters. The same filters
apply to all cohorts within the cruz object.
filter_cruz( cruz, analysis_only = FALSE, spp = NULL, years = NULL, not_years = NULL, cruises = NULL, not_cruises = NULL, regions = NULL, not_regions = NULL, bft_range = NULL, eff_types = NULL, on_off = NULL, lat_range = NULL, lon_range = NULL, verbose = TRUE )filter_cruz( cruz, analysis_only = FALSE, spp = NULL, years = NULL, not_years = NULL, cruises = NULL, not_cruises = NULL, regions = NULL, not_regions = NULL, bft_range = NULL, eff_types = NULL, on_off = NULL, lat_range = NULL, lon_range = NULL, verbose = TRUE )
cruz |
Your |
analysis_only |
If |
spp |
A character vector of species codes, used to filter |
years |
A numeric vector of years, used to filter both |
not_years |
A numeric vector of years, used to filter both |
cruises |
A numeric vector of cruise numbers, used to filter a la |
not_cruises |
A numeric vector of cruise numbers, used to filter a la |
regions |
A character vector of geostratum names, used to filter both |
not_regions |
A character vector of geostratum names, similar to above.
Any segment or sighting occurring within any of these |
bft_range |
The Beaufort Sea State values to filter to, provided as a numeric vector. |
eff_types |
The effort types ('S' = Systematic, 'F' = Fine-scale, 'N' = Non-systematic) to filter to, provided as a character vector. |
on_off |
The |
lat_range |
If not |
lon_range |
If not |
verbose |
Boolean, with default |
This function works by using the filter arguments to determine which rows of DAS data
meet all criteria; since that DAS dataframe comes from within the processed cruz object,
it has a seg_id column indicating the segment IDs pertaining to eligible rows of data.
Those segment IDs are then used to filter segments, sightings, and subgroups.
Note that the analysis_only filter is ignored for subgroups sightings/subgroups/events,
since those are often case-by-case-specific.
Note that when arguments are NULL, they are ignored and no filtering by the associated variable occurs.
Also note that subgroups are not filtered at this time.
Note that there is a similar function, filter_cohort(), that performs a similar task
for only a single cohort, without requiring an in-tact cruz object.
Instead it asks for the requisite datasets separately.
A modified cruz object. See process_surveys() documentation for details.
This function is typically not called by the user, but it certainly can be.
It is called as a subroutine within LTabundR::lta().
g0_combine(g0s, g0cvs)g0_combine(g0s, g0cvs)
g0s |
A numeric vector of weighted estimates of trackline detection probability, g(0). Any length is allowed. |
g0cvs |
A numeric vector, the same length as |
A list with two slots: $g0 holds the combined g(0) estimate, and $CV holds the
combined CV.
This function is an implementation of Barlow (2015), "Inferring trackline detection
probabilities, g(0), for cetaceans from apparent densities in different survey
conditions" (Marine Mammal Science), for processed Wincruz survey data.
This function predicts the relative g(0) (compared to Beaufort sea state 0)
for all Beaufort sea states 0 - 6.
g0_model( spp, truncation_distance = 5.5, cruz, cohort = 1, eff_types = "S", jackknife_fraction = 0.1, seed = NULL, constrain_shape = FALSE, k = 4, toplot = TRUE, verbose = TRUE )g0_model( spp, truncation_distance = 5.5, cruz, cohort = 1, eff_types = "S", jackknife_fraction = 0.1, seed = NULL, constrain_shape = FALSE, k = 4, toplot = TRUE, verbose = TRUE )
spp |
A character vector of species code(s) whose relative trackline detection probability (g(0)) you want to estimate. |
truncation_distance |
The truncation distance, in km, to apply to sightings. |
cruz |
Your |
cohort |
The cohort whose data pertains to the species of interest, provided as a number indicating which slot in |
eff_types |
Effort types to filter segments and sightings to before conducting analysis. The
default is systematic effort only ( |
jackknife_fraction |
The proportion of data to leave out within each jackknife permutation, which is used to calculate the CV of the Rg(0) estimates. The default is 0.1 (i.e., 10% of the data, yielding 10 jackknife loops), after Barlow (2015). |
seed |
Set a seed (any integer) to ensure that the result is reproducible.
If left |
constrain_shape |
Some Rg(0) curves will not decline monotonically due to sample size
issues at low Bft (0-2) or high Bft (5-6) states. To coerce monotonic decline, set this to
|
k |
Smoothing term for the Bft spline in the GAM. Default (and the value used in Barlow 2015) is 4. |
toplot |
Boolean, with default |
verbose |
Boolean, with default |
After Barlow (2015), this function implements the following procedure:
Filter sightings to the specified species code(s), and associate those sightings with their respective 10-km segment ID.
Determine the presence or absence of the species of interest for each segment.
Estimate the Effective Search Area (ESA) for each Beaufort sea state represented in the data.
This is done by fitting a detection function to the sightings data (half-normal key; using function Distance::ds()),
using Beaufort as the only covariate. With this detection function model,
the probability of detection (p(det)) for sightings in each Beaufort state is determined (Distance::predict.ds()$fitted).
The effective strip width (ESW) for each Beaufort state is determined by multiplying p(det) by the supplied truncation_distance.
The ESW is used to calculate the ESA in each segment (ESA = 2 x L x ESW).
Note that Beaufort states 0 and 1 are combined (after Barlow 2015),
since they are typically under-represented in open-ocean fieldwork.
A binomial Generalized Additive Model (GAM) ("logit" link function)
is fit to the segments (using mgcv::gam), based upon Equation 3 from Barlow (2015),
which includes Beaufort sea state, Latitude x Longitude, and Year as predictors
(using the mgcv::s() spline function) and the log of ESA as an offset (stats::offset())
to predict the probability of apparent presence in each segment.
To prevent over-fitting, the spline functions for Beaufort and Year are constrained with k=4,
and model complexity penalty is inflated (gamma = 1.4 in mgcv::gam()).
The GAM model is used to predict the probability of apparent species presence (mgcv::predict.gam()) in
fake segements of equal length, year, and Latitude/Longitude but with different Beaufort sea states, 0 - 6.
By comparing the probability for Beaufort 0 (in which rates of apparent presence would be highest) to that for other Beaufort states, the Relative g(0) (Rg(0))is estimated (Equation 4 in Barlow 2015).
The Coefficient of Variation (CV) for Rg(0) is then estimated using a jackknife procedure,
in which a fraction of the data are sequentially removed (input jackknife_fraction, with default 10%),
Rg(0) is re-estimated by implementing steps 4 - 6 above, and this process is repeated for all sequential fractions of the data.
The CV is derived from these pseudo-estimates (let's call them jacks) with the equation n*CV(jacks) - (n-1)*CV(jacks)),
in which n is the number of jackknife estimates (1 / jackknife_fraction) and
CV is the standard deviation of jacks divided by their mean.
A list:
Rg0 a data.frame of estimates of Relative g(0) at each Beaufort.
gam the mgcv::gam() model output.
jackknife A list of jackknife results: $g0 contains the g(0) estimates from
each jacknife iteration; $ESW contains the effective half-strip-width estimates; $gams contains the gam model objects.
summary: A dataframe summarizing results; this is the primary output you are likely to use..
cruz10: A modified nascent cruz object that has been re-segmentized to have segments of 10km-length.
This usually takes a while to create, so this output gives you the option of passing this object
on to your next call of g0_bft_model() (see cruz10 argument above) to save time.
This is an internal function used in LTabundR::lta() for finding the values
(through optim()) for the parameters needed to conduct parametric bootstrapping
of g0 values for each non-parametric bootstrap of the LTA routine.
g0_optimize(g0, g0_cv, try_count = 20, seed = NULL, verbose = TRUE)g0_optimize(g0, g0_cv, try_count = 20, seed = NULL, verbose = TRUE)
g0 |
Initial estimate of g(0). |
g0_cv |
Initial estimate of g(0) coeffiient of variation. |
try_count |
Number of times to attempt optimization before giving up. |
seed |
Set a seed (any integer) to ensure that the result is reproducible.
If left |
verbose |
Print updates to the Console? |
A list with three named slots: [[1]] g0_mean, the exact mean, according to the optimization results;
[[2]] g0_cv, the CV according to optimization; and [[3]] bestFit, a numeric vector of length 2 containing
parameters to pass to the parameteric g(0) bootstrap routine in LTabundR::lta(). If the initial g(0) estimate
is 1.0, or the initial g(0) CV estimate is 0.0, then these parameters will be returned as NA.
This function produces a multi-pane plot of changes in relative trackline detection probabilities, Rg(0), across Beaufort sea states for a set of species.
g0_plot(Rg0, panes = 3, legend_key = 0.4, legend_font = 7)g0_plot(Rg0, panes = 3, legend_key = 0.4, legend_font = 7)
Rg0 |
A |
panes |
The number of plot panes to produce. Species will be assigned to each pane according to their mean Rg(0) estimate, such that species with similar detectability will be grouped together. |
legend_key |
Height of each legend key, in cm, to allow for fine-tuning the formatting of the plot. |
legend_font |
Legend font size, to allow for fine-tuning the formatting of the plot. |
A ggplot object with faceted panes arranged vertically.
Relative trackline detection probabilities – Rg(0)
g0_resultsg0_results
An object of class data.frame with 175 rows and 13 columns.
Rg(0) estimates for 25 species groups, based on survey data from 1986-2020 (see
noaa_10km_1986_2020 dataset).
This function estimates relative trackline probabilities, Rg(0),
for a set of species and returns a single table (a data.frame) with
the results for each species. This function is a wrapper for LTabundR::g0_model().
See its documentation for details on the procedure.
g0_table( cruz, species, eff_types = "S", jackknife_fraction = NULL, seed = NULL, toplot = TRUE, verbose = TRUE )g0_table( cruz, species, eff_types = "S", jackknife_fraction = NULL, seed = NULL, toplot = TRUE, verbose = TRUE )
cruz |
Your |
species |
A list of sublists, in which each sublist details the settings for a single species (or related group of species). Each sublist needs to have these slots:
|
eff_types |
Effort types to filter segments and sightings to before conducting analysis. The
default is systematic effort only ( |
jackknife_fraction |
The proportion of data to leave out within each jackknife permutation, which is used for estimating the CV of Rg(0) estimates. The default is 0.1 (i.e., 10% of the data, yielding 10 jackknife loops), after Barlow (2015). |
seed |
Set a seed (any integer) to ensure that the result is reproducible.
If left |
toplot |
Boolean, with default |
verbose |
Boolean, with default |
A data.frame, in which every row details the Rg0 estimate for a single species group
in a single Beaufort sea state, with the following columns:
title: The title given to the species group.
spp: Species codes, concatenated by a hyphen if there are multiple in the species group.
bft: Beaufort sea state.
Rg0: Estimate of the relative g(0) for this sea state.
ESW: Estimate of the effective strip half-width (ESW) for this sea state.
Rg0_SE: The standard error of the Rg(0) estimate, non-zero only if jackknife_fraction was used.
Rg0_CV: The CV of the Rg(0) estimate, non-zero only if jackknife_fraction was used.
ESW_SE: The standard error of the ESW estimate, non-zero only if jackknife_fraction was used.
sits: The number of sightings within this sea state used to model Rg(0).
sits_p: The proportion of sightings within this sea state.
segs: The number of segments within this sea state used to model Rg(0).
segs_p: The proportion of segments within this sea state.
See the built-in dataset, data(g0_results), for an example of the output.
Use this function to summarize the Beaufort-specific model of relative trackline probabilities
(from LTabundR::g0_bft_model()) as a single relative g(0) estimate, weighted
by the prevalence of each Beaufort sea state within the survey data.
This function automatically estimates the CV of this weighted value using an iterative
loop with an MCMC core, adapted from Jeff Moore's code.
g0_weighted( Rg0, Rg0_cv, cruz, cohort = 1, iterations = 10000, seed = NULL, beta_range = c(-1.5, 0), beta_step = 0.001, beta_sd_range = c(0, 0.3), beta_sd_step = 1e-04, ymax = 0.2, calculate_pars = TRUE, toplot = TRUE, verbose = TRUE )g0_weighted( Rg0, Rg0_cv, cruz, cohort = 1, iterations = 10000, seed = NULL, beta_range = c(-1.5, 0), beta_step = 0.001, beta_sd_range = c(0, 0.3), beta_sd_step = 1e-04, ymax = 0.2, calculate_pars = TRUE, toplot = TRUE, verbose = TRUE )
Rg0 |
A numeric vector, length 7, of Relative g(0) estimates
for Beaufort sea states 0 - 6. See documentation of |
Rg0_cv |
A numeric vector, length 7, of the CV of Relative g(0) estimates. See same documentation as above for details. |
cruz |
Your |
cohort |
The cohort name within your |
iterations |
The number of draws used to simulate the underlying distribution. |
seed |
Set a seed (any integer) to ensure that the result is reproducible.
If left |
beta_range |
The range in distribution parameters for simulating the g(0) mean. |
beta_step |
The interval between candidate values within the above range. A smaller step means higher resolution and accuracy, but takes longer to process. |
beta_sd_range |
The range in distribution parameters for simulating the g(0) SD. |
beta_sd_step |
The interval between candidate values for the above SD range. |
ymax |
The maximum value on the y axis of the diagnostic Rg0 SD plot. |
calculate_pars |
Boolean with default |
toplot |
Boolean, with default |
verbose |
Boolean, with default |
This code is an adaptation and expansion of Jeff Moore's code (February 2020). This function automatically estimates the CV of this weighted value using an iterative loop with an MCMC core. The MCMC routine is described in Bradford et al. (2021). The iterative loop tries various candidate values for the distribution parameters and calculates the cumulative error of the resulting distribution at each Beaufort state. It then determines the candidate value with the lowest error, weighting each error according to the proportion of effort occurring in the respective Beaufort state.
The output is provided in the form of a list with two slots: g0 and bft.
The g0 slot holds a data.frame in which $wt.mean is the
weighted mean g(0) value across all Beaufort states for the survey data provided,
and $wt.cv is the CV of that estimate.
Other values are reported to facilitate QA/QC, but $wt.mean and $wt.cv is what
you would pass to an abundance estimation routine, such as LTabundR::lta()).
The bft slot holds a dataframe with the proportion of effort in each Beaufort sea state.
cruz effort to a base ggplot2 map.Add cruz effort to a base ggplot2 map.
gg_effort( p, cruz, cohort = 1, color_by_bft = FALSE, color = "black", lwd = 0.1, alpha = 0.5 )gg_effort( p, cruz, cohort = 1, color_by_bft = FALSE, color = "black", lwd = 0.1, alpha = 0.5 )
p |
Base |
cruz |
Your |
cohort |
The cohort whose data you would like to map, provided as a number indicating which slot in |
color_by_bft |
Color code by Beaufort sea state? |
color |
Color string. |
lwd |
Effort thickness. |
alpha |
Effort transparency. |
An updated ggplot2 object.
cruz geostrata to a base ggplot2 map.Add cruz geostrata to a base ggplot2 map.
gg_geostratum( p, cruz, strata, color = "orchid4", lwd = 0.5, lty = 1, crs = 4326 )gg_geostratum( p, cruz, strata, color = "orchid4", lwd = 0.5, lty = 1, crs = 4326 )
p |
Base |
cruz |
Your |
strata |
desc |
color |
Color string. |
lwd |
Boundary line width. |
lty |
Boundary line type. |
crs |
Optional CRS. |
An updated ggplot2 object.
cruz sightings to a base ggplot2 map.Add cruz sightings to a base ggplot2 map.
gg_sightings( p, cruz, cohort = 1, spp = NULL, spp_translate = NULL, color_by_spp = FALSE, color = "black", pch = 16, cex = 0.5, alpha = 0.5 )gg_sightings( p, cruz, cohort = 1, spp = NULL, spp_translate = NULL, color_by_spp = FALSE, color = "black", pch = 16, cex = 0.5, alpha = 0.5 )
p |
Base |
cruz |
Your |
cohort |
The cohort whose data you would like to map, provided as a number indicating which slot in |
spp |
Character vector of species codes. |
spp_translate |
Dataframe of scecies code information for translating between codes and common names. See |
color_by_spp |
Color code by species code? |
color |
Color string. |
pch |
Sighting point type. |
cex |
Sighting point size. |
alpha |
Sighting transparency. |
An updated ggplot2 object.
ggplot object to handle the International Date Line (IDL)Modify a ggplot object to handle the International Date Line (IDL)
ggplot_idl( p_base, lon_range = c(100, -100), lat_range = NULL, idl_padding = 0.02, axes = TRUE, bypass = FALSE )ggplot_idl( p_base, lon_range = c(100, -100), lat_range = NULL, idl_padding = 0.02, axes = TRUE, bypass = FALSE )
p_base |
A |
lon_range |
Desired longitude range, as a two-element vector. The first element should be a positive number between 0 and 180 (indicating decimal degrees East), the second should be a negative number between -180 and 0 (indicating decimal degrees West). |
lat_range |
Desired latitude range, as a two-element vector of decimal degrees (positive = N, negative = S). |
idl_padding |
The space between the Eastern hemisphere plot and the Western hemisphere plot. |
axes |
If |
bypass |
An option to return an unmodified |
A ggplot2 object that is actually two plots side by side, with a small space in between indicating the IDL.
This is an internal function typically not called by a user directly.
This function is used as a subroutine in process_sightings().
It produces school size estimates for each species within a sighting,
based upon all estimates of school size and species composition provided by observers.
group_size( grp, gs_coefficients = NULL, calibrate_floor = 0, geometric_mean = FALSE, use_low_if_na = TRUE, debug_mode = FALSE, verbose = TRUE )group_size( grp, gs_coefficients = NULL, calibrate_floor = 0, geometric_mean = FALSE, use_low_if_na = TRUE, debug_mode = FALSE, verbose = TRUE )
grp |
A dataframe, in which each row is a school size estimate from a single observer,
and each column is a column from the |
gs_coefficients |
If not |
calibrate_floor |
This argument accepts a number
indicating the minimum raw school size estimate
for which school size calibration will be attempted.
When this function is used withing |
geometric_mean |
This argument accepts a Boolean;
if |
use_low_if_na |
If this setting is |
debug_mode |
Boolean, with default |
verbose |
Boolean, with default |
A dataframe in which each row is a species within the sighting,
with final estimates of best / high / low and metadata regarding calibration.
When this function is used internally by LTabundR, the results are passed back to process_sightings().
This is an internal function typically not called by a user directly.
It is called by the subroutine group_size(), which is itself a subroutine
of process_sightings().
This function performs school size calibration for a single observer's estimates.
group_size_calibration( obs, bft, yr, gbest, glow, ghigh, gs_coefficients = NULL, calibrate_floor = 0 )group_size_calibration( obs, bft, yr, gbest, glow, ghigh, gs_coefficients = NULL, calibrate_floor = 0 )
obs |
Character vector with single observer ID. If this observer ID is contained
within |
bft |
Numeric of Beaufort sea state during sighting. |
yr |
Numeric of year of sighting. |
gbest |
Numeric of best school size estimate. |
glow |
Numeric of low school size estimate. |
ghigh |
Numeric of high school size estimate. |
gs_coefficients |
Dataframe of school size coefficients. If not provided, calibration will not be attempted. |
calibrate_floor |
This argument accepts a number indicating the minimum raw school size estimate for which school size calibration will be attempted. |
A one-row dataframe with the best school size estimate, the variance of the estimate,
a boolean indicating whether calibration was possible, and the slope and intercept used for calibration.
Passed back to group_size().
Group size coefficients
group_size_coefficientsgroup_size_coefficients
An object of class data.frame with 162 rows and 21 columns.
A table of group size calibration coefficient values for a variety of species for a variety of observer codes. This table was provided by Jay Barlow (NOAA NMFS Bioligist), was created prior to 2016, and has been used for published analyses through 2021.
This can be useful for plotting datasets that cross the international date line (IDL). (Designed as a behind-the-scences function that most users wont' use, but making it available just in case.)
idl_coerce(df)idl_coerce(df)
df |
Dataframe of coordinates with columns |
Corrected dataframe (all coordinates between 0 and less than -180).
Land
landland
An object of class sf (inherits from data.frame) with 10 rows and 4 columns.
World dataset of land polygons, downloaded from Natural Earth.
This function builds a list of cohort-specific settings – applying only to the analyses
for a certain group of species – which you will pass to load_settings().
load_cohort_settings( id = "default", species = NULL, strata = NULL, probable_species = FALSE, sighting_method = 0, cue_range = 0:7, school_size_range = c(0, 10000), school_size_calibrate = TRUE, calibration_floor = 0, use_low_if_na = FALSE, io_sightings = 0, geometric_mean_group = TRUE, truncation_km = 5.5, beaufort_range = 0:6, abeam_sightings = FALSE, strata_overlap_handling = "smallest", distance_types = c("S", "F", "N"), distance_modes = c("P", "C"), distance_on_off = TRUE )load_cohort_settings( id = "default", species = NULL, strata = NULL, probable_species = FALSE, sighting_method = 0, cue_range = 0:7, school_size_range = c(0, 10000), school_size_calibrate = TRUE, calibration_floor = 0, use_low_if_na = FALSE, io_sightings = 0, geometric_mean_group = TRUE, truncation_km = 5.5, beaufort_range = 0:6, abeam_sightings = FALSE, strata_overlap_handling = "smallest", distance_types = c("S", "F", "N"), distance_modes = c("P", "C"), distance_on_off = TRUE )
id |
An informal identifier for this cohort,
to help you keep track of which cohort is which.
For example, settings for a cohort of large whales species could be named |
species |
A character vector of species codes to include in this cohort.
If |
strata |
A character vector of geostratum names; these must match the names
listed in the |
probable_species |
If |
sighting_method |
A coded integer which determines which sightings
will be included based on how they were first seen.
Allowable codes are
|
cue_range |
Numeric vector of acceptable "observation cues"
for sightings used in estimates of abundance.
( |
school_size_range |
Minimum and maximum group sizes to be included in estimates of abundance. This is the overall group size, not the number of the given species that are present in a group. |
school_size_calibrate |
A logical ( |
calibration_floor |
A numeric indicating the minimum school size estimate for which
school size calibration will be attempted. This pertains only to observers who do no have an entry in the
|
use_low_if_na |
If this setting is |
io_sightings |
A coded integer which specifies how sightings by the independent observer will be handled.
Allowable codes, which are inherited from those used in |
geometric_mean_group |
This argument accepts a Boolean;
if |
truncation_km |
Specifies the maximum perpendicular distance for groups that are to be included for abundance estimation. Also determines the bins used for grouped perpendicular distances. |
beaufort_range |
A numeric vector indicating the Beaufort sea states (0 - 7) to be accepted within usable segments. |
abeam_sightings |
If |
strata_overlap_handling |
This setting informs how effort is split into
segments when surveys cross stratum boundaries, and also which stratum name
is assigned to each row of data. Note that the main impact of this setting is
on how effort is broken into segments; the assigned stratum name is for display
only and will not constrain options for including/excluding strata in analyses
farther along in the |
distance_types |
A character vector of the full-range of effort types that meet the "analysis
inclusion criteria", i.e., will be included in detection function estimation,
and therefore considered in effort segmentizing.
Accepted values are |
distance_modes |
The effort modes that meet "analysis inclusion criteria", i.e.,
will be included in detection function estimation,
and therefore considered in effort segmentizing.
Accepted values are |
distance_on_off |
The value(s) of |
A list with named slots, equivalent to your input arguments.
Save this output to an object, e.g., using the same name you provided in the id argument,
and pass it to load_settings().
WinCruz surveysYou need the output of this function to pass to process_surveys(),
the primary function for processing WinCruz data.
load_settings(strata = NULL, survey = NULL, cohorts = NULL)load_settings(strata = NULL, survey = NULL, cohorts = NULL)
strata |
A named list in which each slot is a |
survey |
Survey-wide settings, provided as the list that is generated with the
command |
cohorts |
Cohort-specific settings, provided as a list of lists.
Each slot contains the settings for a single cohort, which can be generated with the
command |
A list with three named slots, equivalent to your three input arguments.
Save this output to an object, e.g., "settings", and pass it to process_surveys().
This function builds a list of survey-wide settings (applying to all segments
and all sightings of all species, regardless of their cohort designation),
which you will pass to load_settings().
load_survey_settings( out_handling = "remove", interpolate = NULL, min_row_interval = 2, max_row_interval = 3600, max_row_km = 100, km_filler = 1, speed_filler = 10 * 1.852, segment_method = "day", segment_target_km = 150, segment_max_interval = 48, segment_remainder_handling = "segment", seed = NULL, ship_list = NULL, species_codes = NULL, group_size_coefficients = NULL, smear_angles = FALSE )load_survey_settings( out_handling = "remove", interpolate = NULL, min_row_interval = 2, max_row_interval = 3600, max_row_km = 100, km_filler = 1, speed_filler = 10 * 1.852, segment_method = "day", segment_target_km = 150, segment_max_interval = 48, segment_remainder_handling = "segment", seed = NULL, ship_list = NULL, species_codes = NULL, group_size_coefficients = NULL, smear_angles = FALSE )
out_handling |
This argument allows you to specify
how data occurring outside of geo-strata should be handled.
If this is set to |
interpolate |
This argument allows you to interpolate the |
min_row_interval |
The minimum time interval, in seconds, between rows in order for the Great Circle distance between rows to be calculated. Intervals less than this number will be assigned a distance of 0 km. |
max_row_interval |
The maximum allowable time interval, in seconds,
between rows before |
max_row_km |
The maximum allowable distance interval, in km,
between rows before the function assumes that there has been a break in survey data logging.
The default was chosen arbitrarily to find a value that replicates the
processing results from |
km_filler |
When valid speed and position information is not available
(e.g., the given distance exceeds |
speed_filler |
When speed is not available in the data, this value (in kph)
will be used as a filler in order to estimate the
distance between consecutive rows of data based on timestamp differences
(when lat/long coordinates are not available).
The default was chosen arbitrarily to find a value that replicates
the processing results from |
segment_method |
The two method options are |
segment_target_km |
If segmentizing by |
segment_max_interval |
If segmentizing by |
segment_remainder_handling |
If segmentizing by |
seed |
Set a seed (any integer) to ensure that your survey is processed reproducibly:
namely, segments will be chopped the exact same way every time.
Some of the segment remainder handling methods (namely |
ship_list |
A |
species_codes |
A |
group_size_coefficients |
A |
smear_angles |
If |
A list with named slots, equivalent to your input arguments.
Save this output to an object, e.g., "survey_settings", and pass it to load_settings().
For a single species or species pool, fit a detection function and estimate density / abundance, with an option to conduct parametric / non-parametric bootstrap sampling for variance estimation.
lta( cruz, Rg0, fit_filters, df_settings, estimates, use_g0 = TRUE, abund_eff_types = c("S"), abund_bft_range = 0:6, bootstraps = 0, seed = NULL, max_attempts = 5, results_file = NULL, toplot = TRUE, verbose = TRUE )lta( cruz, Rg0, fit_filters, df_settings, estimates, use_g0 = TRUE, abund_eff_types = c("S"), abund_bft_range = 0:6, bootstraps = 0, seed = NULL, max_attempts = 5, results_file = NULL, toplot = TRUE, verbose = TRUE )
cruz |
Your |
Rg0 |
The result of |
fit_filters |
A named list, with filters and settings pertaining to the data
used to fit a detection function model.
The slots below are recognized, but only
|
df_settings |
A named list, with parameters for fitting the detection function. The following slots are recognized, but none is required (i.e., all have defaults):
|
estimates |
A nested list (i.e., a list of sublists), in which each constituent sublist
contains the settings for a single density/abundance estimate.
Check out the
|
use_g0 |
A Boolean, with default |
abund_eff_types |
A character vector of |
abund_bft_range |
A numeric vector of Beaufort Sea Sates accepted as systematic effort
(for density / abundance estimation). The default is |
bootstraps |
The number of bootstrap iterations. If 0 or 1, no bootstrapping will be carried out. |
seed |
Set a seed (any integer) to ensure that the bootstrap results are reproducible.
If left |
max_attempts |
The maximum number of attempts for each bootstrap iteration;
the bootstrap can fail at the detection-function fitting stage if the |
results_file |
If not |
toplot |
Boolean, with default |
verbose |
Boolean, with default |
See the vignette online for detailed examples & case studies.
Survey area calculations:
The area for which abundance is to be estimated is calculated separately for each sublist within estimates
according to the inpunts regions and regions_remove. This calculation is performed by a call to the
LTabundR function strata_area(), which handles complex combinations and subtractions of geostrata,
accounting for overlapping strata and the (optional) removal of any land area
(see its documentation for details).
The polygon for each resulting study area is added to the respective estimates sublist.
Those polygons can be retrieved from the output's $inputs slot.
Weighted g(0) estimates:
If g(0) values are not supplied manually for an estimates sublist, a weighted g(0)
will be estimated as part of this function's operations through a call to the
LTabundR function g0_weighted(), which automatically optimizes a model that
estimates the g(0) and its CV based on the distribution of effort in different
Beaufort sea states within the specific year, region, and cruise in question.
This is only done if the input Rg0 is supplied.
Covariates in detection function estimation: Before detection functions are modelled,
any covariates supplied by the user and specified as a factor are first
tested for eligibility. Only factors with
at least two levels (or whatever you specified with df_settings$covariates_levels)
and 10 observations in each level (or whatever you specified with df_settings$covariates_n_per_level)
are eligible for inclusion.
Fitting a detection function: The detection function is estimated using functions
in the package mrds, primarily the main function mrds::ddf(), which uses a
Horvitz-Thompson-like estimator to predict the probability of detection for each sighting.
If multiple base key functions (e.g., half-normal or hazard-rate) are provided, and/or if
covariates are specified, model fitting is done in a forward stepwise procedure:
In the first round, the base model (no covariates, i.e., "~1") is fit first.
In the second round, each covariate is added one at a time;
at the end of the round, the covariate, if any, that produces the lowest AICc
below the AICc from the previous round is added to the formula.
This process is repeated in subsequent rounds, adding a new covariate term in each round,
until the AICc no longer improves.
If a second base key is provided, the process is repeated for that second key.
All models within delta_aic of the model with the lowest AICc qualify as best-fitting models.
The best-fitting model(s) is(are) then used to estimate the Effective Strip half-Width (ESW)
based on the covariates associated with each sighting.
If multiple best-fitting models occur, we will find the average ESW for each
sighting across all models, using a weighted mean approach in which we weight according to model AICc.
To turn off this model averaging step, set delta_aic to 0 to avoid passing
multiple models to the abundance estimation stage.
This stage of the lta() command is executed within a backend function, LTabundR::df_fit(),
which has its own documentation for your reference.
Note that if LnSsTot and/or Bft (or any other numeric covariate) are included as
candidate covariates, missing data (in the case of LnSsTot, rows where ss_valid == FALSE),
will be removed before detection function fitting, but those sightings will not be removed
from the sightings data used for abundance estimation (see below). (Note that the code to
handle these exceptions are contained within lta(), not df_fit()).
Estimating density & abundance: Estimates are produced for various combinations
of species, regions, and years, according to the arguments specified in your estimates list(s).
Before these estimates are produced, we filter the data used to fit the detection function
to strictly systematic (design-based) effort
(as specified in the abund_eff_types and abund_bft_range inputs).
Note that if NA's occur in the esw column
(due, for instance, to a covariate with missing data for a sighting),
they will be replaced with the mean esw value
for the remainder of the dataset in that region-year.
Similarly, if sightings has a column named ss_valid (all standard cruz objects do)
and any of the rows in that column are FALSE, those rows will have their best
school size estimate (which will be NA or 1, since they are invalid) replaced
by the mean best estimate for their respective species in the year for which abundance is being estimated.
Currently the data used for that mean estimate are not specific to a given region, just the year of the abundance estimate.
This stage of the lta() command is executed within a back-end function, LTabundR::abundance(),
which has its own documentation for your reference.
Bootstrap variance estimation: If the bootstraps input value is greater than 1, bootstrap variance estimation will be attempted.
In each bootstrap iteration, survey segments are re-sampled with replacement
before fitting the detection function and estimating density/abundance.
Note that the entire process is repeated in each bootstrap: step-wise fitting
of the detection function, averaging of the best-fitting models, and density/abundance
estimation for all species/region/year combinations specified in your estimates input.
At the end of the bootstrap process, results are summarized for each species/region/year combination.
95% confidence intervals are calculated using the BCA method (adapted from package coxed, function bca()).
g(0) values during bootstrapping: When conducting the non-parametric bootstrap routine
to estimate the CV of density and abundance, uncertainty is incorporated into the g(0) value
in each iteration using a parametric bootstrapping subroutine:
First, a logit-transformed distribution is modeled
based upon the mean and CV of g(0) provided by the user in the estimates input
(see documentation for LTabundR::g0_optimize() for details on this step).
This modeled distribution is used to randomly draw a g(0) value for each iteration
of the density/abundance bootstrap routine. In this way,
the uncertainty in g(0) is propagated into uncertainty in density/abundance.
Workflow recommendations: This function was designed to optimize workflow where possible. Some considerations:
Expect a single lta() call for each species pool. You can use a single call
to estimate the detection function once, then predict density/abundance separately for each species within the pool.
Some inputs will be common across all species pools (e.g., df_settings and bootstraps).
It may be most efficient – and easiest to keep consistent and to update –
if you define these common inputs at the top of your script,
then call them with a simple variable in each of your lta() calls.
We recommend setting up each lta() call starting with bootstraps = 0,
so that you can first test that the simple estimation step is successful for all species pools.
Then test the bootstrapping functionality by setting bootstraps to 10 in each lta() call.
Track how long it takes for your code to run, which you can use to predict
processing time for a larger number of iterations, e.g., bootstraps = 1000.
The most complicated argument to prepare is estimates. To help with this,
LTabundR includes a function, lta_estimates(). See its documentation for details.
A named list:
pool: The species pool this estimate pertains to.
inputs: A record of the inputs you provided, stored as a list.
estimate: A table of density/abundance estimates for each species/region/year
combination specified in the estimates input.
This data.frame contains the following fields:
Region: Name(s) of geostrata represented in this estimate.
Area: Area of geostratum / region, in square km.
year: Years represented in this estimate.
segments: The number of effort segments used to estimate density/abundance.
km: The km of trackline effort contained in these segments.
Area_covered: The Area surveyed, according to km and ESW_mean (see next column).
ESW_mean: Mean effective strip width, in kw, calculated as the mean probability of detection for all detections.
n: The number of detections in the data.
g0_est: The mean g(0) estimate of detections, which may differ by group due to group size.
ER_clusters: The encounter rate for detections (schools) (n / km)
D_clusters: The density of detections (schools).
N_clusters: The abundance of schools.
size_mean: Average school size.
size_sd: Standard deviation of school size.
ER: Animal encounter rate.
D: Animal density.
N: Animal abundance.
g0_small: the weighted g(0) for small group sizes in this estimate.
g0_large: the weighted g(0) for large group sizes in this estimate.
g0_cv_small: the CV of weighted g(0) for small group sizes in this estimate.
g0_cv_large: the CV of weighted g(0) for large group sizes in this estimate.
df: A named list with details for the detection function.
best_models: A data.frame summary of the best-fitting models,
based upon the table produced by Distance::summarize_ds_models().
See that function's documentation for details.
all_models: Similar to the preceding slot, a tabular summary of all models tested.
best_objects: A list containing the ds objects (produced by package Distance)
for each of the best-fitting models.
sample_size: A data.frame with the detections for each species within the species pool
used to fit the detection function (as well as Other species; see the other_species input).
Ntot is total detections for each species; Ndet is total detections within the truncation distance
and therefore used in the detection function fitting routine; TD is the truncation distance.
curve: A data.frame of the best-fitting detection function curve
(best-fitting models averaged together, weighted by AICc), for 100 distances between 0
and the truncation_distance (two columns: km and p, the probability of detection
at that distance).
g0_tables: A list with g(0) estimation parameters for each sublist in estimates.
bootstrap: A named list with results from the bootstrap process, only
returned if the bootstraps input is greater than 1.
summary: a data.frame with a row for each species/region/year combination for which density/abundance was estimated.
Notable columns include g0_mean and g0_cv (the mean and CV of g(0) values across parametric bootstrap iterations,
which may differ slightly from the non-bootstrapped g0_ estimates provided in the estimate slot above.);
Nmean (the mean abundance, based on bootstrap re-sampling);
Nmedian (median abundance); Nsd (standard-deviation of abundance);
CV (coefficient of variation, which applies to both density and abundance);
L95 (the lower BCA 95% confidence interval), and U95 (the upper BCA 95% confidence interval).
details: a data.frame with details for every iteration of the bootstrap routine.
df: a data.frame with the detection function curve for each bootstrap iteration.
lta().This function is designed for a QA/QC step before running the lta() function
(line transect analysis). It checks for missing data in covariate columns,
group size columns (if lnsstot is a desired covariate), and the perpendicular distance column (PerpDistKm).
The function runs these checks twice: first for all sightings to be used in fitting the detection function
(where missing data are not preferred but would not be fatal; sightings with incomplete data would simply be removed,
lowering your sample size for the model fit), and second for detections that contribute to each point estimate
(here missing data is disastrous; unless the missing data are filled in, the detection would be removed and the density estimate would be affected.)
This function can be used to pinpoint and address holes in the data as the user sees fit.
lta_checks(cruz, df_settings, fit_filters, estimates)lta_checks(cruz, df_settings, fit_filters, estimates)
cruz |
The same |
df_settings |
The same |
fit_filters |
The same |
estimates |
The same |
The function prints messages to the Console as it performs its checks,
and it also returns a list with all details needed to find & edit rows in the sightings data that have missing data.
Compute confidence intervals of a bootstrapped LTA estimate
lta_ci(estimate, bootstraps, ci = 0.95)lta_ci(estimate, bootstraps, ci = 0.95)
estimate |
The actual estimate |
bootstraps |
The bootstrapped values |
ci |
The percent confidence interval sought (as a decimal). |
A list with three versions of the 95% confidence interval,
in each case returned as a two-element vector: $quantile is the simple quantile-based
CI of the bootstraps; $bca is the bias-correction with acceleration; and $bca_lognormal
is the log-normal version of the bca CI. Adapted from Karin Forney's Excel magic.
Combine the results of LTabundR::lta() from separate regions,
weighting density by respective area and
handling the combination of CV and 95% confidence interval estimates.
lta_combine(d1, n1, cv1, lci1, uci1, area1, d2, n2, cv2, lci2, uci2, area2)lta_combine(d1, n1, cv1, lci1, uci1, area1, d2, n2, cv2, lci2, uci2, area2)
d1 |
Density estimate (animals per square km) from region 1. |
n1 |
Abundance estimate from region 1. |
cv1 |
CV estimate from region 1. |
lci1 |
Lower 95% confidence interval of abundance from region 1. |
uci1 |
Upper 95% confidence interval of abundance from region 1. |
area1 |
Area, in square km, of region 1. |
d2 |
Density estimate for region 2. |
n2 |
Abundance estimate for region 2. |
cv2 |
CV estimate for region 2. |
lci2 |
LCI for region 2. |
uci2 |
UCI for region 2. |
area2 |
Area for region 2. |
A one-row data.frame with these columns:
D: the combined density (animals per square km), weighted by the areas of constituent regions.
N: the combined abundance.
CV: the combined CV of density and abundance.
LCI: the lower 95% confidence interval of abundance.
UCI: the upper 95% confidence interval of abundance.
area: combined area.
This function loops through a list of results from LTabundR::lta() and updates
their CV and 95% CI estimates, which were produced using a bootstrap method,
using new estimates based on the delta method.
lta_delta_method(ltas, verbose = TRUE)lta_delta_method(ltas, verbose = TRUE)
ltas |
A |
verbose |
Boolean; print report of new estimates to the console? |
An updated version of the ltas input with new values for CV, L95, and U95 in the $bootstrap$summary slot.
Loop through a list of stratified line-transect-analysis results and "destratify" – i.e., pool – them into a single estimate.
lta_destratify( lta_list, years, combine_method = "arithmetic", new_region = NULL, verbose = TRUE )lta_destratify( lta_list, years, combine_method = "arithmetic", new_region = NULL, verbose = TRUE )
lta_list |
A |
years |
A numeric vector of year(s) in which you want to pool all region-stratified results into a single annual estimate. |
combine_method |
A character string indicating the means by which estimates
of the CV and 95% confidence interval of abundance will be destratified.
The two recognized options are |
new_region |
A name for the pooled geostratum represented by the pooled estimate. If this is not provided, a name will be generated from the geostrata that are pooled. |
verbose |
A Boolean, with default |
Stratified estimates of parameter means are pooled using a weighted mean
in which the area of each geostratum is used as the weight. Stratified estimates of
abundance variance terms (SD, CV, and 95% confidence interval) are pooled either
arithmetically – using standard equations to pool estimates one at a time –
or iteratively – using the bootstrap results contained within the lta_list.
The iterative technique resamples the abundance bootstrap estimates from each
geostratum 10,000 times then calculates SD, CV, and 95% confidence interval from the
resulting distribution. Some variance terms, e.g., the SD of school size and the CV of g(0),
are not destratified in the current version and are instead replaced with NA.
A modified lta_list, in which stratified estimates have been pooled into
single annual estimates for relevant years.
Run diagnostics on a LTA result
lta_diagnostics( lta_result, options = 1:8, describe_options = FALSE, wait = TRUE )lta_diagnostics( lta_result, options = 1:8, describe_options = FALSE, wait = TRUE )
lta_result |
The result of |
options |
Numeric vector indicating which output options to return.
These options are printed for the user when |
describe_options |
Boolean; if |
wait |
Boolean; if |
A series of printed tables and plots, which the user can step through using the Enter key.
This function reads in the line-transect-analysis results (from LTabundR::lta()) within a directory
and concatenates them into a list.
lta_enlist(lta_path)lta_enlist(lta_path)
lta_path |
The path to a directory containing |
A list of LTA results.
estimates sub-lists for lta()
This function can be used to efficiently build up sub-lists for the estimates input
that you must pass to the lta() function for line-transect analysis.
Most studies of multiple species endeavor to estimate density/abundance for each species
in the same set of year-region scenarios.
Doing so typically requires multiple estimates sub-lists for each species of interest.
Writing those sub-lists manually can be redundant, tedious, and prone to inconsistencies or error.
To ensure the exact same scenarios are applied to each species of interest, you
can use this function to return a custom function that you can then use to creates a
standard set of sub-lists for each of you species.
lta_estimates(scenarios)lta_estimates(scenarios)
scenarios |
A list of sub-lists. Each sublist specifies one scenario for a density/abundance estimate. The accepted names within each sublist are:
These arguments are explained under the |
This function returns a custom function named estimator(), which accepts the following inputs:
spp (required)
title (required)
g0 (the remainder are optional)
g0_cv
g0_threshold
alt_g0_spp
combine_g0
These arguments are explained under the estimates input for the lta() function.
The estimator() function will return a list of sub-lists, in which the
species-specific inputs it accepts are added to each sub-list in the scenarios argument you provided above.
The result of the estimator() function is what you can pass as the estimates argument in lta().
See the vignette case studies for examples.
This function returns abundance estimate plots (i.e., with year on the x axis, abundance on the y axis, the best estimate represented by a point, and the confidence interval represented by a vertical line). This function is capable of producing multi-panel plots for multiple species, and it is designed to produce a dynamic layout according to the number of species pools provided.
lta_plot(lta_result, species = NULL, years = NULL, nrows = NULL, ncols = NULL)lta_plot(lta_result, species = NULL, years = NULL, nrows = NULL, ncols = NULL)
lta_result |
The result of |
species |
A character vector of estimate titles. If |
years |
A numeric vector of years whose estimates will be included in all plots,
even if an estimate is not available for a given |
nrows |
Number of rows in multi-panel plot. Can be |
ncols |
Number of columns in multi-panel plot. Can be |
A ggplot2 plot, or many ggplot2 plots arranged by gridExtra::grid.arrange().
lta() outputsThis function allows you to pool, or concatenate, the results of two separate lta() runs
in order to achieve the desired number of bootstrap iterations. An example use case:
you are running a 1,000-iteration lta() call overnight, but the power goes out at iteration 900.
In the morning you can run a 100-iteration version of the same lta() call, then use
this function to pool the two results together.
lta_pool(ltas, bootstraps = NULL)lta_pool(ltas, bootstraps = NULL)
ltas |
A |
bootstraps |
Desired number of bootstraps to keep. Example use case: You have two |
An lta() output object.
The $estimate slot will be the exact same as the first slot in the ltas input;
The $details slot will have the pooled bootstrap samples.
The $df slot will have the pooled detection function curves.
The $summary slot will have updated summary statistics based on the pooled set of bootstraps.
This function formats the results from an LTA analysis (LTabundR::lta()) into
that expected for standard tables in NOAA stock assessment reports (Tables 1, 2, 3, and 4, as well as appendix tables).
lta_report(lta_result, cruz = NULL, verbose = TRUE)lta_report(lta_result, cruz = NULL, verbose = TRUE)
lta_result |
An object holding the result of |
cruz |
The cruz object (produced from LTabundR::process_surveys())
that was passed to |
verbose |
Boolean, with default |
A list with five slots:
table1a: Sighting counts for all species in the cruz dataset for the years in which estimates were prepared.
If the cruz argument was NULL, this slot is also NULL. If not, a count of all sightings and systematic-only sightings
(i.e., EffType = "S" and Bft <= 6) are given for each species-year-region in the cruz data.
These counts are provided separately from the $table1b slot below, since those counts are based on the
lta_result object, and will not include sightings for species that did not have a specific LTA estimate
specified when it was made. We also include this separately so as to give the user full flexibility in how they summarize
sighting counts by region/population/stock.
table1b: Sighting counts used in estimates of density/abundance. Columns are prepared
for total sightings (Ntot) and systematic sightings (Nsys), but they are left blank, since it
is not clear how sightings from multiple regions in $table1a would be concatenated for this table,
since that involves stock-level designations.
The user can fill in those gaps accordingly.
table2: Sample sizes and truncation distances for detection functions
modeled by using pooled species/sightings
table3: Line-transect parameter estimates (mean Effective Strip half-Width, ESW;
mean school size; trackline detection probability, g(0); and its CV).
table4: Density and abundance estimates.
tableA1 : Appendix table with study areas for each geostratum/cohort/year.
tableA2: A list in which each slot is a data.frame with Effort & Beaufort allocation,
parsed by geostratum, for each year. If the cruz argument was NULL, this slot is also NULL.
Example of LTA results for three delphinids in 2010 and 2017
lta_resultlta_result
An object of class list of length 6.
This dataset was processed using the following code:
data("cnp_150km_1986_2020")
cruz <- cnp_150km_1986_2020
cruz$strata
data('g0_results')
Rg0 <- g0_results
fit_filters = list(spp = c('013', '026', '031'), # striped, frasers, melon-headed
pool = 'Multi-species pool 1',
cohort = 'all',
truncation_distance = 5,
other_species = 'remove',
years = 1986:2017,
regions = NULL,
not_regions = NULL)
df_settings = list(covariates = c('bft','lnsstot','cruise','year','ship','species'),
covariates_factor = c(FALSE, FALSE, TRUE, TRUE, TRUE, TRUE),
covariates_levels = 2,
covariates_n_per_level = 10,
detection_function_base = 'hn',
base_model = '~1',
delta_aic = 2)
estimates <-
list(
list(spp = '013',
title = 'Striped dolphin',
years = 2010,
regions = 'HI_EEZ',
g0 = 0.33, g0_cv = 0.20),
list(spp = '013',
title = 'Striped dolphin',
years = 2017,
regions = 'HI_EEZ',
g0 = 0.32, g0_cv = 0.21),
list(spp = '026',
title = "Fraser's dolphin",
years = 2010,
regions = 'HI_EEZ',
g0 = 0.33, g0_cv = 0.20),
list(spp = '026',
title = "Fraser's dolphin",
years = 2017,
regions = 'HI_EEZ',
g0 = 0.32, g0_cv = 0.21),
list(spp = '031',
title = 'Melon-headed whale',
years = 2010,
regions = 'HI_EEZ',
g0 = 0.33, g0_cv = 0.20),
list(spp = '031',
title = 'Melon-headed whale',
years = 2017,
regions = 'HI_EEZ',
g0 = 0.32, g0_cv = 0.21))
result <- lta(cruz,
Rg0,
fit_filters,
df_settings,
estimates,
use_g0 = TRUE,
bootstraps = 100,
toplot=TRUE,
verbose=TRUE)
A flexible routine for carrying out subgroup-based line-transect analysis
using the methodologies described for Hawai'ian false killer whales,
Pseudorca crassidens, in Bradford et al. (2020).
The function returns an estimate
of density and abundance – along with estimates of intermediate parameters –
with a CV derived from a bootstrapping routine.
As part of this process, relative trackline detection probability (g(0)) is modeled
as a function of Beaufort sea state (using LTabndR function g0_model()),
then a weighted g(0) and its CV are estimated using LTabundR function g0_weighted().
lta_subgroup( df_sits, truncation_distance, ss, density_segments, density_das, density_sightings, df_settings = list(covariates = NULL, covariates_factor = NULL, covariates_levels = 2, covariates_n_per_level = 10, simplify_cue = TRUE, simplify_bino = TRUE, detection_function_base = "hn", base_model = "~1", delta_aic = 2), Rg0 = NULL, cruz10 = NULL, g0_spp = NULL, g0_truncation = NULL, g0_constrain_shape = FALSE, g0_jackknife_fraction = 0.1, abundance_area = NULL, iterations = 5000, seed = NULL, output_dir = NULL, toplot = FALSE, verbose = TRUE )lta_subgroup( df_sits, truncation_distance, ss, density_segments, density_das, density_sightings, df_settings = list(covariates = NULL, covariates_factor = NULL, covariates_levels = 2, covariates_n_per_level = 10, simplify_cue = TRUE, simplify_bino = TRUE, detection_function_base = "hn", base_model = "~1", delta_aic = 2), Rg0 = NULL, cruz10 = NULL, g0_spp = NULL, g0_truncation = NULL, g0_constrain_shape = FALSE, g0_jackknife_fraction = 0.1, abundance_area = NULL, iterations = 5000, seed = NULL, output_dir = NULL, toplot = FALSE, verbose = TRUE )
df_sits |
(Required.) A |
truncation_distance |
(Required.) The truncation distance, in km, to apply during detection function model fitting. |
ss |
(Required.) A numeric vector of subgroup school sizes to use to find its mean and bootstrapped CV. In Bradford et al. (2020), data come from all Phase 1 and Phase 2 estimates of subgroup sizes from 2010 onwards. These estimates are the geometric mean of repeat estimates from separate observers. |
density_segments |
(Required.) The survey segments to be used in density/abundance estimation.
For example, Bradford et al. (2020) used 150-km segments to estimate false killer whale
density in the Hawaiian EEZ in 2017 (these data are available in the built-in dataset
|
density_das |
(Required.) The complete survey data corresponding to the above segments.
These data will be used to determine the proportion of survey effort occurring in each Beaufort
sea state during Relative |
density_sightings |
(Required.) The encounters to use in density/abundance estimation.
In Bradford et al. (2020), these were the Phase 1 detections of false killer whales
within the population-region-year of interest, e.g., Northwest Hawaiian Island population sightings
within the Hawaiian EEZ in 2017. No filtering will be applied to these sightings,
so make sure only the sightings you wish to use are included and nothing more.
Note that all column names within |
df_settings |
Optional. A named list, with parameters for fitting the detection function.
See detailed documentation in the |
Rg0 |
A |
cruz10 |
A processed |
g0_spp |
A character vector of species codes to use to estimate |
g0_truncation |
The truncation distance to use when estimating |
g0_constrain_shape |
Some Rg(0) curves will not decline monotonically
due to sample size issues at low Bft (0-2) or high Bft (5-6) states.
To coerce monotonic decline, set this input to |
g0_jackknife_fraction |
The proportion of data to leave out within each jackknife permutation for estimating the CV of g(0). The default is 0.1 (i.e., 10% of the data, yielding 10 jackknife loops), after Barlow (2015). |
abundance_area |
The area in square km of the region of interest. The density estimate will be scaled by this area. |
iterations |
Number of iterations to use in the various CV bootstrapping procedures
occurring throughout this function, specifically: Effective Strip Half-Width CV estimation,
school size CV estimation, weighted |
seed |
Set a seed (any integer) to ensure that the bootstrap results are reproducible.
If left |
output_dir |
The path in which results |
toplot |
A Boolean, with default |
verbose |
A Boolean, with default |
This function performs the following operations:
Fits a detection function to df_sits, using the LTabundR function df_fit().
That function will be used to estimate the effective strip half-width (ESW) of each sighting in detection_sightings (and bootstrapped versions thereof).
Conducts bootstrap re-sampling of the detection function fitting routine in order to estimate the CV of ESW.
Estimates the arithmetic mean of subgroup school size based on the ss input.
Creates a bootstrap-resampled distribution of subgroup school sizes, with which CV is estimated.
Models the relative g(0) in different survey conditions using the LTabundR function g0_model().
This function also estimates the CV of the Rg(0) estimate in each Beaufort sea state using jackknife resampling.
Estimates the ESW and encounter rate (subgroup detections / trackline surveyed).
Creates a bootstrap-resampled distribution of encounter rate and ESW estimates.
Calculates a weighted g(0) estimate according to the proportion of effort occurring in each Beaufort sea state,
then uses an automated parameter optimization routine (see details in LTabundR function g0_weighted()) to
estimate the CV of the weighted g(0) estimate.
Creates a bootstrap-resampled distribution of the weighted g(0) estimate.
Estimates density using the best estimates of effective strip half-width, school size, g(0), and the encounter rate.
Estimates abundance by scaling the density estimate by the provided abundance_area, if provided.
Creates a bootstrap-resampled distribution of the density estimate by iteratively drawing values (without replacement, since the constituent distributions were already built with replacement) from the resampled distributions of the constituent parameters of the density equation.
Creates a bootstrap-resampled distribtion of the abundance estimate by
scaling the density distribution by abundance_area.
A list with these slots: $estimate (point estimates of parameters, detailed below),
$bft (proportion of survey effort in each sea state),
$g0_details (details on g0 fitting),
$df (details on detection function fitting),
$bootstraps (parameter values for each bootstrap iteration),
$iterations (the number of iterations). Columns in $estimate slot are as follows:
D: The estimate of density for the population.
D_CV: The CV of the density estimate.
D_L95: The lower 95% confidence interval of density using the BCA method.
D_U95: The upper 95% confidence interval of density using the BCA method.
N: The estimate of abundance.
N_CV: The CV of the abundance estimate.
N_L95: The lower 95% confidence interval of abundance using the BCA method.
N_U95: The upper 95% confidence interval of abundance using the BCA method.
ER: The estimate of the encounter rate.
ESW = The estimate of the Effective Strip Width (km) for the population.
ESW_CV = Estimate of ESW CV, based on standard deviation of bootstrap estimates of ESW.
ss = Mean subgroup size estimate.
n: Number of sightings used in density estimation.
L: Survey effort, in km, used in density estimation.
n_segments: Number of effort segments used in density estimation.
g0: The empirical weighted mean of g(0) for the point estimate, based on sightings conditions in density_segments.
g0_cv: The CV of this estimate of the point estimate of the weighted mean of g(0), as estimated by an MCMC routine.
g0_details: A list with detailed results from Rg(0) estimation (see output details in ?g0_model).
df: A list with detailed results from detection function estimation (see output details in ?df_fit).
bootstraps: A named list with the bootstrapped values for esw (effective strip half-width),
ss (subgroup size), g0 (relative g(0)), er (encounter rate), D (density), and N (abundance).
iterations: number of bootstrap iterations used for CV estimation.
See the online vignette for more details
Wincruz surveyProduced an interactive leaflet map of your Wincruz survey data.
map_cruz( cruz, cohort = 1, eez_show = TRUE, eez_color = "black", eez_weight = 0.6, eez_opacity = 0.5, strata_show = TRUE, strata_color = "forestgreen", strata_weight = 1, strata_opacity = 0.5, effort_show = FALSE, effort_color = "darkblue", effort_weight = 0.6, effort_opacity = 0.85, sightings_show = TRUE, sightings_color = "color code", sightings_radius = 1, sightings_opacity = 0.5, initial_zoom = 4, verbose = TRUE )map_cruz( cruz, cohort = 1, eez_show = TRUE, eez_color = "black", eez_weight = 0.6, eez_opacity = 0.5, strata_show = TRUE, strata_color = "forestgreen", strata_weight = 1, strata_opacity = 0.5, effort_show = FALSE, effort_color = "darkblue", effort_weight = 0.6, effort_opacity = 0.85, sightings_show = TRUE, sightings_color = "color code", sightings_radius = 1, sightings_opacity = 0.5, initial_zoom = 4, verbose = TRUE )
cruz |
Your |
cohort |
The cohort whose data you would like to map, provided as a number indicating which slot in |
eez_show |
Boolean; display EEZ boundaries? |
eez_color |
Character string; color of EEZ boundary lines, if |
eez_weight |
Single positive numeric; weight (thickness) of EEZ boundary lines, if |
eez_opacity |
Single numeric between 0 and 1; opacity of EEZ boundary lines, if |
strata_show |
Boolean; display geostratum boundaries? |
strata_color |
Character string; color of geostratum boundary lines, if |
strata_weight |
Single positive numeric; weight (thickness) of geostratum boundary lines, if |
strata_opacity |
Single numeric between 0 and 1; opacity of geostratum boundary lines, if |
effort_show |
Boolean; display survey tracks? Default is |
effort_color |
Single character string; color of survey tracklines, if |
effort_weight |
Single positive numeric; weight (thickness) of survey tracklines, if |
effort_opacity |
Single numeric between 0 and 1; opacity of survey tracklines, if |
sightings_show |
Boolean; display sightings? |
sightings_color |
A single character string, indicating the color for sighting markers.
Note: if you enter |
sightings_radius |
A single postive numeric, indicating the size of the sightings markers; this argument is ignored if |
sightings_opacity |
A single numeric between 0 and 1, indicating the opacity of sightings markers; this argument is ignored if |
initial_zoom |
Initial zoom default for the |
verbose |
Boolean, with default |
An interactive leaflet map.
Cruise data processed for all NOAA SWFSC and PIFSC surveys, 1986 - 2020 (10 km segment lengths)
noaa_10km_1986_2020noaa_10km_1986_2020
An object of class list of length 3.
This dataset was processed using the following code:
data(group_size_coefficients)
survey <- load_survey_settings(
out_handling = 'stratum',
max_row_interval = Inf,
segment_method = "equallength",
segment_target_km = 10,
segment_max_interval = 6,
segment_remainder_handling = c("segment"),
group_size_coefficients = group_size_coefficients)
data(strata_ccs)
data(strata_cnp)
strata <- c(strata_ccs, strata_cnp)
strata$NEPAC <- data.frame(Lat = c(-20, -20, 65, 65), Lon = c(-230, -70, -70, -200))
all_species <- load_cohort_settings(
id = "all",
species = NULL,
probable_species = FALSE,
sighting_method = 0,
cue_range = 0:7,
school_size_range = c(0, 10000),
school_size_calibrate = TRUE,
calibration_floor = 0,
use_low_if_na = TRUE,
io_sightings = 0,
geometric_mean_group = TRUE,
truncation_km = 7.5,
beaufort_range = 0:6,
abeam_sightings = FALSE,
strata_overlap_handling = c("smallest"),
distance_types = c('S','F','N'),
distance_modes = c('P','C'),
distance_on_off = TRUE
)
settings <- load_settings(strata = strata,
study_area = NULL,
survey = survey,
cohorts = list(all_species))
das_file = c('../test_code/data/swfsc_1986_2020.das')
swfsc <- process_surveys(das_file,
settings = settings)
das_file = '../test_code/CNP/CenPac1986-2020_Final_alb.das'
pifsc <- process_surveys(das_file,
settings = settings)
cruzes <- list(swfsc, pifsc)
noaa_10km_1986_2020 <- cruz_combine(cruzes)
sf lineThis is an internal function typically not called by a user directly.
points_to_line(data, long, lat, id_field = NULL, sort_field = NULL)points_to_line(data, long, lat, id_field = NULL, sort_field = NULL)
data |
The dataframe containing columns with coordinates. |
long |
A character vector with the name of the column with longitude coordinates. |
lat |
A character vector with the name of the column with latitude coordinates. |
id_field |
If the dataframe contains data for multiple lines, specify the name of the column (as a character vector) that indicates which line each point belongs to. |
sort_field |
If the dataframe is not arranged in the sequence you wish, specify the name of the column (as a character vector) you want to arrange by before creating the line. |
A sp::SpatialLines object created from sp::spRbind().
An interior function, typically not called by analysts. This function returns segment and sighting data according to resampled segment IDs, which serve as part of the bootstrap variance estimation process. The function includes an option to specify a selection of segment IDs, which allows the same bootstrap segments to be selected for the abundance estimation stage as was used in the detection function model fitting stage.
prep_bootstrap_datasets(segments, sightings, segment_picks = NULL, seed = NULL)prep_bootstrap_datasets(segments, sightings, segment_picks = NULL, seed = NULL)
segments |
Effort segments dataframe, drawn from a |
sightings |
Sightings dataframe, drawn from a |
segment_picks |
If segment IDs have been previously selected for this dataset, provide them here. |
seed |
Set a seed (any integer) to ensure that the result is reproducible.
If left |
A list with resampled data: segments, sightings, and segment_picks
(a numeric vector of segment IDs that have been re-sampled).
This function is the near-equivalent of the DISTRAV subroutine in ABUND9.
This is an internal function typically not called by a user directly.
It is called in format_das().
process_km( das, min_interval = 5, max_interval = 3600, replacement_interval = 3600, max_km_gap = 100, km_filler = 1, speed_filler = 10 * 1.852, debug_mode = TRUE )process_km( das, min_interval = 5, max_interval = 3600, replacement_interval = 3600, max_km_gap = 100, km_filler = 1, speed_filler = 10 * 1.852, debug_mode = TRUE )
das |
A dataframe of |
min_interval |
Minimum seconds between rows before distance will be calculated. Default is 30 seconds; if the interval is less than this value, the distance will be assumed to be 0 km. |
max_interval |
The maximum time interval, in seconds, between rows before assuming that
there has been a break in survey data logging. This time interval will be replaced with the value specified in |
replacement_interval |
The time interval, in second, to use as a replacement
when the time interval between rows exceeds |
max_km_gap |
Another way of avoiding long gaps in data; this is the maximum distance gap, in km, allowed between rows of data.
This constraint is applied after the |
km_filler |
When valid speed and position information is not available (e.g., the given distance exceeds |
speed_filler |
When speed is not available in the data, this value (in kmh) will be used as a filler in order to estimate the distance between consecutive rows of data based on timestamp differences (when lat/long coordinates are not available). |
debug_mode |
Boolean, with default |
A numeric vector, the same length as the number of rows in das, of distances (in km).
The final element of this vector will be 0.
This is an internal function typically not called by a user directly. It takes a dataframe of polygon coordinates and returns a list with the polygon formatted in various ways, as well as a calculation of the area of the polygon with land area removed (optionally).
process_polygon(polygon_dataframe, remove_land = TRUE, toplot = FALSE)process_polygon(polygon_dataframe, remove_land = TRUE, toplot = FALSE)
polygon_dataframe |
A dataframe in which the first two columns are |
remove_land |
If |
toplot |
If |
A list with four named slots:
coords The input dataframe, with longitudes corrected to proper negative decimal degrees, e.g., longitudes supplied as -185 will become 175.
polygon The polygon created by sf::st_polygon()
sf The sf version of the polygon that will be passed to mapping functions.
sf_land The sf version of the land polygons included within the polygon, if any.
km2 The area of the polygon, in square kilometers.
idl A Boolean indicating whether or not this polygon crosses the International Date Line.
lat_range Latitude range of polygon, in decimal degrees (N positive, S negative).
lon_range Longitude range of polygon, in decimal degrees (E positive, W negative).
plot A ggplot object; NULL if the input toplot is FALSE.
This is an internal function typically not called by a user directly.
It is the fifth subroutine called within process_surveys(), after segmentize() and before process_subgroups().
process_sightings( cruz, calibrate = NULL, calibrate_floor = NULL, geometric_mean = NULL, verbose = TRUE )process_sightings( cruz, calibrate = NULL, calibrate_floor = NULL, geometric_mean = NULL, verbose = TRUE )
cruz |
A |
calibrate |
An argument allowing you to override the settings contained within the |
calibrate_floor |
Another argument allowing for settings override. This argument accepts a number indicating the minimum raw school size estimate for which school size calibration will be attempted. |
geometric_mean |
Another argument allowing settings override.
This argument accepts a Boolean;
if |
verbose |
Boolean, with default |
A modified cruz object, in which a sightings dataframe
(one row for each species in each sighting, with school size estimates averaged and calibrated according to cohort-specific settings)
has been added to each <cohort> list. The sightings dataframe has a new column, included, indicating whether or not
a sighting will be included in an analysis according to the inclusion criteria specified in cohort-specific settings,
as well as a new column, ss_valid, indicating whether or not the school size estimate
for this sighting is valid and appropriate for use in abundance estimation and/or detection function fitting
with a school-size covariate. All columns are described in detail within the
documentation for the LTabundR function, process_surveys().
Determine in/out status of DAS events for each geo-strata provided by settings.
This function loops through each stratum dataframe you have provided it in settings$strata,
formats the stratum, and asks whether each DAS row occurs within it.
This is an internal function typically not called by a user directly.
It is the second subroutine called within process_surveys(), after load_das() and before format_das().
process_strata(das, settings, verbose = TRUE)process_strata(das, settings, verbose = TRUE)
das |
A |
settings |
A |
verbose |
Boolean, with default |
A list with two named slots: settings and das.
The das slot has the dataframe of your survey data.
For each stratum, a column named stratum_<StratumName> is added to the das dataframe;
each row in this column is TRUE (included) or FALSE.
Subgroups are found based on DAS event code "G" and associated events.
Subgroup sizes are estimated for each phase (based upon the false killer whale protocol),
and both arithmetic and geometric means are provided.
This is an internal function typically not called by a user directly.
It is the final processing subroutine called within process_surveys(), after the subroutine process_sightings().
process_subgroups(cruz, edits = NULL, verbose = TRUE)process_subgroups(cruz, edits = NULL, verbose = TRUE)
cruz |
A |
edits |
An optional input: a Each If this input is supplied, the See the vignette for details. |
verbose |
Boolean, with default |
A finalized cruz object.
If subgroups are found, a subgroups slot is added to the analysis list for a cohort.
This subgroups slot holds a list with three dataframes:
events, in which each row is a school size estimate for a single subgroup during a single phase – 1 or 2 – within a single sighting;
subgroups, in which each row is a single phase for a single subgroup, with all school size estimates averaged together (both arithmetically and geometrically);
sightings, in which each row is a school size estimate for a single phase for a single sighting, with all subgroup school sizes summed together.
Phase is determined simply according to the OnEffort column. If it is TRUE, Phase is 1; if not, Phase is 2.
Wincruz survey data for analysis.This function is the main command you will use to begin working with your survey data in R.
It takes Wincruz survey data – .DAS file(s) – and user-specified settings
to prepare the data for density estimation and/or habitat modeling analyses.
This function was designed to be similar to ABUND9, the Fortran program
written by Jay Barlow (NOAA SWFSC) for the same purpose.
process_surveys( das_file, settings, edits = NULL, process_sightings = TRUE, process_subgroups = TRUE, save_local = FALSE )process_surveys( das_file, settings, edits = NULL, process_sightings = TRUE, process_subgroups = TRUE, save_local = FALSE )
das_file |
One or more filenames/filepaths to DAS files with survey data,
supplied as a character vector. If multiple files are supplied, each file will be
processed separately then combined using |
settings |
An object representing the output of |
edits |
An optional list of staged edits for modifying the |
process_sightings |
A Boolean, with default |
process_subgroups |
A Boolean, with default |
save_local |
If TRUE (not the default), the resulting |
This function is a wrapper for several subroutines, which are executed in the following order:
Read and format the survey data contained in your DAS file using functions developed in the package swfscDAS
(this step is carried out using the internal LTabundR function load_das()).
Interpolate the DAS data, if instructed by settings. See load_survey_settings() for details.
Determine which DAS events occur within the geo-strata
provided by the user (using the internal LTabundR function process_strata()).
Remove invalid entries, determine the ship used in each cruise,
calculate the distance transited between each DAS row, and initiate the
data structure for the eventual cruz object output.
(using the internal LTabundR function format_das()).
Parse survey effort into "segments", which are used in variance estimation,
and determine which segments should be included in the analysis based upon user-specified settings
(using the internal LTabundR function segmentize()).
Process sightings (optional) by determining which should be included in the analysis based upon user-specified settings,
and refine school size estimates by calibrating observer estimates and averaging estimates from multiple observers.
(using the internal LTabundR function process_sightings()).
Process subgroup size estimates (optional) for false killer whales
(using the internal LTabundR function process_subgroups()).
The above process is repeated for each DAS file; if there are multiple
DAS files, the results are combined using LTabundR::cruz_combine().
Optionally save the result as an RData object to easily pass the processed data to other R scripts.
A cruz object, which is a nested list with the following primary slots:
settings, containing the settings list you provided as an argument.
strata, containing a dataframe summarizing the geostrata provided (their name and area, in square km).
cohorts, containing a named list for each cohort you specified within the settings argument.
Each cohort slot has a similar structure:
cruz$cohorts$<cohort>$<details>
The name of each <cohort> slot is drawn from the id slot within that cohort's settings (e.g., settings$cohorts[[1]]$id).
All cohorts have the same three slots for <details>:
segments, a data.frame with metadata for each effort segment (see below).
das, a data.frame of the survey data (see below).
sightings, a data.frame with details for each sighting (see below).
Some cohorts may also have a fourth <details> slot, subgroups,
if subgroups were found in the data for the species specified in the cohort.
This slot will contain a list (see below).
segments data structure
A data.frame with metadata for each segment; each row is a segment.
Cruise: Cruise number
ship: Ship name initials
stratum: Stratum designation for this segment
seg_id: Unique segment identifier
yday: Numeric day of year
dist: Distance surveyed in this segment
lat1: Start latitude of segment, decimal degrees
lon1: Start longitude of segment, decimal degrees
DateTime1: Date and time for start of segment, formatted as a lubridate::datetime object
timestamp1: Numeric timestamp for start of segment (seconds since 00:00:00 UTC on 1 January 1970)
lat2: Ending latitude
lon2: Ending longitude
DateTime2: Date and time of end of segment
timestamp2: Numeric timestamp for end of segment
mlat: Latitude of middle of segment (i.e., the coordinate for the row of DAS data that is at nrow(<segment data>) / 2)
mlon: Longitude of middle of segment
mDateTime: Date and time of middle of segment
mtimestamp: Numeric timestamp of middle of segment
use: A decision as to whether or not this segment will be included in the analysis, based upon user-specified criteria in settings.
Mode: Effort mode (P for passing or C for closing)
EffType: Effort type (S for systematic, N for non-systematic – i.e., off design-based trackline – and F for fine-scale)
OnEffort: If TRUE, standard search protocols are in practice
ESWsides: Number of sides for which the effective strip width (ESW) will apply. When traveling nearshore, this may be only 1
year: Year
month: Numeric month
day: Numeric day of month
min_line: The line number of DAS data at the start of this segment
max_line: The final line number
n_rows: Number of rows of DAS data in this segment
avgBft: Weighted average Beaufort sea state during this segment
avgSwellHght: Weighted average Swell Height, in feet, during this segment
avgHorizSun: Weighted average horizontal sun angle, corresponding to a clock face, during this segment
avgVertSun: Weighted average vertical sun angle (12 = overhead, 1-3 = at the horizon) during this segment
avgGlare: Weighted average Glare status during this segment
avgVis: Weighted average visibility (defines as the distance, in nautical miles, at which a dolphin could be seen surfacing with the water, not the sky, as the background) during this segment
avgCourse: Weighted average ship heading during this segment
avgSpdKt: Weighted average speed, in knots, during this segment
das data structure
The data.frame of DAS survey data, as read and formatted by swfscDAS::das_read() and swfscDAS::das_process()
See the latter function documentation for details on columns. We have added the following columns during the preparation
of the cruz object:
stratum_<stratum name> A Boolean indicating whether or not this row of data occurs within this geostratum polygon.
There will be a column like this for each geostratum provided in your settings object.
year Year
month Numeric month
day Numeric day of month
yday Numeric day of year
km_int Distance, in kilometers, between this row of data and the next. See documentation for process_km() for details.
km_cum Cumulative distance traveled up to this point in the DAS data.
ship Ship name initials
stratum Final stratum designation, decided based upon user-specific settings.
seg_id Identifier for the segment containing this row of data.
use: A Boolean decision as to whether or not this segment will be included in the analysis, based upon user-specified criteria in settings.
sightings data structure
The data.frame of processed sightings, as prepared by swfscDAS::das_sight(return.format = 'complete').
See that function's documentation for details on columns. Note that the unique sighting identifier can be
found in column SightNodaily, not SightNo.
That function returns up to several rows for each sighting (DAS event codes S, s, A, 1, 2, ..., etc.).
We have processed the result further such that each row represents the school size estimate
for a single species within a single sighting. For example, single-species sightings will always have just one row.
We have also added the following columns during the preparation
of the cruz object:
See the columns added to the das slot above; those have all been propagated to this sightings table.
species: species code (character string) for the species represented by this row.
best: Best estimate of school size (calibrated and averaged across observer estimates according to settings)
low: Low estimate of school size (ditto)
high: High estimate of school size (ditto)
prob: If TRUE, this species code is a probable identification (DAS event code ?).
mixed: If TRUE, this species occurred in a mixed-species school.
ss_tot: Total school size (calibrated and averaged across observer estimates according to settings)
ss_percent: Percent of the school comprised by this species (averaged across observer estimates).
n_sp: Number of species in this sighting.
n_obs: Number of observers who contributed a school size estimate for this species.
n_best: Number of valid best estimates of school size.
n_low: Number of valid low estimates.
n_high: Number of valid high estimates.
calibr: Boolean indicating whether school size calibration was applied.
ss_valid: Boolean indicating whether or not the school size estimate
for this sighting is valid and appropriate for use in abundance estimation and/or detection function fitting
with a school-size covariate.
included: Boolean indicating whether the sightings should be included
in the analysis based on the specified settings. Any sighting with use == FALSE
will also have included == FALSE, but it is possible for sightings
to have use == TRUE with included == FALSE. For example, if the setting
abeam_sightings is set to FALSE, a sighting with a bearing angle beyond
the ship's beam can be excluded from the analysis (included == FALSE)
even though the effort segment it occurs within will still be used (use == TRUE).
subgroups data structure
If subgroup events (DAS event code G) are found pertaining to the species in your cohort,
this slot will have a list with three slots:
sightings: A data.frame in which each row is a school size estimate
for a single phase for a single sighting, with all subgroup school sizes summed together.
Columns:
Cruise
Date
SightNo
Phase
DateTime Mean date and time of estimates of this sighting
Lat (same – mean)
Lon (same – mean)
Species
Angle (same – mean)
RadDist (same – mean)
seg_id Identifier for the segment containing this row of data.
PerpDist (same – mean)
GSBest Sum of arithmetic means of best estimates of subgroups
GSBest_geom Sum of geometric means
EffType Type of effort (systematic, nonsystematic, or fine-scale)
OnEffort Whether or not standard search protocols are in use (TRUE or FALSE).
use Whether the segment on which this sighting occurred meets analysis inclusion criteria.
stratum_[stratum name] A set of columns, one for each geostratum in the cruz object settings file,
indicating whether or not this location occurs within each geostratum.
stratum The geostratum to which this location was assigned, based upon cohort settings.
subgroups: A data.frame in which each row is a single phase
for a single subgroup, with all school size estimates averaged together (both arithmetically and geometrically). Columns:
Cruise
Date
DateTime First date and time of estimates of this subgroup
Lat (same – first data point for estimates of this subgroup)
Lon (same)
OnEffort (same)
EffType (same)
SightNo (same)
Species (same)
SubGrp (same)
Angle Mean angle to this subgroup
RadDist Mean radial distance to this subgroup
seg_id Identifier for the segment containing this row of data.
PerpDist Mean perpendicular distance to this subgroup
GSBest Arithmetic mean of best estimates of this subgroup. If no best estimates are given, the GSL value will be used here.
GSH Arithmetic mean of high estimates of this subgroup
GSL Arithmetic mean of low estimates of this subgroup
GSBest_geom Geometric mean of best
GSH_geom Geometric mean of high
GSL_geom Geometric mean of low
Phase Phase (1 or 2)
use Whether the segment on which this sighting occurred meets analysis inclusion criteria.
stratum_[stratum name] A set of columns, one for each geostratum in the cruz object settings file,
indicating whether or not this location occurs within each geostratum.
stratum The geostratum to which this location was assigned, based upon cohort settings.
events: A data.frame in which each row is single subgroup size estimate from a single observer for a single phase (Phase 1 – on effort / passing mode – or Phase 2 – off effort / closing mode).
This is effectively the "raw" subgroup data. Columns:
Cruise Cruise number
Date Date, in format YYYY-MM-DD
DateTime Date and time, in format YYYY-MM-DD HH:MM:SS
Lat Latitude, in decimal degrees
Lon Longitude, in decimal degrees
OnEffort If TRUE, standard search protocols are in use. If FALSE, non-standard protocols (or no searching at all).
EffType Effort type (S for systematic, N for non-systematic, and F for fine-scale)
SightNo Sighting number of the day (the count resets every day)
Species Species code (character string)
Line Line number in DAS data
SubGrp Subgroup identifier code
Event Count of estimates for this subgroup-phase
Obs Observer code
GSBest Best estimate of subgroup size
GSH High estimate of subgroup size
GSL Low estimate of subgroup size
Angle Angle between bow and subgroup
RadDist Radial distance to subgroup, in km
use Whether the segment on which this sighting occurred meets analysis inclusion criteria.
stratum_[stratum name] A set of columns, one for each geostratum in the cruz object settings file,
indicating whether or not this location occurs within each geostratum.
stratum The geostratum to which this location was assigned, based upon cohort settings.
PerpDist Perpendicular distance to subgroup from the trackline represented by the ship heading, in km
sgid Unique subgroup identifier
sitid Unique sighting identifier
phase Phase in protocol; all OnEffort == TRUE estimates are Phase 1; all OnEffort == FALSE estimates are Phase 2.
This cruz object can be carried forward into data exploration (e.g., see the LTabundR function cruz_explorer()),
analyses (e.g., see the LTabundR function lta()),
or passed to mapping functions (see the LTabundR functions that begin with map_...)
or summary functions (see the LTabundR functions that begin with summarize_...).
This is an internal function typically not called by a user directly.
This function reads in a .DAT file with coordinates for one or more polygons,
returning a list.
read_polygon(dat_file)read_polygon(dat_file)
dat_file |
Filepath to a |
A named list:
polygons A dataframe summarizing the polygons contained in the .DAT file.
It has four columns: name (polygon name), area (polygon area, if provided),
name_i (the index of the polygon in the file), and area_i (the index of the area provided in the file).
coordinates A list with a slot for each polygon contained within the .DAT file. Each polygon is a
dataframe with two columns: Lon and Lat, with coordinates formatted as provided by the .DAT file.
dat The raw DAT file, as it was read by R, returned as a dataframe.
This is an internal function, typically not called by the user.
region_das(das, regions)region_das(das, regions)
das |
The |
regions |
A character vector of geostrata whose segments you want. |
A vector of line_num values whose data occur within any of regions,
which can be used to filter segments and sightings.
This is an internal function, typically not called by the user.
region_segments(das, regions)region_segments(das, regions)
das |
The |
regions |
A character vector of geostrata whose segments you want. |
A vector of segment IDs whose data occur within regions,
which can be used to filter segments and sightings by the seg_id column.
This function chops DAS effort into discrete sections for the purposes of estimating the variance of the abundance estimate.
This is an internal function typically not called by a user directly.
It is the fourth subroutine called within process_surveys(), after format_das() and before process_sightings().
However, arguments are provided that allow you to call this function directly and override settings so that you can
explore how segmentizing works.
segmentize( cruz, segment_method = NULL, segment_target_km = NULL, segment_max_interval = NULL, segment_remainder_handling = NULL, beaufort_range = NULL, distance_types = NULL, distance_modes = NULL, distance_on_off = NULL, seed = NULL, to_plot = TRUE, debug_mode = FALSE, verbose = FALSE )segmentize( cruz, segment_method = NULL, segment_target_km = NULL, segment_max_interval = NULL, segment_remainder_handling = NULL, beaufort_range = NULL, distance_types = NULL, distance_modes = NULL, distance_on_off = NULL, seed = NULL, to_plot = TRUE, debug_mode = FALSE, verbose = FALSE )
cruz |
A nascent |
segment_method |
This and the remainder of inputs allow you to override
the settings contained within the |
segment_target_km |
If segmentizing by |
segment_max_interval |
If segmentizing by |
segment_remainder_handling |
If segmentizing by |
beaufort_range |
A numeric vector indicating the Beaufort sea states (0 - 7) to be accepted within usable segments. |
distance_types |
A character vector of the effort types that will be included
in detection function estimation,
and therefore considered in effort segmentizing.
Accepted values are |
distance_modes |
The effort modes that will be included in
detection function estimation,
and therefore considered in effort segmentizing.
Accepted values are |
distance_on_off |
The value(s) of |
seed |
Supply a number to ensure that segment chopping is exactly reproducible.
Some of the remainder handling methods (namely |
to_plot |
Boolean, with default |
debug_mode |
Boolean, with default |
verbose |
Boolean, with default |
A modified cruz object, in which each cohort slot contains a list with the following slots:
das (with two new columns, seg_id, indicating the segment corresponding to each DAS row;
and use, indicating whether or not (TRUE or FALSE) the segment is to be included in the analysis.)
and segments (a dataframe summarizing each segment).
Ship codes
shipsships
An object of class data.frame with 66 rows and 3 columns.
A data.frame matching the ship name initials to the NOAA-NFMS cruise number.
Species codes used in WinCRUZ
species_codesspecies_codes
A data.frame with 164 rows and 5 variables:
Code used in WinCRUZ
Abbreviated name, in all CAPS
Latin Genus species
Most common name
Alternative common names
A data.frame containing species codes and associated identifiers.
Retrieve common and scientific names for a species based on their code number or short name, or vice versa: retrieve the species code based on common or scientific name.
species_translator( id, codes = NULL, match_by_code = TRUE, match_by_short_name = TRUE, match_by_latin = TRUE, match_by_common = TRUE )species_translator( id, codes = NULL, match_by_code = TRUE, match_by_short_name = TRUE, match_by_latin = TRUE, match_by_common = TRUE )
id |
Your search query term; can be a character or numeric. The function will return partial matches and is case insensitive. |
codes |
A |
match_by_code |
The remaining inputs are a way to toggle on/off certain
methods for searching for matches. This input will try to match your search query
to species codes, e.g., |
match_by_short_name |
Try matching search query to "short name" species codes,
e.g., |
match_by_latin |
Try matching search query to scientific name. |
match_by_common |
Try matching search query to common name. |
A data.frame with all viable patches to your search query.
species_translator('046') # match by species code species_translator('46') # partial matches work species_translator(46) # numeric codes work species_translator('RM_WHA') # partial short names work species_translator('Physeter') # latin names work species_translator('orca') # common names work + partial matches + case insensitive species_translator('orca', match_by_latin=FALSE) # toggle match modesspecies_translator('046') # match by species code species_translator('46') # partial matches work species_translator(46) # numeric codes work species_translator('RM_WHA') # partial short names work species_translator('Physeter') # latin names work species_translator('orca') # common names work + partial matches + case insensitive species_translator('orca', match_by_latin=FALSE) # toggle match modes
This function allows for complex combinations / subtractions of geostratum polygons and calculates the resulting area before and after the removal of dry land. Diagnostic plots are provided that ensure the result is correct.
strata_area( strata_all, strata_keep, strata_remove = NULL, remove_land = TRUE, toplot = TRUE, verbose = TRUE )strata_area( strata_all, strata_keep, strata_remove = NULL, remove_land = TRUE, toplot = TRUE, verbose = TRUE )
strata_all |
A named |
strata_keep |
A character vector of the names of the geostrata
within |
strata_remove |
A character vector of the names of the
geostrata you want to remove. For example,
perhaps you want to keep the |
remove_land |
A Boolean, with default |
toplot |
If |
verbose |
If |
A list with the following slots:
km2 The area of the resulting survey area polygon, in square km.
km2_keep The area of the strata_keep polygons, after combining them to account
for any overlapping portions of the polygons, but before removing land.
km2_remove The area of the strata_remove polygons, if any were provided,
after combining them to account for any overlapping portions of the polygons,
but before removing land.
km2_with_land The area of the resulting survey area polygon before removing land.
sf The sf object of the resulting polygon.
Note that if toplot is TRUE (the default), a diagnostic plot will also be produced.
Strata CCS
strata_ccsstrata_ccs
An object of class list of length 5.
Typical geostrata used in the California Current System region.
Strata CNP
strata_cnpstrata_cnp
An object of class list of length 12.
Typical geostrata used in the Central North Pacific region.
Strata ETP
strata_etpstrata_etp
An object of class list of length 70.
Typical geostrata used in the Eastern Tropical Pacific region.
The LTabundR package comes with several built-in datasets of geographic strata
that are commonly used in NOAA/NMFS surveys. The functions strata_explore()
and strata_select() were developed to help you explore those built-in options.
strata_explore() launches a leaflet map displaying the built-in
geostrata datasets available for your use in the common NOAA/NMFS survey regions.
Each stratum displayed as a separate layer that can be hidden or hovered over to get details.
strata_explore( region, start_at = 1, strata_color = "darkblue", begin_hidden = FALSE )strata_explore( region, start_at = 1, strata_color = "darkblue", begin_hidden = FALSE )
region |
Name of the survey region of interest. Options currently supported:
|
start_at |
A number indicating the geostratum index you wish to begin at, if you know you aren't interested in those early on in the list. For example, the ETP has over 70 built-in geostrata available! |
strata_color |
Color of geostratum. |
|
If |
An interactive leaflet map.
The name of the geostratum, and the numeric identifier for it, are printed
in a legend as well as in a pop-up box that appears when you hover over a stratum.
Use this identifier as an argument in the companion function, strata_select(), to access the datasets of coordinates
underlying the polygons displayed.
A simple diagnostic function, usually not used by most analysts.
strata_segments(cruz, cohort = 1, plot_title = "Stratum assignments")strata_segments(cruz, cohort = 1, plot_title = "Stratum assignments")
cruz |
Your |
cohort |
The cohort whose data you would like to display, provided as a number indicating which slot in |
plot_title |
Optional title for plot. |
A ggplot2 object.
The LTabundR package comes with several built-in datasets of geographic strata
that are commonly used in NOAA/NMFS surveys. The functions strata_explore()
and strata_select() were developed to help you explore those built-in options.
Those built-in datasets come in the form of a list, in which each slot is a
separate geostratum. strata_select() allows you to "grab" the underlying data (i.e., the data.frame
of Lat/Long coordinates) for one of the geostrata displayed by strata_explore().
strata_select(selections, region)strata_select(selections, region)
selections |
Numeric index of the geostratum you wish to "grab" from a
list of geostrata. This index is printed in the legend produced by |
region |
Name of the survey region pertaining to your selection (the same region you passed to |
A data.frame of coordinates for the boundary of a geostratum. You can
pass this object to the strata argument for load_settings().
Stage edits to subgroups (e.g., phase and population assignments)
subgroup_edits( cohort, sgid, exclude = NULL, ObsStd = NULL, phase = NULL, population = NULL, pop_prob = NULL )subgroup_edits( cohort, sgid, exclude = NULL, ObsStd = NULL, phase = NULL, population = NULL, pop_prob = NULL )
cohort |
The cohort whose data will be edited,
provided as the number or name of the slot in |
sgid |
A character vector of subgroup IDs whose data will be edited. |
exclude |
A Boolean vector, with length of either 1 or the same as |
ObsStd |
A Boolean vector, with length of either 1 or the same as |
phase |
A numeric vector, with length of either 1 or the same as |
population |
A character vector, with length of either 1 or the same as |
pop_prob |
A numeric vector, with length of either 1 or the same as |
A list of staged edits that will be accepted by the edits input in process_subgroups().
This is an internal function typically not called by a user directly.
It is called in process_subgroups(), which is an internal function called in process_surveys().
subgroup_events(das, species_filter = "033")subgroup_events(das, species_filter = "033")
das |
A dataframe of |
species_filter |
Species code(s), as a character vector, if you only want subgroup data for certain species. The default is for false killer whales, Pseudorca crassidens, for whom the subgroup data collection protocol was developed (see Bradford et al. 2018. |
A data.frame in which each row is a single school size estimate for a single subgroup within a single phase of a single sighting
(effectively, the 'raw' data for subgroups within the das data).
Simple explorer for subgroups data
subgroup_explorer(cruz, cohort = "pseudorca")subgroup_explorer(cruz, cohort = "pseudorca")
cruz |
Your |
cohort |
The cohort whose data you would like to review, provided as the number or name of the slot in |
A Shiny app to explore subgroup event data for a cohort within a cruz object.
Review & stage edits to subgroup phase assignments
subgroup_phases(cruz, cohort)subgroup_phases(cruz, cohort)
cruz |
Your |
cohort |
The cohort whose subgroup phases you would like to review and stage edits for, provided as either the cohort name (e.g., |
A Shiny app that allows you to make manually stage revisions to the phase assigned to each
subgroup (this is in reference to the protocol developed for false killer whales by NOAA PIFSC). Those
phases were assigned automatically during the process_surveys() routine; this is a way for you
to review those assignments and prepare a set of revisions. When you close the app,
those revisions are returned as a list(), which you can then save to file and/or
pass to LTabundR::subgroup_edit(), which will implement the revisions by modifying the data in your cruz object.
This function, subgroup_phases(), does not edit the cruz object in any form.
Assign subgroups to populations based on polygons
subgroup_populations( populations, cruz, cohort = "pseudorca", default_pop = "pelagic", verbose = TRUE )subgroup_populations( populations, cruz, cohort = "pseudorca", default_pop = "pelagic", verbose = TRUE )
populations |
A named list in which each slot is a |
cruz |
Your |
cohort |
The cohort whose data you would like to use, provided as the number or name of the slot in |
default_pop |
desc |
verbose |
Boolean; print updates to console? |
A data.frame of population assignments for each subgroup event, formatted to be accepted as edits
as an input in process_subgroups().
This is an internal function, not typically called by the user.
It is called during the process_subgroups() routine within process_surveys(),
and may also be called if the user manually edits subgroup phase assignments using the subgroup_phases() function.
It takes the result of the function subgroup_subgroups().
subgroup_sightings(subgroups)subgroup_sightings(subgroups)
subgroups |
The output of |
A data.frame with one row for each phase of each sighting.
This is an internal function, not typically called by the user.
It is called during the process_subgroups() routine within process_surveys(),
and may also be called if the user manually edits subgroup phase assignments using the subgroup_phases() function.
It takes the result of the function subgroup_events().
subgroup_subgroups(events)subgroup_subgroups(events)
events |
The output of |
A data.frame with one row for each subgroup in each phase of a sighting.
Wincruz by Beaufort Sea StateCalulcate the distance and proportion of effort within each Beaufort Sea State
within your Wincruz survey data.
summarize_bft(cruz, use_only = TRUE, cohort = 1)summarize_bft(cruz, use_only = TRUE, cohort = 1)
cruz |
Your |
use_only |
If |
cohort |
The cohort whose data you would like to summarize, provided as a number indicating which slot in |
A list with various summary tables:
overall: Overall summary of effort, parsed by Beaufort sea state, for the entire dataset.
Three columns: Bft, km, prop (the fraction of effort for this sea state).
by_year: Same table as overall, this time parsed by year.
by_cruise: Same table as overall, this time parsed by geostratum.
details: Same table as overall, this time parsed by each unique Cruise-year-stratum combination.
Summarize sighting distances in a table
summarize_distances( distances, distance_range = c(0, 10), distance_interval = 0.5 )summarize_distances( distances, distance_range = c(0, 10), distance_interval = 0.5 )
distances |
Perpendicular distances to sightings, usually in km. |
distance_range |
The range of distances for which to summarize detection distances. |
distance_interval |
The interval of distances to summarize in the table. |
A dataframe with a row for each distance interval, summarizing the number of sightings, etc.
Wincruz survey effortInventory and summarize survey effort within a LTabundR cruz object in various ways.
summarize_effort(cruz, cohort = 1)summarize_effort(cruz, cohort = 1)
cruz |
Your |
cohort |
The cohort whose data you would like to summarize, provided as a number indicating which slot in |
A list with various summary tables:
total: Grand total distance and days surveyed. Two columns: km, days.
total_by_year: Total distance and days surveyed for each year Three columns:
year, km, days.
total_by_cruise: Total distance and days surveyed for each cruise. Four columns:
Cruise, year, km, days.
total_by_effort: Total distance and days surveyed, grouped by segments that will be included in the analysis and those that won't.
Five columns: Cruise, year, use (used for analysis or not), km, and days.
total_by_stratum: Total distances and days surveyed within each stratum, again grouped by segments
that will be included in the analysis and those that won't. Six columns:
Cruise, year, stratum, use, km, days.
Wincruz surveyInventory and summarize sightings within a LTabundR cruz object in various ways.
summarize_sightings(cruz, cohort = 1)summarize_sightings(cruz, cohort = 1)
cruz |
Your |
cohort |
The cohort whose data you would like to map, provided as a number indicating which slot in |
A list with various summary tables. In each table, each row is a count for a single species code.
simple_totals: includes all sightings, even if they will not be included in analysis.
Seven columns:
code (species code), short_name, scientific_name, common_name, n (number of sightings), ss_mean (mean school size), ss_sd (standard devication of school size).
analysis_totals: only includes sightings that meet all inclusion criteria for the analysis.
Same columns as simple_totals.
stratum_simple_totals: inclues all sightings, even if they will not be included in analysis,
parsed by each geostratum. Same columns as simple_totals, with the addition of year, Cruise, and stratum.
stratum_analysis_totals: only includes sightings that meet all inclusion criteria for the analysis,
parsed by each geostratum. Same columns as simple_totals, with the addition of year, Cruise, and stratum.
Summarize sightings for a species (or several)
summarize_species( spp, cruz, cohort = 1, filter_to_regions = NULL, exclude_regions = NULL, distance_restrict = TRUE, distance_range = c(0, 10), distance_interval = 0.5 )summarize_species( spp, cruz, cohort = 1, filter_to_regions = NULL, exclude_regions = NULL, distance_restrict = TRUE, distance_range = c(0, 10), distance_interval = 0.5 )
spp |
A character vector with codes for the species you wish to summarize. |
cruz |
Your |
cohort |
The cohort whose data you would like to map, provided as a number indicating which slot in |
filter_to_regions |
Regions (geostrata) to filter the results down to. Use |
exclude_regions |
Regions (geostrata) to exclude from the results. This can be helpful if, for example, you wish to summarize sightings for a large region but not for regions nested within it, such as insular geostrata. |
distance_restrict |
If |
distance_range |
The range of distances for which to summarize detection distances. |
distance_interval |
The interval of distances to summarize. |
A list with the following named slots:
species: A dataframe with the codes, common names, and scientific name(s) for the specified species (as found in data(species_codes))
n_total: Total number of sightings (mixed-species are only counted once; this is true for all other slots here as well).
n_analysis: Number of sightings that will qualify for inclusion in the analysis (included == TRUE).
school_size: Dataframe with summary metrics of school size for each species.
yearly_total: Dataframe with counts and school sizes metrics for all sightings, parsed by year of sighting.
yearly_analysis: Dataframe with counts and school size metrics for sightings included in the analysis, parsed by year of sighting.
regional_total: Dataframe with counts and school sizes metrics for all sightings, parsed by regional geostratum.
regional_analysis: Dataframe with counts and school size metrics for sightings included in the analysis, parsed by regional geostratum.
detection_distances: A dataframe with sighting counts for various
perpendicular distances (in KM) (systematic sightings only).
The percent_beyond column can be used to identify appropriate truncation distances for this species group.
sightings: Dataframe with all sightings information for this species group.