diff --git a/_pkgdown.yml b/_pkgdown.yml index 3592095..4a42180 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -1,7 +1,7 @@ url: https://MathMarEcol.github.io/zoomss development: mode: devel - destination: docs + destination: / version_label: info version_tooltip: The package is in the early stages of development. Use with caution. reference: diff --git a/docs/404.html b/docs/404.html deleted file mode 100644 index 106bc51..0000000 --- a/docs/404.html +++ /dev/null @@ -1,75 +0,0 @@ - - -
- - - - -YEAR: 2025 -COPYRIGHT HOLDER: zoomss authors -- -
LICENSE.md
- Copyright (c) 2025 zoomss authors
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-ZooMSS requires two sets of input data:
-Groups - Contains all taxa-specific parameter -values for each model group, including size ranges and functional group -properties.
Environmental data - A Time-series dataframe
-with time series of environmental conditions with time,
-sst, and chl columns.
Get the default published Groups dataframe using:
-Groups <- getGroups()
-#> Using default ZooMSS functional groups. Use getGroups() to customize.Now create an environmental data time-series using the helper
-function. This time-series uses a constant sea surface temperature
-(sst) and chlorophyll a (chl) with a
-0.1 yr-1 timestep (dt).
-env_data <- createInputParams(time = seq(0, 100, by = 0.1) ,
- sst = 15,
- chl = 0.15)
-#> ZooMSS input parameters created:
-#> - Time points: 1001 (time values provided)
-#> - Time steps: 1000 (intervals to simulate)
-#> - Time range: 0 to 100 years
-#> - dt = 0.1 years
-#> - SST range: 15 to 15 deg C
-#> - Chlorophyll range: 0.15 to 0.15 mg/m^3We can look at the environment data and check everything is ok -with:
-
-plotEnvironment(env_data)
Now we run ZooMSS and save every isave timestep to
-reduce storage requirements.
-mdl <- zoomss_model(input_params = env_data, Groups = Groups, isave = 2)
-#> Functional groups validation passed
-#> Calculating phytoplankton parameters from environmental time seriesThe model includes several built-in plotting functions for analysis -and visualization.
-These plots display total abundance and mean growth/mortality across -all size classes through time.
-
-
-library(patchwork)
-p1 <- plotTimeSeries(mdl, by = "abundance") # Plot abundance time series
-p2 <- plotTimeSeries(mdl, by = "growth") # Plot growth rate time series
-p3 <- plotTimeSeries(mdl, by = "mortality") # Plot predation mortality time series
-
-wrap_plots(p1, p2, p3, nrow = 3, guides = "collect")
We can also plot total biomass through time.
-
-p4 <- plotTimeSeries(mdl, by = "biomass") + theme(legend.position = "none") # Plot biomass
-p5 <- plotTimeSeries(mdl, by = "biomass", stacked = TRUE) # Plot stacked biomass
-p6 <- plotTimeSeries(mdl, by = "biomass", stacked = TRUE, proportion = TRUE) # Plot proportional stacked biomass
-
-wrap_plots(p4, p5, p6, nrow = 3, guides = "collect")
Plot mean species-resolved size spectra for the final
-n_years.
-plotSizeSpectra(mdl, n_years = 10)
-#> Averaging final 10 years (50 saved time steps with isave = 2) of N from 500 total saved time steps.
Plot predator-prey mass ratios for the idx timestep
-plotPPMR(mdl, idx = 500) # Plot final timestep
The Zooplankton Model of Size Spectra (ZooMSS) is a functional size-spectrum model of the marine ecosystem (following Heneghan et al. 2016) to resolve phytoplankton, nine zooplankton functional groups (heterotrophic flagellates and ciliates, omnivorous and carnivorous copepods, larvaceans, euphausiids, salps, chaetognaths and jellyfish) and three size-based fish groups. Zooplankton functional groups are resolved using their body-size ranges, size-based feeding characteristics and carbon content, and the zooplankton community emerges from the model across global environmental gradients, depending on the functional traits of the different groups.
-We developed the Zooplankton Model of Size Spectra (ZooMSSv2) based on the prototype of Heneghan et al. (2016). ZooMSS uses the functional size-spectrum framework (Blanchard et al., 2017) to resolve the body size ranges, size-based feeding characteristics and carbon content of nine zooplankton groups and three fish groups. The model supports time-varying environmental conditions enabling studies of seasonal cycles, climate change scenarios, and ecosystem responses to environmental variability.
-ZooMSS represents the marine ecosystem as three communities: phytoplankton, zooplankton and fish. The zooplankton community consists of nine of the most abundant zooplankton groups, and the fish community was made up of a small, medium and large group. Dynamics of the phytoplankton are not explicitly resolved in the model, rather the mean size structure of the phytoplankton community is estimated directly from satellite chlorophyll a observations (Brewin et al., 2010; Barnes et al., 2011; Hirata et al., 2011). Abundances of the zooplankton and fish communities are driven by size-dependent processes of growth and mortality, with the temporal dynamics of each functional group governed by separate second-order McKendrick-von Foerster equations.
-You can install the development version of zoomss from GitHub with:
-
-# install.packages("pak")
-pak::pak("MathMarEcol/zoomss")Heneghan, R.F., Everett, J.D., Blanchard, J.L., Richardson, A.J., 2016. Zooplankton Are Not Fish: Improving Zooplankton Realism in Size-Spectrum Models Mediates Energy Transfer in Food Webs. Front. Mar. Sci. 3, 1–15. https://doi.org/10.3389/fmars.2016.00201
Heneghan, R.F., Everett, J.D., Sykes, P., Batten, S.D., Edwards, M., Takahashi, K., Suthers, I.M., Blanchard, J.L., Richardson, A.J., in review, A global size-spectrum model of the marine ecosystem that resolves zooplankton composition. Ecological Modelling
If you encounter problems running the model, raise an issue on GitHub: https://github.com/MathMarEcol/ZoopSizeSpectraModel/issues
-If you find errors or want to improve the model, we’d love you to make the changes and submit a pull request for us to review and approve.
-A dataset containing the biological parameters for different -functional groups used in the ZooMSS size-structured marine ecosystem model. -These represent various taxa from flagellates to large fish, each defined -by their feeding behavior, size ranges, and physiological parameters.
-A data frame with 12 rows (functional groups) and 19 columns:
Character. Name of the functional group/taxa
Character. Broad category (Zooplankton or Fish)
Character. Feeding strategy (Heterotroph, FilterFeeder, Omnivore, Carnivore)
Numeric. Initial proportion of total biomass
Numeric. Log10 minimum body weight (g) for the group
Numeric. Log10 maximum body weight (g) for the group
Numeric. Log10 maturation body weight (g)
Numeric. Search coefficient for predation interactions
Numeric. Search exponent for predation scaling
Numeric. Predator-prey mass ratio scaling parameter
Numeric. Predator-prey mass ratio (for fish groups)
Numeric. Feeding kernel width parameter
Numeric. Gross growth efficiency scaling
Numeric. Carbon content proportion
Numeric. Reproduction parameter
Numeric. Fishing mortality rate
Numeric. Log10 minimum weight for fishing mortality
Numeric. Log10 maximum weight for fishing mortality
Character. Color code for plotting the functional group
ZooMSS Functional Groups Data
-The GroupInputs dataset defines 12 functional groups spanning from -small microzooplankton (flagellates, ciliates) through various mesozooplankton -groups (copepods, euphausiids, chaetognaths) to gelatinous zooplankton (salps, jellyfish) -and three fish size classes (small, medium, large). Each group is characterized by:
Size ranges: W0 to Wmax define the body size spectrum
Feeding behavior: Different strategies for resource acquisition
Interaction parameters: Search rates and predator-prey relationships
Physiological rates: Growth efficiency and carbon content
These parameters are based on marine ecological literature and represent -typical values for temperate marine ecosystems.
-data(GroupInputs)
-head(GroupInputs)
-#> # A tibble: 6 × 19
-#> Species Type FeedType Prop W0 Wmax Wmat SearchCoef SearchExp PPMRscale
-#> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
-#> 1 Flagell… Zoop… Heterot… 0.1 -12 -6.8 -8.8 640 0.8 1.5
-#> 2 Ciliates Zoop… Heterot… 0.1 -9.3 -6.3 -8.3 640 0.8 0.04
-#> 3 Larvace… Zoop… FilterF… 0.1 -6.4 -3.2 -5.2 640 0.8 -3
-#> 4 OmniCop… Zoop… Omnivore 0.04 -7.5 -3.5 -5.5 640 0.8 -0.5
-#> 5 CarnCop… Zoop… Carnivo… 0.06 -7.5 -2.5 -4.5 640 0.8 1.5
-#> 6 Euphaus… Zoop… Omnivore 0.1 -4.2 0.2 -1.8 640 0.8 -2
-#> # ℹ 9 more variables: PPMR <dbl>, FeedWidth <dbl>, GrossGEscale <dbl>,
-#> # Carbon <dbl>, Repro <dbl>, Fmort <dbl>, Fmort_W0 <dbl>, Fmort_Wmax <dbl>,
-#> # PlotColour <chr>
-
-# View size ranges across groups
-plot(GroupInputs$W0, GroupInputs$Wmax,
- col = GroupInputs$PlotColour,
- xlab = "Log10 Min Weight", ylab = "Log10 Max Weight")
-text(GroupInputs$W0, GroupInputs$Wmax, GroupInputs$Species, pos = 3, cex = 0.7)
-
-GroupInputs
-
- getGroups()
-
- calculatePhytoParam()
-
- createEnviroData()
-
- createInputParams()
-
- validateGroups()
-
- zoomss_model()
-
- zoomss_mvf()
-
- zoomss_params()
-
- zoomss_run()
-
- zoomss_setup()
-
- plotEnvironment()
-
- plotPPMR()
-
- plotSizeSpectra()
-
- plotTimeSeries()
-
- averageTimeSeries()
-
- extractPPMR()
-
- extractSizeRange()
-
- extractTrophicLevels()
-
- getBiomass()
-
- getGroups()
-
- reduceAll()
-
- reduceSize()
-
- reduceSpecies()
-
- untibble()
-
- Removes tibble attributes and converts to a plain data frame -for improved speed and memory efficiency in computational workflows.
-zAveOutput.RdCalculates the mean of the final portion (default 50%) of a time series -to obtain equilibrium values after model spin-up period.
-zAveOutput(x, prop = 0.5)2D array with averaged values (groups x size_classes)
-Calculate Average Output from Model Time Series
-This function removes the initial transient period from time series data -and calculates the mean of the remaining portion, providing representative -steady-state values. Essential for obtaining equilibrium abundances, growth rates, -and other model outputs after the model has reached dynamic equilibrium.
-getBiomass.RdConverts abundance data to wet weight biomass by multiplying abundances -by the corresponding body weights for each size class.
-getBiomass(res, vmdl)List of biomass matrices in grams wet weight
-Convert Abundance to Biomass
-This function transforms abundance matrices to biomass by applying the -weight vector across size classes. Essential for analyses requiring biomass -units rather than abundance counts.
-calculatePhytoParam.RdConverts chlorophyll concentration data to phytoplankton size spectrum -parameters (slope, intercept, maximum size) using established oceanographic relationships.
-calculatePhytoParam(df)Data frame with added columns:
phyto_slope: Power law slope for phytoplankton size spectrum
phyto_int: Log10 intercept for phytoplankton abundance
phyto_max: Maximum phytoplankton size (log10 grams)
pico_biom, nano_biom, micro_biom: Biomass in each size class
Calculate Phytoplankton Size Spectrum Parameters
-This function implements the Brewin et al. (2015) algorithm to partition -chlorophyll among picophytoplankton, nanophytoplankton, and microphytoplankton size -classes, then calculates:
Size spectrum slope and intercept parameters
Maximum phytoplankton size based on micro proportion
Biomass estimates for each size class
These parameters drive the dynamic phytoplankton spectrum in ZooMSS that serves -as the base of the food web. The function can work with either chlorophyll-only -data (using empirical relationships) or direct phytoplankton biomass measurements.
-Brewin, R.J.W., et al. (2015). A three-component model of phytoplankton size class -for the Atlantic Ocean. Ecological Modelling, 306, 90-101.
-Maranon, E., et al. (2014). Resource supply overrides temperature as a controlling -factor of marine phytoplankton growth. PLoS ONE, 9(6), e99312.
-zCarbonBiomass.RdConverts abundance data to carbon biomass by multiplying by body weights -and then by carbon content factors for each functional group.
-zCarbonBiomass(res, vmdl)List of carbon biomass matrices (grams carbon)
-Convert Abundance to Carbon Biomass
-This function performs a two-step conversion:
Abundance to wet weight biomass (using body weights)
Wet weight to carbon biomass (using group-specific carbon content)
Carbon biomass is essential for biogeochemical analyses and comparisons -with field data that are often reported in carbon units.
-zConvert2Tibble.RdConverts ZooMSS list output to a tibble format with proper column -names based on functional group species names.
-zConvert2Tibble(li, vmdl)Tibble with columns named by species and rows representing spatial cells
-Convert List to Tibble Format
-This function converts aggregated ZooMSS output (typically from -reduceSize or similar functions) into a tibble format suitable for -analysis and visualization. Currently designed for 2D data (species x cells).
-createInputParams.RdCreates a properly formatted input parameters data frame for ZooMSS model -simulations, combining temporal parameters with environmental time series data.
-createInputParams(time, sst, chl, cellID = NULL)Numeric vector of time values in years (must be increasing and uniform, can start at any value)
Numeric vector of sea surface temperature values in deg C
Numeric vector of chlorophyll concentration values in mg/m^3
Optional numeric vector of cell identifiers for spatial data (default: NULL)
Data frame with columns: time, time_step, sst, chl, and cellID (if provided)
-Create ZooMSS Input Parameters Object
-This function combines environmental time series (SST and chlorophyll) with -time data to create the input_params object required by zoomss_model(). -The function performs validation checks using assertthat to ensure:
All input vectors are numeric and of equal length
SST values are within reasonable ocean range (-2 to 35 deg C)
Chlorophyll values are positive and within typical range (0 to 50 mg/m^3)
Time values are increasing and reasonable
if (FALSE) { # \dontrun{
-# Create simple environmental time series
-time_vec <- seq(0, 10, 0.01) # 10 years with 0.01 year time steps
-sst_vec <- 15 + 3*sin(2*pi*time_vec/1) # annual cycle
-chl_vec <- 0.5 + 0.2*cos(2*pi*time_vec/1) # annual cycle
-
-# Create input parameters object
-input_params <- createInputParams(time_vec, sst_vec, chl_vec)
-
-# Use with ZooMSS model
-results <- zoomss_model(input_params, Groups, isave = 50)
-} # }
-
-zCreateSimpleTimeSeries.RdCreates simple synthetic environmental time series with optional seasonal -variation for testing ZooMSS model runs when real environmental data is not available.
-createEnviroData(
- n_time_steps,
- dt,
- base_sst = 15,
- base_chl = 0.5,
- seasonal = TRUE,
- sst_amplitude = 3,
- chl_amplitude = 0.2
-)Number of time steps to generate
Time step size in years
Base sea surface temperature in deg C (default: 15)
Base chlorophyll concentration in mg/m^3 (default: 0.5)
Logical, whether to add seasonal variation (default: TRUE)
Amplitude of SST seasonal variations in deg C (default: 3)
Amplitude of chlorophyll seasonal variations in mg/m^3 (default: 0.2)
Data frame with columns: time, sst, chl
-Create Simple Environmental Time Series for Testing
-This function generates synthetic sea surface temperature and chlorophyll -time series that can be used for testing ZooMSS model behavior. The function can -create either static environmental conditions or seasonal cycles with sinusoidal -variation. This is particularly useful for:
Testing model sensitivity to environmental forcing
Creating idealized scenarios for model exploration
Generating data when real environmental data is unavailable
The seasonal option creates SST and chlorophyll cycles that are out of phase, -mimicking typical ocean patterns where chlorophyll peaks when SST is lower.
-# Create seasonal environmental data
-env_data <- createEnviroData(
- n_time_steps = 1000,
- dt = 0.01,
- seasonal = TRUE
-)
-#> Error in createEnviroData(n_time_steps = 1000, dt = 0.01, seasonal = TRUE): unused argument (n_time_steps = 1000)
-
-# Create static environmental conditions
-static_data <- createEnviroData(
- n_time_steps = 500,
- dt = 0.01,
- seasonal = FALSE,
- base_sst = 20,
- base_chl = 1.0
-)
-#> Error in createEnviroData(n_time_steps = 500, dt = 0.01, seasonal = FALSE, base_sst = 20, base_chl = 1): unused argument (n_time_steps = 500)
-
-extractSizeRange.RdSubsets ZooMSS output to include only specified size classes, -useful for focusing analysis on particular size ranges.
-extractSizeRange(list_in, minb, maxb)List of abundance matrices with only specified size classes
-Extract Size Range from ZooMSS Output
-This function extracts a subset of size classes from the full -ZooMSS output matrices. Useful for analyzing specific size ranges -(e.g., microzooplankton, mesozooplankton) or excluding boundary effects -from model analysis.
-extractPPMR.RdCalculates predator-prey mass ratio (PPMR) values and biomass weightings -for creating PPMR distribution plots in ZooMSS analysis.
-extractPPMR(dat)List containing PPMR density data and species-specific values for plotting
-Calculate PPMR Data for Plotting
-This function computes theoretical and realized PPMR patterns by:
Calculating size-dependent PPMR values using Wirtz 2012 equations
Weighting by biomass to show community-level patterns
Computing species-specific PPMR values
Handling special cases for filter feeders (larvaceans, salps)
This is a helper function primarily used by plotPPMR for visualization. -PPMR analysis provides insights into food web structure and predation patterns.
-getGroups.RdProvides access to the default ZooMSS functional groups or loads custom -groups from a file. This function is the primary way to obtain Groups data for -ZooMSS model runs.
-getGroups(source = c("default", "file", "template"), file = NULL)Data frame containing functional groups with required columns: -Species, Type, W0, Wmax, and other biological parameters
-Get Default ZooMSS Functional Groups
-This function provides flexible access to functional groups data:
Default groups: Returns the standard ZooMSS functional groups (9 groups)
Custom file: Loads and validates groups from a user-provided CSV file
Template creation: Exports default groups to a file for user modification
The default groups include: Flagellates, Ciliates, Larvaceans, OmniCopepods, -CarnCopepods, Euphausiids, Chaetognaths, Salps, and Jellyfish.
-All groups data is validated to ensure it contains required columns and -reasonable parameter values for successful model runs.
-if (FALSE) { # \dontrun{
-# Use default groups
-Groups <- getGroups()
-
-# Create a template file for modification
-getGroups(source = "template", file = "my_groups.csv")
-
-# Load custom groups from file
-custom_groups <- getGroups(source = "file", file = "my_groups.csv")
-
-# Modify default groups programmatically
-Groups <- getGroups()
-Groups$W0[Groups$Species == "Flagellates"] <- -12.5 # Modify minimum size
-} # }
-
-loadDefaultGroups.RdLoads the default functional groups from the package data or CSV file. -This is an internal function used by getGroups().
-loadDefaultGroups()Data frame with default functional groups
-Load Default Functional Groups Data
-This function handles the actual loading of default groups data, -whether from package data (if available) or from the CSV file in data-raw.
-makeDietTibble.RdConverts ZooMSS diet matrix from wide format to long (tidy) format -with predator-prey relationships clearly defined.
-makeDietTibble(mat, mdl)Long tibble with columns: Predator, Prey, Diet
-Create Diet Matrix in Long Tibble Format
-This function transforms diet matrices into a long format suitable for -analysis and visualization of feeding relationships. The resulting tibble -contains predator-prey pairs with diet fraction values, making it easy to -analyze trophic interactions and create food web visualizations.
-plotEnvironment.RdCreates plots of sea surface temperature and chlorophyll time series -for visualizing environmental forcing data used in ZooMSS model runs.
-plotEnvironment(env_data)ggplot object (if patchwork available) or list of two ggplot objects
-Plot Environmental Time Series
-This function creates two separate plots with different y-axes scales:
SST plot (red line) with temperature in deg C
Chlorophyll plot (green line) with concentration in mg/m^3
The plots can be combined using the patchwork package if available, otherwise -separate plots are returned as a list. This helps users visualize the -environmental forcing that drives ZooMSS model dynamics.
-# Create sample data and plot
-env_data <- data.frame(
- time = 1:100,
- dt = 0.01,
- sst = 15 + 3*sin(2*pi*(1:100)/50),
- chlo = 0.5 + 0.2*cos(2*pi*(1:100)/50)
-)
-plots <- plotEnvironment(env_data)
-
-zPlot_AbundTimeSeries.RdCreates time series plots showing how total abundance of each functional -group changes throughout the ZooMSS simulation period.
-zPlot_AbundTimeSeries(dat)ggplot object showing abundance time series by species
-Plot Abundance Time Series
-This function creates time series visualization by:
Summing abundances across all size classes for each functional group
Converting to long format for ggplot visualization
Plotting log-transformed abundance over time
Using species-specific colors and filtering out zero abundances
Time series plots help identify:
Equilibration time for model runs
Seasonal or cyclical patterns in abundance
Relative abundance patterns between functional groups
Model stability and convergence behavior
if (FALSE) { # \dontrun{
-# After running ZooMSS model with SaveTimeSteps = TRUE
-results <- zoomss_model(input_params, Groups, SaveTimeSteps = TRUE)
-time_plot <- zPlot_AbundTimeSeries(results)
-print(time_plot)
-} # }
-
-zPlot_BiomassTimeSeries.RdCreates flexible time series plots showing how total biomass of functional -groups changes throughout the ZooMSS simulation, with options for line plots, -stacked area plots, and proportional displays.
-zPlot_BiomassTimeSeries(
- dat,
- stacked = FALSE,
- proportional = FALSE,
- species = NULL
-)ZooMSS results object containing model outputs with time series data
Logical, whether to create stacked area plot instead of line plot (default: FALSE)
Logical, whether to show proportions instead of absolute values (default: FALSE)
Character vector of species names to include in plot. If NULL, all species included (default: NULL)
ggplot object showing biomass time series by species
-Plot Biomass Time Series
-This function creates biomass time series visualization with multiple options:
Line plots: Individual species biomass trajectories over time
Stacked plots: Cumulative biomass showing total ecosystem biomass
Proportional plots: Relative biomass contributions (0-1 scale)
Species filtering: Focus on specific functional groups
The function calculates biomass by multiplying abundance by body weights and -summing across size classes for each functional group. Different plot types help -visualize different aspects of ecosystem dynamics:
Line plots show individual group patterns and relative magnitudes
Stacked plots show total ecosystem biomass and contributions
Proportional plots highlight shifts in community composition
if (FALSE) { # \dontrun{
-# After running ZooMSS model with SaveTimeSteps = TRUE
-results <- zoomss_model(input_params, Groups, SaveTimeSteps = TRUE)
-
-# Basic line plot of all species
-biomass_plot <- zPlot_BiomassTimeSeries(results)
-
-# Stacked area plot showing total biomass
-stacked_plot <- zPlot_BiomassTimeSeries(results, stacked = TRUE)
-
-# Proportional plot showing relative contributions
-prop_plot <- zPlot_BiomassTimeSeries(results, proportional = TRUE)
-
-# Focus on specific groups
-copepod_plot <- zPlot_BiomassTimeSeries(results,
- species = c("OmniCopepods", "CarnCopepods"))
-} # }
-
-zPlot_GrowthTimeSeries.RdCreates time series plots showing how average growth rates of each functional -group change throughout the ZooMSS simulation period.
-zPlot_GrowthTimeSeries(dat)ggplot object showing growth rate time series by species
-Plot Growth Rate Time Series
-This function creates growth rate time series by:
Averaging growth rates across all size classes for each functional group
Converting to long format for ggplot visualization
Plotting log-transformed growth rates over time
Using species-specific colors and filtering out zero values
Growth rate time series help assess:
Environmental effects on organism growth
Seasonal patterns in productivity
Differences in growth potential between functional groups
Model response to changing environmental conditions
if (FALSE) { # \dontrun{
-# After running ZooMSS model with SaveTimeSteps = TRUE
-results <- zoomss_model(input_params, Groups, SaveTimeSteps = TRUE)
-growth_plot <- zPlot_GrowthTimeSeries(results)
-print(growth_plot)
-} # }
-
-plotPPMR.RdCreates a plot showing the distribution of predator-prey mass ratios (PPMR) -across functional groups, providing insights into the trophic structure of the ecosystem.
-plotPPMR(dat)ggplot object showing PPMR distribution with species-specific overlays
-Plot Predator-Prey Mass Ratio (PPMR) Distribution
-This function calculates and visualizes PPMR patterns by:
Computing theoretical PPMR values for each functional group and size class
Weighting by biomass to show realized community patterns
Creating a density plot of PPMR distribution across the community
Overlaying species-specific PPMR values as points
PPMR is a key ecological metric that describes the size relationship between -predators and their prey, providing insight into food web structure and -energy transfer efficiency in marine ecosystems.
-if (FALSE) { # \dontrun{
-# After running ZooMSS model
-results <- zoomss_model(input_params, Groups, SaveTimeSteps = FALSE)
-ppmr_plot <- plotPPMR(results)
-print(ppmr_plot)
-} # }
-
-zPlot_PredTimeSeries.RdCreates time series plots showing how average predation mortality rates of each -functional group change throughout the ZooMSS simulation period.
-zPlot_PredTimeSeries(dat)ggplot object showing predation mortality time series by species
-Plot Predation Mortality Time Series
-This function creates predation mortality time series by:
Averaging predation mortality rates across all size classes for each functional group
Converting to long format for ggplot visualization
Plotting mortality rates over time without log transformation
Using species-specific colors and filtering out zero values
Predation mortality time series help assess:
Predation pressure on different functional groups over time
Seasonal or temporal patterns in predation intensity
Relative vulnerability of functional groups to predation
Model dynamics and predator-prey interactions
if (FALSE) { # \dontrun{
-# After running ZooMSS model with SaveTimeSteps = TRUE
-results <- zoomss_model(input_params, Groups, SaveTimeSteps = TRUE)
-mortality_plot <- zPlot_PredTimeSeries(results)
-print(mortality_plot)
-} # }
-
-plotSizeSpectra.RdCreates a log-log plot of abundance versus body size for all functional groups, -showing the classic size spectrum pattern in marine ecosystems.
-plotSizeSpectra(dat)ggplot object showing log abundance vs log body weight by species
-Plot Size Spectra for ZooMSS Results
-This function visualizes the abundance size spectrum by:
Converting abundance data to long format with body weights
Filtering out zero abundances to focus on active size classes
Creating log-log plots colored by functional group
Using species-specific colors defined in the Groups parameter table
Size spectra are fundamental patterns in marine ecology, typically showing -declining abundance with increasing body size. This visualization helps -assess model realism and identify dominant size classes within each -functional group.
-if (FALSE) { # \dontrun{
-# After running ZooMSS model
-results <- zoomss_model(input_params, Groups, SaveTimeSteps = FALSE)
-size_plot <- plotSizeSpectra(results)
-print(size_plot)
-} # }
-
-zSizeBiomass.RdConverts abundance to biomass and sums across all functional groups -to provide total biomass per size class per spatial cell.
-zExtractBiomassSize(res, w)List of vectors with total biomass per size class (grams wet weight)
-Calculate Size-Class Biomass
-This function provides size-class-level biomass by summing across -functional groups. Useful for analyzing community size structure and -comparing size spectrum patterns between locations.
-zExtractBiomassSpecies.RdConverts abundance to biomass and sums across all size classes -to provide total biomass per functional group per spatial cell.
-zExtractBiomassSpecies(res, vmdl)List of vectors with total biomass per functional group (grams wet weight)
-Calculate Species-Level Biomass
-This function combines abundance-to-biomass conversion with size-class -aggregation in one step, providing species-level biomass summaries useful -for spatial analyses and ecological comparisons.
-zSpeciesCarbonBiomass.RdConverts abundance data to carbon biomass and then sums across all -size classes to provide total carbon biomass per functional group.
-zSpeciesCarbonBiomass(res, vmdl)List of vectors with total carbon biomass per functional group (grams carbon)
-Convert Abundance to Species-Level Carbon Biomass
-This function combines carbon biomass conversion with size-class aggregation:
Converts abundance to wet weight biomass
Converts to carbon biomass using group-specific factors
Sums across all size classes for each functional group
Provides species-level carbon biomass useful for ecological stoichiometry -and biogeochemical cycle analyses.
-zSumAll.RdCalculates total abundance across all functional groups and size classes, -providing a single abundance value per spatial cell.
-reduceAll(list_in)Vector of total abundance values (one per spatial cell)
-Sum All ZooMSS Output
-This function provides the most aggregated view of ZooMSS output by -summing across both functional groups and size classes. Useful for comparing -total community abundance between locations or time periods.
-zSumSize.RdThis file contains utility functions for processing, analyzing, and -transforming ZooMSS model outputs for visualization and interpretation.
-Sums abundance values across all size classes for each functional group, -providing total abundance per group.
-reduceSize(list_in)List of vectors with total abundance per functional group
-ZooMSS Utility Functions for Analysis and Post-Processing
-The utility functions in this file provide tools for:
Converting between abundance and biomass
Aggregating results across size classes or functional groups
Calculating ecological metrics (trophic levels, PPMR)
Processing environmental data for model input
Data format conversions for analysis workflows
These functions are essential for the ZooMSS analysis pipeline and help users -work with model outputs in different formats depending on their research needs. -Sum ZooMSS Output Across Size Bins
-This function collapses the size dimension of ZooMSS output by summing -across all size classes. Useful for analyzing total abundance patterns without -size structure detail.
-if (FALSE) { # \dontrun{
-# After running ZooMSS model
-results <- zoomss_model(input_params, Groups, SaveTimeSteps = FALSE)
-total_abundances <- reduceSize(results$abundances)
-} # }
-
-zSumSpecies.RdSums abundance values across all functional groups for each size class, -providing total abundance per size class.
-reduceSpecies(list_in)List of vectors with total abundance per size class
-Sum ZooMSS Output Across Functional Groups
-This function collapses the functional group dimension by summing across -all groups for each size class. Useful for analyzing community size spectrum -patterns without functional group detail.
-zTrophicLevel.RdCalculates trophic levels for each functional group based on their -diet composition using an iterative Gauss-Seidel algorithm.
-extractTrophicLevels(diet_matrix)Vector of trophic levels for each functional group (length 12)
-Calculate Trophic Levels from Diet Matrix
-This function computes trophic levels by:
Starting with phytoplankton at trophic level 1.0
Initializing all other groups at trophic level 2.0
Iteratively updating trophic levels based on weighted diet composition
Continuing until convergence (difference < 0.01) or maximum iterations (100)
Trophic level calculation follows: TL = 1 + sum(diet_fraction_i * TL_prey_i)
-This provides a quantitative measure of each group's position in the food web -and is useful for analyzing ecosystem structure and energy transfer efficiency.
-if (FALSE) { # \dontrun{
-# After running ZooMSS model
-results <- zoomss_model(input_params, Groups, SaveTimeSteps = FALSE)
-trophic_levels <- extractTrophicLevels(results$diets)
-
-# View trophic levels by group
-names(trophic_levels) <- results$model$param$Groups$Species
-print(trophic_levels)
-} # }
-
-validateGroups.RdPerforms comprehensive validation of functional groups data to ensure -it meets ZooMSS model requirements.
-validateGroups(groups)TRUE if validation passes (invisibly), otherwise throws an error
-Validate Functional Groups Data
-This function validates:
Required column names are present
Data types are correct
Parameter values are within reasonable ranges
No missing values in critical columns
Size ranges are logical (W0 < Wmax)
if (FALSE) { # \dontrun{
-Groups <- getGroups()
-validateGroups(Groups) # Should pass
-
-# This would fail validation:
-bad_groups <- Groups
-bad_groups$W0 <- NULL
-validateGroups(bad_groups) # Error: missing required column
-} # }
-
-R/zoomss_model.R
- zoomss_model.RdThis is the main wrapper function that orchestrates a complete ZooMSS -model simulation from parameter setup through model execution to output processing.
-Data frame containing model parameters and environmental time series. -Must include columns: time (time vector in years), sst (sea surface temperature), -and chl (chlorophyll). Can optionally include cellID for spatial data. The time step (dt) -and maximum time (tmax) are automatically calculated from the time vector. Can be created using createInputParams().
Data frame defining functional groups with their biological parameters. -Must include columns defining species characteristics, size ranges, and feeding parameters. -If NULL, uses default ZooMSS functional groups. Can be obtained/customized using -getGroups().
Save frequency in time steps (default: 10)
Complete ZooMSS model results object containing:
param: Model parameters and environmental forcing data
N: Abundance time series (time x groups x size classes)
gg: Growth rate time series
Z: Mortality rate time series
diet: Diet composition time series
time: Time values corresponding to saved results (accounting for isave)
Additional model structure and kernel data
Run Complete ZooMSS Model Simulation
-This function coordinates the entire ZooMSS modeling workflow:
Validates that environmental time series data is provided
Sets up model parameters using the Groups data and input parameters
Initializes the model structure and feeding kernels
Runs the model forward in time with dynamic environmental forcing
Processes outputs by averaging the final 50% of the simulation
Returns organized results including abundances, diets, growth, and mortality
This is the primary entry point for -running ZooMSS simulations with environmental forcing.
-if (FALSE) { # \dontrun{
-# Basic usage with default groups
-env_data <- createEnviroData(10, 0.01)
-input_params <- createInputParams(env_data$time, env_data$sst, env_data$chl)
-results <- zoomss_model(input_params, isave = 50)
-
-# Using custom groups
-Groups <- getGroups() # Get default groups
-Groups$W0[1] <- -12.5 # Modify a parameter
-results <- zoomss_model(input_params, Groups, isave = 100)
-
-# Loading groups from file
-custom_groups <- getGroups(source = "file", file = "my_groups.csv")
-results <- zoomss_model(input_params, custom_groups)
-} # }
-
-R/zoomss_mvf.R
- zoomss_mvf.RdSolves the McKendrick-von Foerster (MvF) partial differential equation -for size-structured population dynamics using a finite difference approach in base R.
-zoomss_mvf(
- ngrps,
- curr_min_size,
- curr_max_size,
- A_iter,
- C_iter,
- Nb_iter,
- S_iter,
- A,
- B,
- C,
- Nb,
- S
-)Number of functional groups in the model
Vector of minimum size class indices for each group
Vector of maximum size class indices for each group
Matrix of advection coefficients for current iteration
Matrix of diagonal coefficients for current iteration
Matrix to store updated abundances for current iteration
Matrix of source terms for current iteration
Matrix of advection coefficients
Matrix of diffusion coefficients
Matrix of diagonal coefficients
Matrix of abundances to be updated
Matrix of source terms
McKendrick-von Foerster Equation Solver (Base R Implementation)
-This function implements the numerical solution to the McKendrick-von Foerster -equation, which describes how populations change across size classes over time. -The equation is solved using an upwind finite difference scheme that handles:
Growth through size classes (advection term)
Diffusion between adjacent size classes
Source and sink terms from feeding and mortality
The function processes each functional group separately and applies boundary conditions -appropriate for size-structured models. The last size class is set to zero abundance -to represent maximum size limits.
-This is a core computational component of ZooMSS that updates population abundances -at each time step based on growth, mortality, and reproduction processes.
-if (FALSE) { # \dontrun{
-# This function is typically called internally by zoomss_run
-# Example shows the structure of parameters needed:
-ngrps <- 9
-ngrid <- 100
-curr_min_size <- c(1, 10, 20, 30, 40, 50, 60, 70, 80)
-curr_max_size <- c(30, 40, 50, 60, 70, 80, 90, 95, 100)
-
-# Initialize coefficient matrices
-A <- matrix(0, nrow = ngrps, ncol = ngrid)
-B <- matrix(0, nrow = ngrps, ncol = ngrid)
-C <- matrix(1, nrow = ngrps, ncol = ngrid)
-S <- matrix(0, nrow = ngrps, ncol = ngrid)
-Nb <- matrix(0.1, nrow = ngrps, ncol = ngrid)
-
-# Run MvF solver
-updated_abundances <- zoomss_mvf(ngrps, curr_min_size, curr_max_size,
- A, C, Nb, S, A, B, C, Nb, S)
-} # }
-
-R/zoomss_params.R
- zoomss_params.RdSets up the complete parameter list for ZooMSS model runs, including -functional group parameters, model dimensions, and environmental forcing data.
-Data frame containing functional group definitions with columns: -Species, Type, W0 (log min size), Wmax (log max size), and various biological parameters
Data frame with model parameters including: -time (time vector in years), sst (sea surface temperature), and chl (chlorophyll). -The time vector can start at any value and the model automatically calculates dt (time step) and tmax (maximum time).
Save frequency in time steps (default: 50)
List containing comprehensive model parameters:
Groups: Functional group definitions
ngrps: Number of functional groups
ngrid: Number of size classes
w: Size class weights (g)
tmax, dt, isave: Temporal parameters
zoo_grps, fish_grps: Indices for different organism types
phyto_int_ts, phyto_slope_ts: Time series of phytoplankton parameters
temp_eff_zoo_ts, temp_eff_fish_ts: Time series of temperature effects
Additional biological and physical parameters
Set Up ZooMSS Model Parameters
-This function creates a comprehensive parameter object that contains:
-Static Parameters (fixed across time steps):
Model dimensions (number of groups, size classes, time steps)
Biological parameters (growth efficiency, mortality rates)
Size class definitions and ranges for each functional group
Phytoplankton size spectrum parameters
Dynamic Parameters (calculated from environmental data):
Phytoplankton abundance time series based on chlorophyll
Temperature effects on metabolism for zooplankton and fish
Environmental forcing validation and interpolation
The function validates that environmental time series data covers the full -simulation period and pre-calculates time-varying parameters to optimize -model performance during the main simulation loop.
-if (FALSE) { # \dontrun{
-# Load functional groups
-data(Groups)
-
-# Create environmental time series
-env_data <- createEnviroData(10, 0.01)
-input_params <- createInputParams(env_data$time, env_data$sst, env_data$chl)
-
-# Generate parameter list
-params <- zoomss_params(Groups, input_params, isave = 50)
-} # }
-
-R/zoomss_run.R
- zoomss_run.RdRuns the ZooMSS model forward in time, updating environmental conditions -and population dynamics at each time step using the McKendrick-von Foerster framework.
-List containing complete model output:
param: Model parameters used in simulation
N: Abundance time series (time x groups x size classes)
gg: Growth rate time series
diet: Diet composition time series
Z: Mortality rate time series
time: Time values corresponding to saved results (accounting for isave)
w: Size class weights (g)
Additional time series data and model results
Run ZooMSS Model Forward in Time
-This is the core simulation engine of ZooMSS that:
-Environmental Dynamics:
Updates phytoplankton abundance spectrum based on chlorophyll time series
Applies temperature effects on zooplankton and fish metabolism
Recalculates feeding kernels with current environmental conditions
Population Dynamics:
Solves McKendrick-von Foerster equation for size-structured growth
Updates feeding interactions between all size classes and groups
Calculates mortality from predation, senescence, and fishing
Handles recruitment and boundary conditions for each functional group
Time Integration:
Processes model through all time steps with adaptive environmental forcing
Saves output at specified intervals for memory efficiency
Maintains mass balance and numerical stability throughout simulation
Unlike static models, this version dynamically updates phytoplankton spectra -and temperature effects at each time step based on provided environmental data.
-if (FALSE) { # \dontrun{
-# Set up model parameters and structure
-params <- zoomss_params(Groups, input_params)
-model <- zoomss_setup(params)
-
-# Run the simulation
-results <- zoomss_run(model)
-
-# Access final abundances
-final_abundances <- results$N[dim(results$N)[1],,]
-} # }
-
-R/zoomss_setup.R
- zoomss_setup.RdSets up the ZooMSS model structure by calculating feeding kernels, mortality -rates, and other model components that remain static during the simulation.
-Model object containing:
param: Input parameters (passed through)
dynam_xxx: Dynamic feeding kernel arrays for group interactions (where xxx = growthkernel, diffkernel, dietkernel, mortkernel)
phyto_xxx: Phytoplankton feeding kernel arrays (where xxx = growthkernel, diffkernel, dietkernel)
nPP: Initial phytoplankton abundance spectrum
M_sb_base: Baseline senescence mortality rates
fish_mort: Fishing mortality rates
assim_eff: Assimilation efficiency matrix
temp_eff: Temperature effect matrix (initialized)
N: Initial abundance arrays
time: Time array for storing time values (initialized as NA)
Additional model structure components
Setup ZooMSS Model Structure and Feeding Kernels
-This function initializes the core ZooMSS model structure by calculating:
-Static Components (calculated once):
Feeding preference kernels based on predator-prey size ratios
Search volumes and encounter rates between size classes
Baseline mortality rates (senescence, fishing)
Initial abundance distributions for all functional groups
Dynamic Component Structures (updated during run):
Phytoplankton feeding kernels (structure calculated here, values updated with environment)
Growth and diffusion kernels for zooplankton and fish interactions
Diet and mortality tracking arrays
Model Architecture:
Size-structured populations across logarithmic size classes
Multiple functional groups with different feeding behaviors
Environmental coupling through phytoplankton and temperature
The function separates static calculations (done once for efficiency) from -dynamic calculations (updated each time step in zoomss_run).
-if (FALSE) { # \dontrun{
-# Create parameters for model setup
-params <- zoomss_params(Groups, input_params)
-
-# Initialize model structure
-model <- zoomss_setup(params)
-
-# Model is now ready for time integration with zoomss_run
-results <- zoomss_run(model)
-} # }
-
-