Package 'sa4all'

Title: Write Stock Assessments for general purposes
Description: Create files and the structure necessary to facilitate rapid and reproducible creation of stock assessment documents from model output generated by Stock Synthesis (SS). The included components and structure are specific to requests from the Pacific Fisheries Management Council for US West Coast groundfish.
Authors: Kelli F. Johnson [aut, cre] (ORCID: <https://orcid.org/0000-0002-5149-451X>), Chantel R. Wetzel [aut] (ORCID: <https://orcid.org/0000-0002-7573-8240>), James N. Ianelli [aut] (Hi!)
Maintainer: Kelli F. Johnson <[email protected]>
License: MIT + file LICENSE
Version: 0.0.0.0002
Built: 2026-05-16 08:21:15 UTC
Source: https://github.com/afsc-assessments/sa4all

Help Index


Read, render, and use a figure from a specific directory.

Description

Concatenate input regarding a specified figure with the caption, alternative caption for accessibility, and reference label.

Usage

add_figure(
  filein,
  caption = "Add figure caption",
  alt_caption = NULL,
  label = "default",
  width = 100,
  height = 100
)

Arguments

filein

The path of the figure to be added (e.g., "C:\My figure directory\plot.png").

caption

A character string providing the figure caption that will be added below the figure in the document. A default text string is provided, but it is not informative and should be changed.

alt_caption

A character string providing alternative text for the figure. The default is NULL, which will force the alternative text to be equal to caption. Note, that the default is not ideal. Instead, alternative text that describes what is going on in the figure should be included.

label

A character string that will be used as the figure reference for citation of figure in the document.

width

A numeric value between 0 and 100 that dictates the figure width in terms of percentage of size. The default is 100.

height

A numeric value between 0 and 100 that dictates the figure height in terms of percentage of size. The default is 100.

Value

cat is used to print output to the screen if you run this function on its own or to a resulting rendered file if called within an .Rmd file, where the latter is more likely.

Author(s)

Chantel R. Wetzel

Examples

## Not run: 

# See below for how to include this function in your .Rmd file.

```{r, results = 'asis'}
add_figure(filein = file.path("My figure directory", "plots", "ts7_Spawning_output.png")
  caption = "Spawning output timeseries.",
  alt_caption = NULL,
  label = "ssb",
  width = 100, height = 100
)
```

## End(Not run)

A data frame of authors and their affiliations

Description

A data frame of potential stock assessment authors and their affiliations.

Details

There are multiple ways to add your name to the list of authors. You could fork the package, add your name to the csv file authors.csv which is located in the data-raw directory, and submit a pull request. You could also just email the package maintainer your name, affiliation, and address. Either option is great. Just remember to follow the steps again when any of your information changes.


Check to make sure index.Rmd contains all current YAML options

Description

As the csasdown package is updated, sometimes new mandatory YAML options are added to the index.Rmd file. Running this function will compare your file to the version built into the currently installed version of csasdown and issue a stop() statement telling you what doesn't match if needed.

Usage

check_yaml(type = "resdoc")

Arguments

type

Type of document. Currently this is only implemented for research documents.


Creates a temporary directory for compiling the latex file with latex commands for a csasdown type

Description

Creates a temporary directory for compiling the latex file with latex commands for a csasdown type

Usage

create_tempdir_for_latex(
  type = NULL,
  where = "r",
  tmp_dir = NULL,
  root_dir = here::here()
)

Arguments

type

The csasdown document type. See draft()

where

Where to look for the tex file. If "r", look in root directory, if "b", look in the _book subdirectory. Any other value will cause an error

tmp_dir

A temporary directory. If NULL, once will be created in the filesystem using tempdir()

root_dir

A directory where everything will be copied from

Details

The compiled tex file will be copied from either the root directory or the _book directory, depending on the value of where. The necessary directories knitr-figs-pdf, knitr-figs-word, knitr-cache-pdf, and knitr-cache-word will be copied recursively into the temporary directory, preserving the directory structure necessary for the build.

Value

The temporary directory's full path

Examples

## Not run: 
root_dir <- getwd()
tmp_dir <- create_tempdir_for_latex("resdoc", "b")
setwd(tmp_dir)
tinytex::latexmk("resdoc.tex")
setwd(root_dir)

## End(Not run)

Internal Code to Build, Load, and Render the sa Template

Description

A non-exported function used by Kelli F. Johnson to build and load sa4all and copy and render the template for a stock assessment document.

Usage

doit(dirgit = "~/_myods/sa4all", authors = c("James N. Ianelli"))

Arguments

dirgit

A file path to where the sa4all repository is cloned.

authors

A vector of author names. For example, "John R. Doe" without first name first. The middle initial or name is optional. Entries must exactly match those used in the "data-raw\authors.csv" file. If you need additional authors added to this file please contact the package maintainers or add them to the .csv file and run the R script also found in that folder prior to submitting a pull request. Following this workflow ensures that the author's address is also added.

Author(s)

Kelli Faye Johnson


Create a sa4all Draft Containing Directories and Files

Description

Create a directory with files needed for a stock assessment document written with sa4all.

Usage

draft(
  authors,
  species = "Walleye pollock",
  latin = "Theragra chalcogrammus",
  coast = "Eastern Bering Sea",
  type = c("sa", "ak"),
  create_dir = FALSE,
  edit = FALSE,
  ...
)

Arguments

authors

A vector of author names. For example, "John R. Doe" without first name first. The middle initial or name is optional. Entries must exactly match those used in the "data-raw\authors.csv" file. If you need additional authors added to this file please contact the package maintainers or add them to the .csv file and run the R script also found in that folder prior to submitting a pull request. Following this workflow ensures that the author's address is also added.

species

A vector of character strings providing species names for all species included in the stock assessment. Typically, there will only be one species, but this template can accommodate a species complex as well. Each species should be capitalized as you would like to see it used in the middle of a sentence. For example, "Pacific Hake" is used in the stock assessment of hake; not "pacific hake" because Pacific Hake is the preferred name, not pacific hake. The text can be called in the document using spp for the form to be used in the middle of a sentence and Spp when placed at the beginning of a sentence.

latin

A character string specifying the Latin name without italic formatting. Please capitalize as you want it to be used in the document though because case will not be altered.

coast

A character string specifying which part of the coast the stock assessment includes. For example, "US West". Do not include "coast" because it will be added internally.

type

The name of the template you want to copy from those available within sa4all. See the function call for available options, where the first listed will be used for the default. "sa" defaults to PFMC outline, "ak" defaults that for the NPFMC SAFE report style.

create_dir

codeFALSE uses the current working directory for the template. TRUE will create a new directory and "default", which is the default of draft(), leaves it up to the package to determine.

edit

A logical value, with a default of FALSE, specifyi tong if you want the main file opened for editing by default. The software chosen by R is normally not ideal and the file isn't one normally edited by users, which is why sa4all doesn't use the default value of draft.

...

Additional arguments that you wish to pass to draft. See args(rmarkdown::draft)

Details

Along with specifying some initial inputs, such as authors and species, this code is a wrapper for draft(). Users should focus on the input arguments that come before type because these will be specific to your stock assessment and are used to set up the initial file structure.

Value

Invisibly returns the file name of the document, which will be the main indexing file that links to the auxiliary files. If edit = TRUE, this file will also be opened for editing.

Author(s)

Kelli Faye Johnson

See Also

See draft.

Examples

## Not run: 
sa4all::draft()

## End(Not run)

Create tex file from executive summary tables

Description

Create tex file from executive summary tables

Usage

es_table_tex(
  dir,
  table_folder = NULL,
  save_loc = NULL,
  csv_name = "table_labels.csv"
)

Arguments

dir

The directory to look for the csv file that has a list of all csv files to create tex files for. The csv file format should match the table_labels.csv created by r4ss function SSexecutivesummary. The columns names in this folder are caption, altcaption, label, filename, and loc (optional). The loc column is a directory location to find the file (filename) that a tex file should be created for. The dir can be set to the mod_loc where the function will automatically look for them inside a table folder in that location.

table_folder

The relative path for the table directory, where it must be relative to dir because it will be appended to this argument using file.path. An alternative is to supply the full file path in dir and use table_folder = "".

save_loc

optional input that requires a full path which will allow users to save the tex file to a specific location (e.g. inside doc folder) other than the file.path(dir, table_folder). Default NULL

csv_name

CSV file name to create tex table scripts for. This file should have the following columns: caption, altcaption, label, filenem, loc (optional) where caption will be the table caption, altcapation is the accessibility text for the table (can be NA if the caption should be used), label is the text to reference the table, filename is the file name of the csv file to be read, and loc (optional) is the location to file the csv file indicated by the filename.

Author(s)

Chantel Wetzel

Examples

## Not run: 
#example of creating tex files for those created by the 
 # r4ss function SSexecutivesummary
	es_table_tex(dir = mod_loc)
#example of using a user created csv file:
es_table_tex(dir = "C:/models/table_to_add_to_doc",
			 save_loc = "C:/model/tex_tables",
			 csv_name = "non_es_document_tables.csv")

## End(Not run)

Get Affiliations for Authors

Description

Get addresses for each author using a look-up function, where addresses are stored internally.

Usage

get_affiliation(authors)

Arguments

authors

A vector of author names. For example, "John R. Doe" without first name first. The middle initial or name is optional. Entries must exactly match those used in the "data-raw\authors.csv" file. If you need additional authors added to this file please contact the package maintainers or add them to the .csv file and run the R script also found in that folder prior to submitting a pull request. Following this workflow ensures that the author's address is also added.

Value

A vector the same length as the input author argument is returned, providing the matching address for each entry as a text string.

Author(s)

Kelli Faye Johnson

Examples

get_affiliation("Kelli F. Johnson")
get_affiliation(c("Kelli F. Johnson", "Chantel R. Wetzel"))
# Returns an NA for the unknown name
testthat::expect_true(is.na(get_affiliation("Kelli Johnson")))

Get Available Rmd Options For A Given Section

Description

Get available options in the sa4all package for a given section. By section, we are referring to a section in the document such as the section on fishery-independent information, which is denoted in the files using s and is part of the Data section, i.e., section 03. See the example for how to get a vector of available survey types.

Usage

get_avail(
  precursor,
  dir = system.file("rmarkdown", "templates", "sa", package = "sa4all")
)

Arguments

precursor

A character string that starts with a two-digit number and is followed by a single alpha character that specifies the type. Specifically, everything before the "-" in the Rmd files that are available in the package.

dir

A file path to the directory of interest. It can be relative or absolute. The default value looks to see the available options in the package folder, but you can change this to be the folder for your stock assessment, which would be helpful if you have added or deleted certain files from the default template.

Value

Returns a vector of character values. The resulting vector is most likely used by other functions in sa4all.

Author(s)

Kelli Faye Johnson

Examples

get_avail(precursor = "11s")

The following script will look for the CSV file plotInfoTable created by r4ss in order to automate some of the plots. The plotInfoTable file is added to the folder each time SS_plots is run (including when you update any of the plots) The most recent version of plotInfoTable with the complete list of plots will be used.

Description

The following script will look for the CSV file plotInfoTable created by r4ss in order to automate some of the plots. The plotInfoTable file is added to the folder each time SS_plots is run (including when you update any of the plots) The most recent version of plotInfoTable with the complete list of plots will be used.

Usage

get_plotinfo(mod_loc, plot_folder = "plots")

Arguments

mod_loc

directory of the model

plot_folder

folder name of the r4ss plots

Author(s)

Melissa Monk & Chantel Wetzel


Read, render, and use a child document

Description

Read a child document, render it based on the file extension, which can be .Rmd, .md, or .tex, and place the resulting text into the main document. Acts as a wrapper for knit_child().

Usage

read_child(filein)

Arguments

filein

A file path for the file that will be read in. Typically, full or relative paths are allowed.

Details

The input file will be knit() quietly using internal code to set quiet = TRUE to supresses the progress bar and messages output from knitr. All R objects will be available in the global environment after the file is rendered. That is, you will be able to inspect all R objects that are created within filein after you attempt to render parent file. This is helpful when you receive and error message or you just want to investigate the structure or results of an object made during the process. For example, if the child document includes the creation of a data frame named test, then you could inspect the data frame after rendering the document, e.g., dim(test).

Child documents are extremely helpful for when you want to share scripts or text across multiple assessments documents, e.g., north and south area models for a given species. In this situation, you could have two folders that store the each store an individual assessment and a third folder that stores text that is common to both documents. Then, you would call this common text within each of the Introduction sections using read_child(file.path("..", "commonintro.Rmd")) inside of an R chunk. See the example section for more details.

Value

cat is used to print output to the screen if you run this function on its own or to a resulting rendered file if called within an .Rmd file, where the latter is more likely.

Author(s)

Chantel R. Wetzel

Examples

## Not run: 

# See below for how to include this function in your .Rmd file.
# Note that the label for the R chunk (e.g., child_firstexample)
# needs to be unique, that is each time you copy and paste this code
# you must change the label to be a new value that isn't used elsewhere.
# This example will look for a file called commonintro.Rmd inside a
# folder called {common_text} that is located
just outside of your current directory.
```{r child_firstexample}
read_child(filein = file.path("..", "common_text", "commonintro.Rmd"))
```

## End(Not run)

Create a sa4all an RData object

Description

Read an SS model output using r4ss to create a RData object with defined quantities to be used when creating an assessment document using sa4all document written with sa4all.

Usage

read_model(
  mod_loc,
  save_loc = NULL,
  plotfolder = "plots",
  printstats = FALSE,
  fecund_mult = "million eggs",
  create_plots = TRUE,
  png = TRUE,
  html = FALSE,
  datplot = TRUE,
  fleetnames = NULL,
  forecastplot = TRUE,
  maxrows = 4,
  maxcols = 4,
  bub_scale = 6,
  create_tables = TRUE,
  ci_value = 0.95,
  es_only = FALSE,
  tables = c("a", "b", "c", "d", "e", "f", "g", "h", "i", "catch", "timeseries",
    "numbers"),
  divide_by_2 = FALSE,
  adopted_ofl = NULL,
  adopted_abc = NULL,
  adopted_acl = NULL,
  forecast_ofl = NULL,
  forecast_abc = NULL,
  ...
)

Arguments

mod_loc

A file path to the directory that houses the Stock Synthesis model that will be used as the base model in this document.

save_loc

optional input that requires a full path which will allow users to save the tex file created from csv files to a specific location (e.g. inside doc folder) other than the file.path(mod_loc, table_folder). Default NULL

plotfolder

location of the r4ss figure directory

printstats

Input to SS_output to prevent output to the screen

fecund_mult

User input to define the multiplier for fecundity in terms of eggs if fecundity is defined in terms of numbers within SS. The default is millions of eggs but there may be instances where the multiplier may be lower or higher, billions or thousands, which can be revised by the user. If the fecundity units in SS are set as biomass then the fecundity units (fecund_unit) will be set as metric tons.

create_plots

TRUE//FALSE to specify whether to create model plots using r4ss

png

TRUE create png plot files

html

create html files

datplot

create the data plots using SS_plots

fleetnames

A vector of user-defined fleet names. If input left as the default value of NULL, then the model-object fleet names will be used.

forecastplot

Add forecast years to figure plost

maxrows

Number of rows for plots. Default set to 4.

maxcols

Number of columns for plots. Default set to 4.

bub_scale

Bubble scale size to use for plotting.

create_tables

TRUE/FALSE to run SSexecutivesummary tables

ci_value

To calculate confidence intervals, default is set at 0.95

es_only

TRUE/FALSE switch to produce only the executive summary tables will be produced, default is FALSE which will return all executive summary tables, historical catches, and numbers-at-ages

tables

Which tables to produce (default is everything). Note: some tables depend on calculations related to previous tables, so will fail if requested on their own (e.g., Table 'f' can't be created without also creating Table 'a')

divide_by_2

This will allow the user to calculate single sex values based on the new sex specification (-1) in SS for single sex models. Default value is FALSE. TRUE will divide by 2.

adopted_ofl

Vector of adopted ofl values to be printed in the mangagement performance table. This should be a vector of 10 values.

adopted_abc

Vector of adopted abc values to be printed in the mangagement performance table. This should be a vector of 10 values.

adopted_acl

Vector of adopted acl values to be printed in the mangagement performance table. This should be a vector of 10 values.

forecast_ofl

Optional input vector for management adopted OFL values for table g. These values will be overwrite the OFL values in the projection table, rather than the model estimated OFL values. Example input: c(1500, 1300)

forecast_abc

Optional input vector for management adopted ABC values for table g. These values will be overwrite the ABC values in the projection table, rather than the model estimated ABC values. Example input: c(1500, 1300)

...

Additional input arguments passed to SS_output for reading output files from Stock Synthesis into a list.

Details

Read an SS model output using r4ss to create a RData object with defined quantities to be used when creating an assessment document using sa4all document written with sa4all.

Author(s)

Chantel Wetzel

Examples

## Not run: 
simplemod_loc <- tail(dir(pattern = "simple",
  system.file("extdata", package = "r4ss"),
  full.names = TRUE), 1)
sa4all::read_model(mod_loc = simplemod_loc,
  fecund_mult = "billion eggs")

## End(Not run)

sa4all: Generate stock assessment pdfs from Stock Synthesis (SS)

Description

The sa4all is designed to facilitate the easy construction of stock assessment documents for species that were modelled with Stock Synthesis (SS), a statistical catch-at-age assessment framework.


Test your installation of sa4all

Description

Test the installation of sa4all to build the template pdf.

Usage

session_test()

Details

sa4all relies on a lot of back-end functionality that typical R packages do not require. Ensuring that these are installed properly is facilitated when you use Rstudio because the developers of Rstudio have put in a lot of work towards making it easy for users to compile documents. sa4all also relies on sed which is available in the tools provided by R, i.e., rtools40, but not always available in your path.

The premise of this function is to store information if the pdf build is not successful that is of use to the developers. If you provide the generic output that is returned to the developers, then they will be able to help you and future individuals like yourself work through installation problems. So, thank you for being willing to help.

Value

A list object is returned with two entries. The first entry, session_info, contains stored information about your work session. The typical output from Sys.getenv is augmented with information pertinent to the sa4all package and compiling accessible pdf documents. The second entry, tried, is the output from tryCatch when attempting to compile the .Rmd files into a pdf using bookdown::render_book. If the function fails to produce a successful pdf, then a utils::bug.report is generated and users are sent to github issues, where they can fill out an issue based on the installation issue template.

Author(s)

Kelli F. Johnson

Examples

localtest <- session_test()

Custom table for sa4all

Description

Custom table for sa4all

Usage

table_format(
  x,
  format = "latex",
  caption = "Add Caption",
  label = NULL,
  digits = getOption("digits"),
  booktabs = TRUE,
  col_names = NULL,
  linesep = "",
  longtable = TRUE,
  font_size = 10,
  align = "c",
  col_names_align = "c",
  hold_position = TRUE,
  escape = TRUE,
  bold_header = FALSE,
  landscape = FALSE,
  repeat_header = FALSE,
  header_grouping = NULL,
  format.args = NULL,
  custom_width = FALSE,
  col_to_adjust = NULL,
  width = NULL,
  create_png = FALSE,
  ...
)

Arguments

x

An R object, typically a matrix or data frame.

format

As defined by kableExtra::kbl(). Default for sa4all is 'latex'.

caption

As defined by kableExtra::kbl().

label

As defined by kableExtra::kbl().

digits

As defined by kableExtra::kbl().

booktabs

As defined by kableExtra::kbl(). Logical.

col_names

Names for the columns to show on table.

linesep

As defined by kableExtra::kbl().

longtable

As defined by kableExtra::kbl().

font_size

Font size in pts. If NULL, document font size is used.

align

As defined by kableExtra::kbl().

col_names_align

As defined in kableExtra::linebreak().

hold_position

As defined in kableExtra::kable_styling(). Logical.

escape

As defined by kableExtra::kable_styling().

bold_header

Make headers bold. Logical

landscape

Make this table in landscape orientation?

repeat_header

If landscape, repeat the header on subsequent pages?

header_grouping

As defined by kableExtra::kable_styling()

format.args

As defined by kableExtra::kbl().

custom_width

Logical. Allow for custom column widths

col_to_adjust

Vector of columns to adjust width. Only used if custom_width = TRUE.

width

Vector or single value of column widths (i.e. c('2cm', '2cm')) for the columns defined in the col_to_adjust.

create_png

Logical. If set to true tables will be created as png objects in the doc.

...

Extra arguments supplied to kbl.

Examples

table_format(head(iris))

Technical report output formatting

Description

Format for creating a technical report with the .pdf extension. This format will be used to generate markdown from R Markdown and a resulting pdf will be saved to the disk.

Usage

techreport_pdf(
  latex_engine = c("lualatex", "pdflatex"),
  pandoc_args = c("--top-level-division=section", "--wrap=none",
    "--default-image-extension=png", "--lua-filter=tagged-filter.lua"),
  ...
)

Arguments

latex_engine

The desired latex engine, where luaLaTex is the default because it leads to a 508 compliant document. This argument is passed to pdf_book. Only a single value can be passed, but all options are listed below.

pandoc_args

Arguments for pandoc. This argument is passed to pdf_book.

...

Additional arguments passed to pdf_book.


Compile Authors Names in YAML Form

Description

Write a file to the disk with all authors and their affiliations using the yaml form for inclusion in the stock assessment.

Usage

write_authors(authors, fileout = "00authors.Rmd")

Arguments

authors

A vector of author names. For example, "John R. Doe" without first name first. The middle initial or name is optional. Entries must exactly match those used in the "data-raw\authors.csv" file. If you need additional authors added to this file please contact the package maintainers or add them to the .csv file and run the R script also found in that folder prior to submitting a pull request. Following this workflow ensures that the author's address is also added.

fileout

A file path for the file that will be saved to the disk. Typically, full or relative paths are allowed.

Author(s)

Kelli Faye Johnson

Examples

# An example with a standard first name middle initial full stop and last name
# then a first initial full stop middle initial full stop and last name and
# last a first name and last name with no middle initial.
eg <- utils::capture.output(
  write_authors(
    c("Kelli F. Johnson", "E. J. Dick", "Qi Lee"),
    fileout = ""
  )
)
## Not run: 
print(eg)

## End(Not run)

Write Summary Files

Description

Write a file to the disk with the title using the yaml form for inclusion in the stock assessment.

Usage

write_summary(type = c("executive", "onepage"), fileout = "01summaries.Rmd")

Arguments

type

A vector of the type of summaries you want included in the stock assessment document. Current options are listed in the default call to write_summary.

fileout

A file path for the file that will be saved to the disk. Typically, full or relative paths are allowed.

Author(s)

Kelli Faye Johnson


Compile Title in YAML format

Description

Write a file to the disk with the title using the yaml form for inclusion in the stock assessment.

Usage

write_title(
  species,
  latin,
  coast,
  year = format(Sys.Date(), "%Y"),
  fileout = "00title.Rmd"
)

Arguments

species

A vector of character strings providing species names for all species included in the stock assessment. Typically, there will only be one species, but this template can accommodate a species complex as well. Each species should be capitalized as you would like to see it used in the middle of a sentence. For example, "Pacific Hake" is used in the stock assessment of hake; not "pacific hake" because Pacific Hake is the preferred name, not pacific hake. The text can be called in the document using spp for the form to be used in the middle of a sentence and Spp when placed at the beginning of a sentence.

latin

A character string specifying the Latin name without italic formatting. Please capitalize as you want it to be used in the document though because case will not be altered.

coast

A character string specifying which part of the coast the stock assessment includes. For example, "US West". Do not include "coast" because it will be added internally.

year

A numeric or character string specifying the year. The default uses Sys.Date() to format the year into a four digit character value.

fileout

A file path for the file that will be saved to the disk. Typically, full or relative paths are allowed.

Details

The Latin name as specified in "latin" argument will be encased in underscores to facilitate it being italicized. Using emph is not allowed because the tagging structure for the creation of the 508 compliant pdf will not render the LaTex code here. Nevertheless, the use of markdown inside the yaml seems to work just fine.

Author(s)

Kelli Faye Johnson