diff --git a/dev/.documenter-siteinfo.json b/dev/.documenter-siteinfo.json index fe0edec..aa56025 100644 --- a/dev/.documenter-siteinfo.json +++ b/dev/.documenter-siteinfo.json @@ -1 +1 @@ -{"documenter":{"julia_version":"1.6.7","generation_timestamp":"2024-11-30T17:16:07","documenter_version":"1.8.0"}} \ No newline at end of file +{"documenter":{"julia_version":"1.6.7","generation_timestamp":"2024-12-05T17:06:39","documenter_version":"1.8.0"}} \ No newline at end of file diff --git a/dev/CreateInitializeLoop/index.html b/dev/CreateInitializeLoop/index.html index a9d43d5..8ac912d 100644 --- a/dev/CreateInitializeLoop/index.html +++ b/dev/CreateInitializeLoop/index.html @@ -1,2 +1,2 @@ -Control flow · PALEOboxes Documentation

Control flow

Model Creation

A YAML format configuration file defines both the model structure (spatial domains containing biogeochemical variables and reactions that operate on them) and model parameter values. Reactions (subtypes of AbstractReaction) are identified by Type name (without module prefix) in the configuration file.

To create the model, the numerical solver or host should call create_model_from_config which reads the configuration file, and then:

Model initialisation

To initialise the model, the numerical solver or host should then:

State Variable initialization

To initialise state Variables and perform any Reaction-specific initialisation, the numerical solver or host should:

  • call dispatch_setup with attribute_name = :norm_value. These Reaction setup methods should set state Variables according to the :norm_value Variable attribute (which can be set in the variable_attributes: section of the config file). Reactions may also use these values internally.
    • optionally (if normalisation values are required by a numerical solver), copy the Variable normalisation values from the arrays in ModelData to the solver.
  • optionally call dispatch_setup with attribute_name = :initial_value to set state Variables according to the :initial_value Variable attribute (which can be set in the variable_attributes: section of the config file).

Main loop

To calculate the model derivative, the numerical solver or host should:

Additional notes

Operator splitting and Domain tiling: Reaction and Domain subsets

The default initialisation described above calculates the model derivative for all model Reactions for all Domains, using the cellranges_all, and dispatchlists_all fields of the ModelData struct. A custom Vector of CellRanges can be used to select a subset of ReactionMethods by Domain and operatorID, eg to implement operator splitting. Tiles within Domain eg to implement Domain decomposition for a multithreaded model can be defined by specifying CellRanges with a subset of cell indices within Domains.

The custom Vector of CellRanges should then be supplied to

Multithreaded models

To use with a multithreaded solver eg for a spatially tiled model:

  • Set threadsafe=true when calling create_modeldata. The subsequent call to allocate_variables! will then allocate Julia Threads.Atomic variables for PALEO Variables with attribute atomic: = true (usually scalar accumulator variables for totals etc).
  • Supply a method_barrier implementing a thread barrier function to initialize_reactiondata!. Reactions are sorted into groups, where each group has no dependencies and later groups depend on earlier ones. The method_barrier will be inserted between these groups of independent Reactions.

Automatic differentiation

  • Set eltype when calling create_modeldata to the appropriate dual number type for a (forward) automatic differentation implementation. All model arrays are held in the created ModelData struct and multiple ModelData instances can be created, allowing a combination of eg AD Jacobian and standard derivative calculations with different array types.
+Control flow · PALEOboxes Documentation

Control flow

Model Creation

A YAML format configuration file defines both the model structure (spatial domains containing biogeochemical variables and reactions that operate on them) and model parameter values. Reactions (subtypes of AbstractReaction) are identified by Type name (without module prefix) in the configuration file.

To create the model, the numerical solver or host should call create_model_from_config which reads the configuration file, and then:

Model initialisation

To initialise the model, the numerical solver or host should then:

State Variable initialization

To initialise state Variables and perform any Reaction-specific initialisation, the numerical solver or host should:

  • call dispatch_setup with attribute_name = :norm_value. These Reaction setup methods should set state Variables according to the :norm_value Variable attribute (which can be set in the variable_attributes: section of the config file). Reactions may also use these values internally.
    • optionally (if normalisation values are required by a numerical solver), copy the Variable normalisation values from the arrays in ModelData to the solver.
  • optionally call dispatch_setup with attribute_name = :initial_value to set state Variables according to the :initial_value Variable attribute (which can be set in the variable_attributes: section of the config file).

Main loop

To calculate the model derivative, the numerical solver or host should:

Additional notes

Operator splitting and Domain tiling: Reaction and Domain subsets

The default initialisation described above calculates the model derivative for all model Reactions for all Domains, using the cellranges_all, and dispatchlists_all fields of the ModelData struct. A custom Vector of CellRanges can be used to select a subset of ReactionMethods by Domain and operatorID, eg to implement operator splitting. Tiles within Domain eg to implement Domain decomposition for a multithreaded model can be defined by specifying CellRanges with a subset of cell indices within Domains.

The custom Vector of CellRanges should then be supplied to

Multithreaded models

To use with a multithreaded solver eg for a spatially tiled model:

  • Set threadsafe=true when calling create_modeldata. The subsequent call to allocate_variables! will then allocate Julia Threads.Atomic variables for PALEO Variables with attribute atomic: = true (usually scalar accumulator variables for totals etc).
  • Supply a method_barrier implementing a thread barrier function to initialize_reactiondata!. Reactions are sorted into groups, where each group has no dependencies and later groups depend on earlier ones. The method_barrier will be inserted between these groups of independent Reactions.

Automatic differentiation

  • Set eltype when calling create_modeldata to the appropriate dual number type for a (forward) automatic differentation implementation. All model arrays are held in the created ModelData struct and multiple ModelData instances can be created, allowing a combination of eg AD Jacobian and standard derivative calculations with different array types.
diff --git a/dev/DesignOverview/index.html b/dev/DesignOverview/index.html index d9ddb98..026a667 100644 --- a/dev/DesignOverview/index.html +++ b/dev/DesignOverview/index.html @@ -1,2 +1,2 @@ -PALEOboxes coupler design · PALEOboxes Documentation

PALEOboxes coupler design

A PALEO Model contains Domains, each of which contain Variables defining Fields containing Data arrays, and Reactions with ReactionMethods that operate on the Variables to calculate model time evolution.

The PALEOboxes Julia package (abbreviated to PB in the PALEO code) implements a coupler that provides a unified mechanism for

  1. ‘low-level’ coupling (e.g. linking individual redox Reactions within a Domain), on which is built
  2. ‘module-level’ coupling (linking e.g. atmosphere and ocean components) based on standardising names for communicating fluxes, and which enables
  3. separation of biogeochemical reaction and transport.

A YAML format configuration file then defines both the model structure (spatial domains containing biogeochemical variables and reactions that operate on them) and model parameter values.

Composing Reactions and Variables within a Domain

Figure 1

The PALEOboxes object model illustrated by a fragment of a marine biogeochemical model representing two phytoplankton populations competing for the same nutrient. The Ocean Domain contains two Reactions phytA and phytB, and three state Variables P, phytA and phytB with paired time derivatives P_sms, phytA_sms and phytB_sms. The Reactions are both instances of the same class PaleoReactionSimplePhyt, with a Parameter k_P, and a single method. The ReactionMethod defines interactions with a nutrient P via a Variable Dependency P and a Variable Contributor P_sms, and a population represented by Variable Dependency phyt and Contributor phyt_sms. P and P_sms from each PaleoReactionSimplePhyt instance are linked at run time to the same Domain Variables P and P_sms, using the default names from the PaleoReactionSimplePhyt code. phyt and phyt_sms are renamed in the configuration file to two different pairs of Domain Variables phytA, phytA_sms and phytB, phytB_sms, hence representing two distinct phytoplankton populations.

Reactions and ReactionMethods

Reactions contain Parameters and are implemented as subtypes of AbstractReaction along with associated methods. ReactionMethods and VariableReactions are created by Reactions during model initialization. All PALEO model time evolution (including external prescribed forcing, biogeochemistry, transport within eg an ocean Domain) is then implemented by the ReactionMethods as they are called during the model main loop.

Biogeochemical Variables

Variables defined as VariableReactions are then linked within (or across) Domains, creating corresponding VariableDomains. Linking of Variables is based on names (as text strings). Default names are encoded in the Reaction implementations (with standard names for e.g. chemical species such as O2, DIC marine tracers), and can be overridden in the configuration file. This is analogous to the use of ‘dummy variables’ in a Fortran or Python function call, and allows (i) a combination of default names for commonly-used biogeochemical variables (‘P’, ‘SO4’ etc), with (ii) renamed variables to allow multiple Reaction instances (e.g. two phytoplankton populations with state variable names and parameter choices for the same Reaction implementation), or (iii) enable rerouting of fluxes and dependencies that are specific to the model configuration, or (iv) sort out name conflicts where no default names have been established.

Variables are classified into two pairings: Properties with Dependencies (shown shaded green in Figure 1, linked at run time to Domain VariableDomPropDeps), or flux Targets and Contributors (shaded pink in Figure 1, linked at run-time to Domain VariableDomContribTargets). This classification retains flexibility while providing sufficient information to allow automatic detection of errors in model specification (for example, a Dependency with no Property, or a flux Contributor with no Target), and automatic scheduling of Reactions within the model main loop (as a Reaction that defines a Property must be executed before a Reaction that Depends on this property).

Variables can specify metadata as an extensible list of attributes which can then be queried (using get_attribute) and filtered on (using get_variables) during model configuration and initialisation. This enables the labelling of groups of variables (e.g. the :advect and :vertical_motion attributes are used by a Reaction implementing ocean transport to identify those state variables representing solutes that should be transported; the :vfunction attribute is used by numerical solvers to identify state variables and their time derivatives).

Spatially-resolved Domains and Grids

Domains may contain a Grid (a subtype of AbstractMesh) to define a spatially-resolved Domain containing multiple cells.

Three-dimensional Domains (eg ocean) are associated with two-dimensional boundary Domains (eg oceansurface, oceanfloor), and also provide Subdomains (subtypes of AbstractSubdomain, eg ocean.oceansurface, ocean.oceanfloor) that specify the subset of 3D ocean cells adjacent to the 2D boundaries.

Fields and Data

Variables contain Fields which represent data (a subtype of AbstractData defined by the :field_data ttribute) in a function space (a subtype of AbstractSpace defined by the :space attribute).

The AbstractSpace subtype (see Spaces) can define a per-Domain (ScalarSpace) or per-cell (CellSpace) quantity, where the number of cells is defined by the Domain grid.

The AbstractData subtype (see Data types) defines the information that is stored per Domain or per grid cell. ScalarData defines one value, ArrayScalarData an array of scalar values eg for intensity on a wavelength grid, and AbstractIsotopeScalar a multiple-component isotope system (see Isotopes).

Coupling Spatial Domains

Figure 2

Defining and coupling spatial Domains. The four Domains atm, oceansurface, ocean and fluxAtmOceansurface are defined in the model configuration file. The first three of these contain arbitrary biogeochemical Reactions and Variables. Domain fluxAtmOceansurface contains only a FluxTarget Reaction and a set of Target Variables fluxO2. Exchange fluxes are accumulated into these flux Variables (in this case, produced by air-sea exchange reactions in the oceansurface Domain), and then redistributed to atm and ocean by the FluxTransfer Reactions taking account of mapping between Domain dimensions.

Coupling between Earth system components is provided by Fluxes, implemented by Fluxes.ReactionFluxTargets (Figure 2) that provide a set of flux Target Variables in nominated flux coupler Domains, and Fluxes.ReactionFluxTransfer that then transfer fluxes (with appropriate mapping) to a different Domain.

Variable text names may be referred to from other Domains by prefixing with Domain and Subdomain names (eg ocean.P_conc links to the 3D ocean interior Variable P_conc, ocean.oceansurface.O2_conc links to the ocean oxygen concentration for the 2D subset of ocean cells adjacent to the oceansurface boundary).

Separating time integration, reaction, and transport

Figure 3

Examples of model configurations with different reaction/transport partitioning: a) a configuration with offline transport and forcing provided by Reactions within the PALEO framework. The only external dependencies are state variables and derivatives, with time integration provided by a standard ODE solver such as CVODE and the overall model workflow (initialisation, solution, output) managed by the PALEOmodel package. b) an ocean-only model embedded in a GCM host which provides transport and physical properties such as temperature and sequences the model workflow.

The :vfunction Variable attribute is used to identify pairs of state variables (labelled with :vfunction = VF_StateExplicit) and their corresponding time derivatives (labelled with :vfunction = VF_Deriv). Algebraic constraints are defined by Variables labelled with :vfunction = VF_Constraint, with a corresponding number of state variables labelled with :vfunction = VF_State. Implicit variables are defined by pairs of variables and time derivatives labelled with :vfunction = VF_Total and :vfunction = VF_Deriv, with a corresponding number of state variables labelled with :vfunction = VF_State.

To access variables, a numerical ODE or DAE solver can use VariableAggregator to implement a high-level interface to aggregated lists. A host dynamical model can alternatively use get_variables during model configuration and initialisation to link to individual host data arrays.

The abstractions described above enable a natural separation of biogeochemical reaction and transport, which can then either be provided by a host dynamical model e.g. implemented in C or Fortran, or as offline transport implemented by PALEO “reactions” within the framework (Figure 3). This enables both rapid, interactive development and experimentation in a PC/workstation environment using offline transport, and deployment of the same model code as a component embedded in a larger GCM model.

+PALEOboxes coupler design · PALEOboxes Documentation

PALEOboxes coupler design

A PALEO Model contains Domains, each of which contain Variables defining Fields containing Data arrays, and Reactions with ReactionMethods that operate on the Variables to calculate model time evolution.

The PALEOboxes Julia package (abbreviated to PB in the PALEO code) implements a coupler that provides a unified mechanism for

  1. ‘low-level’ coupling (e.g. linking individual redox Reactions within a Domain), on which is built
  2. ‘module-level’ coupling (linking e.g. atmosphere and ocean components) based on standardising names for communicating fluxes, and which enables
  3. separation of biogeochemical reaction and transport.

A YAML format configuration file then defines both the model structure (spatial domains containing biogeochemical variables and reactions that operate on them) and model parameter values.

Composing Reactions and Variables within a Domain

Figure 1

The PALEOboxes object model illustrated by a fragment of a marine biogeochemical model representing two phytoplankton populations competing for the same nutrient. The Ocean Domain contains two Reactions phytA and phytB, and three state Variables P, phytA and phytB with paired time derivatives P_sms, phytA_sms and phytB_sms. The Reactions are both instances of the same class PaleoReactionSimplePhyt, with a Parameter k_P, and a single method. The ReactionMethod defines interactions with a nutrient P via a Variable Dependency P and a Variable Contributor P_sms, and a population represented by Variable Dependency phyt and Contributor phyt_sms. P and P_sms from each PaleoReactionSimplePhyt instance are linked at run time to the same Domain Variables P and P_sms, using the default names from the PaleoReactionSimplePhyt code. phyt and phyt_sms are renamed in the configuration file to two different pairs of Domain Variables phytA, phytA_sms and phytB, phytB_sms, hence representing two distinct phytoplankton populations.

Reactions and ReactionMethods

Reactions contain Parameters and are implemented as subtypes of AbstractReaction along with associated methods. ReactionMethods and VariableReactions are created by Reactions during model initialization. All PALEO model time evolution (including external prescribed forcing, biogeochemistry, transport within eg an ocean Domain) is then implemented by the ReactionMethods as they are called during the model main loop.

Biogeochemical Variables

Variables defined as VariableReactions are then linked within (or across) Domains, creating corresponding VariableDomains. Linking of Variables is based on names (as text strings). Default names are encoded in the Reaction implementations (with standard names for e.g. chemical species such as O2, DIC marine tracers), and can be overridden in the configuration file. This is analogous to the use of ‘dummy variables’ in a Fortran or Python function call, and allows (i) a combination of default names for commonly-used biogeochemical variables (‘P’, ‘SO4’ etc), with (ii) renamed variables to allow multiple Reaction instances (e.g. two phytoplankton populations with state variable names and parameter choices for the same Reaction implementation), or (iii) enable rerouting of fluxes and dependencies that are specific to the model configuration, or (iv) sort out name conflicts where no default names have been established.

Variables are classified into two pairings: Properties with Dependencies (shown shaded green in Figure 1, linked at run time to Domain VariableDomPropDeps), or flux Targets and Contributors (shaded pink in Figure 1, linked at run-time to Domain VariableDomContribTargets). This classification retains flexibility while providing sufficient information to allow automatic detection of errors in model specification (for example, a Dependency with no Property, or a flux Contributor with no Target), and automatic scheduling of Reactions within the model main loop (as a Reaction that defines a Property must be executed before a Reaction that Depends on this property).

Variables can specify metadata as an extensible list of attributes which can then be queried (using get_attribute) and filtered on (using get_variables) during model configuration and initialisation. This enables the labelling of groups of variables (e.g. the :advect and :vertical_motion attributes are used by a Reaction implementing ocean transport to identify those state variables representing solutes that should be transported; the :vfunction attribute is used by numerical solvers to identify state variables and their time derivatives).

Spatially-resolved Domains and Grids

Domains may contain a Grid (a subtype of AbstractMesh) to define a spatially-resolved Domain containing multiple cells.

Three-dimensional Domains (eg ocean) are associated with two-dimensional boundary Domains (eg oceansurface, oceanfloor), and also provide Subdomains (subtypes of AbstractSubdomain, eg ocean.oceansurface, ocean.oceanfloor) that specify the subset of 3D ocean cells adjacent to the 2D boundaries.

Fields and Data

Variables contain Fields which represent data (a subtype of AbstractData defined by the :field_data ttribute) in a function space (a subtype of AbstractSpace defined by the :space attribute).

The AbstractSpace subtype (see Spaces) can define a per-Domain (ScalarSpace) or per-cell (CellSpace) quantity, where the number of cells is defined by the Domain grid.

The AbstractData subtype (see Data types) defines the information that is stored per Domain or per grid cell. ScalarData defines one value, ArrayScalarData an array of scalar values eg for intensity on a wavelength grid, and AbstractIsotopeScalar a multiple-component isotope system (see Isotopes).

Coupling Spatial Domains

Figure 2

Defining and coupling spatial Domains. The four Domains atm, oceansurface, ocean and fluxAtmOceansurface are defined in the model configuration file. The first three of these contain arbitrary biogeochemical Reactions and Variables. Domain fluxAtmOceansurface contains only a FluxTarget Reaction and a set of Target Variables fluxO2. Exchange fluxes are accumulated into these flux Variables (in this case, produced by air-sea exchange reactions in the oceansurface Domain), and then redistributed to atm and ocean by the FluxTransfer Reactions taking account of mapping between Domain dimensions.

Coupling between Earth system components is provided by Fluxes, implemented by Fluxes.ReactionFluxTargets (Figure 2) that provide a set of flux Target Variables in nominated flux coupler Domains, and Fluxes.ReactionFluxTransfer that then transfer fluxes (with appropriate mapping) to a different Domain.

Variable text names may be referred to from other Domains by prefixing with Domain and Subdomain names (eg ocean.P_conc links to the 3D ocean interior Variable P_conc, ocean.oceansurface.O2_conc links to the ocean oxygen concentration for the 2D subset of ocean cells adjacent to the oceansurface boundary).

Separating time integration, reaction, and transport

Figure 3

Examples of model configurations with different reaction/transport partitioning: a) a configuration with offline transport and forcing provided by Reactions within the PALEO framework. The only external dependencies are state variables and derivatives, with time integration provided by a standard ODE solver such as CVODE and the overall model workflow (initialisation, solution, output) managed by the PALEOmodel package. b) an ocean-only model embedded in a GCM host which provides transport and physical properties such as temperature and sequences the model workflow.

The :vfunction Variable attribute is used to identify pairs of state variables (labelled with :vfunction = VF_StateExplicit) and their corresponding time derivatives (labelled with :vfunction = VF_Deriv). Algebraic constraints are defined by Variables labelled with :vfunction = VF_Constraint, with a corresponding number of state variables labelled with :vfunction = VF_State. Implicit variables are defined by pairs of variables and time derivatives labelled with :vfunction = VF_Total and :vfunction = VF_Deriv, with a corresponding number of state variables labelled with :vfunction = VF_State.

To access variables, a numerical ODE or DAE solver can use VariableAggregator to implement a high-level interface to aggregated lists. A host dynamical model can alternatively use get_variables during model configuration and initialisation to link to individual host data arrays.

The abstractions described above enable a natural separation of biogeochemical reaction and transport, which can then either be provided by a host dynamical model e.g. implemented in C or Fortran, or as offline transport implemented by PALEO “reactions” within the framework (Figure 3). This enables both rapid, interactive development and experimentation in a PC/workstation environment using offline transport, and deployment of the same model code as a component embedded in a larger GCM model.

diff --git a/dev/DomainsVariablesFields/index.html b/dev/DomainsVariablesFields/index.html index 06702f4..b6bbd77 100644 --- a/dev/DomainsVariablesFields/index.html +++ b/dev/DomainsVariablesFields/index.html @@ -1,9 +1,9 @@ -Domains, Variables, Fields, and Data arrays. · PALEOboxes Documentation

Domains, Variables, Fields, and Data arrays.

A Model contains Domains, each of which contain Variables defining Fields which contain Data arrays, and Reactions with ReactionMethods that operate on the Fields to calculate model time evolution.

Model

Domains

PALEOboxes.DomainType
Domain

A model region containing Variables and Reactions that act on them.

Domain spatial size is defined by grid, which may be nothing to define a scalar Domain, or an AbstractMesh to define a spatially-resolved Domain with multiple cells.

Named data_dims may be set by set_data_dimension! to allow Variables with additional non-spatial dimensions, eg to represent quantities on a wavelength grid.

source

Grids

PALEOboxes.internal_sizeFunction
internal_size(::Type{<:AbstractSpace}, mesh::AbstractMesh; [subdomain=""] [space=:cell]) -> NTuple{ndims, Int}

Array size to use for model Variables.

All AbstractMesh concrete subtypes (UnstructuredVectorGrid, CartesianLinearGrid, ...) should implement this method.

Optional Keyword Arguments

  • subdomain::String="": a named subdomain
source
PALEOboxes.cartesian_sizeFunction
cartesian_size(mesh::AbstractMesh) -> NTuple{ndims, Int}

Optional (only regular Cartesian grids should implement this method): Array size of Cartesian Domain.

NB: this may be different from internal_size if the mesh implements a mapping eg to a Vector for internal model Variables.

source
PALEOboxes.Grids.set_subdomain!Function
set_subdomain!(grid::PB.AbstractMesh, subdomainname::AbstractString, subdom::PB.AbstractSubdomain, allowcreate::Bool=false)

Set Subdomain

source
PALEOboxes.Grids.UnstructuredColumnGridType
UnstructuredColumnGrid <: PB.AbstractMesh

Minimal Grid for a Vector Domain composed of columns (not necessarily forming a 2-D array).

Fields

  • ncells::Int total number of cells in this Domain
  • Icolumns::Vector{Vector{Int}}: Icolumns[n] should be the indices of column n, in order from surface to floor, where n is also the index of

any associated boundary surface.

  • z_coords::Vector{FixedCoord}: z coordinates of cell mid point, lower surface, upper surface
  • columnnames::Vector{Symbol}: optional column names
source
PALEOboxes.Grids.CartesianLinearGridType
CartesianLinearGrid <: PB.AbstractMesh

nD grid with netcdf CF1.0 coordinates, using Vectors for PALEO internal representation of Variables, with a mapping linear indices <–> some subset of grid indices.

The linear indices mapping should be set with set_linear_index. Conversion of Field values between the PALEO internal representation (a Vector with a linear index) and a Cartesian Array with multiple dimensions (for import and export of model output) is then implemented by cartesian_to_internal and internal_to_cartesian.

Fields

  • ncells::Int64: number of cells in Domain = length(linear_index) (may be subset of total points in prod(dims))
  • dimnames::Vector{String}: names of dimensions (ordered list)
  • dims::Vector{Int}: sizes of dimensions (ordered list)
  • coords::Vector{Vector{Float64}}: attached cell-centre coordinates for each dimension (ordered list)
  • coords_edges::Vector{Vector{Float64}}: attached cell-edge coordinates for each dimension (ordered list)
source
PALEOboxes.Grids.CartesianArrayGridType
CartesianArrayGrid <: PB.AbstractMesh

nD grid with netcdf CF1.0 coordinates, using n-dimensional Arrays for PALEO internal representation of Variables

Fields

  • ncells::Int64: number of cells in Domain = length(linear_index) (may be subset of total points in prod(dims))
  • dimnames::Vector{String}: names of dimensions (ordered list)
  • dims::Vector{Int}: sizes of dimensions (ordered list)
  • coords::Vector{Vector{Float64}}: attached cell-centre coordinates for each dimension (ordered list)
  • coords_edges::Vector{Vector{Float64}}: attached cell-edge coordinates for each dimension (ordered list)
source

Subdomains

PALEOboxes.Grids.BoundarySubdomainType
BoundarySubdomain <: PB.AbstractSubdomain

A 2D subdomain corresponding to the 2D boundary Domain associated with a 3D interior Domain:

  • indices[ibnd] is the index of the 3D interior cell corresponding to a 2D boundary cell ibnd.
source
PALEOboxes.Grids.InteriorSubdomainType
InteriorSubdomain <: PB.AbstractSubdomain

A 3D subdomain corresponding to the 3D interior Domain associated with a 2D boundary Domain: indices[iint] is either:

  • missing if iint is the index of an interior cell in the 3D Domain, or
  • the index of the 2D boundary Domain cell corresponding to the boundary-adjacent 3D interior Domain cell iint
source
PALEOboxes.Grids.subdomain_viewFunction
subdomain_view(values, subdomain::BoundarySubdomain) -> view

Create a view on values in an interior Domain to access cells corresponding to indices in a boundary Domain.

source
subdomain_view(values, subdomain::InteriorSubdomain) -> var

Return unmodified values from a boundary Domain, indices to access from interior supplied by subdomain_indices

source
subdomain_view(values, subdomain::Nothing) -> values

Fallback when subdomain == nothing

source
PALEOboxes.Grids.subdomain_indicesFunction
subdomain_indices(subdomain::BoundarySubdomain) -> nothing

No additional indices required to access Variables in an interior Domain from a boundary Domain (view created by subdomain_view is sufficient).

source
subdomain_indices(subdomain::InteriorSubdomain) -> indices

Return indices to access Variables in a boundary Domain from interior Domain (will have missing entries where interior cells do not correspond to boundary)

