Movatterモバイル変換


[0]ホーム

URL:


Type:Package
Title:R Code for Stock Synthesis
Version:1.44.0
Depends:R (≥ 3.5.0)
Imports:coda, corpcor, dplyr, forcats, ggplot2, lifecycle, stringr,kableExtra
Suggests:gtools, gplots, knitr, maps, pso, testthat, truncnorm,rmarkdown, shiny, flextable, reshape2, ggpubr
Description:A collection of R functions for use with Stock Synthesis, a fisheries stock assessment modeling platform written in ADMB by Dr. Richard D. Methot at the NOAA Northwest Fisheries Science Center. The functions include tools for summarizing and plotting results, manipulating files, visualizing model parameterizations, and various other common stock assessment tasks. This version of '{r4ss}' is compatible with Stock Synthesis versions 3.24 through 3.30 (specifically version 3.30.19.01, from April 2022).
License:GPL-3
Encoding:UTF-8
LazyLoad:yes
URL:https://github.com/r4ss/r4ss
BugReports:https://github.com/r4ss/r4ss/issues
RoxygenNote:7.1.2
NeedsCompilation:no
Packaged:2022-05-25 23:21:14 UTC; Ian.Taylor
Author:Ian G. Taylor [aut, cre], Ian J. Stewart [aut], Allan C. Hicks [aut], Tommy M. Garrison [aut], Andre E. Punt [aut], John R. Wallace [aut], Chantel R. Wetzel [aut], James T. Thorson [aut], Yukio Takeuchi [aut], Kotaro Ono [aut], Cole C. Monnahan [aut], Christine C. Stawitz [aut], Z. Teresa A'mar [aut], Athol R. Whitten [aut], Kelli F. Johnson [aut], Robbie L. Emmet [aut], Sean C. Anderson [aut], Gwladys I. Lambert [aut], Megan M. Stachura [aut], Andrew B. Cooper [aut], Andi Stephens [aut], Neil L. Klaer [aut], Carey R. McGilliard [aut], Iago Mosqueira [aut], Watal M. Iwasaki [aut], Kathryn L. Doering [aut], Andrea M. Havron [aut], Nathan Vaughan [aut], LaTreese S. Denson [aut], Ashleigh J. Novak [aut], Henning Winker [aut], Lee Qi [aut], Megumi Oshima [aut], Eric Fletcher [aut]
Maintainer:Ian G. Taylor <Ian.Taylor@noaa.gov>
Repository:CRAN
Date/Publication:2022-05-26 18:00:02 UTC

r4ss: R Code for Stock Synthesis

Description

A collection of R functions for use with Stock Synthesis, a fisheries stock assessment modeling platform written in ADMB by Dr. Richard D. Methot at the NOAA Northwest Fisheries Science Center. The functions include tools for summarizing and plotting results, manipulating files, visualizing model parameterizations, and various other common stock assessment tasks. This version of 'r4ss' is compatible with Stock Synthesis versions 3.24 through 3.30 (specifically version 3.30.19.01, from April 2022).

Author(s)

Maintainer: Ian G. TaylorIan.Taylor@noaa.gov

Authors:

See Also

Useful links:

Examples

## Not run: # read in the report file using SS_outputmyreplist <- SS_output(dir = "c:/SS/simple/")# make a collection of plots using SS_plotsSS_plots(replist = myreplist)## End(Not run)

Make plots from Rebuilder program

Description

Make a set of plots based on output from Andre Punt's Rebuilder program.

Usage

DoProjectPlots(  dirn = "C:/myfiles/",  fileN = c("res.csv"),  Titles = "",  ncols = 200,  Plots = list(1:25),  Options = list(c(1:9)),  LegLoc = "bottomright",  yearmax = -1,  Outlines = c(2, 2),  OutlineMulti = c(2, 2),  AllTraj = c(1, 2, 3, 4),  AllInd = c(1, 2, 3, 4, 5, 6, 7),  BioType = "Spawning biomass",  CatchUnit = "(mt)",  BioUnit = "(mt)",  BioScalar = 1,  ColorsUsed = "default",  Labels = "default",  pdf = FALSE,  pwidth = 6.5,  pheight = 5,  lwd = 2)

Arguments

dirn

Directory (or vector of directories) where rebuilder outputfiles are stored.

fileN

Vector of filenames containing rebuilder output.Default=c("res.csv").

Titles

Titles for plots when using multiple filenames. Default="".

ncols

Number of columns to read in output file (fileN). Default=200.

Plots

List to get specific plots (currently 1 through 8).Default=list(1:25). If there are multiple files, supply a list of vectors,e.g. list(c(1,5),c(2:5))

Options

List to get specific strategies in the trajectory plots.Default=list(c(1:9)).If there are multiple files, supply a list of vectors,e.g. list(c(1,5),c(2:5))

LegLoc

Location for the legend (for plots with a legend).Default="bottomright".

yearmax

Maximum year to show in the plots. Set negative to show allyears. Default=-1.

Outlines

Number of rows, columns for some of the plots.Default=c(2,2).

OutlineMulti

Number of rows, columns for other plots.Default=c(2,2).

AllTraj

Vector of trajectories to show. Default=c(1,2,3,4).

AllInd

Vector of individual plots to show. Default=c(1,2,3,4,5,6,7).

BioType

Label for biomass type. Default="Spawning biomass".

CatchUnit

Units of catch. Default="(mt)".

BioUnit

Units of biomass. Default="(mt)".

BioScalar

Scalar for biomass plot. Default=1.

ColorsUsed

Optional vector for alternative line colors.Default="default".

Labels

Optional vector for alternative legend labels.Default="default".

pdf

Option to send figures to pdf file instead of plot window inRgui. Default=FALSE.

pwidth

Width of the plot window or PDF file (in inches). Default=7.

pheight

Height of the plot window or PDF file (in inches). Default=7.

lwd

Line width for many of the plot elements. Default=2.

Author(s)

Andre Punt, Ian Taylor

Examples

## Not run: # example with one fileDoProjectPlots(  dirn = "c:/myfiles/", Plots = 1:8,  Options = c(1, 2, 3, 4, 5, 9), LegLoc = "bottomleft")# example with multiple files# Plots - set to get specific plots# Options - set to get specific strategies in the trajectory plotsTitles <- c("Res1", "Res2", "Res3")Plots <- list(c(1:9), c(6:7))Options <- list(c(7:9, 3), c(5, 7))DoProjectPlots(  fileN = c("res1.csv", "res2.csv"), Titles = Titles, Plots = Plots,  Options = Options, LegLoc = "bottomleft", yearmax = -1,  Outlines = c(2, 2), OutlineMulti = c(3, 3), AllTraj = c(1:4),  AllInd = c(1:7), BioType = "Spawning numbers", BioUnit = "(lb)",  BioScalar = 1000, CatchUnit = "(lb)",  ColorsUse = rep(c("red", "blue"), 5),  Labels = c("A", "B", "C", "D", "E", "F"))## End(Not run)

Perform SS implementation of Laplace Approximation

Description

(Attempt to) perform the SS implementation of the Laplace Approximationfrom Thorson, Hicks and Methot (2014) ICES J. Mar. Sci.

Usage

NegLogInt_Fn(  File = NA,  Input_SD_Group_Vec,  CTL_linenum_List,  ESTPAR_num_List,  PAR_num_Vec,  Int_Group_List = list(1),  StartFromPar = TRUE,  Intern = TRUE,  ReDoBiasRamp = FALSE,  BiasRamp_linenum_Vec = NULL,  CTL_linenum_Type = NULL,  systemcmd = FALSE,  exe = "ss")

Arguments

File

Directory containing Stock Synthesis files(e.g., "C:/Users/James Thorson/Desktop/")

Input_SD_Group_Vec

Vector where each element is the standard deviationfor a group of random effects (e.g., a model with a single group of randomeffects will have Input_SD_Group_Vec be a vector of length one)

CTL_linenum_List

List (same length asInput_SD_Group_Vec),where eachelement is a vector giving the line number(s) for the random effect standarddeviation parameter or penalty in the CTL file (and where each line willcorrespond to a 7-parameter or 14-parameter line).

ESTPAR_num_List

List (same length asInput_SD_Group_Vec),where eachelement is a vector giving the parameter number for the random effectcoefficients in that group of random effects. These "parameter numbers"correspond to the number of these parameters in the list of parameters in the".cor" output file.

PAR_num_Vec

Vector giving the number in the ".par" vector for eachrandom effect coefficient.

Int_Group_List

List where each element is a vector, providing a way ofgrouping different random effect groups into a single category. Althoughthis input is still required, it is no has the former input Version has beenhardwired to Version = 1.

StartFromPar

Logical flag (TRUE or FALSE) saying whether to start eachround of optimization from a ".par" file (I recommend TRUE)

Intern

Logical flag saying whether to display all ss3 runtime outputin the R terminal

ReDoBiasRamp

Logical flag saying whether to re-do the bias ramp(usingSS_fitbiasramp()) each time Stock Synthesis is run.

BiasRamp_linenum_Vec

Vector giving the line numbers from the CTL filethat contain the information about the bias ramp.

CTL_linenum_Type

Character vector (same length asInput_SD_Group_Vec),where each element is either "Short_Param", "Long_Penalty", "Long_Penalty".Default is NULL, and if not explicitly specified the program will attempt todetect these automatically based on the length of relevant lines from the CTLfile.

systemcmd

Should R call SS using "system" function instead of "shell".This may be required when running R in Emacs on Windows. Default = FALSE.

exe

SS executable name (excluding extension), either "ss" or "ss3".This string is used for both calling the executable and also finding theoutput files like ss.par. For 3.30, it should always be "ss" since theoutput file names are hardwired in the TPL code.

Author(s)

James Thorson

References

Thorson, J.T., Hicks, A.C., and Methot, R.D. 2014. Randomeffect estimation of time-varying factors in Stock Synthesis. ICES J. Mar.Sci.

See Also

read.admbFit(),getADMBHessian()

Examples

## Not run: # need the full path because wd is changed in functiondirec <- "C:/Models/LaplaceApprox/base"if ("Optimization_record.txt" %in% list.files(direc)) {  file.remove(file.path(direc, "Optimization_record.txt"))}Opt <- optimize(  f = NegLogInt_Fn,  interval = c(0.001, 0.12),  maximum = FALSE,  File = direc,  Input_SD_Group_Vec = 1,  CTL_linenum_List = list(127:131),  ESTPAR_num_List = list(86:205),  Int_Group_List = 1,  PAR_num_Vec = NA,  Intern = TRUE)## End(Not run)

Make plot of likelihood contributions by fleet

Description

This style of plot was officially named a "Piner Plot" at theCAPAM Selectivity Workshop, La Jolla March 2013. This is inhonor of Kevin Piner's contributions to interpreting likelihoodprofiles. He's surely not the first person to make such a plotbut the name seems to have stuck.

Usage

PinerPlot(  summaryoutput,  plot = TRUE,  print = FALSE,  component = "Length_like",  main = "Changes in length-composition likelihoods by fleet",  models = "all",  fleets = "all",  fleetnames = "default",  profile.string = "R0",  profile.label = expression(log(italic(R)[0])),  exact = FALSE,  ylab = "Change in -log-likelihood",  col = "default",  pch = "default",  lty = 1,  lty.total = 1,  lwd = 2,  lwd.total = 3,  cex = 1,  cex.total = 1.5,  xlim = "default",  ymax = "default",  xaxs = "r",  yaxs = "r",  type = "o",  legend = TRUE,  legendloc = "topright",  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1,  plotdir = NULL,  add_cutoff = FALSE,  cutoff_prob = 0.95,  verbose = TRUE,  fleetgroups = NULL,  likelihood_type = "raw_times_lambda",  minfraction = 0.01)

Arguments

summaryoutput

List created by the functionSSsummarize().

plot

Plot to active plot device?

print

Print to PNG files?

component

Which likelihood component to plot. Default is "Length_like".

main

Title for plot. Should match component.

models

Optional subset of the models described insummaryoutput. Either "all" or a vector of numbers indicatingcolumns in summary tables.

fleets

Optional vector of fleet numbers to include.

fleetnames

Optional character vector of names for each fleet.

profile.string

Character string used to find parameter over which theprofile was conducted. Ifexact=FALSE, this can be a substring ofone of the SS parameter labels found in the Report.sso file.For instance, the default input 'R0'matches the parameter 'SR_LN(R0)'. Ifexact=TRUE, thenprofile.string needs to be an exact match to the parameter label.

profile.label

Label for x-axis describing the parameter over whichthe profile was conducted.

exact

Should theprofile.string have to match the parameterlabel exactly, or is a substring OK.

ylab

Label for y-axis. Default is "Change in -log-likelihood".

col

Optional vector of colors for each line.

pch

Optional vector of plot characters for the points.

lty

Line total for the likelihood components.

lty.total

Line type for the total likelihood.

lwd

Line width for the likelihood components.

lwd.total

Line width for the total likelihood.

cex

Character expansion for the points representing the likelihoodcomponents.

cex.total

Character expansion for the points representing the totallikelihood.

xlim

Range for x-axis. Change in likelihood is calculated relative tovalues within this range.

ymax

Maximum y-value. Default is 10\plotted.

xaxs

The style of axis interval calculation to be used for the x-axis(see ?par for more info)

yaxs

The style of axis interval calculation to be used for the y-axis(see ?par for more info).

type

Line type (see ?plot for more info).

legend

Include legend?

legendloc

Location of legend (see ?legend for more info).

pwidth

Width of plot

pheight

Height of plot

punits

Units for PNG file

res

Resolution of plots printed to files.The default isres = 300.

ptsize

Point size for PNG file

cex.main

Character expansion for plot titles

plotdir

Directory where PNG files will be written. by default it willbe the directory where the model was run.

add_cutoff

Add dashed line at ~1.92 to indicate 95% confidence intervalbased on common cutoff of half of chi-squared of p=.95 with 1 degree offreedom:0.5*qchisq(p=cutoff_prob, df=1). The probability valuecan be adjusted using thecutoff_prob below.

cutoff_prob

Probability associated withadd_cutoff above.

verbose

Return updates of function progress to the R GUI? (Doesn't doanything yet.)

fleetgroups

Optional character vector, with length equal tothe number of declared fleets, where fleets with the same value areaggregated

likelihood_type

choice of "raw" or "raw_times_lambda" (the default)determines whether or not likelihoods plotted are adjusted by lambdas(likelihood weights)

minfraction

Minimum change in likelihood (over range considered) as afraction of change in total likelihood for a component to be included in thefigure.

Author(s)

Ian Taylor, Kevin Piner, Jim Thorson

References

Kevin Piner says that he's not the originator of this idea soAthol Whitten is going to add a reference here.


Apply Francis composition weighting method TA1.8 for conditional age-at-length fits

Description

Uses an extension of method TA1.8 (described in Appendix A of Francis, 2011)to do stage-2 weighting of conditional age at length composition data from aStock Synthesis model.

Usage

SSMethod.Cond.TA1.8(  fit,  fleet,  part = 0:2,  seas = NULL,  plotit = TRUE,  printit = FALSE,  datonly = FALSE,  plotadj = !datonly,  maxpanel = 1000,  FullDiagOut = FALSE,  ShowVersionB = FALSE,  fleetnames = NULL,  add = FALSE)

Arguments

fit

Stock Synthesis output as read by r4SS function SS_output

fleet

vector of one or more fleet numbers whose data are tobe analysed simultaneously (the output N multiplier appliesto all fleets combined)

part

vector of one or more partition values; analysis is restrictedto composition data with one of these partition values.Default is to include all partition values (0, 1, 2).

seas

string indicating how to treat data from multiple seasons'comb' - combine seasonal data for each year and plot against Yr'sep' - treat seasons separately, plotting against Yr.SIf is.null(seas) it is assumed that there is only one season inthe selected data (a warning is output if this is not true) andoption 'comb' is used.

plotit

if TRUE, make an illustrative plot like one or morepanels of Fig. 4 in Francis (2011).

printit

if TRUE, print results to R console.

datonly

if TRUE, don't show the model expectations

plotadj

if TRUE, plot the confidence intervals associated withthe adjusted sample sizes (TRUE by default unless datonly = TRUE)

maxpanel

maximum number of panels within a plot

FullDiagOut

Print full diagnostics?

ShowVersionB

Report the Version B value in addition to the default?

fleetnames

Vector of alternative fleet names to draw from forplot titles and captions. It should have length equal to the numberof fleets in the model, not the number of fleets considered in this function.

add

add to existing plot

Details

The function outputs a multiplier,w,(with bootstrap 95% confidence intervals) so thatN2i =w xN1i,whereN1i andN2i are the stage-1 and stage-2 multinomialsample sizes for theith composition. Optionally makes a plotof observed and expected mean ages, with two alternativesets of confidence limits - based onN1i (thin lines) andN2i(thick lines) - for the observed values.

This function formerly reported two versions of w differ according to whetherthe calculated mean ages areindexed by year (version A) or by year and length bin (version B).However, research by Punt (2015) found Version A to perform better andversion B is no longer recommended and is only reported if requested by the user.

CAUTIONARY/EXPLANATORY NOTE. The large number of options available in SS makes itvery difficult to be sure that what this function does is appropriate for allcombinations of options. The following notes (for version A) might help anyonewanting to check or correct the code.

  1. The code first removes unneeded rowsfrom database condbase.

  2. The remaining rows of the database are grouped(indexed by vector indx) and relevant statistics (e.g., observed and expectedmean age), and ancillary data, are calculated for each group (these are storedin pldat - one row per group).

  3. If the data are to be plotted they are furthergrouped by fleet, with one panel of the plot per fleet.

  4. A single multiplier,w, is calculated to apply to all theselected data.

Author(s)

Chris Francis, Andre Punt, Ian Taylor

References

Francis, R.I.C.C. (2011). Data weighting in statisticalfisheries stock assessment models. Can. J. Fish. Aquat. Sci. 68: 1124-1138.

Punt, A.E. (2015). Some insights into data weighting in integrated stock assessments.Fish. Res.

See Also

SSMethod.TA1.8()


Apply Francis composition weighting method TA1.8

Description

Uses method TA1.8 (described in Appendix A of Francis 2011) to dostage-2 weighting of composition data from a Stock Synthesis model.Outputs a multiplier,w (with bootstrap 95% confidence interval),so thatN2y =w xN1y, whereN1y andN2y are the stage-1 and stage-2multinomial sample sizes for the data set in year y. Optionallymakes a plot of observed (with confidence limits, based onN1y)and expected mean lengths (or ages).

CAUTIONARY/EXPLANATORY NOTE.The large number of options available in SS makes it verydifficult to be sure that what this function does isappropriate for all combinations of options. The followingnotes might help anyone wanting to check or correct the code.

  1. The code first takes the appropriate database (lendbase, sizedbase,agedbase, or condbase) and removes unneeded rows.

  2. The remaining rows of the database are grouped into individualcomps (indexed by vector indx) and relevant statistics (e.g.,observed and expected mean length or age), and ancillary data,are calculated for each comp (these are stored in pldat - one rowper comp).If the data are to be plotted, the comps are grouped, with eachgroup corresponding to a panel in the plot, and groups are indexedby plindx.

  3. A single multiplier is calculated to apply to all the comps.

Usage

SSMethod.TA1.8(  fit,  type,  fleet,  part = 0:2,  sexes = 0:3,  seas = NULL,  method = NULL,  plotit = TRUE,  printit = FALSE,  datonly = FALSE,  plotadj = !datonly,  maxpanel = 1000,  fleetnames = NULL,  label.part = TRUE,  label.sex = TRUE,  set.pars = TRUE,  add = FALSE)

Arguments

fit

Stock Synthesis output as read by r4SS function SS_output

type

either 'len' (for length composition data), 'size' (forgeneralized size composition data), 'age' (for age composition data),or 'con' (for conditional age at length data)

fleet

vector of one or more fleet numbers whose data are tobe analysed simultaneously (the output N multiplier appliesto all fleets combined)

part

vector of one or more partition values; analysis is restrictedto composition data with one of these partition values.Default is to include all partition values (0, 1, 2).

sexes

vector of one or more values for Sexes; analysis isrestricted to composition data with one of theseSexes values. Ignored if type=='con'.

seas

string indicating how to treat data from multiple seasons'comb' - combine seasonal data for each year and plot against Yr'sep' - treat seasons separately, plotting against Yr.SIf is.null(seas) it is assumed that there is only one season inthe selected data (a warning is output if this is not true) andoption 'comb' is used.

method

a vector of one or more size-frequency method numbers(ignored unless type = 'size').If !is.null(method), analysis is restricted to size-frequencymethods in this vector. NB comps are separated by method

plotit

if TRUE, make an illustrative plot like one or morepanels of Fig. 4 in Francis (2011).

printit

if TRUE, print results to R console.

datonly

if TRUE, don't show the model expectations

plotadj

if TRUE, plot the confidence intervals associated withthe adjusted sample sizes (TRUE by default unless datonly = TRUE)

maxpanel

maximum number of panels within a plot

fleetnames

Vector of alternative fleet names to draw from forplot titles and captions. It should have length equal to the numberof fleets in the model, not the number of fleets considered in this function.

label.part

Include labels indicating which partitions are included?

label.sex

Include labels indicating which sexes are included?

set.pars

Set the graphical parameters such as mar and mfrow.Can be set to FALSE in order to add plots form multiple calls tothis function as separate panels in one larger figure.

add

add to existing plot

Author(s)

Chris Francis, Andre Punt, Ian Taylor

References

Francis, R.I.C.C. (2011). Data weighting in statisticalfisheries stock assessment models. Canadian Journal ofFisheries and Aquatic Sciences 68: 1124-1138.

See Also

SSMethod.Cond.TA1.8()

Examples

## Not run: Nfleet <- length(myreplist[["FleetNames"]])for (Ifleet in 1:Nfleet) {  SSMethod.TA1.8(myreplist, "len", fleet = Ifleet, maxpanel = maxpanel)}for (Ifleet in 1:Nfleet) {  SSMethod.TA1.8(myreplist, "age", fleet = Ifleet, maxpanel = maxpanel)}for (Ifleet in 1:Nfleet) {  SSMethod.TA1.8(myreplist, "size", fleet = Ifleet, maxpanel = maxpanel)}for (Ifleet in 1:Nfleet) {  SSMethod.TA1.8(myreplist, "con", fleet = Ifleet, maxpanel = maxpanel)}for (Ifleet in 1:Nfleet) {  SSMethod.Cond.TA1.8(myreplist, fleet = Ifleet, maxpanel = maxpanel)}## End(Not run)

Create table of fixed forecast catches

Description

Processing values of dead or retained biomass from timeseries outputto fit the format required at the bottom of the forecast file.This can be used to map the catches resulting from forecasting with a particularharvest control rule into a model representing a different state of nature.This is a common task for US west coast groundfish but might be useful elsewhere.

Usage

SS_ForeCatch(  replist,  yrs = 2021:2032,  average = FALSE,  avg.yrs = 2016:2020,  total = NULL,  digits = 2,  dead = TRUE,  zeros = FALSE)

Arguments

replist

A list object created bySS_output().

yrs

Range of years in which to fill in forecast catches from timeseries

average

Use average catch over a range of years for forecast(as opposed to using forecast based on control rule)

avg.yrs

Range of years to average over

total

Either single value or vector of annual total forecast catchused to scale values (especially if values are from average catches).For west coast groundfish, total might be ACL for next 2 forecast years

digits

Number of digits to round to in table

dead

TRUE/FALSE switch to choose dead catch instead of retained catch.

zeros

Include entries with zero catch (TRUE/FALSE)

Author(s)

Ian G. Taylor

See Also

SS_readforecast(),SS_readforecast()

Examples

  ## Not run:     # create table based on average over past 5 years    SS_ForeCatch(base,                # object created by SS_output                 yrs = 2021:2022,     # years with fixed catch                 average = TRUE,      # catch by fleet from average catch                 avg.yrs = 2014:2018) # use average of catches over past 5 years    # create table with pre-defined totals where the first 2 years    # are based on current harvest specifications and the next 10 are set to some    # new value (with ratio among fleets based on average over past 5 years)    SS_ForeCatch(base,                # object created by SS_output                 yrs = 2021:2022,     # years with fixed catch                 average = TRUE,      # catch by fleet from average catch                 avg.yrs = 2016:2020, # use average of catches over past 5 years                 total = c(rep(241.3, 2), rep(300, 10))) # total    # create table based on harvest control rule projection in SS    # that can be mapped into an alternative state of nature    SS_ForeCatch(low_state,          # object created by SS_output for low state                 yrs=2021:2032,      # forecast period after fixed ACL years                 average=FALSE)      # use values forecast in SS, not historic catch  ## End(Not run)

Iteratively apply the jitter option in SS

Description

Iteratively run a Stock Synthesis model with different jittered startingparameter values based on the jitter fraction. Output files are renamedin the format Report1.sso, Report2.sso, etc.

Usage

SS_RunJitter(  mydir,  model = "ss",  extras = "-nohess",  Njitter,  Intern = TRUE,  systemcmd = FALSE,  printlikes = TRUE,  verbose = FALSE,  jitter_fraction = NULL,  init_values_src = NULL)

Arguments

mydir

Directory where model files are located.

model

Name of the Stock Synthesis model file (which has the .exe foron Windows) inmydir without the extension (if any), e.g.,"ss" or"ss_win".

extras

Additional command line arguments passed to the executable.The default,"-nohess", runs each jittered model without the hessian.

Njitter

Number of jitters, or a vector of jitter iterations.Iflength(Njitter) > 1 only the iterations specified will be ran,else1:Njitter will be executed.

Intern

Show command line info in R console or keep hidden. The default,TRUE, keeps the executable hidden.

systemcmd

Option to switch between 'shell' and 'system'. The default,FALSE, facilitates using the shell command on Windows.

printlikes

A logical value specifying if the likelihood values shouldbe printed to the console.

verbose

A logical value specifying if output should be printedto the screen.

jitter_fraction

The value, typically 0.1, used to define a uniformdistribution in cumulative normal space to generate new initial parameter values.The default ofNULL forces the user to specify the jitter_fractionin the starter file, and this value must be greater than zero andwill not be overwritten.

init_values_src

Either zero or one, specifying if the initial values tojitter should be read from the control file or from the par file, respectively.The default isNULL, which will leave the starter file unchanged.

Value

A vector of likelihoods for each jitter iteration.

Author(s)

James T. Thorson, Kelli F. Johnson, Ian G. Taylor

Examples

## Not run: #### Run jitter from par file with arbitrary, but common, choice of 0.1modeldir <- tail(dir(system.file("extdata", package = "r4ss"), full.names = TRUE), 1)numjitter <- 25jit.likes <- SS_RunJitter(  mydir = modeldir, Njitter = numjitter,  jitter_fraction = 0.1, init_value_src = 1)#### Read in results using other r4ss functions# (note that un-jittered model can be read using keyvec=0:numjitter)profilemodels <- SSgetoutput(dirvec = modeldir, keyvec = 1:numjitter, getcovar = FALSE)# summarize outputprofilesummary <- SSsummarize(profilemodels)# Likelihoodsprofilesummary[["likelihoods"]][1, ]# Parametersprofilesummary[["pars"]]## End(Not run)

Create relative sensitivity plots as described in Cope and Gertseva (2020)

Description

Uses output fromSSsummarize() to make a figure showingsensitivity of various quantities of interest.

Usage

SS_Sensi_plot(  model.summaries,  dir = "",  current.year,  mod.names,  Sensi.RE.out = "Sensi_RE_out.DMP",  CI = 0.95,  TRP.in = 0.4,  LRP.in = 0.25,  sensi_xlab = "Sensitivity scenarios",  ylims.in = c(-1, 2, -1, 2, -1, 2, -1, 2, -1, 2, -1, 2),  plot.figs = c(1, 1, 1, 1, 1, 1),  sensi.type.breaks = NA,  anno.x = NA,  anno.y = NA,  anno.lab = NA,  spawn.lab = NA,  yield.lab = NA,  F.lab = NA)

Arguments

model.summaries

Output fromSSsummarize()summarizing results of models to be included

dir

Directory where plots will be created, either relativeto working directory or an absolute path

current.year

Year to report output

mod.names

List the names of the sensitivity runs

Sensi.RE.out

Saved file of relative changes

CI

Confidence interval box based on the reference model

TRP.in

Target relative abundance value

LRP.in

Limit relative abundance value

sensi_xlab

X-axis label

ylims.in

Y-axis label

plot.figs

Which plots to make/save?

sensi.type.breaks

vertical breaks that can separate out typesof sensitivities

anno.x

Horizontal positioning of the sensitivity types labels

anno.y

Vertical positioning of the sensitivity types labels

anno.lab

Sensitivity types labels

spawn.lab

Label for spawning output or spawning biomass. By defaultit will be set to "SO" if any model has spawning output in numbers and "SB"if all models have spawning output in biomass. Subscripts will be addedfor 0 or current year.

yield.lab

Label for yield reference point.By default it will be set to something like "Yield(SPR=0.3)" where the SPRvalue is the SPR target. If the models have different SPR targets, it willbe set to "Yield(tgt SPR)".

F.lab

Label for F reference point.By default it will be set to something like "F(SPR=0.3)" where the SPRvalue is the SPR target. If the models have different SPR targets, it willbe set to "F(tgt SPR)".

Author(s)

Jason Cope

References

Cope, J. and Gertseva, V. 2020. A new way to visualizeand report structural and data uncertainty in stock assessments.Can. J. Fish. Aquat. Sci. 77:1275-1280.https://doi.org/10.1139/cjfas-2020-0082

See Also

SSsummarize()

Examples

## Not run: # Set directory and extract ouput from models# Model 1 needs to be the Reference model, with sensitivity runs following# from run 2 on.# Note: models are available in Jason Cope's github repository:# https://github.com/shcaba/Stock-Assessment-Sensitivity-Plots/dir <-  "C:/Users/.../GitHub/Stock-Assessment-Sensitivity-Plots/Sensitivity_runs/"models.dirs <- paste0("Cab_SCS_MS_", 1:19)zz <- SSgetoutput(dirvec = file.path(dir, models.dirs))# Use the summarize function in r4ss to get model summariesmodel.summaries <- SSsummarize(zz)# Define the names of each model. This will be used to label runs in the# table and in the figures.mod.names <- c(  "Reference",  "M: Fix to 2009",  "M: Fix to prior",  "M: Fix to Hamel",  "M: Fix to VBGF",  "M: Fix to OR",  "VBGF 2009",  "VBGF Grebel",  "OR maturity",  "Est. h",  "All rec devs",  "No rec devs",  "High bias adj.",  "Harmonic mean",  "Dirichlet",  "Wts = 1",  "No blocks",  "First blocks in 2000",  "Alt rec catches")# Run the sensitivity plot functionSS_Sensi_plot(  model.summaries = model.summaries,  dir = dir,  current.year = 2019,  mod.names = mod.names, # List the names of the sensitivity runs  likelihood.out = c(1, 1, 0),  Sensi.RE.out = "Sensi_RE_out.DMP", # Saved file of relative errors  CI = 0.95, # Confidence interval box based on the reference model  TRP.in = 0.4, # Target relative abundance value  LRP.in = 0.25, # Limit relative abundance value  sensi_xlab = "Sensitivity scenarios", # X-axis label  ylims.in = c(-1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1), # Y-axis label  plot.figs = c(1, 1, 1, 1, 1, 1), # Which plots to make/save?  sensi.type.breaks = c(6.5, 9.5, 13.5, 16.5), # vertical breaks  anno.x = c(3.75, 8, 11.5, 15, 18), # positioning of types labels  anno.y = c(1, 1, 1, 1, 1), # positioning of types labels  anno.lab = c(    "Natural mortality", "VBGF/Mat.", "Recruitment", "Data Wts.",    "Other"  ) # Sensitivity types labels)## End(Not run)

Change parameters, bounds, or phases in the control file.

Description

Loops over a subset of control file to change parameter lines.Current initial value, lower and upper bounds, and phase can be modified,but function could be expanded to control other columns.Depends onSS_parlines().Used bySS_profile() and thess3sim package.

Usage

SS_changepars(  dir = NULL,  ctlfile = "control.ss_new",  newctlfile = "control_modified.ss",  linenums = NULL,  strings = NULL,  newvals = NULL,  repeat.vals = FALSE,  newlos = NULL,  newhis = NULL,  newprior = NULL,  newprsd = NULL,  newprtype = NULL,  estimate = NULL,  verbose = TRUE,  newphs = NULL)

Arguments

dir

Directory with control file to change.

ctlfile

Control file name. Default="control.ss_new".

newctlfile

Name of new control file to be written.Default="control_modified.ss".

linenums

Line numbers of control file to be modified. Either this orthestrings argument are needed. Default=NULL.

strings

Strings (with optional partial matching) indicating whichparameters to be modified. This is an alternative tolinenums.strings correspond to the commented parameter names included incontrol.ss_new, or whatever is written as comment at the endof the 14 number parameter lines. Default=NULL.

newvals

Vector of new parameter values. Default=NULL.The vector can containNA values, which will assign the originalvalue to the given parameter but change the remainder parameters, wherethe vector of values needs to be in the same order as eitherlinenums orstrings.

repeat.vals

If multiple parameter lines match criteria, repeat thenewvals input for each line.

newlos

Vector of new lower bounds. Default=NULL.The vector can containNA values, which will assign the originalvalue to the given parameter but change the remainder parameters, wherethe vector of values needs to be in the same order as eitherlinenums orstrings.

newhis

Vector of new high bounds. Must be the same length as newhisDefault=NULL.The vector can containNA values, which will assign the originalvalue to the given parameter but change the remainder parameters, wherethe vector of values needs to be in the same order as eitherlinenums orstrings.

newprior

Vector of new prior values.Default=NULL.The vector can containNA values, which will assign the originalvalue to the given parameter but change the remainder parameters, wherethe vector of values needs to be in the same order as eitherlinenums orstrings.

newprsd

Vector of new prior sd values.Default=NULL.The vector can containNA values, which will assign the originalvalue to the given parameter but change the remainder parameters, wherethe vector of values needs to be in the same order as eitherlinenums orstrings.

newprtype

Vector of new prior type.Default=NULL.The vector can containNA values, which will assign the originalvalue to the given parameter but change the remainder parameters, wherethe vector of values needs to be in the same order as eitherlinenums orstrings.

estimate

Optional vector or single value of TRUE/FALSE for whichparameters are to be estimated. Changes sign of phase to be positive ornegative. DefaultNULL causes no change to phase.

verbose

More detailed output to command line. Default=TRUE.

newphs

Vector of new phases. Can be a single value, which will berepeated for each parameter, the same length as newvals, where eachvalue corresponds to a single parameter, orNULL, where thephases will not be changed. If one wants to strictly turn parameterson or off and not change the phase in which they are estimated useestimate = TRUE orestimate = FALSE, respectively.The vector can containNA values, which will assign the originalvalue to the given parameter but change the remaining parameters, wherethe vector of values needs to be in the same order as eitherlinenums orstrings.

Author(s)

Ian Taylor, Christine Stawitz, Chantel Wetzel

See Also

SS_parlines(),SS_profile()

Examples

## Not run: SS_changepars(  dir = "C:/ss/SSv3.30.03.05_May11/Simple - Copy",  strings = c("steep", "sigmaR"), newvals = c(.4, .6))## parameter names in control file matching input vector 'strings' (n=2):## [1] "SR_BH_steep" "SR_sigmaR"## These are the ctl file lines as they currently exist:##     LO HI     INIT PRIOR PR_type SD PHASE env_var&link dev_link dev_minyr dev_maxyr## 95 0.2  1 0.613717   0.7    0.05  1     4       0       0         0         0## 96 0.0  2 0.600000   0.8    0.80  0    -4       0       0         0         0##        dev_PH Block Block_Fxn       Label Linenum## 95          0     0         0 SR_BH_steep      95## 96          0     0         0   SR_sigmaR      96## line numbers in control file (n=2):## [1] 95 96#### wrote new file to control_modified.ss with the following changes:##    oldvals newvals oldphase newphase oldlos newlos oldhis newhis       comment## 1 0.613717     0.4        4       -4    0.2    0.2      1      1 # SR_BH_steep## 2 0.600000     0.6       -4       -4    0.0    0.0      2      2   # SR_sigmaR## End(Not run)

Extract total catch, spawning output, and fraction unfished from forecast years

Description

Values of total catch, spawning output, and fraction unfished are extractedfrom the forecast years of a time series table for inclusion in a decision table.

Usage

SS_decision_table_stuff(replist, yrs = 2021:2032, digits = c(0, 0, 3))

Arguments

replist

A list object created bySS_output().

yrs

Range of years from which to extract values

digits

Vector of number of digits to round to in table for

  • 1 catch

  • 2 spawning output

  • 3 fraction unfished (column is called "depl")

Author(s)

Ian G. Taylor

See Also

SS_ForeCatch()


Run retrospective analyses

Description

Do retrospective analyses by creating new directories, copying model files,and iteratively changing the starter file to set the number of years of datato exclude. Note that there was a bug for retrospectives in 3.30.01;the user should update their model to a newer version of Stock Synthesis torun retrospectives

Usage

SS_doRetro(  masterdir,  oldsubdir,  newsubdir = "retrospectives",  subdirstart = "retro",  years = 0:-5,  overwrite = TRUE,  exefile = "ss",  extras = "-nox",  intern = FALSE,  CallType = "system",  RemoveBlocks = FALSE)

Arguments

masterdir

Directory where everything takes place.

oldsubdir

Subdirectory withinmasterdir with existing modelfiles.

newsubdir

Subdirectory withinmasterdir where retrospectiveswill be run. Default is 'retrospectives'.

subdirstart

First part of the pattern of names for the directories inwhich the models will actually be run.

years

Vector of values to iteratively enter into the starter file forretrospective year. Should be zero or negative values.

overwrite

Overwrite any input files with matching names in thesubdirectories where models will be run.

exefile

Executable file found in directory with model files.On Windows systems, this value will be automatically updated if a singleexecutable exists in the directory of model files. Input exefile=NULL ifthe executable is in your path and doesn't need copying.

extras

Additional commands to use when running SS. Default = "-nox"will reduce the amount of command-line output.

intern

Display runtime information from SS in the R console (vs.saving to a file).

CallType

Either "system" or "shell" (choice depends on how you're runningR. Default is "system".

RemoveBlocks

Logical switch determining whether specifications ofblocks is removed from top of control file. Blocks can cause problems forretrospective analyses, but the method for removing them is overlysimplistic and probably won't work in most cases. Default=FALSE.

Author(s)

Ian Taylor, Jim Thorson

See Also

SSgetoutput()

Examples

## Not run: # note: don't run this in your main directory--make a copy in case something# goes wrongmydir <- "C:/Simple"## retrospective analysesSS_doRetro(  masterdir = mydir,  oldsubdir = "",  newsubdir = "retrospectives",  years = 0:-5)retroModels <- SSgetoutput(  dirvec = file.path(mydir, "retrospectives", paste("retro", 0:-5, sep = "")))retroSummary <- SSsummarize(retroModels)endyrvec <- retroSummary[["endyrs"]] + 0:-5SSplotComparisons(retroSummary,  endyrvec = endyrvec,  legendlabels = paste("Data", 0:-5, "years"))## End(Not run)

Estimate bias adjustment for recruitment deviates

Description

Uses standard error of estimated recruitment deviates to estimate the 5controls (Methot and Taylor, 2011)for bias adjustment in Stock Synthesis.

Usage

SS_fitbiasramp(  replist,  verbose = FALSE,  startvalues = NULL,  method = "BFGS",  twoplots = TRUE,  transform = FALSE,  plot = TRUE,  print = FALSE,  plotdir = "default",  shownew = TRUE,  oldctl = NULL,  newctl = NULL,  altmethod = "nlminb",  exclude_forecast = FALSE,  pwidth = 6.5,  pheight = 5,  punits = "in",  ptsize = 10,  res = 300,  cex.main = 1)

Arguments

replist

A list object created bySS_output().

verbose

Controls the amount of output to the screen. Default=FALSE.

startvalues

A vector of 5 values for the starting points in theminimization. Default=NULL.

method

A method to apply to the 'optim' function. See ?optim foroptions. Default="BFGS". By default, optim is not used, and the optimizationis based on the inputaltmethod.

twoplots

Make a two-panel plot showing devs as well as transformeduncertainty, or just the second panel in the set? Default=TRUE.

transform

An experimental option to treat the transform the 5quantities to improve minimization. Doesn't work well. Default=FALSE.

plot

Plot to active plot device?

print

Print to PNG files?

plotdir

Directory where PNG files will be written. By default it willbe the directory where the model was run.

shownew

Include new estimated bias adjustment values on top of valuesused in the model? (TRUE/FALSE)

oldctl

Optional name of existing control file to modify.Default=NULL.

newctl

Optional name of new control file to create from old file withestimated bias adjustment values. Default=NULL.

altmethod

Optimization tool to use in place of optim, either "nlminb"or "psoptim". If not equal to either of these, then optim is used.

exclude_forecast

Exclude forecast values in the estimation ofalternative bias adjustment inputs?

pwidth

Default width of plots printed to files in units ofpunits. The default ispwidth=6.5.

pheight

Height of plots printed to png files in units ofpunits.Default is designed to allow two plots per page, withpheight_tall usedfor plots that work best with a taller format and a single plot per page.

punits

Units forpwidth andpheight. Can be "px"(pixels), "in" (inches), "cm" (centimeters), or "mm" (millimeters).The default ispunits="in".

ptsize

Point size for plotted text in plots printed to files (seehelp("png") in R for details).

res

Resolution of plots printed to files.The default isres = 300.

cex.main

Character expansion for plot titles.The default iscex.main=1.

Details

Implementation of the bias adjustment ramp within Stock Synthesis increasesthe likelihood that the estimated recruitment events, which arelog-normally distributed, are mean unbiased and comparable to results fromMarkov chain Monte Carlo estimation routines(Methot and Taylor, 2011).Options to account for the fact that data typically do not equally representall modelled time periods are as follows:

  1. fix the bias adjustment parameters at best-guess values informed by a previousassessment or model run;

  2. fix values based on data availability, such that the start of the ramp alignswith the availability of composition data, the ramp down begins the last yearthose data are informative about recruitment, and the adjustment level isinformed by life history;

  3. set the adjustment level to 1.0 for all years to mimic how it was handledit Stock Synthesis prior to 2009; or

  4. set the adjustment level to 0.0 for all years, but this last option isnot recommended because it will lead to biased results.

Author(s)

Ian Taylor

References

Methot, R.D. and Taylor, I.G., 2011.Adjusting for bias due to variability of estimated recruitments in fishery assessment models.Can. J. Fish. Aquat. Sci., 68:1744-1760.

See Also

SS_output()


Create HTML files to view figures in browser.

Description

Writes a set of HTML files with tabbed navigation between them. Depends onSS_plots() with settings in place to write figures to PNG files.Should open main file in default browser automatically.

Usage

SS_html(  replist = NULL,  plotdir = NULL,  plotInfoTable = NULL,  title = "SS Output",  width = 500,  openfile = TRUE,  multimodel = FALSE,  filenotes = NULL,  verbose = TRUE)

Arguments

replist

A list object created bySS_output().

plotdir

Directory where PNG files are located.

plotInfoTable

CSV file with info on PNG files. By default, theplotdir directory will be searched for files with name beginning'plotInfoTable*'

title

Title for HTML page.

width

Width of plots (in pixels).

openfile

Automatically open index.html in default browser?

multimodel

Override errors associated with plots from multiple modelruns. Only do this if you know what you're doing.

filenotes

Add additional notes to home page.

verbose

Display more info while running this function?

Note

By default, this function will look in the directory where PNG fileswere created for CSV files with the name 'plotInfoTable...' written by'SS_plots. HTML files are written to link to these plots and put in the samedirectory. Please provide feedback on any bugs, annoyances, or suggestionsfor improvement.

Author(s)

Ian Taylor

See Also

SS_plots(),SS_output()


Make html diagnostic tables

Description

Creates html tables that show diagnostic outputs, including status checks, gradients, and correlations.

Usage

SS_makeHTMLdiagnostictable(replist, plotdir = NULL, gradmax = 0.001)

Arguments

replist

A list object created bySS_output().

plotdir

Directory where the text files containing the tables will be written.By default it will be the directory where the model was run.

gradmax

the largest gradient value for estimated parameter; the default is 1E-3

Value

a three-element vector; the first element is the name of the html table file, the second is the table caption, and the third is the category of output type

Author(s)

Christine Stawitz

See Also

SS_plots(),SS_output(),SS_html()


A function to create a list object for the output from Stock Synthesis

Description

Reads the Report.sso and (optionally) the covar.sso, CompReport.sso andother files produced by Stock Synthesis and formats the importantcontent of these files into a list in the R workspace. A few statisticsunavailable elsewhere are taken from the .par and .cor files. Summaryinformation and statistics can be returned to the R console or justcontained within the list produced by this function.

Usage

SS_output(  dir = "C:/myfiles/mymodels/myrun/",  dir.mcmc = NULL,  repfile = "Report.sso",  compfile = "CompReport.sso",  covarfile = "covar.sso",  forefile = "Forecast-report.sso",  wtfile = "wtatage.ss_new",  warnfile = "warning.sso",  ncols = NULL,  forecast = TRUE,  warn = TRUE,  covar = TRUE,  readwt = TRUE,  checkcor = TRUE,  cormax = 0.95,  cormin = 0.01,  printhighcor = 10,  printlowcor = 10,  verbose = TRUE,  printstats = TRUE,  hidewarn = FALSE,  NoCompOK = TRUE,  aalmaxbinrange = 4)

Arguments

dir

Directory containing the Stock Synthesis model output.Forward slashes or double backslashes and quotes are necessary.This can also either be an absolute path or relative to the workingdirectory.

dir.mcmc

Optional directory containing MCMC output. This can either berelative todir, such thatfile.path(dir, dir.mcmc)will end up in the right place, or an absolute path.

repfile

Name of the big report file (could be renamed by user).

compfile

Name of the composition report file.

covarfile

Name of the covariance output file.

forefile

Name of the forecast file.

wtfile

Name of the file containing weight at age data.

warnfile

Name of the file containing warnings.

ncols

The maximum number of columns in files being read in. If thisvalue is too big the function runs more slowly, too small and errors willoccur. A warning will be output to the R command line if the value is toosmall. It should be bigger than the maximum age + 10 and the number ofyears + 10. The default value isNULL, which finds the optimum width.

forecast

Read the forecast-report file?

warn

Read the Warning.sso file?

covar

Read covar.sso to get variance information and identify badcorrelations?

readwt

Read the weight-at-age file?

checkcor

Check for bad correlations?

cormax

The specified threshold for defining high correlations. Aquantity with any correlation above this value is identified.

cormin

The specified threshold for defining low correlations. Onlyquantities with all correlations below this value are identified (to findvariables that appear too independent from the model results).

printhighcor

The maximum number of high correlations to print to theR GUI.

printlowcor

The maximum number of low correlations to print to the RGUI.

verbose

A logical value specifying if output should be printedto the screen.

printstats

Print summary statistics about the output to the R GUI?

hidewarn

Hides some warnings output from the R GUI.

NoCompOK

Allow the function to work without a CompReport file.

aalmaxbinrange

The largest length bin range allowed for compositiondata to be considered as conditional age-at-length data.

Value

Many values are returned. Complete list would be quite long, butshould probably be created at some point in the future.

Author(s)

Ian Stewart, Ian Taylor

See Also

SS_plots()

Examples

## Not run: # read model outputmyreplist <- SS_output(dir = "c:/SS/Simple/")# make a bunch of plotsSS_plots(myreplist)# read model output and also read MCMC results (if run), which in# this case would be stored in c:/SS/Simple/mcmc/myreplist <- SS_output(dir = "c:/SS/Simple/", dir.mcmc = "mcmc")## End(Not run)

Get parameter lines from Stock Synthesis control file

Description

A simple function which takes as input the full path and filename of acontrol file for input to Stock Synthesis. Ideally, a Control.SS_New filewill be used, so that it represents what SS thinks the inputs are, and notwhat the user thinks the inputs are.

Usage

SS_parlines(  ctlfile = "control.ss_new",  dir = NULL,  version = "3.30",  verbose = TRUE,  active = FALSE)

Arguments

ctlfile

File name of control file including path.

dir

Alternative input of path, where file is assumed to be"control.ss_new". Default=NULL.

version

SS version number. Currently only "3.24" or "3.30" are supported,either as character or numeric values (noting that numeric 3.30 = 3.3).

verbose

TRUE/FALSE switch for amount of detail produced by function.Default=TRUE.

active

Should only active parameters (those with positive phase) beoutput? Default=FALSE.

Details

It returns a table which should contain one line for each parameter in themodel. Currently, only the first 7 values are returned, because allparameters have those values. In the future, extended parameter lines couldbe returned.

Parameter lines are identified as those which have 7 or 14 numeric elementsfollowed by a non-numeric element. It's possible that this system couldbreak down under certain circumstances

Author(s)

Ian Taylor

See Also

SS_changepars(),SS_readctl(),SS_readctl_3.24()

Examples

## Not run: parlines <- SS_parlines(ctlfile = "c:/ss/Simple/Control.SS_New")head(parlines)#       LO    HI     INIT PRIOR PR_type   SD PHASE              Label Line_num# 42  0.05  0.15  0.10000  0.10       0  0.8    -3  NatM_p_1_Fem_GP_1       42# 43  0.05  0.15  0.10000  0.10       0  0.8    -3  NatM_p_2_Fem_GP_1       43# 44  1.00 45.00 32.28100 36.00       0 10.0     2 L_at_Amin_Fem_GP_1       44# 45 40.00 90.00 71.34260 70.00       0 10.0     4 L_at_Amax_Fem_GP_1       45# 46  0.05  0.25  0.15199  0.15       0  0.8     4 VonBert_K_Fem_GP_1       46# 47  0.05  0.25  0.10000  0.10       0  0.8    -3  CV_young_Fem_GP_1       47## End(Not run)

plot many quantities related to output from Stock Synthesis

Description

Creates a user-chosen set of plots, including biological quantities, timeseries, and fits to data. Plots are sent to R GUI, single PDF file, ormultiple PNG files. This is now just a wrapper which calls on separatefunctions to make all the plots.

Usage

SS_plots(  replist = NULL,  plot = 1:26,  print = NULL,  pdf = FALSE,  png = TRUE,  html = png,  printfolder = "plots",  dir = "default",  fleets = "all",  areas = "all",  fleetnames = "default",  fleetcols = "default",  fleetlty = 1,  fleetpch = 1,  lwd = 1,  areacols = "default",  areanames = "default",  verbose = TRUE,  uncertainty = TRUE,  forecastplot = FALSE,  datplot = TRUE,  Natageplot = TRUE,  samplesizeplots = TRUE,  compresidplots = TRUE,  comp.yupper = 0.4,  sprtarg = "default",  btarg = "default",  minbthresh = "default",  pntscalar = NULL,  bub.scale.pearson = 1.5,  bub.scale.dat = 3,  pntscalar.nums = 2.6,  pntscalar.tags = 2.6,  minnbubble = 8,  aalyear = -1,  aalbin = -1,  aalresids = TRUE,  maxneff = 5000,  cohortlines = c(),  smooth = TRUE,  showsampsize = TRUE,  showeffN = TRUE,  sampsizeline = FALSE,  effNline = FALSE,  showlegend = TRUE,  pwidth = 6.5,  pheight = 4,  pheight_tall = 6.5,  punits = "in",  ptsize = 10,  res = 300,  mainTitle = FALSE,  cex.main = 1,  selexlines = 1:6,  rows = 1,  cols = 1,  maxrows = 6,  maxcols = 4,  maxrows2 = 4,  maxcols2 = 4,  andrerows = 4,  tagrows = 3,  tagcols = 3,  parrows = 4,  parcols = 2,  fixdims = TRUE,  new = TRUE,  SSplotDatMargin = 8,  filenotes = NULL,  catchasnumbers = NULL,  catchbars = TRUE,  legendloc = "topleft",  minyr = -Inf,  maxyr = Inf,  sexes = "all",  scalebins = FALSE,  scalebubbles = FALSE,  tslabels = NULL,  catlabels = NULL,  maxsize = 1,  showmle = TRUE,  showpost = TRUE,  showprior = TRUE,  showinit = TRUE,  showdev = FALSE,  fitrange = FALSE,  ...)

Arguments

replist

A list object created bySS_output().

plot

Plot sets to be created, see list of plots below. Use tospecify only those plot sets of interest, e.g., c(1,2,5,10). Plots for datanot available in the model run will automatically be skipped, whether calledor not.Current grouping of plots is as follows:

  1. Biology

  2. Selectivity and retention

  3. Timeseries

  4. Recruitment deviations

  5. Recruitment bias adjustment

  6. Spawner-recruit

  7. Catch

  8. SPR

  9. Discards

  10. Mean weight

  11. Indices

  12. Numbers at age

  13. Length comp data

  14. Age comp data

  15. Conditional age-at-length data

  16. Length comp fits

  17. Age comp fits

  18. Conditional age-at-length fits

  19. Francis and Punt conditional age-at-length comp fits

  20. Mean length-at-age and mean weight-at-age

  21. Tags

  22. Yield

  23. Movement

  24. Data range

  25. Parameter distributions

  26. Diagnostic tables

print

Deprecated input for backward compatibility, now replaced bypng = TRUE/FALSE.

pdf

Send plots to PDF file instead of R GUI?

png

Send plots to PNG files instead of R GUI?

html

RunSS_html() on completion? By default has samevalue aspng.

printfolder

The sub-directory under 'dir' (see below) in which thePNG files will be located. The default sub-directory is "plots".The directory will be created if it doesn\'t exist.If 'printfolder' is set to "", it is ignored and the PNG files will be locatedin the directory specified by 'dir'.

dir

The directory in which a PDF file (if requested) will be createdand within which the printfolder sub-directory (see above) will be createdif png=TRUE. By default it will be the same directory that the report filewas read from by theSS_output function. Alternatives to the defaultcan be either relative (to the working directory) or absolute paths.The function will attempt to create the directory it doesn't exist, but itdoes not do so recursively.

fleets

Either the string "all", or a vector of numerical values, likec(1,3), listing fleets or surveys for which plots should be made. Bydefault, plots will be made for all fleets and surveys. Default="all".

areas

Either the string "all", or a vector of numerical values, likec(1,3), listing areas for which plots should be made in a multi-area model.By default, plots will be made for all areas (excepting cases where thefunction has not yet been updated for multi-area models). Default="all".

fleetnames

Either the string "default", or a vector of charactersstrings to use for each fleet name. Default="default".

fleetcols

Either the string "default", or a vector of colors to usefor each fleet. Default="default".

fleetlty

Vector of line types used for each fleet in some plots.Default=1.

fleetpch

Vector of point types used for each fleet in some plots.Default=1.

lwd

Line width for some plots. Default=1.

areacols

Either the string "default", or a vector of colors to usefor each area. Default="default".

areanames

Optional vector of names for each area used in titles.Default="default".

verbose

Return updates of function progress to the R GUI?Default=TRUE.

uncertainty

Include values in plots showing estimates of uncertainty(requires positive definite hessian in model? Default=TRUE.

forecastplot

Include forecast years in the timeseries plots andplots of time-varying quantities?

datplot

Plot the data by itself? This is useful in documentpreparation, but doesn't change across alternative model runs with the samedata, so can be committed to save time once the plots have been created once.Setting datplot=FALSE is equivalent to leaving off plots 15 and 16.Default=TRUE.

Natageplot

Plot the expected numbers at age bubble plots and mean-agetime series? Default=TRUE.

samplesizeplots

Show sample size plots? Default=TRUE.

compresidplots

Show residuals for composition plots?

comp.yupper

Upper limit on ymax for polygon/histogram compositionplots. This avoids scaling all plots to have max=1 if there is a vectorwith only a single observed fish in it. Default=0.4.

sprtarg

Specify the F/SPR proxy target. Default=0.4.

btarg

Target %unfished to be used in plots showing %unfished. May beomitted by setting to NA.

minbthresh

Threshold depletion to be used in plots showing depletion.May be omitted by setting to NA.

pntscalar

This scalar defines the maximum bubble size for bubbleplots. This option is still available but a better choice is to usebub.scale.pearson and bub.scale.dat, which are allow the same scalingthroughout all plots.

bub.scale.pearson

Character expansion (cex) value for a proportion of1.0 in bubble plot of Pearson residuals. Default=1.5.

bub.scale.dat

Character expansion (cex) value for a proportion of 1.0in bubble plot of composition data. Default=3.

pntscalar.nums

This scalar defines the maximum bubble size fornumbers-at-age and numbers-at-length plots.

pntscalar.tags

This scalar defines the maximum bubble size fortagging plots.

minnbubble

This defines the minimum number of years below which blankyears will be added to bubble plots to avoid cropping. Default=8.

aalyear

Years to plot multi-panel conditional age-at-length fits forall length bins; must be in a "c(YYYY,YYYY)" format. Useful for checking thefit of a dominant year class, critical time period, etc. Default=-1.

aalbin

The length bin for which multi-panel plots of the fit toconditional age-at-length data will be produced for all years. Useful tosee if growth curves are ok, or to see the information on year classes movethrough the conditional data. Default=-1.

aalresids

Plot the full set of conditional age-at-length Pearsonresiduals? Turn to FALSE if plots are taking too long and you don't wantthem.

maxneff

The maximum value to include on plots of input and effectivesample size. Occasionally a calculation of effective N blows up to verylarge numbers, rendering it impossible to observe the relationship for otherdata. Default=5000.

cohortlines

Optional vector of birth years for cohorts for which toadd growth curves to numbers at length bubble plots. Default=c().

smooth

Add loess smoother to observed vs. expected index plots andinput vs. effective sample size? Default=TRUE.

showsampsize

Display sample sizes on composition plots? Default=TRUE.

showeffN

Display effective sample sizes on composition plots?Default=TRUE.

sampsizeline

show line for input sample sizes on top of conditionalage-at-length plots (TRUE/FALSE, still in development)

effNline

show line for effective sample sizes on top of conditionalage-at-length plots (TRUE/FALSE, still in development)

showlegend

Display legends in various plots?

pwidth

Default width of plots printed to files in units ofpunits. The default ispwidth=6.5.

pheight

Height of plots printed to png files in units ofpunits.Default is designed to allow two plots per page, withpheight_tall usedfor plots that work best with a taller format and a single plot per page.

pheight_tall

Height of tall plots printed to png files in units ofpunits, where the tall plots are a subset of the plots which typicallywork best in a taller format.

punits

Units forpwidth andpheight. Can be "px"(pixels), "in" (inches), "cm" (centimeters), or "mm" (millimeters).The default ispunits="in".

ptsize

Point size for plotted text in plots printed to files (seehelp("png") in R for details).

res

Resolution of plots printed to files.The default isres = 300.

mainTitle

Logical indicating if a title should be included at the top(not yet implemented for all plots)

cex.main

Character expansion parameter for plot titles (not yetimplemented for all plots). Default=1.

selexlines

Vector controlling which lines should be shown onselectivity plots if the model includes retention. Default=1:5.

rows

Number of rows to use for single panel plots. Default=1.

cols

Number of columns to use for single panel plots. Default=1.

maxrows

Maximum number of rows to for multi-panel plots.

maxcols

Maximum number of columns for multi-panel plots.

maxrows2

Maximum number of rows for conditional age-at-lengthmulti-panel plots.

maxcols2

Maximum number of rows for conditional age-at-lengthmulti-panel plots.

andrerows

Number of rows of Andre's conditional age-at-length plotswithin each page.

tagrows

Number of rows for tagging-related plots.

tagcols

Number of columns for tagging-related plots.

parrows

Number of rows for parameter distribution plots.

parcols

Number of columns for parameter distribution plots.

fixdims

Control whether multi-panel plots all have dimensions equalto maxrows by maxcols, or resized within those limits to fit number ofplots. Default=TRUE.

new

Open a new window or add to existing plot windows. Default=TRUE.

SSplotDatMargin

Size of right-hand margin in data plot (may be toosmall if fleet names are long)

filenotes

Optional vector of character strings to be added to introHTML page (if created) with notes about the model.

catchasnumbers

Is catch input in numbers instead of biomass?Default=F.

catchbars

show catch by fleet as barplot instead of stacked polygons(default=TRUE)

legendloc

Location for all legends. Default="topleft".

minyr

First year to show in time-series and time-varying plots

maxyr

Last year to show in time-series and time-varying plots. Thiscan either be an alternative to, or redundant with, the forecastplot input.

sexes

Which sexes to show in composition plots. Default="all".

scalebins

Rescale expected and observed proportions in compositionplots by dividing by bin width for models where bins have different widths?Caution!: May not work correctly in all cases.

scalebubbles

scale data-only bubbles by sample size, not justproportion within sample? Default=FALSE.

tslabels

Either NULL to have default labels for timeseries plots ora vector of appropriate length (currently 11) with labels for each figure

catlabels

Either NULL to have default labels for catch plots ora vector of appropriate length (currently 10) with labels for each figure

maxsize

The size of the largest bubble in the datasizeplot. Default is 1.0.

showmle

Show MLE estimate and asymptotic variance estimate with bluelines in the parameter distribution plots?

showpost

Show posterior distribution as bar graph in parameterdistribution plots (requires MCMC results to be available inreplist)?

showprior

Show prior distribution as black line in the parameterdistribution plots?

showinit

Show initial value as red triangle in the parameterdistribution plots?

showdev

Include devs in the parameter distribution plots?

fitrange

Fit range in parameter distribution plots tightly around MLEand posterior distributions instead of full parameter range?

...

Additional arguments that will be passed to some subfunctions.

Author(s)

Ian Stewart, Ian Taylor

References

Walters, Hilborn, and Christensen, 2008, Surplus productiondynamics in declining and recovering fish populations. Can. J. Fish. Aquat.Sci. 65: 2536-2551.

See Also

SS_output(),SSplotBiology(),SSplotCatch(),SSplotComps(),SSplotDiscard(),SSplotIndices(),SSplotMnwt(),SSplotNumbers(),SSplotRecdevs(),SSplotSelex(),SSplotSpawnrecruit(),SSplotSPR(),SSplotTags(),SSplotTimeseries(),SSplotYield()


Run a likelihood profile in Stock Synthesis.

Description

Iteratively changes the control file using SS_changepars.

Usage

SS_profile(  dir = "C:/myfiles/mymodels/myrun/",  masterctlfile = "control.ss_new",  newctlfile = "control_modified.ss",  linenum = NULL,  string = NULL,  profilevec = NULL,  usepar = FALSE,  globalpar = FALSE,  parfile = "ss.par",  parlinenum = NULL,  parstring = NULL,  dircopy = TRUE,  exe.delete = FALSE,  model = "ss",  extras = "-nox",  systemcmd = FALSE,  saveoutput = TRUE,  overwrite = TRUE,  whichruns = NULL,  version = "3.30",  prior_check = TRUE,  read_like = TRUE,  verbose = TRUE)

Arguments

dir

Directory where input files and executable are located.

masterctlfile

Source control file. Default = "control.ss_new"

newctlfile

Destination for new control files (must match entry instarter file). Default = "control_modified.ss".

linenum

Line number of parameter to be changed. Can be used insteadofstring or left as NULL. Can be a vector if you are profiling multipleparameters at the same time.

string

String partially matching name of parameter to be changed. Canbe used instead oflinenum or left as NULL. Can be a vector if you areprofiling multiple parameters at the same time.

profilevec

Vector of values to profile over. If you are profileingover multiple parameters at the same time this should be a data.frame ormatrix with a column for each parameter.

usepar

Use PAR file from previous profile step for starting values?

globalpar

Use global par file ("parfile_original_backup.sso", which isautomatically copied from originalparfile) for all runs insteadof the par file from each successive run

parfile

Name of par file to use (for 3.30 models, this needs toremain 'ss.par'). Whenglobalpar=TRUE, the backup copy of thisis used for all runs.

parlinenum

Line number in par file to change (if usepar = TRUE).Can be a vector if you are profiling multiple parameters at the same time.

parstring

String in par file preceding line number to change asan alternative to parlinenum (only needed if usepar = TRUE).Can be a vector if you are profiling multiple parameters at the same time.

dircopy

Copy directories for each run? NOT IMPLEMENTED YET.

exe.delete

Delete exe files in each directory? NOT IMPLEMENTED YET.

model

Name of executable. Default = "ss".

extras

Additional commands to use when running SS. Default = "-nox"will reduce the amount of command-line output.

systemcmd

Should R call SS using "system" function instead of "shell".This may be required when running R in Emacs. Default = FALSE.

saveoutput

Copy output .SSO files to unique names. Default = TRUE.

overwrite

Overwrite any existing .SSO files. Default = TRUE. If FALSE,then some runs may be skipped.

whichruns

Optional vector of run indices to do. This can be used tore-run a subset of the cases in situations where the function wasinterrupted or some runs fail to converge. Must be a subset of 1:n, where nis the length of profilevec.

version

SS version number. Currently "3.24" or "3.30" are supported,either as character or numeric values (noting that numeric 3.30 = 3.3).version = NULL is no longer the default or an allowed entry.The default isversion = "3.30".

prior_check

Check to make sure the starter file is set to includethe prior likelihood contribution in the total likelihood. Default = TRUE.

read_like

Read the table of likelihoods from each model as it finishes.Default = TRUE. Changing to FALSE should allow the function to play througheven if something is wrong with reading the table.

verbose

Controls amount of info output to command line. Default =TRUE.

Note

The starting values used in this profile are not ideal and some modelsmay not converge. Care should be taken in using an automated tool like this,and some models are likely to require rerunning with alternate startingvalues.

Also, someday this function will be improved to work directly with theplotting functionSSplotProfile(), but they don't yet work welltogether. Thus, even ifSS_profile() is used, the output shouldbe read usingSSgetoutput() or by multiple calls toSS_output() before sending toSSplotProfile().

Author(s)

Ian Taylor

See Also

SSplotProfile(),SSgetoutput(),SS_changepars(),SS_parlines()

Examples

## Not run: # note: don't run this in your main directory# make a copy in case something goes wrongmydir <- "C:/ss/Simple - Copy"# the following commands related to starter.ss could be done by hand# read starter filestarter <- SS_readstarter(file.path(mydir, "starter.ss"))# change control file name in the starter filestarter[["ctlfile"]] <- "control_modified.ss"# make sure the prior likelihood is calculated# for non-estimated quantitiesstarter[["prior_like"]] <- 1# write modified starter fileSS_writestarter(starter, dir = mydir, overwrite = TRUE)# vector of values to profile overh.vec <- seq(0.3, 0.9, .1)Nprofile <- length(h.vec)# run SS_profile commandprofile <- SS_profile(  dir = mydir, # directory  # "NatM" is a subset of one of the  # parameter labels in control.ss_new  model = "ss",  masterctlfile = "control.ss_new",  newctlfile = "control_modified.ss",  string = "steep",  profilevec = h.vec)# read the output files (with names like Report1.sso, Report2.sso, etc.)profilemodels <- SSgetoutput(dirvec = mydir, keyvec = 1:Nprofile)# summarize outputprofilesummary <- SSsummarize(profilemodels)# OPTIONAL COMMANDS TO ADD MODEL WITH PROFILE PARAMETER ESTIMATEDMLEmodel <- SS_output("C:/ss/SSv3.24l_Dec5/Simple")profilemodels[["MLE"]] <- MLEmodelprofilesummary <- SSsummarize(profilemodels)# END OPTIONAL COMMANDS# plot profile using summary created aboveSSplotProfile(profilesummary, # summary object  profile.string = "steep", # substring of profile parameter  profile.label = "Stock-recruit steepness (h)") # axis label# make timeseries plots comparing models in profileSSplotComparisons(profilesummary, legendlabels = paste("h =", h.vec))############################################################################ example two-dimensional profile# (e.g. over 2 of the parameters in the low-fecundity stock-recruit function)base_dir <- "c:/mymodel"dir_profile_SR <- file.path(base_dir, "Profiles/Zfrac_and_Beta")# make a grid of values in both dimensions Zfrac and Beta# vector of values to profile overZfrac_vec <- seq(from = 0.2, to = 0.6, by = 0.1)Beta_vec <- c(0.5, 0.75, 1.0, 1.5, 2.0)par_table <- expand.grid(Zfrac = Zfrac_vec, Beta = Beta_vec)nrow(par_table)## [1] 25head(par_table)##   Zfrac Beta## 1   0.2 0.50## 2   0.3 0.50## 3   0.4 0.50## 4   0.5 0.50## 5   0.6 0.50## 6   0.2 0.75# run SS_profile command# requires modified version of SS_profile available via# remotes::install_github("r4ss/r4ss@profile_issue_224")profile <- SS_profile(  dir = dir_profile_SR, # directory  masterctlfile = "control.ss_new",  newctlfile = "control_modified.ss",  string = c("Zfrac", "Beta"),  profilevec = par_table,  extras = "-nohess")# get model outputprofilemodels <- SSgetoutput(  dirvec = dir_profile_SR,  keyvec = 1:nrow(par_table), getcovar = FALSE)n <- length(profilemodels)profilesummary <- SSsummarize(profilemodels)# add total likelihood (row 1) to table created abovepar_table[["like"]] <- as.numeric(profilesummary[["likelihoods"]][1, 1:n])# reshape data frame into a matrix for use with contourlike_matrix <- reshape2::acast(par_table, Zfrac ~ Beta, value.var = "like")# make contour plotcontour(  x = as.numeric(rownames(like_matrix)),  y = as.numeric(colnames(like_matrix)),  z = like_matrix)## End(Not run)

Read all Stock Synthesis input files for a model

Description

Read all the input files for a Stock Synthesis model into R as a list object.These files will be in a single directory on your machine, i.e.,dir.Functionality comes from the⁠r4ss::SS_read*()⁠ functions.This function simplifies the number of lines of code you need to write byusing all of the read functions to read in thestarter, control, data, and forecast files.The starter file is helpful because it provides names for thecontrol and data files.

Usage

SS_read(dir = NULL, ss_new = FALSE, verbose = FALSE)

Arguments

dir

A file path to the directory of interest.Typically used withfile, an additional input argument,to specify input and output file paths.The default value isdir = NULL, which leads to usingthe current working directory, and thus, full file paths shouldnot be specified for other arguments as they will be appendedtodir.

ss_new

A logical that controls if the.ss_new files orthe original input files are read in.The default is to read the original files.

verbose

A logical value specifying if output should be printedto the screen.

Value

An invisible list is returned.The first element is the directory that was provided in the argumentdir.The second element is the result ofnormalizePath(dir),which gives the full path.The remaining four elements are list objects from reading inthe following input files:

Author(s)

Ian G. Taylor, Kelli F. Johnson

See Also

Examples

# Read in the 'simple' example model stored in {r4ss}inputs <- SS_read(  dir = system.file("extdata", "simple_3.30.13", package = "r4ss"))

read ss_summary file

Description

read Stock Synthesis ss_summary.sso file into list object in R

Usage

SS_read_summary(file = "ss_summary.sso", verbose = FALSE)

Arguments

file

Filename either with full path or relative to working directory.

verbose

A logical value specifying if output should be printedto the screen.

Value

Output will be a list with four elements,header,likelihoods,parameters, andderived_quants.Each is a data frame with rownames indicating the quantity shown in each row.

Author(s)

Ian Taylor

See Also

SS_output(),SS_readforecast(),SS_readdat(),SS_readstarter()

Examples

## Not run: summary <- SS_read_summary(file = "c:/mymodel/ss_summary.sso")## End(Not run)

Read control file from SS

Description

Read control file from Stock Synthesis (SS) into R as a list object.This function acts as a wrapper for version-specific SS_readctl_ functions.For example, if the control file was written using SS 3.24,thenSS_readctl will callSS_readctl_3.24. Input arguments that do notpertain to the version of your control file can be left at theirdefault values.

Usage

SS_readctl(  file,  version = "3.30",  verbose = FALSE,  echoall = lifecycle::deprecated(),  use_datlist = TRUE,  datlist = "data.ss_new",  nseas = NULL,  N_areas = NULL,  Nages = NULL,  Ngenders = lifecycle::deprecated(),  Nsexes = NULL,  Npopbins = NA,  Nfleets = NULL,  Nfleet = NULL,  Do_AgeKey = NULL,  Nsurveys = NULL,  N_tag_groups = NULL,  N_CPUE_obs = NULL,  catch_mult_fleets = NULL,  predM_fleets = NULL,  Ntag_fleets = NULL,  N_rows_equil_catch = NULL,  N_dirichlet_parms = NULL,  ptype = FALSE)

Arguments

file

Filename either with full path or relative to working directory.

See the formal arguments for a possible default filename.

version

SS version number. Currently "3.24" or "3.30" are supported,either as character or numeric values (noting that numeric 3.30 = 3.3).version = NULL is no longer the default or an allowed entry.The default isversion = "3.30".

verbose

Should there be verbose output while running the file?Defaults to FALSE.

echoall

Deprecated. Debugging tool (not fully implemented) of echoingblocks of values as it is being read.

use_datlist

LOGICAL. If TRUE, use datlist to derive parameters whichcan not be determined from control file. Defaults to TRUE.

datlist

list or character. If list, should be a list produced fromSS_writedat(). If character, should be the file name of an SS data file.

nseas

number of seasons in the model. This information is notexplicitly available in control file and used only ifuse_datlist = FALSE.

N_areas

number of spatial areas in the model. Default = 1. This information is notexplicitly available in control file and used only if ifuse_datlist = FALSE.

Nages

oldest age in the model. This information is also notexplicitly available in control file and used only ifuse_datlist = FALSE.

Ngenders

Deprecated. Number of sexes in the model. This information is also notexplicitly available in control file and used only ifuse_datlist = FALSE.

Nsexes

number of sexes in the model. This information is also notexplicitly available in control file and used only ifuse_datlist = FALSE.

Npopbins

number of population bins in the model. This information is also notexplicitly available in control file and this information is only required if length basedmaturity vector is directly supplied (Maturity option of 6). and used onlyifuse_datlist = FALSE.

Nfleets

Number of fishing fleets and surveys, for 3.30 models.

Nfleet

Number of fishing fleets, for 3.24 and lower version models.

Do_AgeKey

Flag to indicate if 7 additional ageing error parameters tobe read set 1 (but in fact any non zero numeric in R) or TRUE to enable toread them 0 or FALSE to disable them. This information is notexplicitly available in control file and used only ifuse_datlist = FALSE.

Nsurveys

Number of surveys, for 3.24 and lower version models.

N_tag_groups

number of tag release group. Default =NA. This informationis not explicitly available control file and used only ifuse_datlist = FALSE. This information is only required if custom tagparameters is enabled (TG_custom=1)

N_CPUE_obs

Number of CPUE observations. Used only in control file 3.24syntax ifuse_datlist = FALSE.

catch_mult_fleets

Integer vector of fleets using the catch multiplieroption. Defaults to NULL and should be left as such if 1) the catchmultiplier option is not used for any fleet or 2)use_datlist = TRUE anddatlist is specified. Used only in control file 3.30 syntax ifuse_datlist = FALSE.

predM_fleets

integer vector of fleets with predator mortality included.Predator mortality fleets are only available in v3.30.18 andhigher. Defaults to NULL and should be left as such if 1) predation mortalityis not used for any fleets; 2)use_datlist = TRUE anddatlist is specified;or 3) if comments in the control file should be used instead to determinethe the predM_fleets. Used only in control file 3.30 syntax ifuse_datlist = FALSE.