source
subdomain_indices(subdomain::Nothing) -> nothing

fallback when subdomain == nothing

source

Regions, Dimensions and Coordinates

PALEOboxes.Grids.get_regionFunction
get_region(grid::Union{PB.AbstractMesh, Nothing}, values; selectargs...) -> values_subset, (dim_subset::NamedDimension, ...)

Return the subset of values given by selectargs (Grid-specific keywords eg cell=, column=, ...) and corresponding dimensions (with attached coordinates).

source
get_region(grid::Nothing, values) -> values[]

Fallback for Domain with no grid, assumed 1 cell

source
get_region(grid::UnstructuredVectorGrid, values; cell) -> 
-    values_subset, (dim_subset::NamedDimension, ...)

Keywords for region selection:

  • cell::Union{Int, Symbol}: an Int, or a Symbol to look up in cellnames
source
get_region(grid::UnstructuredColumnGrid, values; column, [cell=nothing]) -> 
-    values_subset, (dim_subset::NamedDimension, ...)

Keywords for region selection:

  • column::Union{Int, Symbol}: (may be an Int, or a Symbol to look up in columnames)
  • cell::Int: optional cell index within column, highest cell is cell 1
source
get_region(grid::Union{CartesianLinearGrid{2}, CartesianArrayGrid{2}} , internalvalues; [i=i_idx], [j=j_idx]) ->
-    arrayvalues_subset, (dim_subset::NamedDimension, ...)

Keywords for region selection:

  • i::Int: optional, slice along first dimension
  • j::Int: optional, slice along second dimension

internalvalues are transformed if needed from internal Field representation as a Vector length ncells, to an Array (2D if neither i, j arguments present, 1D if i or j present, 0D ie one cell if both present)

source
get_region(grid::Union{CartesianLinearGrid{3}, CartesianArrayGrid{3}}, internalvalues; [i=i_idx], [j=j_idx]) ->
-    arrayvalues_subset, (dim_subset::NamedDimension, ...)

Keywords for region selection:

  • i::Int: optional, slice along first dimension
  • j::Int: optional, slice along second dimension
  • k::Int: optional, slice along third dimension

internalvalues are transformed if needed from internal Field representation as a Vector length ncells, to an Array (3D if neither i, j, k arguments present, 2D if one of i, j or k present, 1D if two present, 0D ie one cell if i, j, k all specified).

source

Grids may define name dimensions and attach coordinates for the convenience of output visualisation. Any coordinate information required by Reactions should be supplied as Variables.

PALEOboxes.NamedDimensionType
NamedDimension

A named dimension, with optional attached fixed coordinates coords

PALEO convention is that where possible coords contains three elements, for cell midpoints, lower edges, upper edges, in that order.

source

Variables

PALEO Variables exist in Domains and represent biogeochemical or other quantities. They are defined by Reactions as VariableReactions which are then linked to create VariableDomains, and contain Fields which represent data (a subtype of AbstractData) in a function space (a subtype of AbstractSpace) with dimensions defined by the Domain grid (a subtype of AbstractMesh)

Dataflow dependency between Variables is represented by two pairings:

PALEOboxes.VariableTypeType
@enum VariableType

Enumeration of VariableBase subtypes. Allowed values:

  • VariableReaction: VT_ReactProperty, VT_ReactDependency, VT_ReactContributor, VT_ReactTarget
  • VariableDomain : VT_DomPropDep, VT_DomContribTarget
source
PALEOboxes.VariableDomContribTargetType
VariableDomContribTarget <: VariableDomain

Model (Domain) VariableDomain linking a single VariableReaction{VT_ReactTarget} to multiple VariableReaction{VT_ReactContributor} and VariableReaction{VT_ReactDependency}.

source

Variable Attributes

PALEOboxes.AttributeType
Attribute{T}

Definition for Variable attribute name. Defines a data type T, a default_value, required (true if always present ie added with default_value when Variable is created), units, and an optional description.

Note that Variable attributes are stored as a per-Variable Dict(name => value), these definitions are only used to provide defaults, check types, and provide descriptive metadata.

ParseFromString should usually be Nothing: a value of Type T is then required when calling set_attribute!. If ParseFromString is true, then set_attribute! will accept an AbstractString and call Base.parse(T, strvalue) to convert to T. This allows eg an enum-valued Attribute to be defined by Attribute{EnumType, true} and implementing parse(EnumType, rawvalue::AbstractString)

source
PALEOboxes.StandardAttributesConstant
StandardAttributes

List of standard Variable attributes.

Some of these follow netCDF COARDS/CF conventions:

COARDS:https://ferret.pmel.noaa.gov/Ferret/documentation/coards-netcdf-conventions

CF conventions: https://cfconventions.org/cf-conventions/cf-conventions.html#_description_of_the_data

source
32×5 DataFrame
+Domains, Variables, Fields, and Data arrays. · PALEOboxes Documentation

Domains, Variables, Fields, and Data arrays.

A Model contains Domains, each of which contain Variables defining Fields which contain Data arrays, and Reactions with ReactionMethods that operate on the Fields to calculate model time evolution.

Model

Domains

PALEOboxes.DomainType
Domain

A model region containing Variables and Reactions that act on them.

Domain spatial size is defined by grid, which may be nothing to define a scalar Domain, or an AbstractMesh to define a spatially-resolved Domain with multiple cells.

Named data_dims may be set by set_data_dimension! to allow Variables with additional non-spatial dimensions, eg to represent quantities on a wavelength grid.

source

Grids

PALEOboxes.internal_sizeFunction
internal_size(::Type{<:AbstractSpace}, mesh::AbstractMesh; [subdomain=""] [space=:cell]) -> NTuple{ndims, Int}

Array size to use for model Variables.

All AbstractMesh concrete subtypes (UnstructuredVectorGrid, CartesianLinearGrid, ...) should implement this method.

Optional Keyword Arguments

  • subdomain::String="": a named subdomain
source
PALEOboxes.cartesian_sizeFunction
cartesian_size(mesh::AbstractMesh) -> NTuple{ndims, Int}

Optional (only regular Cartesian grids should implement this method): Array size of Cartesian Domain.

NB: this may be different from internal_size if the mesh implements a mapping eg to a Vector for internal model Variables.

source
PALEOboxes.Grids.set_subdomain!Function
set_subdomain!(grid::PB.AbstractMesh, subdomainname::AbstractString, subdom::PB.AbstractSubdomain, allowcreate::Bool=false)

Set Subdomain

source
PALEOboxes.Grids.UnstructuredColumnGridType
UnstructuredColumnGrid <: PB.AbstractMesh

Minimal Grid for a Vector Domain composed of columns (not necessarily forming a 2-D array).

Fields

  • ncells::Int total number of cells in this Domain
  • Icolumns::Vector{Vector{Int}}: Icolumns[n] should be the indices of column n, in order from surface to floor, where n is also the index of

any associated boundary surface.

  • z_coords::Vector{FixedCoord}: z coordinates of cell mid point, lower surface, upper surface
  • columnnames::Vector{Symbol}: optional column names
source
PALEOboxes.Grids.CartesianLinearGridType
CartesianLinearGrid <: PB.AbstractMesh

nD grid with netcdf CF1.0 coordinates, using Vectors for PALEO internal representation of Variables, with a mapping linear indices <–> some subset of grid indices.

The linear indices mapping should be set with set_linear_index. Conversion of Field values between the PALEO internal representation (a Vector with a linear index) and a Cartesian Array with multiple dimensions (for import and export of model output) is then implemented by cartesian_to_internal and internal_to_cartesian.

Fields

  • ncells::Int64: number of cells in Domain = length(linear_index) (may be subset of total points in prod(dims))
  • dimnames::Vector{String}: names of dimensions (ordered list)
  • dims::Vector{Int}: sizes of dimensions (ordered list)
  • coords::Vector{Vector{Float64}}: attached cell-centre coordinates for each dimension (ordered list)
  • coords_edges::Vector{Vector{Float64}}: attached cell-edge coordinates for each dimension (ordered list)
source
PALEOboxes.Grids.CartesianArrayGridType
CartesianArrayGrid <: PB.AbstractMesh

nD grid with netcdf CF1.0 coordinates, using n-dimensional Arrays for PALEO internal representation of Variables

Fields

  • ncells::Int64: number of cells in Domain = length(linear_index) (may be subset of total points in prod(dims))
  • dimnames::Vector{String}: names of dimensions (ordered list)
  • dims::Vector{Int}: sizes of dimensions (ordered list)
  • coords::Vector{Vector{Float64}}: attached cell-centre coordinates for each dimension (ordered list)
  • coords_edges::Vector{Vector{Float64}}: attached cell-edge coordinates for each dimension (ordered list)
source

Subdomains

PALEOboxes.Grids.BoundarySubdomainType
BoundarySubdomain <: PB.AbstractSubdomain

A 2D subdomain corresponding to the 2D boundary Domain associated with a 3D interior Domain:

  • indices[ibnd] is the index of the 3D interior cell corresponding to a 2D boundary cell ibnd.
source
PALEOboxes.Grids.InteriorSubdomainType
InteriorSubdomain <: PB.AbstractSubdomain

A 3D subdomain corresponding to the 3D interior Domain associated with a 2D boundary Domain: indices[iint] is either:

  • missing if iint is the index of an interior cell in the 3D Domain, or
  • the index of the 2D boundary Domain cell corresponding to the boundary-adjacent 3D interior Domain cell iint
source
PALEOboxes.Grids.subdomain_viewFunction
subdomain_view(values, subdomain::BoundarySubdomain) -> view

Create a view on values in an interior Domain to access cells corresponding to indices in a boundary Domain.

source
subdomain_view(values, subdomain::InteriorSubdomain) -> var

Return unmodified values from a boundary Domain, indices to access from interior supplied by subdomain_indices

source
subdomain_view(values, subdomain::Nothing) -> values

Fallback when subdomain == nothing

source
PALEOboxes.Grids.subdomain_indicesFunction
subdomain_indices(subdomain::BoundarySubdomain) -> nothing

No additional indices required to access Variables in an interior Domain from a boundary Domain (view created by subdomain_view is sufficient).

source
subdomain_indices(subdomain::InteriorSubdomain) -> indices

Return indices to access Variables in a boundary Domain from interior Domain (will have missing entries where interior cells do not correspond to boundary)

source
subdomain_indices(subdomain::Nothing) -> nothing

fallback when subdomain == nothing

source

Regions, Dimensions and Coordinates

PALEOboxes.Grids.get_regionFunction
get_region(grid::Union{PB.AbstractMesh, Nothing}, values; selectargs...) -> values_subset, (dim_subset::NamedDimension, ...)

Return the subset of values given by selectargs (Grid-specific keywords eg cell=, column=, ...) and corresponding dimensions (with attached coordinates).

source
get_region(grid::Nothing, values) -> values[]

Fallback for Domain with no grid, assumed 1 cell

source
get_region(grid::UnstructuredVectorGrid, values; cell) -> 
+    values_subset, (dim_subset::NamedDimension, ...)

Keywords for region selection:

  • cell::Union{Int, Symbol}: an Int, or a Symbol to look up in cellnames
source
get_region(grid::UnstructuredColumnGrid, values; column, [cell=nothing]) -> 
+    values_subset, (dim_subset::NamedDimension, ...)

Keywords for region selection:

  • column::Union{Int, Symbol}: (may be an Int, or a Symbol to look up in columnames)
  • cell::Int: optional cell index within column, highest cell is cell 1
source
get_region(grid::Union{CartesianLinearGrid{2}, CartesianArrayGrid{2}} , internalvalues; [i=i_idx], [j=j_idx]) ->
+    arrayvalues_subset, (dim_subset::NamedDimension, ...)

Keywords for region selection:

  • i::Int: optional, slice along first dimension
  • j::Int: optional, slice along second dimension

internalvalues are transformed if needed from internal Field representation as a Vector length ncells, to an Array (2D if neither i, j arguments present, 1D if i or j present, 0D ie one cell if both present)

source
get_region(grid::Union{CartesianLinearGrid{3}, CartesianArrayGrid{3}}, internalvalues; [i=i_idx], [j=j_idx]) ->
+    arrayvalues_subset, (dim_subset::NamedDimension, ...)

Keywords for region selection:

  • i::Int: optional, slice along first dimension
  • j::Int: optional, slice along second dimension
  • k::Int: optional, slice along third dimension

internalvalues are transformed if needed from internal Field representation as a Vector length ncells, to an Array (3D if neither i, j, k arguments present, 2D if one of i, j or k present, 1D if two present, 0D ie one cell if i, j, k all specified).

source

Grids may define name dimensions and attach coordinates for the convenience of output visualisation. Any coordinate information required by Reactions should be supplied as Variables.

PALEOboxes.NamedDimensionType
NamedDimension

A named dimension, with optional attached fixed coordinates coords

PALEO convention is that where possible coords contains three elements, for cell midpoints, lower edges, upper edges, in that order.

source

Variables

PALEO Variables exist in Domains and represent biogeochemical or other quantities. They are defined by Reactions as VariableReactions which are then linked to create VariableDomains, and contain Fields which represent data (a subtype of AbstractData) in a function space (a subtype of AbstractSpace) with dimensions defined by the Domain grid (a subtype of AbstractMesh)

Dataflow dependency between Variables is represented by two pairings:

PALEOboxes.VariableTypeType
@enum VariableType

Enumeration of VariableBase subtypes. Allowed values:

  • VariableReaction: VT_ReactProperty, VT_ReactDependency, VT_ReactContributor, VT_ReactTarget
  • VariableDomain : VT_DomPropDep, VT_DomContribTarget
source
PALEOboxes.VariableDomContribTargetType
VariableDomContribTarget <: VariableDomain

Model (Domain) VariableDomain linking a single VariableReaction{VT_ReactTarget} to multiple VariableReaction{VT_ReactContributor} and VariableReaction{VT_ReactDependency}.

source

Variable Attributes

PALEOboxes.AttributeType
Attribute{T}

Definition for Variable attribute name. Defines a data type T, a default_value, required (true if always present ie added with default_value when Variable is created), units, and an optional description.

Note that Variable attributes are stored as a per-Variable Dict(name => value), these definitions are only used to provide defaults, check types, and provide descriptive metadata.

ParseFromString should usually be Nothing: a value of Type T is then required when calling set_attribute!. If ParseFromString is true, then set_attribute! will accept an AbstractString and call Base.parse(T, strvalue) to convert to T. This allows eg an enum-valued Attribute to be defined by Attribute{EnumType, true} and implementing parse(EnumType, rawvalue::AbstractString)

source
PALEOboxes.StandardAttributesConstant
StandardAttributes

List of standard Variable attributes.

Some of these follow netCDF COARDS/CF conventions:

COARDS:https://ferret.pmel.noaa.gov/Ferret/documentation/coards-netcdf-conventions

CF conventions: https://cfconventions.org/cf-conventions/cf-conventions.html#_description_of_the_data

source
32×5 DataFrame
  name                       default_value  required  units      description
  Symbol                     Any            Bool      String     String
 ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
@@ -38,26 +38,26 @@
  standard_name                                false             netcdf CF conventions standard name
  totalnames                 String[]          false             Vector of total Variable names for this species
  vertical_movement          0.0               false  m d-1      vertical advective transport (+ve upwards) in column
- vphase                     VP_Undefined      false             phase for concentrations in multiphase cells
PALEOboxes.VariableFunctionType
@enum VariableFunction

Allowed values of :vfunction Variable Attribute, defining the Variable function to the host ODE or DAE solver.

Explicit ODE problems with dS/dt = F(S) consist of pairs of S::VFStateExplicit, F::VFDeriv Variables.

An implicit ODE problem with dU/dt = F(U) where Total variables U are functions U(S) of State variables S will consist of pairs of U::VFTotal and F::VFDeriv Variables, and also the same number of S::VF_StateTotal (in no particular order).

Algebraic constraints C(S) = 0 include variables C::VFConstraint and the same number of S::VFState, with no corresponding VF_Deriv.

Not all solvers support all combinations.

source

TODO standard Variable names.

Use NetCDF CF standard names https://cfconventions.org/Data/cf-standard-names/76/build/cf-standard-name-table.html ?

Fields

Field, data and function space are defined by Variable Attributes in combination with an AbstractMesh

Examples:

PALEOboxes.FieldType
Field{D <: AbstractData, S <: AbstractSpace, V, N, M}

A Field of values::V of data type D defined on function space S over mesh::M and (optionally) with N data_dims::NTuple{N, NamedDimensions}.

source

Spaces

PALEOboxes.CellSpaceType
CellSpace <: AbstractSpace

A per-cell quantity. Use as Variable attribute :space to create a Variable with data array dimensions from Grid cells.

source
PALEOboxes.ColumnSpaceType
ColumnSpace <: AbstractSpace

A per-column quantity. Use as Variable attribute :space to create a Variable with data array dimensions from Grid columns.

source

Data types

PALEOboxes.AbstractDataType
AbstractData

Defines a Data type that can be composed with an AbstractSpace to form a Field

Concrete subtypes should implement:

allocate_values, check_values, zero_values!, dof_values, get_values_output

If the subtype needs to provide values for a numerical solver (eg as a state variable), it also needs to implement:

init_values!, copyfieldto!, copytofield!, add_field!, add_field_vec!

If the subtype has a representation as components, it should implement: num_components, get_components

source
PALEOboxes.UndefinedDataType
UndefinedData <: AbstractData

Undefined data type (no methods implemented). Used to indicate that a Variable can link to any data type.

source
PALEOboxes.ArrayScalarDataType
ArrayScalarData <: AbstractData

An Array of Field scalars (eg a intensity on a wavelength grid).

NB: only implements minimal methods sufficient to allow use as a model internal variable, not as a state variable.

source
PALEOboxes.allocate_valuesFunction
allocate_values(
+ vphase                     VP_Undefined      false             phase for concentrations in multiphase cells
PALEOboxes.VariableFunctionType
@enum VariableFunction

Allowed values of :vfunction Variable Attribute, defining the Variable function to the host ODE or DAE solver.

Explicit ODE problems with dS/dt = F(S) consist of pairs of S::VFStateExplicit, F::VFDeriv Variables.

An implicit ODE problem with dU/dt = F(U) where Total variables U are functions U(S) of State variables S will consist of pairs of U::VFTotal and F::VFDeriv Variables, and also the same number of S::VF_StateTotal (in no particular order).

Algebraic constraints C(S) = 0 include variables C::VFConstraint and the same number of S::VFState, with no corresponding VF_Deriv.

Not all solvers support all combinations.

source

TODO standard Variable names.

Use NetCDF CF standard names https://cfconventions.org/Data/cf-standard-names/76/build/cf-standard-name-table.html ?

Fields

Field, data and function space are defined by Variable Attributes in combination with an AbstractMesh

Examples:

PALEOboxes.FieldType
Field{D <: AbstractData, S <: AbstractSpace, V, N, M}

A Field of values::V of data type D defined on function space S over mesh::M and (optionally) with N data_dims::NTuple{N, NamedDimensions}.

source

Spaces

PALEOboxes.CellSpaceType
CellSpace <: AbstractSpace

A per-cell quantity. Use as Variable attribute :space to create a Variable with data array dimensions from Grid cells.

source
PALEOboxes.ColumnSpaceType
ColumnSpace <: AbstractSpace

A per-column quantity. Use as Variable attribute :space to create a Variable with data array dimensions from Grid columns.

source

Data types

PALEOboxes.AbstractDataType
AbstractData

Defines a Data type that can be composed with an AbstractSpace to form a Field

Concrete subtypes should implement:

allocate_values, check_values, zero_values!, dof_values, get_values_output

If the subtype needs to provide values for a numerical solver (eg as a state variable), it also needs to implement:

init_values!, copyfieldto!, copytofield!, add_field!, add_field_vec!

If the subtype has a representation as components, it should implement: num_components, get_components

source
PALEOboxes.UndefinedDataType
UndefinedData <: AbstractData

Undefined data type (no methods implemented). Used to indicate that a Variable can link to any data type.

source
PALEOboxes.ArrayScalarDataType
ArrayScalarData <: AbstractData

An Array of Field scalars (eg a intensity on a wavelength grid).

NB: only implements minimal methods sufficient to allow use as a model internal variable, not as a state variable.

source
PALEOboxes.allocate_valuesFunction
allocate_values(
     field_data::Type{<:AbstractData}, data_dims::Tuple{Vararg{NamedDimension}}, data_type, space::Type{<:AbstractSpace}, spatial_size::Tuple;
     thread_safe::Bool, allocatenans::Bool,
-) -> values

allocate Field.values (eg an Array) for field_data with dimensions defined by spatial_size and data_dims

source
PALEOboxes.check_valuesFunction
check_values(
+) -> values

allocate Field.values (eg an Array) for field_data with dimensions defined by spatial_size and data_dims

source
PALEOboxes.check_valuesFunction
check_values(
     existing_values, 
     field_data::Type{<:AbstractData},
     data_dims::Tuple{Vararg{NamedDimension}}, 
     data_type, 
     space::Type{<:AbstractSpace}, 
     spatial_size::Tuple{Integer, Vararg{Integer}}
-)

Check existing_values is of suitable type, size etc for use as Field.values, throw exception if not.

source
PALEOboxes.zero_values!Function
zero_values!(values, field_data::Type{<:AbstractData}, data_dims::Tuple{Vararg{NamedDimension}}, space::Type{<:AbstractSpace}, cellrange)

Set values over spatial region cellrange to zero at start of main loop

source
PALEOboxes.dof_valuesFunction
dof_values(
+)

Check existing_values is of suitable type, size etc for use as Field.values, throw exception if not.

source
PALEOboxes.zero_values!Function
zero_values!(values, field_data::Type{<:AbstractData}, data_dims::Tuple{Vararg{NamedDimension}}, space::Type{<:AbstractSpace}, cellrange)

Set values over spatial region cellrange to zero at start of main loop

source
PALEOboxes.dof_valuesFunction
dof_values(
     field_data::Type{<:AbstractData}, 
     data_dims::Tuple{Vararg{NamedDimension}}, 
     space::Type{<:AbstractSpace}, 
     mesh, 
     cellrange
-) -> dof::Int

Return degrees-of-freedom for field_data over spatial region cellrange.

source
PALEOboxes.get_values_outputFunction

Optional: sanitize values for storing as model output. Default implementation is usually OK - only implement eg for Atomic types that should be converted to standard types for storage

source

sanitized version of values, suitable for storing as output

source
PALEOboxes.get_values_outputFunction

Optional: sanitize values for storing as model output. Default implementation is usually OK - only implement eg for Atomic types that should be converted to standard types for storage

source

sanitized version of values, suitable for storing as output

source
PALEOboxes.init_values!Function
init_values!(
     values, field_data::Type{<:AbstractData}, data_dims::Tuple{Vararg{NamedDimension}}, space::Type{<:AbstractSpace},
     init_value::Symbol, attribv::VariableBase, convertfn, convertvalues, cellrange, info::NTuple{3, String}
-)

Initialize values at model start to init_value over region cellrange using information from Variable attribv attributes, scaled by convertfn and convertvalues.

Optional: only required if this field_data type is used for a model (state) Variable that requires initialisation.

Arguments:

  • values: data to be zeroed
  • init_value::Symbol: one of :initialvalue, :normvalue, requesting type of initial value required
  • attribv::VariableBase: Variable with attributes to use for initialisation
  • convertfn::Function: apply multiplier convertfn(convertvalues, i) to initialisation value for cell i. Typically this is used to convert units eg concentration to mol.
  • convertvalues: parameters (if any) required by convertfn, eg a volume measure.
  • cellrange: range of cells to initialise
  • info::::NTuple{3, String}: Tuple (varinfo, convertinfo, trsfrinfo) of identifier strings to use for log messages
source
PALEOboxes.copyfieldto!Function
copyfieldto!(
+)

Initialize values at model start to init_value over region cellrange using information from Variable attribv attributes, scaled by convertfn and convertvalues.

Optional: only required if this field_data type is used for a model (state) Variable that requires initialisation.

Arguments:

  • values: data to be zeroed
  • init_value::Symbol: one of :initialvalue, :normvalue, requesting type of initial value required
  • attribv::VariableBase: Variable with attributes to use for initialisation
  • convertfn::Function: apply multiplier convertfn(convertvalues, i) to initialisation value for cell i. Typically this is used to convert units eg concentration to mol.
  • convertvalues: parameters (if any) required by convertfn, eg a volume measure.
  • cellrange: range of cells to initialise
  • info::::NTuple{3, String}: Tuple (varinfo, convertinfo, trsfrinfo) of identifier strings to use for log messages
source
PALEOboxes.copyfieldto!Function
copyfieldto!(
     dest,
     doff, 
     values, 
@@ -65,7 +65,7 @@
     data_dims::Tuple{Vararg{NamedDimension}}, 
     space::Type{<:AbstractSpace}, 
     cellrange
-) -> num_copied::Int

Copy Field.values values from spatial region defined by cellrange, to dest Array starting at index doff.

Number of values over whole Domain should equal degrees-of-freedom returned by dof_values

Required if this field_data type needs to provide values for a numerical solver.

source
PALEOboxes.copytofield!Function
copytofield!(
+) -> num_copied::Int

Copy Field.values values from spatial region defined by cellrange, to dest Array starting at index doff.

Number of values over whole Domain should equal degrees-of-freedom returned by dof_values

Required if this field_data type needs to provide values for a numerical solver.

source
PALEOboxes.copytofield!Function
copytofield!(
     values,
     field_data::Type{<:AbstractData},
     data_dims::Tuple{Vararg{NamedDimension}},
@@ -73,7 +73,7 @@
     cellrange, 
     src, 
     soff
-) -> num_copied::Int

Copy from src Array starting at index soff to Field.values values for spatial region defined by cellrange.

Number of values over whole Domain should equal degrees-of-freedom returned by dof_values

Required if this field_data type needs to provide values for a numerical solver.

source
PALEOboxes.add_field_vec!Function
add_field_vec!(
+) -> num_copied::Int

Copy from src Array starting at index soff to Field.values values for spatial region defined by cellrange.

Number of values over whole Domain should equal degrees-of-freedom returned by dof_values

Required if this field_data type needs to provide values for a numerical solver.

source
PALEOboxes.add_field_vec!Function
add_field_vec!(
     dest, 
     field_data::Type{<:AbstractData}, 
     data_dims::Tuple{Vararg{NamedDimension}}, 
@@ -82,7 +82,7 @@
     cellrange,
     src, 
     soff
-) -> num_added::Int

Implement dest += a*src where dest is a Field.values, src is an Array, a is a number, over region defined by cellrange, starting at index soff in src.

Returns number of elements of src used.

See copytofield!, copyfieldto! for the relationship between Array src and Field values dest.

source
PALEOboxes.num_componentsMethod
num_components(field_data::Type{<:AbstractData}) -> Int

get number of components (optional - implement if field_data has a representation as components)

source
PALEOboxes.get_componentsFunction
get_components(values, field_data::Type{<:AbstractData}) -> Vector

Convert Field values to a Vector of components (optional - implement if field_data has a representation as components)

source

Isotopes

PALEOboxes.AbstractIsotopeScalarType
AbstractIsotopeScalar <: AbstractData

An IsotopeScalar represents a quantity or flux with isotopic composition. Can be added, subtracted, multiplied by a scalar, and decomposed into components with the same (bulk) transport properties.

Implementation

Each IsotopeScalar should be added to IsotopeTypes, and implement:

  • get_total(is::IsotopeScalar) -> total
  • arithmetic operations +/- (ie IsotopeScalars can be added and subtracted) and *number, /number (IsotopeScalars can be scaled by a real number).
  • methods of the AbstractData interface

and optional isotope-specific functions, eg for a single isotope:

  • isotope_totaldelta(::Type{<: IsotopeScalar}, total, delta) -> IsotopeScalar()
  • get_delta(is::IsotopeScalar) -> delta
source
PALEOboxes.IsotopeLinearType
IsotopeLinear <: AbstractIsotopeScalar

Linearized representation of isotopic composition, where moldelta = total * delta.

source
PALEOboxes.isotope_totaldeltaFunction
isotope_totaldelta(::Type{IsotopeLinear}, total, delta) -> IsotopeLinear

Create an IsotopeLinear from total and delta

Examples:

julia> a = PB.isotope_totaldelta(PB.IsotopeLinear, 10.0, -2.0)
+) -> num_added::Int

Implement dest += a*src where dest is a Field.values, src is an Array, a is a number, over region defined by cellrange, starting at index soff in src.

Returns number of elements of src used.

See copytofield!, copyfieldto! for the relationship between Array src and Field values dest.

source
PALEOboxes.num_componentsMethod
num_components(field_data::Type{<:AbstractData}) -> Int

get number of components (optional - implement if field_data has a representation as components)

source
PALEOboxes.get_componentsFunction
get_components(values, field_data::Type{<:AbstractData}) -> Vector

Convert Field values to a Vector of components (optional - implement if field_data has a representation as components)

source

Isotopes

PALEOboxes.AbstractIsotopeScalarType
AbstractIsotopeScalar <: AbstractData

An IsotopeScalar represents a quantity or flux with isotopic composition. Can be added, subtracted, multiplied by a scalar, and decomposed into components with the same (bulk) transport properties.

Implementation

Each IsotopeScalar should be added to IsotopeTypes, and implement:

  • get_total(is::IsotopeScalar) -> total
  • arithmetic operations +/- (ie IsotopeScalars can be added and subtracted) and *number, /number (IsotopeScalars can be scaled by a real number).
  • methods of the AbstractData interface

and optional isotope-specific functions, eg for a single isotope:

  • isotope_totaldelta(::Type{<: IsotopeScalar}, total, delta) -> IsotopeScalar()
  • get_delta(is::IsotopeScalar) -> delta
source
PALEOboxes.IsotopeLinearType
IsotopeLinear <: AbstractIsotopeScalar

Linearized representation of isotopic composition, where moldelta = total * delta.

source
PALEOboxes.isotope_totaldeltaFunction
isotope_totaldelta(::Type{IsotopeLinear}, total, delta) -> IsotopeLinear

Create an IsotopeLinear from total and delta

Examples:

julia> a = PB.isotope_totaldelta(PB.IsotopeLinear, 10.0, -2.0)
 (v=10.0, v_moldelta=-20.0, ‰=-2.0)
 
 julia> b = a*2
@@ -95,4 +95,4 @@
 30.0
 
 julia> PB.get_delta(c)
--2.0
source
+-2.0
source
PALEOboxes.get_totalFunction

generic get_total for non-isotope variable

source
get_total(is::IsotopeLinear)

Get isotope total

source
PALEOboxes.get_deltaFunction
get_delta(is::IsotopeLinear)

Get isotope delta (per mil)

source
diff --git a/dev/Reaction API/index.html b/dev/Reaction API/index.html index a4918e0..bca28b0 100644 --- a/dev/Reaction API/index.html +++ b/dev/Reaction API/index.html @@ -8,11 +8,11 @@ ) some_additional_field::Float64 # additional fields to eg cache data read from disk etc -end

Derived types should implement register_methods!, and may optionally implement create_reaction, set_model_geometry, check_configuration, register_dynamic_methods!.

Methods should be registered using add_method_setup!, add_method_initialize!, add_method_do!.

Any parameters not included in pars should be added explicitly with add_par (this is rarely needed).

source
PALEOboxes.ReactionBaseType
ReactionBase

Base Type for a biogeochemical Reaction.

Implementation

Include as field base in types derived from AbstractReaction

source

Parameters

PALEOboxes.AbstractParameterType
AbstractParameter

Base Type for Parameters

See also: Parameter, VecParameter, VecVecParameter

source
PALEOboxes.ParameterType
Parameter{T, ParseFromString}

A reaction parameter of type T.

Create using short names ParDouble, ParInt, ParBool, ParString.

Read value as <par>[], set with setvalue!.

Parameters with external=true may be set from the Model-level Parameters list, if name is present in that list.

ParseFromString should usually be Nothing: a value of Type T is then required when calling setvalue!. If ParseFromString is not Nothing, then setvalue! will accept an AbstractString and call Base.parse(ParseFromString, strvalue). This allows eg an enum-valued Parameter to be defined by Parameter{EnumType, EnumType} and implementing parse(EnumType, rawvalue::AbstractString)

source
PALEOboxes.VecParameterType
VecParameter{T, ParseFromString}

A reaction parameter of type Vector{T}.

Create using short names ParDoubleVec, ParStringVec.

Read values as <par>[i], access raw Vector{T} as <par>.v.

Set with setvalue!, in config file use standard yaml syntax for a vector eg [1, 2, 3]

See Parameter for additional documentation.

Implementation

Implements part of the AbstractVector interface, sufficient to access elements as <par>[i], and to support iteration eg for v in <par>; ...; end.

source
PALEOboxes.VecVecParameterType
VecVecParameter{T, ParseFromString}

A reaction parameter of type Vector{Vector{T}}.

Create using short names ParDoubleVecVec.

Read values as <par>.v::Vector{Vector{T}}.

Set using standard yaml syntax for a vector of vectors eg [[1, 2, 3], [4, 5, 6]]

See Parameter for additional documentation.

source
PALEOboxes.ParametersTupleFunction
ParametersTuple(parameters::AbstractParameter...) -> NamedTuple
-ParametersTuple(parameters) -> NamedTuple

Create a NamedTuple of Parameters.

source
PALEOboxes.add_parFunction
add_par(reaction::AbstractReaction, par::AbstractParameter)
-add_par(reaction::AbstractReaction, objectwithpars)

Add a single parameter or parameters from fields of objectwithpars to a new Reaction.

Not usually needed: Parameters in pars::ParametersTuplewill be added automatically, only needed if there are additional Parameters that are not members ofpars`.

source
PALEOboxes.setvalue!Function
setvalue!(par::Parameter, value)

Set Parameter to value.

Optionally (if Parameter has Type parameter ParseFromString != Nothing) parse value from a String.

source

Registering Reactions with the PALEOboxes framework

All subtypes of AbstractReaction that are present in loaded modules are available to the PALEO framework. Available Reactions can be listed with find_reaction and find_all_reactions. The default create_reaction is called to create Reactions when the model is created (this method can be overridden if needed).

PALEOboxes.create_reactionMethod
create_reaction(ReactionType::Type{<:AbstractReaction}, base::ReactionBase) -> reaction::AbstractReaction

Default method to create a ReactionType and set base field.

A reaction implementation may optionally implement a custom method eg to set additional fields

source
PALEOboxes.find_reactionFunction
find_reaction(class::AbstractString) -> ReactionType

Look up "class" in list of Reactions available in currently loaded modules (using find_all_reactions), and return fully-qualified Reaction Type (including module prefixes).

source
PALEOboxes.find_all_reactionsFunction
find_all_reactions() -> Dict{String, Type}

Use InteractiveUtils.subtypes(AbstractReaction) to find all currently loaded subtypes off AbstractReaction, and create a Dict with last part of the name of the Type as key (ie without the module prefix) and Type as value.

Any Types that generate non-unique keys (eg Module1.MyReactionType and Module2.MyReactionType) will generate a warning, and no entry will be added to the Dict (so if this Reaction is present in a config file, it will not be found and will error).

source

Defining Domain Grids and array sizes

PALEOboxes.set_model_geometryFunction
set_model_geometry(reaction, model)

Optional: define Domain grid, data_dims.

One Reaction per Domain may create a grid (an AbstractMesh subtype) and set the domain.grid field.

Multiple Reactions per domain may call set_data_dimension! to define (different) named data dimensions (eg wavelength grids).

source
PALEOboxes.set_data_dimension!Function
set_data_dimension!(domain::Domain, dim::NamedDimension; allow_exists=false)

Define a Domain data dimension as a NamedDimension

Variables may then specify data dimensions as a list of names using the :data_dims Variable Attribute.

source

Creating and registering Reaction methods

All Reactions should implement register_methods!, and may optionally implement register_dynamic_methods!.

PALEOboxes.register_methods!Function
register_methods!(reaction)
-register_methods!(reaction, model)

Add ReactionMethods, using add_method_setup!, add_method_initialize! add_method_do!. See also register_dynamic_methods!.

source
PALEOboxes.register_dynamic_methods!Function
register_dynamic_methods!(reaction)
-register_dynamic_methods!(reaction, model)

Optional: called after first variable link pass, to add ReactionMethods that depend on Variables generated by other Reactions (see register_methods!).

source

These methods should then define one or more ReactionMethods, which requires:

In addition it is possible to add Predefined ReactionMethods for some common operations (Variable initialisation, calculating totals, etc).

Defining VariableReactions

PALEOboxes.VariableReactionType
VariableReaction(VT, localname => link_namestr, units, description; attributes=Tuple()) -> VariableReaction{VT}
+end

Derived types should implement register_methods!, and may optionally implement create_reaction, set_model_geometry, check_configuration, register_dynamic_methods!.

Methods should be registered using add_method_setup!, add_method_initialize!, add_method_do!.

Any parameters not included in pars should be added explicitly with add_par (this is rarely needed).

source
PALEOboxes.ReactionBaseType
ReactionBase

Base Type for a biogeochemical Reaction.

Implementation

Include as field base in types derived from AbstractReaction

source

Parameters

PALEOboxes.AbstractParameterType
AbstractParameter

Base Type for Parameters

See also: Parameter, VecParameter, VecVecParameter

source
PALEOboxes.ParameterType
Parameter{T, ParseFromString}

A reaction parameter of type T.

Create using short names ParDouble, ParInt, ParBool, ParString.

Read value as <par>[], set with setvalue!.

Parameters with external=true may be set from the Model-level Parameters list, if name is present in that list.

ParseFromString should usually be Nothing: a value of Type T is then required when calling setvalue!. If ParseFromString is not Nothing, then setvalue! will accept an AbstractString and call Base.parse(ParseFromString, strvalue). This allows eg an enum-valued Parameter to be defined by Parameter{EnumType, EnumType} and implementing parse(EnumType, rawvalue::AbstractString)

source
PALEOboxes.VecParameterType
VecParameter{T, ParseFromString}

A reaction parameter of type Vector{T}.

Create using short names ParDoubleVec, ParStringVec.

Read values as <par>[i], access raw Vector{T} as <par>.v.

Set with setvalue!, in config file use standard yaml syntax for a vector eg [1, 2, 3]

See Parameter for additional documentation.

Implementation

Implements part of the AbstractVector interface, sufficient to access elements as <par>[i], and to support iteration eg for v in <par>; ...; end.

source
PALEOboxes.VecVecParameterType
VecVecParameter{T, ParseFromString}

A reaction parameter of type Vector{Vector{T}}.

Create using short names ParDoubleVecVec.

Read values as <par>.v::Vector{Vector{T}}.

Set using standard yaml syntax for a vector of vectors eg [[1, 2, 3], [4, 5, 6]]

See Parameter for additional documentation.

source
PALEOboxes.ParametersTupleFunction
ParametersTuple(parameters::AbstractParameter...) -> NamedTuple
+ParametersTuple(parameters) -> NamedTuple

Create a NamedTuple of Parameters.

source
PALEOboxes.add_parFunction
add_par(reaction::AbstractReaction, par::AbstractParameter)
+add_par(reaction::AbstractReaction, objectwithpars)

Add a single parameter or parameters from fields of objectwithpars to a new Reaction.

Not usually needed: Parameters in pars::ParametersTuplewill be added automatically, only needed if there are additional Parameters that are not members ofpars`.

source
PALEOboxes.setvalue!Function
setvalue!(par::Parameter, value)

Set Parameter to value.

Optionally (if Parameter has Type parameter ParseFromString != Nothing) parse value from a String.

source

Registering Reactions with the PALEOboxes framework

All subtypes of AbstractReaction that are present in loaded modules are available to the PALEO framework. Available Reactions can be listed with find_reaction and find_all_reactions. The default create_reaction is called to create Reactions when the model is created (this method can be overridden if needed).

PALEOboxes.create_reactionMethod
create_reaction(ReactionType::Type{<:AbstractReaction}, base::ReactionBase) -> reaction::AbstractReaction

Default method to create a ReactionType and set base field.

A reaction implementation may optionally implement a custom method eg to set additional fields

source
PALEOboxes.find_reactionFunction
find_reaction(class::AbstractString) -> ReactionType

Look up "class" in list of Reactions available in currently loaded modules (using find_all_reactions), and return fully-qualified Reaction Type (including module prefixes).

source
PALEOboxes.find_all_reactionsFunction
find_all_reactions() -> Dict{String, Type}

Use InteractiveUtils.subtypes(AbstractReaction) to find all currently loaded subtypes off AbstractReaction, and create a Dict with last part of the name of the Type as key (ie without the module prefix) and Type as value.

Any Types that generate non-unique keys (eg Module1.MyReactionType and Module2.MyReactionType) will generate a warning, and no entry will be added to the Dict (so if this Reaction is present in a config file, it will not be found and will error).

source

Defining Domain Grids and array sizes

PALEOboxes.set_model_geometryFunction
set_model_geometry(reaction, model)

Optional: define Domain grid, data_dims.

One Reaction per Domain may create a grid (an AbstractMesh subtype) and set the domain.grid field.

Multiple Reactions per domain may call set_data_dimension! to define (different) named data dimensions (eg wavelength grids).

source
PALEOboxes.set_data_dimension!Function
set_data_dimension!(domain::Domain, dim::NamedDimension; allow_exists=false)

Define a Domain data dimension as a NamedDimension

Variables may then specify data dimensions as a list of names using the :data_dims Variable Attribute.

source

Creating and registering Reaction methods

All Reactions should implement register_methods!, and may optionally implement register_dynamic_methods!.

PALEOboxes.register_methods!Function
register_methods!(reaction)
+register_methods!(reaction, model)

Add ReactionMethods, using add_method_setup!, add_method_initialize! add_method_do!. See also register_dynamic_methods!.

source
PALEOboxes.register_dynamic_methods!Function
register_dynamic_methods!(reaction)
+register_dynamic_methods!(reaction, model)

Optional: called after first variable link pass, to add ReactionMethods that depend on Variables generated by other Reactions (see register_methods!).

source

These methods should then define one or more ReactionMethods, which requires:

In addition it is possible to add Predefined ReactionMethods for some common operations (Variable initialisation, calculating totals, etc).

Defining VariableReactions

PALEOboxes.VariableReactionType
VariableReaction(VT, localname => link_namestr, units, description; attributes=Tuple()) -> VariableReaction{VT}
 VariableReaction(VT, linklocal_namestr, units, description; attributes=Tuple()) -> VariableReaction{VT}    
 
 VarProp, VarPropScalar, VarPropStateIndep, VarPropScalarStateIndep -> VariableReaction{VT_ReactProperty}
@@ -27,7 +27,7 @@
 [deprecated] VariableReaction(VT, localname, units, description; link_namestr, attributes=Tuple()) -> VariableReaction{VT}

Reaction view on a model variable.

Reactions define AbstractVarLists of VariableReactions when creating a ReactionMethod. Within a ReactionMethod, a VariableReaction is referred to by localname. When the model is initialised, VariableDomain variables are created that link together VariableReactions with the same link_namestr, and data Arrays are allocated. views on the VariableDomain data Arrays are then passed to the ReactionMethod function at each timestep.

Subtypes

The Type parameter VT is one of VT_ReactProperty, VT_ReactDependency, VT_ReactContributor, VT_ReactTarget, where short names are defined for convenience:

const VarPropT        = VariableReaction{VT_ReactProperty}
 const VarDepT         = VariableReaction{VT_ReactDependency}
 const VarTargetT      = VariableReaction{VT_ReactTarget}
-const VarContribT     = VariableReaction{VT_ReactContributor}

There are two pairings of VariableReactions with VariableDomains:

  • Reaction Property and Dependency Variables, linked to a VariableDomPropDep. These are used to represent a quantity calculated in one Reaction that is then used by other Reactions.
  • Reaction Target and Contributor Variables, linked to a VariableDomContribTarget. These are used to represent a flux-like quantity, with one Reaction definining the Target and multiple Reactions adding contributions.

Variable Attributes and constructor convenience functions

Variable attributes are used to define Variable :space AbstractSpace (scalar, per-cell, etc) and data content :field_data AbstractData, and to label state Variables for use by numerical solvers.

VariableReaction is usually not called directly, instead convenience functions are defined that provide commonly-used combinations of VT and attributes:

short nameVTattributes
:space:field_data:vfunction:initialize_to_zero:datatype:is_constant
VarPropVT_ReactPropertyCellSpaceScalarDataVF_Undefined--false
VarPropScalarVT_ReactPropertyScalarSpaceScalarDataVF_Undefined--false
VarPropStateIndepVT_ReactPropertyCellSpaceScalarDataVF_Undefined-Float64true
VarPropScalarStateIndepVT_ReactPropertyScalarSpaceScalarDataVF_Undefined-Float64true
VarDepVT_ReactDependencyCellSpaceUndefinedDataVF_Undefined--false
VarDepColumnVT_ReactDependencyColumnSpaceUndefinedDataVF_Undefined--false
VarDepScalarVT_ReactDependencyScalarSpaceUndefinedDataVF_Undefined--false
VarDepStateIndepVT_ReactDependencyCellSpaceUndefinedDataVF_Undefined-Float64true
VarDepColumnStateIndepVT_ReactDependencyColumnSpaceUndefinedDataVF_Undefined-Float64true
VarDepScalarStateIndepVT_ReactDependencyScalarSpaceUndefinedDataVF_Undefined-Float64true
VarTargetVT_ReactTargetCellSpaceScalarDataVF_Undefinedtrue-false
VarTargetScalarVT_ReactTargetScalarSpaceScalarDataVF_Undefinedtrue-false
VarContribVT_ReactContributorCellSpaceUndefinedDataVF_Undefined--false
VarContribColumnVT_ReactContributorColumnSpaceUndefinedDataVF_Undefined--false
VarContribScalarVT_ReactContributorScalarSpaceUndefinedDataVF_Undefined--false
VarStateExplicitVT_ReactDependencyCellSpaceScalarDataVF_StateExplicit--false
VarStateExplicitScalarVT_ReactDependencyScalarSpaceScalarDataVF_StateExplicit--false
VarDerivVT_ReactContributorCellSpaceScalarDataVF_Derivtrue-false
VarDerivScalarVT_ReactContributorScalarSpaceScalarDataVF_Derivtrue-false
VarStateVT_ReactDependencyCellSpaceScalarDataVF_State--false
VarStateScalarVT_ReactDependencyScalarSpaceScalarDataVF_State--false
VarConstraintVT_ReactContributorCellSpaceScalarDataVF_Constrainttrue-false
VarConstraintScalarVT_ReactContributorScalarSpaceScalarDataVF_Constrainttrue-false

This illustrates some general principles for the use of attributes:

  • All Variables must define the :space VariableAttribute (a subtype of AbstractSpace) to specify whether they are Domain scalars, per-cell quantities, etc. This is used to define array dimensions, and to check that dimensions match when variables are linked.
  • The :field_data attribute (a subtype of AbstractData) specifies the quantity that Property and Target Variables represent. This defaults to ScalarData to represent a scalar value. To eg represent a single isotope the :field_data attribute should be set to IsotopeLinear. Dependency and Contributor Variables with :field_data = UndefinedData then acquire this value when they are linked, or may specify :field_data to constrain allowed links.
  • The :initialize_to_zero attribute is set for Target variables, this is than used (by the ReactionMethod created by add_method_initialize_zero_vars_default!) to identify variables that should be initialised to zero at the start of each timestep.
  • The :vfunction attribute is used to label state Variables and corresponding time derivatives, for access by a numerical solver.
    • An ODE-like combination of a state variable and time derivative are defined by a paired VarStateExplicit and VarDeriv. Note that that these are just VarDep and VarContrib with the :vfunction attribute set, and that there is no VarProp and VarTarget defined in the model (these are effectively provided by the numerical solver). The pairing is defined by the naming convention of varname and varname_sms.
    • An algebraic constraint (for a DAE) is defined by a VarState and VarConstraint. Note that that these are just VarDep and VarContrib with the :vfunction attribute set, and that there is no VarProp and VarTarget defined in the model (these are effectively provided by the numerical solver). These variables are not paired.
    • The :initializetozero attribute is also set for Contributor variables VarDeriv and VarConstraint (as there is no corresponding Target variable in the model).
    • The :field_data attribute should be set on labelled state etc Variables (as there are no corresponding Property or Target variables in the model to define this).
  • The :is_constant attribute is used to identify constant Property Variables (not modified after initialisation). A Dependency Variable with :is_constant = true can only link to a constant Property Variable.
  • The :datatype attribute is used both to provide a concrete datatype for constant Variables, and to exclude a non-constant Variable from automatic differentiation (TODO document that usage).

Additional attributes can be specified to provide model-specific information, with defaults defined in the Reaction .jl code that can often then be overridden in the .yaml configuration file, see StandardAttributes. Examples include:

  • :initial_value, :norm_value, :initial_delta for state variables or constant variables. NB: the Reaction creating these variables is responsible for implementing a setup method to read the attributes and set the variable data array appropriately at model initialisation.
  • An :advect attribute is used to label tracer variables to indicate that they should have advective transport applied by a transport Reaction included in the model.

NB: after Variables are linked to Domain Variables, the attributes used are those from the master Variable (either a Property or Target variable, or a labelled state variable Dependency or Contributor with no corresponding Property or Target). Additional attributes must therefore be set on this master Variable.

Specifying links

localname identifies the VariableReaction within the Reaction, and can be used to set variable_attributes: and variable_links: in the .yaml configuration file.

linkreq_domain.linkreq_subdomain.linkreq_name defines the Domain, Subdomain and name for run-time linking to VariableDomain variables.

Arguments

  • VT::VariableType: one of VT_ReactProperty, VT_ReactDependency, VT_ReactContributor, VT_ReactTarget
  • localname::AbstractString: Reaction-local Variable name
  • link_namestr::AbstractString: <linkreq_domain>.[linkreq_subdomain.]linkreq_name. Parsed by parse_variablereaction_namestr to define the requested linking to Domain Variable.
  • linklocal_namestr::AbstractString: <linkreq_domain>.[linkreq_subdomain.]localname. Convenience form to define both localname and requested linking to Domain Variable, for the common case where linkreq_name == localname.
  • units::AbstractString: units ("" if not applicable)
  • description::AbstractString: text describing the variable

Keywords

source
PALEOboxes.parse_variablereaction_namestrFunction
parse_variablereaction_namestr(linkstr) 
+const VarContribT     = VariableReaction{VT_ReactContributor}

There are two pairings of VariableReactions with VariableDomains:

  • Reaction Property and Dependency Variables, linked to a VariableDomPropDep. These are used to represent a quantity calculated in one Reaction that is then used by other Reactions.
  • Reaction Target and Contributor Variables, linked to a VariableDomContribTarget. These are used to represent a flux-like quantity, with one Reaction definining the Target and multiple Reactions adding contributions.

Variable Attributes and constructor convenience functions

Variable attributes are used to define Variable :space AbstractSpace (scalar, per-cell, etc) and data content :field_data AbstractData, and to label state Variables for use by numerical solvers.

VariableReaction is usually not called directly, instead convenience functions are defined that provide commonly-used combinations of VT and attributes:

short nameVTattributes
:space:field_data:vfunction:initialize_to_zero:datatype:is_constant
VarPropVT_ReactPropertyCellSpaceScalarDataVF_Undefined--false
VarPropScalarVT_ReactPropertyScalarSpaceScalarDataVF_Undefined--false
VarPropStateIndepVT_ReactPropertyCellSpaceScalarDataVF_Undefined-Float64true
VarPropScalarStateIndepVT_ReactPropertyScalarSpaceScalarDataVF_Undefined-Float64true
VarDepVT_ReactDependencyCellSpaceUndefinedDataVF_Undefined--false
VarDepColumnVT_ReactDependencyColumnSpaceUndefinedDataVF_Undefined--false
VarDepScalarVT_ReactDependencyScalarSpaceUndefinedDataVF_Undefined--false
VarDepStateIndepVT_ReactDependencyCellSpaceUndefinedDataVF_Undefined-Float64true
VarDepColumnStateIndepVT_ReactDependencyColumnSpaceUndefinedDataVF_Undefined-Float64true
VarDepScalarStateIndepVT_ReactDependencyScalarSpaceUndefinedDataVF_Undefined-Float64true
VarTargetVT_ReactTargetCellSpaceScalarDataVF_Undefinedtrue-false
VarTargetScalarVT_ReactTargetScalarSpaceScalarDataVF_Undefinedtrue-false
VarContribVT_ReactContributorCellSpaceUndefinedDataVF_Undefined--false
VarContribColumnVT_ReactContributorColumnSpaceUndefinedDataVF_Undefined--false
VarContribScalarVT_ReactContributorScalarSpaceUndefinedDataVF_Undefined--false
VarStateExplicitVT_ReactDependencyCellSpaceScalarDataVF_StateExplicit--false
VarStateExplicitScalarVT_ReactDependencyScalarSpaceScalarDataVF_StateExplicit--false
VarDerivVT_ReactContributorCellSpaceScalarDataVF_Derivtrue-false
VarDerivScalarVT_ReactContributorScalarSpaceScalarDataVF_Derivtrue-false
VarStateVT_ReactDependencyCellSpaceScalarDataVF_State--false
VarStateScalarVT_ReactDependencyScalarSpaceScalarDataVF_State--false
VarConstraintVT_ReactContributorCellSpaceScalarDataVF_Constrainttrue-false
VarConstraintScalarVT_ReactContributorScalarSpaceScalarDataVF_Constrainttrue-false