Ntag_fleets

The number of catch fleets in the model (fleets of )type 1 or 2; not surveys). Used to set the number of survey parameters.Only used in control file 3.30 reading if tagging data is in the model anduse_datlist = FALSE.

N_rows_equil_catch

Integer value of the number of parameter lines toread for equilibrium catch. Defaults to NULL, which means the function willattempt to figure out how many lines of equilibrium catch to read from thecontrol file comments. Used only in control file 3.30 syntax ifuse_datlist = FALSE.

N_dirichlet_parms

Integer value of the number of Dirichlet-Multinomialparameters. Defaults to 0. Used only in control file 3.30 syntax ifuse_datlist = FALSE.

ptype

LOGICAL ifTRUE, which is the default,a column will be included in the output indicating parameter type.UsingTRUE can be useful, but causes problems forSS_writectl,and therefore is not recommended if you intend to write the listback out into a file.Used only in control file 3.24 syntax.

Value

A list structure where each element is a section of the control file.

Author(s)

Ian G. Taylor, Yukio Takeuchi, Neil L. Klaer

See Also

See the following for version-specific SS_readctl functions:SS_readctl_3.24SS_readctl_3.30.The returned list structure can be written back to the disk usingSS_writectl.
See the following for otherSS_read functions:SS_readctlSS_readdatSS_readforecastSS_readstarterSS_readwtatage.

Examples

# Read in the 'simple' example SS model stored in r4ss# Find the directorydirsimple <- system.file("extdata", "simple_3.30.13", package = "r4ss")# Read in the dat file to define the structure of the control file so that# you don't have to specify things in the function call such as 'Nfleet'datfilename <- dir(dirsimple, pattern = "data\\.ss", full.names = TRUE)dat <- r4ss::SS_readdat(file = datfilename, verbose = FALSE)# Read in the control file using a list object for datlistctl <- r4ss::SS_readctl(  file = dir(dirsimple, pattern = "control\\.ss", full.names = TRUE),  verbose = FALSE,  datlist = dat, use_datlist = TRUE)# Read in the control file using a file name for datlistctl <- r4ss::SS_readctl(  file = dir(dirsimple, pattern = "control\\.ss", full.names = TRUE),  verbose = FALSE,  datlist = datfilename, use_datlist = TRUE)

read control file from SS version 3.24

Description

Read Stock Synthesis (version 3.24) control file into list object in R.This function comes with its wrapper function SS_readctlthat calls SS_readctl_3.24 (this function) or SS_readctl_3.30(to be available in future).

Usage

SS_readctl_3.24(  file,  verbose = FALSE,  echoall = lifecycle::deprecated(),  version = lifecycle::deprecated(),  use_datlist = TRUE,  datlist = "data.ss_new",  nseas = NULL,  N_areas = NULL,  Nages = NULL,  Ngenders = lifecycle::deprecated(),  Nsexes = NULL,  Npopbins = NA,  Nfleet = NULL,  Nsurveys = NULL,  Do_AgeKey = NULL,  N_tag_groups = NULL,  N_CPUE_obs = NULL,  ptype = FALSE)

Arguments

file

Filename either with full path or relative to working directory.

See the formal arguments for a possible default filename.

verbose

Should there be verbose output while running the file?Defaults to FALSE.

echoall

Deprecated. Debugging tool (not fully implemented) of echoingblocks of values as it is being read.

version

Deprecated. SS version number. Currently only "3.24" or "3.30" are supported,either as character or numeric values (noting that numeric 3.30 = 3.3).

use_datlist

LOGICAL if TRUE, use datlist to derive parameters whichcan not be determined from control file. Defaults to TRUE

datlist

list or character. if list : produced from SS_writedator character : file name of dat file.

nseas

number of seasons in the model. This information is notexplicitly available in control file and used only ifuse_datlist = FALSE.

N_areas

number of spatial areas in the model. Default = 1. This information is notexplicitly available in control file and used only if ifuse_datlist = FALSE.

Nages

oldest age in the model. This information is also notexplicitly available in control file and used only ifuse_datlist = FALSE.

Ngenders

Deprecated. Number of sexes in the model. This information is also notexplicitly available in control file and used only ifuse_datlist = FALSE.

Nsexes

number of sexes in the model. This information is also notexplicitly available in control file and used only ifuse_datlist = FALSE.

Npopbins

number of population bins in the model. This information is also notexplicitly available in control file and this information is only required if length basedmaturity vector is directly supplied (Maturity option of 6). and used onlyifuse_datlist = FALSE.

Nfleet

number of fisheries in the model. This information is also notexplicitly available in control file

Nsurveys

number of survey fleets in the model. This information is also notexplicitly available in control file

Do_AgeKey

Flag to indicate if 7 additional ageing error parameters tobe read set 1 (but in fact any non zero numeric in R) or TRUE to enable toread them 0 or FALSE to disable them. This information is notexplicitly available in control file and used only ifuse_datlist = FALSE.

N_tag_groups

number of tag release group. Default =NA. This informationis not explicitly available control file and used only ifuse_datlist = FALSE. This information is only required if custom tagparameters is enabled (TG_custom=1)

N_CPUE_obs

numeric vector of length=Nfleet+Nsurveys containing numberof data points of each CPUE time series

ptype

include a column in the output indicating parameter type?(Can be useful, but causes problems for SS_writectl.) Defaults to FALSE.

Author(s)

Yukio Takeuchi, Neil Klaer, Iago Mosqueira, and Kathryn Doering

See Also

SS_readctl(),SS_readdat()SS_readdat_3.24(),SS_readdat_3.30()SS_readstarter(),SS_readforecast(),SS_writestarter(),SS_writeforecast(),SS_writedat()


read control file from SS version 3.30

Description

Read Stock Synthesis (version 3.30) control file into list object in R.This function should be called from SS_readctl.

Usage

SS_readctl_3.30(  file,  verbose = FALSE,  echoall = lifecycle::deprecated(),  version = lifecycle::deprecated(),  use_datlist = TRUE,  datlist = "data.ss_new",  nseas = NULL,  N_areas = NULL,  Nages = NULL,  Ngenders = lifecycle::deprecated(),  Nsexes = NULL,  Npopbins = NULL,  Nfleets = NULL,  Ntag_fleets = NULL,  Do_AgeKey = NULL,  N_tag_groups = NULL,  catch_mult_fleets = NULL,  predM_fleets = NULL,  N_rows_equil_catch = NULL,  N_dirichlet_parms = NULL)

Arguments

file

Filename either with full path or relative to working directory.

See the formal arguments for a possible default filename.

verbose

Should there be verbose output while running the file?Defaults to FALSE.

echoall

Deprecated. Debugging tool (not fully implemented) of echoingblocks of values as it is being read.

version

Deprecated. SS version number. Currently only "3.24" or "3.30" are supported,either as character or numeric values (noting that numeric 3.30 = 3.3).

use_datlist

LOGICAL. If TRUE, use datlist to derive parameters whichcan not be determined from control file. Defaults to TRUE.

datlist

list or character. If list, should be a list produced fromSS_writedat(). If character, should be the file name of an SS data file.

nseas

number of seasons in the model. This information is notexplicitly available in control file and used only ifuse_datlist = FALSE.

N_areas

number of spatial areas in the model. Default = 1. This information is notexplicitly available in control file and used only if ifuse_datlist = FALSE.

Nages

oldest age in the model. This information is also notexplicitly available in control file and used only ifuse_datlist = FALSE.

Ngenders

Deprecated. Number of sexes in the model. This information is also notexplicitly available in control file and used only ifuse_datlist = FALSE.

Nsexes

number of sexes in the model. This information is also notexplicitly available in control file and used only ifuse_datlist = FALSE.

Npopbins

number of population bins in the model. This information is also notexplicitly available in control file and this information is only required if length basedmaturity vector is directly supplied (Maturity option of 6). and used onlyifuse_datlist = FALSE.

Nfleets

number of fishery and survey fleets in the model. This information is also notexplicitly available in control file

Ntag_fleets

The number of catch fleets in the model (fleets of )type 1 or 2; not surveys). Used to set the number of survey parameters.Only used if tagging data is in the model anduse_datlist is FALSE.

Do_AgeKey

Flag to indicate if 7 additional ageing error parameters tobe read set 1 (but in fact any non zero numeric in R) or TRUE to enable toread them 0 or FALSE to disable them. This information is notexplicitly available in control file and used only ifuse_datlist = FALSE.

N_tag_groups

number of tag release group. Default =NA. This informationis not explicitly available control file and used only ifuse_datlist = FALSE. This information is only required if custom tagparameters is enabled (TG_custom=1)

catch_mult_fleets

integer vector of fleets using the catch multiplieroption. Defaults to NULL and should be left as such if 1) the catchmultiplier option is not used for any fleets or 2) use_datlist = TRUE anddatlist is specified.

predM_fleets

integer vector of fleets with predator mortality included.Predator mortality fleets are only available in v3.30.18 andhigher. Defaults to NULL and should be left as such if 1) predation mortalityis not used for any fleets; 2) use_datlist = TRUE and datlist is specified;or 3) if comments in the control file should be used instead to determinethe the predM_fleets.

N_rows_equil_catch

Integer value of the number of parameter lines toread for equilibrium catch. Defaults to NULL, which means the function willattempt to figure out how many lines of equilibrium catch to read from thecontrol file comments.

N_dirichlet_parms

Integer value of the number of Dirichlet multinomialparameters. Defaults to 0.

Author(s)

Neil Klaer, Yukio Takeuchi, Watal M. Iwasaki, and Kathryn Doering

See Also

SS_readctl(),SS_readdat()SS_readdat_3.24(),SS_readdat_3.30()SS_readctl_3.24(),SS_readstarter(),SS_readforecast(),SS_writestarter(),SS_writeforecast(),SS_writedat()


read Stock Synthesis data file

Description

Read Stock Synthesis data file into list object in R. This function is awrapper which calls SS_readdat_2.00, SS_readdat_3.00, SS_readdat_3.24, or SS_readdat_3.30(and potentially additional functions in the future). This setup allows thosefunctions to be cleaner (if somewhat redundant) than a single function thatattempts to do everything. Returned datlist is mostly consistent across versions.

Usage

SS_readdat(  file,  version = "3.30",  verbose = TRUE,  echoall = FALSE,  section = NULL)

Arguments

file

Filename either with full path or relative to working directory.

See the formal arguments for a possible default filename.

version

SS version number.Currently "2.00", "3.00", "3.24" or "3.30" are supported,either as character or numeric values (noting that numeric 3.30 = 3.3). Ifversion is NULL, the version (3.24 or 3.30) will be looked for on the firstline of the file.

verbose

Should there be verbose output while running the file?Default=TRUE.

echoall

Debugging tool (not fully implemented) of echoing blocks ofdata as it is being read.

section

Which data set to read. Only applies for a data.ss_new filecreated by Stock Synthesis. Allows the choice of either expected values(section=2) or bootstrap data (section=3+). Leaving default of section=NULLwill read input data, (equivalent to section=1).

Author(s)

Ian G. Taylor, Allan C. Hicks, Neil L. Klaer, Kelli F. Johnson,Chantel R. Wetzel

See Also

SS_readdat_2.00(),SS_readdat_3.00(),SS_readdat_3.24(),SS_readdat_3.30(),SS_readctl(),SS_readctl_3.24()SS_readstarter(),SS_readforecast(),SS_writestarter(),SS_writeforecast(),SS_writedat()


read data file from SS version 2.00

Description

Read Stock Synthesis (version 2.00) data file into list object in R.This function was formerly called SS_readdat. That name is now usedfor a wrapper function that calls either SS_readdat_2.00 SS_readdat_3.00SS_readdat_3.24 or SS_readdat_3.30 (and potentially additional functions in the future).

Usage

SS_readdat_2.00(file, verbose = TRUE, echoall = FALSE, section = NULL)

Arguments

file

Filename either with full path or relative to working directory.

See the formal arguments for a possible default filename.

verbose

Should there be verbose output while running the file?Default=TRUE.

echoall

Debugging tool (not fully implemented) of echoing blocks ofdata as it is being read.

section

Which data set to read. Only applies for a data.ss_new filecreated by Stock Synthesis. Allows the choice of either expected values(section=2) or bootstrap data (section=3+). Leaving default of section=NULLwill read input data, (equivalent to section=1). ## needs to be added

Author(s)

Ian G. Taylor, Yukio Takeuchi, Z. Teresa A'mar, Neil L. Klaer

See Also

SS_readdat(),SS_readdat_3.30()SS_readstarter(),SS_readforecast(),SS_writestarter(),SS_writeforecast(),SS_writedat()


read data file from SS version 3.00

Description

Read Stock Synthesis (version 3.00) data file into list object in R.This function was formerly called SS_readdat. That name is now usedfor a wrapper function that calls either SS_readdat_3.24 or SS_readdat_3.30(and potentially additional functions in the future).

Usage

SS_readdat_3.00(file, verbose = TRUE, echoall = FALSE, section = NULL)

Arguments

file

Filename either with full path or relative to working directory.

See the formal arguments for a possible default filename.

verbose

Should there be verbose output while running the file?Default=TRUE.

echoall

Debugging tool (not fully implemented) of echoing blocks ofdata as it is being read.

section

Which data set to read. Only applies for a data.ss_new filecreated by Stock Synthesis. Allows the choice of either expected values(section=2) or bootstrap data (section=3+). Leaving default of section=NULLwill read input data, (equivalent to section=1).

Author(s)

Ian G. Taylor, Yukio Takeuchi, Z. Teresa A'mar

See Also

SS_readdat(),SS_readdat_3.30()SS_readstarter(),SS_readforecast(),SS_writestarter(),SS_writeforecast(),SS_writedat()


read data file from SS version 3.24

Description

Read Stock Synthesis (version 3.24) data file into list object in R.This function was formerly called SS_readdat. That name is now usedfor a wrapper function that calls either SS_readdat_3.24 or SS_readdat_3.30(and potentially additional functions in the future).

Usage

SS_readdat_3.24(file, verbose = TRUE, echoall = FALSE, section = NULL)

Arguments

file

Filename either with full path or relative to working directory.

See the formal arguments for a possible default filename.

verbose

Should there be verbose output while running the file?Default=TRUE.

echoall

Debugging tool (not fully implemented) of echoing blocks ofdata as it is being read.

section

Which data set to read. Only applies for a data.ss_new filecreated by Stock Synthesis. Allows the choice of either expected values(section=2) or bootstrap data (section=3+). Leaving default of section=NULLwill read input data, (equivalent to section=1).

Author(s)

Ian G. Taylor, Yukio Takeuchi, Z. Teresa A'mar, Kelli F. Johnson,Chantel R. Wetzel

See Also

SS_readdat(),SS_readdat_3.30()SS_readstarter(),SS_readforecast(),SS_writestarter(),SS_writeforecast(),SS_writedat()


read data file from SS version 3.30

Description

Read Stock Synthesis (version 3.30) data file into list object in R.This function was formerly called SS_readdat. That name is now usedfor a wrapper function that calls either SS_readdat_3.24 or SS_readdat_3.30(and potentially additional functions in the future).

Usage

SS_readdat_3.30(file, verbose = TRUE, echoall = FALSE, section = NULL)

Arguments

file

Filename either with full path or relative to working directory.

See the formal arguments for a possible default filename.

verbose

Should there be verbose output while running the file?Default=TRUE.

echoall

Debugging tool (not fully implemented) of echoing blocks ofdata as it is being read.

section

Which data set to read. Only applies for a data.ss_new filecreated by Stock Synthesis. Allows the choice of either expected values(section=2) or bootstrap data (section=3+). Leaving default of section=NULLwill read input data, (equivalent to section=1).

Author(s)

Ian G. Taylor, Yukio Takeuchi, Z. Teresa A'mar, Chris J. Grandin,Kelli F. Johnson, Chantel R. Wetzel

See Also

SS_readdat(),SS_readdat_3.30()SS_readstarter(),SS_readforecast(),SS_writestarter(),SS_writeforecast(),SS_writedat()


read forecast file

Description

read Stock Synthesis forecast file into list object in R

Usage

SS_readforecast(  file = "forecast.ss",  Nfleets = NULL,  Nareas = NULL,  nseas = NULL,  version = "3.30",  readAll = FALSE,  verbose = TRUE)

Arguments

file

Filename either with full path or relative to working directory.

See the formal arguments for a possible default filename.

Nfleets

Number of fleets (not required in 3.30).

Nareas

Number of areas (not required in 3.30).

nseas

number of seasons (not required in 3.30).

version

SS version number. Currently "3.24" or "3.30" are supported,either as character or numeric values (noting that numeric 3.30 = 3.3).version = NULL is no longer the default or an allowed entry.The default isversion = "3.30".

readAll

Should the function continue even if Forecast = 0 or -1(at which point SS stops reading)?

verbose

Should there be verbose output while running the file?

Author(s)

Ian Taylor + Nathan Vaughan

See Also

SS_readstarter(),SS_readdat(),SS_writestarter(),SS_writeforecast(),SS_writedat(),


read ss.par file from SS version 3.24

Description

Read Stock Synthesis (version 3.24) parameter file into list object in R.

Usage

SS_readpar_3.24(parfile, datsource, ctlsource, verbose = TRUE)

Arguments

parfile

Filename either with full path or relative to working directory.

datsource

list or character. If list, should be a list producedfromSS_writedat(). If character, should be the full file location of anSS data file.

ctlsource

list or character. If list, should be a list producedfromSS_writectl(). If character, should be the full file location of anSS control file.

verbose

Should there be verbose output while running the file?Default=TRUE.

Author(s)

Nathan R. Vaughan

See Also

SS_readctl(),SS_readdat()SS_readdat_3.24(),SS_readdat_3.24()SS_readctl_3.24(),SS_readstarter(),SS_readforecast(),SS_writestarter(),SS_writeforecast(),SS_writedat()


read ss.par file from SS version 3.30

Description

Read Stock Synthesis (version 3.30) parameter file into list object in R.

Usage

SS_readpar_3.30(parfile, datsource, ctlsource, verbose = TRUE)

Arguments

parfile

Filename either with full path or relative to working directory.

datsource

list or character. If list, should be a list producedfromSS_writedat(). If character, should be the full file location of anSS data file.

ctlsource

list or character. If list, should be a list producedfromSS_writectl(). If character, should be the full file location of anSS control file.

verbose

Should there be verbose output while running the file?Default=TRUE.

Author(s)

Nathan R. Vaughan

See Also

SS_readctl(),SS_readdat(),SS_readstarter(),SS_readforecast(),SS_writestarter(),SS_writeforecast(),SS_writedat()


read starter file

Description

read Stock Synthesis starter file into list object in R

Usage

SS_readstarter(file = "starter.ss", verbose = TRUE)

Arguments

file

Filename either with full path or relative to working directory.

See the formal arguments for a possible default filename.

verbose

Should there be verbose output while running the file?

Author(s)

Ian Taylor

See Also

SS_readforecast(),SS_readdat(),SS_writestarter(),SS_writeforecast(),SS_writedat()


Read weight-at-age data file

Description

Read in a weight-at-age data file into a data frame in R.

Usage

SS_readwtatage(file = "wtatage.ss", verbose = TRUE)

Arguments

file

Filename either with full path or relative to working directory.

See the formal arguments for a possible default filename.

verbose

A logical value specifying if output should be printedto the screen.

Value

Returns a data frame with a variable number of columns based on thenumber of ages that are included in the file. Though, the first columnswill always be Yr, Seas, Sex, Bio_Pattern, BirthSeas, and Fleet.The seventh column will be age zero.The last or next to last column will be the maximum age includedin the weight-at-age data. For SS version 3.30 and greater, the last columnwill be a column of comments.

Author(s)

Kelli F. Johnson, Ian G. Taylor


Insert a vector of recruitment deviations into the control file.

Description

A function to insert a vector of recruitment deviations into the controlfile for simulation studies. This can also be achieved by using the .parfile, but Ian Taylor prefers this approach for no good reason.

Usage

SS_recdevs(  fyr,  lyr,  ctl = NULL,  recdevs = NULL,  rescale = TRUE,  scaleyrs = NULL,  dir = "working_directory",  ctlfile = "control.ss_new",  newctlfile = "control_modified.ss",  verbose = TRUE,  writectl = TRUE,  returnctl = FALSE,  newmaxbias = NULL)

Arguments

fyr

First year of the recdev vector.

lyr

Last year of the recdev vector.

ctl

Either NULL to read anew or an already read control file.Default=NULL.

recdevs

Either NULL to generate anew or an already generated vectorof recdevs. Default=NULL.

rescale

Should the recdevs be rescaled to have mean = 0 and std.deviation = sigmaR? Default=TRUE.

scaleyrs

Vector of years over which rescaling (if chosen) shouldoccur.

dir

Directory where files are located. Default is to use the workingdirectory in use by R. Default="working_directory".

ctlfile

Name of control file to modify. Default="control.ss_new".

newctlfile

Name of new file to output modified control file.Default="control_modified.ss".

verbose

Verbose output to R command line? Default=TRUE.

writectl

Write new file? Default=TRUE.

returnctl

Return contents ctl file as an object in the R workspace.Default=FALSE.

newmaxbias

Replace the maximum bias adjustment fraction with anynon-NULL value. Default=NULL.

Author(s)

Ian Taylor


Split apart bootstrap data to make input file.

Description

A function to split apart bootstrap data files created in data.ss_new. Toget bootstraps, the input "N bootstrap file to produce" in starter.ss needsto be 3 or greater. The function can either create a file for just theinput data (ifinputs=TRUE), a file for just the MLE values(ifMLE = TRUE), or separate files for each of the bootstraps(ifinputs=FALSE andMLE=FALSE).

Usage

SS_splitdat(  inpath = "working_directory",  outpath = "working_directory",  inname = "data.ss_new",  outpattern = "BootData",  number = FALSE,  verbose = TRUE,  fillblank = TRUE,  MLE = TRUE,  inputs = FALSE,  notes = "")

Arguments

inpath

Directory containing the input file. By default the workingdirectory given by getwd() is used. Default="working_directory".

outpath

Directory into which the output file will be written.Default="working_directory".

inname

File name of input data file to be split.Default="Data.SS_New".

outpattern

File name of output data file. Default="BootData".

number

Append bootstrap number to the file name chosen inoutpattern? Default=F.

verbose

Provide richer command line info of function progress?Default=TRUE.

fillblank

Replace blank lines with "#". Helps with running on linux.Default=TRUE.

MLE

Grab the maximum likelihood values from the second block inData.SS_New (instead of bootstrap values or copies of inputs)? Default=TRUE.

inputs

Grab the copy of the input values values from the first blockin Data.SS_New (instead of MLE or bootstrap values)? Default=F.

notes

Notes to the top of the new file (comment indicator "#C" willbe added). Default="".

Author(s)

Ian Taylor


Calculate new tunings for length and age compositions and (re)run models

Description

Creates a table of values that can be copied into the SS control filefor SS 3.30 models to adjust the input sample sizes for length and agecompositions based on either the Francis or McAllister-Ianelli tuning oradds the Dirichlet-Multinomial parameters to the necessary files totune the model using an integrated method.Optionally, this function can automatically add these tunings to theappropriate files and rerun the model for the desired number of iterations.

Usage

SS_tune_comps(  replist = NULL,  fleets = "all",  option = c("Francis", "MI", "none", "DM"),  digits = 6,  write = TRUE,  niters_tuning = 0,  init_run = FALSE,  dir = getwd(),  model = "ss",  exe_in_path = FALSE,  extras = "-nox",  allow_up_tuning = FALSE,  verbose = TRUE,  ...)

Arguments

replist

A list object created bySS_output().

fleets

Either the string 'all', or a vector of fleet numbers

option