This illustrates some general principles for the use of attributes:

  • All Variables must define the :space VariableAttribute (a subtype of AbstractSpace) to specify whether they are Domain scalars, per-cell quantities, etc. This is used to define array dimensions, and to check that dimensions match when variables are linked.
  • The :field_data attribute (a subtype of AbstractData) specifies the quantity that Property and Target Variables represent. This defaults to ScalarData to represent a scalar value. To eg represent a single isotope the :field_data attribute should be set to IsotopeLinear. Dependency and Contributor Variables with :field_data = UndefinedData then acquire this value when they are linked, or may specify :field_data to constrain allowed links.
  • The :initialize_to_zero attribute is set for Target variables, this is than used (by the ReactionMethod created by add_method_initialize_zero_vars_default!) to identify variables that should be initialised to zero at the start of each timestep.
  • The :vfunction attribute is used to label state Variables and corresponding time derivatives, for access by a numerical solver.
    • An ODE-like combination of a state variable and time derivative are defined by a paired VarStateExplicit and VarDeriv. Note that that these are just VarDep and VarContrib with the :vfunction attribute set, and that there is no VarProp and VarTarget defined in the model (these are effectively provided by the numerical solver). The pairing is defined by the naming convention of varname and varname_sms.
    • An algebraic constraint (for a DAE) is defined by a VarState and VarConstraint. Note that that these are just VarDep and VarContrib with the :vfunction attribute set, and that there is no VarProp and VarTarget defined in the model (these are effectively provided by the numerical solver). These variables are not paired.
    • The :initializetozero attribute is also set for Contributor variables VarDeriv and VarConstraint (as there is no corresponding Target variable in the model).
    • The :field_data attribute should be set on labelled state etc Variables (as there are no corresponding Property or Target variables in the model to define this).
  • The :is_constant attribute is used to identify constant Property Variables (not modified after initialisation). A Dependency Variable with :is_constant = true can only link to a constant Property Variable.
  • The :datatype attribute is used both to provide a concrete datatype for constant Variables, and to exclude a non-constant Variable from automatic differentiation (TODO document that usage).

Additional attributes can be specified to provide model-specific information, with defaults defined in the Reaction .jl code that can often then be overridden in the .yaml configuration file, see StandardAttributes. Examples include:

  • :initial_value, :norm_value, :initial_delta for state variables or constant variables. NB: the Reaction creating these variables is responsible for implementing a setup method to read the attributes and set the variable data array appropriately at model initialisation.
  • An :advect attribute is used to label tracer variables to indicate that they should have advective transport applied by a transport Reaction included in the model.

NB: after Variables are linked to Domain Variables, the attributes used are those from the master Variable (either a Property or Target variable, or a labelled state variable Dependency or Contributor with no corresponding Property or Target). Additional attributes must therefore be set on this master Variable.

Specifying links

localname identifies the VariableReaction within the Reaction, and can be used to set variable_attributes: and variable_links: in the .yaml configuration file.

linkreq_domain.linkreq_subdomain.linkreq_name defines the Domain, Subdomain and name for run-time linking to VariableDomain variables.

Arguments

  • VT::VariableType: one of VT_ReactProperty, VT_ReactDependency, VT_ReactContributor, VT_ReactTarget
  • localname::AbstractString: Reaction-local Variable name
  • link_namestr::AbstractString: <linkreq_domain>.[linkreq_subdomain.]linkreq_name. Parsed by parse_variablereaction_namestr to define the requested linking to Domain Variable.
  • linklocal_namestr::AbstractString: <linkreq_domain>.[linkreq_subdomain.]localname. Convenience form to define both localname and requested linking to Domain Variable, for the common case where linkreq_name == localname.
  • units::AbstractString: units ("" if not applicable)
  • description::AbstractString: text describing the variable

Keywords

source
PALEOboxes.parse_variablereaction_namestrFunction
parse_variablereaction_namestr(linkstr) 
     -> (linkreq_domain, linkreq_subdomain, linkreq_name, link_optional)

Parse a linkstr into component parts.

linkstr is of format: [(][<linkreq_domain>.][<linkreq_subdomain>.]<linkreq_name>[)]

  • Optional brackets ( ... ) set link_optional=true
  • linkreq_name may contain %reaction% which will later be substituted with <Reaction name>/

Examples:

julia> PALEOboxes.parse_variablereaction_namestr("foo")  # Common case eg for a property that should be public
 ("", "", "foo", false)
 
@@ -38,7 +38,7 @@
 ("ocean", "", "foo", false)
 
 julia> PALEOboxes.parse_variablereaction_namestr("(ocean.oceansurface.goo)") # Full syntax
-("ocean", "oceansurface", "goo", true)
source
PALEOboxes.set_attribute!Function
set_attribute!(var::VariableBase, name::Symbol, value, allow_create=false) -> var

Set Variable attribute.

source

Defining collections of VariableReactions

PALEOboxes.AbstractVarListType
AbstractVarList

Variables required by a ReactionMethod methodfn are specified by a Tuple of VarList_xxx <: AbstractVarList, each containing a collection of VariableReaction.

These are then converted (by the create_accessors method) to a corresponding Tuple of collections of views on Domain data arrays , which are then be passed to the ReactionMethod methodfn.

NB: creates and uses a copy of supplied Variables including metadata, so set / modify Variable attributes before creating a VarList.

Implementation

Subtypes of AbstractVarList should implement:

  • a constructor that takes a collection of VariableReactions
  • create_accessors, returning the views on Domain data arrays in a subtype-specific collection.
  • get_variables, returning the collection of VariableReactions (as a flat list).
source
PALEOboxes.VarList_singleType
VarList_single(var; components=false) -> VarList_single

Create a VarList_single describing a single VariableReaction, create_accessors will then return a single accessor.

source
PALEOboxes.VarList_namedtupleType
VarList_namedtuple(varcollection; components=false) -> VarList_namedtuple

Create a VarList_namedtuple describing a collection of VariableReactions, create_accessors will then return a NamedTuple with field names = VariableReaction.localname and field values = corresponding data arrays.

If components = true, each NamedTuple field will be a Vector of data array components.

source
PALEOboxes.VarList_tupleType
VarList_tuple(varcollection; components=false) -> VarList_tuple

Create a VarList_tuple describing a collection of VariableReactions, create_accessors will then return a Tuple of data arrays.

An entry of nothing in varcollection will produce nothing in the corresponding entry in the Tuple of arrays supplied to the Reaction method.

If components = true, each Tuple field will be a Vector of data array components.

source
PALEOboxes.VarList_ttupleType
VarList_ttuple(varcollection) -> VarList_ttuple

Create a VarList_ttuple describing a collection of collections of VariableReactions, create_accessors will then return a Tuple of Tuples of data arrays.

source
PALEOboxes.VarList_vectorType
VarList_vector(varcollection; components=false, forceview=false) -> VarList_vector

Create a VarList_vector describing a collection of VariableReactions, create_accessors will then return a Vector of data arrays.

If components = true, each Vector element will be a Vector of data array components.

If forceview = true, each accessor will be a 1-D view to help type stability, even if this is redundant (ie no view required, v::Vector -> view(v, 1:length(v)))

source
PALEOboxes.VarList_vvectorType
VarList_vvector(Vector{Vector{VariableReaction}}::vars; components=false) -> VarList_vvector

Create a VarList_vvector describing a Vector of Vectors of VariableReactions, create_accessors will then return a Vector of Vectors of data arrays.

If components = true, each Vector of Vectors element will be a Vector of data array components.

source
PALEOboxes.VarList_nothingType
VarList_nothing() -> VarList_nothing

Create a placeholder for a missing/unavailable VariableReaction. create_accessors will then return nothing.

source

Implementing method functions

Reaction method functions should iterate over the cells in the Domain supplied by cellrange argument and calculate appropriate biogeochemical fluxes etc (which may include the model time derivative and any intermediate or diagnostic output).

Iterating over cells

The simplest case is a method function that iterates over individual cells, with skeleton form:

function do_something_cellwise(m::PB.AbstractReactionMethod, pars, (vars, ), cellrange::PB.AbstractCellRange, deltat)
+("ocean", "oceansurface", "goo", true)
source
PALEOboxes.set_attribute!Function
set_attribute!(var::VariableBase, name::Symbol, value, allow_create=false) -> var

Set Variable attribute.

source

Defining collections of VariableReactions

PALEOboxes.AbstractVarListType
AbstractVarList

Variables required by a ReactionMethod methodfn are specified by a Tuple of VarList_xxx <: AbstractVarList, each containing a collection of VariableReaction.

These are then converted (by the create_accessors method) to a corresponding Tuple of collections of views on Domain data arrays , which are then be passed to the ReactionMethod methodfn.

NB: creates and uses a copy of supplied Variables including metadata, so set / modify Variable attributes before creating a VarList.

Implementation

Subtypes of AbstractVarList should implement:

  • a constructor that takes a collection of VariableReactions
  • create_accessors, returning the views on Domain data arrays in a subtype-specific collection.
  • get_variables, returning the collection of VariableReactions (as a flat list).
source
PALEOboxes.VarList_singleType
VarList_single(var; components=false) -> VarList_single

Create a VarList_single describing a single VariableReaction, create_accessors will then return a single accessor.

source
PALEOboxes.VarList_namedtupleType
VarList_namedtuple(varcollection; components=false) -> VarList_namedtuple

Create a VarList_namedtuple describing a collection of VariableReactions, create_accessors will then return a NamedTuple with field names = VariableReaction.localname and field values = corresponding data arrays.

If components = true, each NamedTuple field will be a Vector of data array components.

source
PALEOboxes.VarList_tupleType
VarList_tuple(varcollection; components=false) -> VarList_tuple

Create a VarList_tuple describing a collection of VariableReactions, create_accessors will then return a Tuple of data arrays.

An entry of nothing in varcollection will produce nothing in the corresponding entry in the Tuple of arrays supplied to the Reaction method.

If components = true, each Tuple field will be a Vector of data array components.

source
PALEOboxes.VarList_ttupleType
VarList_ttuple(varcollection) -> VarList_ttuple

Create a VarList_ttuple describing a collection of collections of VariableReactions, create_accessors will then return a Tuple of Tuples of data arrays.

source
PALEOboxes.VarList_vectorType
VarList_vector(varcollection; components=false, forceview=false) -> VarList_vector

Create a VarList_vector describing a collection of VariableReactions, create_accessors will then return a Vector of data arrays.

If components = true, each Vector element will be a Vector of data array components.

If forceview = true, each accessor will be a 1-D view to help type stability, even if this is redundant (ie no view required, v::Vector -> view(v, 1:length(v)))

source
PALEOboxes.VarList_vvectorType
VarList_vvector(Vector{Vector{VariableReaction}}::vars; components=false) -> VarList_vvector

Create a VarList_vvector describing a Vector of Vectors of VariableReactions, create_accessors will then return a Vector of Vectors of data arrays.

If components = true, each Vector of Vectors element will be a Vector of data array components.

source
PALEOboxes.VarList_nothingType
VarList_nothing() -> VarList_nothing

Create a placeholder for a missing/unavailable VariableReaction. create_accessors will then return nothing.

source

Implementing method functions

Reaction method functions should iterate over the cells in the Domain supplied by cellrange argument and calculate appropriate biogeochemical fluxes etc (which may include the model time derivative and any intermediate or diagnostic output).

Iterating over cells

The simplest case is a method function that iterates over individual cells, with skeleton form:

function do_something_cellwise(m::PB.AbstractReactionMethod, pars, (vars, ), cellrange::PB.AbstractCellRange, deltat)
 
     @inbounds for i in cellrange.indices
         vars.A[i]  = something*vars.B[i]*vars.C[i]  # in general A is some function of B, C, etc
@@ -104,7 +104,7 @@
 
     x = vgatherind(ST, v_a, i)  # x is a packed SIMD vector with type conversion to Float32
     vscatterind!(x, v_b, i)
-end
source

Adding ReactionMethods

PALEOboxes.ReactionMethodType
ReactionMethod(
+end
source

Adding ReactionMethods

PALEOboxes.ReactionMethodType
ReactionMethod(
     methodfn::Function,
     reaction::AbstractReaction,
     name::String,
@@ -113,13 +113,13 @@
     operatorID::Vector{Int64}, 
     domain::AbstractDomain; 
     preparefn = (m, vardata) -> vardata
-) -> m::ReactionMethod

Defines a callback function methodfn with Variables varlists, to be called from the Model framework either during setup or as part of the main loop.

Fields

  • methodfn: callback from Model framework

  • reaction: the Reaction that created this ReactionMethod

  • name: a descriptive name, eg generated from the name of methodfn

  • varlists: Tuple of VarLists, each representing a list of VariableReactions. Corresponding Variable accessors vardata (views on Arrays) will be provided to the methodfn callback. NB: not concretely typed to reduce compile time, as not performance-critical

  • p: optional context field (of arbitrary type) to store data needed by methodfn.

  • operatorID

  • domain

  • preparefn: preparefn(m::ReactionMethod, vardata::Tuple) -> modified_vardata::Tuple optionally modify vardata to eg add buffers. NB: not concretely typed as not performance-critical

methodfn

The methodfn callback is:

methodfn(m::ReactionMethod, pars, vardata::Tuple, cellrange::AbstractCellRange, modelctxt)

or (if Parameters are not required):

methodfn(m::ReactionMethod, vardata::Tuple, cellrange::AbstractCellRange, modelctxt)

With arguments:

  • m::ReactionMethod: context is available as m.reaction::AbstractReaction (the Reaction that defined the ReactionMethod), and m.p (an arbitrary extra context field supplied when ReactionMethod created).
  • pars: a struct with Parameters as fields (current just the ParametersTuple defined as reaction.pars)
  • vardata: A Tuple of collections of views on Domain data arrays corresponding to VariableReactions defined by varlists
  • cellrange::AbstractCellRange: range of cells to calculate.
  • modelctxt:
    • for a setup method, :setup, :initial_value or :norm_value defining the type of setup requested
    • for a main loop method deltat providing timestep information eg for rate throttling.

preparefn

An optional preparefn callback can be supplied eg to allocate buffers that require knowledge of the data types of vardata or to cache expensive calculations:

preparefn(m::ReactionMethod, vardata::Tuple) -> modified_vardata::Tuple

This is called after model arrays are allocated, and prior to setup.

source
PALEOboxes.add_method_setup!Function
add_method_setup!(reaction::AbstractReaction, method::AbstractReactionMethod)
-add_method_setup!(reaction::AbstractReaction, methodfn::Function, vars::Tuple{Vararg{AbstractVarList}}; kwargs...) -> ReactionMethod

Add or create-and-add a setup method (called before main loop) eg to set persistent data or initialize state variables. methodfn, vars, kwargs are passed to ReactionMethod.

source
PALEOboxes.add_method_initialize!Function
add_method_initialize!(reaction::AbstractReaction, method::AbstractReactionMethod)
-add_method_initialize!(reaction::AbstractReaction, methodfn::Function, vars::Tuple{Vararg{AbstractVarList}}; kwargs...) -> ReactionMethod

Add or create-and-add an initialize method (called at start of each main loop iteration) eg to zero out accumulator Variables. methodfn, vars, kwargs are passed to ReactionMethod.

source
PALEOboxes.add_method_do!Function
add_method_do!(reaction::AbstractReaction, method::AbstractReactionMethod)
-add_method_do!(reaction::AbstractReaction, methodfn::Function, vars::Tuple{Vararg{AbstractVarList}}; kwargs...) -> ReactionMethod

Add or create and add a main loop method. methodfn, vars, kwargs are passed to ReactionMethod.

source

Predefined ReactionMethods

Setup and initialization of Variables

PALEOboxes.add_method_setup_initialvalue_vars_default!Function
add_method_setup_initialvalue_vars_default!(react::AbstractReaction, variables [; kwargs...])

Create and add a default method to initialize Variables matching filterfn (defaults to state Variables) at beginning of integration.

Setup callbacks used

  • State Variables and similar (:vfunction != VF_Undefined) are initialized in a setup callback with attribute_name in (:initial_value, :norm_value), with values from those Variable attributes.
  • If force_state_norm_value=false, other Variables (with :vfunction == VF_Undefined) are initialized in a setup callback with attribute_name=:setup, with values from the :initial_value Variable attribute. NB: filterfn must be set to include these Variables.
  • If force_initial_norm_value=true, all Variables (including those with :vfunction == VF_Undefined) are initialised as state Variables

Keywords

  • filterfn: set to f(var)::Bool to override the default selection for state variables only (Variables with :vfunction in (VF_StateExplicit, VF_State, VF_Total, VF_StateTotal, VF_Constraint))
  • force_initial_norm_value=false: true to always use :initial_value, :norm_value, even for variables with :vfunction=VF_Undefined
  • transfer_attribute_vars=[]: Set to a list of the same length as variables to initialise variables from attributes of transfer_attribute_vars.
  • setup_callback=(method, attribute_name, var, vardata) -> nothing: Set to a function that is called after each Variable initialisation eg to store norm values.
  • convertvars=[]
  • convertfn = (convertvars_tuple, i) -> 1.0
  • convertinfo = ""

Including volume etc conversion

Set convertvars to a Vector of Variables (eg for cell volume) and supply convertfn and convertinfo to initialize to :initial_value*convertfn(convertvars_tuple, i) where the argument of convertfn is the Tuple generated by VarList_tuple(convertvars).

Example: To interpret :initial_value as a concentration-like quantity:

convertvars = [volume], 
+) -> m::ReactionMethod

Defines a callback function methodfn with Variables varlists, to be called from the Model framework either during setup or as part of the main loop.

Fields

  • methodfn: callback from Model framework

  • reaction: the Reaction that created this ReactionMethod

  • name: a descriptive name, eg generated from the name of methodfn

  • varlists: Tuple of VarLists, each representing a list of VariableReactions. Corresponding Variable accessors vardata (views on Arrays) will be provided to the methodfn callback. NB: not concretely typed to reduce compile time, as not performance-critical

  • p: optional context field (of arbitrary type) to store data needed by methodfn.

  • operatorID

  • domain

  • preparefn: preparefn(m::ReactionMethod, vardata::Tuple) -> modified_vardata::Tuple optionally modify vardata to eg add buffers. NB: not concretely typed as not performance-critical

methodfn

The methodfn callback is:

methodfn(m::ReactionMethod, pars, vardata::Tuple, cellrange::AbstractCellRange, modelctxt)

or (if Parameters are not required):

methodfn(m::ReactionMethod, vardata::Tuple, cellrange::AbstractCellRange, modelctxt)

With arguments:

  • m::ReactionMethod: context is available as m.reaction::AbstractReaction (the Reaction that defined the ReactionMethod), and m.p (an arbitrary extra context field supplied when ReactionMethod created).
  • pars: a struct with Parameters as fields (current just the ParametersTuple defined as reaction.pars)
  • vardata: A Tuple of collections of views on Domain data arrays corresponding to VariableReactions defined by varlists
  • cellrange::AbstractCellRange: range of cells to calculate.
  • modelctxt:
    • for a setup method, :setup, :initial_value or :norm_value defining the type of setup requested
    • for a main loop method deltat providing timestep information eg for rate throttling.

preparefn

An optional preparefn callback can be supplied eg to allocate buffers that require knowledge of the data types of vardata or to cache expensive calculations:

preparefn(m::ReactionMethod, vardata::Tuple) -> modified_vardata::Tuple

This is called after model arrays are allocated, and prior to setup.

source
PALEOboxes.add_method_setup!Function
add_method_setup!(reaction::AbstractReaction, method::AbstractReactionMethod)
+add_method_setup!(reaction::AbstractReaction, methodfn::Function, vars::Tuple{Vararg{AbstractVarList}}; kwargs...) -> ReactionMethod

Add or create-and-add a setup method (called before main loop) eg to set persistent data or initialize state variables. methodfn, vars, kwargs are passed to ReactionMethod.

source
PALEOboxes.add_method_initialize!Function
add_method_initialize!(reaction::AbstractReaction, method::AbstractReactionMethod)
+add_method_initialize!(reaction::AbstractReaction, methodfn::Function, vars::Tuple{Vararg{AbstractVarList}}; kwargs...) -> ReactionMethod

Add or create-and-add an initialize method (called at start of each main loop iteration) eg to zero out accumulator Variables. methodfn, vars, kwargs are passed to ReactionMethod.

source
PALEOboxes.add_method_do!Function
add_method_do!(reaction::AbstractReaction, method::AbstractReactionMethod)
+add_method_do!(reaction::AbstractReaction, methodfn::Function, vars::Tuple{Vararg{AbstractVarList}}; kwargs...) -> ReactionMethod

Add or create and add a main loop method. methodfn, vars, kwargs are passed to ReactionMethod.

source

Predefined ReactionMethods

Setup and initialization of Variables

PALEOboxes.add_method_setup_initialvalue_vars_default!Function
add_method_setup_initialvalue_vars_default!(react::AbstractReaction, variables [; kwargs...])

Create and add a default method to initialize Variables matching filterfn (defaults to state Variables) at beginning of integration.

Setup callbacks used

  • State Variables and similar (:vfunction != VF_Undefined) are initialized in a setup callback with attribute_name in (:initial_value, :norm_value), with values from those Variable attributes.
  • If force_state_norm_value=false, other Variables (with :vfunction == VF_Undefined) are initialized in a setup callback with attribute_name=:setup, with values from the :initial_value Variable attribute. NB: filterfn must be set to include these Variables.
  • If force_initial_norm_value=true, all Variables (including those with :vfunction == VF_Undefined) are initialised as state Variables

Keywords

  • filterfn: set to f(var)::Bool to override the default selection for state variables only (Variables with :vfunction in (VF_StateExplicit, VF_State, VF_Total, VF_StateTotal, VF_Constraint))
  • force_initial_norm_value=false: true to always use :initial_value, :norm_value, even for variables with :vfunction=VF_Undefined
  • transfer_attribute_vars=[]: Set to a list of the same length as variables to initialise variables from attributes of transfer_attribute_vars.
  • setup_callback=(method, attribute_name, var, vardata) -> nothing: Set to a function that is called after each Variable initialisation eg to store norm values.
  • convertvars=[]
  • convertfn = (convertvars_tuple, i) -> 1.0
  • convertinfo = ""

Including volume etc conversion

Set convertvars to a Vector of Variables (eg for cell volume) and supply convertfn and convertinfo to initialize to :initial_value*convertfn(convertvars_tuple, i) where the argument of convertfn is the Tuple generated by VarList_tuple(convertvars).

Example: To interpret :initial_value as a concentration-like quantity:

convertvars = [volume], 
 convertfn = ((volume, ), i) -> volume[i], 
-convertinfo = " * volume"
source
PALEOboxes.add_method_initialize_zero_vars_default!Function
add_method_initialize_zero_vars_default!(react::AbstractReaction, variables=PB.get_variables(react))

Create and add a default method to initialize Variables to zero at beginning of each timestep. Defaults to adding all Variables from react with :initialize_to_zero attribute true.

NB: TODO variables are converted to VarDep (no dependency checking or sorting needed, could define a VarInit or similar?)

source

Adding totals for Variables

PALEOboxes.add_method_do_totals_default!Function
add_method_do_totals_default!(react::AbstractReaction, total_candidates=PB.get_variables(react);
-    [filterfn] [, methodname] [, total_localnames] [, operatorID])

Create and add a method to add total variables (Scalar Properties), for Variables in collection total_candidates that match filterfn (defaults to those that are Array Variables and have attribute `:calc_total == true).

NB: total Variables will require initialization to zero using add_method_initialize_zero_vars_default!

source

Chemical reactions

PALEOboxes.RateStoichType
RateStoich(
+convertinfo = " * volume"
source
PALEOboxes.add_method_initialize_zero_vars_default!Function
add_method_initialize_zero_vars_default!(react::AbstractReaction, variables=PB.get_variables(react))

Create and add a default method to initialize Variables to zero at beginning of each timestep. Defaults to adding all Variables from react with :initialize_to_zero attribute true.

NB: TODO variables are converted to VarDep (no dependency checking or sorting needed, could define a VarInit or similar?)

source

Adding totals for Variables

PALEOboxes.add_method_do_totals_default!Function
add_method_do_totals_default!(react::AbstractReaction, total_candidates=PB.get_variables(react);
+    [filterfn] [, methodname] [, total_localnames] [, operatorID])

Create and add a method to add total variables (Scalar Properties), for Variables in collection total_candidates that match filterfn (defaults to those that are Array Variables and have attribute `:calc_total == true).

NB: total Variables will require initialization to zero using add_method_initialize_zero_vars_default!

source

Chemical reactions

PALEOboxes.RateStoichType
RateStoich(
     ratevartemplate, stoich_statevarname;
     deltavarname_eta=nothing, prcessname="", sms_prefix="", sms_suffix="_sms"
 ) -> RateStoich

Calculate fluxes for a biogeochemical reaction given rate, stoichiometry, and optionally isotope eta.

Add to a Reaction using create_ratestoich_method and add_method_do!.

A Property Variable should be set to provide the reaction rate (often this is implemented by another method of the same Reaction). This method will then link to that (using the local and link names supplied by ratevartemplate) and calculate the appropriate product rates, omitting products that are not present (VariableReaction not linked) in the Model configuration. Metadata for use when analysing model output should be added to the rate variable using add_rate_stoichiometry!, in the usual case where this Variable is supplied as ratevartemplate this will happen automatically.

Arguments:

  • ratevartemplate::Union{VarPropT, VarDepT}: used to define the rate variable local and link names.
  • stoich_statevarname: collection of Tuple(stoichiometry, name) eg ((-2.0, "O2"), (-1.0,"H2S::Isotope"), (1.0, "SO4::Isotope"))
  • deltavarname_eta: optional tuple of variable delta + eta ("SO4_delta", -30.0) or ("SO4_delta", rj.pars.delta). If a Parameter is supplied, this is read in do_react_ratestoich to allow modification.
  • processname::String: optional tag to identify the type of reaction in model output
  • add_rate_stoichiometry=true: true to add call add_rate_stoichiometry! to add metadata to ratevartemplate.

Examples:

Create a RateStoich representing the reaction 2 O2 + H2S -> H2SO4

julia> myratevar = PALEOboxes.VarProp("myrate", "mol yr-1", "a rate");
@@ -127,6 +127,6 @@
 julia> rs = PALEOboxes.RateStoich(myratevar, ((-2.0, "O2"), (-1.0,"H2S"), (1.0, "SO4")));
 
 julia> rs.stoich_statevarname
-((-2.0, "O2"), (-1.0, "H2S"), (1.0, "SO4"))
source
PALEOboxes.create_ratestoich_methodFunction
create_ratestoich_method(reaction::AbstractReaction, ratestoich::RateStoich; isotope_data=ScalarData)
-    -> ReactionMethod

Create method (see RateStoich).

source
PALEOboxes.add_rate_stoichiometry!Function
add_rate_stoichiometry!(ratevar::VarPropT, ratestoich::RateStoich)

Add metadata to rate variable ratevar for use when analysing model output.

Only needs to be called explicitly if RateStoich was supplied with a VarDep that links to the rate variable, not the rate variable itself.

Adds Variable attributes:

  • rate_processname::String = ratestoich.processname
  • rate_species::Vector{String} reactants + products from ratestoich.stoich_statevarname
  • rate_stoichiometry::Vector{Float64} reaction stoichiometry from ratestoich.stoich_statevarname
source

Internal details of Variable arrays accessor generation

VariableReactions in the AbstractVarLists for a ReactionMethod are processed by create_accessor to supply views on arrays as corresponding arguments to the ReactionMethod function.

PALEOboxes.create_accessorFunction
 create_accessor(var::VariableReaction, modeldata, arrays_idx, components, [,forceview=false])
-    -> accessor or (accessor, subdomain_indices)

Creates a view on a (single) VariableDomain data array linked by var::VariableReaction. Called by an AbstractVarList create_accessors implementation to generate a collection of views for multiple VariableReactions.

Returns:

  • if var is linked, an accessor or Tuple (accessor, subdomain_indices) that provides a view on variable data.
  • if var is not linked, nothing if var is optional, or errors and doesn't return if var is non-optional.

Mapping of indices for Subdomains <–> Domains:

  • if no Subdomain, returns unmodified indices (if forceview=false), or an equivalent view (if forceview=true, this is to help type stability)
  • if Variable is a Domain interior and Subdomain is a Domain boundary, accessor is a view with a subset of Domain indices.
  • if Variable is a Domain boundary and Subdomain is the Domain interior, returns a Tuple with subdomain_indices, length(Subdomain size), with missing for interior points.

Mapping of multi-component (Isotope) Variables:

  • If components=false:
    • map multi-component Variable to accessor::IsotopeArray
    • return a single-component Variable as a accessor::AbstractArray.
  • If components=true:
    • variable data as a accessor::Vector{Array}, length=number of components
source
PALEOboxes.create_accessorsFunction
create_accessors(varlist::AbstractVarList, modeldata::AbstractModelData, arrays_idx::Int) -> vardata

Return a collection vardata of views on Domain data arrays for VariableReactions in varlist. Collection and view are determined by varlist Type.

source
+((-2.0, "O2"), (-1.0, "H2S"), (1.0, "SO4"))source
PALEOboxes.create_ratestoich_methodFunction
create_ratestoich_method(reaction::AbstractReaction, ratestoich::RateStoich; isotope_data=ScalarData)
+    -> ReactionMethod

Create method (see RateStoich).

source
PALEOboxes.add_rate_stoichiometry!Function
add_rate_stoichiometry!(ratevar::VarPropT, ratestoich::RateStoich)

Add metadata to rate variable ratevar for use when analysing model output.

Only needs to be called explicitly if RateStoich was supplied with a VarDep that links to the rate variable, not the rate variable itself.

Adds Variable attributes:

  • rate_processname::String = ratestoich.processname
  • rate_species::Vector{String} reactants + products from ratestoich.stoich_statevarname
  • rate_stoichiometry::Vector{Float64} reaction stoichiometry from ratestoich.stoich_statevarname
source

Internal details of Variable arrays accessor generation

VariableReactions in the AbstractVarLists for a ReactionMethod are processed by create_accessor to supply views on arrays as corresponding arguments to the ReactionMethod function.

PALEOboxes.create_accessorFunction
 create_accessor(var::VariableReaction, modeldata, arrays_idx, components, [,forceview=false])
+    -> accessor or (accessor, subdomain_indices)

Creates a view on a (single) VariableDomain data array linked by var::VariableReaction. Called by an AbstractVarList create_accessors implementation to generate a collection of views for multiple VariableReactions.

Returns:

  • if var is linked, an accessor or Tuple (accessor, subdomain_indices) that provides a view on variable data.
  • if var is not linked, nothing if var is optional, or errors and doesn't return if var is non-optional.

Mapping of indices for Subdomains <–> Domains:

  • if no Subdomain, returns unmodified indices (if forceview=false), or an equivalent view (if forceview=true, this is to help type stability)
  • if Variable is a Domain interior and Subdomain is a Domain boundary, accessor is a view with a subset of Domain indices.
  • if Variable is a Domain boundary and Subdomain is the Domain interior, returns a Tuple with subdomain_indices, length(Subdomain size), with missing for interior points.

Mapping of multi-component (Isotope) Variables:

  • If components=false:
    • map multi-component Variable to accessor::IsotopeArray
    • return a single-component Variable as a accessor::AbstractArray.
  • If components=true:
    • variable data as a accessor::Vector{Array}, length=number of components
source
PALEOboxes.create_accessorsFunction
create_accessors(varlist::AbstractVarList, modeldata::AbstractModelData, arrays_idx::Int) -> vardata

Return a collection vardata of views on Domain data arrays for VariableReactions in varlist. Collection and view are determined by varlist Type.

source
diff --git a/dev/ReactionCatalog/index.html b/dev/ReactionCatalog/index.html index 2379f54..9537e87 100644 --- a/dev/ReactionCatalog/index.html +++ b/dev/ReactionCatalog/index.html @@ -8,7 +8,7 @@ R*: P # rename to represent Phosphorus variable_attributes: R:norm_value: 3.1e15 # mol - R:initial_value: 3.1e15 # mol

See also

ReactionReservoir (one value per cell for a spatially resolved Domain eg ocean), ReactionReservoirWellMixed (one value for a whole spatially resolved Domain).

Parameters

Methods and Variables for default Parameters

source
PALEOboxes.Reservoirs.ReactionReservoirType
ReactionReservoir, ReactionReservoirTotal

A single (vector) reservoir (state variable) representing a biogeochemical tracer, ie one value per cell in a spatially-resolved Domain (eg ocean).

State Variables can represent either per-cell concentration, or per-cell moles, set by parameter state_conc:

  • state_conc=false (default): create R (mol) and R_sms (mol yr-1) as state variable and source-sink, calculate R_conc (mol m-3)
  • state_conc=true: create R_conc (mol m-3) and R_conc_sms (mol m-3 yr-1) as state variable and source-sink, calculate R (mol), NB: R_sms (mol yr-1) is still available and is added to R_conc_sms.

In addition:

  • if parameter field_data <: AbstractIsotopeScalar (eg IsotopeLinear), a Property R_delta is created.
  • ReactionReservoirTotal or ReactionReservoirConcTotal also calculates the Domain total R_total (units mol), eg to check budgets.

Local name prefix R should then be renamed using variable_links: in the configuration file.

Initialisation

Initial value is set using variable_attributes: in the configuration file, using R:initial_value and R:initial_delta (for 'stateconc=false') or `Rconc:initialvalueandRconc:initialdelta` (for a 'stateconc=true'). (NB: even if initial_value is set on R, it sets concentration in mol m-3.)

Transport is defined by attributes :advect, :vertical_movement (m d-1) set on the concentration variable R_conc. Optical extinction is defined by the :specific_light_extinction (m^2 mol-1) attribute set on the concentration variable R_conc.

Example configuration in .yaml file

            reservoir_P:  # ocean Phosphorus
+                    R:initial_value:        3.1e15  # mol

See also

ReactionReservoir (one value per cell for a spatially resolved Domain eg ocean), ReactionReservoirWellMixed (one value for a whole spatially resolved Domain).

Parameters

  • field_data[DataType]=PALEOboxes.ScalarData, default_value=PALEOboxes.ScalarData, allowed_values=Type[PALEOboxes.ScalarData, PALEOboxes.IsotopeLinear], description="disable / enable isotopes and specify isotope type"
  • const[Bool]=false, default_value=false, description="true to provide a constant value: R is not a state variable, fluxes in R_sms Variable are ignored"
  • state_norm[Bool]=false, default_value=false, description="true to provide solver with normalized values"

Methods and Variables for default Parameters

  • methodfn_do_nothing
    • R_sms (mol yr-1), VT_ReactContributor, VF_Deriv, description="scalar reservoir source-sinks"
  • do_reactionreservoirscalar
    • R_norm (), VT_ReactProperty, description="scalar reservoir normalized"
    • R (mol), VT_ReactDependency, VF_StateExplicit, description="scalar reservoir"
source
PALEOboxes.Reservoirs.ReactionReservoirType
ReactionReservoir, ReactionReservoirTotal

A single (vector) reservoir (state variable) representing a biogeochemical tracer, ie one value per cell in a spatially-resolved Domain (eg ocean).

State Variables can represent either per-cell concentration, or per-cell moles, set by parameter state_conc:

  • state_conc=false (default): create R (mol) and R_sms (mol yr-1) as state variable and source-sink, calculate R_conc (mol m-3)
  • state_conc=true: create R_conc (mol m-3) and R_conc_sms (mol m-3 yr-1) as state variable and source-sink, calculate R (mol), NB: R_sms (mol yr-1) is still available and is added to R_conc_sms.

In addition:

  • if parameter field_data <: AbstractIsotopeScalar (eg IsotopeLinear), a Property R_delta is created.
  • ReactionReservoirTotal or ReactionReservoirConcTotal also calculates the Domain total R_total (units mol), eg to check budgets.

Local name prefix R should then be renamed using variable_links: in the configuration file.

Initialisation

Initial value is set using variable_attributes: in the configuration file, using R:initial_value and R:initial_delta (for 'stateconc=false') or `Rconc:initialvalueandRconc:initialdelta` (for a 'stateconc=true'). (NB: even if initial_value is set on R, it sets concentration in mol m-3.)

Transport is defined by attributes :advect, :vertical_movement (m d-1) set on the concentration variable R_conc. Optical extinction is defined by the :specific_light_extinction (m^2 mol-1) attribute set on the concentration variable R_conc.

Example configuration in .yaml file

            reservoir_P:  # ocean Phosphorus
                 class: ReactionReservoirTotal       # include _total (mol)
                 parameters:
                     # field_data: ScalarData        # change to IsotopeLinear to represent an isotope                       
@@ -16,7 +16,7 @@
                     R*: P                           # rename to represent Phosphorus
                 variable_attributes:
                     R:norm_value:           3e-3    # mol m-3, normalisation value (used by some solvers)
-                    R:initial_value:        2e-3    # mol m-3, initial concentration

See also

ReactionReservoirWellMixed (one value for the whole Domain), ReactionReservoirScalar (one value for a reservoir in a 0D Domain eg for COPSE (Bergman et al., 2004)), ReactionReservoirConst (constant time-independent value ie no state variable).

Parameters

  • field_data[DataType]=PALEOboxes.ScalarData, default_value=PALEOboxes.ScalarData, allowed_values=Type[PALEOboxes.ScalarData, PALEOboxes.IsotopeLinear], description="disable / enable isotopes and specify isotope type"
  • total[Bool]=false, default_value=false, description="true to calculate R_total"
  • limit_delta_conc[Float64]=0.0 (mol m-3), default_value=0.0, description="**EXPERIMENTAL** attempt to limit delta for low/-ve concentrations (0.0 to disable)"
  • state_conc[Bool]=false, default_value=false, description="true to define R_conc, R_sms_conc as the state variable pair and calculate R, false to define R, R_sms and calculate R_conc"

Methods and Variables for default Parameters

  • do_reactionreservoir
    • R (mol), VT_ReactDependency, VF_StateExplicit, description="vector reservoir"
    • R_conc (mol m-3), VT_ReactProperty, description="concentration"
    • volume (m3), VT_ReactDependency, description="cell volume (or cell phase volume eg for a sediment with solid and liquid phases)"
  • methodfn_do_nothing
    • R_sms (mol yr-1), VT_ReactContributor, VF_Deriv, description="vector reservoir source-sinks"
source
PALEOboxes.Reservoirs.ReactionReservoirWellMixedType
ReactionReservoirWellMixed

A Scalar Reservoir representing a well-mixed tracer in a vector Domain (eg ocean). Provides a scalar state Variable R and R_sms, and also vector Variables: R_conc (set to uniform concentration), and R_vec_sms Target for accumulating fluxes that is added to the scalar R_sms.

Initialisation

Initial value is set in the variable_attributes: section in the configuration file, using R:initial_value and R:initial_delta. NB: may be initialized either from mean concentration or total (set by parameter initialization_type)

TODO salinity normalisation.

See also

ReactionReservoir (one value per cell), ReactionReservoirScalar (one value for a reservoir in a 0D Domain eg for COPSE (Bergman et al., 2004)).

Parameters

  • field_data[DataType]=PALEOboxes.ScalarData, default_value=PALEOboxes.ScalarData, allowed_values=Type[PALEOboxes.ScalarData, PALEOboxes.IsotopeLinear], description="disable / enable isotopes and specify isotope type"
  • initialization_type[String]="conc", default_value="conc", allowed_values=["conc", "total"], description=":initial_value attribute represents conc (mol m-3) or total (mol)"

Methods and Variables for default Parameters

  • do_reservoir_well_mixed
    • R (mol), VT_ReactDependency, VF_StateExplicit, description="scalar reservoir"
    • R_norm (), VT_ReactProperty, description="scalar reservoir normalized"
    • R_conc (mol m-3), VT_ReactProperty, description="concentration"
    • volume_total (m^3), VT_ReactDependency, description="total volume"
  • do_reservoir_well_mixed_sms
    • R_sms (mol yr-1), VT_ReactContributor, VF_Deriv, description="scalar reservoir source-sinks"
    • R_vec_sms (mol yr-1), VT_ReactTarget, description="vector reservoir source-sinks"
source
PALEOboxes.Reservoirs.ReactionReservoirConstType
ReactionReservoirConst

A single (vector) constant tracer R_conc (constant replacement for a ReactionReservoir).

Local name prefix R should then be renamed using variable_links: in the configuration file.

Initialisation

Set :initial_value, :initial_delta on R_conc (mol m-3) in the variable_attributes: section of the config file.

TODO salinity normalisation.

Example configuration in .yaml file

            reservoir_B:  # Constant value for ocean Boron 
+                    R:initial_value:        2e-3    # mol m-3, initial concentration

See also

ReactionReservoirWellMixed (one value for the whole Domain), ReactionReservoirScalar (one value for a reservoir in a 0D Domain eg for COPSE (Bergman et al., 2004)), ReactionReservoirConst (constant time-independent value ie no state variable).

Parameters

  • field_data[DataType]=PALEOboxes.ScalarData, default_value=PALEOboxes.ScalarData, allowed_values=Type[PALEOboxes.ScalarData, PALEOboxes.IsotopeLinear], description="disable / enable isotopes and specify isotope type"
  • total[Bool]=false, default_value=false, description="true to calculate R_total"
  • limit_delta_conc[Float64]=0.0 (mol m-3), default_value=0.0, description="**EXPERIMENTAL** attempt to limit delta for low/-ve concentrations (0.0 to disable)"
  • state_conc[Bool]=false, default_value=false, description="true to define R_conc, R_sms_conc as the state variable pair and calculate R, false to define R, R_sms and calculate R_conc"

Methods and Variables for default Parameters

  • do_reactionreservoir
    • R (mol), VT_ReactDependency, VF_StateExplicit, description="vector reservoir"
    • R_conc (mol m-3), VT_ReactProperty, description="concentration"
    • volume (m3), VT_ReactDependency, description="cell volume (or cell phase volume eg for a sediment with solid and liquid phases)"
  • methodfn_do_nothing
    • R_sms (mol yr-1), VT_ReactContributor, VF_Deriv, description="vector reservoir source-sinks"
source
PALEOboxes.Reservoirs.ReactionReservoirWellMixedType
ReactionReservoirWellMixed

A Scalar Reservoir representing a well-mixed tracer in a vector Domain (eg ocean). Provides a scalar state Variable R and R_sms, and also vector Variables: R_conc (set to uniform concentration), and R_vec_sms Target for accumulating fluxes that is added to the scalar R_sms.

Initialisation

Initial value is set in the variable_attributes: section in the configuration file, using R:initial_value and R:initial_delta. NB: may be initialized either from mean concentration or total (set by parameter initialization_type)

TODO salinity normalisation.

See also

ReactionReservoir (one value per cell), ReactionReservoirScalar (one value for a reservoir in a 0D Domain eg for COPSE (Bergman et al., 2004)).

Parameters

  • field_data[DataType]=PALEOboxes.ScalarData, default_value=PALEOboxes.ScalarData, allowed_values=Type[PALEOboxes.ScalarData, PALEOboxes.IsotopeLinear], description="disable / enable isotopes and specify isotope type"
  • initialization_type[String]="conc", default_value="conc", allowed_values=["conc", "total"], description=":initial_value attribute represents conc (mol m-3) or total (mol)"

Methods and Variables for default Parameters

  • do_reservoir_well_mixed
    • R (mol), VT_ReactDependency, VF_StateExplicit, description="scalar reservoir"
    • R_norm (), VT_ReactProperty, description="scalar reservoir normalized"
    • R_conc (mol m-3), VT_ReactProperty, description="concentration"
    • volume_total (m^3), VT_ReactDependency, description="total volume"
  • do_reservoir_well_mixed_sms
    • R_sms (mol yr-1), VT_ReactContributor, VF_Deriv, description="scalar reservoir source-sinks"
    • R_vec_sms (mol yr-1), VT_ReactTarget, description="vector reservoir source-sinks"
source
PALEOboxes.Reservoirs.ReactionReservoirConstType
ReactionReservoirConst

A single (vector) constant tracer R_conc (constant replacement for a ReactionReservoir).

Local name prefix R should then be renamed using variable_links: in the configuration file.

Initialisation

Set :initial_value, :initial_delta on R_conc (mol m-3) in the variable_attributes: section of the config file.

TODO salinity normalisation.

Example configuration in .yaml file

            reservoir_B:  # Constant value for ocean Boron 
                 class: ReactionReservoirConst
                 parameters:
                     field_data: IsotopeLinear
@@ -24,7 +24,7 @@
                     R*: B
                 variable_attributes:                      
                     R_conc:initial_value:       0.4269239 # contemporary value
-                    R_conc:initial_delta:       34.0

See also

ReactionReservoir

Parameters

  • field_data[DataType]=PALEOboxes.ScalarData, default_value=PALEOboxes.ScalarData, allowed_values=Type[PALEOboxes.ScalarData, PALEOboxes.IsotopeLinear], description="disable / enable isotopes and specify isotope type"

Methods and Variables

  • setup_initialvalue_vars_default
    • R_conc (mol m-3), VT_ReactProperty, description="concentration"
source
PALEOboxes.Reservoirs.ReactionReservoirForcedType
ReactionReservoirForced

A single (vector) constant tracer (constant replacement for a ReactionReservoir), with forcing.

Calculates R_conc = R_conc_initial * R_FORCE.

Local name prefix R should then be renamed using variable_links: in the configuration file.

Initialisation

NB: set :initial_value, :initial_delta on R_conc_initial in the variable_attributes: section of the config file.

TODO salinity normalisation.

See also

ReactionReservoirConst, ReactionReservoir

Parameters

  • field_data[DataType]=PALEOboxes.ScalarData, default_value=PALEOboxes.ScalarData, allowed_values=Type[PALEOboxes.ScalarData, PALEOboxes.IsotopeLinear], description="disable / enable isotopes and specify isotope type"

Methods and Variables for default Parameters

  • do_reactionreservoirconstforced
    • R_conc_initial (mol m-3), VT_ReactProperty, description="initial concentration"
    • R_conc (mol m-3), VT_ReactProperty, description="concentration = initial * forcing"
    • R_FORCE (), VT_ReactDependency, description="forcing factor"
source
PALEOboxes.Reservoirs.ReactionConstType
ReactionConst, ReactionScalarConst

Create constant Property Variables with names from parameter constnames.

Initialisation

Constant values set by :initial_value, :initial_delta attributes in the variable_attributes: section of the configuration file.

Example configuration in .yaml file

    atmfloor:
+                    R_conc:initial_delta:       34.0

See also

ReactionReservoir

Parameters

  • field_data[DataType]=PALEOboxes.ScalarData, default_value=PALEOboxes.ScalarData, allowed_values=Type[PALEOboxes.ScalarData, PALEOboxes.IsotopeLinear], description="disable / enable isotopes and specify isotope type"

Methods and Variables

  • setup_initialvalue_vars_default
    • R_conc (mol m-3), VT_ReactProperty, description="concentration"
source
PALEOboxes.Reservoirs.ReactionReservoirForcedType
ReactionReservoirForced

A single (vector) constant tracer (constant replacement for a ReactionReservoir), with forcing.

Calculates R_conc = R_conc_initial * R_FORCE.

Local name prefix R should then be renamed using variable_links: in the configuration file.

Initialisation

NB: set :initial_value, :initial_delta on R_conc_initial in the variable_attributes: section of the config file.

TODO salinity normalisation.

See also

ReactionReservoirConst, ReactionReservoir

Parameters

  • field_data[DataType]=PALEOboxes.ScalarData, default_value=PALEOboxes.ScalarData, allowed_values=Type[PALEOboxes.ScalarData, PALEOboxes.IsotopeLinear], description="disable / enable isotopes and specify isotope type"

Methods and Variables for default Parameters

  • do_reactionreservoirconstforced
    • R_conc_initial (mol m-3), VT_ReactProperty, description="initial concentration"
    • R_conc (mol m-3), VT_ReactProperty, description="concentration = initial * forcing"
    • R_FORCE (), VT_ReactDependency, description="forcing factor"
source
PALEOboxes.Reservoirs.ReactionConstType
ReactionConst, ReactionScalarConst

Create constant Property Variables with names from parameter constnames.

Initialisation

Constant values set by :initial_value, :initial_delta attributes in the variable_attributes: section of the configuration file.

Example configuration in .yaml file

    atmfloor:
         reactions:                
             floorstubgasmr:  # Provide mixing-ratio boundary condition for a subset of atmospheric variables
                 class: ReactionConst
@@ -34,9 +34,9 @@
                     O2_mr:initial_value:  [0.21]  # mol/mol
                     CH4_mr:initial_value:  [0.7443e-6] # [.NaN] # [1.271e-6] # [1.8e-6]  # mol/mol
                     CO2_mr:initial_value:  [300e-6]  # mol/mol
-                    H2_mr:initial_value:   [.NaN]  # mol/mol

See also

ReactionReservoirConst, ReactionReservoirScalar. These provide additional variables (eg R_delta) to allow them to function as a drop-in replacement for a non-constant Reservoir.

Parameters

  • constnames[Vector{String}]=["constvar"], default_value=["constvar"], description="vector of names for constant Variables. Isotopes use <name>::CIsotope syntax"

Methods and Variables for default Parameters

  • setup_initialvalue_vars_default
    • constvar (unknown), VT_ReactProperty, description="constant value"
source

Linking to Reservoirs from a Reaction

PALEOboxes.Reservoirs.ReservoirLinksVectorFunction
ReservoirLinksVector(isotope_data::Dict, reservoirlist) -> (res::Vector, sms::Vector, diag::Vector)

Convenience function to create variables required for a Reaction to link to a list of Reservoir variables. res contains VariableReactions <reservoir_name>, sms <reservoir_name>_sms that link to State, State_sms variables. diag contains VariableReactions <reservoir_name>_norm etc that link to additional properties.

Arguments

  • reservoirlist::[(reservoir_name[::Isotope], units, description), ...]: list of Reservoirs
source

Variable Statistics

PALEOboxes.VariableStats.ReactionSumType
ReactionSum, ReactionVectorSum

A sum of variables (eg budget).

  • If Parameter component_to_add == 0, all components of Isotopes are included.
  • If Parameter component_to_add == component_number, a single component only is included.

Parameters

  • vars_to_add[Vector{String}]=["2\myvar", "myothervar", "-1\mythirdvar"], default_value=["2\myvar", "myothervar", "-1\mythirdvar"], description="vector of variable names to add, eg [2*myvar, myothervar, -1*mythirdvar]"
  • vars_prefix[String]="", default_value="", description="optional prefix for vars_to_add"
  • component_to_add[Int64]=0, default_value=0, description="component to add, 0 for all"
  • vectorsum[Bool]=false, default_value=false, description="true to accumulate sum into vector Variable, false to accumulate sum into scalar (adding vector cells if necessary)"

Methods and Variables for default Parameters

  • do_scalarsum
    • sum (unknown), VT_ReactProperty, description="sum of specified variables"
    • [myvar] (unknown), VT_ReactDependency, description=""
    • [myothervar] (unknown), VT_ReactDependency, description=""
    • [mythirdvar] (unknown), VT_ReactDependency, description=""
source
PALEOboxes.VariableStats.ReactionWeightedMeanType
ReactionWeightedMean

Weighted mean (eg by area or volume) of Variable

Parameters

  • field_data[DataType]=PALEOboxes.ScalarData, default_value=PALEOboxes.ScalarData, allowed_values=Type[PALEOboxes.ScalarData, PALEOboxes.IsotopeLinear], description="disable / enable isotopes and specify isotope type"

Methods and Variables

  • do_weighted_mean
    • var (unknown), VT_ReactDependency, description="variable to calculate weighted mean from"
    • measure (unknown), VT_ReactDependency, description="cell area or volume"
    • measure_total (unknown), VT_ReactDependency, description="total Domain area or volume"
    • var_mean (unknown), VT_ReactProperty, description="weighted mean over Domain area or volume"
source
PALEOboxes.VariableStats.ReactionAreaVolumeValInRangeType
ReactionAreaVolumeValInRange

Fraction of Domain area or volume with Variable in a range of values.

Parameters

  • range_min[Float64]=-Inf (mol m-3), default_value=-Inf, description="minimum value to include in frac"
  • range_max[Float64]=Inf (mol m-3), default_value=Inf, description="maximum value to include in frac"