Which type of tuning: 'none', 'Francis', 'MI', or 'DM'.The first option,none, will only return information about theFrancis and MI weights that are suggested.

digits

Number of digits to round numbers to.

write

Write suggested tunings to a file saved to the disk calledsuggested_tunings.ss. This file name is currently hard coded and willbe saved indir.

niters_tuning

The number of times to retune models. Defaults to 0,where only the tunings should be calculated and the model is not rerun. Notethat for DM, it will be assumed that 0 means not to run the model andspecifying 1 or greater will only run the model once (because DM is not aniterative retuning method).

init_run

Should the model be run before calculating the tunings?Defaults toFALSE. This run is not counted as an iteration forniters_tuning and will not be used ifoption = "DM".

dir

The path to the model directory.

model

The name of the stock synthesis executable. This model isassumed to be either in the same folder as the model files (specified indir), or in the PATH ifexe_in_path = TRUE. This will not be used ifinit_run = FALSE andniters_tuning = 0.

exe_in_path

logical. If TRUE, will look for exe in the PATH. If FALSE,will look for exe in the model folders. Default = FALSE.

extras

Additional commands to use when running SS. Default = "-nox"will reduce the amount of command-line output. A commonly used option is"-nohess" to skip calculating the hessian (and asymptotic uncertainty).

allow_up_tuning

Allow tuning values for Francis or MI > 1? Defaults toFALSE, which caps tuning values at 1.

verbose

A logical value specifying if output should be printedto the screen.

...

Additional arguments to pass torun_SS_models.

Value

Returns a table that can be copied into the control file.Ifwrite=TRUE then will write the values to a file(currently hardwired to go in the directory where the model was runand called "suggested_tunings.ss").

option

Francis

The Francis approach to data weighting adjusts the input sample sizes usinga scalar such that the fit of the expected value is within the uncertaintyintervals based on the expected fit given adjusted sample sizes.

McAllister-Ianelli (MI)

Also known as the Harmonic-Mean approach to data weighting, theMcAllister-Ianelli weighting approach uses a scalar to adjust the inputsample size of composition data based matching the arithmetic meanof the input sample size to the harmonic mean of the effective sample size.

Dirichlet-Multinomial (DM)

The Dirichlet-Multinomial likelihood is an alternative approach that allowsthe tuning factor to be estimated rather than iteratively tuned.Note that foroption = "DM" a table of tunings isnot created as the DM is not an iterative reweighting option. Instead, eachof the fleets with length- and age-composition data will be assigned a DMparameter and the model will be rerun.

SS versions

3.30.00-3.30.11

Recommended_var_adj and other columns were named differently in theseearly version of SS. Calculations are thus done internally based onfinding the correct column name.

3.30.12-3.30.16

Starting with SS version 3.30.12, the "Length_Comp_Fit_Summary"table in Report.sso is already in the format required to paste intothe control file to apply the McAllister-Ianelli tuning. However, thisfunction provides the additional option of the Francis tuning and theability to compare the two approaches, as well as the functionality to addtunings and rerun the model. The "Age_Comp_Fit_Summary" table in Report.ssois formatted similarly though, though the Recommended_var_adj was wronglyset to 1 for all fleets in SS versions 3.30.12 to 3.30.16. Thus, theMI approach is not taken from this recommended column, instead, it iscalculated from the harmonic mean and input sample sizes.

Author(s)

Ian G. Taylor, Kathryn Doering

References

Francis, R.I.C.C. (2011). Data weighting in statisticalfisheries stock assessment models. Can. J. Fish. Aquat. Sci. 68: 1124-1138.

See Also

SSMethod.TA1.8()

Examples

## Not run: # Set up the folders ----# Create a temporary directory, feel free to change this locationmod_path <- file.path(tempdir(), "simple_mod")# Path to simple model in r4ss and copy files to mod_pathexample_path <- system.file("extdata", "simple_3.30.13", package = "r4ss")# copy model input filescopy_SS_inputs(dir.old = example_path, dir.new = mod_path, verbose = FALSE)# copy over the Report filefile.copy(  from = file.path(example_path, "Report.sso"),  to = file.path(mod_path, "Report.sso"))# copy comp report filefile.copy(  from = file.path(example_path, "CompReport.sso"),  to = file.path(mod_path, "CompReport.sso"))# Use the SS_tune_comps function----# Examples where a model is not run ----# Just get the Francis and MI tables, without running the model. Note that the# model in mod_path needs to already have been run with Stock Synthesis, so# that a report file is available.weight_table <- SS_tune_comps(  dir = mod_path,  option = "none",  verbose = FALSE)# view the weights. Note that the columns New_Francis and New_MI show the# weights, but neither were added to the New_Var_adj columnweight_table# Get the Francis and MI tables, but with the Francis weights in the# New_Var_adj column. Note if option = "MI" were used, the output would be# the same except that the New_Var_adj column would contain the MI weights.weight_table_fran <- SS_tune_comps(  dir = mod_path,  option = "Francis",  verbose = FALSE)weight_table_fran# Add Dirichlet multinomial tuning parameters to the model, without running it.DM_parm_info <- SS_tune_comps(  option = "DM",  niters_tuning = 0, # 0 means the model will not be run.  dir = mod_path,  model = "ss",  extras = "-nohess",  verbose = FALSE)# See the Dirichlet parameters added to the model.DM_parm_info[["tuning_table_list"]]# can also look in the data file to see which fleets of comp data now have# DM parameters. The "ParmSelect" column of the len_info and age_info# contains the dirichlet multinomial parameter numbers.dat <- SS_readdat(file.path(mod_path, "simple_data.ss"), verbose = FALSE)dat[["len_info"]]dat[["age_info"]]# Examples where models are run ----# Run MI weighting and allow upweighting for 1 iteration. Assume that an ss# executable called "ss or ss.exe" is available in the mod_path folder.# If the executable is not available, then the call will exit on error.# Note that the Dirichlet mulitnomial parameters will be removed, but any# previous tunings will be retained.tune_info <- SS_tune_comps(  option = "MI",  niters_tuning = 1,  dir = mod_path,  allow_up_tuning = TRUE,  model = "ss",  verbose = FALSE)# see the tuning table, and the weights applied to the model.tune_info# Add Dirichlet multinomial paramters and rerun. The function will# automatically remove the MI weighting and add in the DM parameters.# Use extras = "-nohess" when running model to speed up run.DM_parm_info <- SS_tune_comps(  option = "DM",  niters_tuning = 1, # must be 1 or greater to run  dir = mod_path,  model = "ss",  extras = "-nohess",  verbose = FALSE)# see the DM parameter estimatesDM_parm_info[["tuning_table_list"]]# cleanup ----unlink(mod_path, recursive = TRUE)## End(Not run)

Modify variance and sample size adjustments in the control file

Description

Function has not been fully tested yet

Usage

SS_varadjust(  dir = "C:/myfiles/mymodels/myrun/",  ctlfile = "control.ss_new",  newctlfile = "control_modified.ss",  keyword = "variance adjustments",  newtable = NULL,  newrow = NULL,  rownumber = NULL,  maxcols = 100,  maxrows = 100,  overwrite = FALSE,  version = "3.30",  verbose = TRUE)

Arguments

dir

Directory with control file to change.

ctlfile

Control file name. Default="control.ss_new".

newctlfile

Name of new control file to be written.Default="control_modified.ss".

keyword

Keyword to use as reference for start of section onvariance adjustments

newtable

Optional table of new variance adjustment values

newrow

Optional vector of new variance adjustment values for a particular row

rownumber

Which of the 6 rows to replace with 'newrow' if present?

maxcols

Maximum number of columns to search among in 3.24 models(may need to increase from default if you have a huge number of fleets)

maxrows

Maximum number of rows to search among in 3.30 models(may need to increase from default if you have a huge number of fleets)

overwrite

Overwrite file if it exists?

version

SS version number. Currently "3.24" or "3.30" are supported,either as character or numeric values (noting that numeric 3.30 = 3.3).version = NULL is no longer the default or an allowed entry.The default isversion = "3.30".

verbose

TRUE/FALSE switch for amount of detail produced by function.Default=TRUE.

Author(s)

Ian G. Taylor, Gwladys I. Lambert

See Also

SS_tune_comps(),SS_parlines(),SS_changepars()

Examples

## Not run: # load model output into Rreplist <- SS_output(dir = "c:/model/")# get new variance adjustments (varadjust <- SS_tune_comps(replist, option = "Francis")print(varadjust)# write new table to fileSS_varadjust(  dir = replist[["inputs"]][["dir"]], newctlfile = "new_control.ss",  newtable = varadjust, overwrite = FALSE)## End(Not run)

Write all Stock Synthesis input files for a model

Description

Writes all the input files for a Stock Synthesis model using the listcreated bySS_read()(presumably after modification of one or more elements)using the⁠SS_write*()⁠ functions for the four orfive model input files.

Usage

SS_write(inputlist, dir = "", overwrite = FALSE, verbose = FALSE)

Arguments

inputlist

list created bySS_read()

dir

A file path to the directory of interest.Typically used withfile, an additional input argument,to specify input and output file paths.The default value isdir = NULL, which leads to usingthe current working directory, and thus, full file paths shouldnot be specified for other arguments as they will be appendedtodir.

overwrite

A logical value specifying if the existing file(s)should be overwritten. The default value isoverwrite = FALSE.

verbose

A logical value specifying if output should be printedto the screen.

Author(s)

Ian G. Taylor

See Also

Examples

## Not run: # read inputlist to modify the data fileinputlist <- SS_read(  dir = system.file("extdata", "simple_3.30.13", package = "r4ss"))# modify the starter file (use the par file)inputlist[["start"]][["init_values_src"]] <- 1# modify the data file (remove age comps from years prior to 1990)inputlist[["dat"]][["agecomp"]] <- inputlist[["dat"]][["agecomp"]] %>%  dplyr::filter(Yr >= 1990)# modify the control file (turn off early recdevs and change range of yrs)inputlist[["ctl"]][["recdev_early_phase"]] <-  -abs(inputlist[["ctl"]][["recdev_early_phase"]])inputlist[["ctl"]][["MainRdevYrFirst"]] <- 1980# write the files to a new folder within the source directorySS_write(  inputlist = inputlist,  dir = file.path(inputlist[["dir"]], "modified_inputs"))## End(Not run)

Write Stock Synthesis control file

Description

Write Stock Synthesis control file from list object in R which was probablycreated usingSS_readctl(). This function is awrapper which calls either SS_writectl_3.24 or SS_writectl_3.30(and potentially additional functions in the future).

Usage

SS_writectl(  ctllist,  outfile,  version = "3.30",  overwrite = FALSE,  verbose = FALSE)

Arguments

ctllist

List object created bySS_readdat().

outfile

Filename for where to write new control file.

version

SS version number. Currently "3.24" or "3.30" are supported,either as character or numeric values (noting that numeric 3.30 = 3.3).version = NULL is no longer the default or an allowed entry.The default isversion = "3.30".

overwrite

Should existing files be overwritten? Defaults to FALSE.

verbose

Should there be verbose output while running the file?Defaults to FALSE.

Author(s)

Ian G. Taylor, Yukio Takeuchi, Gwladys I. Lambert, Kathryn Doering

See Also

SS_writedat_3.24(),SS_writedat_3.30(),SS_readdat(),SS_readstarter(),SS_writestarter(),SS_readforecast(),SS_writeforecast()


write control file

Description

write Stock Synthesis control file from list object in R which was probablycreated usingSS_readctl()

Usage

SS_writectl_3.24(  ctllist,  outfile,  overwrite = FALSE,  verbose = FALSE,  nseas = lifecycle::deprecated(),  N_areas = lifecycle::deprecated(),  Do_AgeKey = lifecycle::deprecated())

Arguments

ctllist

List object created bySS_readctl().

outfile

Filename for where to write new data file.

overwrite

Should existing files be overwritten? Default=FALSE.

verbose

Should there be verbose output while running the file?Defaults to FALSE.

nseas

Deprecated. number of season in the model. This information is notexplicitly available in control file

N_areas

Deprecated. number of spatial areas in the model. This information is also notexplicitly available in control file

Do_AgeKey

Deprecated. Flag to indicate if 7 additional ageing error parameters to be readset 1 (but in fact any non zero numeric in R) or TRUE to enable to read them 0 or FALSE (default)to disable them. This information is not explicitly available in control file, too.

Author(s)

Yukio Takeuchi

See Also

SS_readctl(),SS_readctl_3.24(),SS_readstarter(),


write control file for SS version 3.30

Description

write Stock Synthesis control file from list object in R which was createdusingSS_readctl().This function is designed to be calledusingSS_writectl() and should not be called directly.

Usage

SS_writectl_3.30(ctllist, outfile, overwrite = FALSE, verbose = FALSE)

Arguments

ctllist

List object created bySS_readctl().

outfile

Filename for where to write new data file.

overwrite

Should existing files be overwritten? Default=FALSE.

verbose

Should there be verbose output while running the file?Defaults to FALSE.

Author(s)

Kathryn Doering, Yukio Takeuchi, Neil Klaer, Watal M. Iwasaki

See Also

SS_readctl(),SS_readctl_3.30(),SS_readstarter(),SS_readforecast(),SS_writestarter(),SS_writeforecast(),SS_writedat()


write Stock Synthesis data file

Description

Write Stock Synthesis data file from list object in R which was probablycreated usingSS_readdat(). This function is awrapper which calls either SS_writedat_3.24 or SS_writedat_3.30(and potentially additional functions in the future). This setup allows thosefunctions to be cleaner (if somewhat redundant) than a single function thatattempts to do everything.

Usage

SS_writedat(  datlist,  outfile,  version = "3.30",  overwrite = FALSE,  faster = FALSE,  verbose = TRUE)

Arguments

datlist

List object created bySS_readdat()(or bySS_readdat_3.24() orSS_readdat_3.24())

outfile

Filename for where to write new data file.

version

SS version number. Currently only "3.24" or "3.30" are supported,either as character or numeric values (noting that numeric 3.30 = 3.3).

overwrite

Should existing files be overwritten? Default=FALSE.

faster

Speed up writing by writing length and age comps without aligningthe columns (by using write.table instead of print.data.frame)

verbose

Should there be verbose output while running the file?

Author(s)

Ian G. Taylor, Yukio Takeuchi, Gwladys I. Lambert

See Also

SS_writedat_3.24(),SS_writedat_3.30(),SS_readdat(),SS_readstarter(),SS_writestarter(),SS_readforecast(),SS_writeforecast()


write data file for SS version 3.24

Description

Write Stock Synthesis data file from list object in R which was probablycreated usingSS_readdat() (which would have called onSS_readdat_3.24()).

Usage

SS_writedat_3.24(  datlist,  outfile,  overwrite = FALSE,  faster = FALSE,  verbose = TRUE)

Arguments

datlist

List object created bySS_readdat().

outfile

Filename for where to write new data file.

overwrite

Should existing files be overwritten? Default=FALSE.

faster

Speed up writing by writing length and age comps without aligningthe columns (by using write.table instead of print.data.frame)

verbose

Should there be verbose output while running the file?

Author(s)

Ian G. Taylor, Yukio Takeuchi, Gwladys I. Lambert, Kelli F. Johnson,Chantel R. Wetzel

See Also

SS_writedat(),SS_writedat_3.30(),SS_readdat(),SS_readstarter(),SS_writestarter(),SS_readforecast(),SS_writeforecast()


write data file for SS version 3.30

Description

Write Stock Synthesis data file from list object in R which was probablycreated usingSS_readdat() (which would have called onSS_readdat_3.30()).

Usage

SS_writedat_3.30(  datlist,  outfile,  overwrite = FALSE,  faster = FALSE,  verbose = TRUE)

Arguments

datlist

List object created bySS_readdat().

outfile

Filename for where to write new data file.

overwrite

Should existing files be overwritten? Default=FALSE.

faster

Speed up writing by writing length and age comps without aligningthe columns (by using write.table instead of print.data.frame)

verbose

Should there be verbose output while running the file?

Author(s)

Ian G. Taylor, Yukio Takeuchi, Gwladys I. Lambert, Kelli F. Johnson,Chantel R. Wetzel

See Also

SS_writedat(),SS_writedat_3.24(),SS_readdat(),SS_readstarter(),SS_writestarter(),SS_readforecast(),SS_writeforecast()


write forecast file

Description

write Stock Synthesis forecast file from list object in R which was probablycreated usingSS_readforecast()

Usage

SS_writeforecast(  mylist,  dir = NULL,  file = "forecast.ss",  writeAll = FALSE,  overwrite = FALSE,  verbose = TRUE)

Arguments

mylist

List object created bySS_readforecast().

dir

Directory for new forecast file. Default=NULL (workingdirectory).

file

Filename for new forecast file. Default="forecast.ss".

writeAll

Should the function continue even if Forecast=0(at which point SS stops reading, and remaining elements in list may not beavailable, depending on settings used in SS_readforecast)

overwrite

Should existing files be overwritten? Default=FALSE.

verbose

Should there be verbose output while running the file?Default=TRUE.

Author(s)

Ian Taylor

See Also

SS_readstarter(),SS_readforecast(),SS_readdat(),SS_writestarter(),SS_writedat()


write ss.par file from SS version 3.24

Description

Write Stock Synthesis (version 3.24) parameter file from list object in R to file.

Usage

SS_writepar_3.24(parlist, outfile, overwrite = TRUE, verbose = FALSE)

Arguments

parlist

List object created bySS_readpar_3.24().

outfile

Filename for where to write new parameter file.

overwrite

Should existing files be overwritten? Default=TRUE.

verbose

Should there be verbose output while running the file?

Author(s)

Nathan R. Vaughan

See Also

SS_readctl(),SS_readdat()SS_readdat_3.24(),SS_readdat_3.24()SS_readctl_3.24(),SS_readstarter(),SS_readforecast(),SS_writestarter(),SS_writeforecast(),SS_writedat()


write ss.par file from SS version 3.30

Description

Write Stock Synthesis (version 3.30) parameter file from list object in R to file.

Usage

SS_writepar_3.30(parlist, outfile, overwrite = TRUE, verbose = FALSE)

Arguments

parlist

List object created bySS_readpar_3.30().

outfile

Filename for where to write new parameter file.

overwrite

Should existing files be overwritten? Default=TRUE.

verbose

Should there be verbose output while running the file?

Author(s)

Nathan R. Vaughan

See Also

SS_readctl(),SS_readdat()SS_readdat_3.24(),SS_readdat_3.30()SS_readctl_3.24(),SS_readstarter(),SS_readforecast(),SS_writestarter(),SS_writeforecast(),SS_writedat()


write starter file

Description

write Stock Synthesis starter file from list object in R which was probablycreated usingSS_readstarter()

Usage

SS_writestarter(  mylist,  dir = NULL,  file = "starter.ss",  overwrite = FALSE,  verbose = TRUE,  warn = TRUE)

Arguments

mylist

List object created bySS_readstarter().

dir

Directory for new starter file. Default=NULL (working directory).

file

Filename for new starter file. Default="starter.ss".

overwrite

Should existing files be overwritten? Default=FALSE.

verbose

Should there be verbose output while running the file?Default=TRUE.

warn

Print warning if overwriting file?

Author(s)

Ian Taylor

See Also

SS_readstarter(),SS_readforecast(),SS_writestarter(),SS_writeforecast(),SS_writedat()


Write weight-at-age file

Description

Write Stock Synthesis weight-at-age file from R object that was probablycreated usingSS_readwtatage()

Usage

SS_writewtatage(  mylist,  dir = NULL,  file = "wtatage.ss",  overwrite = FALSE,  verbose = TRUE,  warn = TRUE)

Arguments

mylist

Object created bySS_readwtatage().

dir

A file path to the directory of interest.Typically used withfile, an additional input argument,to specify input and output file paths.The default value isdir = NULL, which leads to usingthe current working directory, and thus, full file paths shouldnot be specified for other arguments as they will be appendedtodir.

file

Filename for new weight-at-age file, whichwill be appended todir to create a full file path.Default="wtatage.ss".

overwrite

A logical value specifying if the existing file(s)should be overwritten. The default value isoverwrite = FALSE.

verbose

A logical value specifying if output should be printedto the screen.

warn

A logical value specifying if a warning should begenerated if overwritingfile.The default value iswarn = TRUE.

Author(s)

Kelli F. Johnson

See Also

SS_readwtatage()


A function to create a table of biology for assessment reporting:length, weight, % mature, fecundity, and selectivity

Description

Takes the object created by SS_output to create table for reportingfor West Coast groundfish. Works with Stock Synthesis versions 3.30.12and later.

Usage

SSbiologytables(  replist = NULL,  printfolder = "tables",  dir = "default",  fleetnames = "default",  selexyr = "default")

Arguments

replist

A list object created bySS_output().

printfolder

The sub-directory under 'dir' (see below) in which thePNG files will be located. The default sub-directory is "plots".The directory will be created if it doesn not exist.If 'printfolder' is set to "", it is ignored and the PNG files willbe located in the directory specified by 'dir'.

dir

The directory in which a PDF file (if requested) will be createdand within which the printfolder sub-directory (see above) will be createdif png=TRUE. By default it will be the same directory that the report filewas read from by theSS_output function. Alternatives to the defaultcan be either relative (to the working directory) or absolute paths.The function will attempt to create the directory it does not exist, but itdoes not do so recursively.

fleetnames

Either the string "default", or a vector of charactersstrings to use for each fleet name. Default="default".

selexyr

The year to summarize selectivity, the default is the finalmodel yr strings to use for each fleet name. Default="default".

Value

A csv files containing biology and selectivity tables

Author(s)

Chantel Wetzel


Fit models to parametric bootstraps

Description

Run a series of models fit to parametric bootstrap data taken fromdata.ss_new. This is not yet a generalized function, just some example codefor how to do a parametric bootstrap such as was done for the Pacific hakemodel in 2006.

Usage

SSbootstrap()

Note

Thanks to Nancie Cummings for inspiration.

Author(s)

Ian Taylor


Convert Time-Steps

Description

Function to convert non-annual into annual time-steps for retros and cpue residuals

Usage

SSdiagsTime2Year(ss3out, time.steps = 0.25, end.time)

Arguments

ss3out

outputs from r4ss::SS_output() or r4ss::SSsummarize()

time.steps

time steps behind yrs e.g. 0.25 for quarterly

end.time

last time step e.g. 2018.75 with a cpue observation

Value

Reformatted Rep file outputs


A function to create a executive summary tables from an SS Report.sso file

Description

Takes the output from SS_output and creates executive summary tablesas required by the current Terms of Reference for US West Coastgroundfish stock. Additionally, historical catches, time-series and numbers-at-ages tables are created.

Usage

SSexecutivesummary(  replist,  plotfolder = "default",  ci_value = 0.95,  es_only = FALSE,  fleetnames = NULL,  tables = c("a", "b", "c", "d", "e", "f", "g", "h", "i", "catch", "timeseries",    "numbers", "biomass", "likes"),  divide_by_2 = FALSE,  endyr = NULL,  adopted_ofl = NULL,  adopted_abc = NULL,  adopted_acl = NULL,  forecast_ofl = NULL,  forecast_abc = NULL,  format = TRUE,  match_digits = FALSE,  verbose = TRUE)

Arguments

replist

A list object created bySS_output().

plotfolder

Directory where the 'tables' directory will be created.The default is the dir location where the Report.sso file is located.

ci_value

To calculate confidence intervals, default is set at 0.95

es_only

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

fleetnames

A vector of user-defined names providing a name for each fleet in the model.

tables

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

divide_by_2

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

endyr

Optional input to choose a different ending year for tables(could be useful for catch-only updates)

adopted_ofl

Vector of adopted ofl values to be printed in the management performancetable. This should be a vector of 10 values.

adopted_abc

Vector of adopted abc values to be printed in the management performancetable. This should be a vector of 10 values.

adopted_acl

Vector of adopted acl values to be printed in the management performancetable. This should be a vector of 10 values.

forecast_ofl

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

forecast_abc

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

format

Logical. Option to control whether tables are formatted (e.g. commas added, CIs separated with "-"). Theformatting is intended to create tables that can be cut and pasted easily into a word document without additional formattingwork. If the tables are being used by LaTex/Markdown or other documenting software, having formatting turned on preventsthe tables from being formatted further since the objects are no longer numeric.

match_digits

TRUE/FALSE switch on whether the low and high interval valuesin e_ReferencePoints_ES will be reported with the same number of decimal digitsas the estimate.

verbose

Return updates of function progress to the R console?

Value

Individual csv files for each executive summary table and additional tables (catch, timeseries, numbers-at-age).

Author(s)

Chantel Wetzel


Read MCMC output.

Description

Reads the MCMC output (in the posteriors.sso and derived_posteriors.ssofiles) from a model.

Usage

SSgetMCMC(  dir = NULL,  verbose = TRUE,  writecsv = FALSE,  postname = "posteriors.sso",  derpostname = "derived_posteriors.sso",  csv1 = "keyposteriors.csv",  csv2 = "nuisanceposteriors.csv",  keystrings = c("NatM", "R0", "steep", "RecrDev_2008", "Q_extraSD"),  nuisancestrings = c("Objective_function", "SSB_", "InitAge", "RecrDev"),  burnin = 0,  thin = 1)

Arguments

dir

Directory containing MCMC output.

verbose

TRUE/FALSE switch to get more or less information about theprogress of the function.

writecsv

Write key parameters and certainty nuisance quantities to aCSV file.

postname

Name of file with parameter posteriors (default matches"posteriors.sso" used by SS, but the user could change the name)

derpostname

Name of file with parameter posteriors (default matches"derived_posteriors.sso" used by SS, but the user could change the name)

csv1

First CSV file for key parameters.

csv2

Second CSV file for nuisance quantities.

keystrings

Vector of strings that partially match parameter names towrite to the file csv1. This file intended to feed intomcmc.out().

nuisancestrings

Vector of strings that partially match derivedquantity names to write to the file csv2. This file intended to feed intomcmc.nuisance().

burnin

Optional burn-in value to apply on top of the option in thestarter file.

thin

Optional thinning value to apply on top of the option in thestarter file and in the-mcsave runtime command.

Author(s)

Ian Taylor

See Also

mcmc.out(),mcmc.nuisance(),SSplotPars()


Get output from multiple Stock Synthesis models.

Description

Apply the functionSS_output() multiple times and save output asindividual objects or a list of lists.

Usage

SSgetoutput(  keyvec = NULL,  dirvec = NULL,  getcovar = TRUE,  getcomp = TRUE,  forecast = TRUE,  verbose = TRUE,  ncols = 210,  listlists = TRUE,  underscore = FALSE,  save.lists = FALSE)

Arguments

keyvec

A vector of strings that are appended to the output files fromeach model if models are all in one directory. Default=NULL.

dirvec

A vector of directories (full path or relative to workingdirectory) in which model output is located. Default=NULL.

getcovar

Choice to read or not read covar.sso output (saves time andmemory). Default=TRUE.

getcomp

Choice to read or not read CompReport.sso output (saves timeand memory). Default=TRUE.

forecast

Choice to read or not read forecast quantities.Default=FALSE.

verbose

Print various messages to the command line as the functionruns? Default=TRUE.

ncols

Maximum number of columns in Report.sso (same input as forSS_output()). Default=210.

listlists

Save output from each model as a element of a list (i.e.make a list of lists). Default = TRUE.

underscore

Add an underscore '_' between any file names and any keysin keyvec. Default=FALSE.

save.lists