Methods and Variables

  • do_area_volume_in_range
    • rangevar (unknown), VT_ReactDependency, description="variable to check within range"
    • measure (unknown), VT_ReactDependency, description="cell area or volume"
    • measure_total (unknown), VT_ReactDependency, description="total Domain area or volume"
    • frac (), VT_ReactProperty, description="fraction of Domain area or volume in specified range"
source

Fluxes

PALEOboxes.FluxesModule
Fluxes

Create and manage collections of Target and Contrib Variables used to define fluxes within or between Domains.

Conventions for defining biogeochemical fluxes within Domains

  • Particulate organic matter (including CaCO3) with stoichiometry Corg:N:P:Ccarb is usually transferred as: flux_list ["P", "N", "Corg::CIsotope", "Ccarb::CIsotope"] with a prefix indicating the function (eg export_).
  • Solute fluxes are usually transferred as: flux_list ["DIC::CIsotope", "TAlk", "Ca", "P", "O2", "SO4::SIsotope", "H2S::SIsotope", "CH4::CIsotope"] (where these names match the Reservoir names for the solutes), with a prefix indicating the function (usually just flux_ or soluteflux_).

Conventions for defining global fluxes between modules

The model configuration .yaml file should create a Domain for each global flux, containing one or more Fluxes.ReactionFluxTarget. Fluxes are then transferred (copied) by adding a Fluxes.ReactionFluxTransfer to each destination Domain.

Naming conventions for Earth system fluxes:

Domain nametarget prefixflux_list (illustrative, add as needed)
fluxAtoLandflux_["CO2::CIsotope", "O2"]
fluxRtoOceanflux_["DIC::CIsotope", "TAlk", "Ca", "P", "SO4::SIsotope"]
fluxOceanBurialflux_["Corg::CIsotope", "Ccarb::CIsotope", "Porg", "Pauth", "PFe", "P", "GYP::SIsotope", "PYR::SIsotope"]
fluxSedCrusttoAOceanflux_["C::CIsotope", "S::SIsotope", "Redox"]
fluxLandtoSedCrustflux_["Ccarb::CIsotope", "Corg::CIsotope", "GYP::SIsotope", "PYR::SIsotope"]
fluxOceanfloorparticulateflux_["P", "N", "Corg::CIsotope", "Ccarb::CIsotope"]
soluteflux_["DIC::CIsotope", "TAlk", "Ca", "P", "O2", "SO4::SIsotope", "H2S::SIsotope", "CH4::CIsotope"]
fluxAtmtoOceansurfaceflux_["CO2::CIsotope", "CH4::CIsotope", "O2"]
source
PALEOboxes.Fluxes.ReactionFluxTargetType
ReactionFluxTarget

Provides either a target for fluxes from fluxlist in an input Domain or a constant stub, optionally calculates totals.

For each fluxname in fluxlist, creates:

  • if const_stub==false, an input VarTarget pars.target_prefix[]*"flux_"*fluxname (or if const_stub==true, a constant VarProp).
  • if flux_totals is true, a total VarPropScalar target_prefix[]*"flux_total_"*fluxname.

Parameters

  • fluxlist[Vector{String}]=["example"], default_value=["example"], description="available fluxes"
  • target_prefix[String]="flux_", default_value="flux_", description="target names will be "<target_prefix><fluxname>", target total names will be "<target_prefix>total_<fluxname>" (where <fluxname> is an entry in fluxlist)"
  • flux_totals[Bool]=false, default_value=false, description="true to calculate flux totals (as "<target_prefix>flux_total_<fluxname>")"
  • const_stub[Bool]=false, default_value=false, description="true to provide constant flux defined by :initial_value, :initial_delta attributes on input Target Variables "<target_prefix>flux_<fluxname>""

Methods and Variables for default Parameters

  • methodfn_do_nothing
    • flux_example (mol yr-1), VT_ReactTarget, description="flux input"
source
PALEOboxes.Fluxes.ReactionFluxTransferType
ReactionFluxTransfer

Copy fluxes, optionally using transfer matrices to define cell-cell mappings if input and output fluxes are in a different Domain.

There are three common cases:

  • Transfer within a Domain, using transfer_matrix Identity
  • Transfer from a fluxXXX Domain to the Domain hosting the ReactionFluxTransfer, using transfer_matrix to define a mapping if these Domains are of different sizes.
  • Transfer from a fluxXXX Domain to the boundary cells of an interior Domain (eg ocean.oceansurface), where the Domain hosting the ReactionFluxTransfer is the corresponding boundary Domain (eg oceansurface).

Flux names

The list of flux names is generated by finding all names that match the pattern supplied to input_fluxes, so

parameters:
+                    H2_mr:initial_value:   [.NaN]  # mol/mol

See also

ReactionReservoirConst, ReactionReservoirScalar. These provide additional variables (eg R_delta) to allow them to function as a drop-in replacement for a non-constant Reservoir.

Parameters

  • constnames[Vector{String}]=["constvar"], default_value=["constvar"], description="vector of names for constant Variables. Isotopes use <name>::CIsotope syntax"

Methods and Variables for default Parameters

  • setup_initialvalue_vars_default
    • constvar (unknown), VT_ReactProperty, description="constant value"
source

Linking to Reservoirs from a Reaction

PALEOboxes.Reservoirs.ReservoirLinksVectorFunction
ReservoirLinksVector(isotope_data::Dict, reservoirlist) -> (res::Vector, sms::Vector, diag::Vector)

Convenience function to create variables required for a Reaction to link to a list of Reservoir variables. res contains VariableReactions <reservoir_name>, sms <reservoir_name>_sms that link to State, State_sms variables. diag contains VariableReactions <reservoir_name>_norm etc that link to additional properties.

Arguments

  • reservoirlist::[(reservoir_name[::Isotope], units, description), ...]: list of Reservoirs
source

Variable Statistics

PALEOboxes.VariableStats.ReactionSumType
ReactionSum, ReactionVectorSum

A sum of variables (eg budget).

  • If Parameter component_to_add == 0, all components of Isotopes are included.
  • If Parameter component_to_add == component_number, a single component only is included.

Parameters

  • vars_to_add[Vector{String}]=["2\myvar", "myothervar", "-1\mythirdvar"], default_value=["2\myvar", "myothervar", "-1\mythirdvar"], description="vector of variable names to add, eg [2*myvar, myothervar, -1*mythirdvar]"
  • vars_prefix[String]="", default_value="", description="optional prefix for vars_to_add"
  • component_to_add[Int64]=0, default_value=0, description="component to add, 0 for all"
  • vectorsum[Bool]=false, default_value=false, description="true to accumulate sum into vector Variable, false to accumulate sum into scalar (adding vector cells if necessary)"

Methods and Variables for default Parameters

  • do_scalarsum
    • sum (unknown), VT_ReactProperty, description="sum of specified variables"
    • [myvar] (unknown), VT_ReactDependency, description=""
    • [myothervar] (unknown), VT_ReactDependency, description=""
    • [mythirdvar] (unknown), VT_ReactDependency, description=""
source
PALEOboxes.VariableStats.ReactionWeightedMeanType
ReactionWeightedMean

Weighted mean (eg by area or volume) of Variable

Parameters

  • field_data[DataType]=PALEOboxes.ScalarData, default_value=PALEOboxes.ScalarData, allowed_values=Type[PALEOboxes.ScalarData, PALEOboxes.IsotopeLinear], description="disable / enable isotopes and specify isotope type"

Methods and Variables

  • do_weighted_mean
    • var (unknown), VT_ReactDependency, description="variable to calculate weighted mean from"
    • measure (unknown), VT_ReactDependency, description="cell area or volume"
    • measure_total (unknown), VT_ReactDependency, description="total Domain area or volume"
    • var_mean (unknown), VT_ReactProperty, description="weighted mean over Domain area or volume"
source
PALEOboxes.VariableStats.ReactionAreaVolumeValInRangeType
ReactionAreaVolumeValInRange

Fraction of Domain area or volume with Variable in a range of values.

Parameters

  • range_min[Float64]=-Inf (mol m-3), default_value=-Inf, description="minimum value to include in frac"
  • range_max[Float64]=Inf (mol m-3), default_value=Inf, description="maximum value to include in frac"

Methods and Variables

  • do_area_volume_in_range
    • rangevar (unknown), VT_ReactDependency, description="variable to check within range"
    • measure (unknown), VT_ReactDependency, description="cell area or volume"
    • measure_total (unknown), VT_ReactDependency, description="total Domain area or volume"
    • frac (), VT_ReactProperty, description="fraction of Domain area or volume in specified range"
source

Fluxes

PALEOboxes.FluxesModule
Fluxes

Create and manage collections of Target and Contrib Variables used to define fluxes within or between Domains.

Conventions for defining biogeochemical fluxes within Domains

  • Particulate organic matter (including CaCO3) with stoichiometry Corg:N:P:Ccarb is usually transferred as: flux_list ["P", "N", "Corg::CIsotope", "Ccarb::CIsotope"] with a prefix indicating the function (eg export_).
  • Solute fluxes are usually transferred as: flux_list ["DIC::CIsotope", "TAlk", "Ca", "P", "O2", "SO4::SIsotope", "H2S::SIsotope", "CH4::CIsotope"] (where these names match the Reservoir names for the solutes), with a prefix indicating the function (usually just flux_ or soluteflux_).

Conventions for defining global fluxes between modules

The model configuration .yaml file should create a Domain for each global flux, containing one or more Fluxes.ReactionFluxTarget. Fluxes are then transferred (copied) by adding a Fluxes.ReactionFluxTransfer to each destination Domain.

Naming conventions for Earth system fluxes:

Domain nametarget prefixflux_list (illustrative, add as needed)
fluxAtoLandflux_["CO2::CIsotope", "O2"]
fluxRtoOceanflux_["DIC::CIsotope", "TAlk", "Ca", "P", "SO4::SIsotope"]
fluxOceanBurialflux_["Corg::CIsotope", "Ccarb::CIsotope", "Porg", "Pauth", "PFe", "P", "GYP::SIsotope", "PYR::SIsotope"]
fluxSedCrusttoAOceanflux_["C::CIsotope", "S::SIsotope", "Redox"]
fluxLandtoSedCrustflux_["Ccarb::CIsotope", "Corg::CIsotope", "GYP::SIsotope", "PYR::SIsotope"]
fluxOceanfloorparticulateflux_["P", "N", "Corg::CIsotope", "Ccarb::CIsotope"]
soluteflux_["DIC::CIsotope", "TAlk", "Ca", "P", "O2", "SO4::SIsotope", "H2S::SIsotope", "CH4::CIsotope"]
fluxAtmtoOceansurfaceflux_["CO2::CIsotope", "CH4::CIsotope", "O2"]
source
PALEOboxes.Fluxes.ReactionFluxTargetType
ReactionFluxTarget

Provides either a target for fluxes from fluxlist in an input Domain or a constant stub, optionally calculates totals.

For each fluxname in fluxlist, creates:

  • if const_stub==false, an input VarTarget pars.target_prefix[]*"flux_"*fluxname (or if const_stub==true, a constant VarProp).
  • if flux_totals is true, a total VarPropScalar target_prefix[]*"flux_total_"*fluxname.

Parameters

  • fluxlist[Vector{String}]=["example"], default_value=["example"], description="available fluxes"
  • target_prefix[String]="flux_", default_value="flux_", description="target names will be "<target_prefix><fluxname>", target total names will be "<target_prefix>total_<fluxname>" (where <fluxname> is an entry in fluxlist)"
  • flux_totals[Bool]=false, default_value=false, description="true to calculate flux totals (as "<target_prefix>flux_total_<fluxname>")"
  • const_stub[Bool]=false, default_value=false, description="true to provide constant flux defined by :initial_value, :initial_delta attributes on input Target Variables "<target_prefix>flux_<fluxname>""

Methods and Variables for default Parameters

  • methodfn_do_nothing
    • flux_example (mol yr-1), VT_ReactTarget, description="flux input"
source
PALEOboxes.Fluxes.ReactionFluxTransferType
ReactionFluxTransfer

Copy fluxes, optionally using transfer matrices to define cell-cell mappings if input and output fluxes are in a different Domain.

There are three common cases:

  • Transfer within a Domain, using transfer_matrix Identity
  • Transfer from a fluxXXX Domain to the Domain hosting the ReactionFluxTransfer, using transfer_matrix to define a mapping if these Domains are of different sizes.
  • Transfer from a fluxXXX Domain to the boundary cells of an interior Domain (eg ocean.oceansurface), where the Domain hosting the ReactionFluxTransfer is the corresponding boundary Domain (eg oceansurface).

Flux names

The list of flux names is generated by finding all names that match the pattern supplied to input_fluxes, so

parameters:
     input_fluxes:  fluxAtmtoOceansurface.flux_$fluxname$
-    output_fluxes:  ocean.oceansurface.$fluxname$_sms

will:

  1. Match eg fluxAtmtoOceansurface.flux_CO2, fluxAtmtoOceansurface.flux_O2 and generate names CO2, O2.
  2. Generate variables with Reaction-local names input_CO2, input_O2, and link names configured to link to the input fluxes
  3. Generate variables with Reaction-local names output_CO2, output_O2, and link names configured to link to the output flux names generated by substituting $fluxname$ in output_fluxes.

This handles the common case eg O2 where the names of the input and output fluxes match. However, if they don't match, eg the input flux is called CO2 and the output flux should be applied to DIC, then it is necessary to use variable_links: to change the link name for output_CO2 to DIC.

Parameters

  • input_fluxes[String]="[inputdomain.][inputsubdomain.]flux_$fluxname$", default_value="[inputdomain.][inputsubdomain.]flux_$fluxname$", description="string to match to find input flux Variables. These Variables will local names "input_$fluxname$"."
  • output_fluxes[String]="[outputdomain.][outputsubdomain.]$fluxname$_sms", default_value="[outputdomain.][outputsubdomain.]$fluxname$_sms", description="string to use to generate output flux Variables where $fluxname$ is substituted from input_fluxes. These Variables will local names "output_$fluxname$", and are optional (ie ignored if not linked). Usually the output Domain is the Domain hosting the ReactionFluxTransfer (in general, it must be a Domain of the same size as the Domain hosting the ReactionFluxTransfer)."
  • transfer_multiplier[Float64]=1.0, default_value=1.0, description="scalar multiplier for transfer"
  • transfer_matrix[String]="Identity", default_value="Identity", allowed_values=["Identity", "Distribute", "Custom"], description="matrix defining input Domain (length n) -> output Domain (length m) mapping: 'Identity' copies fluxes directly, requires m == n; 'Distribute' uniformly distributes fluxes from input->output: sums over n and them distributes fraction 1/m evenly to each m; 'Custom' requires transfer matrix to be supplied"
source

Contributing to flux couplers from a Reaction

PALEOboxes.Fluxes.FluxContribFunction
FluxContrib(
+    output_fluxes:  ocean.oceansurface.$fluxname$_sms

will:

  1. Match eg fluxAtmtoOceansurface.flux_CO2, fluxAtmtoOceansurface.flux_O2 and generate names CO2, O2.
  2. Generate variables with Reaction-local names input_CO2, input_O2, and link names configured to link to the input fluxes
  3. Generate variables with Reaction-local names output_CO2, output_O2, and link names configured to link to the output flux names generated by substituting $fluxname$ in output_fluxes.

This handles the common case eg O2 where the names of the input and output fluxes match. However, if they don't match, eg the input flux is called CO2 and the output flux should be applied to DIC, then it is necessary to use variable_links: to change the link name for output_CO2 to DIC.

Parameters

  • input_fluxes[String]="[inputdomain.][inputsubdomain.]flux_$fluxname$", default_value="[inputdomain.][inputsubdomain.]flux_$fluxname$", description="string to match to find input flux Variables. These Variables will local names "input_$fluxname$"."
  • output_fluxes[String]="[outputdomain.][outputsubdomain.]$fluxname$_sms", default_value="[outputdomain.][outputsubdomain.]$fluxname$_sms", description="string to use to generate output flux Variables where $fluxname$ is substituted from input_fluxes. These Variables will local names "output_$fluxname$", and are optional (ie ignored if not linked). Usually the output Domain is the Domain hosting the ReactionFluxTransfer (in general, it must be a Domain of the same size as the Domain hosting the ReactionFluxTransfer)."
  • transfer_multiplier[Float64]=1.0, default_value=1.0, description="scalar multiplier for transfer"
  • transfer_matrix[String]="Identity", default_value="Identity", allowed_values=["Identity", "Distribute", "Custom"], description="matrix defining input Domain (length n) -> output Domain (length m) mapping: 'Identity' copies fluxes directly, requires m == n; 'Distribute' uniformly distributes fluxes from input->output: sums over n and them distributes fraction 1/m evenly to each m; 'Custom' requires transfer matrix to be supplied"
source

Contributing to flux couplers from a Reaction

PALEOboxes.Fluxes.FluxContribFunction
FluxContrib(
     fluxprefix::AbstractString, flux_list;
     [, isotope_data::Dict]
     [, space=PB.CellSpace][, alloptional=true]
@@ -52,4 +52,4 @@
 PALEOboxes.VariableReaction{PALEOboxes.VT_ReactContributor}
   localname='fluxRtoOcean_flux_SO4'
   link_name='fluxRtoOcean.flux_SO4[unlinked]'
-  attributes=Dict{Symbol, Any}(:description => "flux SO4", :space => PALEOboxes.ScalarSpace, :standard_variable => false, :norm_value => 1.0, :data_dims => String[], :long_name => "", :vfunction => PALEOboxes.VF_Undefined, :field_data => PALEOboxes.IsotopeLinear, :initial_delta => 0.0, :units => "mol yr-1"…)
source

Forcings

PALEOboxes.Forcings.ReactionForceInterpType
ReactionForceInterp

Provide a scalar Property F, linearly interpolated from a table of values vs time tforce.

The table of values is set by parameters force_times and force_values.

The input time Variable is tforce, with default linking to the global.tforce Variable.

Use the configuration file to rename the output variable F (and if necessary, the input Variable tforce).

Set extrapolate = "extrapolate" to use extrapolate_before, extrapolate_after to set constant values when 'tforce' is out-of-range of force_times (or alternatively, set extrapolate = "throw" and use guard values for force_times at -1e30, 1e30).

Parameters

  • force_times[Vector{Float64}]=[-1.0e30, 1.0e30] (yr), default_value=[-1.0e30, 1.0e30], description="interpolated forcing times"
  • force_values[Vector{Float64}]=[1.0, 1.0], default_value=[1.0, 1.0], description="interpolated forcing values"
  • extrapolate[String]="throw", default_value="throw", allowed_values=["throw", "constant"], description="behaviour if tforce is out of range"
  • extrapolate_before[Float64]=NaN, default_value=NaN, description="value to use if 'extrapolate=constant' and tforce < first(perturb_times)"
  • extrapolate_after[Float64]=NaN, default_value=NaN, description="value to use if 'extrapolate=constant' and tforce > last(perturb_times)"

Methods and Variables

  • do_forceinterp
    • tforce –> global.tforce (yr), VT_ReactDependency, description="historical time at which to apply forcings, present = 0 yr"
    • F (), VT_ReactProperty, description="interpolated forcing"
source
PALEOboxes.GridForcings.ReactionForceGridType
ReactionForceGrid

Apply time-dependent, periodic forcing from a variable in a netcdf or Matlab file, optionally applying a scaling, a constant linear offset, and a linear offset generated from a scalar model variable.

Reads records tidx_start:tidx_end (assumed to be the last dimension) for data_var from a gridded dataset in netcdf_file or matlab_file, maps grid to linear using the Domain grid (which must match that of data_var).

If tidx_end > tidx_start (ie multiple records), reads a netcdf or Matlab variable named time_var, applies periodicity cycle_time, and uses this to linearly interpolate to model time.

Then applies forcing:

F = scale*`data_var` + constant_offset + scale_offset_var*`scalar_offset_var`

Optionally (if interp_vars is non-empty), interpolate forcing from additional dimensions in the netcdf file, given values supplied by additional Variable dependencies. NB: netcdf dimensions order must be grid_vars x interp_varsxtimevar, where order withininterpvars` also must match netcdf order.

Parameters

  • netcdf_file[String]="", default_value="", description="netcdf file with gridded time-series data"
  • matlab_file[String]="", default_value="", description="matlab file with gridded time-series data"
  • matlab_key[String]="", default_value="", description="Dictionary key in Matlab file to use (empty string to stay at top level Dict)"
  • data_var[String]="", default_value="", description="variable name in data file"
  • time_var[String]="time", default_value="time", description="time variable name in data file (empty to generate evenly spaced times from cycle_time)"
  • time_fac[Float64]=1.0, default_value=1.0, description="multiplier to convert time_var to model time (yr)"
  • tidx_start[Int64]=1, default_value=1, description="first record in data file to use"
  • tidx_end[Int64]=1, default_value=1, description="last record in data file to use (set equal to tidx_start for constant forcing from single record)"
  • use_timeav[Bool]=false, default_value=false, description="true to average records and provide constant forcing at time-averaged value"
  • time_extrap_const[Bool]=false, default_value=false, description="true to extrapolate out-of-range times to first/last value, false to error if time out-of-range"
  • cycle_time[Float64]=0.0 (yr), default_value=0.0, description="time periodicity to apply (0.0 to disable periodic)"
  • interp_vars[Vector{String}]=String[], default_value=String[], description="optional interpolation variables for additional grid dimensions. NB: netcdf dimensions order must be grid_vars x interp_vars x time_var, where order within interp_vars also must match netcdf order"
  • interp_log[Vector{Bool}]=Bool[], default_value=Bool[], description="true to interpolate interp_vars in log space"
  • data_replace_nan[Float64]=NaN, default_value=NaN, description="value to replace NaN in data"
  • scale[Float64]=1.0, default_value=1.0, description="scaling factor to apply"
  • constant_offset[Float64]=0.0, default_value=0.0, description="constant offset to apply"
  • scale_offset_var[Float64]=0.0, default_value=0.0, description="scaling for additional scalar offset from model variable (0.0 to disable)"

Methods and Variables for default Parameters

  • do_force_grid
    • tforce –> global.tforce (yr), VT_ReactDependency, description="historical time at which to apply forcings, present = 0 yr"
    • F (unknown), VT_ReactProperty, description="interpolated forcing"
source
PALEOboxes.FluxPerturb.ReactionFluxPerturbType
ReactionFluxPerturb

Provide a scalar flux F, linearly interpolated from a table of values vs time tforce.

The table of values is set by parameters perturb_times and perturb_totals, and optionally perturb_deltas.

The input time Variable is tforce, with default linking to the global.tforce Variable.

Use the configuration file to rename output variable F (and if necessary, the input Variable tforce).

Set extrapolate = "extrapolate" to use extrapolate_before, extrapolate_after to set constant values when 'tforce' is out-of-range of perturb_times (or alternatively, set extrapolate = "throw" and use guard values for perturb_times at -1e30, 1e30).

Parameters

  • field_data[DataType]=PALEOboxes.ScalarData, default_value=PALEOboxes.ScalarData, allowed_values=Type[PALEOboxes.ScalarData, PALEOboxes.IsotopeLinear], description="disable / enable isotopes and specify isotope type"
  • perturb_times[Vector{Float64}]=[-1.0e30, 1.0e30] (yr), default_value=[-1.0e30, 1.0e30], description="interpolated perturbation times"
  • perturb_totals[Vector{Float64}]=[1.0, 1.0] (mol yr-1), default_value=[1.0, 1.0], description="interpolated perturbation totals"
  • perturb_deltas[Vector{Float64}]=[0.0, 0.0] (per mil), default_value=[0.0, 0.0], description="interpolated perturbation deltas"
  • extrapolate[String]="throw", default_value="throw", allowed_values=["throw", "constant"], description="behaviour if tforce is out of range"
  • extrapolate_before[Float64]=NaN, default_value=NaN, description="value to use if 'extrapolate=constant' and tforce < first(perturb_times)"
  • extrapolate_before_delta[Float64]=NaN, default_value=NaN, description="value to use if 'extrapolate=constant' and tforce < first(perturb_times)"
  • extrapolate_after[Float64]=NaN, default_value=NaN, description="value to use if 'extrapolate=constant' and tforce > last(perturb_times)"
  • extrapolate_after_delta[Float64]=NaN, default_value=NaN, description="value to use if 'extrapolate=constant' and tforce > last(perturb_times)"

Methods and Variables

  • do_flux_perturb
    • tforce –> global.tforce (yr), VT_ReactDependency, description="time at which to apply perturbation"
    • F (mol yr-1), VT_ReactContributor, description="interpolated flux perturbation"
    • FApplied –> %reaction%FApplied (mol yr-1), VT_ReactProperty, description="flux perturbation applied, for diagnostic output"
source
PALEOboxes.FluxPerturb.ReactionRestoreType
ReactionRestore

Adds RestoringFlux in response to discrepancy between Variable WatchLevel and Parameter RequiredLevel

Parameters

  • field_data[DataType]=PALEOboxes.ScalarData, default_value=PALEOboxes.ScalarData, allowed_values=Type[PALEOboxes.ScalarData, PALEOboxes.IsotopeLinear], description="disable / enable isotopes and specify isotope type"
  • RequiredLevel[Float64]=0.0 (mol), default_value=0.0, description="target value of WatchLevel"
  • trestore[Float64]=1.0 (yr), default_value=1.0, description="restoring timescale"
  • RequiredDelta[Float64]=0.0 (per mil), default_value=0.0, description="target value of WatchLevel delta"
  • source_only[Bool]=false, default_value=false, description="false to allow input and output, true to allow input only"

Methods and Variables

  • do_restore
    • WatchLevel (mol), VT_ReactDependency, description="level to observe and restore"
    • RestoringFlux (mol yr-1), VT_ReactContributor, description="restoring flux"
    • RestoringApplied –> %reaction%RestoringApplied (mol yr-1), VT_ReactProperty, description="restoring flux for diagnostic output"
source

Grids

Minimal generic model grids for test purposes.

These just define the Domain size, and don't provide coordinate or metric information (cell volume, area). Models will usually require a Reaction with a Domain-specific implementation (eg for ocean, atmosphere) that defines coordinates and volumes etc and also implements transport (advection, eddy diffusion, etc).

PALEOboxes.GridReactions.ReactionUnstructuredVectorGridType
ReactionUnstructuredVectorGrid

Create an PB.Grids.UnstructuredVectorGrid with ncells (from ncells Parameter).

Parameters

  • ncells[Int64]=1, default_value=1, description="number of grid cells"
source
PALEOboxes.GridReactions.ReactionCartesianGridType
ReactionCartesianGrid

Create a PB.Grids.CartesianArrayGrid with dims and dimnames`

Parameters

  • dimnames[Vector{String}]=["lat", "lon", "z"], default_value=["lat", "lon", "z"], description="grid dimension names"
  • dims[Vector{Int64}]=[2, 3, 4], default_value=[2, 3, 4], description="grid dimensions"
source
PALEOboxes.GridReactions.ReactionGrid2DNetCDFType
ReactionGrid2DNetCDF

Create a 2D PB.Grids.CartesianLinearGrid from grid information in a NetCDF file.

Parameters

  • grid_type[UnionAll]=PALEOboxes.Grids.CartesianArrayGrid, default_value=PALEOboxes.Grids.CartesianArrayGrid, allowed_values=Type[PALEOboxes.Grids.CartesianArrayGrid, PALEOboxes.Grids.CartesianLinearGrid], description="Cartesian grid type to create"
  • grid_file[String]="", default_value="", description="netcdf file with 2D grid information"
  • coordinate_names[Vector{String}]=["longitude", "latitude"], default_value=["longitude", "latitude"], description="coordinate names to read from netcdf file"
  • equalspacededges[Bool]=false, default_value=false, description="true to calculate cell edges assuming an equal-spaced grid"
  • area_var[String]="", default_value="", description="netcdf variable with cell area (if available)"
  • planet_radius[Float64]=6.371229e6, default_value=6.371229e6, description="radius to calculate cell area from spherical geometry (if area_var = "")"

Methods

  • setup_grid_2DNetCDF
    • Asurf (m^2), VT_ReactProperty, description="horizontal area of surface"
    • Asurf_total (m^2), VT_ReactProperty, description="total horizontal area of surface"
source
+ attributes=Dict{Symbol, Any}(:description => "flux SO4", :space => PALEOboxes.ScalarSpace, :standard_variable => false, :norm_value => 1.0, :data_dims => String[], :long_name => "", :vfunction => PALEOboxes.VF_Undefined, :field_data => PALEOboxes.IsotopeLinear, :initial_delta => 0.0, :units => "mol yr-1"…)source

Forcings

PALEOboxes.Forcings.ReactionForceInterpType
ReactionForceInterp

Provide a scalar Property F, linearly interpolated from a table of values vs time tforce.

The table of values is set by parameters force_times and force_values.

The input time Variable is tforce, with default linking to the global.tforce Variable.

Use the configuration file to rename the output variable F (and if necessary, the input Variable tforce).

Set extrapolate = "extrapolate" to use extrapolate_before, extrapolate_after to set constant values when 'tforce' is out-of-range of force_times (or alternatively, set extrapolate = "throw" and use guard values for force_times at -1e30, 1e30).

Parameters

  • force_times[Vector{Float64}]=[-1.0e30, 1.0e30] (yr), default_value=[-1.0e30, 1.0e30], description="interpolated forcing times"
  • force_values[Vector{Float64}]=[1.0, 1.0], default_value=[1.0, 1.0], description="interpolated forcing values"
  • extrapolate[String]="throw", default_value="throw", allowed_values=["throw", "constant"], description="behaviour if tforce is out of range"
  • extrapolate_before[Float64]=NaN, default_value=NaN, description="value to use if 'extrapolate=constant' and tforce < first(perturb_times)"
  • extrapolate_after[Float64]=NaN, default_value=NaN, description="value to use if 'extrapolate=constant' and tforce > last(perturb_times)"

Methods and Variables

  • do_forceinterp
    • tforce –> global.tforce (yr), VT_ReactDependency, description="historical time at which to apply forcings, present = 0 yr"
    • F (), VT_ReactProperty, description="interpolated forcing"
source
PALEOboxes.GridForcings.ReactionForceGridType
ReactionForceGrid

Apply time-dependent, periodic forcing from a variable in a netcdf or Matlab file, optionally applying a scaling, a constant linear offset, and a linear offset generated from a scalar model variable.

Reads records tidx_start:tidx_end (assumed to be the last dimension) for data_var from a gridded dataset in netcdf_file or matlab_file, maps grid to linear using the Domain grid (which must match that of data_var).

If tidx_end > tidx_start (ie multiple records), reads a netcdf or Matlab variable named time_var, applies periodicity cycle_time, and uses this to linearly interpolate to model time.

Then applies forcing:

F = scale*`data_var` + constant_offset + scale_offset_var*`scalar_offset_var`

Optionally (if interp_vars is non-empty), interpolate forcing from additional dimensions in the netcdf file, given values supplied by additional Variable dependencies. NB: netcdf dimensions order must be grid_vars x interp_varsxtimevar, where order withininterpvars` also must match netcdf order.

Parameters

  • netcdf_file[String]="", default_value="", description="netcdf file with gridded time-series data"
  • matlab_file[String]="", default_value="", description="matlab file with gridded time-series data"
  • matlab_key[String]="", default_value="", description="Dictionary key in Matlab file to use (empty string to stay at top level Dict)"
  • data_var[String]="", default_value="", description="variable name in data file"
  • time_var[String]="time", default_value="time", description="time variable name in data file (empty to generate evenly spaced times from cycle_time)"
  • time_fac[Float64]=1.0, default_value=1.0, description="multiplier to convert time_var to model time (yr)"
  • tidx_start[Int64]=1, default_value=1, description="first record in data file to use"
  • tidx_end[Int64]=1, default_value=1, description="last record in data file to use (set equal to tidx_start for constant forcing from single record)"
  • use_timeav[Bool]=false, default_value=false, description="true to average records and provide constant forcing at time-averaged value"
  • time_extrap_const[Bool]=false, default_value=false, description="true to extrapolate out-of-range times to first/last value, false to error if time out-of-range"
  • cycle_time[Float64]=0.0 (yr), default_value=0.0, description="time periodicity to apply (0.0 to disable periodic)"
  • interp_vars[Vector{String}]=String[], default_value=String[], description="optional interpolation variables for additional grid dimensions. NB: netcdf dimensions order must be grid_vars x interp_vars x time_var, where order within interp_vars also must match netcdf order"
  • interp_log[Vector{Bool}]=Bool[], default_value=Bool[], description="true to interpolate interp_vars in log space"
  • data_replace_nan[Float64]=NaN, default_value=NaN, description="value to replace NaN in data"
  • scale[Float64]=1.0, default_value=1.0, description="scaling factor to apply"
  • constant_offset[Float64]=0.0, default_value=0.0, description="constant offset to apply"
  • scale_offset_var[Float64]=0.0, default_value=0.0, description="scaling for additional scalar offset from model variable (0.0 to disable)"

Methods and Variables for default Parameters

  • do_force_grid
    • tforce –> global.tforce (yr), VT_ReactDependency, description="historical time at which to apply forcings, present = 0 yr"
    • F (unknown), VT_ReactProperty, description="interpolated forcing"
source
PALEOboxes.FluxPerturb.ReactionFluxPerturbType
ReactionFluxPerturb

Provide a scalar flux F, linearly interpolated from a table of values vs time tforce.

The table of values is set by parameters perturb_times and perturb_totals, and optionally perturb_deltas.

The input time Variable is tforce, with default linking to the global.tforce Variable.

Use the configuration file to rename output variable F (and if necessary, the input Variable tforce).

Set extrapolate = "extrapolate" to use extrapolate_before, extrapolate_after to set constant values when 'tforce' is out-of-range of perturb_times (or alternatively, set extrapolate = "throw" and use guard values for perturb_times at -1e30, 1e30).

Parameters

  • field_data[DataType]=PALEOboxes.ScalarData, default_value=PALEOboxes.ScalarData, allowed_values=Type[PALEOboxes.ScalarData, PALEOboxes.IsotopeLinear], description="disable / enable isotopes and specify isotope type"
  • perturb_times[Vector{Float64}]=[-1.0e30, 1.0e30] (yr), default_value=[-1.0e30, 1.0e30], description="interpolated perturbation times"
  • perturb_totals[Vector{Float64}]=[1.0, 1.0] (mol yr-1), default_value=[1.0, 1.0], description="interpolated perturbation totals"
  • perturb_deltas[Vector{Float64}]=[0.0, 0.0] (per mil), default_value=[0.0, 0.0], description="interpolated perturbation deltas"
  • extrapolate[String]="throw", default_value="throw", allowed_values=["throw", "constant"], description="behaviour if tforce is out of range"
  • extrapolate_before[Float64]=NaN, default_value=NaN, description="value to use if 'extrapolate=constant' and tforce < first(perturb_times)"
  • extrapolate_before_delta[Float64]=NaN, default_value=NaN, description="value to use if 'extrapolate=constant' and tforce < first(perturb_times)"
  • extrapolate_after[Float64]=NaN, default_value=NaN, description="value to use if 'extrapolate=constant' and tforce > last(perturb_times)"
  • extrapolate_after_delta[Float64]=NaN, default_value=NaN, description="value to use if 'extrapolate=constant' and tforce > last(perturb_times)"

Methods and Variables

  • do_flux_perturb
    • tforce –> global.tforce (yr), VT_ReactDependency, description="time at which to apply perturbation"
    • F (mol yr-1), VT_ReactContributor, description="interpolated flux perturbation"
    • FApplied –> %reaction%FApplied (mol yr-1), VT_ReactProperty, description="flux perturbation applied, for diagnostic output"
source
PALEOboxes.FluxPerturb.ReactionRestoreType
ReactionRestore

Adds RestoringFlux in response to discrepancy between Variable WatchLevel and Parameter RequiredLevel

Parameters

  • field_data[DataType]=PALEOboxes.ScalarData, default_value=PALEOboxes.ScalarData, allowed_values=Type[PALEOboxes.ScalarData, PALEOboxes.IsotopeLinear], description="disable / enable isotopes and specify isotope type"
  • RequiredLevel[Float64]=0.0 (mol), default_value=0.0, description="target value of WatchLevel"
  • trestore[Float64]=1.0 (yr), default_value=1.0, description="restoring timescale"
  • RequiredDelta[Float64]=0.0 (per mil), default_value=0.0, description="target value of WatchLevel delta"
  • source_only[Bool]=false, default_value=false, description="false to allow input and output, true to allow input only"

Methods and Variables

  • do_restore
    • WatchLevel (mol), VT_ReactDependency, description="level to observe and restore"
    • RestoringFlux (mol yr-1), VT_ReactContributor, description="restoring flux"
    • RestoringApplied –> %reaction%RestoringApplied (mol yr-1), VT_ReactProperty, description="restoring flux for diagnostic output"
source

Grids

Minimal generic model grids for test purposes.

These just define the Domain size, and don't provide coordinate or metric information (cell volume, area). Models will usually require a Reaction with a Domain-specific implementation (eg for ocean, atmosphere) that defines coordinates and volumes etc and also implements transport (advection, eddy diffusion, etc).

PALEOboxes.GridReactions.ReactionUnstructuredVectorGridType
ReactionUnstructuredVectorGrid

Create an PB.Grids.UnstructuredVectorGrid with ncells (from ncells Parameter).

Parameters

  • ncells[Int64]=1, default_value=1, description="number of grid cells"
source
PALEOboxes.GridReactions.ReactionCartesianGridType
ReactionCartesianGrid

Create a PB.Grids.CartesianArrayGrid with dims and dimnames`

Parameters

  • dimnames[Vector{String}]=["lat", "lon", "z"], default_value=["lat", "lon", "z"], description="grid dimension names"
  • dims[Vector{Int64}]=[2, 3, 4], default_value=[2, 3, 4], description="grid dimensions"
source
PALEOboxes.GridReactions.ReactionGrid2DNetCDFType
ReactionGrid2DNetCDF

Create a 2D PB.Grids.CartesianLinearGrid from grid information in a NetCDF file.

Parameters

  • grid_type[UnionAll]=PALEOboxes.Grids.CartesianArrayGrid, default_value=PALEOboxes.Grids.CartesianArrayGrid, allowed_values=Type[PALEOboxes.Grids.CartesianArrayGrid, PALEOboxes.Grids.CartesianLinearGrid], description="Cartesian grid type to create"
  • grid_file[String]="", default_value="", description="netcdf file with 2D grid information"
  • coordinate_names[Vector{String}]=["longitude", "latitude"], default_value=["longitude", "latitude"], description="coordinate names to read from netcdf file"
  • equalspacededges[Bool]=false, default_value=false, description="true to calculate cell edges assuming an equal-spaced grid"
  • area_var[String]="", default_value="", description="netcdf variable with cell area (if available)"
  • planet_radius[Float64]=6.371229e6, default_value=6.371229e6, description="radius to calculate cell area from spherical geometry (if area_var = "")"

Methods

  • setup_grid_2DNetCDF
    • Asurf (m^2), VT_ReactProperty, description="horizontal area of surface"
    • Asurf_total (m^2), VT_ReactProperty, description="total horizontal area of surface"
source
diff --git a/dev/References/index.html b/dev/References/index.html index 4797769..b82c150 100644 --- a/dev/References/index.html +++ b/dev/References/index.html @@ -1,2 +1,2 @@ -References · PALEOboxes Documentation
+References · PALEOboxes Documentation
diff --git a/dev/Solver API/index.html b/dev/Solver API/index.html index ad6c992..86974d3 100644 --- a/dev/Solver API/index.html +++ b/dev/Solver API/index.html @@ -8,31 +8,31 @@ config_files, configmodel::AbstractString; modelpars::Dict = Dict() -) -> model::Model

Construct model from a single YAML config_file, or from a collection of config_files, which are read in order and concatenated before being parsed as yaml.

Optional argument modelpars provides parameters that override those in <configmodel>: parameters: section.

source
PALEOboxes.check_variable_linksFunction
check_variable_links(model, modeldata; [throw_on_error=true] [, expect_hostdep_varnames=["global.tforce"]]) -> links_ok::Bool

Check all Variables linked correctly, by checking that there are no unexpected host-dependent non-state Variables (ie unlinked Variables)

source
PALEOboxes.create_modeldataFunction
create_modeldata(model::Model [, eltype] [; threadsafe]) -> modeldata::ModelData

Create a new ModelData struct for model variables of element type eltype.

source
PALEOboxes.ModelDataType
ModelData(model::Model; arrays_eltype::DataType=Float64, threadsafe::Bool=false, allocatenans::Bool=true)

Create a ModelData struct containing model data arrays.

One set of data arrays is created with eltype=arrays_eltype, accessed with arrays_idx=1

Additional sets of data arrays may be added by push_arrays_data!, eg in order to support automatic differentiation which requires Dual numbers as the array element type.

Fields

  • cellranges_all::Vector{AbstractCellRange}: default cellranges covering all domains
  • dispatchlists_all: default dispatchlists covering all domains
  • solver_view_all: optional untyped context field for use by external solvers.
source
PALEOboxes.add_arrays_data!Function
add_arrays_data!(
+) -> model::Model

Construct model from a single YAML config_file, or from a collection of config_files, which are read in order and concatenated before being parsed as yaml.

Optional argument modelpars provides parameters that override those in <configmodel>: parameters: section.

source
PALEOboxes.check_variable_linksFunction
check_variable_links(model, modeldata; [throw_on_error=true] [, expect_hostdep_varnames=["global.tforce"]]) -> links_ok::Bool

Check all Variables linked correctly, by checking that there are no unexpected host-dependent non-state Variables (ie unlinked Variables)

source
PALEOboxes.create_modeldataFunction
create_modeldata(model::Model [, eltype] [; threadsafe]) -> modeldata::ModelData

Create a new ModelData struct for model variables of element type eltype.

source
PALEOboxes.ModelDataType
ModelData(model::Model; arrays_eltype::DataType=Float64, threadsafe::Bool=false, allocatenans::Bool=true)

Create a ModelData struct containing model data arrays.

One set of data arrays is created with eltype=arrays_eltype, accessed with arrays_idx=1

Additional sets of data arrays may be added by push_arrays_data!, eg in order to support automatic differentiation which requires Dual numbers as the array element type.

Fields

  • cellranges_all::Vector{AbstractCellRange}: default cellranges covering all domains
  • dispatchlists_all: default dispatchlists covering all domains
  • solver_view_all: optional untyped context field for use by external solvers.
source
PALEOboxes.add_arrays_data!Function
add_arrays_data!(
     model, modeldata, arrays_eltype::DataType, arrays_tagname::AbstractString;
-    [method_barrier=nothing] [, generated_dispatch=true] [, kwargs...])

Add a data array set to modeldata, allocate memory, and initialize reactiondata.

Element type and tag name are set by arrays_eltype, arrays_tagname

See allocate_variables!(model::Model, modeldata::AbstractModelData, arrays_idx::Int) and [initialize_reactiondata!] for keyword arguments.

source
PALEOboxes.push_arrays_data!Function
push_arrays_data!(modeldata, arrays_eltype::DataType, arrays_tagname::AbstractString)

Add an (unallocated) additional array set with element type arrays_eltype.

source
PALEOboxes.allocate_variables!Function
allocate_variables!(
+    [method_barrier=nothing] [, generated_dispatch=true] [, kwargs...])

Add a data array set to modeldata, allocate memory, and initialize reactiondata.

Element type and tag name are set by arrays_eltype, arrays_tagname

See allocate_variables!(model::Model, modeldata::AbstractModelData, arrays_idx::Int) and [initialize_reactiondata!] for keyword arguments.

source
PALEOboxes.push_arrays_data!Function
push_arrays_data!(modeldata, arrays_eltype::DataType, arrays_tagname::AbstractString)

Add an (unallocated) additional array set with element type arrays_eltype.

source
PALEOboxes.allocate_variables!Function
allocate_variables!(
     vars, modeldata, arrays_idx; 
     [, eltypemap::Dict{String, DataType}],
     [, default_host_dependent_field_data=nothing],
     [, allow_base_link=true],
     [. use_base_transfer_jacobian=true],
     [, use_base_vars=String[]],
-    [, check_units_opt=:no])

Allocate or link memory for VariableDomains vars in modeldata array set arrays_idx

Element type of allocated Arrays is determined by eltype(modeldata, arrays_idx) (the usual case, allowing use of AD types), which can be overridden by Variable :datatype attribute if present (allowing Variables to ignore AD types). :datatype may be either a Julia DataType (eg Float64), or a string to be looked up in eltypemap.

If allow_base_link==true, and any of the following are true a link is made to the base array (arrays_idx=1), instead of allocating a new array in array set arrays_idx: - Variable element type matches modeldata base eltype (arraysidx=1) - `usebasetransferjacobian=trueand Variable:transferjacobianattribute is set - Variable full name is inusebase_vars`

Field data type is determined by Variable :field_data attribute, optionally this can take a default_host_dependent_field_data default for Variables with host_dependent(v)==true (these are Variables with no Target or no Property linked, intended to be external dependencies supplied by the solver).

If check_units_opt != :no then the :units field of linked variable is checked, resulting in either a warning (if check_units_opt=:warn) or error (if check_units_opt=:error).

source
allocate_variables!(model, modeldata, arrays_idx; kwargs...)

Allocate memory for Domain variables for every Domain in model.

See allocate_variables!(domain::Domain, modeldata::AbstractModelData, arrays_idx::Int).

source
allocate_variables!(domain, modeldata, arrays_idx; [hostdep=false] [, kwargs...])

Allocate memory for Domain Variables.

If hostdep=false, only internal Variables are allocated, allowing host-dependent Variables (usually state Variables and derivatives + any external dependencies) to be set to views on host-managed arrays.

See allocate_variables!(vars, modeldata::AbstractModelData, arrays_idx::Int).

source
PALEOboxes.check_readyMethod
check_ready(model, modeldata; [throw_on_error=true]) -> ready::Bool

Check all variable pointers set (ie all arrays allocated for variable data)

source
PALEOboxes.check_configurationMethod
check_configuration(model; [throw_on_error=true]) -> config_ok::Bool

Calls optional Reaction check_configuration methods to perform additional configuration checks.

source
PALEOboxes.initialize_reactiondata!Method
initialize_reactiondata!(model::Model, modeldata::AbstractModelData; kwargs...)

Processes VarList_...s from ReactionMethods and populates modeldata.sorted_methodsdata_... with sorted lists of ReactionMethods and corresponding Variable accessors.

Optionally calls create_dispatch_methodlists(model, modeldata, modeldata.cellranges_all) to set modeldata.dispatchlists_all to default ReactionMethodDispatchLists for entire model.

Keyword arguments

  • arrays_indices=1:num_arrays(modeldata): modeldata arrays_idx to generate dispatch lists for
  • create_dispatchlists_all=false: true to set modeldata.dispatchlists_all
  • generated_dispatch=true: true to use autogenerated code for modeldata.dispatchlists_all (fast dispatch, slow compile)
source
PALEOboxes.dispatch_setupFunction
dispatch_setup(model, attribute_name, modeldata, cellranges=modeldata.cellranges_all)

Call setup methods, eg to initialize data arrays (including state variables).

attribute_name defines the setup operation performed. dispatch_setup should be called in sequence with attribute_name = :

  • :setup: initialise Reactions and set up any non-state Variables (eg model grid Variables) (applied to modeldata arrays_idx=1, values then copied to other arrays_idx)
  • :norm_value: set state Variable values from :norm_value attribute in .yaml file, and initialise any Reaction state that requires this value (arrays_idx 1 only)
  • :initial_value (optional): set state Variable values from :initial_value attribute in .yaml file (arrays_idx 1 only)
source
PALEOboxes.create_dispatch_methodlistsFunction
create_dispatch_methodlists(model::Model, modeldata::AbstractModelData, arrays_idx::Int, cellranges; kwargs) 
-    -> DispatchMethodLists(list_initialize, list_do)

Compile lists of initialize and do methods + corresponding cellrange for main loop do_deriv.

Subset of methods and cellrange to operate on are generated from supplied cellranges.

Keyword arguments

  • verbose=false: true for additional log output
  • generated_dispatch=true: true to create ReactionMethodDispatchLists (fast dispatch using generated code, slow compile time), false to create ReactionMethodDispatchListNoGen (slow dynamic dispatch, fast compile time)
source
PALEOboxes.ReactionMethodDispatchListType
ReactionMethodDispatchList

Defines a list of ReactionMethod with corresponding CellRange and views on Variable data (sub)arrays.

source

Attaching numerical solvers

High-level access to aggregated collections of Variables is provided by VariableAggregator and VariableAggregatorNamed (see Accessing model objects for low-level access).

PALEOboxes.VariableAggregatorType
VariableAggregator(vars, cellranges, modeldata, arrays_idx) -> VariableAggregator

Aggregate multiple VariableDomains into a flattened list (a contiguous Vector).

Creates a VariableAggregator for collection of Variables vars, with indices from corresponding cellranges, for data arrays in modeldata with arrays_idx.

cellranges may contain nothing entries to indicate whole Domain.

This is mostly useful for aggregating state Variables, derivatives, etc to implement an interface to a generic ODE/DAE etc solver.

Values may be copied to and from a Vector using copyto!

source
PALEOboxes.get_indicesFunction
get_indices(va::VariableAggregator, varnamefull::AbstractString; allow_not_found=false) -> indices::UnitRange{Int64}

Return indices in flattened Vector corresponding to Variable varnamefull

source
Base.copyto!Method
copyto!(dest::VariableAggregator, src::AbstractVector; sof=1) -> num_copied::Int

Set aggregated Variables dest = (contiguous) Vector src.

Optional sof sets first index in src to use.

source
Base.copyto!Method
copyto!(dest::AbstractVector, va::VariableAggregator; dof=1) -> num_copied::Int

Set (contiguous) Vector dest = aggregated Variables src

Optional dof sets first index in dest

source
PALEOboxes.VariableAggregatorNamedType
VariableAggregatorNamed(modeldata, arrays_idx=1) -> VariableAggregatorNamed
+    [, check_units_opt=:no])

Allocate or link memory for VariableDomains vars in modeldata array set arrays_idx

Element type of allocated Arrays is determined by eltype(modeldata, arrays_idx) (the usual case, allowing use of AD types), which can be overridden by Variable :datatype attribute if present (allowing Variables to ignore AD types). :datatype may be either a Julia DataType (eg Float64), or a string to be looked up in eltypemap.

If allow_base_link==true, and any of the following are true a link is made to the base array (arrays_idx=1), instead of allocating a new array in array set arrays_idx: - Variable element type matches modeldata base eltype (arraysidx=1) - `usebasetransferjacobian=trueand Variable:transferjacobianattribute is set - Variable full name is inusebase_vars`

Field data type is determined by Variable :field_data attribute, optionally this can take a default_host_dependent_field_data default for Variables with host_dependent(v)==true (these are Variables with no Target or no Property linked, intended to be external dependencies supplied by the solver).

If check_units_opt != :no then the :units field of linked variable is checked, resulting in either a warning (if check_units_opt=:warn) or error (if check_units_opt=:error).

source
allocate_variables!(model, modeldata, arrays_idx; kwargs...)

Allocate memory for Domain variables for every Domain in model.

See allocate_variables!(domain::Domain, modeldata::AbstractModelData, arrays_idx::Int).

source
allocate_variables!(domain, modeldata, arrays_idx; [hostdep=false] [, kwargs...])

Allocate memory for Domain Variables.

If hostdep=false, only internal Variables are allocated, allowing host-dependent Variables (usually state Variables and derivatives + any external dependencies) to be set to views on host-managed arrays.

See allocate_variables!(vars, modeldata::AbstractModelData, arrays_idx::Int).

source
PALEOboxes.check_readyMethod
check_ready(model, modeldata; [throw_on_error=true]) -> ready::Bool

Check all variable pointers set (ie all arrays allocated for variable data)

source
PALEOboxes.check_configurationMethod
check_configuration(model; [throw_on_error=true]) -> config_ok::Bool

Calls optional Reaction check_configuration methods to perform additional configuration checks.

source
PALEOboxes.initialize_reactiondata!Method
initialize_reactiondata!(model::Model, modeldata::AbstractModelData; kwargs...)

Processes VarList_...s from ReactionMethods and populates modeldata.sorted_methodsdata_... with sorted lists of ReactionMethods and corresponding Variable accessors.

Optionally calls create_dispatch_methodlists(model, modeldata, modeldata.cellranges_all) to set modeldata.dispatchlists_all to default ReactionMethodDispatchLists for entire model.

Keyword arguments

  • arrays_indices=1:num_arrays(modeldata): modeldata arrays_idx to generate dispatch lists for
  • create_dispatchlists_all=false: true to set modeldata.dispatchlists_all
  • generated_dispatch=true: true to use autogenerated code for modeldata.dispatchlists_all (fast dispatch, slow compile)
source
PALEOboxes.dispatch_setupFunction
dispatch_setup(model, attribute_name, modeldata, cellranges=modeldata.cellranges_all)

Call setup methods, eg to initialize data arrays (including state variables).