Save each list of parsed output as a .Rdata file (with defaultfilenaming convention based on iteration and date stamp.

Author(s)

Ian Taylor

See Also

SS_output()SSsummarize()


Convert a matrix of natural mortality values intoinputs for Stock Synthesis

Description

Inspired by Valerio Bartolino and North Sea herring

Usage

SSmakeMmatrix(  mat,  startyr,  outfile = NULL,  overwrite = FALSE,  yrs.in.columns = TRUE)

Arguments

mat

a matrix of natural mortality by year and age, starting with age 0

startyr

the first year of the natural mortality values (no missing years)

outfile

optional file to which the results will be written

overwrite

if 'outfile' is provided and exists, option to overwrite or not

yrs.in.columns

an indicator of whether the matrix has years in columns or rows

Value

Prints inputs with option to write to chosen file

Author(s)

Ian Taylor


Calculate Mohn's Rho values for select quantities

Description

Function calculates:(1) a rho value for the ending year for each retrospective relative to the reference modelas in Mohn (1999),(2) a "Wood's Hole Mohn's Rho", which is a rho value averaged across all years for eachretrospective relative to the reference model, and(3) an "Alaska Fisheries Science Center and Hurtado-Ferro et al. (2015) Mohn's rho,which is the average rho per retrospective "peel".

Usage

SSmohnsrho(summaryoutput, endyrvec, startyr, verbose = TRUE)

Arguments

summaryoutput

List created bySSsummarize. The expected order for themodels are the full reference model, the retro -1, retro -2, and so forth.

endyrvec

Single year or vector of years representing thefinal year of values to show for each model.

startyr

Single year used to calculate the start of the Wood's HoleMohn's Rho value across all years. Defaults to startyr of reference model.

verbose

Print messages when running the function?

Author(s)

Chantel R. Wetzel and Carey McGilliard

References

Hurtado-Ferro et al. 2015. Looking in the rear-view mirror: biasand retrospective patterns in integrated, age-structured stock assessmentmodels. ICES J. Mar. Sci Volume 72, Issue 1, 1 January 2015,Pages 99-110, https://doi.org/10.1093/icesjms/fsu198Mohn, R. 1999. The retrospective problem in sequential population analysis:An investigation using cod fishery and simulated data. ICES J. Mar. SciVolume 56, Pages 473-488


Plot matrix of either length or observed age at true age

Description

Distribution of length at age or observed age at true age is representedas a histogram. Values are from the AGE_LENGTH_KEY and AGE_AGE_KEY sectionsof Report.sso ($ALK and $AAK in the list created by SS_output)

Usage

SSplotAgeMatrix(  replist,  option = 1,  slices = NULL,  scale = NULL,  add = FALSE,  col.grid = "grey90",  col.bars = grey(0, alpha = 0.5),  shift_hi = 0,  shift_lo = 0,  plot = TRUE,  print = FALSE,  labels = c("Age", "Length", "True age", "Observed age", "for ageing error type",    "Distribution of", "at"),  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1,  mainTitle = TRUE,  plotdir = "default")

Arguments

replist

A list object created bySS_output().

option

Switch set to either 1 for length at true age or2 for obs. age at true age

slices

Optional input to choose which matrix (slice of the 3D-array)within $AAK or $ALK to plot. By default all slices will be shown.For ageing imprecision this should correspond to the ageing error matrixnumber. Distribution of length at age ($ALK) is ordered by season,sub-season, and then morph. A future version could allow subsetting plotsby these dimensions.

scale

Multiplier for bars showing distribution. Species with many agesbenefit from expanded bars. NULL value causes function to attempt automaticscaling.

add

Add to existing plot

col.grid

A character value specifying the color of the grid lines

col.bars

The color of the filled polygons.

shift_hi

A numeric value specifying the amount to shift the top ofthe polygon up.

shift_lo

A numeric value specifying the amount to shift the bottomof the polygon up.

plot

Plot to active plot device?

print

Print to PNG files?

labels

Vector of labels for plots (titles and axis labels)

pwidth

Width of plot

pheight

Height of plot

punits

Units for PNG file

res

Resolution of plots printed to files.The default isres = 300.

ptsize

Point size for PNG file

cex.main

Character expansion for plot titles

mainTitle

Logical indicating if a title should be included at the top

plotdir

directory where PNG files will be written. by default it willbe the directory where the model was run.

Author(s)

Ian G. Taylor

See Also

SSplotNumbers()


Plot biology related quantities.

Description

Plot biology related quantities from Stock Synthesis model output, includingmean weight, maturity, fecundity, and spawning output.

Usage

SSplotBiology(  replist,  plot = TRUE,  print = FALSE,  add = FALSE,  subplots = 1:32,  seas = 1,  morphs = NULL,  forecast = FALSE,  minyr = -Inf,  maxyr = Inf,  colvec = c("red", "blue", "grey20"),  ltyvec = c(1, 2),  shadealpha = 0.1,  imageplot_text = FALSE,  imageplot_text_round = 0,  legendloc = "topleft",  plotdir = "default",  labels = c("Length (cm)", "Age (yr)", "Maturity", "Mean weight (kg) in last year",    "Spawning output", "Length (cm, beginning of the year)", "Natural mortality",    "Female weight (kg)", "Female length (cm)", "Fecundity", "Default fecundity label",    "Year", "Hermaphroditism transition rate", "Fraction females by age at equilibrium"),  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1,  mainTitle = TRUE,  verbose = TRUE)

Arguments

replist

A list object created bySS_output().

plot

Plot to active plot device?

print

Print to PNG files?

add

add to existing plot

subplots

vector controlling which subplots to createNumbering of subplots is as follows:

  • 1 growth curve only

  • 2 growth curve with CV and SD

  • 3 growth curve with maturity and weight

  • 4 distribution of length at age (still in development)

  • 5 length or wtatage matrix

  • 6 maturity

  • 7 fecundity from model parameters

  • 8 fecundity at weight from BIOLOGY section

  • 9 fecundity at length from BIOLOGY section

  • 10 spawning output at length

  • 11 spawning output at age

  • 21 Natural mortality (if age-dependent)

  • 22 Time-varying growth persp

  • 23 Time-varying growth contour

  • 24 plot time-series of any time-varying quantities (created if theMGparm_By_Year_after_adjustments table (report:7) is available in theReport.sso file)

  • 31 hermaphroditism transition probability

  • 32 hermaphroditism cumulative probability

Additional plots not created by default

  • 101 diagram with labels showing female growth curve

  • 102 diagram with labels showing female growth curve & male offsets

  • 103 diagram with labels showing female CV = f(A) (offset type 2)

  • 104 diagram with labels showing female CV = f(A) & male offset (type 2)

  • 105 diagram with labels showing female CV = f(A) (offset type 3)

  • 106 diagram with labels showing female CV = f(A) & male offset (type 3)

seas

which season to plot (values other than 1 only work inseasonal models but but maybe not fully implemented)

morphs

Which morphs to plot (if more than 1 per sex)? By default thiswill bereplist[["mainmorphs"]]

forecast

Include forecast years in plots of time-varying biology?

minyr

optional input for minimum year to show in plots

maxyr

optional input for maximum year to show in plots

colvec

vector of length 3 with colors for various points/lines

ltyvec

vector of length 2 with lty for females/males in growth plotsvalues can be applied to other plots in the future

shadealpha

Transparency parameter used to make default shadecolvalues (see ?rgb for more info)

imageplot_text

Whether to add numerical text to the image plotswhen using weight at age. Defaults to FALSE.

imageplot_text_round

The number of significant digits to whichthe image plot text is rounded. Defaults to 0, meaning whole numbers. Ifall your values are small and there's no contrast in the text, you mightwant to make this 1 or 2.

legendloc

Location of legend (see ?legend for more info)

plotdir

Directory where PNG files will be written. by default it willbe the directory where the model was run.

labels

Vector of labels for plots (titles and axis labels)

pwidth

Width of plot

pheight

Height of plot

punits

Units for PNG file

res

Resolution of plots printed to files.The default isres = 300.

ptsize

Point size for PNG file

cex.main

Character expansion for plot titles

mainTitle

Logical indicating if a title should be included at the top

verbose

Return updates of function progress to the R GUI?

Author(s)

Ian Stewart, Ian Taylor

See Also

SS_plots(),SS_output()


Plot catch related quantities.

Description

Plot catch related quantities from Stock Synthesis output. Plots includeharvest rate, continuous F, landings, and discard fraction.

Usage

SSplotCatch(  replist,  subplots = 1:16,  add = FALSE,  areas = 1,  plot = TRUE,  print = FALSE,  type = "l",  fleetlty = 1,  fleetpch = 1,  fleetcols = "default",  fleetnames = "default",  lwd = 3,  areacols = "default",  areanames = "default",  minyr = -Inf,  maxyr = Inf,  annualcatch = TRUE,  forecastplot = FALSE,  plotdir = "default",  showlegend = TRUE,  legendloc = "topleft",  order = "default",  xlab = "Year",  labels = c("Harvest rate/Year", "Continuous F", "Landings", "Total catch",    "Predicted discards", "Discard fraction", "(mt)", "(numbers x1000)",    "Observed and expected", "aggregated across seasons"),  catchasnumbers = NULL,  catchbars = TRUE,  addmax = TRUE,  ymax = NULL,  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1,  verbose = TRUE)

Arguments

replist

A list object created bySS_output().

subplots

Vector controlling which subplots to createNumbering of subplots is as follows,

Basic plots for all models

  • 1 landings

  • 2 landings stacked

  • 3 observed and expected landings (if different)

  • 9 harvest rate

Plots for models with discards

  • 4 total catch (including discards)

  • 5 total catch (including discards) stacked

  • 6 discards

  • 7 discards stacked plot (depends on multiple fleets)

  • 8 discard fraction

  • 16 landings + dead discards

Plots for seasonal models

  • 10 landings aggregated across seasons

  • 11 landings aggregated across seasons stacked

  • 12 total catch (if discards present) aggregated across seasons

  • 13 total catch (if discards present) aggregated across seasons stacked

  • 14 discards aggregated across seasons

  • 15 discards aggregated across seasons stacked

add

Add to existing plot? (not yet implemented)

areas

Optional subset of areas to plot for spatial models

plot

Plot to active plot device?

print

Print to PNG files?

type

Type parameter passed to plot function. Default "l" is linesonly. Other options include "o" for overplotting points on lines.

fleetlty

Vector of line type by fleet

fleetpch

Vector of plot character by fleet

fleetcols

Vector of colors by fleet

fleetnames

Optional replacement for fleenames used in data file,should include all fleets (not just those with catch)

lwd

Line width

areacols

Vector of colors by area. Default uses rich.colors by ArniMagnusson

areanames

Names for areas. Default is to use Area1, Area2,...

minyr

Optional input for minimum year to show in plots

maxyr

Optional input for maximum year to show in plots

annualcatch

Include plot of catch aggregated across seasons withineach year

forecastplot

Add points from forecast years

plotdir

Directory where PNG or PDF files will be written. By defaultit will be the directory where the model was run.

showlegend

Put legend on plot

legendloc

Location of legend (see ?legend for more info)

order

Optional input to change the order of fleets in stacked plots.

xlab

x-label for all plots

labels

Vector of labels for plots (titles and axis labels)

catchasnumbers

Is catch in numbers instead of biomass? Should be setautomatically if set to NULL. If fleets include a mix of biomass andnumbers, then catch plots should be interpreted carefully.

catchbars

Show catch by fleet as barplot instead of stacked polygons?(default=TRUE)

addmax

Add a point on the y-axis for the maximum catch (default=TRUE)

ymax

Optional input for ymax value (can be used to add or subtractwhite space at the top of the figure)

pwidth

Width of plot

pheight

Height of plot

punits

Units for PNG file

res

Resolution of plots printed to files.The default isres = 300.

ptsize

point size for PNG file

cex.main

Character expansion for plot titles

verbose

Report progress to R console?

Author(s)

Ian Taylor, Ian Stewart

See Also

SS_plots(),SS_output()


Plot cumulative catch by cohort.

Description

Cumulative catch contributions for each cohort are plotted based onestimated catch-at-age matrix and weight-at-age values by fleet. Curves areshown in units of both numbers and biomass.

Usage

SSplotCohortCatch(  replist,  subplots = 1:2,  add = FALSE,  plot = TRUE,  print = FALSE,  cohortcols = "default",  cohortfrac = 1,  cohortvec = NULL,  cohortlabfrac = 0.1,  cohortlabvec = NULL,  lwd = 3,  plotdir = "default",  xlab = "Year",  labels = c("Age", "Cumulative catch by cohort (in numbers x1000)",    "Cumulative catch by cohort (x1000 mt)"),  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1,  verbose = TRUE)

Arguments

replist

A list object created bySS_output().

subplots

Vector controlling which subplots to create

add

Add to existing plot? (not yet implemented)

plot

Plot to active plot device?

print

Print to PNG files?

cohortcols

Vector of colors to show for each cohort. Default is rangeof colors shade indicating time period.

cohortfrac

What fraction of the cohorts to include in plot. If value< 1 is used, then cohorts are filtered to only include those with thehighest maximum cumulative catch. Value will be overridden bycohortvec.

cohortvec

Optional vector of birth years for cohorts to include inplot. Value overridescohortfrac.

cohortlabfrac

What fraction of the cohorts to label in plot. Bydefault, top 10% of cohorts are labeled. Value will be overridden bycohortlabvec.

cohortlabvec

Optional vector of birth years for cohorts to label inplot. Value overridescohortlabfrac.

lwd

Line width

plotdir

Directory where PNG or PDF files will be written. By defaultit will be the directory where the model was run.

xlab

x-label for all plots

labels

Vector of labels for plots (titles and axis labels)

pwidth

Width of plot

pheight

Height of plot

punits

Units for PNG file

res

Resolution of plots printed to files.The default isres = 300.

ptsize

point size for PNG file

cex.main

Character expansion for plot titles (no titles in thisfunction yet)

verbose

Report progress to R console?

Author(s)

Ian Taylor

See Also

SS_plots(),SS_output()


plot model comparisons

Description

Creates a user-chosen set of plots comparing model output from a summary ofmultiple models, where the collection was created using theSSsummarize function.

Usage

SSplotComparisons(  summaryoutput,  subplots = 1:20,  plot = TRUE,  print = FALSE,  png = print,  pdf = FALSE,  models = "all",  endyrvec = NULL,  indexfleets = NULL,  indexUncertainty = TRUE,  indexQlabel = TRUE,  indexQdigits = 4,  indexSEvec = NULL,  indexPlotEach = FALSE,  labels = c("Year", "Spawning biomass (t)", "Fraction of unfished",    "Age-0 recruits (1,000s)", "Recruitment deviations", "Index", "Log index",    "SPR-related quantity", "Density", "Management target",    "Minimum stock size threshold", "Spawning output", "Harvest rate"),  col = NULL,  shadecol = NULL,  pch = NULL,  lty = 1,  lwd = 2,  spacepoints = 10,  staggerpoints = 1,  initpoint = 0,  tickEndYr = TRUE,  shadeForecast = TRUE,  xlim = NULL,  ylimAdj = 1.05,  xaxs = "i",  yaxs = "i",  type = "o",  uncertainty = TRUE,  shadealpha = 0.1,  legend = TRUE,  legendlabels = NULL,  legendloc = "topright",  legendorder = NULL,  legendncol = 1,  sprtarg = NULL,  btarg = NULL,  minbthresh = NULL,  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  plotdir = NULL,  filenameprefix = "",  densitynames = c("SSB_Virgin", "R0"),  densityxlabs = NULL,  rescale = TRUE,  densityscalex = 1,  densityscaley = 1,  densityadjust = 1,  densitysymbols = TRUE,  densitytails = TRUE,  densitymiddle = FALSE,  densitylwd = 1,  fix0 = TRUE,  new = TRUE,  add = FALSE,  par = list(mar = c(5, 4, 1, 1) + 0.1),  verbose = TRUE,  mcmcVec = FALSE,  show_equilibrium = TRUE)

Arguments

summaryoutput

List created bySSsummarize

subplots

Vector of subplots to be createdNumbering of subplots is as follows:

  • 1 spawning biomass

  • 2 spawning biomass with uncertainty intervals

  • 3 biomass ratio (hopefully equal to fraction of unfished)

  • 4 biomass ratio with uncertainty

  • 5 SPR ratio

  • 6 SPR ratio with uncertainty

  • 7 F value

  • 8 F value with uncertainty

  • 9 recruits

  • 10 recruits with uncertainty

  • 11 recruit devs

  • 12 recruit devs with uncertainty

  • 13 index fits

  • 14 index fits on a log scale

  • 15 phase plot

  • 16 densities

  • 17 cumulative densities

plot

Plot to active plot device?

print

Send plots to PNG files in directory specified byplotdir?

png

Has same result asprint, included for consistency withSS_plots.

pdf

Write output to PDF file? Can't be used in conjunction withpng orprint.

models

Optional subset of the models described insummaryoutput. Either "all" or a vector of numbers indicatingcolumns in summary tables.

endyrvec

Optional single year or vector of years representing thefinal year of values to show for each model. By default it is set to theending year specified in each model.

indexfleets

Fleet numbers for each model to compareindices of abundance. Can take different forms:

  • NULL: (default) create a separate plot for each index as long as the fleetnumbering is the same across all models.

  • integer: create a single comparison plot for the chosen index

  • vector of length equal to number of models: a single fleet numberfor each model to be compared in a single plot

  • list: list of fleet numbers associated with indices within eachmodel to be compared, where the list elements are each a vector of thesame length but the names of the list elements don't matter and can beabsent.

indexUncertainty

Show uncertainty intervals on index data?Default=FALSE because if models have any extra standard deviations added,these intervals may differ across models.

indexQlabel

Add catchability to legend in plot of index fits(TRUE/FALSE)?

indexQdigits

Number of significant digits for catchability in legend(ifindexQlabel = TRUE)

indexSEvec

Optional replacement for the SE values insummaryoutput[["indices"]] to deal with the issue of differing uncertainty bymodels described above.

indexPlotEach

TRUE plots the observed index for each model withcolors, or FALSE just plots observed once in black dots.

labels

Vector of labels for plots (titles and axis labels)

col

Optional vector of colors to be used for lines. Input NULLmakes use ofrich.colors.short function.

shadecol

Optional vector of colors to be used for shading uncertaintyintervals. The default (NULL) is to use the same colors provided bycol (either the default or a user-chosen input) and make themmore transparent by applying theshadealpha input as an alphatransparency value (using theadjustcolor() function)

pch

Optional vector of plot character values

lty

Optional vector of line types

lwd

Optional vector of line widths

spacepoints

Number of years between points shown on top of lines (forlong timeseries, points every year get mashed together)

staggerpoints

Number of years to stagger the first point (ifspacepoints > 1) for each line (so that adjacent lines have points indifferent years)

initpoint

Year value for first point to be added to lines.Points added to plots are those that satisfy(Yr-initpoint)%%spacepoints == (staggerpoints*iline)%%spacepoints

tickEndYr

TRUE/FALSE switch to turn on/off extra axis mark at finalyear in timeseries plots.

shadeForecast

TRUE/FALSE switch to turn on off shading of years beyondthe maximum ending year of the models

xlim

Optional x limits

ylimAdj

Multiplier for ylim parameter. Allows additional white spaceto fit legend if necessary. Default=1.05.

xaxs

Choice of xaxs parameter (see ?par for more info)

yaxs

Choice of yaxs parameter (see ?par for more info)

type

Type parameter passed to points (default 'o' overplots points ontop of lines)

uncertainty

Show plots with uncertainty intervals? Either a singleTRUE/FALSE value, or a vector of TRUE/FALSE values for each model,or a set of integers corresponding to the choice of models.

shadealpha

Transparency adjustment used to make default shadecolvalues (implemented asadjustcolor(col=col, alpha.f=shadealpha))

legend

Add a legend?

legendlabels

Optional vector of labels to include in legend. Defaultis 'model1','model2',etc.

legendloc

Location of legend. Either a string like "topleft" or avector of two numeric values representing the fraction of the maximum inthe x and y dimensions, respectively. Seehelp("legend") for more info onthe string options.

legendorder

Optional vector of model numbers that can be used to havethe legend display the model names in an order that is different than thatwhich is represented in the summary input object.

legendncol

Number of columns for the legend.

sprtarg

Target value for SPR-ratio where line is drawn in the SPRplots and phase plot.

btarg

Target biomass value at which to show a line (set to 0 toremove)

minbthresh

Minimum biomass threshold at which to show a line (set to0 to remove)

pwidth

Default width of plots printed to files in units ofpunits. The default ispwidth=6.5.

pheight

Height of plots printed to png files in units ofpunits.Default is designed to allow two plots per page, withpheight_tall usedfor plots that work best with a taller format and a single plot per page.

punits

Units forpwidth andpheight. Can be "px"(pixels), "in" (inches), "cm" (centimeters), or "mm" (millimeters).The default ispunits="in".

res

Resolution of plots printed to files.The default isres = 300.

ptsize

Point size for plotted text in plots printed to files (seehelp("png") in R for details).

plotdir

Directory where PNG or PDF files will be written. By defaultit will be the directory where the model was run.

filenameprefix

Additional text to append to PNG or PDF file names.It will be separated from default name by an underscore.

densitynames

Vector of names (or subset of names) of parameters orderived quantities contained insummaryoutput[["pars"]][["Label"]] orsummaryoutput[["quants"]][["Label"]] for which to make density plots

densityxlabs

Optional vector of x-axis labels to use in the densityplots (must be equal in length to the printed vector of quantities thatmatch thedensitynames input)

rescale

TRUE/FALSE control of automatic rescaling of units intothousands, millions, or billions

densityscalex

Scalar for upper x-limit in density plots (values below1 will cut off the right tail to provide better contrast among narrowerdistributions

densityscaley

Scalar for upper y-limit in density plots (values below1 will cut off top of highest peaks to provide better contrast among broaderdistributions

densityadjust

Multiplier on bandwidth of kernel in density functionused for smoothing MCMC posteriors. See 'adjust' in ?density for details.

densitysymbols

Add symbols along lines in density plots. Quantilesarec(0.025,0.1,0.25,0.5,0.75,0.9,0.975).

densitytails

Shade tails outside of 95% interval darker indensity plots?

densitymiddle

Shade middle inside of 95% interval darker indensity plots?

densitylwd

Line width for density plots

fix0

Always include 0 in the density plots?

new

Create new empty plot window

add

Allows single plot to be added to existing figure. This needs tobe combined with specific 'subplots' input to make sure only one thing getsadded.

par

list of graphics parameter values passed to theparfunction

verbose

Report progress to R GUI?

mcmcVec

Vector of TRUE/FALSE values (or single value) indicatingwhether input values are from MCMC or to use normal distribution aroundMLE

show_equilibrium

Whether to show the equilibrium values forSSB. For some model comparisons, these might not be comparable and thususeful to turn off. Defaults to TRUE.

Author(s)

Ian G. Taylor, John R. Wallace

See Also

SS_plots(),SSsummarize(),SS_output(),SSgetoutput()

Examples

## Not run: # directories where models were run need to be defineddir1 <- "c:/SS/mod1"dir2 <- "c:/SS/mod2"# read two modelsmod1 <- SS_output(dir = dir1)mod2 <- SS_output(dir = dir2)# create list summarizing model resultsmod.sum <- SSsummarize(list(mod1, mod2))# plot comparisonsSSplotComparisons(mod.sum, legendlabels = c("First model", "Second model"))# Example showing comparison of MLE to MCMC results where the mcmc would have# been run in the subdirectory 'c:/SS/mod1/mcmc'mod1 <- SS_output(dir = "c:/SS/mod1", dir.mcmc = "mcmc")# pass the same model twice to SSsummarize in order to plot it twicemod.sum <- SSsummarize(list(mod1, mod1))# compare MLE to MCMCSSplotComparisons(mod.sum,  legendlabels = c("MCMC", "MLE"),  mcmcVec = c(TRUE, FALSE))## End(Not run)

Plot composition data and fits.

Description

Plot composition data and fits from Stock Synthesis output. Multi-figureplots depend onmake_multifig.

Usage

SSplotComps(  replist,  subplots = c(1:10, 21, 24),  kind = "LEN",  sizemethod = 1,  aalyear = -1,  aalbin = -1,  plot = TRUE,  print = FALSE,  fleets = "all",  fleetnames = "default",  sexes = "all",  yupper = 0.4,  datonly = FALSE,  samplesizeplots = TRUE,  compresidplots = TRUE,  bub = FALSE,  showyears = TRUE,  showsampsize = TRUE,  showeffN = TRUE,  aggregates_by_mkt = FALSE,  sampsizeline = FALSE,  effNline = FALSE,  minnbubble = 3,  pntscalar = NULL,  scalebubbles = FALSE,  cexZ1 = 1.5,  bublegend = TRUE,  colvec = c(rgb(1, 0, 0, 0.7), rgb(0, 0, 1, 0.7), rgb(0.1, 0.1, 0.1, 0.7)),  linescol = c(rgb(0, 0.5, 0, 0.7), rgb(0.8, 0, 0, 0.7), rgb(0, 0, 0.8, 0.7)),  xlas = 0,  ylas = NULL,  axis1 = NULL,  axis2 = NULL,  axis1labs = NULL,  sizebinlabs = NULL,  blue = rgb(0, 0, 1, 0.7),  red = rgb(1, 0, 0, 0.7),  pwidth = 6.5,  pheight = 6.5,  punits = "in",  ptsize = 10,  res = 300,  plotdir = "default",  cex.main = 1,  linepos = 1,  fitbar = FALSE,  do.sqrt = TRUE,  smooth = TRUE,  cohortlines = c(),  labels = c("Length (cm)", "Age (yr)", "Year", "Observed sample size",    "Effective sample size", "Proportion", "cm", "Frequency", "Weight", "Length", "(mt)",    "(numbers x1000)", "Stdev (Age)", "Conditional AAL plot, ", "Size bin"),  printmkt = TRUE,  printsex = TRUE,  maxrows = 6,  maxcols = 4,  maxrows2 = 4,  maxcols2 = 4,  rows = 1,  cols = 1,  andre_oma = c(3, 0, 3, 0),  andrerows = 4,  fixdims = TRUE,  fixdims2 = FALSE,  maxneff = 5000,  verbose = TRUE,  scalebins = FALSE,  addMeans = TRUE,  mainTitle = FALSE,  ...)

Arguments

replist

A list object created bySS_output().

subplots

vector controlling which subplots to createNumbering of subplots is as follows, where subplots 21 to 24(aggregated across years) are provided first, and subplots1 to 10 are all repeated for each fleet

  • 1 index data by fleet

  • 1 multi-panel composition plot

  • 2 single panel bubble plot for numbers at length or age

  • 3 multi-panel bubble plots for conditional age-at-length

  • 4 multi-panel plot of fit to conditional age-at-length for specific years

  • 5 Pearson residuals for A-L key

  • 6 multi-panel plot of point and line fit to conditionalage-at-length for specific length bins

  • 7 sample size plot

  • 8 TA1.8 Francis weighting plot

  • 9 TA1.8 Francis weighting plot for conditional data

  • 10 Andre's mean age and std. dev. in conditional AAL

  • 21 composition by fleet aggregating across years

  • 22 composition by fleet aggregating across years within each season

  • 23 composition by fleet aggregating across seasons within a year

  • 24 bubble plot comparison of length or age residuals

kind

indicator of type of plot can be "LEN", "SIZE", "AGE", "cond","GSTAGE", "GSTLEN", "L@A", or "W@A".

sizemethod

if kind = "SIZE" then this switch chooses which of thegeneralized size bin methods will be plotted.

aalyear

Years to plot multi-panel conditional age-at-length fits forall length bins; must be in a "c(YYYY,YYYY)" format. Useful for checking thefit of a dominant year class, critical time period, etc. Default=-1.

aalbin

The length bin for which multi-panel plots of the fit toconditional age-at-length data will be produced for all years. Useful tosee if growth curves are ok, or to see the information on year classes movethrough the conditional data. Default=-1.

plot

plot to active plot device?

print

print to PNG files?

fleets

optional vector to subset fleets for which plots will be made

fleetnames

optional vector of fleet names to put in the labels

sexes

which sexes to show plots for. Default="all" which will includemales, females, and unsexed. This option is not fully implemented for allplots.

yupper

upper limit on ymax for polygon/histogram composition plots

datonly

make plots of data without fits?

samplesizeplots

make sample size plots?

compresidplots

make plots of residuals for fit to composition data?

bub

make bubble plot for numbers at age or size?

showyears

Add labels for years to sample size plots?

showsampsize

add sample sizes to plot

showeffN

add effective sample sizes to plot

aggregates_by_mkt

separate plots of aggregates across yearsinto different plots for each market category (retained, discarded)?

sampsizeline

show line for input sample sizes on top of conditionalage-at-length plots (TRUE/FALSE, still in development)

effNline

show line for effective sample sizes on top of conditionalage-at-length plots (TRUE/FALSE, still in development)

minnbubble

number of unique x values before adding buffer. see?bubble3 for more info.

pntscalar

This scalar defines the maximum bubble size for bubbleplots. This option is still available but a better choice is to use cexZ1which allow the same scaling throughout all plots.

scalebubbles

scale data-only bubbles by sample size, not justproportion within sample? Default=FALSE.

cexZ1

Character expansion (cex) for point associated with value of 1.

bublegend

Add legend with example bubble sizes to bubble plots.

colvec

Vector of length 3 with colors for females, males, unsexed fish

linescol

Color for lines on top of polygons

xlas

label style (las) input for x-axis. Default 0 has horizontallabels, input 2 would provide vertical lables.

ylas

label style (las) input for y-axis. Default NULL has horizontallabels when all labels have fewer than 6 characters and vertical otherwise.Input 0 would force vertical labels, and 1 would force horizontal.

axis1

optional position of bottom axis values

axis2

optional position of left size axis values

axis1labs

optional vector of labels for axis1 (either NULL or needs tomatch length of axis1)

sizebinlabs

Vector of size bin labels corresponding to the generalizedsize frequency method

blue

What color to use for males in bubble plots (default is slightlytransparent blue)

red

What color to use for females in bubble plots (default is slightlytransparent red)

pwidth

Default width of plots printed to files in units ofpunits. The default ispwidth=6.5.

pheight

Height of plots printed to png files in units ofpunits.Default is designed to allow two plots per page, withpheight_tall usedfor plots that work best with a taller format and a single plot per page.

punits

Units forpwidth andpheight. Can be "px"(pixels), "in" (inches), "cm" (centimeters), or "mm" (millimeters).The default ispunits="in".

ptsize

Point size for plotted text in plots printed to files (seehelp("png") in R for details).

res

Resolution of plots printed to files.The default isres = 300.

plotdir

directory where PNG files will be written. by default it willbe the directory where the model was run.

cex.main

character expansion parameter for plot titles

linepos

should lines be added before points (linepos=1) or after(linepos=2)?

fitbar

show fit to bars instead of points

do.sqrt

scale bubbles based on sqrt of size vector. see ?bubble3 formore info.

smooth

add loess smoother to observed vs. expected index plots andinput vs. effective sample size?

cohortlines

optional vector of birth years for cohorts for which toadd growth curves to numbers at length bubble plots

labels

vector of labels for plots (titles and axis labels)

printmkt

show market categories in plot titles?

printsex

show sex in plot titles?

maxrows

maximum (or fixed) number or rows of panels in the plot

maxcols

maximum (or fixed) number or columns of panels in the plot

maxrows2

maximum number of rows for conditional age at length plots

maxcols2

maximum number of columns for conditional age at lengthplots

rows

number or rows to return to as default for next plots to come orfor single plots

cols

number or cols to return to as default for next plots to come orfor single plots

andre_oma

Outer margins passed to Andre's multi-panel conditionalage-at-length plots.

andrerows

Number of rows of Andre's conditional age-at-length plotswithin each page. Default=3.

fixdims

fix the dimensions at maxrows by maxcols or resize based onnumber of years of data

fixdims2

fix the dimensions at maxrows by maxcols in aggregate plotsor resize based on number of fleets

maxneff

the maximum value to include on plots of input and effectivesample size. Occasionally a calculation of effective N blows up to verylarge numbers, rendering it impossible to observe the relationship for otherdata. Default=5000.

verbose

return updates of function progress to the R GUI?

scalebins

Rescale expected and observed proportions by dividing bybin width for models where bins have different widths? Caution!: May notwork correctly in all cases.

addMeans

Add parameter means in addition to medians for MCMCposterior distributions in which the median and mean differ.

mainTitle

Logical indicating if a title for the plot should be produced

...

additional arguments that will be passed tothepar command in themake_multifig() function.

Author(s)

Ian Taylor

See Also

SS_plots(),make_multifig()


Timeline of presence/absence of data by type, year, and fleet.

Description

Plot shows graphical display of what data is being used in the model. Somedata types may not yet be included. Note, this is based on output from themodel, not the input data file.

Usage

SSplotData(  replist,  plot = TRUE,  print = FALSE,  plotdir = "default",  subplot = 1:2,  fleetcol = "default",  datatypes = "all",  fleets = "all",  fleetnames = "default",  ghost = FALSE,  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1,  margins = c(5.1, 2.1, 2.1, 8.1),  cex = 2,  lwd = 12,  maxsize = 1,  alphasize = 1,  mainTitle = FALSE,  verbose = TRUE)

Arguments

replist

A list object created bySS_output().

plot

plot to active plot device?

print

print to PNG files?

plotdir

directory where PNG files will be written. by default it willbe the directory where the model was run.

subplot

vector controlling which subplots to createCurrently there are only 2 subplots:

  • 1 equal size points showing presence/absence of data type by year/fleet

  • 2 points scaled to indicate quantity or precision of data

fleetcol

Either the string "default", or a vector of colors to usefor each fleet. If tagging data is included, an additional color needs to beadded for the tag releases which are not assigned to a fleet.

datatypes

Either the string "all", or a vector including some subsetof the following: "catch", "cpue", "lendbase", "sizedbase", "agedbase","condbase", "ghostagedbase", "ghostcondbase", "ghostlendbase", "ladbase","wadbase", "mnwgt", "discard", "tagrelease", and "tagdbase1".

fleets

Either the string "all", or a vector of numerical values, likec(1,3), listing fleets or surveys to be included in the plot.

fleetnames

A vector of alternative names to use in the plot. Bydefault the parameter names in the data file are used.

ghost

TRUE/FALSE indicator for whether to show presence ofcomposition data from ghost fleets (data for which the fit is shown, but isnot included in the likelihood calculations).

pwidth

width of plot

pheight

height of plot

punits

units for PNG file

res

Resolution of plots printed to files.The default isres = 300.

ptsize

point size for PNG file

cex.main

character expansion for plot titles

margins

margins of plot (passed to par() function), which may need tobe increased if fleet names run off right-hand margin

cex

Character expansion for points showing isolated years of data

lwd

Line width for lines showing ranges of years of data

maxsize

The size (cex) of the largest bubble in the datasizeplot. Default is 1.

alphasize

The transparency of the bubbles in the datasizeplot. Defaults to 1 (no transparency). Useful for models with lots ofoverlapping points.

mainTitle

TRUE/FALSE switch to turn on/off the title on the plot.

verbose

report progress to R GUI?

Author(s)

Ian Taylor, Chantel Wetzel, Cole Monnahan

See Also

SS_plots(),SS_output(),SS_readdat()


Plot fit to discard fraction.

Description

Plot fit to discard fraction from Stock Synthesis output file.

Usage

SSplotDiscard(  replist,  subplots = 1:2,  plot = TRUE,  print = FALSE,  plotdir = "default",  fleets = "all",  fleetnames = "default",  datplot = FALSE,  labels = c("Year", "Discard fraction", "Total discards", "for"),  yhi = 1,  ymax = NULL,  col1 = "blue",  col2 = "black",  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1,  verbose = TRUE)

Arguments

replist

A list object created bySS_output().

subplots

Vector of which plots to make (1 = data only, 2 = with fit).Ifplotdat = FALSE then subplot 1 is not created, regardless ofchoice ofsubplots.

plot

Plot to active plot device?

print

Print to PNG files?

plotdir

Directory where PNG files will be written. by default it willbe the directory where the model was run.

fleets

Optional vector to subset fleets for which plots will be made

fleetnames

Optional replacement for fleenames used in data file

datplot

Make data-only plot of discards? This can override the choiceofsubplots.

labels

Vector of labels for plots (titles and axis labels)

yhi

Maximum y-value which will always be included in the plot(all data included regardless). Default = 1 so that discard fractions are alwaysplotted on a 0-1 range, but total discard amounts which are greater than this valuewill exceed it.

ymax

Optional maximum y-value to include (useful if upper tails ondiscard amounts are very high)

col1

First color to use in plot (for expected values)

col2

Second color to use in plot (for observations and intervals)

pwidth

Width of plot

pheight

Height of plot

punits

Units for PNG file

res

Resolution of plots printed to files.The default isres = 300.

ptsize

Point size for PNG file

cex.main

Character expansion for plot titles

verbose

Report progress to R GUI?

Author(s)

Ian G. Taylor, Ian J. Stewart, Robbie L. Emmet

See Also

SS_plots()


Plot Dynamic B0

Description

Plots the spawning output with and without fishing mortality

Usage

SSplotDynamicB0(  replist,  ylab = "Spawning biomass (mt)",  equilibrium = TRUE,  forecast = FALSE,  yrs = "all",  plot = TRUE,  print = FALSE,  plotdir = "default",  verbose = TRUE,  uncertainty = TRUE,  legend = TRUE,  legendlabels = c("equilibrium", "without fishing", "with fishing"),  legendloc = "bottom",  col = c("blue", "red"),  lty = 1,  lwd = 2,  add = FALSE,  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  mainTitle = FALSE,  mar = NULL)

Arguments

replist

A list object created bySS_output().

ylab

Y-axis label. Default is "Spawning biomass (mt)" which is replacedby "Spawning output" for models withreplist[["SpawnOutputUnits"]] == "numbers"

equilibrium

Show equilibrium in plot? Applies whether "yrs" is specifiedor not.

forecast

Show forecast years in plot? Only applies if yrs = "all".

yrs

Which years to include. Default "all" will show startyr to endyr + 1modified by the argumentsforecast.

plot

Plot to active plot device?

print

Print to PNG files?

plotdir

Directory where PNG files will be written. By default it willbe the directory where the model was run.

verbose

A logical value specifying if output should be printedto the screen.

uncertainty

Show 95% uncertainty intervals around point estimates?These intervals will only appear when uncertainty in the dynamic B0estimates is available via the control file settings for"read specs for more stddev reporting".

legend

Add a legend?

legendlabels

Character vector with labels for the unfishedequilibrium point (ifequilibrium = TRUE) and the two lines showingspawning biomass or output without and with fishing.

legendloc

Location of legend. Either a string like "topleft" or avector of two numeric values representing the fraction of the maximum inthe x and y dimensions, respectively. Seehelp("legend") for more info onthe string options.

col

Optional vector of colors to be used for the two lines(single value will apply to both lines).

lty

Optional vector of line types to be used for the two lines(single value will apply to both lines).

lwd

Optional vector of line widths to be used for the two lines(single value will apply to both lines).

add

add to existing plot

pwidth

Default width of plots printed to files in units ofpunits. The default ispwidth=6.5.

pheight

Height of plots printed to png files in units ofpunits.Default is designed to allow two plots per page, withpheight_tall usedfor plots that work best with a taller format and a single plot per page.

punits

Units forpwidth andpheight. Can be "px"(pixels), "in" (inches), "cm" (centimeters), or "mm" (millimeters).The default ispunits="in".

res

Resolution of plots printed to files.The default isres = 300.

ptsize

Point size for plotted text in plots printed to files (seehelp("png") in R for details).

mainTitle

Logical indicating if a title should be included at the top(not yet implemented for all plots)

mar

Either NULL to allow the default (which depends on whether the main title is included or not) or a numerical vector of the form c(bottom, left, top, right) which gives the number of lines of margin to be specified on the four sides of the plot, which is passed topar().

Author(s)

Ian G. Taylor

See Also

SSplotTimeseries()


Plot indices of abundance and associated quantities.

Description

Plot indices of abundance with or without model fit as well as other diagnosticplots such as observed vs. expected index and plots related to time-varyingcatchability (if present).

Usage

SSplotIndices(  replist,  subplots = c(1:10, 12),  plot = TRUE,  print = FALSE,  fleets = "all",  fleetnames = "default",  smooth = TRUE,  add = FALSE,  datplot = TRUE,  labels = c("Year", "Index", "Observed index", "Expected index", "Log index",    "Log observed index", "Log expected index", "Standardized index", "Catchability (Q)",    "Time-varying catchability", "Vulnerable biomass",    "Catchability vs. vulnerable biomass", "Residual", "Deviation"),  fleetcols = NULL,  col1 = "default",  col2 = "default",  col3 = "blue",  col4 = "red",  pch1 = 21,  pch2 = 16,  cex = 1,  bg = "white",  legend = TRUE,  legendloc = "topright",  seasnames = NULL,  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1,  mainTitle = FALSE,  plotdir = "default",  minyr = NULL,  maxyr = NULL,  maximum_ymax_ratio = Inf,  show_input_uncertainty = TRUE,  verbose = TRUE,  ...)

Arguments

replist

A list object created bySS_output().

subplots

vector controlling which subplots to createNumbering of subplots is as follows, where subplot 9 (comparison of all indices) isprovided first:

  • 1 index data by fleet

  • 2 index data with fit by fleet

  • 3 observed vs expected index values with smoother

  • 4 index data by fleet on a log scale (lognormal error only)

  • 5 index data with fit by fleet on a log scale (lognormal error only)

  • 6 log(observed) vs log(expected) with smoother (lognormal error only)

  • 7 time series of time-varying catchability (only if actually time-varying)

  • 8 catchability vs. vulnerable biomass (if catchability is not constant)

  • 9 comparison of all indices

  • 10 index residuals based on total uncertainty

  • 11 index residuals based on input uncertainty (not currently provided)

  • 12 index deviations (independent of index uncertainty)

plot

plot to active plot device?

print

print to PNG files?

fleets

optional vector to subset fleets for which plots will be made

fleetnames

optional replacement for fleenames used in data file

smooth

add smoothed line to plots of observed vs. expected samplesizes

add

add to existing plot (not yet implemented)

datplot

make plot of data only?

labels

vector of labels for plots (titles and axis labels)

fleetcols

vector of colors for all fleets (including thosewith no index data)

col1

vector of colors for points in each season for time series plot.Default is red for single season models and a rainbow using therich.colors.short function for multiple seasons.

col2

vector of colors for points in each season for obs. vs. exp.plot. Default is blue for single season models and a rainbow using therich.colors.short function for multiple seasons.

col3

color of line showing expected index in time series plot.Default is blue.

col4

color of smoother shown in obs. vs. exp. plots. Default is red.

pch1

single value or vector of plotting characters (pch parameter)for time-series plots of index fit. Default=21.

pch2

single value or vector of plotting characters (pch parameter)for sample size plots of index fit. Default=16.

cex

character expansion factor for points showing observed values.Default=1.

bg

Background color for points with pch=21.

legend

add a legend to seasonal colors (only for seasonal models)

legendloc

add a legend to seasonal colors (default is "topright")

seasnames

optional vector of names for each season to replacedefaults if a legend is used

pwidth

width of plot

pheight

height of plot

punits

units for PNG file

res

Resolution of plots printed to files.The default isres = 300.

ptsize

point size for PNG file

cex.main

character expansion for plot titles

mainTitle

switch which allows the plot title to be left off

plotdir

directory where PNG files will be written. by default it willbe the directory where the model was run.

minyr

First year to show in plot (for zooming in on a subset ofvalues)

maxyr

Last year to show in plot (for zooming in on a subset ofvalues)

maximum_ymax_ratio

Maximum allowed value for ymax (specifiedas ratio of y), which overrides anyvalue of ymax that is greater (default = Inf)

show_input_uncertainty

Switch controlling whether to add thickeruncertainty interval lines indicating the input uncertainty relative tothe total uncertainty which may result from estimating a parameter forextra standard deviations. This is only added for the plots with indexfit included (the data-only plots only show the input uncertainty).

verbose

report progress to R GUI?

...

Extra arguments to pass to calls toplot

Author(s)

Ian Stewart, Ian Taylor, James Thorson

See Also

SS_plots(),SS_output()


Plot uncertainty around chosen selectivity ogive from MCMC.

Description

Plot uncertainty in selectivity from an MCMC output for whichever fleet/yearwas chosen in the optional extra "more stddev reporting"

Usage

SSplotMCMC_ExtraSelex(  post,  add = FALSE,  nsexes = 1,  shift = 0,  fleetname = "default",  col = "blue")

Arguments

post

A data frame containing either derived_posteriors.sso or a goodsubset of it. This can be an element of the list created by the theSSgetMCMC() function.

add

TRUE/FALSE option to add results to an existing plot.

nsexes

Number of sexes in the model (should match model values but isonly used in the title).

shift

Optional adjustment to the x values to avoid overlap ofintervals when overplotting on an existing plot.

fleetname

Optional input to make the title better. Default will besomething like "Fleet 1", using the numbering from the model.

col

Color for points and lines.

Author(s)

Ian Taylor


Plot mean weight data and fits.

Description

Plot mean weight data and fits from Stock Synthesis output. Intervals arebased on T-distributions as specified in model.

Usage

SSplotMnwt(  replist,  subplots = 1:2,  ymax = NULL,  plot = TRUE,  print = FALSE,  fleets = "all",  fleetnames = "default",  datplot = FALSE,  labels = c("Year", "discard", "retained catch", "whole catch",    "Mean individual body weight (kg)", "Mean weight in", "for"),  col1 = "blue",  col2 = "black",  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1,  plotdir = "default",  verbose = TRUE)

Arguments

replist

A list object created bySS_output().

subplots

Vector of which plots to make (1 = data only, 2 = with fit).Ifplotdat = FALSE then subplot 1 is not created, regardless ofchoice ofsubplots.

ymax

Optional input to override default ymax value.

plot

plot to active plot device?

print

print to PNG files?

fleets

optional vector to subset fleets for which plots will be made

fleetnames

optional replacement for fleenames used in data file

datplot

Make data-only plot of discards? This can override the choiceofsubplots.

labels

vector of labels for plots (titles and axis labels)

col1

first color to use in plot (for expected values)

col2

second color to use in plot (for observations and intervals)

pwidth

width of plot

pheight

height of plot

punits

units for PNG file

res

Resolution of plots printed to files.The default isres = 300.

ptsize

point size for PNG file

cex.main

character expansion for plot titles

plotdir

directory where PNG files will be written. by default it willbe the directory where the model was run.

verbose

report progress to R GUI?

Author(s)

Ian Taylor, Ian Stewart

See Also

SS_plots(),SS_output()


Show movement rates on a map.

Description

Make a map with colored spatial cells and add arrows representing movementrates between cells.

Usage

SSplotMovementMap(  replist = NULL,  xlim,  ylim,  polygonlist,  colvec,  land = "grey",  xytable = NULL,  moveage = 5,  moveseas = 1,  lwdscale = 5,  legend = TRUE,  title = NULL,  areanames = NULL,  cex = 1)

Arguments

replist

A list object created bySS_output().

xlim

range of longitude values in the map

ylim

range of latitude values in the map

polygonlist

a list of data frames, each with two columns representingthe longitude and latitude values of the colored polygons. The order ofelements in the list should match the numbering of areas in the SS model.

colvec

vector of colors for each polygon (ifreplist isprovided)

land

color of landmasses in the map

xytable

data frame of latitude and longitude values which will beconnected by the arrows representing movement rates. The order should matchthe order of areas inpolygonlist and in the SS model. Not necessaryif no arrows are shown on the map.

moveage

age for which movement rates will be represented

moveseas

season for which movement rates will be represented

lwdscale

scaling factor for arrows in the plot. The largest rate ofmovement shown will be scaled to have a line width equal to this value.

legend

add a legend to show the movement rate associated with thewidest arrows

title

optional title to be added above map

areanames

optional vector of names to be shown on map at coordinatesmatching xytable values

cex

character expansion to apply to text shown by areanames (if used)

Note

Inspired by plots of MULTIFAN-CL movement patterns presented by AdamLangley

Author(s)

Ian Taylor

See Also

SS_output(),SSplotMovementRates()


Plot movement rates from model output

Description

Plots estimated movement rates in final year for each area/season with movement asreported in Report.sso. If movement is time-varying, an additional figure showspattern across years (if the MGparm_By_Year_after_adjustments table (report:7)is available in the Report.sso file)

Usage

SSplotMovementRates(  replist,  plot = TRUE,  print = FALSE,  subplots = 1:2,  plotdir = "default",  colvec = "default",  ylim = "default",  legend = TRUE,  legendloc = "topleft",  moveseas = "all",  min.move.age = 0.5,  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1,  verbose = TRUE)

Arguments

replist

A list object created bySS_output().

plot

plot to active plot device?

print

print to PNG files?

subplots

which subplots to create.

plotdir

where to put the plots (uses model directory by default)

colvec

vector of colors for each movement rate in the plot

ylim

optional input for y range of the plot. By default plot rangesfrom 0 to 10% above highest movement rate (not including fish staying in anarea).

legend

add a legend designating which color goes with which pair ofareas?

legendloc

location passed to legend function (if used)

moveseas

choice of season for which movement rates are shown

min.move.age

Minimum age of movement (in future will come from Report file)

pwidth

width of plot

pheight

height of plot

punits

units for PNG file

res

Resolution of plots printed to files.The default isres = 300.

ptsize

point size for PNG file

cex.main

Character expansion parameter for plot titles

verbose

Print information on function progress.

Author(s)

Ian Taylor

See Also

SS_output(),SSplotMovementRates(),

Examples

## Not run: SSplotMovementRates(myreplist)## End(Not run)

Plot numbers-at-age related data and fits.

Description

Plot numbers-at-age related data and fits from Stock Synthesis output.Plots include bubble plots, mean age, equilibrium age composition,sex-ratio, and ageing imprecision patterns.

Usage

SSplotNumbers(  replist,  subplots = c(1:10),  plot = TRUE,  print = FALSE,  numbers.unit = 1000,  areas = "all",  areanames = "default",  areacols = "default",  pntscalar = 2.6,  bub.bg = gray(0.5, alpha = 0.5),  bublegend = TRUE,  period = c("B", "M"),  meanlines = TRUE,  add = FALSE,  labels = c("Year", "Age", "True age (yr)", "SD of observed age (yr)",    "Mean observed age (yr)", "Mean age (yr)", "mean age in the population",    "Ageing imprecision", "Numbers at age at equilibrium",    "Equilibrium age distribution", "Fraction female in numbers at age", "Length",    "Mean length (cm)", "mean length (cm) in the population", "expected numbers at age",    "Beginning of year", "Middle of year", "expected numbers at length",    "Fraction female in numbers at length"),  pwidth = 6.5,  pheight = 6.5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1,  plotdir = "default",  mainTitle = FALSE,  verbose = TRUE)

Arguments

replist

A list object created bySS_output().

subplots

vector controlling which subplots to createNumbering of subplots is as follows,

  • 1: Expected numbers at age

  • 2: Mean age in the population

  • 3: Fraction female in numbers at age

  • 4: Equilibrium age distribution

  • 5: Ageing imprecision: SD of observed age (plot using image() formerlyincluded in this group but now replaced by better distribution plots)

  • 6: Expected numbers at length

  • 7: Mean length in the population

  • 8: Fraction female in numbers at length

  • 9: no plot yet

  • 10: Distribution of observed age at true age by ageing error type

plot

plot to active plot device?

print

print to PNG files?

numbers.unit

Units for numbers. Default (based on typical Stock Synthesissetup) is thousands (numbers.unit=1000).

areas

optional subset of areas to plot for spatial models

areanames

names for areas. Default is to use Area1, Area2,...

areacols

vector of colors by area

pntscalar

maximum bubble size for bubble plots; each plot scaledindependently based on this maximum size and the values plotted. Often someplots look better with one value and others with a larger or smaller value.Default=2.6

bub.bg

background color for bubbles(no control over black border at this time)

bublegend

Add legend with example bubble sizes?

period

indicator of whether to make plots using numbers at age justfrom the beginning ("B") or middle of the year ("M") (new option startingwith SSv3.11)

meanlines

add lines for mean age or length on top of bubble plots

add

add to existing plot? (not yet implemented)

labels

vector of labels for plots (titles and axis labels)

pwidth

Default width of plots printed to files in units ofpunits. The default ispwidth=6.5.

pheight

Height of plots printed to png files in units ofpunits.Default is designed to allow two plots per page, withpheight_tall usedfor plots that work best with a taller format and a single plot per page.

punits

Units forpwidth andpheight. Can be "px"(pixels), "in" (inches), "cm" (centimeters), or "mm" (millimeters).The default ispunits="in".

res

Resolution of plots printed to files.The default isres = 300.

ptsize

Point size for plotted text in plots printed to files (seehelp("png") in R for details).

cex.main

character expansion for plot titles

plotdir

directory where PNG files will be written. by default it willbe the directory where the model was run.

mainTitle

Logical indicating if a title should be included at the top

verbose

report progress to R GUI?

Author(s)

Ian Stewart, Ian Taylor

See Also

SS_output(),SS_plots()


Plot distributions of priors, posteriors, and estimates.

Description

Make multi-figure plots of prior, posterior, and estimated asymptoticparameter distributions. MCMC not required to make function work.

Usage

SSplotPars(  replist,  plotdir = NULL,  xlab = "Parameter value",  ylab = "Density",  showmle = TRUE,  showpost = TRUE,  showprior = TRUE,  showinit = TRUE,  showdev = FALSE,  showlegend = TRUE,  fitrange = FALSE,  xaxs = "i",  xlim = NULL,  ylim = NULL,  verbose = TRUE,  debug = FALSE,  nrows = 4,  ncols = 2,  ltyvec = c(1, 1, 3, 4),  colvec = c("blue", "red", "black", "gray60", rgb(0, 0, 0, 0.5)),  add = FALSE,  plot = TRUE,  print = FALSE,  pwidth = 6.5,  pheight = 6.5,  punits = "in",  ptsize = 10,  res = 300,  strings = NULL,  exact = FALSE,  newheaders = NULL)

Arguments

replist

A list object created bySS_output().

plotdir

A path to the folder where the plots will be saved. The defaultisNULL, which leads to the plots being created in the folder thatcontains the results.

xlab

Label on horizontal axis.

ylab

Label on vertical axis.

showmle

Show MLE estimate and asymptotic variance estimate with bluelines?

showpost

Show posterior distribution as bar graph if MCMC resultsare available inreplist?

showprior

Show prior distribution as black line?

showinit

Show initial value as red triangle?

showdev

Include devs in the plot?

showlegend

Show the legend?

fitrange

Fit range tightly around MLE & posterior distributions,instead of full parameter range?

xaxs

Parameter input for x-axis. See?par for more info.

xlim

Optional x-axis limits to be applied to all plots.Otherwise, limits are based on the model results.

ylim

Optional y-axis limits to be applied to all plots.Otherwise, limits are based on the model results.

verbose

Controls amount of text output (maybe).

debug

Provide additional messages to help with debugging when thefunction fails.

nrows

How many rows in multi-figure plot.

ncols

How many columns in multi-figure plot.

ltyvec

Vector of line types used for lines showing MLE and priordistributions and the median of the posterior distribution.

colvec

Vector of colors used for lines and polygons showing MLE,initial value, prior, posterior, and median of the posterior.

add

Add to existing plot?

plot

Plot to active plot device?

print

Print to PNG files?

pwidth

Default width of plots printed to files in units ofpunits. Default=7.

pheight

Default height width of plots printed to files in units ofpunits. Default=7.

punits

Units forpwidth andpheight. Can be "px"(pixels), "in" (inches), "cm" or "mm". Default="in".

ptsize

Point size for plotted text in plots printed to files (seehelp("png") in R for details). Default=12.

res

Resolution of plots printed to files.The default isres = 300.

strings

Subset parameters included in the plot using substring fromparameter names (i.e. "SR" will get "SR_LN(R0)" and "SR_steep" if they are bothestimated quantities in this model).

exact

Should strings input match parameter names exactly? Otherwisesubstrings are allowed.

newheaders

Optional vector of headers for each panel to replace theparameter names.

Author(s)

Ian G. Taylor, Cole C. Monnahan

Examples

## Not run: # read model resultsmodel <- SS_output(dir = "c:/SS/Simple/")# make default plots where parameter distribution plots will appear# in the "pars" tabSS_plots(model)# create just the "pars" tab with control of the inputs that are# passed to SSplotParsSS_plots(model,  plot = 25, showmle = TRUE, showpost = TRUE,  showprior = TRUE, showinit = TRUE, showdev = FALSE, fitrange = FALSE)# call SSplotPars directlySSplotPars(replist = model)# Create plot in custom location. Note that strings can be partial match.# File name will be "parameter_distributions.png"# or "parameter_distributions_pageX.png" when they don't all fit on one pageSSplotPars(  replist = model, strings = c("steep", "R0"),  nrows = 2, ncols = 1, plot = FALSE, print = TRUE,  plotdir = file.path(model[["inputs"]][["dir"]], "distribution_plots"))## End(Not run)

Plot likelihood profile results

Description

Makes a plot of change in negative-log-likelihood for each likelihoodcomponent that contributes more than some minimum fraction of change intotal.

Usage

SSplotProfile(  summaryoutput,  plot = TRUE,  print = FALSE,  models = "all",  profile.string = "steep",  profile.label = "Spawner-recruit steepness (h)",  exact = FALSE,  ylab = "Change in -log-likelihood",  components = c("TOTAL", "Catch", "Equil_catch", "Survey", "Discard", "Mean_body_wt",    "Length_comp", "Age_comp", "Size_at_age", "SizeFreq", "Morphcomp", "Tag_comp",    "Tag_negbin", "Recruitment", "InitEQ_Regime", "Forecast_Recruitment", "Parm_priors",    "Parm_softbounds", "Parm_devs", "F_Ballpark", "Crash_Pen"),  component.labels = c("Total", "Catch", "Equilibrium catch", "Index data", "Discard",    "Mean body weight", "Length data", "Age data", "Size-at-age data",    "Generalized size data", "Morph composition data", "Tag recapture distribution",    "Tag recapture total", "Recruitment", "Initital equilibrium recruitment",    "Forecast recruitment", "Priors", "Soft bounds", "Parameter deviations",    "F Ballpark", "Crash penalty"),  minfraction = 0.01,  sort.by.max.change = TRUE,  col = "default",  pch = "default",  lty = 1,  lty.total = 1,  lwd = 2,  lwd.total = 3,  cex = 1,  cex.total = 1.5,  xlim = "default",  ymax = "default",  xaxs = "r",  yaxs = "r",  type = "o",  legend = TRUE,  legendloc = "topright",  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1,  plotdir = NULL,  add_cutoff = FALSE,  cutoff_prob = 0.95,  verbose = TRUE,  ...)

Arguments

summaryoutput

List created by the functionSSsummarize().

plot

Plot to active plot device?

print

Print to PNG files?

models

Optional subset of the models described insummaryoutput. Either "all" or a vector of numbers indicatingcolumns in summary tables.

profile.string

Character string used to find parameter over which theprofile was conducted. Ifexact=FALSE, this can be a substring ofone of the SS parameter labels found in the Report.sso file.For instance, the default input 'steep'matches the parameter 'SR_BH_steep'. Ifexact=TRUE, thenprofile.string needs to be an exact match to the parameter label.

profile.label

Label for x-axis describing the parameter over whichthe profile was conducted.

exact

Should theprofile.string have to match the parameterlabel exactly, or is a substring OK.

ylab

Label for y-axis. Default is "Change in -log-likelihood".

components

Vector of likelihood components that may be included inplot. List is further refined by any components that are not present inmodel or have little change over range of profile (based on limitminfraction). Hopefully this doesn't need to be changed.

component.labels

Vector of labels for use in the legend that matchesthe vector incomponents.

minfraction

Minimum change in likelihood (over range considered) as afraction of change in total likelihood for a component to be included in thefigure.

sort.by.max.change

Switch giving option to sort components in legendin order of maximum amount of change in likelihood (over range considered).Default=TRUE.

col

Optional vector of colors for each line.

pch

Optional vector of plot characters for the points.

lty

Line total for the likelihood components.

lty.total

Line type for the total likelihood.

lwd

Line width for the likelihood components.

lwd.total

Line width for the total likelihood.

cex

Character expansion for the points representing the likelihoodcomponents.

cex.total

Character expansion for the points representing the totallikelihood.

xlim

Range for x-axis. Change in likelihood is calculated relative tovalues within this range.

ymax

Maximum y-value. Default is 10% greater than largest valueplotted.

xaxs

The style of axis interval calculation to be used for the x-axis(see ?par for more info)

yaxs

The style of axis interval calculation to be used for the y-axis(see ?par for more info).

type

Line type (see ?plot for more info).

legend

Include legend?

legendloc

Location of legend (see ?legend for more info).

pwidth

Width of plot

pheight

Height of plot

punits

Units for PNG file

res

Resolution of plots printed to files.The default isres = 300.

ptsize

Point size for PNG file

cex.main

Character expansion for plot titles

plotdir

Directory where PNG files will be written. by default it willbe the directory where the model was run.

add_cutoff

Add dashed line at ~1.92 to indicate 95% confidence intervalbased on common cutoff of half of chi-squared of p=.95 with 1 degree offreedom:0.5*qchisq(p=cutoff_prob, df=1). The probability valuecan be adjusted using thecutoff_prob below.

cutoff_prob

Probability associated withadd_cutoff above.

verbose

Return updates of function progress to the R GUI? (Doesn't doanything yet.)

...

Additional arguments passed to theplot command.

Note

Someday the functionSS_profile() will be improved andmade to work directly with this plotting function, but they don't yet workwell together. Thus, even ifSS_profile() is used, the outputshould be read usingSSgetoutput() or by multiple calls toSS_output().

Author(s)

Ian Taylor, Ian Stewart

See Also

SSsummarize(),SS_profile(),SS_output(),SSgetoutput()


Plot recruitment deviations

Description

Plot recruitment deviations and associated quantities including derivedmeasures related to bias adjustment.

Usage

SSplotRecdevs(  replist,  subplots = 1:3,  plot = TRUE,  print = FALSE,  add = FALSE,  uncertainty = TRUE,  minyr = -Inf,  maxyr = Inf,  forecastplot = FALSE,  col1 = "black",  col2 = "blue",  col3 = "green3",  col4 = "red",  legendloc = "topleft",  labels = c("Year", "Asymptotic standard error estimate", "Log recruitment deviation",    "Bias adjustment fraction, 1 - stddev^2 / sigmaR^2"),  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1,  plotdir = "default",  verbose = TRUE)

Arguments

replist

A list object created bySS_output().

subplots

vector controlling which subplots to create

plot

plot to active plot device?

print

print to PNG files?

add

add to existing plot (not yet implemented)

uncertainty

include plots showing uncertainty?

minyr

optional input for minimum year to show in plots

maxyr

optional input for maximum year to show in plots

forecastplot

include points from forecast years?

col1

first color used

col2

second color used

col3

third color used

col4

fourth color used

legendloc

location of legend. see ?legend for more info

labels

vector of labels for plots (titles and axis labels)

pwidth

width of plot

pheight

height of plot

punits

units for PNG file

res

Resolution of plots printed to files.The default isres = 300.

ptsize

point size for PNG file

cex.main

character expansion for plot titles

plotdir

directory where PNG files will be written. by default it willbe the directory where the model was run.

verbose

report progress to R GUI?

Author(s)

Ian Taylor, Ian Stewart

See Also

SS_plots(),SS_fitbiasramp()


Plot of recruitment distribution among areas and seasons

Description

Image plot shows fraction of recruitment in each combination of area andseason. This is based on the RECRUITMENT_DIST section of the Report.ssofile.

Usage

SSplotRecdist(  replist,  plot = TRUE,  print = FALSE,  areanames = NULL,  seasnames = NULL,  xlab = "",  ylab = "",  main = "Distribution of recruitment by area and season",  plotdir = "default",  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1,  verbose = TRUE)

Arguments

replist

A list object created bySS_output().

plot

plot to active plot device?

print

print to PNG files?

areanames

optional vector to replace c("Area1","Area2",...)

seasnames

optional vector to replace c("Season1","Season2",...)

xlab

optional x-axis label (if the area names aren\'t informativeenough)

ylab

optional y-axis label (if the season names aren\'t informativeenough)

main

title for plot

plotdir

directory where PNG files will be written. by default it willbe the directory where the model was run.

pwidth

width of plot

pheight

height of plot

punits

units for PNG file

res

Resolution of plots printed to files.The default isres = 300.

ptsize

point size for PNG file

cex.main

character expansion for plot titles

verbose

report progress to R GUI?

Author(s)

Ian Taylor

See Also

SS_plots(),SSplotRecdevs()


Make squid plot of retrospectives of recruitment deviations.

Description

Inspired by Jim Ianelli and named by Sean Cox, the squid plot is a way toexamine retrospective patterns in estimation of recruitment deviations.

Usage

SSplotRetroRecruits(  retroSummary,  endyrvec,  cohorts,  ylim = NULL,  uncertainty = FALSE,  labels = c("Recruitment deviation", "Recruitment (billions)",    "relative to recent estimate", "Age"),  main = "Retrospective analysis of recruitment deviations",  mcmcVec = FALSE,  devs = TRUE,  relative = FALSE,  labelyears = TRUE,  legend = FALSE,  leg.ncols = 4)

Arguments

retroSummary

List object created bySSsummarize() thatsummarizes the results of a set of retrospective analysis models.ss

endyrvec

Vector of years representing the final year of values toshow for each model.

cohorts

Which cohorts to show in plot.

ylim

Limits of y-axis.

uncertainty

Show uncertainty intervals around lines? (This can get abit busy.)

labels

Vector of plot labels.

main

Title for plot.

mcmcVec

Either vector of TRUE/FALSE values indicating which modelsuse MCMC. Or single value applied to all models.

devs

Plot deviations instead of absolute recruitment values?

relative

Show deviations relative to most recent estimate or relativeto 0.

labelyears

Label cohorts with text at the end of each line?

legend

Add a legend showing which color goes with which line (asalternative tolabelyears).

leg.ncols

Number of columns for the legend.

Author(s)

Ian Taylor

References

Ianelli et al. (2011) Assessment of the walleye pollock stock inthe Eastern Bering Sea.(Figure 1.31, which is on an absolute, rather than log scale.)

See Also

SSsummarize()

Examples

## Not run: # run retrospective analysisSS_doRetro(olddir = "2013hake_12", years = 0:-10)# read in outputretroModels <- SSgetoutput(dirvec = paste("retrospectives/retro", -10:0, sep = ""))# summarize outputretroSummary <- SSsummarize(retroModels)# set the ending year of each model in the setendyrvec <- retroModels[[1]][["endyr"]] - 10:0# make comparison plotpdf("retrospectives/retrospective_comparison_plots.pdf")SSplotComparisons(retroSummary, endyrvec = endyrvec, new = FALSE)dev.off()# make Squid Plot of recdev retrospectivespdf("retrospectives/retrospective_dev_plots.pdf", width = 7, height = 10)par(mfrow = c(2, 1))# first scaled relative to most recent estimateSSplotRetroRecruits(retroSummary,  endyrvec = endyrvec, cohorts = 1999:2012,  relative = TRUE, legend = FALSE)# second without scalingSSplotRetroDevs(retroSummary,  endyrvec = endyrvec, cohorts = 1999:2012,  relative = FALSE, legend = FALSE)dev.off()## End(Not run)

Plot Spawning Potential Ratio (SPR) quantities.

Description

Plot time series of SPR, 1-SPR, the chosen SPR ratio and the phase plot.

Usage

SSplotSPR(  replist,  add = FALSE,  plot = TRUE,  print = FALSE,  uncertainty = TRUE,  subplots = 1:4,  forecastplot = FALSE,  col1 = "black",  col2 = "blue",  col3 = "green3",  col4 = "red",  sprtarg = "default",  btarg = "default",  labels = c("Year", "SPR", "1-SPR", "Relative fishing intensity",    "Relative spawning output"),  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1,  plotdir = "default",  verbose = TRUE)

Arguments

replist

A list object created bySS_output().

add

add to existing plot (not yet implemented)

plot

plot to active plot device?

print

print to PNG files?

uncertainty

include plots showing uncertainty?

subplots

vector controlling which subplots to createNumbering of subplots is as follows:

  1. timeseries of SPR,

  2. timeseries of 1 - SPR,

  3. timeseries of SPR ratio (as specified in the starter file), and

  4. phase plot of Biomass ratio vs SPR ratio (as specified in thestarter file).

forecastplot

Include forecast years in plot?

col1

first color used

col2

second color used

col3

third color used

col4

fourth color used

sprtarg

F/SPR proxy target. "default" chooses based on model output,where models which have SPR_report_basis = 0 or 1 specified in the starterfile will use the SPR target specified in the forecast file. Models whichhave SPR_report_basis = 2 will use SPR at MSY for the SPR targetand models which have the SPR_report_basis = 3 will useSPR at Btarget for the SPR target in these plots. Zero or negative values ofsprtarg input here will cause no horizontal line to be plotted.

btarg

target depletion to be used in plots showing depletion. May beomitted by setting to NA. "default" chooses based on model output.

labels

vector of labels for plots (titles and axis labels)

pwidth

width of plot

pheight

height of plot

punits

units for PNG file

res

Resolution of plots printed to files.The default isres = 300.

ptsize

point size for PNG file

cex.main

character expansion for plot titles

plotdir

directory where PNG files will be written. by default it willbe the directory where the model was run.

verbose

report progress to R GUI?

Author(s)

Ian Stewart, Ian Taylor

See Also

SS_plots(),SS_output()


Plot selectivity

Description

Plot selectivity, including retention and other quantities, with additionalplots for time-varying selectivity.

Usage

SSplotSelex(  replist,  infotable = NULL,  fleets = "all",  fleetnames = "default",  sizefactors = c("Lsel"),  agefactors = c("Asel", "Asel2"),  years = "endyr",  minyr = -Inf,  maxyr = Inf,  season = 1,  sexes = "all",  selexlines = 1:6,  subplot = 1:25,  skipAgeSelex10 = TRUE,  plot = TRUE,  print = FALSE,  add = FALSE,  labels = c("Length (cm)", "Age (yr)", "Year", "Selectivity", "Retention",    "Discard mortality"),  col1 = "red",  col2 = "blue",  lwd = 2,  spacepoints = 5,  staggerpoints = 1,  legendloc = "bottomright",  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1,  mainTitle = TRUE,  showmain = lifecycle::deprecated(),  mar = NULL,  plotdir = "default",  verbose = TRUE)

Arguments

replist

A list object created bySS_output().

infotable

Optional table of information controlling appearance ofplot and legend. Is produced as output and can be modified and entered asinput.

fleets

Optional vector to subset fleets for which to make plots

fleetnames

Optional replacement for fleenames used in data file

sizefactors

Which elements of the factors column of SIZE_SELEX shouldbe included in plot of selectivity across multiple fleets?

agefactors

Which elements of the factors column of AGE_SELEX shouldbe included in plot of selectivity across multiple fleets?

years

Which years for selectivity are shown in multi-line plot(default = last year of model).

minyr

optional input for minimum year to show in plots

maxyr

optional input for maximum year to show in plots

season

Which season (if seasonal model) for selectivity shown inmulti-line plot (default = 1).

sexes

Optional vector to subset genders for which to make plots(1=females, 2=males)

selexlines

Vector to select which lines get plotted. values are 1.Selectivity, 2. Retention, 3. Discard mortality, 4. Keep.

subplot

Vector controlling which subplots to create.Numbering of subplots is as follows,

Plots with all fleets grouped together

  • 1 selectivity at length in end year for all fleets shown together

  • 2 selectivity at age in end year for all fleets shown together(this includes both age-based selectivity "Asel" and age values derivedfrom length-based, "Asel2". You can choose only one using"agefactors" if needed.)

Plots of time-varying length-based selectivity

  • 3 selectivity at length time-varying surface

  • 4 selectivity at length time-varying contour

  • 5 retention at length time-varying surface

  • 6 retention at length time-varying surface

  • 7 discard mortality time-varying surface

  • 8 discard mortality time-varying contour

Selectivity at length in end year by fleet

  • 9 selectivity, retention, and discard mortality at length in ending year

Plots of time-varying age-based selectivity

  • 11 selectivity at age time-varying surface

  • 12 selectivity at age time-varying contour

Selectivity at age in end year by fleet

  • 13 selectivity at age in ending year if time-varying

  • 14 selectivity at age in ending year if NOT time-varying

  • 15 matrix of selectivity deviations for semi-parametric selectivity

Selectivity for both/either age or length

  • 21 selectivity at age and length contour with overlaid growth curve

  • 22 selectivity with uncertainty if requested at end of control file

skipAgeSelex10

Exclude plots for age selectivity type 10 (selectivity= 1.0 for all ages beginning at age 1)?

plot

Plot to active plot device?

print

Print to PNG files?

add

Add to existing plot (not yet implemented)

labels

vector of labels for plots (titles and axis labels)

col1

color for female growth curve

col2

color for male growth curve

lwd

Line widths for plots

spacepoints

number of years between points shown on top of lines (forlong timeseries, points every year get mashed together)

staggerpoints

number of years to stagger the first point (ifspacepoints > 1) for each line (so that adjacent lines have points indifferent years)

legendloc

location of legend. See ?legend for more info.

pwidth

Default width of plots printed to files in units ofpunits. The default ispwidth=6.5.

pheight

Height of plots printed to png files in units ofpunits.Default is designed to allow two plots per page, withpheight_tall usedfor plots that work best with a taller format and a single plot per page.

punits

Units forpwidth andpheight. Can be "px"(pixels), "in" (inches), "cm" (centimeters), or "mm" (millimeters).The default ispunits="in".

res

Resolution of plots printed to files.The default isres = 300.

ptsize

Point size for plotted text in plots printed to files (seehelp("png") in R for details).

cex.main

character expansion for plot titles

mainTitle

Logical indicating if a title should be included at the top(not yet implemented for all plots)

showmain

Deprecated, use mainTitle instead.

mar

Either NULL to allow the default (which depends on whether the main title is included or not) or a numerical vector of the form c(bottom, left, top, right) which gives the number of lines of margin to be specified on the four sides of the plot, which is passed topar().

plotdir

Directory where PNG files will be written. By default it willbe the directory where the model was run.

verbose

A logical value specifying if output should be printedto the screen.

Author(s)

Ian Stewart, Ian Taylor

See Also

SS_plots(),SS_output()


Plot sex-ratio data and fits for two sex models

Description

Plot sex-ratio data and fits from Stock Synthesis output. Multi-figureplots depend onmake_multifig. The confidence intervals around theobserved points are based on a Jeffreys interval calculated fromthe adjusted input sample size (with a floor of 1).

Usage

SSplotSexRatio(  replist,  kind = "AGE",  sexratio.option = 2,  CI = 0.75,  plot = TRUE,  print = FALSE,  fleets = "all",  fleetnames = "default",  yupper = 4,  datonly = FALSE,  linescol = rgb(0.6, 0, 0.9, 0.7),  lwd = 2,  showsampsize = TRUE,  showeffN = TRUE,  axis1 = NULL,  axis2 = NULL,  pwidth = 6.5,  pheight = 5,  punits = "in",  ptsize = 10,  res = 300,  plotdir = "default",  cex.main = 1,  labels = c("Length (cm)", "Age (yr)", "Sex ratio (females:males)", "Fraction female"),  maxrows = 6,  maxcols = 6,  rows = 1,  cols = 1,  fixdims = TRUE,  verbose = TRUE,  mainTitle = FALSE,  ...)

Arguments

replist

A list object created bySS_output().

kind

indicator of type of plot can be "LEN", "SIZE", "AGE", "cond","GSTAGE", "L@A", or "W@A".

sexratio.option

code to choose among (1) female:male ratio or(2) fraction females out of the total

CI

confidence interval for uncertainty

plot

plot to active plot device?

print

print to PNG files?

fleets

optional vector to subset fleets for which plots will be made

fleetnames

optional vector of fleet names to put in the labels

yupper

upper limit on ymax (only applies for sexratio.option == 1)

datonly

make plots of data without fits?

linescol

Color for line showing expected value (default is purple).

lwd

line width

showsampsize

add sample sizes to plot

showeffN

add effective sample sizes to plot

axis1

position of bottom axis values

axis2

position of left size axis values

pwidth

default width of plots printed to files in units ofpunits. Default=7.

pheight

default height width of plots printed to files in units ofpunits. Default=7.

punits

units forpwidth andpheight. Can be "px"(pixels), "in" (inches), "cm" or "mm". Default="in".

ptsize

point size for plotted text in plots printed to files (seehelp("png") in R for details). Default=12.

res

Resolution of plots printed to files.The default isres = 300.

plotdir

directory where PNG files will be written. by default it willbe the directory where the model was run.

cex.main

character expansion parameter for plot titles

labels

vector of labels for plots (titles and axis labels)

maxrows

maximum (or fixed) number or rows of panels in the plot

maxcols

maximum (or fixed) number or columns of panels in the plotplots

rows

number or rows to return to as default for next plots to come orfor single plots

cols

number or cols to return to as default for next plots to come orfor single plots

fixdims

fix the dimensions at maxrows by maxcols or resize based onnumber of years of data

verbose

return updates of function progress to the R GUI?

mainTitle

Logical indicating if a title for the plot should be produced

...

additional arguments that will be passed to the plotting.

Author(s)

Cole Monnahan, Ian Taylor

References

Brown, L.; Cai, T. Tony; DasGupta, A. (2001).Interval Estimation for a Binomial Proportion. Statistical Science.16(2): 101-133. http://www.jstor.org/stable/2676784.

See Also

SS_plots(),make_multifig_sexratio()


Plot spawner-recruit curve.

Description

Plot spawner-recruit curve based on output from Stock Synthesis model.

Usage

SSplotSpawnrecruit(  replist,  subplot = 1:3,  add = FALSE,  plot = TRUE,  print = FALSE,  xlim = NULL,  ylim = NULL,  labels = c("Spawning biomass (mt)", "Recruitment (1,000s)", "Spawning output",    expression(paste("Spawning output (relative to ", italic(B)[0], ")")),    expression(paste("Recruitment (relative to  ", italic(R)[0], ")")),    "Log recruitment deviation"),  bioscale = "default",  plotdir = "default",  pwidth = 6.5,  pheight = 6.5,  punits = "in",  res = 300,  ptsize = 10,  verbose = TRUE,  colvec = c("blue", "black", "black", gray(0, 0.7)),  ltyvec = c(1, 2, 1, NA),  ptcol = "default",  legend = TRUE,  legendloc = NULL,  minyr = "default",  textmindev = 0.5,  relative = FALSE,  expected = TRUE,  estimated = TRUE,  bias_adjusted = TRUE,  show_env = TRUE,  virg = TRUE,  init = TRUE,  forecast = FALSE)

Arguments

replist

A list object created bySS_output().

subplot

vector of which subplots to show. 1=plot without labels,2=plot with year labels.

add

add to existing plot?

plot

plot to active plot device?

print

print to PNG files?

xlim

optional control of x range

ylim

optional control of y range

labels

vector containing x-axis label for models with spawning biomassin metric tons, y-axis label, and alternative x-axis for models with a fecundityrelationship making spawning output not equal to spawning biomass.

bioscale

multiplier on spawning biomass, set to 0.5 for single-sexmodels

plotdir

directory where PNG files will be written. by default it willbe the directory where the model was run.

pwidth

Default width of plots printed to files in units ofpunits. The default ispwidth=6.5.

pheight

Height of plots printed to png files in units ofpunits.Default is designed to allow two plots per page, withpheight_tall usedfor plots that work best with a taller format and a single plot per page.

punits

Units forpwidth andpheight. Can be "px"(pixels), "in" (inches), "cm" (centimeters), or "mm" (millimeters).The default ispunits="in".

res

Resolution of plots printed to files.The default isres = 300.

ptsize

Point size for plotted text in plots printed to files (seehelp("png") in R for details).

verbose

report progress to R GUI?

colvec

vector of length 4 with colors for 3 lines and 1 set of points(where the 4th value for the points is the color of the circle around thebackground color provided byptcol

ltyvec

vector of length 4 with line types for the 3 lines and 1 setof points, where the points are disconnected (lty=NA) by default

ptcol

vector or single value for the color of the points, "default"will by replaced by a vector of colors of length equal tonrow(replist[["recruit"]])

legend

add a legend to the figure?

legendloc

location of legend. By default it is chosen as the firstvalue in the set of "topleft", "topright", "bottomright" that results in nooverlap with the points in the plot, but the user can override this with theirchoice of location. See ?legend for more info on the options.

minyr

minimum year of recruitment deviation to show in plot

textmindev

minimum recruitment deviation for label to be added soonly extreme devs are labeled (labels are added to first and last years aswell). Default=0.7.

relative

scale both axes so that B0 and R0 are at 1to show spawning output and recruitment relative to the equilibrium

expected

show line for expected recruitment (stock-recruit curve)

estimated

show points for estimated recruitment values(including deviations)

bias_adjusted

show lines for bias adjusted expected recruitment

show_env

add line for expected recruitment with environmentalvariability

virg

add point for equilibrium conditions (x=B0,y=R0)

init

add point for initial conditions (x=B1,y=R1), only appearsif this point differs from virgin values

forecast

include forecast years in the curve?

Author(s)

Ian Stewart, Ian Taylor

See Also

SS_plots(),SS_output()


Plot the summary F (or harvest rate).

Description

Plots the summary F (or harvest rate) as set up in the starter file Needs alot of work to be generalized

Usage

SSplotSummaryF(  replist,  yrs = "all",  Ftgt = NA,  ylab = "Summary Fishing Mortality",  plot = TRUE,  print = FALSE,  plotdir = "default",  verbose = TRUE,  uncertainty = TRUE,  add = FALSE,  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  mar = NULL)

Arguments

replist

A list object created bySS_output().

yrs

Which years to include.

Ftgt

Target F where horizontal line is shown.

ylab

Y-axis label.

plot

Plot to active plot device?

print

Print to PNG files?

plotdir

Directory where PNG files will be written. By default it willbe the directory where the model was run.

verbose

Verbose output to R console?

uncertainty

Show 95% uncertainty intervals around point estimates?

add

add to existing plot

pwidth

Default width of plots printed to files in units ofpunits. The default ispwidth=6.5.

pheight

Height of plots printed to png files in units ofpunits.Default is designed to allow two plots per page, withpheight_tall usedfor plots that work best with a taller format and a single plot per page.

punits

Units forpwidth andpheight. Can be "px"(pixels), "in" (inches), "cm" (centimeters), or "mm" (millimeters).The default ispunits="in".

res

Resolution of plots printed to files.The default isres = 300.

ptsize

Point size for plotted text in plots printed to files (seehelp("png") in R for details).

mar

Either NULL to allow the default (which depends on whether the main title is included or not) or a numerical vector of the form c(bottom, left, top, right) which gives the number of lines of margin to be specified on the four sides of the plot, which is passed topar().

Author(s)

Allan Hicks

See Also

SSplotTimeseries()


Plot tagging data and fits

Description

Plot observed and expected tag recaptures in aggregate and by tag group.

Usage

SSplotTags(  replist = replist,  subplots = 1:10,  latency = NULL,  taggroups = NULL,  rows = 1,  cols = 1,  tagrows = 3,  tagcols = 3,  plot = TRUE,  print = FALSE,  pntscalar = 2.6,  minnbubble = 8,  pwidth = 6.5,  pheight = 5,  punits = "in",  ptsize = 10,  res = 300,  cex.main = 1,  col1 = rgb(0, 0, 1, 0.7),  col2 = "red",  col3 = "grey95",  col4 = "grey70",  labels = c("Year", "Frequency", "Tag Group", "Fit to tag recaptures by tag group",    "Post-latency tag recaptures aggregated across tag groups",    "Observed tag recaptures by year and tag group",    "Residuals for post-latency tag recaptures: (obs-exp)/sqrt(exp)",    "Observed and expected post-latency tag recaptures by year and tag group",    "Summarized observed and expected numbers of recaptures by fleet",    "Pearson residuals by tag group"),  plotdir = "default",  verbose = TRUE)

Arguments

replist

A list object created bySS_output().

subplots

vector controlling which subplots to create

latency

period of tag mixing to exclude from plots (in future couldbe included in SS output)

taggroups

which tag groups to include in the plots. Default=NULLcauses all groups to be included.

rows

number or rows of panels for regular plots

cols

number or columns of panels for regular plots

tagrows

number or rows of panels for multi-panel plots

tagcols

number or columns of panels for multi-panel plots

plot

plot to active plot device?

print

print to PNG files?

pntscalar

maximum bubble size for balloon plots; each plot scaledindependently based on this maximum size and the values plotted. Often someplots look better with one value and others with a larger or smaller value.Default=2.6

minnbubble

minimum number of years below which blank years will beadded to bubble plots to avoid cropping

pwidth

default width of plots printed to files in units ofpunits. Default=7.

pheight

default height width of plots printed to files in units ofpunits. Default=7.

punits

units forpwidth andpheight. Can be "px"(pixels), "in" (inches), "cm" or "mm". Default="in".

ptsize

point size for plotted text in plots printed to files (seehelp("png") in R for details). Default=12.

res

Resolution of plots printed to files.The default isres = 300.

cex.main

character expansion parameter for plot titles

col1

color for bubbles

col2

color for lines with expected values

col3

shading color for observations within latency period

col4

shading color for observations after latency period

labels

vector of labels for plots (titles and axis labels)

plotdir

directory where PNG files will be written. by default it willbe the directory where the model was run.

verbose

return updates of function progress to the R GUI?

Author(s)

Andre E. Punt, Ian G. Taylor, Ashleigh J. Novak

See Also

SS_plots(),SS_output()


Plot timeseries data

Description

Plot timeseries data contained in TIME_SERIES output from Stock Synthesisreport file. Some values have optional uncertainty intervals.

Usage

SSplotTimeseries(  replist,  subplot,  add = FALSE,  areas = "all",  areacols = "default",  areanames = "default",  forecastplot = TRUE,  uncertainty = TRUE,  bioscale = 1,  minyr = -Inf,  maxyr = Inf,  plot = TRUE,  print = FALSE,  plotdir = "default",  verbose = TRUE,  btarg = "default",  minbthresh = "default",  xlab = "Year",  labels = NULL,  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1,  mainTitle = FALSE,  mar = NULL)

Arguments

replist

A list object created bySS_output().

subplot

number controlling which subplot to createNumbering of subplots is as follows, where the spawning biomass plots(7 to 10) are provided first when this function is called bySS_plots():

  • 1 Total biomass (mt) with forecast

  • 2 Total biomass by area (spatial models only)

  • 3 Total biomass (mt) at beginning of spawning season with forecast

  • 4 Summary biomass (mt) with forecast

  • 5 Summary biomass (mt) by area (spatial models only)

  • 6 Summary biomass (mt) at beginning of season 1 with forecast

  • 7 Spawning output with forecast with ~95% asymptotic intervals

  • 8 Spawning output by area (spatial models only)

  • 9 Relative spawning output with forecast with ~95% asymptotic intervals

  • 10 Relative spawning output by area (spatial models only)

  • 11 Age-0 recruits (1,000s) with forecast with ~95% asymptotic intervals

  • 12 Age-0 recruits by area (spatial models only)

  • 13 Fraction of recruits by area (spatial models only)

  • 14 Age-0 recruits (1,000s) by birth season with forecast

  • 15 Fraction of total Age-0 recruits by birth season with forecast

add

add to existing plot? (not yet implemented)

areas

optional subset of areas to plot for spatial models

areacols

vector of colors by area. Default uses rich.colors by ArniMagnusson

areanames

names for areas. Default is to use Area1, Area2,...

forecastplot

add points from forecast years

uncertainty

add intervals around quantities for which uncertainty isavailable

bioscale

scaling for spawning biomass. Default = 1.Previously this was set to0.5 for single-sex models, and 1.0 for all others, but now single-sexmodels are assumed to use the -1 option for Nsexes in the data file so thescaling is done automatically by SS.

minyr

optional input for minimum year to show in plots

maxyr

optional input for maximum year to show in plots

plot

plot to active plot device?

print

print to PNG files?

plotdir

directory where PNG or PDF files will be written. by defaultit will be the directory where the model was run.

verbose

report progress to R GUI?

btarg

Target depletion to be used in plots showing depletion. May beomitted by setting to 0. "default" chooses value based on modeloutput.

minbthresh

Threshold depletion to be used in plots showing depletion.May be omitted by setting to 0. "default" assumes 0.25 unless btarg in modeloutput is 0.25 in which case minbthresh = 0.125 (U.S. west coast flatfish).

xlab

x axis label for all plots

labels

vector of labels for plots (titles and axis labels)

pwidth

width of plot

pheight

height of plot

punits

units for PNG file

res

Resolution of plots printed to files.The default isres = 300.

ptsize

point size for PNG file

cex.main

character expansion for plot titles

mainTitle

Logical indicating if a title should be included at the top(not yet implemented for all plots)

mar

Either NULL to allow the default (which depends on whether the main title is included or not) or a numerical vector of the form c(bottom, left, top, right) which gives the number of lines of margin to be specified on the four sides of the plot, which is passed topar().

Author(s)

Ian Taylor, Ian Stewart

See Also

SS_plots(),SS_output()


Plot yield and surplus production.

Description

Plot yield and surplus production from Stock Synthesis output. Surplusproduction is based on Walters et al. (2008).

Usage

SSplotYield(  replist,  subplots = 1:4,  refpoints = c("MSY", "Btgt", "SPR", "Current"),  add = FALSE,  plot = TRUE,  print = FALSE,  labels = c("Fraction unfished", "Equilibrium yield (mt)", "Total biomass (mt)",    "Surplus production (mt)", "Yield per recruit (kg)"),  col = "blue",  col2 = "black",  lty = 1,  lwd = 2,  cex.main = 1,  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  plotdir = "default",  verbose = TRUE)

Arguments

replist

A list object created bySS_output().

subplots

vector controlling which subplots to createNumbering of subplots is as follows:

  • 1 yield curve

  • 2 yield curve with reference points

  • 3 surplus production vs. biomass plots (Walters et al. 2008)

refpoints

character vector of which reference points to display insubplot 2, from the options 'MSY', 'Btgt', and 'SPR'.

add

add to existing plot? (not yet implemented)

plot

plot to active plot device?

print

print to PNG files?

labels

vector of labels for plots (titles and axis labels)

col

line color for equilibrium plot

col2

line color for dynamic surplus production plot

lty

line type (only applied to equilibrium yield plot at this time)

lwd

line width (only applied to equilibrium yield plot at this time)

cex.main

character expansion for plot titles

pwidth

width of plot

pheight

height of plot

punits

units for PNG file

res

Resolution of plots printed to files.The default isres = 300.

ptsize

point size for PNG file

plotdir

directory where PNG files will be written. by default it willbe the directory where the model was run.

verbose

report progress to R GUI?

Author(s)

Ian Stewart, Ian Taylor

References

Walters, Hilborn, and Christensen, 2008, Surplus productiondynamics in declining and recovering fish populations. Can. J. Fish. Aquat.Sci. 65: 2536-2551

See Also

SS_plots(),SS_output()


Summarize the output from multiple Stock Synthesis models.

Description

Summarize various quantities from the model output collected bySSgetoutput() and return them in a list of tables and vectors.

Usage

SSsummarize(  biglist,  sizeselfactor = "Lsel",  ageselfactor = "Asel",  selfleet = NULL,  selyr = "startyr",  selgender = 1,  SpawnOutputUnits = NULL,  lowerCI = 0.025,  upperCI = 0.975,  verbose = TRUE)

Arguments

biglist

A list of lists, one for each model. The individual lists canbe created bySS_output() or the list of lists can becreated bySSgetoutput() (which iteratively callsSS_output()).

sizeselfactor

A string or vector of strings indicating which elementsof the selectivity at length output to summarize. Default=c("Lsel").

ageselfactor

A string or vector of strings indicating which elementsof the selectivity at age output to summarize. Default=c("Asel").

selfleet

Vector of fleets for which selectivity will be summarized.NULL=all fleets. Default=NULL.

selyr

String or vector of years for which selectivity will besummarized. NOTE: NOT CURRENTLY WORKING. Options: NULL=all years,"startyr" = first year.

selgender

Vector of genders (1 and/or 2) for which selectivity willbe summarized. NULL=all genders. Default=NULL.

SpawnOutputUnits

Optional single value or vector of "biomass" or"numbers" giving units of spawning for each model.

lowerCI

Quantile for lower bound on calculated intervals. Default =0.025 for 95% intervals.

upperCI

Quantile for upper bound on calculated intervals. Default =0.975 for 95% intervals.

verbose

A logical value specifying if output should be printedto the screen.

Author(s)

Ian Taylor

See Also

SSgetoutput()


make table comparing quantities across models

Description

Creates a table comparing key quantities from multiple models, which is areduction of the full information in various parts of the list created usingtheSSsummarize function.

Usage

SStableComparisons(  summaryoutput,  models = "all",  likenames = c("TOTAL", "Survey", "Length_comp", "Age_comp", "priors", "Size_at_age"),  names = c("Recr_Virgin", "R0", "steep", "NatM", "L_at_Amax", "VonBert_K", "SSB_Virg",    "Bratio_2021", "SPRratio_2020"),  digits = NULL,  modelnames = "default",  csv = FALSE,  csvdir = "workingdirectory",  csvfile = "parameter_comparison_table.csv",  verbose = TRUE,  mcmc = FALSE)

Arguments

summaryoutput

list created bySSsummarize

models

optional subset of the models described insummaryoutput. Either "all" or a vector of numbers indicatingcolumns in summary tables.

likenames

Labels for likelihood values to include, should matchsubstring of labels insummaryoutput[["likelihoods"]].

names

Labels for parameters or derived quantities to include, shouldmatch substring of labels insummaryoutput[["pars"]] orsummaryoutput[["quants"]].

digits

Optional vector of the number of decimal digits to use inreporting each quantity.

modelnames

optional vector of labels to use as column names. Defaultis 'model1','model2',etc.

csv

write resulting table to CSV file?

csvdir

directory for optional CSV file

csvfile

filename for CSV file

verbose

report progress to R GUI?

mcmc

summarize MCMC output in table?

Author(s)

Ian Taylor

See Also

SSsummarize(),SSplotComparisons(),SS_output()


Plot unavailable spawning output

Description

Calculate and plot the unavailable spawning output- separating out ones thatare unavailable because they're too small to be selected from ones that aretoo big to be selected

Usage

SSunavailableSpawningOutput(  replist,  plot = TRUE,  print = FALSE,  plotdir = "default",  pwidth = 6.5,  pheight = 5,  punits = "in",  res = 300,  ptsize = 10,  cex.main = 1)

Arguments

replist

A list object created bySS_output().

plot

Plot to active plot device?

print

Print to PNG files?

plotdir

Directory where PNG files will be written. by default it willbe the directory where the model was run.

pwidth

Width of plot

pheight

Height of plot

punits

Units for PNG file

res

Resolution of plots printed to files.The default isres = 300.

ptsize

Point size for PNG file

cex.main

Character expansion for plot titles

Author(s)

Megan Stachura, Andrew Cooper, Andi Stephens, Neil Klaer, Ian G. Taylor


Create a plot for the TSC report

Description

Creates a plot of catch and spawning biomass from the output ofSS_output() for the NOAA TSC report.

Usage

TSCplot(  SSout,  yrs = "default",  ylimBar = "default",  ylimDepl = c(0, 1.025),  colBar = "yellow",  cexBarLabels = 1.1,  cex.axis = 1.1,  space = 0,  pchDepl = 19,  colDepl = "red",  lwdDepl = 3,  shiftDepl = 0.25,  pchSpace = 5,  ht = 4,  wd = 7,  labelLines = 2.8,  makePDF = NULL,  makePNG = NULL,  MCMC = FALSE)

Arguments

SSout

The output fromSS_output()

yrs

The vector of years to plot

ylimBar

y-axis limits for catch barplot

ylimDepl

y-axis limits for depletion line

colBar

colors of the bars

cexBarLabels

character expansion for the labels underneath the bars(years)

cex.axis

character expansion for the axis labels

space

space between bars (see space argument ofbarplot)

pchDepl

character type for points on the depletion line

colDepl

color of the points on the depletion line

lwdDepl

width of the depletion line

shiftDepl

shift from beginning of the year for the points on thedepletion line. Helps to guide the eye for exactly which year it correspondsto.

pchSpace

number of years between points on the depletion line. Highernumbers help tidy up the plot when plotting many years.

ht

Height of the plot in inches

wd

Width of the plot in inches

labelLines

line argument formtext to move the axis labels

makePDF

filename for a pdf file. If NULL it does not make a pdf. Canspecify a pdf filename or a png filename. Not both at the same time.

makePNG

filename for a png image. If NULL it does not make a png.Can specify a pdf filename or a png filename. Not both at the same time.

MCMC

If TRUE, will use mcmc results. It needs a list element called'mcmc' on SSout.

Details

It creates a plot on the current graphics device, in a pdf file, or as a pngimage of the figure used in the TSC report produced by the NWFSC. Itexpects the SS results read in bySS_output(). If MCMC resultsare to be plotted, a 'mcmc' list element should be added using theSSgetMCMC() function. See the examples below.

Value

Returns a data frame with the years, spawning biomass, depletion,and total dead catch.

Author(s)

Allan Hicks

See Also

SS_output()SSgetMCMC()

Examples

## Not run: # define directorydirectory <- "C:\\NOAA2011\\Dover\\Models\\base_20110701"# read model outputbase <- SS_output(dir = directory, covar = FALSE, verbose = FALSE)# show the plot in RTSCplot(base)TSCplot(base, yrs = 2000:2011, pchSpace = 1)# Create the plot as a PNG fileTSCplot(base, makePNG = "C:\\NOAA2012\\Assessments\\TSCdover.png")# Create the plot as a PDF fileTSCplot(base, makePDF = "C:\\NOAA2012\\Assessment\\TSCdover.pdf")# Model with MCMC resultsdirectory <- "C:/Models"base <- SS_output(dir = directory, dir.mcmc = "mcmc")TSCplot(base, ylimDepl = c(0, 1.25), pchSpace = 1, MCMC = TRUE)## End(Not run)

Add legend to plots

Description

ss3diags function to add legend to plots

Usage

add_legend(  legendlabels,  legendloc = "topleft",  legendorder = NULL,  legendncol = 1,  legendcex = 1,  legendsp = 0.9,  col = NULL,  pch = NULL,  lty = 1,  lwd = 2,  type = "l")

Arguments

legendlabels

Optional vector of labels to include in legend.

legendloc

Location of legend. Either a string like "topleft" or avector of two numeric values representing the fraction of the maximum inthe x and y dimensions, respectively. Seehelp("legend") for more info onthe string options.

legendorder

Optional vector of model numbers that can be used to havethe legend display the model names in an order that is different than thatwhich is represented in the summary input object.

legendncol

Number of columns for the legend.

legendcex

Allows to adjust legend cex. Defaults to 1.

legendsp

Space between legend labels

col

Optional vector of colors to be used for lines. Input NULL

pch

Optional vector of plot character values

lty

Optional vector of line types

lwd

Optional vector of line widths

type

Type parameter passed to points (default 'o' overplots points ontop of lines)


Create a bubble plot.

Description

Bubble plot based on function vaguely based onbubble by EdzerPebesma in gstat package. By default, positive values have closed bubblesand negative values have open bubbles.

Usage

bubble3(  x,  y,  z,  col = 1,  cexZ1 = 5,  maxsize = NULL,  do.sqrt = TRUE,  bg.open = gray(0.95, 0.3),  legend = TRUE,  legendloc = "top",  legend.z = "default",  legend.yadj = 1.1,  main = "",  cex.main = 1,  xlab = "",  ylab = "",  minnbubble = 3,  xlim = NULL,  ylim = NULL,  axis1 = TRUE,  xlimextra = 1,  add = FALSE,  las = 1,  allopen = TRUE)

Arguments

x

Vector of x-values.

y

Vector of y-values.

z

Vector of bubble sizes, where positive sizes will be plotted asclosed bubbles and negative as open unlessallopen==TRUE.

col

Color for bubbles. Should be either a single value or vectorof length equal to x, y, and z vectors.

cexZ1

Character expansion (cex) value for a proportion of 1.0.

maxsize

Size of largest bubble. Preferred option is now an expansionfactor for a bubble with z=1 (seecexZ1 above).

do.sqrt

Should size be based on the area? (Diameter proportional tosqrt(z)). Default=TRUE.

bg.open

background color for open bubbles (border will equal 'col')

legend

Add a legend to the plot?

legendloc

Location for legend (default='top')

legend.z

If a legend is added, what z values will be shown. Defaultis c(-3,-2,-1,.1,1,2,3) for Pearson-like quantities and a smaller range forproportions that are all less than 1.

legend.yadj

If a legend is added, how much should the y-axis beexpanded to make space for it.

main

Title of plot. Default="".

cex.main

Character expansion for title. Default=1.

xlab

X-axis label.

ylab

Y-axis label.

minnbubble

Minimum number of unique x values below which extra spaceis added to horizontal axis (to make plot look better). Default = 8.

xlim

Optional limits on x-range.

ylim

Optional limits on y-range.

axis1

Show the horizontal axis on plot? Option allows turning off foruse in multi-figure plots.

xlimextra

Extra space (see minnbubble above). Default = 1.

add

Add bubbles to existing plot? Default=FALSE.

las

Style of axis labels (see ?par for more info).

allopen

Should all bubbles be open (instead of just negative values)?

Author(s)

Ian Stewart and Ian Taylor


Check input argumentinputlist

Description

Check the elements of theinputlist list used as an argument inSS_write() function.

Usage

check_inputlist(inputlist)

Arguments

inputlist

List created by theSS_read() function withelements "dat", "ctl", "start", "fore", and (optionally) "wtatage".

Value

Either TRUE if the input list is valid, or FALSE if not, witha warning about which elements are missing.

Author(s)

Kelli F. Johnson, Ian G. Taylor

See Also

SS_write()


Check input argumentmodel

Description

Check that the executable name provided inmodel,an input argument to numerousr4ss functions,does not contain the extension and is available.

Usage

check_model(model, mydir = getwd())

Arguments

model

Name of the Stock Synthesis model file (which has the .exe foron Windows) inmydir without the extension (if any), e.g.,"ss" or"ss_win".

mydir

The directory wheremodel is located.

Value

A cleanedmodel name based on the input argument.

Author(s)

Kelli F. Johnson


Copy a the Stock Synthesis input files from one directory to another

Description

Reads the starter.ss file to figure out the names of the control anddata files, than copies those files along with starter.ss, forecast.ss,and wtatage.ss (if present) to a new directory, as specified.

Usage

copy_SS_inputs(  dir.old = NULL,  dir.new = NULL,  create.dir = TRUE,  overwrite = FALSE,  recursive = FALSE,  use_ss_new = FALSE,  copy_exe = FALSE,  copy_par = FALSE,  dir.exe = NULL,  verbose = TRUE)

Arguments

dir.old

Location of model files to be copied, either an absolutepath or relative to the working directory.

dir.new

New location to which the files should be copied,either an absolute path or relative to the working directory.

create.dir

Create dir.new directory if it doesn't exist already?

overwrite

Overwrite existing files with matching names?

recursive

logical. Should elements of the path other than the last becreated?

use_ss_new

Use .ss_new files instead of original inputs?

copy_exe

Copy any executables found in dir.old to dir.new ordir.exe (if provided)?

copy_par

Copy any .par files found in dir.old to dir.new?

dir.exe

Path to executable to copy instead of any in dir.old

verbose

Return updates of function progress to the R console?

Value

Logical indicating whether all input files were copied successfully.

Author(s)

Ian Taylor

Examples

## Not run: copy_SS_inputs(  dir.old = "c:/SS/old_model",  dir.new = "c:/SS/new_model")## End(Not run)

Rename Stock Synthesis files by adding integer value

Description

Rename files found withpattern by addingi to theirname before the extension.

Usage

file_increment(  i,  verbose = FALSE,  pattern = "^[CcPRw][a-zA-Z]+\\.sso|summary\\.sso|\\.par$")

Arguments

i

An integer value to append to the file name before the.sso extension.

verbose

A logical value specifying if output should be printedto the screen.

pattern

A character value specifying the file names to searchfor ingetwd().

Details

The.par file, which is the only file extension searched forwith the default entry that does not end in.sso, ismodified differently.⁠_i.sso⁠ is added to the file name.

Value

Invisibly returns a vector of logical values specifyingwhether or not the file was successfully renamed.

Author(s)

Kelli F. Johnson


Read admodel.hes file

Description

This function reads in all of the information contained in the.hes file. Some is needed for relaxing the covariance matrix, while the restis recorded and rewritten to file as ADMB expects.

Usage

getADMBHessian(File = getwd(), FileName = "admodel.hes")

Arguments

File

Directory in which .hes file is located. Defaults to the workingdirectory.

FileName

Name of .hes file. Defaults to admodel.hes.

Value

A list with elements num.pars, hes, hybrid_bounded_flag, and scale.

Note

Explanation of the methods (in PDF form):https://github.com/admb-project/admb-examples/blob/master/admb-tricks/covariance-calculations/ADMB_Covariance_Calculations.pdf

Author(s)

Cole Monnahan

See Also

read.admbFit(),NegLogInt_Fn()


Gather information for the NOAA Species Information System (SIS)

Description

Processes model results contained in the list created bySS_output() in a format that is more convenient for submissionto SIS. Currently the results are returned invisibly as a list of two tablesand written to a CSV file from which results could be copied into SIS.In the future some more direct link could be explored to avoid the manualcopy step.

Usage

get_SIS_info(  model,  dir = NULL,  writecsv = TRUE,  stock = "StockName",  final_year = 2019,  data_year = NULL,  sciencecenter = "NWFSC",  Mgt_Council = "NA")

Arguments

model

Output from SS_output

dir

Directory where the file will be written

writecsv

Write results to a CSV file (where the name will have theformat "[stock]_2019_SIS_info.csv" wherestockis an additional input

stock

String to prepend id info to filename for CSV file

final_year

Year of assessment and reference points(typically will bemodel[["endyr"]] + 1)

data_year

Last year of of timeseries data

sciencecenter

Origin of assessment report

Mgt_Council

Council jurisdiction. Currently the only optionoutside of the default is Gulf of Mexico ("GM")

Author(s)

Ian G. Taylor, Andi Stephens, LaTreese S. Denson

See Also

SS_output()

Examples

## Not run: # directory with the model outputmydir <- file.path(path.package("r4ss"), "extdata/simple_3.30.13")# read the model outputmodel <- SS_output(dir = mydir)# run get_SIS_info:info <- get_SIS_info(model, stock = "SimpleExample")## End(Not run)

Collect comments lines starting from "#C"in datfile, ctlfile, starter.ss, forecast.ss etc

Description

This function is used internally by SS_readdat_3.30,SS_readctl_3.30.This will identify 1st numeric data in dat (vector of string)Then this function collects lines starting "#C" from linesabove 1st numeric data.

Usage

get_comments(dat, defaultComments = NULL)

Arguments

dat

vector of strings usually outputs of readLines(*)* is filename of datfile, ctlfile etc

defaultComments

vector of stringsdefault : NULL, to read whole commentsIf this function finds lines containg one of elementsof defaultComments, those lines will be ignorede.g. c("^#C file created using the SS_writectl function in the R package r4ss","^#C file write time:")is given, comments generated by SS_writectl_3.30 will be ignored.

Author(s)

Yukio Takeuchi

See Also

SS_readdat,SS_readdat_3.30,SS_readctl,SS_readctl_3.30


Get the name of the data .ss_new file in a directory

Description

In previous versions of Stock Synthesis,the file new data file was nameddata.ss_new.⁠_echo⁠ was added to the name when the file was parsed into three separatefiles.

Usage

get_dat_new_name(dir)

Arguments

dir

Relative or absolute path to a directory

Value

A string with the name of the data .ss_new file. If not found, willbe NA. Both of strings are searched for usingdir(pattern = ) andif both exist, thendata_echo.ss_new is returned.


Get the highest phase used in the control file

Description

Get the highest phase used in the control file

Usage

get_last_phase(ctl)

Arguments

ctl

A control file list read in usingr4ss::SS_readctl.

Author(s)

Kathryn Doering


Get the tuning table

Description

Get the tuning table

Usage

get_tuning_table(  replist,  fleets,  option,  digits = 6,  write = TRUE,  verbose = TRUE)

Arguments

replist

A list object created bySS_output().

fleets

A vector of fleet numbers

option

Which type of tuning: 'none', 'Francis', 'MI', or 'DM'

digits

Number of digits to round numbers to

write

Write suggested tunings to a file 'suggested_tunings.ss'

verbose

A logical value specifying if output should be printedto the screen.


Get time varying parameter labels

Description

function to add get the names of short time varying parameter lines

Usage

get_tv_parlabs(full_parms, block_design)

Arguments

full_parms

the dataframe with the full parameter lines in the controlfile as read in by r4ss.

block_design

The block design in the control file as read in by r4ss.


Utility function to test if x is "numerically" integer wrt machine epsilontaken from example section of help of is.integer

Description

Utility function to test if x is "numerically" integer wrt machine epsilontaken from example section of help of is.integer

Usage

is.wholenumber(x, tol = .Machine[["double.eps"]]^0.5)

Arguments

x

value to check if it is "integer"

tol

tolerace


Create multi-figure plots.

Description

Function created as an alternative to lattice package for multi-figure plotsof composition data and fits from Stock Synthesis output.

Usage

make_multifig(  ptsx,  ptsy,  yr,  linesx = 0,  linesy = 0,  ptsSD = 0,  sampsize = 0,  effN = 0,  showsampsize = TRUE,  showeffN = TRUE,  sampsize_label = "N=",  effN_label = "effN=",  sampsizeround = 1,  maxrows = 6,  maxcols = 6,  rows = 1,  cols = 1,  fixdims = TRUE,  main = "",  cex.main = 1,  xlab = "",  ylab = "",  size = 1,  cexZ1 = 1.5,  bublegend = TRUE,  maxsize = NULL,  do.sqrt = TRUE,  minnbubble = 8,  allopen = TRUE,  xbuffer = c(0.1, 0.1),  ybuffer = c(0, 0.15),  yupper = NULL,  ymin0 = TRUE,  xlas = 0,  ylas = NULL,  axis1 = NULL,  axis2 = NULL,  axis1labs = NULL,  linepos = 1,  type = "o",  polygons = TRUE,  bars = FALSE,  barwidth = "default",  ptscex = 1,  ptscol = 1,  ptscol2 = 1,  colvec = c(rgb(1, 0, 0, 0.7), rgb(0, 0, 1, 0.7), rgb(0.1, 0.1, 0.1, 0.7)),  linescol = c(rgb(0, 0.8, 0, 0.7), rgb(1, 0, 0, 0.7), rgb(0, 0, 1, 0.7)),  lty = 1,  lwd = 2,  pch = 1,  nlegends = 3,  legtext = list("yr", "sampsize", "effN"),  legx = "default",  legy = "default",  legadjx = "default",  legadjy = "default",  legsize = c(1.2, 1),  legfont = c(2, 1),  venusmars = TRUE,  sampsizeline = FALSE,  effNline = FALSE,  sampsizemean = NULL,  effNmean = NULL,  ipage = 0,  scalebins = FALSE,  sexvec = NULL,  multifig_colpolygon = grey(c(0.6, 0.8, 0.7), alpha = 0.7),  multifig_oma = NULL,  ...)

Arguments

ptsx

vector of x values for points or bars

ptsy

vector of y values for points or bars of same length as ptsx

yr

vector of category values (years) of same length as ptsx

linesx

optional vector of x values for lines

linesy

optional vector of y values for lines

ptsSD

optional vector of standard deviations used to plot error barson top of each point under the assumption of normally distributed error

sampsize

optional sample size vector of same length as ptsx

effN

optional effective sample size vector of same length as ptsx

showsampsize

show sample size values on plot?

showeffN

show effective sample size values on plot?

sampsize_label

label on sampsize

effN_label

label on effN

sampsizeround

rounding level for sample size values

maxrows

maximum (or fixed) number or rows of panels in the plot

maxcols

maximum (or fixed) number or columns of panels in the plot

rows

number or rows to return to as default for next plots to come orfor single plots

cols

number or cols to return to as default for next plots to come orfor single plots

fixdims

fix the dimensions at maxrows by maxcols or resize based onnumber of elements inyr input.

main

title of plot

cex.main

character expansion for title

xlab

x-axis label

ylab

y-axis label

size

vector of bubbles sizes if making a bubble plot

cexZ1

Character expansion (cex) for point associated with value of 1.

bublegend

Add legend with example bubble sizes to bubble plots.

maxsize

maximum size of bubbles

do.sqrt

scale bubbles based on sqrt of size vector. see ?bubble3 formore info.

minnbubble

number of unique x values before adding buffer. see?bubble3 for more info.

allopen

should all bubbles be open? see ?bubble3 for more info.

xbuffer

extra space around points on the left and right as fractionof total width of plot

ybuffer

extra space around points on the bottom and top as fractionof total height of plot

yupper

upper limit on ymax (applied before addition of ybuffer)

ymin0

fix minimum y-value at 0?

xlas

label style (las) input for x-axis. Default 0 has horizontallabels, input 2 would provide vertical lables.

ylas

label style (las) input for y-axis. Default NULL has horizontallabels when all labels have fewer than 6 characters and vertical otherwise.Input 0 would force vertical labels, and 1 would force horizontal.

axis1

optional position of bottom axis values

axis2

optional position of left size axis values

axis1labs

optional vector of labels for axis1 (either NULL or needs tomatch length of axis1)

linepos

should lines be added on top of points (linepos=1) or behind(linepos=2)? A value of linepos = 0 will result in no line.

type

type of line/points used for observed values (see 'type' in?plot for details) on top of a grey polygon. Default is "o" for overplottingpoints on lines.

polygons

should polygons be added to the(turning off is required for sex-ratio plot)

bars

should the ptsx/ptsy values be bars instead of points(TRUE/FALSE) NOT CURRENTLY FUNCTIONAL

barwidth

width of bars in barplot, default method chooses based onquick and dirty formula also, current method of plot(...type='h') could bereplaced with better approach

ptscex

character expansion factor for points (default=1)

ptscol

color for points/bars

ptscol2

color for negative value points in bubble plots

colvec

Vector of length 3 with colors for females, males, unsexed fish

linescol

color for lines

lty

line type

lwd

line width

pch

point character type

nlegends

number of lines of text to add as legends in each plot

legtext

text in legend, a list of length=nlegends. values may be anyof 1. "yr", 2. "sampsize", 3. "effN", or a vector of length = ptsx.

legx

vector of length=nlegends of x-values of legends (default isfirst one on left, all after on right)

legy

vector of length=nlegends of y-values of legends (default is topfor all plots)

legadjx

left/right adjustment of legends around legx

legadjy

left/right adjustment of legends around legy

legsize

font size for legends. default=c(1.2,1.0) (larger for yearand normal for others)

legfont

font type for legends, same as "font" under ?par

venusmars

Label females and males with venus and mars symbols?

sampsizeline

show line for input sample sizes on top of conditionalage-at-length plots (TRUE/FALSE/scalar, still in development)

effNline

show line for effective sample sizes on top of conditionalage-at-length plots (TRUE/FALSE/scalar, still in development)

sampsizemean

mean input sample size value (used when sampsizeline=TRUE)

effNmean

mean effective sample size value (used when effNline=TRUE)

ipage

which page of plots when covering more than will fit withinmaxrows by maxcols.

scalebins

Rescale expected and observed proportions by dividing bybin width for models where bins have different widths? Caution!: May notwork correctly in all cases.

sexvec

vector of sex codes if more than one present (otherwise NULL)

multifig_colpolygon

vector of polygon fill colors of length 3(for females, males, and unsexed fish). Can be input to SS_plots and will bepassed to this function via the ... argument.

multifig_oma

vector of outer margins. Can be input to SS_plots and will bepassed to this function via the ... argument.

...

additional arguments passed topar.

Author(s)

Ian Taylor

See Also

SS_plots(),SSplotComps()


Create multi-figure sex ratio plots.

Description

Modified version ofmake_multifig() for multi-figureplots of sex ratio data with crude confidence intervals (+/i 1 se) andfits from Stock Synthesis output.

Usage

make_multifig_sexratio(  dbase,  sexratio.option = 2,  CI = 0.75,  sampsizeround = 1,  maxrows = 6,  maxcols = 6,  rows = 1,  cols = 1,  fixdims = TRUE,  main = "",  cex.main = 1,  xlab = "",  ylab = "Fraction female",  horiz_lab = "default",  xbuffer = c(0.1, 0.1),  ybuffer = "default",  yupper = NULL,  datonly = FALSE,  showsampsize = TRUE,  showeffN = TRUE,  axis1 = NULL,  axis2 = NULL,  ptscex = 1,  ptscol = gray(0.5),  linescol = 4,  lty = 1,  lwd = 2,  nlegends = 3,  legtext = list("yr", "sampsize", "effN"),  legx = "default",  legy = "default",  legadjx = "default",  legadjy = "default",  legsize = c(1.2, 1),  legfont = c(2, 1),  ipage = 0,  multifig_oma = c(5, 5, 5, 2) + 0.1,  ...)

Arguments

dbase

element of list created bySS_output() passed fromSSplotSexRatio()

sexratio.option

code to choose among (1) female:male ratio or(2) fraction females out of the total (the default)

CI

confidence interval for uncertainty

sampsizeround

rounding level for sample size values

maxrows

maximum (or fixed) number or rows of panels in the plot

maxcols

maximum (or fixed) number or columns of panels in the plot

rows

number or rows to return to as default for next plots to come orfor single plots

cols

number or cols to return to as default for next plots to come orfor single plots

fixdims

fix the dimensions at maxrows by maxcols or resize based onnumber of elements inyr input.

main

title of plot

cex.main

character expansion for title

xlab

x-axis label

ylab

y-axis label

horiz_lab

axis labels set horizontal all the time (TRUE), never(FALSE) or only when relatively short ("default")

xbuffer

extra space around points on the left and right as fractionof total width of plot

ybuffer

extra space around points on the bottom and top as fractionof total height of plot. "default" will cause c(0,.15) for sexratio.option=1and c(.15, .3) for sexratio.option=2.

yupper

upper limit on ymax (applied before addition of ybuffer)

datonly

make plots of data without fits?

showsampsize

add sample sizes to plot

showeffN

add effective sample sizes to plot

axis1

position of bottom axis values

axis2

position of left size axis values

ptscex

character expansion factor for points (default=1)

ptscol

color for points/bars

linescol

color for fitted model

lty

line type

lwd

line width

nlegends

number of lines of text to add as legends in each plot

legtext

text in legend, a list of length=nlegends. values may be anyof 1. "yr", 2. "sampsize", 3. "effN", or a vector of length = ptsx.

legx

vector of length=nlegends of x-values of legends (default isfirst one on left, all after on right)

legy

vector of length=nlegends of y-values of legends (default is topfor all plots)

legadjx

left/right adjustment of legends around legx

legadjy

left/right adjustment of legends around legy

legsize

font size for legends. default=c(1.2,1.0) (larger for yearand normal for others)

legfont

font type for legends, same as "font" under ?par

ipage

which page of plots when covering more than will fit withinmaxrows by maxcols.

multifig_oma

vector of outer margins. Can be input to SS_plots and will bepassed to this function via the ... argument.

...

additional arguments (NOT YET IMPLEMENTED).

Details

The SE of the sex ratio is crude and calculated asfollows. First, assume a multinomial which as MLEs of proportions. Thenuse the delta method of the ratio F/M, using the MLE as the expectedvalues and analytical variances and covariance between F and M. Aftersome algebra this calculation reduces to:SE(F/M)= sqrt((f/m)^2*( (1-f)/(f*N) + (1-m)/(m*N) +2/N )). Confidence intervals created fromthese should be considered very crude and would not necessarily beappropriate for future alternative compositional likelihoods.

This function was derived from make_multifig and hence has a lot ofoverlap in functionality and arguments.

Author(s)

Cole Monnahan. Adapted frommake_multifig().

See Also

SS_plots(),SSplotSexRatio()


Summarize nuisance MCMC output

Description

Summarize nuisance MCMC output (used in combination withmcmc.out() for key parameters).

Usage

mcmc.nuisance(  directory = "c:/mydirectory/",  run = "mymodel/",  file = "posteriors.sso",  file2 = "derived_posteriors.sso",  bothfiles = FALSE,  printstats = FALSE,  burn = 0,  header = TRUE,  thin = 1,  trace = 0,  labelstrings = "all",  columnnumbers = "all",  sep = "")

Arguments

directory

Directory where all results are located, one level abovedirectory for particular run.

run

Directory with files from a particular run.

file

Filename either with full path or relative to working directory.

Contents of the file that is referenced here should contain posterior samplesfor nuisance parameters, e.g., posteriors.sso orsomething written bySSgetMCMC.

file2

Optional second file containing posterior samples for nuisanceparameters. This could be derived_posteriors.sso.

bothfiles

TRUE/FALSE indicator on whether to readfile2 inaddition tofile1.

printstats

Return all the statistics for a closer look.

burn

Optional burn-in value to apply on top of the option in thestarter file andSSgetMCMC().

header

Data file with header?

thin

Optional thinning value to apply on top of the option in thestarter file, in themcsave runtime command, and inSSgetMCMC().

trace

Plot trace for param # (to help sort out problem parameters).

labelstrings

Vector of strings that partially match the labels of theparameters you want to consider.

columnnumbers

Vector of column numbers indicating the columns youwant to consider.

sep

Separator for data file passed to theread.table function.

Author(s)

Ian Stewart

See Also

mcmc.out(),SSgetMCMC()


Summarize, analyze and plot key MCMC output.

Description

Makes four panel plot showing trace plots, moving average, autocorrelations,and densities for chosen parameters from MCMC output.

Usage

mcmc.out(  directory = "c:/mydirectory/",  run = "mymodel/",  file = "keyposteriors.csv",  namefile = "postplotnames.sso",  names = FALSE,  headernames = TRUE,  numparams = 1,  closeall = TRUE,  burn = 0,  thin = 1,  scatter = FALSE,  surface = FALSE,  surf1 = 1,  surf2 = 2,  stats = FALSE,  plots = TRUE,  header = TRUE,  sep = ",",  print = FALSE,  new = T,  colNames = NULL)

Arguments

directory

Directory where all results are located, one level abovedirectory for particular run.

run

Directory with files from a particular run.

file

Filename either with full path or relative to working directory.

Contents of the file that is referenced here should contain posterior samplesfor nuisance parameters, e.g., posteriors.sso orsomething written bySSgetMCMC.

namefile

The (optional) file name of the dimension and names ofposteriors.

names

Read in names file (T) or use generic naming (F).

headernames

Use the names in the header offile?

numparams

The number of parameters to analyze.

closeall

By default close all open devices.

burn

Optional burn-in value to apply on top of the option in thestarter file andSSgetMCMC().

thin

Optional thinning value to apply on top of the option in thestarter file, in the-mcsave runtime command, and inSSgetMCMC().

scatter

Can add a scatter-plot of all params at end, default is none.

surface

Add a surface plot of 2-way correlations.

surf1

The first parameter for the surface plot.

surf2

The second parameter for the surface plot.

stats

Print stats if desired.

plots

Show plots or not.

header

Data file with header?

sep

Separator for data file passed to theread.table function.

print

Send to screen unless asked to print.

new

Logical whether or not to open a new plot window before plotting

colNames

Specific names of thefile to extract and work with.NULLkeeps all columns

Value

directory, because this function is used for its plotting side effects

Author(s)

Ian Stewart, Allan Hicks (modifications)

See Also

mcmc.nuisance(),SSgetMCMC()

Examples

## Not run: mcmc.df <- SSgetMCMC(  dir = "mcmcRun", writecsv = T,  keystrings = c("NatM", "R0", "steep", "Q_extraSD"),  nuisancestrings = c("Objective_function", "SSB_", "InitAge", "RecrDev"))mcmc.out("mcmcRun", run = "", numparams = 4, closeall = F)# Or for more controlpar(mar = c(5, 3.5, 0, 0.5), oma = c(0, 2.5, 0.2, 0))mcmc.out("mcmcRun",  run = "",  numparams = 1,  closeall = F,  new = F,  colNames = c("NatM_p_1_Fem_GP_1"))mtext("M (natural mortality)", side = 2, outer = T, line = 1.5, cex = 1.1)## End(Not run)

Make shaded polygons with a mountain-like appearance

Description

Designed to replicate like the cool-looking Figure 7 in Butterworth et al.(2003).

Usage

mountains(  zmat,  xvec = NULL,  yvec = NULL,  zscale = 3,  rev = TRUE,  nshades = 100,  axes = TRUE,  xaxs = "i",  yaxs = "i",  xlab = "",  ylab = "",  las = 1,  addbox = FALSE,  ...)

Arguments

zmat

A matrix where the rows represent the heights of each mountainrange

xvec

Optional input for the x variable

yvec

Optional input for the y variable

zscale

Controls the height of the mountains relative to the y-axisand max(zmat)

rev

Reverse the order of the display of yvec values.

nshades

Number of levels of shading

axes

Add axes to the plot?

xaxs

X-axis as internal or regular (see ?par for details)

yaxs

Y-axis as internal or regular (see ?par for details)

xlab

Optional label for x-axis

ylab

Optional label for y-axis

las

Xxis label style (see ?par for details). Default = 1 = horizontalaxis labels.

addbox

Puts a box around the whole plot

...

Extra inputs passed to the plot command

Author(s)

Ian Taylor

References

Butterworth D.S., Ianelli J.N., Hilborn R. (2003) A statisticalmodel for stock assessment of southern bluefin tuna with temporal changes inselectivity. South African Journal of Marine Science 25:331-362.


Plot points with confidence intervals.

Description

Given a set of x and y values and upper and lower bounds, this functionplots the points with error bars. This was Written by Venables and modifiedto add access to ylim and contents.

Usage

plotCI(  x,  y = NULL,  uiw,  liw = uiw,  ylo = NULL,  yhi = NULL,  ...,  sfrac = 0.01,  ymax = NULL,  add = FALSE,  col = "black")

Arguments

x

The x coordinates of points in the plot

y

The y coordinates of the points in the plot.

uiw

The width of the upper portion of the confidence region.

liw

The width of the lower portion of the confidence region.

ylo

Lower limit of y range.

yhi

Upper limit of y range.

...

Additional inputs that will be passed to the functionplot(x,y,ylim=ylim,...)

sfrac

Fraction of width of plot to be used for bar ends.

ymax

Additional input for Upper limit of y range.

add

Add points and intervals to existing plot? Default=FALSE.

col

Color for the points and lines.

Author(s)

Bill Venables, Ian Stewart, Ian Taylor, John Wallace


Populate multiple Stock Synthesis folders with input files

Description

Creates a set of multiple folders and populate each with SS input filessuch as for the purpose of running a new version of SS for an existingset of test models.

Usage

populate_multiple_folders(  outerdir.old = NULL,  outerdir.new = NULL,  create.dir = TRUE,  overwrite = FALSE,  use_ss_new = FALSE,  exe.dir = NULL,  exe.file = "ss.exe",  exe.only = FALSE,  verbose = TRUE)

Arguments

outerdir.old

Location of existing outer directory containingsubdirectories for each model.

outerdir.new

New outer directory into which the subfoldersshould be created.

create.dir

Create new outer directory if it doesn't exist already?

overwrite

Overwrite existing files with matching names?

use_ss_new

Use .ss_new files instead of original inputs?

exe.dir

Path to executable to copy into all the subfolders.

exe.file

Filename of executable to copy into all the subfolders.A value of NULL will skip copying the executable.

exe.only

Only copy exe files from exe.dir, don't copy input files

verbose

Return updates of function progress to the R console?

Value

Returns table of results indicating which directories weresuccessfully populated with the model input files and/or executables

Author(s)

Ian Taylor

See Also

copy_SS_inputs()

Examples

## Not run: populate_multiple_folders(  outerdir.old = "c:/SS/old_models",  outerdir.new = "c:/SS/new_models",  exe.dir = "c:/SS/SSv3.30.12.00")## End(Not run)

Description

I was tired of the automatically generated symbolthat appeared by default.

Usage

r4ss_logo()

Author(s)

Ian Taylor


Read ADMB .par and .cor files.

Description

This function will parse the .par and .cor files to providethings like parameter estimates, standard deviations,and correlations. Required for Jim Thorson's LaplaceApproximation but likely useful for other purposes.

Usage

read.admbFit(file)

Arguments

file

Name of ADMB executable such that files to read willhave format file.par and file.cor.

Value

List of various things from these files.

Author(s)

James Thorson

See Also

getADMBHessian(),NegLogInt_Fn()


Make a vector of colors.

Description

A subset of rich.colors by Arni Magnusson from the gplots package, with theaddition of alpha transparency (which is now available in the gplots versionas well)

Usage

rich.colors.short(n, alpha = 1)

Arguments

n

Number of colors to generate.

alpha

Alpha transparency value for all colors in vector. Value ispassed to rgb function.

Author(s)

Arni Magnusson, Ian Taylor


Run multiple Stock Synthesis models

Description

Loops over a vector of directories and iteratively runs SS in each one

Usage

run_SS_models(  dirvec = NULL,  model = "ss",  extras = "-nox",  systemcmd = FALSE,  skipfinished = TRUE,  intern = FALSE,  verbose = TRUE,  exe_in_path = FALSE)

Arguments

dirvec

List of directories containing the model files

model

Executable name or path to executable (absolute path, or relativeto the working directory). First, if exe_in_path isFALSE, The function will look an executable with the same name in eachelement of dirvec. Then, if it is not found in each, the function willassume that model is the path to the executable and there is only 1 copy ofthe executable. Note that if there is an exe in your PATH with the samename, this will be used even if exe_in_path is FALSE.

extras

Additional commands to use when running SS. Default = "-nox"will reduce the amount of command-line output.

systemcmd

Should R call SS using "system" function instead of "shell".This may be required when running R in Emacs. Default = FALSE.

skipfinished

Skip any folders that already contain a Report.sso file.This can be helpful if the function is interrupted.

intern

Show output in the R console or save to a file?

verbose

Return updates of function progress to the R console?

exe_in_path

logical. If TRUE, will look for exe in the PATH. If FALSE,will look for exe in the model folders. Default = FALSE.

Value

Returns table showing which directories had model run and whichhad errors like missing executable or Report.sso already present

Author(s)

Ian Taylor

See Also

copy_SS_inputs(),populate_multiple_folders()

Examples

## Not run: extdata_mods <- system.file("extdata", package = "r4ss")dirvec <- c(  file.path(extdata_mods, "simple_3.30.12"),  file.path(extdata_mods, "simple_3.30.13"))# if ss or ss.exe is available in both directories:run_SS_models(dirvec = dirvec)## End(Not run)

Open png device and return info on the file being created

Description

this was previously contained within each of the SSplotXXX() functions.It (1) translates the not-quite-matching specifications for the image to thevalues needed by png(), then (2) returns the plotinfo data.frame(which exists within each function which calls this) after adding a rowwith the filename and caption for each new plotNote: this just opens the png device which needs to be closed via dev.off()outside this function.

Usage

save_png(  plotinfo,  file,  plotdir,  pwidth,  pheight,  punits,  res,  ptsize,  caption = NA,  alt_text = NA,  filenameprefix = NA)

Arguments

plotinfo

table of information about all plots

file

filename to write to (including .png extension)

plotdir

directory where plots will be written

pwidth

Default width of plots printed to files in units ofpunits. The default ispwidth=6.5.

pheight

Height of plots printed to png files in units ofpunits.Default is designed to allow two plots per page, withpheight_tall usedfor plots that work best with a taller format and a single plot per page.

punits

Units forpwidth andpheight. Can be "px"(pixels), "in" (inches), "cm" (centimeters), or "mm" (millimeters).The default ispunits="in".

res

Resolution of plots printed to files.The default isres = 300.

ptsize

Point size for plotted text in plots printed to files (seehelp("png") in R for details).

caption

caption for the image

alt_text

alternative text for screen readers(if left as NA then will be set based on the caption)

filenameprefix

Additional text to append to PNG or PDF file names.It will be separated from default name by an underscore.

Author(s)

Ian G. Taylor


Launch a shiny app that displays various selectivity curves

Description

This app is hosted at https://connect.fisheries.noaa.gov/shiny-selex-ss3/

Usage

selShapes()

Author(s)

Allan Hicks, Andrea Havron, Ian Taylor,

inspired by tcl/tk code written by Tommy Garrison


Allow Multi-PlotsSet the par() to options suitable for ss3diags multi plots.

Description

Seepar for more details on each parameter.

Usage

sspar(  mfrow = c(1, 1),  plot.cex = 1,  mai = c(0.55, 0.6, 0.1, 0.1),  omi = c(0, 0, 0, 0) + 0.1,  labs = TRUE)

Arguments

mfrow

determines plot frame set up

plot.cex

cex graphic option

mai

graphical par for plot margins

omi

Outer margins in lines of text.

labs

if TRUE margins are narrow


modified from "stackpoly" by Jim Lemon from "plotrix" package

Description

Plot one or more columns of numeric values as the top edges of polygonsinstead of lines.

Usage

stackpoly(  x,  y,  main = "",  xlab = "",  ylab = "",  xat = NA,  xaxlab = NA,  xlim = NA,  ylim = NA,  lty = 1,  border = NA,  col = NA,  axis4 = F,  x.hash = NULL,  density = 20,  ...)

Arguments

x

A numeric data frame or matrix with the 'x' values. If 'y' is NULL,these will become the 'y' values and the 'x' positions will be the integersfrom 1 todim(x)[1].

y

The 'y' values.

main

The title for the plot.

xlab

x axis labels for the plot.

ylab

y axis labels for the plot.

xat

Where to put the optional xaxlabs.

xaxlab

Optional labels for the x positions.

xlim

Optional x limits.

ylim

Optional y limits.

lty

Line type for the polygon borders.

border

Color for the polygon borders.

col

Color to fill the polygons. If NULL, 'rainbow' will be called togenerate the colors. If NA, the polygons will not be filled.

axis4

option to add an axis on the right hand side.

x.hash

values from x for which the bars have hash marks instead of solid fill

density

density value for hashed areas

...

Additional arguments passed to 'plot'.

Author(s)

Jim Lemon, Ian Taylor

References

https://cran.r-project.org/package=plotrix


Use 3.30 q options to create the 3.24 q setup

Description

Use 3.30 q options to create the 3.24 q setup

Usage

translate_3.30_to_3.24_Q_setup(  Q_options,  Nfleets,  fleetnames = seq_len(Nfleets))

Arguments

Q_options

The Q options list element in the 3.30control file r4ss list output generated fromSS_readctl.

Nfleets

Number of fleets in the model

fleetnames

Name of the fleets. Defaults to fleet numbers, in the order

Value

A dataframe containing the 3.24 Q setup.


Use 3.30 variance adjustments to create the 3.24 formatting

Description

This functionality used to be in SS_readctl_3.30, but ware removed to avoidconfusion.

Usage

translate_3.30_to_3.24_var_adjust(  Variance_adjustment_list = NULL,  Nfleets,  fleetnames = seq_len(Nfleets))

Arguments

Variance_adjustment_list

The Variance_adjustments_list elementin the control file r4ss list output generated fromSS_readctl.Defaults to NULL, which can be the case if no variance adjustments wereincluded in the model.

Nfleets

Number of fleets in the model

fleetnames

Name of the fleets. Defaults to fleet numbers, in the orderdefined in the model.

Value

A dataframe of 3.24 variance adjustments.


Function to write formatted table similar totable written by gdata::write.fwf from data.frame or matrixThis function does not accept columns or logical with factor

Description

Function to write formatted table similar totable written by gdata::write.fwf from data.frame or matrixThis function does not accept columns or logical with factor

Usage

write_fwf4(  x,  file = "",  append = FALSE,  quote = FALSE,  sep = " ",  na = "NA",  rownames = FALSE,  colnames = TRUE,  rowCol = NULL,  justify = "left",  width = NULL,  eol = "\n",  qmethod = c("escape", "double"),  digits = 6,  checkNA = TRUE,  checkInfty = TRUE,  checkError = TRUE)

Arguments

x

data.frame or matrix the object to be written

file

either a character string naming a file or aconnection open for writing. "" indicates output to the console.

append

logical, append to existing data infile

quote

logical, quote data in output

sep

character, separator between columns in output

na

character, the string to use for missing values i.e.NA inthe output

rownames

logical, print row names

colnames

logical, print column names

rowCol

character, rownames column name

justify

character, alignment of character columns; seeformat()

width

numeric, width of the columns in the output

eol

the character(s) to print at the end of each line (row). Forexample, 'eol="\r\n"' will produce Windows' line endings on a Unix-alike OS,and 'eol="\r"' will produce files as expected by Mac OS Excel 2004.

qmethod

a character string specifying how to deal with embeddeddouble quote characters when quoting strings. Must be one of '"escape"'(default), in which case the quote character is escaped in C style by abackslash, or '"double"', in which case it is doubled. You can specify justthe initial letter.

digits

Used for signif

checkNA

logical if TRUE, function will stop when NA is found

checkInfty

logical if TRUE, function will stop when Infinity is found

checkError

logical if TRUE both, set checkNA and checkInftr TRUE

Author(s)

Yukio Takeuchi


[8]ページ先頭

©2009-2025 Movatter.jp