attribute_name defines the setup operation performed. dispatch_setup should be called in sequence with attribute_name = :

  • :setup: initialise Reactions and set up any non-state Variables (eg model grid Variables) (applied to modeldata arrays_idx=1, values then copied to other arrays_idx)
  • :norm_value: set state Variable values from :norm_value attribute in .yaml file, and initialise any Reaction state that requires this value (arrays_idx 1 only)
  • :initial_value (optional): set state Variable values from :initial_value attribute in .yaml file (arrays_idx 1 only)
source
PALEOboxes.create_dispatch_methodlistsFunction
create_dispatch_methodlists(model::Model, modeldata::AbstractModelData, arrays_idx::Int, cellranges; kwargs) 
+    -> DispatchMethodLists(list_initialize, list_do)

Compile lists of initialize and do methods + corresponding cellrange for main loop do_deriv.

Subset of methods and cellrange to operate on are generated from supplied cellranges.

Keyword arguments

  • verbose=false: true for additional log output
  • generated_dispatch=true: true to create ReactionMethodDispatchLists (fast dispatch using generated code, slow compile time), false to create ReactionMethodDispatchListNoGen (slow dynamic dispatch, fast compile time)
source
PALEOboxes.ReactionMethodDispatchListType
ReactionMethodDispatchList

Defines a list of ReactionMethod with corresponding CellRange and views on Variable data (sub)arrays.

source

Attaching numerical solvers

High-level access to aggregated collections of Variables is provided by VariableAggregator and VariableAggregatorNamed (see Accessing model objects for low-level access).

PALEOboxes.VariableAggregatorType
VariableAggregator(vars, cellranges, modeldata, arrays_idx) -> VariableAggregator

Aggregate multiple VariableDomains into a flattened list (a contiguous Vector).

Creates a VariableAggregator for collection of Variables vars, with indices from corresponding cellranges, for data arrays in modeldata with arrays_idx.

cellranges may contain nothing entries to indicate whole Domain.

This is mostly useful for aggregating state Variables, derivatives, etc to implement an interface to a generic ODE/DAE etc solver.

Values may be copied to and from a Vector using copyto!

source
PALEOboxes.get_indicesFunction
get_indices(va::VariableAggregator, varnamefull::AbstractString; allow_not_found=false) -> indices::UnitRange{Int64}

Return indices in flattened Vector corresponding to Variable varnamefull

source
Base.copyto!Method
copyto!(dest::VariableAggregator, src::AbstractVector; sof=1) -> num_copied::Int

Set aggregated Variables dest = (contiguous) Vector src.

Optional sof sets first index in src to use.

source
Base.copyto!Method
copyto!(dest::AbstractVector, va::VariableAggregator; dof=1) -> num_copied::Int

Set (contiguous) Vector dest = aggregated Variables src

Optional dof sets first index in dest

source
PALEOboxes.VariableAggregatorNamedType
VariableAggregatorNamed(modeldata, arrays_idx=1) -> VariableAggregatorNamed
 VariableAggregatorNamed(vars, modeldata, arrays_idx=1) -> VariableAggregatorNamed
-VariableAggregatorNamed(va::VariableAggregator; ignore_cellranges=false) -> VariableAggregatorNamed

Aggregate VariableDomains into nested NamedTuples, with Domain and Variable names as keys and data arrays (from get_data) as values.

Any / characters in Variable names are replaced with __ (double underscore)

This provides direct access to Variables by name, and is mostly useful for testing or for small models.

Fields

  • vars: nested NamedTuples (domainname, varname) of VariableDomains
  • values: nested NamedTuples (domainname, varname) of data arrays.
source

Aggregated collections of a subset of Parameters as a flattened Vector (eg for sensitivity studies) is provided by ParameterAggregator:

PALEOboxes.ParameterAggregatorType
ParameterAggregator(parfullnames::Vector{String}, model; eltype=Float64) -> ParameterAggregator

Represent a subset of model parameters given by parfullnames as a flattened Vector

parfulnames is a Vector of form ["domainname.reactionname.parname", ...] defining a subset of model parameters (NB: must be of type ParDouble or ParDoubleVec ie scalar or vector of Float64).

norm_values can be used to specify normalisation of the flattened parameter vector (defaults to 1.0).

The parameters can then be set from and copied to a flattened Vector using:

copyto!(pa::ParameterAggregator, newvalues::Vector)  # set from newvalues .* norm_values
+VariableAggregatorNamed(va::VariableAggregator; ignore_cellranges=false) -> VariableAggregatorNamed

Aggregate VariableDomains into nested NamedTuples, with Domain and Variable names as keys and data arrays (from get_data) as values.

Any / characters in Variable names are replaced with __ (double underscore)

This provides direct access to Variables by name, and is mostly useful for testing or for small models.

Fields

  • vars: nested NamedTuples (domainname, varname) of VariableDomains
  • values: nested NamedTuples (domainname, varname) of data arrays.
source

Aggregated collections of a subset of Parameters as a flattened Vector (eg for sensitivity studies) is provided by ParameterAggregator:

PALEOboxes.ParameterAggregatorType
ParameterAggregator(parfullnames::Vector{String}, model; eltype=Float64) -> ParameterAggregator

Represent a subset of model parameters given by parfullnames as a flattened Vector

parfulnames is a Vector of form ["domainname.reactionname.parname", ...] defining a subset of model parameters (NB: must be of type ParDouble or ParDoubleVec ie scalar or vector of Float64).

norm_values can be used to specify normalisation of the flattened parameter vector (defaults to 1.0).

The parameters can then be set from and copied to a flattened Vector using:

copyto!(pa::ParameterAggregator, newvalues::Vector)  # set from newvalues .* norm_values
 copyto!(currentvalues::Vector, pa::ParameterAggregator) # copy to currentvalues, dividing by norm_values
-get_currentvalues(pa::ParameterAggregator) -> currentvalues::Vector

The subset of parameters are then defined by the p parameter Vector used by SciML solvers, and combined with the full set (from the yaml file) to eg solve an ODE to enable sensitivity studies.

eltype can be eg a Dual number to support ForwardDiff automatic differentiation for parameter Jacobians.

source

Defining CellRanges

PALEOboxes.AbstractCellRangeType
AbstractCellRange

Defines a range of cells within a Domain.

Fields

All implementations should define:

  • domain::Domain: the Domain covered by this cellrange.
  • operatorID::Int: If operatorID==0, call all Reactions, otherwise only call those with matching operatorID (this enables operator splitting).
  • indices: an iterable list of cell indices.

And then may provide subtype-specific fields defining additional ranges of cells.

source
PALEOboxes.CellRangeType
CellRange <: AbstractCellRange

Defines a range of cells in a specified Domain as a linear list.

Fields

  • domain

  • operatorID

  • indices: may be any valid Julia indexing range thing eg 1:100, [1 2 3 4], etc

source
PALEOboxes.CellRangeColumnsType
CellRangeColumns <: AbstractCellRange

Defines a range of cells in a specified Domain, organised by columns.

Fields

  • domain

  • operatorID

  • indices: iterator through all cells in arbitrary order

  • columns: iterator through columns: columns[n] returns a Pair icol=>cells where cells are ordered top to bottom

source
PALEOboxes.create_default_cellrangeFunction
create_default_cellrange(model::Model [; operatorID=0]) -> Vector{AbstractCellRange}

Create a Vector of CellRange instances covering the entire model.

source
PALEOboxes.Grids.create_default_cellrangeFunction
create_default_cellrange(domain, grid, [; operatorID=0]) -> CellRange

Create a CellRange for entire domain and supplied operatorID

source
create_default_cellrange(domain, grid::Nothing [; operatorID=0]) -> CellRange

Create a CellRange for entire domain. Fallback for a domain with no grid

source
create_default_cellrange(domain, grid::UnstructuredVectorGrid [; operatorID=0]) -> CellRange

Create a CellRange for entire domain - use linear index.

source
create_default_cellrange(domain, grid::UnstructuredColumnGrid [; operatorID=0]) -> CellRangeColumns

Create a CellRange for entire domain. Return a PB.CellRangeColumns with iterators for columns and cells.

source
create_default_cellrange(domain, grid::Union{CartesianLinearGrid, CartesianArrayGrid} [; operatorID=0]) -> CellRangeColumns

Create a CellRange for entire domain. Return a PB.CellRangeColumns provided by cellrange_cartesiantile

source
PALEOboxes.Grids.cellrange_cartesiantileFunction
cellrange_cartesiantile

Create a range of cells within a region of CartesianLinearGrid specified by rangestuple in a specified PB.Domain

rangestuple is a tuple of Cartesian index ranges eg (1:9, :, :) for a 3D grid.

source

3D case return a CellRangeColumns

source

return partitioning of a 3D Domain into n tiles

source

Main loop

PALEOboxes.do_derivFunction
do_deriv(dispatchlists, deltat::Float64=0.0)
-do_deriv(dispatchlists, pa::ParameterAggregator, deltat::Float64=0.0)

Wrapper function to calculate entire derivative (initialize and do methods) in one call. dispatchlists is from create_dispatch_methodlists.

source
PALEOboxes.dispatch_methodlistFunction
dispatch_methodlist(dl::ReactionMethodDispatchList, deltat::Float64=0.0)
+get_currentvalues(pa::ParameterAggregator) -> currentvalues::Vector

The subset of parameters are then defined by the p parameter Vector used by SciML solvers, and combined with the full set (from the yaml file) to eg solve an ODE to enable sensitivity studies.

eltype can be eg a Dual number to support ForwardDiff automatic differentiation for parameter Jacobians.

source

Defining CellRanges

PALEOboxes.AbstractCellRangeType
AbstractCellRange

Defines a range of cells within a Domain.

Fields

All implementations should define:

  • domain::Domain: the Domain covered by this cellrange.
  • operatorID::Int: If operatorID==0, call all Reactions, otherwise only call those with matching operatorID (this enables operator splitting).
  • indices: an iterable list of cell indices.

And then may provide subtype-specific fields defining additional ranges of cells.

source
PALEOboxes.CellRangeType
CellRange <: AbstractCellRange

Defines a range of cells in a specified Domain as a linear list.

Fields

  • domain

  • operatorID

  • indices: may be any valid Julia indexing range thing eg 1:100, [1 2 3 4], etc

source
PALEOboxes.CellRangeColumnsType
CellRangeColumns <: AbstractCellRange

Defines a range of cells in a specified Domain, organised by columns.

Fields

  • domain

  • operatorID

  • indices: iterator through all cells in arbitrary order

  • columns: iterator through columns: columns[n] returns a Pair icol=>cells where cells are ordered top to bottom

source
PALEOboxes.create_default_cellrangeFunction
create_default_cellrange(model::Model [; operatorID=0]) -> Vector{AbstractCellRange}

Create a Vector of CellRange instances covering the entire model.

source
PALEOboxes.Grids.create_default_cellrangeFunction
create_default_cellrange(domain, grid, [; operatorID=0]) -> CellRange

Create a CellRange for entire domain and supplied operatorID

source
create_default_cellrange(domain, grid::Nothing [; operatorID=0]) -> CellRange

Create a CellRange for entire domain. Fallback for a domain with no grid

source
create_default_cellrange(domain, grid::UnstructuredVectorGrid [; operatorID=0]) -> CellRange

Create a CellRange for entire domain - use linear index.

source
create_default_cellrange(domain, grid::UnstructuredColumnGrid [; operatorID=0]) -> CellRangeColumns

Create a CellRange for entire domain. Return a PB.CellRangeColumns with iterators for columns and cells.

source
create_default_cellrange(domain, grid::Union{CartesianLinearGrid, CartesianArrayGrid} [; operatorID=0]) -> CellRangeColumns

Create a CellRange for entire domain. Return a PB.CellRangeColumns provided by cellrange_cartesiantile

source
PALEOboxes.Grids.cellrange_cartesiantileFunction
cellrange_cartesiantile

Create a range of cells within a region of CartesianLinearGrid specified by rangestuple in a specified PB.Domain

rangestuple is a tuple of Cartesian index ranges eg (1:9, :, :) for a 3D grid.

source

3D case return a CellRangeColumns

source

return partitioning of a 3D Domain into n tiles

source

Main loop

PALEOboxes.do_derivFunction
do_deriv(dispatchlists, deltat::Float64=0.0)
+do_deriv(dispatchlists, pa::ParameterAggregator, deltat::Float64=0.0)

Wrapper function to calculate entire derivative (initialize and do methods) in one call. dispatchlists is from create_dispatch_methodlists.

source
PALEOboxes.dispatch_methodlistFunction
dispatch_methodlist(dl::ReactionMethodDispatchList, deltat::Float64=0.0)
 dispatch_methodlist(dl::ReactionMethodDispatchList, pa::ParameterAggregator, deltat::Float64=0.0)
 dispatch_methodlist(dl::ReactionMethodDispatchListNoGen, deltat::Float64=0.0)
-dispatch_methodlist(dl::ReactionMethodDispatchListNoGen, pa::ParameterAggregator, deltat::Float64=0.0)

Call a list of ReactionMethods.

Implementation

As an optimisation, with dl::ReactionMethodDispatchList uses @generated for Type stability and to avoid dynamic dispatch, instead of iterating over lists.

ReactionMethodDispatchList fields are Tuples hence are fully Typed, the @generated function emits unrolled code with a function call for each Tuple element.

source

Diagnostics

PALEOboxes.show_methods_setupFunction
show_methods_setup(model::Model)

Display ordered list of Reaction setup methods (registered by add_method_setup!, called by dispatch_setup)

source
PALEOboxes.show_methods_initializeFunction
show_methods_initialize(model::Model)

Display ordered list of Reaction initialize methods (registered by add_method_initialize!, called by do_deriv at start of each model timestep).

source
PALEOboxes.show_methods_doFunction
show_methods_do(model::Model)

Display ordered list of Reaction do methods (registered by add_method_do!, called by do_deriv for each model timestep).

source
PALEOboxes.show_variablesFunction
show_variables(obj, ...) -> Table

Show all Variables attached to PALEO object obj

source
PALEOboxes.show_linksFunction
show_links(vardom::VariableDomain)
+dispatch_methodlist(dl::ReactionMethodDispatchListNoGen, pa::ParameterAggregator, deltat::Float64=0.0)

Call a list of ReactionMethods.

Implementation

As an optimisation, with dl::ReactionMethodDispatchList uses @generated for Type stability and to avoid dynamic dispatch, instead of iterating over lists.

ReactionMethodDispatchList fields are Tuples hence are fully Typed, the @generated function emits unrolled code with a function call for each Tuple element.

source

Diagnostics

PALEOboxes.show_methods_setupFunction
show_methods_setup(model::Model)

Display ordered list of Reaction setup methods (registered by add_method_setup!, called by dispatch_setup)

source
PALEOboxes.show_methods_initializeFunction
show_methods_initialize(model::Model)

Display ordered list of Reaction initialize methods (registered by add_method_initialize!, called by do_deriv at start of each model timestep).

source
PALEOboxes.show_methods_doFunction
show_methods_do(model::Model)

Display ordered list of Reaction do methods (registered by add_method_do!, called by do_deriv for each model timestep).

source
PALEOboxes.show_variablesFunction
show_variables(obj, ...) -> Table

Show all Variables attached to PALEO object obj

source
PALEOboxes.show_linksFunction
show_links(vardom::VariableDomain)
 show_links(model::Model, varnamefull::AbstractString)
 show_links(io::IO, vardom::VariableDomain)
-show_links(io::IO, model::Model, varnamefull::AbstractString)

Display all VariableReactions linked to this VariableDomain

varnamefull should be of form "<domain name>.<variable name>"

Linked variables are shown as "<domain name>.<reaction name>.<method name>.<local name>"

source
PALEOboxes.show_parametersFunction
show_parameters(model) -> DataFrame

Get parameters for all reactions in model.

Examples:

Show all model parameters using VS Code table viewer:

julia> vscodedisplay(PB.show_parameters(run.model))

Write out all model parameters as csv for import to a spreadsheet:

julia> CSV.write("pars.csv", PB.show_parameters(run.model))
source
show_parameters(react::AbstractReaction) -> DataFrame
-show_parameters(classname::AbstractString) -> DataFrame

list all parameters for a Reaction react instance or classname

source

Accessing model objects

Model

PALEOboxes.get_domainFunction
get_domain(model::Model, name::AbstractString; allow_not_found=true) -> Domain or nothing
-get_domain(model::Model, domainid) -> Domain

Get Domain by name (may be nothing if name not matched) or domainid (range 1:num_domains).

source
PALEOboxes.get_reactionMethod
get_reaction(model::Model, domainname, reactionname; allow_not_found=false) -> Reaction or nothing

Get Reaction by domainname and reaction name

source
PALEOboxes.set_parameter_value!Function
set_parameter_value!(model::Model, domainname, reactionname, parname, value)

Convenience function to set Parameter value.

source
PALEOboxes.get_parameter_valueFunction
get_parameter_value(model::Model, domainname, reactionname, parname) -> value

Convenience function to get Parameter value.

source
PALEOboxes.set_variable_attribute!Function
set_variable_attribute!(model::Model, varnamefull, attributename::Symbol, value)

Set varnamefull (of form <domain name>.<var name>) attributename to value.

source
PALEOboxes.get_variable_attributeFunction
get_variable_attribute(model::Model, varnamefull, attributename::Symbol, missing_value=missing) -> attributevalue

Get varnamefull (of form <domain name>.<var name>) attributename.

source

Domains

PALEOboxes.get_variableFunction
get_variable(obj, varname, ...) -> variable

Get variable <: VariableBase by name from PALEO object

source
PALEOboxes.get_variablesFunction
get_variables(varlist::AbstractVarList; flatten=true) -> Vector{VariableReaction}

Return VariableReaction in varlist.

If flatten=true, a Vector-of-Vectors is flattened.

source
get_variables(domain; hostdep=nothing, vfunction=VF_Undefined) -> Vector{VariableDomain}

Get domain variables, optionally filtering for subsets based on hostdep and :vfunction attribute

source
get_variables(domain, filter) -> Vector{VariableDomain}

Get subset of domain variables where filter(var) == true.

source
get_variables(method::AbstractReactionMethod; filterfn = v -> true) -> Vector{VariableReaction}

Get VariableReactions from method.varlists as a flat Vector, optionally restricting to those that match filterfn

source
get_variables(reaction, localname) -> Vector{VariableReaction}
-get_variables(reaction; [filterfn=v->true]) -> Vector{VariableReaction}

Get matching Variables from all ReactionMethods.

source
PALEOboxes.get_host_variablesFunction
get_host_variables(domain, vfunction; [match_deriv_suffix=""] [, operatorID=0] [, exclude_var_nameroots=[]] [, verbose=false]) 
-    -> (host_vars, host_deriv_vars)

Get state Variables with VariableFunction vfunction, and optionally corresponding time derivative with VariableFunction VF_Deriv and name matching hostvarname*<match_deriv_suffix`>.

Optionally filter by operatorID, omit Variables with name matching exclude_var_nameroots.

source
PALEOboxes.get_unallocated_variablesFunction
get_unallocated_variables(domain, modeldata, arrays_idx::Int) -> Vector{VariableDomain}

Return any unallocated variables (host-dependent variables which have no data pointer set)

source
PALEOboxes.get_reactionMethod
get_reaction(domain, reactname; allow_not_found) -> Reaction or nothing

Get a reaction by name.

source

VariableDomain

Low-level access to individual Variables.

PALEOboxes.set_data!Function
set_data!(var::VariableDomain, modeldata, arrays_idx::Int, data)

Set VariableDomain to a Field containing data.

Calls wrap_field to create a new Field.

source
PALEOboxes.get_dataFunction
get_data(var::VariableDomain, modeldata::AbstractModelData, arrays_idx::Int=1) -> field.values
-get_data(var::VariableDomain, domaindata::AbstractDomainData) -> field.values

Get Variable var data array from Field.values

source
get_data(va::VariableAggregator) -> Vector

Allocate Vector and set to values of aggregated Variables va.

source
PALEOboxes.get_data_outputFunction
get_data(var::VariableDomain, modeldata::AbstractModelData, arrays_idx::Int) -> get_values_output(field.values)
-get_data(var::VariableDomain, domaindata::AbstractDomainData) -> get_values_output(field.values)

Get a sanitized version of Variable var data array for storing as output from [get_values_output]@ref)(Field.values)

source
+show_links(io::IO, model::Model, varnamefull::AbstractString)

Display all VariableReactions linked to this VariableDomain

varnamefull should be of form "<domain name>.<variable name>"

Linked variables are shown as "<domain name>.<reaction name>.<method name>.<local name>"

source
PALEOboxes.show_parametersFunction
show_parameters(model) -> DataFrame

Get parameters for all reactions in model.

Examples:

Show all model parameters using VS Code table viewer:

julia> vscodedisplay(PB.show_parameters(run.model))

Write out all model parameters as csv for import to a spreadsheet:

julia> CSV.write("pars.csv", PB.show_parameters(run.model))
source
show_parameters(react::AbstractReaction) -> DataFrame
+show_parameters(classname::AbstractString) -> DataFrame

list all parameters for a Reaction react instance or classname

source

Accessing model objects

Model

PALEOboxes.get_domainFunction
get_domain(model::Model, name::AbstractString; allow_not_found=true) -> Domain or nothing
+get_domain(model::Model, domainid) -> Domain

Get Domain by name (may be nothing if name not matched) or domainid (range 1:num_domains).

source
PALEOboxes.get_reactionMethod
get_reaction(model::Model, domainname, reactionname; allow_not_found=false) -> Reaction or nothing

Get Reaction by domainname and reaction name

source
PALEOboxes.set_parameter_value!Function
set_parameter_value!(model::Model, domainname, reactionname, parname, value)

Convenience function to set Parameter value.

source
PALEOboxes.get_parameter_valueFunction
get_parameter_value(model::Model, domainname, reactionname, parname) -> value

Convenience function to get Parameter value.

source
PALEOboxes.set_variable_attribute!Function
set_variable_attribute!(model::Model, varnamefull, attributename::Symbol, value)

Set varnamefull (of form <domain name>.<var name>) attributename to value.

source
PALEOboxes.get_variable_attributeFunction
get_variable_attribute(model::Model, varnamefull, attributename::Symbol, missing_value=missing) -> attributevalue

Get varnamefull (of form <domain name>.<var name>) attributename.

source

Domains

PALEOboxes.get_variableFunction
get_variable(obj, varname, ...) -> variable

Get variable <: VariableBase by name from PALEO object

source
PALEOboxes.get_variablesFunction
get_variables(varlist::AbstractVarList; flatten=true) -> Vector{VariableReaction}

Return VariableReaction in varlist.

If flatten=true, a Vector-of-Vectors is flattened.

source
get_variables(domain; hostdep=nothing, vfunction=VF_Undefined) -> Vector{VariableDomain}

Get domain variables, optionally filtering for subsets based on hostdep and :vfunction attribute

source
get_variables(domain, filter) -> Vector{VariableDomain}

Get subset of domain variables where filter(var) == true.

source
get_variables(method::AbstractReactionMethod; filterfn = v -> true) -> Vector{VariableReaction}

Get VariableReactions from method.varlists as a flat Vector, optionally restricting to those that match filterfn

source
get_variables(reaction, localname) -> Vector{VariableReaction}
+get_variables(reaction; [filterfn=v->true]) -> Vector{VariableReaction}

Get matching Variables from all ReactionMethods.

source
PALEOboxes.get_host_variablesFunction
get_host_variables(domain, vfunction; [match_deriv_suffix=""] [, operatorID=0] [, exclude_var_nameroots=[]] [, verbose=false]) 
+    -> (host_vars, host_deriv_vars)

Get state Variables with VariableFunction vfunction, and optionally corresponding time derivative with VariableFunction VF_Deriv and name matching hostvarname*<match_deriv_suffix`>.

Optionally filter by operatorID, omit Variables with name matching exclude_var_nameroots.

source
PALEOboxes.get_unallocated_variablesFunction
get_unallocated_variables(domain, modeldata, arrays_idx::Int) -> Vector{VariableDomain}

Return any unallocated variables (host-dependent variables which have no data pointer set)

source
PALEOboxes.get_reactionMethod
get_reaction(domain, reactname; allow_not_found) -> Reaction or nothing

Get a reaction by name.

source

VariableDomain

Low-level access to individual Variables.

PALEOboxes.set_data!Function
set_data!(var::VariableDomain, modeldata, arrays_idx::Int, data)

Set VariableDomain to a Field containing data.

Calls wrap_field to create a new Field.

source
PALEOboxes.get_dataFunction
get_data(var::VariableDomain, modeldata::AbstractModelData, arrays_idx::Int=1) -> field.values
+get_data(var::VariableDomain, domaindata::AbstractDomainData) -> field.values

Get Variable var data array from Field.values

source
get_data(va::VariableAggregator) -> Vector

Allocate Vector and set to values of aggregated Variables va.

source
PALEOboxes.get_data_outputFunction
get_data(var::VariableDomain, modeldata::AbstractModelData, arrays_idx::Int) -> get_values_output(field.values)
+get_data(var::VariableDomain, domaindata::AbstractDomainData) -> get_values_output(field.values)

Get a sanitized version of Variable var data array for storing as output from [get_values_output]@ref)(Field.values)

source
diff --git a/dev/index.html b/dev/index.html index d94b6d4..fe49f75 100644 --- a/dev/index.html +++ b/dev/index.html @@ -1,2 +1,2 @@ -Home · PALEOboxes Documentation

PALEOboxes.jl

PALEOboxes.jl provides the model coupler for the PALEO model framework.

PALEO provides a toolkit for constructing biogeochemical reaction-transport models of Earth system components (eg atmosphere, ocean, sediment) as a well as coupled Earth system configurations. Model structure as well as parameters are described by a configuration file, making it straightforward to add and remove biogeochemical tracers and their interactions, change the representation of eg ocean circulation, and couple components together.

+Home · PALEOboxes Documentation

PALEOboxes.jl

PALEOboxes.jl provides the model coupler for the PALEO model framework.

PALEO provides a toolkit for constructing biogeochemical reaction-transport models of Earth system components (eg atmosphere, ocean, sediment) as a well as coupled Earth system configurations. Model structure as well as parameters are described by a configuration file, making it straightforward to add and remove biogeochemical tracers and their interactions, change the representation of eg ocean circulation, and couple components together.

diff --git a/dev/indexpage/index.html b/dev/indexpage/index.html index 1e07209..41a1770 100644 --- a/dev/indexpage/index.html +++ b/dev/indexpage/index.html @@ -1,2 +1,2 @@ -Index · PALEOboxes Documentation

Index

+Index · PALEOboxes Documentation

Index