licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
16988
import Infiltrator ############################################################ # (Function) Spaces ########################################################### """ AbstractSpace Defines a function space within a Domain, on a mesh defined by a Grid """ AbstractSpace """ ScalarSpace <: AbstractSpace A Domain position-independent quantity """ struct ScalarSpace <: AbstractSpace end """ CellSpace <: AbstractSpace A per-cell quantity. Use as Variable attribute :space to create a Variable with data array dimensions from Grid cells. """ struct CellSpace <: AbstractSpace end """ ColumnSpace <: AbstractSpace A per-column quantity. Use as Variable attribute :space to create a Variable with data array dimensions from Grid columns. """ struct ColumnSpace <: AbstractSpace end """ Face1DColumnSpace <: AbstractSpace A quantity defined on upper and lower faces of a cell in a 1D column """ struct Face1DColumnSpace <: AbstractSpace end "parse eg \"CellSpace\" as CellSpace" function Base.parse(::Type{AbstractSpace}, str::AbstractString) dtype = getproperty(@__MODULE__, Symbol(str)) dtype <: AbstractSpace || throw(ArgumentError("$str is not a subtype of AbstractSpace")) return dtype end ################################################################ # AbstractMesh Spaces and sizes # # Concrete types (UnstructuredVectorGrid, CartesianLinearGrid, ...) # should implement internal_size, and optionally cartesian_size ################################################################# """ 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 """ function internal_size end """ 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. """ function cartesian_size end """ spatial_size(::Type{<:AbstractSpace}, mesh::AbstractMesh) -> NTuple{ndims, Int} Array size for given Space and mesh. """ spatial_size(space::Type{<:AbstractSpace}, mesh) = internal_size(space, mesh) ################################################################ # AbstractData interface # # Concrete types (ScalarData, ArrayScalarData, IsotopeData) should implement these methods ################################################################# """ AbstractData Defines a Data type that can be composed with an [`AbstractSpace`](@ref) to form a Field Concrete subtypes should implement: [`allocate_values`](@ref), [`check_values`](@ref), [`zero_values!`](@ref), [`dof_values`](@ref), [`get_values_output`](@ref) If the subtype needs to provide values for a numerical solver (eg as a state variable), it also needs to implement: [`init_values!`](@ref), [`copyfieldto!`](@ref), [`copytofield!`](@ref), [`add_field!`](@ref), [`add_field_vec!`](@ref) If the subtype has a representation as components, it should implement: [`num_components`](@ref), [`get_components`](@ref) """ AbstractData """ 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` """ function allocate_values( field_data::Type{<:AbstractData}, data_dims::Tuple{Vararg{NamedDimension}}, data_type, space::Type{<:AbstractSpace}, spatial_size::Tuple{Integer, Vararg{Integer}}, # an NTuple with at least one element thread_safe::Bool, allocatenans::Bool, ) end """ 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. """ function check_values( existing_values, field_data::Type{<:AbstractData}, data_dims::Tuple{Vararg{NamedDimension}}, data_type, space::Type{<:AbstractSpace}, spatial_size::Tuple{Integer, Vararg{Integer}}, ) end """ check_data_type(existing_values, data_type::Union{Missing, Type}) Helper function for [`check_values`](@ref) implementations: check `existing_values` are consistent with `data_type` (if supplied), throw exception if not. """ check_data_type(existing_values, data_type::Missing) = nothing function check_data_type(existing_values, data_type::Type) existing_eltype = eltype(existing_values) existing_eltype === data_type || throw(ArgumentError("data_type mismatch: supplied $existing_eltype, require $data_type")) return nothing end """ 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 :initial_value, :norm_value, 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 """ 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} ) end """ 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 """ function zero_values!(values, field_data::Type{<:AbstractData}, data_dims::Tuple{Vararg{NamedDimension}}, space::Type{<:AbstractSpace}, cellrange) end """ field_single_element(field_data::Type{<:AbstractData}, N) -> Bool Return true if `field_data` with length(data_dims) = N is represented with a single value that can be accessed as [] (used to optimize FieldRecord storage). Default is probably OK, unless `field_data` uses a Vector of values per element. """ function field_single_element(field_data::Type{<:AbstractData}, N) if N == 0 return true else return false end end """ 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`. """ function dof_values(field_data::Type{<:AbstractData}, data_dims::Tuple{Vararg{NamedDimension}}, space::Type{<:AbstractSpace}, mesh, cellrange) end """ copyfieldto!( dest, doff, values, field_data::Type{<:AbstractData}, 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`](@ref) Required if this `field_data` type needs to provide values for a numerical solver. """ function copyfieldto!(dest, doff, values, field_data::Type{<:AbstractData}, data_dims::Tuple{Vararg{NamedDimension}}, space::Type{<:AbstractSpace}, cellrange) end """ copytofield!( values, field_data::Type{<:AbstractData}, data_dims::Tuple{Vararg{NamedDimension}}, space::Type{<:AbstractSpace}, 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`](@ref) Required if this `field_data` type needs to provide values for a numerical solver. """ function copytofield!(values, field_data::Type{<:AbstractData}, data_dims::Tuple{Vararg{NamedDimension}}, space::Type{<:AbstractSpace}, cellrange, src, soff) end """ add_field!(dest, field_data::Type{<:AbstractData}, data_dims::Tuple{Vararg{NamedDimension}}, space::Type{<:AbstractSpace}, a, cellrange, src) Implement `dest += a*src` where `dest`, `src` are Field.values, `a` is a number, over region defined by `cellrange` """ function add_field!(dest, field_data::Type{<:AbstractData}, data_dims::Tuple{Vararg{NamedDimension}}, space::Type{<:AbstractSpace}, a, cellrange, src) end """ add_field_vec!( dest, field_data::Type{<:AbstractData}, data_dims::Tuple{Vararg{NamedDimension}}, space::Type{<:AbstractSpace}, a, 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!`](@ref), [`copyfieldto!`](@ref) for the relationship between Array `src` and Field values `dest`. """ function add_field_vec!(dest, field_data::Type{<:AbstractData}, data_dims::Tuple{Vararg{NamedDimension}}, space::Type{<:AbstractSpace}, a, cellrange, src, soff) end """ num_components(field_data::Type{<:AbstractData}) -> Int get number of components (optional - implement if `field_data` has a representation as components) """ function num_components(field_data::Type{<:AbstractData}) end """ 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) """ function get_components(values, field_data::Type{<:AbstractData}) end "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" get_values_output(values, data_type::Type{<:AbstractData}, data_dims::Tuple{Vararg{NamedDimension}}, space, mesh) = values ################################################################ # UndefinedData ################################################################# """ UndefinedData <: AbstractData Undefined data type (no methods implemented). Used to indicate that a Variable can link to any data type. """ struct UndefinedData <: AbstractData end ############################################################# # Field ############################################################# """ 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}`. """ struct Field{D <: AbstractData, S <: AbstractSpace, V, N, M} values::V data_dims::NTuple{N, NamedDimension} mesh::M end field_data(field::Field{D, S, V, N, M}) where {D, S, V, N, M} = D space(field::Field{D, S, V, N, M}) where {D, S, V, N, M} = S """ get_field(obj, ...) -> Field Get Field from PALEO object `obj` """ function get_field end """ add_field!(obj, f::Field ...) Add Field or Field to PALEO object `obj` """ function add_field! end "create a new Field, allocating `values` data arrays" function allocate_field( field_data::Type, data_dims::NTuple{N, NamedDimension}, data_type::Type, space::Type{<:AbstractSpace}, mesh; thread_safe::Bool, allocatenans ) where {N} v = allocate_values( field_data, data_dims, data_type, space, spatial_size(space, mesh), thread_safe=thread_safe, allocatenans=allocatenans, ) return Field{field_data, space, typeof(v), N, typeof(mesh)}(v, data_dims, mesh) end "create a new Field, containing supplied `existing_values` data arrays" function wrap_field( existing_values, field_data::Type, data_dims::NTuple{N, NamedDimension}, data_type::Union{DataType, Missing}, space::Type{<:AbstractSpace}, mesh ) where {N} check_values( existing_values, field_data, data_dims, data_type, space, spatial_size(space, mesh), ) return Field{field_data, space, typeof(existing_values), N, typeof(mesh)}(existing_values, data_dims, mesh) end "zero out `field::Field` over region defined by `cellrange`" function zero_field!(field::Field{D, S, V, N, M}, cellrange) where {D, S, V, N, M} zero_values!(field.values, D, field.data_dims, S, cellrange) end "initialize `field::Field` to `init_value` (`:initial_value` or `:norm_value`) from Variable `attribv` attributes, over region defined by `cellrange`. Optionally calculate transformed initial values from supplied `convertfn` and `convertvalues`" function init_field!( field::Field{D, S, V, N, M}, init_value::Symbol, attribv::VariableBase, convertfn, convertvalues, cellrange, info, ) where {D, S, V, N, M} init_values!(field.values, D, field.data_dims, S, init_value, attribv, convertfn, convertvalues, cellrange, info) end "calculate number of degrees-of-freedom for `field::Field` over region defined by `cellrange`" function dof_field(field::Field{D, S, V, N, M}, cellrange) where {D, S, V, N, M} return dof_values(D, field.data_dims, S, field.mesh, cellrange) end "copy `src::Field`` to `dest::Vector`, optionally restricting to region defined by `cellrange`" function Base.copyto!(dest, doff, src::Field{D, S, V, N, M}, cellrange) where {D, S, V, N, M} return copyfieldto!(dest, doff, src.values, D, src.data_dims, S, cellrange) end "copy `src::Vector`` to `dest::Field`, optionally restricting to region defined by `cellrange`" function Base.copyto!(dest::Field{D, S, V, N, M}, cellrange, src, soff) where {D, S, V, N, M} return copytofield!(dest.values, D, dest.data_dims, S, cellrange, src, soff) end "Calculate `dest::Field = dest::Field + a * src::Field`, optionally restricting to region defined by `cellrange`" function add_field!(dest::Field{D, S, V, N, M}, a, cellrange, src::Field{D, S, V, N, M}) where {D, S, V, N, M} return add_field!(dest.values, D, dest.data_dims, S, a, cellrange, src.values) end function add_field_vec!(dest::Field{D, S, V, N, M}, a, cellrange, srcvalues::AbstractVector, soff) where {D, S, V, N, M} return add_field_vec!(dest.values, D, dest.data_dims, S, a, cellrange, srcvalues, soff) end "sanitized version of `values`, suitable for storing as output" function get_values_output(field::Field{D, S, V, N, M}) where {D, S, V, N, M} return get_values_output(field.values, D, field.data_dims, S, field.mesh) end # get values from `linkvar_field`, optionally applying view defined by `linksubdomain` function create_accessor( output_data::Union{Type{D}, Type{UndefinedData}}, # TODO - check space, data_dims, linkvar_field::Field{D, S, V, N, M}, linksubdomain::Union{Nothing, AbstractSubdomain}; forceview, components, ) where {D, S, V, N, M} # create accessor if isnothing(linksubdomain) if forceview if components var_accessor = [view(vc, 1:length(vc)) for vc in get_components(linkvar_field.values, D)] else var_accessor = view(linkvar_field.values, 1:length(linkvar_field.values)) end else if components var_accessor = get_components(linkvar_field.values, D) else var_accessor = linkvar_field.values end end else if components var_accessor = [Grids.subdomain_view(vc, linksubdomain) for vc in get_components(linkvar_field.values, D)] else var_accessor = Grids.subdomain_view(linkvar_field.values, linksubdomain) end end return var_accessor end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
40966
module Grids import NCDatasets import PALEOboxes as PB import Infiltrator # Julia debugger ########################### # Subdomains ########################### """ AbstractSubdomain Defines the relationship between two [`PB.Domain`](@ref)s by mapping indices in one Domain to related indices in the other, eg interior cells adjacent to a boundary. Concrete subtypes should implement: [`subdomain_view`](@ref) [`subdomain_indices`](@ref) """ PB.AbstractSubdomain """ 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`. """ struct BoundarySubdomain <: PB.AbstractSubdomain indices::Vector{Int} end """ 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`. """ function subdomain_view(values, subdomain::BoundarySubdomain) return view(values, subdomain.indices) end """ 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`](@ref) is sufficient). """ function subdomain_indices(subdomain::BoundarySubdomain) return nothing end """ 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` """ struct InteriorSubdomain <: PB.AbstractSubdomain indices::Vector{Union{Missing, Int}} end "Create InteriorSubdomain given size of interior Domain and boundaryindices[ibnd] index of interior point corresponding to boundary point ibnd" function InteriorSubdomain(ninterior, boundaryindices) indices = Vector{Union{Missing, eltype(boundaryindices)}}(undef, ninterior) for i in 1:length(boundaryindices) indices[boundaryindices[i]] = i end return InteriorSubdomain(indices) end """ subdomain_view(values, subdomain::InteriorSubdomain) -> var Return unmodified `values` from a boundary `Domain`, `indices` to access from interior supplied by [`subdomain_indices`](@ref) """ function subdomain_view(values, subdomain::InteriorSubdomain) return values end """ 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) """ function subdomain_indices(subdomain::InteriorSubdomain) return subdomain.indices end function is_boundary(subdomain::InteriorSubdomain, i) return !ismissing(subdomain.indices[i]) end """ subdomain_view(values, subdomain::Nothing) -> values Fallback when `subdomain == nothing` """ function subdomain_view(values, subdomain::Nothing) return values end """ subdomain_indices(subdomain::Nothing) -> nothing fallback when `subdomain == nothing` """ function subdomain_indices(subdomain::Nothing) return nothing end ######################################### # Grids ########################################## """ AbstractMesh Defines additional geometric and topological information for [`PB.Domain`](@ref) Concrete subtypes should implement methods: [`PB.internal_size`](@ref), optionally [`PB.cartesian_size`](@ref) [`PB.Grids.set_subdomain!`](@ref), [`PB.Grids.get_subdomain`](@ref) [`PB.Grids.create_default_cellrange`](@ref), [`PB.Grids.get_region`](@ref) """ PB.AbstractMesh "parse eg \"CartesianLinearGrid\" as CartesianLinearGrid" function Base.parse(::Type{PB.AbstractMesh}, str::AbstractString) dtype = getproperty(@__MODULE__, Symbol(str)) dtype <: PB.AbstractMesh || throw(ArgumentError("$str is not a subtype of AbstractMesh")) return dtype end """ create_default_cellrange(domain, grid, [; operatorID=0]) -> CellRange Create a CellRange for entire `domain` and supplied `operatorID` """ function create_default_cellrange(domain::PB.AbstractDomain, grid::Union{PB.AbstractMesh, Nothing}) end """ 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). """ function get_region(grid::Union{PB.AbstractMesh, Nothing}, values) end """ set_subdomain!(grid::PB.AbstractMesh, subdomainname::AbstractString, subdom::PB.AbstractSubdomain, allowcreate::Bool=false) Set Subdomain """ function set_subdomain!(grid::PB.AbstractMesh, subdomainname::AbstractString, subdom::PB.AbstractSubdomain, allowcreate::Bool=false) if !haskey(grid.subdomains, subdomainname) && !allowcreate error("attempt to create new subdomain name='$subdomainname' failed (allowcreate=false)") end grid.subdomains[subdomainname] = subdom return nothing end """ get_subdomain(grid::PB.AbstractMesh, subdomainname::AbstractString) -> PB.AbstractSubdomain Get Subdomain """ function get_subdomain(grid::PB.AbstractMesh, subdomainname::AbstractString) subdomain = get(grid.subdomains, subdomainname, nothing) !isnothing(subdomain) || error("get_subdomain: no subdomain $subdomainname") return subdomain end # generic handler when subdomainname present function PB.internal_size(space::Type{<:PB.AbstractSpace}, grid::Union{PB.AbstractMesh, Nothing}, subdomainname::AbstractString) if isempty(subdomainname) if space === PB.ScalarSpace return (1, ) else return PB.internal_size(space, grid) end else if space === PB.CellSpace subdomain = get_subdomain(grid, subdomainname) return (length(subdomain.indices),) else error("internal_size: cannot specify subdomain with space=$space (subdomainname=$subdomainname)") end end end # scalar space always supported PB.internal_size(space::Type{PB.ScalarSpace}, grid::Union{PB.AbstractMesh, Nothing}) = (1, ) # ignore subdomain PB.internal_size(space::Type{PB.ScalarSpace}, grid::Union{PB.AbstractMesh, Nothing}, subdomainname::AbstractString) = (1, ) ################################### # Fallbacks for Domain with no grid ##################################### # allow Vector variables length 1 in a 0D Domain without a grid PB.internal_size(space::Type{PB.CellSpace}, grid::Nothing) = (1, ) # allow single dimension PB.cartesian_size(grid::Nothing) = (1, ) cartesian_to_internal(grid::Nothing, griddata::AbstractArray) = griddata get_subdomain(grid::Nothing, subdomainname::AbstractString) = error("get_subdomain: no subdomain $subdomainname") """ create_default_cellrange(domain, grid::Nothing [; operatorID=0]) -> CellRange Create a CellRange for entire `domain`. Fallback for a domain with no grid """ function create_default_cellrange(domain::PB.AbstractDomain, grid::Nothing; operatorID=0) return PB.CellRange(domain=domain, indices=1:PB.get_length(domain), operatorID=operatorID) end """ get_region(grid::Nothing, values) -> values[] Fallback for Domain with no grid, assumed 1 cell """ function get_region(grid::Nothing, values) length(values) == 1 || throw(ArgumentError("grid==Nothing and length(values) != 1")) return values[], () end ################################## # UnstructuredVectorGrid ################################## """ UnstructuredVectorGrid <: PB.AbstractMesh Minimal Grid for a Vector Domain, defines only some named cells for plotting """ Base.@kwdef mutable struct UnstructuredVectorGrid <: PB.AbstractMesh ncells::Int64 "Define some named cells for plotting (only)" cellnames::Dict{Symbol,Int} = Dict{Symbol,Int}() subdomains::Dict{String, PB.AbstractSubdomain} = Dict{String, PB.AbstractSubdomain}() end function Base.show(io::IO, grid::UnstructuredVectorGrid) print(io, "UnstructuredVectorGrid(ncells=", grid.ncells, ", cellnames=", grid.cellnames, ", subdomains: ", keys(grid.subdomains), ")") return nothing end PB.internal_size(space::Type{PB.CellSpace}, grid::UnstructuredVectorGrid) = (grid.ncells, ) # single dimension PB.cartesian_size(grid::UnstructuredVectorGrid) = (grid.ncells, ) cartesian_to_internal(grid::UnstructuredVectorGrid, griddata::AbstractArray) = griddata """ 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` """ function get_region(grid::UnstructuredVectorGrid, values; cell::Union{Int, Symbol}) if cell isa Int idx = cell else idx = get(grid.cellnames, cell, nothing) !isnothing(idx) || throw(ArgumentError("cell ':$cell' not present in grid.cellnames=$(grid.cellnames)")) end return ( values[idx], (), # no dimensions (ie squeeze out a dimension length 1 for single cell) ) end """ create_default_cellrange(domain, grid::UnstructuredVectorGrid [; operatorID=0]) -> CellRange Create a CellRange for entire `domain` - use linear index. """ function create_default_cellrange(domain::PB.AbstractDomain, grid::UnstructuredVectorGrid; operatorID=0) return PB.CellRange(domain=domain, indices=1:grid.ncells, operatorID=operatorID) end ############################################ # UnstructuredColumnGrid ########################################### """ 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 """ Base.@kwdef mutable struct UnstructuredColumnGrid <: PB.AbstractMesh ncells::Int64 Icolumns::Vector{Vector{Int}} z_coords::Vector{PB.FixedCoord} = PB.FixedCoord[] "Define optional column names" columnnames::Vector{Symbol} = Symbol[] subdomains::Dict{String, PB.AbstractSubdomain} = Dict{String, PB.AbstractSubdomain}() end function Base.show(io::IO, grid::UnstructuredColumnGrid) print(io, "UnstructuredColumnGrid(ncells=", grid.ncells, ", columns: ", length(grid.Icolumns), ", columnnames=", grid.columnnames, ", subdomains: ", keys(grid.subdomains), ")") return nothing end PB.internal_size(space::Type{PB.CellSpace}, grid::UnstructuredColumnGrid) = (grid.ncells, ) PB.internal_size(space::Type{PB.ColumnSpace}, grid::UnstructuredColumnGrid) = (length(grid.Icolumns), ) # single dimension PB.cartesian_size(grid::UnstructuredColumnGrid) = (grid.ncells, ) cartesian_to_internal(grid::UnstructuredColumnGrid, griddata::AbstractArray) = griddata """ 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 """ function get_region(grid::UnstructuredColumnGrid, values; column, cell::Union{Nothing, Int}=nothing) if column isa Int column in 1:length(grid.Icolumns) || throw(ArgumentError("column index $column out of range")) colidx = column else colidx = findfirst(isequal(column), grid.columnnames) !isnothing(colidx) || throw(ArgumentError("columnname '$column' not present in grid.columnnames=$(grid.columnnames)")) end if isnothing(cell) indices = grid.Icolumns[colidx] return ( values[indices], (PB.NamedDimension("z", length(indices), PB.get_region(grid.z_coords, indices)), ), ) else # squeeze out z dimension idx = grid.Icolumns[colidx][cell] return ( values[idx], (), # no dimensions (ie squeeze out a dimension length 1 for single cell) ) end end """ create_default_cellrange(domain, grid::UnstructuredColumnGrid [; operatorID=0]) -> CellRangeColumns Create a CellRange for entire `domain`. Return a [`PB.CellRangeColumns`](@ref) with iterators for columns and cells. """ function create_default_cellrange(domain::PB.AbstractDomain, grid::UnstructuredColumnGrid; operatorID=0) return PB.CellRangeColumns( domain=domain, indices=1:grid.ncells, columns=[ (isurf, PB.replace_contiguous_range(grid.Icolumns[isurf])) for isurf in eachindex(grid.Icolumns) ], operatorID=operatorID ) end ###################################### # CartesianLinearGrid ####################################### """ 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) """ Base.@kwdef mutable struct CartesianLinearGrid{N} <: PB.AbstractMesh ncells::Int64 = -1 ncolumns::Int64 = -1 dimnames::Vector{String} = Vector{String}(undef, N) # netcdf dimension names dims::Vector{Int} = Vector{Int}(undef, N) coords::Vector{Vector{Float64}} = Vector{Vector{Float64}}() coords_edges::Vector{Vector{Float64}} = Vector{Vector{Float64}}() "index of longitude dimension (if any)" londim::Int = 0 "index of latitude dimension (if any)" latdim::Int = 0 "index of z dimension (if any)" zdim::Int = 0 "index of surface in z coordinate (if any) (1 or length(z dim))" zidxsurface::Int = 0 "multiplier to use for display (eg -1.0 to convert depth to height)" display_mult::Vector{Float64} = ones(N) subdomains::Dict{String, PB.AbstractSubdomain} = Dict{String, PB.AbstractSubdomain}() "cartesian -> linear index mapping (initialized to `missing` ie linear index contains 0 cells)" linear_index::Array{Union{Missing,Int32}, N} = Array{Union{Missing,Int32},N}(undef, zeros(Int,N)...) "linear -> cartesian index mapping (initialized to empty Vector ie linear index contains 0 cells)" cartesian_index::Vector{CartesianIndex{N}} = Vector{CartesianIndex{N}}() end function Base.show(io::IO, grid::CartesianLinearGrid) dimtuple = NamedTuple{Tuple(Symbol.(grid.dimnames))}(Tuple(grid.dims)) print(io, "CartesianLinearGrid(ncells=", grid.ncells, ", dimensions: ", dimtuple, ", subdomains: ", keys(grid.subdomains), ")") return nothing end PB.internal_size(space::Type{PB.CellSpace}, grid::CartesianLinearGrid) = (grid.ncells, ) PB.internal_size(space::Type{PB.ColumnSpace}, grid::CartesianLinearGrid{3}) = (grid.ncolumns, ) PB.cartesian_size(grid::CartesianLinearGrid) = Tuple(grid.dims) """ 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) """ Base.@kwdef mutable struct CartesianArrayGrid{N} <: PB.AbstractMesh ncells::Int64 = -1 dimnames::Vector{String} = Vector{String}(undef, N) # netcdf dimension names dims::Vector{Int} = Vector{Int}(undef, N) coords::Vector{Vector{Float64}} = Vector{Vector{Float64}}() coords_edges::Vector{Vector{Float64}} = Vector{Vector{Float64}}() "index of longitude dimension (if any)" londim::Int = 0 "index of latitude dimension (if any)" latdim::Int = 0 "index of z dimension (if any)" zdim::Int = 0 "index of surface in z coordinate (if any) (1 or length(z dim))" zidxsurface::Int = 0 "multiplier to use for display (eg -1.0 to convert depth to height)" display_mult::Vector{Float64} = ones(N) subdomains::Dict{String, PB.AbstractSubdomain} = Dict{String, PB.AbstractSubdomain}() end function Base.show(io::IO, grid::CartesianArrayGrid) dimtuple = NamedTuple{Tuple(Symbol.(grid.dimnames))}(Tuple(grid.dims)) print(io, "CartesianArrayGrid(ncells=", grid.ncells, ", dimensions: ", dimtuple, ", subdomains: ", keys(grid.subdomains), ")") return nothing end PB.internal_size(space::Type{PB.CellSpace}, grid::CartesianArrayGrid) = Tuple(grid.dims) PB.cartesian_size(grid::CartesianArrayGrid) = Tuple(grid.dims) """ 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) """ function get_region( grid::Union{CartesianLinearGrid{2}, CartesianArrayGrid{2}}, internalvalues; i::Union{Integer, Colon}=Colon(), j::Union{Integer, Colon}=Colon() ) return _get_region(grid, internalvalues, [i, j]) end """ 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). """ function get_region( grid::Union{CartesianLinearGrid{3}, CartesianArrayGrid{3}}, internalvalues; i::Union{Integer, Colon}=Colon(), j::Union{Integer, Colon}=Colon(), k::Union{Integer, Colon}=Colon() ) return _get_region(grid, internalvalues, [i, j, k]) end function _get_region( grid::Union{CartesianLinearGrid, CartesianArrayGrid}, internalvalues, indices ) if !isempty(grid.coords) && !isempty(grid.coords_edges) dims = [ PB.NamedDimension(grid.dimnames[idx], grid.coords[idx], grid.coords_edges[idx]) for (idx, ind) in enumerate(indices) if isa(ind, Colon) ] elseif !isempty(grid.coords) dims = [ PB.NamedDimension(grid.dimnames[idx], grid.coords[idx]) for (idx, ind) in enumerate(indices) if isa(ind, Colon) ] else dims = [ PB.NamedDimension(grid.dimnames[idx]) for (idx, ind) in enumerate(indices) if isa(ind, Colon) ] end values = internal_to_cartesian(grid, internalvalues) if !all(isequal(Colon()), indices) values = values[indices...] end return values, Tuple(dims) end """ CartesianGrid( gridtype, dimnames::Vector{<:AbstractString}, dims, coords, coords_edges; [londim] [, latdim] [,zdim=0], [,zidxsurface=0], [, ztoheight=1.0]) -> grid::CartesianLinearGrid Create a CartesianLinearGrid or CartesianArrayGrid from dimensions and coordinates. """ function CartesianGrid( GridType::Type{<:Union{CartesianLinearGrid, CartesianArrayGrid}}, dimnames::Vector{<:AbstractString}, dims, coords=Vector{Vector{Float64}}(), coords_edges=Vector{Vector{Float64}}(); londim=findfirst(isequal("lon"), dimnames), latdim=findfirst(isequal("lat"), dimnames), zdim=0, zidxsurface=0, ztoheight=1.0 ) grid = GridType{length(dimnames)}( dimnames=dimnames, dims=dims, coords=coords, coords_edges=coords_edges, londim=londim, latdim=latdim, zdim=zdim, zidxsurface=zidxsurface ) if zdim > 0 grid.display_mult[zdim] = ztoheight end if GridType == CartesianLinearGrid # create linear index (with no points) grid.linear_index = Array{Union{Missing,Int32},length(grid.dims)}(undef, grid.dims...) grid.ncells = 0 else grid.ncells = prod(grid.dims) end return grid end """ CartesianGrid(griddtype, ncfilename::AbstractString, dimnames::Vector{<:AbstractString}; equalspacededges=false) -> grid::CartesianLinearGrid Read a netcdf file with CF1.0 coordinates, and create corresponding a CartesianLinearGrid or CartesianArrayGrid from dimensions `dimnames`. """ function CartesianGrid( GridType::Type{<:Union{CartesianLinearGrid, CartesianArrayGrid}}, ncfilename::AbstractString, dimnames::Vector{<:AbstractString}; equalspacededges=false ) @info "CartesianGrid creating $GridType{$(length(dimnames))} from dimnames=$dimnames in netcdf file $(ncfilename)" grid = GridType{length(dimnames)}() grid.coords = Vector{Vector{Float64}}(undef, length(dimnames)) grid.coords_edges = Vector{Vector{Float64}}(undef, length(dimnames)) NCDatasets.Dataset(ncfilename) do ds # read dimensions and coordinates for i in eachindex(dimnames) dimname = dimnames[i] grid.dimnames[i] = dimname grid.dims[i] = ds.dim[dimname] @info " read dimension $(dimname) = $(grid.dims[i])" v_cf = ds[dimname] grid.coords[i] = Array(v_cf) if haskey(v_cf.attrib, "edges") edgesname = v_cf.attrib["edges"] @info " reading coordinate edges from $edgesname" grid.coords_edges[i] = Array(ds[edgesname]) elseif equalspacededges es = grid.coords[i][2] - grid.coords[i][1] @info " assuming equal spacing $es to calculate coordinate edges" grid.coords_edges[i] = [grid.coords[i] .- es/2.0; grid.coords[i][end] + es/2.0 ] else error(" no edges attribute and equalspacededges=false") end if v_cf.attrib["standard_name"] == "longitude" @info " dim $i got standard_name=='longitude'" grid.londim = i elseif v_cf.attrib["standard_name"] == "latitude" @info " dim $i got standard_name=='latitude'" grid.latdim = i elseif v_cf.attrib["standard_name"] == "depth" @info " dim $i got standard_name=='depth', using this as z dimension" grid.zdim = i grid.display_mult[i] = -1.0 if grid.coords[i][1] < grid.coords[i][end] grid.zidxsurface = 1 else grid.zidxsurface = length(grid.coords[i]) end @info " surface is index $(grid.zidxsurface)" end end end if GridType == CartesianLinearGrid # create linear index (with no points) grid.linear_index = Array{Union{Missing,Int32},length(grid.dims)}(undef, grid.dims...) grid.ncells = 0 else grid.ncells = prod(grid.dims) end return grid end """ set_linear_index(grid::CartesianLinearGrid{3}, v_i, v_j, v_k) Set 3D grid linear index (given by v_i, v_j, v_k Vectors defining Cartesian [i,j,k] for each v_i[l], v_j[l], v_k[l]) """ function set_linear_index(grid::CartesianLinearGrid{3}, v_i, v_j, v_k) grid.ncells = length(v_i) grid.ncolumns = 0 grid.linear_index = Array{Union{Missing,Int32}, 3}(undef, grid.dims...) grid.cartesian_index = Vector{CartesianIndex{3}}(undef, grid.ncells) fill!(grid.linear_index, missing) for l in eachindex(v_i) grid.linear_index[v_i[l], v_j[l], v_k[l]] = l grid.cartesian_index[l] = CartesianIndex(v_i[l], v_j[l], v_k[l]) if v_k[l] == grid.zidxsurface grid.ncolumns += 1 end end return nothing end """ set_linear_index(grid::CartesianLinearGrid{2}, v_i, v_j) Set 2D grid linear index (given by v_i, v_j Vectors defining Cartesian [i,j] for each v_i[l], v_j[l]) """ function set_linear_index(grid::CartesianLinearGrid{2}, v_i, v_j) grid.ncells = length(v_i) grid.linear_index = Array{Union{Missing,Int32}, 2}(undef, grid.dims...) grid.cartesian_index = Vector{CartesianIndex{2}}(undef, grid.ncells) fill!(grid.linear_index, missing) for l in eachindex(v_i) grid.linear_index[v_i[l], v_j[l]] = l grid.cartesian_index[l] = CartesianIndex(v_i[l], v_j[l]) end return nothing end """ cartesian_to_internal(grid::CartesianLinearGrid, griddata::AbstractArray) -> lindata::Vector Convert Cartesian Array `griddata` to Vector on `grid.linear_index` """ function cartesian_to_internal(grid::CartesianLinearGrid, griddata::AbstractArray) size(grid.linear_index) == size(griddata) || error("grid and data size mismatch") return griddata[grid.cartesian_index] end cartesian_to_internal(grid::CartesianArrayGrid, griddata::AbstractArray) = griddata """ internal_to_cartesian(grid::CartesianLinearGrid, internaldata::AbstractVector [,missing_value=missing]) -> griddata::Array Convert Vector `internaldata` (on `grid.linear_index`) to Cartesian Array `griddata` (with `missing_value` where no data) """ function internal_to_cartesian(grid::CartesianLinearGrid, internaldata::AbstractArray; missing_value=missing) grid.ncells == length(internaldata) || error("grid and data size mismatch") if missing_value isa Missing gr_eltype = Union{Missing, eltype(internaldata)} else gr_eltype = eltype(internaldata) end griddata = similar(grid.linear_index, gr_eltype) fill!(griddata, missing_value) griddata[grid.cartesian_index] .= internaldata return griddata end internal_to_cartesian(grid::CartesianArrayGrid, internaldata::AbstractArray; missing_value=missing) = internaldata function get_lon(grid::CartesianLinearGrid, linear_idx::Integer) cartesian_idx = grid.cartesian_index[linear_idx] return _get_coord(grid.coords, grid.londim, "longitude", cartesian_idx) end get_lon(grid::CartesianArrayGrid{N}, cartesian_idx::CartesianIndex{N}) where {N} = _get_coord(grid.coords, grid.londim, "longitude", cartesian_idx) function get_lon_edges(grid::CartesianLinearGrid, linear_idx::Integer) cartesian_idx = grid.cartesian_index[linear_idx] return _get_coord_edges(grid.coords_edges, grid.londim, "longitude", cartesian_idx) end get_lon_edges(grid::CartesianArrayGrid{N}, cartesian_idx::CartesianIndex{N}) where {N} = _get_coord_edges(grid.coords_edges, grid.londim, "longitude", cartesian_idx) function get_lat(grid::CartesianLinearGrid, linear_idx::Integer) cartesian_idx = grid.cartesian_index[linear_idx] return _get_coord(grid.coords, grid.latdim, "latitude", cartesian_idx) end get_lat(grid::CartesianArrayGrid{N}, cartesian_idx::CartesianIndex{N}) where {N} = _get_coord(grid.coords, grid.latdim, "latitude", cartesian_idx) function get_lat_edges(grid::CartesianLinearGrid, linear_idx::Integer) cartesian_idx = grid.cartesian_index[linear_idx] return _get_coord_edges(grid.coords_edges, grid.latdim, "latitude", cartesian_idx) end get_lat_edges(grid::CartesianArrayGrid{N}, cartesian_idx::CartesianIndex{N}) where {N} = _get_coord_edges(grid.coords_edges, grid.latdim, "latitude", cartesian_idx) function _get_coord(coords, cdim, dimname, cartesian_idx::CartesianIndex) cdim > 0 || error("grid has no $dimname dimension") return coords[cdim][cartesian_idx[cdim]] end function _get_coord_edges(coords_edges, cdim, dimname, cartesian_idx::CartesianIndex) cdim > 0 || error("grid has no $dimname dimension") return ( coords_edges[cdim][cartesian_idx[cdim]], coords_edges[cdim][cartesian_idx[cdim]+1], ) end """ linear_indices_cartesian_ranges(grid::CartesianLinearGrid, rangestuple) -> lindices Find linear indices corresponding to a region in a Cartesian grid # Example lindices = linear_indices_cartesian_ranges(grid, (1:2, 10:20, :)) """ #= function linear_indices_cartesian_ranges(grid::CartesianLinearGrid{2}, rangestuple ) r1 = rangestuple[1] r2 = rangestuple[2] return [l for l in grid.linear_index[r1, r2] if !ismissing(l)] end function linear_indices_cartesian_ranges(grid::CartesianLinearGrid{3}, (r1, r2, r3) ) return [l for l in grid.linear_index[r1, r2, r3] if !ismissing(l)] end =# """ cellrange_cartesiantile Create a range of cells within a region of CartesianLinearGrid specified by `rangestuple` in a specified [`PB.Domain`](@ref) `rangestuple` is a tuple of Cartesian index ranges eg (1:9, :, :) for a 3D grid. """ function cellrange_cartesiantile(domain, grid::CartesianLinearGrid{2}, rangestuple; operatorID=0) indices = Int[] r1, r2 = _expandrangetuple(grid.dims, rangestuple[1:2]) for i=1:length(grid.cartesian_index) ci = grid.cartesian_index[i] if ci[1] in r1 && ci[2] in r2 push!(indices, i) end end return PB.CellRange(domain=domain, indices=PB.replace_contiguous_range(indices), operatorID=operatorID) end "3D case return a CellRangeColumns" function cellrange_cartesiantile(domain, grid::CartesianLinearGrid{3}, rangestuple; operatorID=0) grid.zdim == 3 || error("grid.zdim = $(grid.zdim) not supported (must be last dimension = 3)") # recreate (all) surface indices surfindices = [ci for ci in grid.cartesian_index if ci[3] == grid.zidxsurface] r1, r2, r3 = _expandrangetuple(grid.dims, rangestuple) indices = Int[] colindices = Vector{Pair{Int,Vector{Int}}}() # iterate through surface indices and generate columns for is in 1:length(surfindices) sci = surfindices[is] # println("is ", is, " sci ", sci) if sci[1] in r1 && sci[2] in r2 colinds = Int[] # iterate through column in order surface -> floor if grid.zidxsurface == 1 krange = 1:size(grid.linear_index,3) else krange = reverse(1:size(grid.linear_index,3)) end for k in krange li = grid.linear_index[sci[1], sci[2], k ] if k in r3 && !ismissing(li) push!(colinds, li) end end if !isempty(colinds) colinds = PB.replace_contiguous_range(colinds) append!(indices, colinds) push!(colindices, is=>colinds) end end end return PB.CellRangeColumns( domain=domain, indices=PB.replace_contiguous_range(indices), columns=colindices, operatorID=operatorID ) end function cellrange_cartesiantile(domain, grid::CartesianArrayGrid{2}, rangestuple; operatorID=0) rt = _expandrangetuple(grid.dims, rangestuple[1:2]) return PB.CellRange(domain=domain, indices=CartesianIndices(rt), operatorID=operatorID) end function cellrange_cartesiantile(domain, grid::CartesianArrayGrid{3}, rangestuple; operatorID=0) rt = _expandrangetuple(grid.dims, rangestuple[1:3]) return PB.CellRange(domain=domain, indices=CartesianIndices(rt), operatorID=operatorID) end """ create_default_cellrange(domain, grid::Union{CartesianLinearGrid, CartesianArrayGrid} [; operatorID=0]) -> CellRangeColumns Create a CellRange for entire `domain`. Return a [`PB.CellRangeColumns`](@ref) provided by [`cellrange_cartesiantile`](@ref) """ function create_default_cellrange(domain::PB.AbstractDomain, grid::Union{CartesianLinearGrid, CartesianArrayGrid}; operatorID=0) return cellrange_cartesiantile(domain, grid, (:, :, :), operatorID=operatorID) end "expand (1:2, :, :) replacing : with ranges" function _expandrangetuple(dims, rangestuple) ranges = [] for i = 1:length(rangestuple) r = rangestuple[i] if r isa Colon push!(ranges, 1:dims[i]) else push!(ranges, r) end end return Tuple(ranges) end "return partitioning of a 3D Domain into n tiles" function cellrange_cartesiantile(domain::PB.AbstractDomain, grid::CartesianLinearGrid{3}, ntiles::Int; operatorID=0) # get entire Domain default_cellrange = create_default_cellrange(domain, grid) cumulative_cells = Int[] # total cells including column i cc = 0 for (icol, cellscol) in default_cellrange.columns cc += length(cellscol) push!(cumulative_cells, cc) end total_cols = length(default_cellrange.columns) total_cells = last(cumulative_cells) @info "cellrange_cartesiantile total_cols=$total_cols, total_cells=$total_cells" cellranges = [] firsttilecol = 1 for t in 1:ntiles indices = Int[] colindices = Vector{Pair{Int,Vector{Int}}}() tilecells = 0 for tc in firsttilecol:total_cols (icol, cellscol) = default_cellrange.columns[tc] append!(indices, cellscol) push!(colindices, icol=>cellscol) tilecells += length(cellscol) if tilecells >= total_cells/ntiles && t != ntiles firsttilecol = tc+1 break end end @info " tile $t columns $(first(colindices)[1]):$(last(colindices)[1]) total cells $(length(indices))" push!( cellranges, PB.CellRangeColumns( domain=domain, indices=PB.replace_contiguous_range(indices), columns=colindices, operatorID=operatorID ) ) end return cellranges end "derive CellRange for a 2D boundary Domain from a CellRangeColumns for the 3D interior Domain" function cellrange_from_columns(boundarydomain, grid::CartesianLinearGrid{2}, interior_crcolumns::PB.CellRangeColumns) indices = [icol for (icol, cellscol) in interior_crcolumns.columns] return PB.CellRange( domain=boundarydomain, indices=PB.replace_contiguous_range(indices), operatorID=interior_crcolumns.operatorID ) end """ linear_kji_order(grid, v_i, v_j, v_k) -> perm::Vector Find `perm` such that indices `v_i[perm], v_j[perm], v_k[perm]` correspond to traversal of the 3D grid in order k, j, i """ function linear_kji_order(grid, v_i, v_j, v_k) length(grid.dims) == 3 || error("linear_kji_order grid is not a 3D grid") # construct a 3D Array and fill with linear index values linear_index = Array{Union{Missing,Int32},length(grid.dims)}(missing, grid.dims...) for l in eachindex(v_i) linear_index[v_i[l], v_j[l], v_k[l]] = l end # visit 3D Array in k, j, i order and record linear index values perm = Vector{Int}(undef, length(v_i)) ip = 0 for i in 1:grid.dims[1] for j in 1:grid.dims[2] for k in 1:grid.dims[3] if !ismissing(linear_index[i, j, k]) ip += 1 perm[ip] = linear_index[i, j, k] end end end end return (perm, sortperm(perm)) end ########################### # Grid tiling ########################### """ get_tiled_cellranges(model::Model, tiles [; operatorID]) -> cellranges::Vector{Vector} Partition Domains into tiles, assuming a single Cartesian gridded Domain + associated boundaries (eg ocean + oceansurface + ...) and that all additional Domains are scalar Domains (eg atmosphere). `tiles` should be a collection of tuples of ranges eg `tiles = [(1:9, :, :), (10:16, :, :), (17:25, :, :), (26:36, :, :)]`. Returns `cellranges`, a Vector of Vectors of CellRanges providing one Vector of Cellranges per tile. """ function get_tiled_cellranges(model::PB.Model, tiles; operatorID=0) cellranges = [] # vector of vectors, 1 per tile for tr in tiles @info "creating CellRanges for tile $tr operatorID $operatorID" tcellranges = [] for dom in model.domains if !isnothing(dom.grid) push!(tcellranges, cellrange_cartesiantile(dom, dom.grid, tr, operatorID=operatorID)) @info " add CellRange for domain $(dom.name) length $(length(last(tcellranges).indices))" end end push!(cellranges, tcellranges) end # create cellranges for scalar Domains cellrangesscalar = [] @info "creating CellRanges for scalar domains" for dom in model.domains if isnothing(dom.grid) push!(cellrangesscalar, create_default_cellrange(dom, dom.grid, operatorID=operatorID)) @info " added CellRange for scalar domain $(dom.name)" end end @info "adding CellRanges for scalar domains to first tile" append!(first(cellranges), cellrangesscalar) return cellranges end """ get_tiled_cellranges(model::Model, ntiles::Int, interior_domain_name [; operatorID]) -> cellranges::Vector{Vector} Partition Domains into `ntiles` with approximately equal numbers of cells for `interior_domain_name`, assuming a single Cartesian gridded Domain `interior_domain_name` + associated boundaries (eg ocean + oceansurface + ...) and that all additional Domains are scalar Domains (eg atmosphere). Returns `cellranges`, a Vector of Vectors of CellRanges providing one Vector of Cellranges per tile. """ function get_tiled_cellranges(model::PB.Model, ntiles::Int, interior_domain_name::AbstractString; operatorID=0) interior_domain = PB.get_domain(model, interior_domain_name) interior_cellranges = cellrange_cartesiantile(interior_domain, interior_domain.grid, ntiles, operatorID=operatorID) cellranges = [] # vector of vectors, 1 per tile for it in 1:ntiles println("creating CellRanges for tile $it") tcellranges = [] push!(tcellranges, interior_cellranges[it]) for dom in model.domains if !isnothing(dom.grid) && dom != interior_domain push!(tcellranges, cellrange_from_columns(dom, dom.grid, interior_cellranges[it])) println(" add CellRange for domain $(dom.name) length $(length(last(tcellranges).indices))") end end push!(cellranges, tcellranges) end # create cellranges for scalar Domains cellrangesscalar = [] @info "creating CellRanges for scalar domains" for dom in model.domains if isnothing(dom.grid) push!(cellrangesscalar, create_default_cellrange(dom, dom.grid, operatorID=operatorID)) @info " added CellRange for scalar domain $(dom.name)" end end @info "adding CellRanges for scalar domains to first tile" append!(first(cellranges), cellrangesscalar) return cellranges end end # module
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
37580
import Infiltrator """ Model A biogeochemical model consisting of [`Domain`](@ref)s, created from a [YAML](https://en.wikipedia.org/wiki/YAML) configuration file using [`create_model_from_config`](@ref). """ Base.@kwdef mutable struct Model <: AbstractModel name::String config_files::Vector{String} parameters::Dict{String, Any} domains::Vector{AbstractDomain} = Vector{AbstractDomain}() sorted_methods_setup = nothing sorted_methods_initialize = nothing sorted_methods_do = nothing end "Get number of model domains" function get_num_domains(model::Model) return length(model.domains) end """ 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). """ function get_domain(model::Model, name::AbstractString; allow_not_found=true) domainidx = findfirst(d -> d.name==name, model.domains) if isnothing(domainidx) allow_not_found || error("get_domain: no Domain $name") return nothing else return model.domains[domainidx] end end function get_domain(model::Model, domainid) domainid <= length(model.domains) || error("get_domain: invalid domainid=", domainid) return model.domains[domainid] end function get_mesh(model::Model, domainname::AbstractString) return get_domain(model, domainname; allow_not_found=false).grid end """ get_reaction(model::Model, domainname, reactionname; allow_not_found=false) -> Reaction or nothing Get Reaction by domainname and reaction name """ function get_reaction(model::Model, domainname, reactionname; allow_not_found=false) domain = get_domain(model, domainname; allow_not_found) return isnothing(domain) ? nothing : get_reaction(domain, reactionname; allow_not_found) end """ get_variable(model::Model, varnamefull; allow_not_found=false) -> VariableDomain or nothing Get Variable by name of form `<domainname>.<variablename>` """ function get_variable(model::Model, varnamefull::AbstractString; allow_not_found=false) varsplit = split(varnamefull, ".") length(varsplit) == 2 || throw(ArgumentError("varnamefull $varnamefull is not of form <domainname>.<variablename>")) domainname, variablename = varsplit domain = get_domain(model, domainname; allow_not_found) return isnothing(domain) ? nothing : get_variable(domain, variablename; allow_not_found) end """ get_field(model::Model, modeldata, varnamefull) -> Field Get [`Field`](@ref) by Variable name """ function get_field(model::Model, modeldata::AbstractModelData, varnamefull::AbstractString) var = get_variable(model, varnamefull; allow_not_found=false) return get_field(var, modeldata) end """ set_variable_attribute!(model::Model, varnamefull, attributename::Symbol, value) Set `varnamefull` (of form <domain name>.<var name>) `attributename` to `value`. """ function set_variable_attribute!( model::Model, varnamefull::AbstractString, attributename::Symbol, value ) domvar = get_variable(model, varnamefull; allow_not_found=false) return set_attribute!(domvar, attributename, value) end set_variable_attribute!( model::Model, domainname::AbstractString, variablename::AbstractString, attributename::Symbol, value ) = set_variable_attribute!(model, domainname*"."*variablename, attributename, value) """ get_variable_attribute(model::Model, varnamefull, attributename::Symbol, missing_value=missing) -> attributevalue Get `varnamefull` (of form <domain name>.<var name>) `attributename`. """ function get_variable_attribute( model::Model, varnamefull::AbstractString, attributename::Symbol, missing_value=missing, ) domvar = get_variable(model, varnamefull; allow_not_found=false) return get_attribute(domvar, attributename, missing_value) end "convenience function to get VariableReaction with 'localname' from all ReactionMethods of 'reactionname'" function get_reaction_variables( model::Model, domainname::AbstractString, reactionname::AbstractString, localname::AbstractString ) react = get_reaction(model, domainname, reactionname; allow_not_found=false) return get_variables(react, localname) end "convenience function to get VariableReaction matching 'filterfn' from all ReactionMethods of 'reactionname'" function get_reaction_variables( model::Model, domainname::AbstractString, reactionname::AbstractString; filterfn = v -> true, ) react = get_reaction(model, domainname, reactionname; allow_not_found=false) return get_variables(react, filterfn=filterfn) end """ set_parameter_value!(model::Model, domainname, reactionname, parname, value) Convenience function to set Parameter value. """ function set_parameter_value!( model::Model, domainname::AbstractString, reactionname::AbstractString, parname::AbstractString, value ) react = get_reaction(model, domainname, reactionname; allow_not_found=false) return set_parameter_value!(react, parname, value) end """ get_parameter_value(model::Model, domainname, reactionname, parname) -> value Convenience function to get Parameter value. """ function get_parameter_value( model::Model, domainname::AbstractString, reactionname::AbstractString, parname::AbstractString, ) react = get_reaction(model, domainname, reactionname; allow_not_found=false) return get_parameter_value(react, parname, value) end ################################### # creation from _cfg.yaml ################################## """ create_model_from_config( config_file::AbstractString, configmodel::AbstractString; modelpars::Dict = Dict() ) -> model::Model create_model_from_config( config_files, configmodel::AbstractString; modelpars::Dict = Dict() ) -> model::Model Construct model from a single [YAML](https://en.wikipedia.org/wiki/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. """ function create_model_from_config( config_file::AbstractString, configmodel::AbstractString; kwargs... ) return create_model_from_config([config_file], configmodel; kwargs...) end function create_model_from_config( config_files, configmodel::AbstractString; modelpars::Dict=Dict(), sort_methods_algorithm=group_methods, ) io = IOBuffer() print(io, """ ================================================================================ create_model_from_config: configmodel $configmodel """) # concatenate input yaml files yamltext = "" for fn in config_files fnpath = abspath(fn) println(io, " config_file: ", fnpath) isfile(fnpath) || infoerror(io, "config file $fnpath not found") yamltext *= read(fnpath, String) * "\n" # add newline so concatenation correct if one file doesn't have a blank line at end end print(io, """ ================================================================================ """) @info String(take!(io)) data = nothing try data = YAML.load(yamltext) catch e error("$(typeof(e)) while reading .yaml config file(s) $(abspath.(config_files)).\n"* "If the error isn't obvious by looking at the file(s) (often this is a whitespace issue), "* "try an online YAML validator eg http://www.yamllint.com") end conf_model = data[configmodel] for k in keys(conf_model) if !(k in ("parameters", "domains", "geometry_precedence")) error("Model configuration error invalid key '$k'") end end io = IOBuffer() parameters = get(conf_model, "parameters", Dict{String, Any}()) if isnothing(parameters) @warn "empty Model.parameters" parameters = Dict{String,Any}() else println(io, "Model.parameters:") end # extrapars can override parameter from configuration file, but not create new parameters (to catch typos) for (parname, value) in modelpars if haskey(parameters, parname) println(io, " Resetting Model parameter $(rpad(parname, 20)) = $value (configuration file had value=$value)") parameters[parname] = value else error("configuration error: modelpars parameter $parname not present in configuration file for Model parameters:") end end for (parname, value) in parameters println(io, " $(rpad(parname,20)) = $value") end @info String(take!(io)) @timeit "Model" model = Model( config_files=[abspath(fn) for fn in config_files], name=configmodel, parameters=parameters ) conf_domains = conf_model["domains"] @info """ ================================================================================ creating Domains ================================================================================ """ @timeit "creating Domains" begin rdict = find_all_reactions() @info "generated Reaction catalog with $(length(rdict)) Reactions" for (name, conf_domain) in conf_domains nextDomainID = length(model.domains) + 1 @info """ ================================================================================ creating domain '$(name)' ID=$nextDomainID ================================================================================ """ if isnothing(conf_domain) # empty domain will return nothing conf_domain = Dict() end push!( model.domains, create_domain_from_config(name, nextDomainID, conf_domain, model.parameters, rdict) ) end end # timeit # request configuration of Domain sizes, Subdomains @info """ ================================================================================ set_model_geometry ================================================================================ """ for dom in model.domains for react in dom.reactions set_model_geometry(react, model) end end @info """ ================================================================================ register_reaction_methods! ================================================================================ """ @timeit "_register_reaction_methods" _register_reaction_methods!(model) # Link variables @timeit "_link_variables" _link_variables!(model) # sort methods @timeit "_sort_method_dispatch" _sort_method_dispatch!(model, sort_methods_algorithm=sort_methods_algorithm) @info """ ================================================================================ create_model_from_config: done ================================================================================ """ return model end ################################### # setup ################################## """ create_modeldata(model::Model [, eltype] [; threadsafe]) -> modeldata::ModelData Create a new [`ModelData`](@ref) struct for model variables of element type `eltype`. """ function create_modeldata( model::Model, arrays_eltype::DataType=Float64; threadsafe=false, allocatenans=true, # fill Arrays with NaN when first allocated ) modeldata = ModelData(model; arrays_eltype, threadsafe, allocatenans) modeldata.cellranges_all = create_default_cellrange(model) return modeldata end """ create_default_cellrange(model::Model [; operatorID=0]) -> Vector{AbstractCellRange} Create a `Vector` of `CellRange` instances covering the entire model. """ function create_default_cellrange(model::Model ; operatorID=0) cellranges_all = Vector{AbstractCellRange}() for dom in model.domains push!(cellranges_all, Grids.create_default_cellrange(dom, dom.grid, operatorID=operatorID)) end return cellranges_all end """ 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)`](@ref). """ function allocate_variables!( model::Model, modeldata::AbstractModelData, arrays_idx::Int; kwargs... ) @info """ ================================================================================ allocate_variables! (modeldata arrays_idx=$arrays_idx) ================================================================================ """ check_modeldata(model, modeldata) for dom in model.domains allocate_variables!(dom, modeldata, arrays_idx; kwargs...) end return nothing end """ check_ready(model, modeldata; [throw_on_error=true] [, check_hostdep_varnames=true] [, expect_hostdep_varnames=["global.tforce"]]) -> ready Check all variable pointers set, and no unexpected host-dependent non-state Variables (ie unlinked Variables) """ function check_ready( model::Model, modeldata::AbstractModelData; throw_on_error=true, check_hostdep_varnames=true, expect_hostdep_varnames=["global.tforce"], ) check_modeldata(model, modeldata) ready = true for dom in model.domains # don't exit on first error so display report from all Domains ready = ready && check_ready(dom, modeldata, throw_on_error=false) if check_hostdep_varnames dom_hdv, _ = get_host_variables(dom, VF_Undefined) for hv in dom_hdv fullname_hv = fullname(hv) if !(fullname_hv in expect_hostdep_varnames) io = IOBuffer() println(io, "check_ready: unexpected host-dependent Variable $fullname_hv (usually an unlinked Variable due to eg a "* "missing renaming in the :variable_links sections in the .yaml file, a spelling mistake either "* "in a Variable default name in the code or renaming in the .yaml file, or a missing Reaction)") show_links(io, hv) @warn String(take!(io)) ready = false end end end end if !ready @error "check_ready failed" throw_on_error && error("check_ready failed") end return ready end "Check configuration" function check_configuration( model::Model; throw_on_error=true ) configok = true for dom in model.domains configok = configok && check_configuration(dom, model) end if !configok @error "check_configuration failed" throw_on_error && error("check_configuration failed") end return configok end """ 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) """ function initialize_reactiondata!( model::Model, modeldata::AbstractModelData; arrays_indices=1:num_arrays(modeldata), method_barrier=nothing, create_dispatchlists_all=false, generated_dispatch=true, ) @info """ ================================================================================ initialize_reactiondata! (modeldata arrays_indices=$arrays_indices) ================================================================================ """ check_modeldata(model, modeldata) # TODO using Ref here seems to trade off time to create ReactionMethodDispatchList # and time for first call to do_deriv ?? # (Ref gives fast ReactionMethodDispatchList creation, but slow first do_deriv) # NB: passing Ref to call_method seems to speed up first do_deriv # only for arrays_idx = 1 for arrays_idx in arrays_indices arrays_idx in 1:num_arrays(modeldata) || error("arrays_idx $arrays_idx out of range") if arrays_idx == 1 modeldata.sorted_methodsdata_setup = [ Any[Ref(m), Ref(m.preparefn(m, create_accessors(m, modeldata, 1)))] for m in get_methods(model.sorted_methods_setup) ] end modeldata.sorted_methodsdata_initialize[arrays_idx] = [ Any[Ref(m), Ref(m.preparefn(m, create_accessors(m, modeldata, arrays_idx)))] for m in get_methods(model.sorted_methods_initialize; method_barrier) ] modeldata.sorted_methodsdata_do[arrays_idx] = [ Any[Ref(m), Ref(m.preparefn(m, create_accessors(m, modeldata, arrays_idx)))] for m in get_methods(model.sorted_methods_do; method_barrier) ] end if create_dispatchlists_all # create default dispatchlists_all corresponding to cellranges_all for arrays_idx=1 modeldata.dispatchlists_all = create_dispatch_methodlists(model, modeldata, 1, modeldata.cellranges_all; generated_dispatch) end return nothing end """ 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) """ function dispatch_setup( model::Model, attribute_name, modeldata::AbstractModelData, cellranges=modeldata.cellranges_all ) @info """ ================================================================================ dispatch_setup :$attribute_name ================================================================================ """ check_modeldata(model, modeldata) for (method, vardata) in modeldata.sorted_methodsdata_setup for cr in _dispatch_cellranges(method[], cellranges) call_method(method[], vardata[], cr, attribute_name) end end if attribute_name == :setup copy_base_values!(modeldata) end return nothing end """ 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)`](@ref) and [`initialize_reactiondata!`] for keyword arguments. """ function add_arrays_data!( model::Model, modeldata::AbstractModelData, arrays_eltype::DataType, arrays_tagname::AbstractString; method_barrier=nothing, logger=Logging.NullLogger(), kwargs... ) @info "add_arrays_data! (arrays_eltype=$arrays_eltype, arrays_tagname=$arrays_tagname)" Logging.with_logger(logger) do push_arrays_data!(modeldata, arrays_eltype, arrays_tagname) allocate_variables!(model, modeldata, num_arrays(modeldata); kwargs...) copy_base_values!(modeldata, num_arrays(modeldata)) initialize_reactiondata!( model, modeldata; arrays_indices=num_arrays(modeldata), method_barrier, create_dispatchlists_all=false, ) end return nothing end struct DispatchMethodLists list_initialize # not typed to avoid specializing large Tuples list_do # not typed to avoid specializing large Tuples end """ 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`](@ref). 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 `ReactionMethodDispatchList`s (fast dispatch using generated code, slow compile time), `false` to create `ReactionMethodDispatchListNoGen` (slow dynamic dispatch, fast compile time) """ function create_dispatch_methodlists( model::Model, modeldata::AbstractModelData, arrays_idx::Int, cellranges; verbose=false, generated_dispatch=true, ) check_modeldata(model, modeldata) verbose && @info "list_initialize:\n" arrays_idx in 1:length(modeldata.sorted_methodsdata_initialize) || error("list_initialize: arrays_idx $arrays_idx not available") @timeit "list_initialize" list_initialize = _create_dispatch_methodlist( modeldata.sorted_methodsdata_initialize[arrays_idx], cellranges, generated_dispatch, ) verbose && @info "list_do:\n" arrays_idx in 1:length(modeldata.sorted_methodsdata_do) || error("list_do: arrays_idx $arrays_idx not available") @timeit "list_do" list_do = _create_dispatch_methodlist( modeldata.sorted_methodsdata_do[arrays_idx], cellranges, generated_dispatch, ) DispatchMethodLists(list_initialize, list_do) end function _create_dispatch_methodlist(methodsdata, cellranges, generated_dispatch::Bool) methods, vardatas, crs = Ref{<:AbstractReactionMethod}[], Ref{<:Tuple}[], Union{Nothing, AbstractCellRange}[] @timeit "create arrays" begin for (method, vardata) in methodsdata for cr in _dispatch_cellranges(method[], cellranges) push!(methods, method) push!(vardatas, vardata) push!(crs, cr) end end end # timeit if generated_dispatch @timeit "ReactionMethodDispatchList" rmdl = ReactionMethodDispatchList(methods, vardatas, crs) else @timeit "ReactionMethodDispatchListNoGen" rmdl = ReactionMethodDispatchListNoGen(methods, vardatas, crs) end return rmdl end function _dispatch_cellranges(@nospecialize(method::AbstractReactionMethod), cellranges) if is_do_barrier(method) return (nothing, ) else domain = method.domain operatorID = method.operatorID return Iterators.filter( cr -> (cr.domain === domain) && (cr.operatorID == 0 || cr.operatorID in operatorID), cellranges ) end end #################################### # Main loop methods ##################################### """ 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`](@ref). """ function do_deriv(dispatchlists, deltat::Float64=0.0) dispatch_methodlist(dispatchlists.list_initialize) dispatch_methodlist(dispatchlists.list_do, deltat) return nothing end function do_deriv(dispatchlists, pa::ParameterAggregator, deltat::Float64=0.0) dispatch_methodlist(dispatchlists.list_initialize) # assume initialize methods don't use parameters dispatch_methodlist(dispatchlists.list_do, pa, deltat) return nothing end """ 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`](@ref) fields are Tuples hence are fully Typed, the @generated function emits unrolled code with a function call for each Tuple element. """ function dispatch_methodlist( dl::ReactionMethodDispatchListNoGen, deltat::Float64=0.0 ) for i in eachindex(dl.methods) call_method(dl.methods[i], dl.vardatas[i], dl.cellranges[i], deltat) end return nothing end function dispatch_methodlist( dl::ReactionMethodDispatchListNoGen, pa::ParameterAggregator, deltat::Float64=0.0 ) for j in eachindex(dl.methods) methodref = dl.methods[j] if has_modified_parameters(pa, methodref) call_method(methodref, get_parameters(pa, methodref), dl.vardatas[j], dl.cellranges[j], deltat) else call_method(methodref, dl.vardatas[j], dl.cellranges[j], deltat) end end return nothing end @generated function dispatch_methodlist( dl::ReactionMethodDispatchList{M, V, C}, deltat::Float64=0.0 ) where {M, V, C} # See https://discourse.julialang.org/t/manually-unroll-operations-with-objects-of-tuple/11604 ex = quote ; end # empty expression for j=1:fieldcount(M) push!(ex.args, quote # let # call_method(dl.methods[$j][], dl.vardatas[$j][], dl.cellranges[$j], deltat) # pass Ref to function to reduce compile time call_method(dl.methods[$j], dl.vardatas[$j], dl.cellranges[$j], deltat) # end end ) end push!(ex.args, quote; return nothing; end) return ex end @generated function dispatch_methodlist( dl::ReactionMethodDispatchList{M, V, C}, pa::ParameterAggregator, deltat::Float64=0.0 ) where {M, V, C} # See https://discourse.julialang.org/t/manually-unroll-operations-with-objects-of-tuple/11604 ex = quote ; end # empty expression for j=1:fieldcount(M) push!(ex.args, quote if has_modified_parameters(pa, dl.methods[$j]) call_method(dl.methods[$j], get_parameters(pa, dl.methods[$j]), dl.vardatas[$j], dl.cellranges[$j], deltat) else call_method(dl.methods[$j], dl.vardatas[$j], dl.cellranges[$j], deltat) end end ) end push!(ex.args, quote; return nothing; end) return ex end ################################# # Pretty printing ################################ # compact form function Base.show(io::IO, model::Model) print(io, "Model(config_files='", model.config_files,"', name='", model.name,"')") end # multiline form function Base.show(io::IO, ::MIME"text/plain", model::Model) println(io, "Model") println(io, "\tname='", model.name,"'") println(io, "\tconfig_files='", model.config_files,"'") println(io, "\tdomains=", model.domains) end """ show_methods_setup(model::Model) Display ordered list of Reaction setup methods (registered by [`add_method_setup!`](@ref), called by [`dispatch_setup`](@ref)) """ function show_methods_setup(model::Model) println("All methods_setup:") println(model.sorted_methods_setup) return nothing end """ show_methods_initialize(model::Model) Display ordered list of Reaction initialize methods (registered by [`add_method_initialize!`](@ref), called by [`do_deriv`](@ref) at start of each model timestep). """ function show_methods_initialize(model::Model) println("All methods_initialize:") println(model.sorted_methods_initialize) return nothing end """ show_methods_do(model::Model) Display ordered list of Reaction do methods (registered by [`add_method_do!`](@ref), called by [`do_deriv`](@ref) for each model timestep). """ function show_methods_do(model::Model) println("All methods_do:") println(model.sorted_methods_do) return nothing end """ show_variables(model::Model; [attributes], [filter], showlinks=false, modeldata=nothing) -> DataFrame show_variables(model::Model, domainname; [attributes], [filter], showlinks=false, modeldata=nothing) -> DataFrame Show table of Domain Variables. Optionally get variable links, data. # Keywords: See [`show_variables(domain::Domain, kwargs...)`](@ref) # Examples: Display all model Variables using VS Code table viewer: julia> vscodedisplay(PB.show_variables(run.model)) Write out all model Variables as csv for import to a spreadsheet: julia> CSV.write("vars.csv", PB.show_variables(run.model, modeldata=modeldata, showlinks=true)) """ function show_variables(model::Model; kwargs...) df = DataFrames.DataFrame() for dom in model.domains dfdom = show_variables(dom; kwargs...) # prepend domain name DataFrames.insertcols!(dfdom, 1, :domain=>fill(dom.name, size(dfdom,1))) # append to df df = vcat(df, dfdom) end DataFrames.sort!(df, [:domain, :name]) return df end function show_variables(model::Model, domainname::AbstractString; kwargs...) dom = get_domain(model, domainname; allow_not_found=false) return show_variables(dom; kwargs...) end show_links(model::Model, varnamefull::AbstractString) = show_links(stdout, model, varnamefull) function show_links(io::IO, model::Model, varnamefull::AbstractString) vardom = get_variable(model, varnamefull; allow_not_found=false) show_links(io, vardom) end """ 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)) """ function show_parameters(model::Model) df = DataFrames.DataFrame() for dom in model.domains for react in dom.reactions dfreact = show_parameters(react) DataFrames.insertcols!(dfreact, 1, :reaction=>fill(react.name, size(dfreact,1))) DataFrames.insertcols!(dfreact, 2, :classname=>fill(react.classname, size(dfreact,1))) DataFrames.insertcols!(dfreact, 1, :domain=>fill(dom.name, size(dfreact,1))) # append to df df = vcat(df, dfreact) end end DataFrames.sort!(df, [:domain, :reaction, :name]) return df end ###################################### # Variable linking ####################################### """ _link_variables!(model::Model) -> nothing Populate `Domain` variable lists, renaming and linking Reaction variables """ function _link_variables!(model::Model) # First pass - variables defined in config file foreach(_link_clear!, model.domains) @info """ ================================================================================ link_variables: first pass ================================================================================ """ # _link_variables!(model, _link_print) _link_variables!(model, _link_create, false) _link_variables!(model, _link_create_contrib, false) _link_variables!(model, _link_create_dep, false) _link_variables!(model, _link_link, false) # Allow reactions to define additional variables, based on # the model structure @info """ ================================================================================ link_variables: register_reaction_dynamic_methods and configure variables ================================================================================ """ _register_reaction_dynamic_methods!(model) # Second pass including additional variables foreach(_link_clear!, model.domains) @info """ ================================================================================ link_variables: second pass: ================================================================================ """ _link_variables!(model, _link_print, true) _link_variables!(model, _link_create, true) _link_variables!(model, _link_create_contrib, true) _link_variables!(model, _link_create_dep, true) _link_variables!(model, _link_link, true) io = IOBuffer() print(io, """ ================================================================================ link_variables! unlinked variables: ================================================================================ """) _link_variables!(model, _link_print_not_linked, io) @info String(take!(io)) return nothing end """ relink_variables!(model::Model) -> nothing Optional relink `Reaction` variables and repopulate `Domain` Variable lists. Only needed if modifying `variable_links` after calling [`create_model_from_config`](@ref) NB: dynamic Variables are not recreated, so will not reflect any changes """ function relink_variables!(model::Model) foreach(_link_clear!, model.domains) @info """ ================================================================================ relink_variables!: ================================================================================ """ _link_variables!(model, _link_print, true) _link_variables!(model, _link_create, true) _link_variables!(model, _link_create_contrib, true) _link_variables!(model, _link_create_dep, true) _link_variables!(model, _link_link, true) io = IOBuffer() println(io, """ ================================================================================ relink_variables! unlinked variables: ================================================================================ """) _link_variables!(model, _link_print_not_linked, io) @info String(take!(io)) return nothing end function _link_variables!(model::Model, oper, dolog) for dom in model.domains _link_variables!(dom, model, oper, dolog) end end ############################ # Method registration and ordering ############################## function _register_reaction_methods!(model::Model) for dom in model.domains for r in dom.reactions _register_methods!(r, model) # not all methods registered and ReactionVariables available, so no error if missing _configure_variables(r; allow_missing=true, dolog=false) end end return nothing end function _register_reaction_dynamic_methods!(model::Model) for dom in model.domains for r in dom.reactions register_dynamic_methods!(r, model) _configure_variables(r; allow_missing=false, dolog=true) end end return nothing end get_methods_setup(model; kwargs...) = _get_methods(model, :methods_setup) get_methods_initialize(model; kwargs...) = _get_methods(model, :methods_initialize) get_methods_do(model; kwargs...) = _get_methods(model, :methods_do) function _get_methods(model::Model, mfield::Symbol; filterfn=m->!is_do_nothing(m)) methods=ReactionMethod[] for dom in model.domains for r in dom.reactions append!(methods, filter(filterfn, getproperty(r, mfield))) end end return methods end """ _sort_method_dispatch!(model::Model) -> nothing Sort methods into dispatch order, based on variable dependencies """ function _sort_method_dispatch!(model::Model; sort_methods_algorithm=group_methods) # create unsorted list of all Reactions in model all_reacts = Vector{AbstractReaction}() for dom in model.domains append!(all_reacts, dom.reactions) end # get all domain Variables all_domvars = Vector{VariableDomain}() for dom in model.domains append!(all_domvars, get_variables(dom)) end methods_setup = get_methods_setup(model) model.sorted_methods_setup = sort_methods_algorithm(methods_setup, all_domvars) methods_initialize = get_methods_initialize(model) # TODO no sort needed as no dependencies allowed model.sorted_methods_initialize = sort_methods_algorithm(methods_initialize, all_domvars) methods_do = get_methods_do(model) model.sorted_methods_do = sort_methods_algorithm(methods_do, all_domvars) return nothing end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
6329
""" DomainData struct to hold VariableDomain data. """ Base.@kwdef mutable struct DomainData <: AbstractDomainData domain::Domain variable_data::Vector{Any} = Vector{Any}() end function DomainData(domain) domaindata = DomainData(domain = domain, variable_data = fill(nothing, get_num_variables(domain))) return domaindata end """ 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!`](@ref), 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. """ Base.@kwdef mutable struct ModelData <: AbstractModelData model::Model domain_data::Vector{Tuple{DataType, String, Vector{DomainData}}} = Tuple{DataType, String, Vector{DomainData}}[] threadsafe::Bool allocatenans::Bool # fill with NaN when allocating sorted_methodsdata_setup = nothing # only for arrays_idx = 1 sorted_methodsdata_initialize = [] # one per arrays_idx sorted_methodsdata_do = [] # one per arrays_idx cellranges_all::Vector{AbstractCellRange} = Vector{AbstractCellRange}() dispatchlists_all = nothing # only for arrays_idx = 1 solver_view_all = nothing # only for arrays_idx = 1 end function ModelData(model::Model; arrays_eltype::DataType=Float64, threadsafe::Bool=false, allocatenans::Bool=true) modeldata = ModelData(; model, threadsafe, allocatenans, ) push_arrays_data!(modeldata, arrays_eltype, "base") return modeldata end """ push_arrays_data!(modeldata, arrays_eltype::DataType, arrays_tagname::AbstractString) Add an (unallocated) additional array set with element type `arrays_eltype`. """ function push_arrays_data!(modeldata::ModelData, arrays_eltype::DataType, arrays_tagname::AbstractString) isnothing(find_arrays_idx(modeldata, arrays_tagname::AbstractString)) || throw(ArgumentError("arrays_tagname $arrays_tagname already exists")) push!(modeldata.domain_data, (arrays_eltype, arrays_tagname, [DomainData(dom) for dom in modeldata.model.domains])) resize!(modeldata.sorted_methodsdata_initialize, num_arrays(modeldata)) resize!(modeldata.sorted_methodsdata_do, num_arrays(modeldata)) return nothing end """ pop_arrays_data!(modeldata) Remove last array set (NB: base array set with `arrays_idx==1`) cannot be removed). """ function pop_arrays_data!(modeldata::ModelData) length(modeldata.domain_data) > 1 || error("cannot remove base domain_data") return pop!(modeldata.domain_data) end num_arrays(modeldata::ModelData) = length(modeldata.domain_data) find_arrays_idx(modeldata::ModelData, arrays_eltype::DataType) = findfirst(x -> x[1] == arrays_eltype, modeldata.domain_data) find_arrays_idx(modeldata::ModelData, arrays_tagname::AbstractString) = findfirst(x -> [2] == arrays_tagname, modeldata.domain_data) """ copy_base_values!(modeldata::ModelData, array_indices=2:num_arrays(modeldata)) Copy array contents from base `arrays_idx=1` to other `array_indices` """ function copy_base_values!(modeldata::ModelData, array_indices=2:num_arrays(modeldata)) base_domain_data = first(modeldata.domain_data) _, _, base_data = base_domain_data for ai in array_indices domain_data = modeldata.domain_data[ai] dd_eltype, dd_tagname, dd_data = domain_data @info "copy_base_values! copying to modeldata arrays_index $ai ($dd_eltype, $dd_tagname)" for (dbase, d) in IteratorUtils.zipstrict(base_data, dd_data) for (vardata_base, vardata) in IteratorUtils.zipstrict(dbase.variable_data, d.variable_data) if !isnothing(vardata) # non-base arrays may not be allocated if vardata !== vardata_base # non-base array may just be a "link" to the same array vardata.values .= vardata_base.values end end end end end return nothing end """ eltype(modeldata::ModelData, arrays_idx::Int) -> DataType eltype(modeldata::ModelData, arrays_tagname::AbstractString) Determine the type of Array elements for ModelData """ function Base.eltype(modeldata::ModelData, arrays_idx::Int) arrays_idx in 1:length(modeldata.domain_data) || throw(ArgumentError("arrays_idx $arrays_idx out of range")) return modeldata.domain_data[arrays_idx][1] end function Base.eltype(modeldata::ModelData, arrays_tagname::AbstractString) arrays_idx = find_arrays_idx(modeldata, arrays_tagname) !isnothing(arrays_idx) || throw(ArgumentError("arrays_tagname $arrays_tagname not found")) return eltype(modeldata, arrays_idx) end Base.eltype(modeldata::ModelData) = error("eltype(modeldata) not supported") "Check ModelData consistent with Model" function check_modeldata(model::Model, modeldata::ModelData) if model === modeldata.model return nothing else error("modeldata inconsistent with model - check for missing call to create_modeldata") end end # compact form function Base.show(io::IO, md::ModelData) print(io, "ModelData(model=", md.model, ", domain_data=", [(x[1], x[2]) for x in md.domain_data], ")") end # multiline form function Base.show(io::IO, ::MIME"text/plain", md::ModelData) println(io, "ModelData") println(io, " model=", md.model) println(io, " domain_data=", [(x[1], x[2]) for x in md.domain_data]) println(io, " solver_view_all=", md.solver_view_all) end function get_domaindata(modeldata::ModelData, domain::AbstractDomain, arrays_idx::Int) arrays_idx in 1:length(modeldata.domain_data) || throw(ArgumentError("arrays_idx $arrays_idx out of range")) return modeldata.domain_data[arrays_idx][3][domain.ID] end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
7400
""" PALEOboxes PALEOboxes provides the model coupler for the PALEO model framework. It is registered as a Julia package with public github repository [PALEOboxes.jl](https://github.com/PALEOtoolkit/PALEOboxes.jl) and online [documentation](https://paleotoolkit.github.io/PALEOboxes.jl) A PALEO `Model` contains `Domain`s, each of which contain Variables defining `Field`s containing `Data` arrays, and Reactions with `ReactionMethod`s that operate on the Variables to calculate model time evolution. PALEOboxes creates the model from a .yaml configuration file, and 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. """ module PALEOboxes import YAML import Graphs # formerly LightGraphs import DataFrames using DocStringExtensions import OrderedCollections import Logging import Printf import PrecompileTools import TimerOutputs: @timeit, @timeit_debug include("utils/DocStrings.jl") include("Types.jl") include("CoordsDims.jl") include("Fields.jl") include("data/AtomicScalar.jl") include("data/ScalarData.jl") include("data/ArrayScalarData.jl") include("data/IsotopeData.jl") include("VariableAttributes.jl") include("VariableReaction.jl") include("VariableDomain.jl") include("Parameter.jl") include("ParameterAggregator.jl") include("ReactionMethodSorting.jl") include("Model.jl") include("Domain.jl") include("CellRange.jl") include("ReactionMethod.jl") include("Reaction.jl") include("ReactionFactory.jl") include("ModelData.jl") include("Grids.jl") include("reactionmethods/SetupInitializeUtilityMethods.jl") include("reactionmethods/VariableStatsMethods.jl") include("reactionmethods/RateStoich.jl") include("utils/Interpolation.jl") include("utils/TestUtils.jl") include("utils/SIMDutils.jl") include("utils/IteratorUtils.jl") include("utils/DocUtils.jl") include("variableaggregators/VariableAggregator.jl") include("reactioncatalog/Reactions.jl") # Deprecated functions """ get_statevar DEPRECATED - moved to PALEOmodel """ function get_statevar end """ get_statevar_norm DEPRECATED - moved to PALEOmodel """ function get_statevar_norm end ##################################################### # Precompilation # Run code to precompile ####################################################### """ precompile_reaction(rdict::Dict{String, Type}, classname::AbstractString; logger=Logging.NullLogger()) precompile_reaction(ReactionType::Type{<:AbstractReaction}; logger=Logging.NullLogger()) For use in @PrecompileTools.compile_workload: create Reaction and call register_methods """ function precompile_reaction(rdict::Dict{String, Type}, classname::AbstractString; logger=Logging.NullLogger()) try Logging.with_logger(logger) do rj = create_reaction(rdict, classname, "test", Dict{String, Any}()) rj.base.domain = Domain(name="test", ID=1, parameters=Dict{String, Any}()) register_methods!(rj) end catch ex @warn "precompile_reaction(rdict, $classname) failed with exception:" ex end return nothing end function precompile_reaction(ReactionType::Type{<:AbstractReaction}; logger=Logging.NullLogger()) try Logging.with_logger(logger) do rj = create_reaction(ReactionType, "test", Dict{String, Any}()) rj.base.domain = Domain(name="test", ID=1, parameters=Dict{String, Any}()) register_methods!(rj) end catch ex @warn "precompile_reaction($ReactionType) failed with exception:" ex end return nothing end """ run_model(configfile::AbstractString, configname::AbstractString; call_do_deriv=true, tforce=0.0, logger=Logging.NullLogger()) run_model(model::Model; call_do_deriv=true, tforce=0.0, logger=Logging.NullLogger()) For use in @PrecompileTools.compile_workload: create_model_from_config and optionally call do_deriv at time tforce """ function run_model(configfile::AbstractString, configname::AbstractString; logger=Logging.NullLogger(), kwargs...) try model = Logging.with_logger(logger) do create_model_from_config(configfile, configname) end run_model(model; logger, kwargs...) catch ex @warn "run_model($configfile, $configname) failed with exception:" ex end return nothing end function run_model(model::Model; call_do_deriv=true, tforce=0.0, logger=Logging.NullLogger()) try Logging.with_logger(logger) do arrays_idx = 1 modeldata = create_modeldata(model) allocate_variables!(model, modeldata, arrays_idx) check_ready(model, modeldata) initialize_reactiondata!(model, modeldata; create_dispatchlists_all=true) check_configuration(model) dispatch_setup(model, :setup, modeldata) dispatch_setup(model, :norm_value, modeldata) dispatch_setup(model, :initial_value, modeldata) # take a time step at forcing time tforce - TODO, can be model dependent on missing setup if call_do_deriv # set tforce (if present) hostdep_vars = VariableDomain[] for dom in model.domains dv, _ = get_host_variables(dom, VF_Undefined) append!(hostdep_vars, dv ) end hostdep = VariableAggregatorNamed(hostdep_vars, modeldata, arrays_idx) set_values!(hostdep, Val(:global), Val(:tforce), tforce; allow_missing=true) dispatchlists = modeldata.dispatchlists_all do_deriv(dispatchlists) end end catch ex @warn "run_model($model; call_do_deriv=$call_do_deriv) failed with exception:" ex end return nothing end @PrecompileTools.setup_workload begin # create Reactions and register methods to precompile this code # Putting some things in `setup` can reduce the size of the # precompile file and potentially make loading faster. rdict = find_all_reactions() reactionlist = [ "ReactionFluxTransfer", "ReactionReservoirScalar", "ReactionFluxPerturb", "ReactionReservoir", "ReactionReservoirForced", "ReactionSum", "ReactionFluxTarget", "ReactionForceInterp", "ReactionGrid2DNetCDF", "ReactionAreaVolumeValInRange", "ReactionReservoirWellMixed", "ReactionForceGrid", "ReactionConst", "ReactionRestore", "ReactionScalarConst", "ReactionVectorSum", "ReactionWeightedMean", "ReactionReservoirTotal", "ReactionUnstructuredVectorGrid", "ReactionCartesianGrid", "ReactionReservoirConst", ] @PrecompileTools.compile_workload begin # all calls in this block will be precompiled, regardless of whether # they belong to your package or not (on Julia 1.8 and higher) for r in reactionlist precompile_reaction(rdict, r) end # Negligible difference ? run_model(joinpath(@__DIR__, "../test/configreservoirs.yaml"), "model1") run_model(joinpath(@__DIR__, "../test/configfluxes.yaml"), "model1") end end end # module
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
16238
import Preferences """ AbstractParameter Base Type for Parameters See also: [`Parameter`](@ref), [`VecParameter`](@ref), [`VecVecParameter`](@ref) """ AbstractParameter """ Parameter{T, ParseFromString} A reaction parameter of type `T`. Create using short names `ParDouble`, `ParInt`, `ParBool`, `ParString`. Read value as `<par>[]`, set with [`setvalue!`](@ref). 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!`](@ref). If `ParseFromString` is not `Nothing`, then [`setvalue!`](@ref) 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) """ mutable struct Parameter{T, ParseFromString} <: AbstractParameter name::String description::String units::String "value" v::T default_value::T allowed_values::Vector{T} frozen::Bool external::Bool end # Parameter behaves as a minimal 0D array (NB: doesn't support full Array interface) Base.getindex(parameter::Parameter) = parameter.v Base.size(parameter::Parameter) = Tuple{}() Base.length(parameter::Parameter) = 1 """ ParDouble(name, defaultvalue::Float64; units="", description="", external=false) """ function ParDouble( name, defaultvalue::Float64; units="", description="", external=false ) return Parameter{Float64, Nothing}( name, description, units, defaultvalue, defaultvalue, Vector{Float64}(), false, external ) end """ ParInt(name, defaultvalue::Integer; units="", description="", allowed_values=Vector{Int}(), external=false) """ function ParInt( name, defaultvalue::Integer; units="", description="", allowed_values=Vector{Int}(), external=false ) # splat allowed_values to allow Tuple etc return Parameter{Int, Nothing}( name, description, units, defaultvalue, defaultvalue, [allowed_values...], false, external ) end """ ParEnum(name, defaultvalue::T; units="", description="", allowed_values=Vector{T}(), external=false) T can be an Enum (or any Type) that implements Base.parse. """ function ParEnum( name, defaultvalue::T; units="", description="", allowed_values=Vector{T}(), external=false ) where {T} # splat allowed_values to allow Tuple etc return Parameter{T, T}( name, description, units, defaultvalue, defaultvalue, [allowed_values...], false, external ) end """ ParType(::Type{T}, name, defaultvalue; units="", description="", allowed_values=Vector{T}(), external=false) T can be an abstract Type that implements Base.parse. """ function ParType( ::Type{T}, name, defaultvalue::Type{D}; units="", description="", allowed_values=Vector{Type}(), external=false ) where {T, D <: T} # splat allowed_values to allow Tuple etc return Parameter{Type, T}( name, description, units, defaultvalue, defaultvalue, [allowed_values...], false, external ) end """ ParBool(name, defaultvalue::Bool; description="", external=false) """ function ParBool( name, defaultvalue::Bool; description="", external=false ) return Parameter{Bool, Nothing}( name, description, "", defaultvalue, defaultvalue, Vector{Bool}(), false, external ) end """ ParString(name, defaultvalue::String; description="", allowed_values=Vector{String}(), external=false) """ function ParString( name, defaultvalue::String; description="", allowed_values=Vector{String}(), external=false ) # splat allowed_values to allow Tuple etc par = Parameter{String, Nothing}( name, description, "", defaultvalue, defaultvalue, [allowed_values...], false, external ) setvalue!(par, defaultvalue) # catch attempt to set a defaultvalue not in allowed_values return par end """ 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!`](@ref), in config file use standard yaml syntax for a vector eg [1, 2, 3] See [`Parameter`](@ref) 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`. """ mutable struct VecParameter{T, ParseFromString} <: AbstractParameter name::String description::String units::String v::Vector{T} default_value::Vector{T} allowed_values::Vector{T} frozen::Bool external::Bool end # VecParameter behaves as a minimal 1D array (NB: doesn't support full Array interface) Base.getindex(p::VecParameter, index) = p.v[index] Base.firstindex(p::VecParameter) = firstindex(p.v) Base.lastindex(p::VecParameter) = lastindex(p.v) Base.size(p::VecParameter) = size(p.v) Base.length(p::VecParameter) = length(p.v) Base.iterate(p::VecParameter, state=1) = state > length(p) ? nothing : (p.v[state], state+1) Base.keys(p::VecParameter) = keys(p.v) Base.eltype(::Type{VecParameter{T, ParseFromString}}) where {T, ParseFromString} = T """ ParDoubleVec(name, defaultvalue::Vector{Float64}; units="", description="", external=false) """ function ParDoubleVec( name, defaultvalue::Vector{Float64}; units="", description="", external=false ) return VecParameter{Float64, Nothing}( name, description, units, defaultvalue, defaultvalue, Vector{Float64}(), false, external ) end """ ParIntVec(name, defaultvalue::Vector{Integer}; units="", description="", allowed_values=Vector{Int}(), external=false) """ function ParIntVec( name, defaultvalue::Vector{Int}; units="", description="", allowed_values=Vector{Int}(), external=false ) # splat allowed_values to allow Tuple etc par = VecParameter{Int, Nothing}( name, description, units, defaultvalue, defaultvalue, [allowed_values...], false, external ) setvalue!(par, defaultvalue) # catch attempt to set defaultvalue not in allowed_values return par end """ ParBoolVec(name, defaultvalue::Vector{Bool}; description="", external=false) """ function ParBoolVec( name, defaultvalue::Vector{Bool}; description="", external=false ) return VecParameter{Bool, Nothing}( name, description, "", defaultvalue, defaultvalue, Vector{Bool}(), false, external ) end """ ParStringVec(name, defaultvalue::Vector{String}; description="", external=false) """ function ParStringVec( name, defaultvalue::Vector{String}=String[]; description="", allowed_values=Vector{String}(), external=false ) # splat allowed_values to allow Tuple etc par = VecParameter{String, Nothing}( name, description, "", defaultvalue, defaultvalue, [allowed_values...], false, external ) setvalue!(par, defaultvalue) # catch attempt to set defaultvalue not in allowed_values return par end """ 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`](@ref) for additional documentation. """ mutable struct VecVecParameter{T, ParseFromString} <: AbstractParameter name::String description::String units::String v::Vector{Vector{T}} default_value::Vector{Vector{T}} allowed_values::Vector{T} # Int, String only frozen::Bool external::Bool end """ ParDoubleVecVec(name, defaultvalue::Vector{Vector{Float64}}; units="", description="", external=false) """ function ParDoubleVecVec( name, defaultvalue::Vector{Vector{Float64}} = Vector{Vector{Float64}}(); units="", description="", external=false ) par = VecVecParameter{Float64, Nothing}( name, description, units, defaultvalue, defaultvalue, Vector{Float64}(), false, external ) return par end """ check_parameter_sum(parameter::VecParameter, ncells) -> sumok::Bool Check whether `parameter` is of length `ncells` and correctly normalized to sum to 1.0 """ function check_parameter_sum(parameter::VecParameter, ncells; tol=1e-3) sumok = true isnothing(ncells) || length(parameter.v) == ncells || (sumok = false; @error "config error: length($(parameter.name)) != $ncells") sumpar = sum(parameter.v) abs(sumpar - 1.0) < tol || (sumok = false; @error "config error: sum($(parameter.name)) = $sumpar != 1 +/- $(tol)") return sumok end """ vecvecpar_matrix(par::VecVecParameter) -> Matrix Convert `par.v` to a Matrix # Examples: ```jldoctest; setup = :(import PALEOboxes) julia> p = PB.ParDoubleVecVec("pdvv"); julia> PB.setvalue!(p, [[1.0, 2.0], [3.0, 4.0]]); julia> PB.vecvecpar_matrix(p) 2×2 Array{Float64,2}: 1.0 2.0 3.0 4.0 ``` """ function vecvecpar_matrix(par::VecVecParameter{T}) where T nrows = length(par.v) if nrows == 0 return Matrix{T}(undef, 0, 0) end ncols = length(par.v[1]) m = Matrix{T}(undef, nrows, ncols) for (i, rowvals) in enumerate(par.v) length(rowvals) == ncols || error("par is not convertable to a matrix: ", par) m[i, :] .= rowvals end return m end "Prevent modification via properties" function Base.setproperty!(par::AbstractParameter, s::Symbol, v) error("setproperty! attempt to set Parameter $(par.name).$s=$v (use setvalue! to set :v)") end # Default - no attempt to parse value from String function _parsevalue(par::Union{Parameter{T, Nothing}, VecParameter{T, Nothing}, VecVecParameter{T, Nothing}}, value) where {T} return value end function _parsevalue(par::Union{Parameter{T, Nothing}, VecParameter{T, Nothing}, VecVecParameter{T, Nothing}}, value::AbstractString) where {T} return value end # any (Data)Type - any subtype of PT is acceptable function _parsevalue(par::Union{Parameter{T, PT}, VecParameter{T, PT}, VecVecParameter{T, PT}}, value::Type{V}) where {T, PT, V <: PT} return value end # enum is a value of type T function _parsevalue(par::Union{Parameter{T, T}, VecParameter{T, T}, VecVecParameter{T, T}}, value::T) where {T} return parse(T, value) end # attempt to parse value::PT from AbstractString function _parsevalue(par::Union{Parameter{T, PT}, VecParameter{T, PT}, VecVecParameter{T, PT}}, value::AbstractString) where {T, PT} return parse(PT, value) end """ setvalue!(par::Parameter, value) Set Parameter to `value`. Optionally (if [`Parameter`](@ref) has Type parameter `ParseFromString != Nothing`) parse `value` from a String. """ function setvalue!(par::Parameter, rawvalue) value = _parsevalue(par, rawvalue) if !isempty(par.allowed_values) && !(value in par.allowed_values) error("setvalue! attempt to set Parameter $(par.name) to invalid value=$value (allowed_values=$(par.allowed_values))") end if par.frozen error("setvalue! Parameter $(par.name) can no longer be modified") end setfield!(par, :v, value) return nothing end function setvalue!(par::VecParameter, values) if !isempty(par.allowed_values) for rawv in values v = _parsevalue(par, rawv) if !(v in par.allowed_values) error("setvalue! attempt to set VecParameter $(par.name) to $values with invalid value(s) (allowed_values=$(par.allowed_values))") end end end if par.frozen error("setvalue! Parameter $(par.name) can no longer be modified") end setfield!(par, :v, values) return nothing end # allow an empty Vector{Any} (as that is what yaml provides for []) function setvalue!(par::VecParameter{T, ParseFromString}, values::Vector{Any}) where{T, ParseFromString} if isempty(values) return setvalue!(par, T[]) else return setvalue!(par, values) # will error end end function setvalue!(par::VecVecParameter, values) if !isempty(par.allowed_values) for rawv in Iterators.Flatten(values) v = _parsevalue(par, rawv) if !(v in par.allowed_values) error("setvalue! attempt to set VecVecParameter $(par.name) to $values with invalid value(s) (allowed_values=$(par.allowed_values))") end end end if par.frozen error("setvalue! Parameter $(par.name) can no longer be modified") end setfield!(par, :v, values) return nothing end """ setvalueanddefault!(par::Parameter, value; freeze=false) Set Parameter value and default to `value`. Optionally (if [`Parameter`](@ref) has Type parameter `ParseFromString != Nothing`) parse `value` from a String. """ function setvalueanddefault!(par::Union{Parameter, VecParameter, VecVecParameter}, rawvalue; freeze=false) value = _parsevalue(par, rawvalue) setvalue!(par, value) setfield!(par, :default_value, value) if freeze setfrozen!(par) end return nothing end """ externalvalue(io, rawvalue::AbstractString, external_parameters) -> value Replace `"external%somename"`` with `external_parameters["somename"]` Write log message to io """ function externalvalue(io::IO, rawvalue::AbstractString, external_parameters) # substitute 'external%parname' with value of external parameter 'parname' if length(rawvalue) > 9 && findfirst("external%", rawvalue) == 1:9 externalkey = rawvalue[10:end] if haskey(external_parameters, externalkey) value = external_parameters[externalkey] println(io, " expandvalue: $rawvalue -> $value") else error(" $(rawvalue) external parameter $(externalkey) not found") end else value = rawvalue end return value end "Non-string values returned unmodified" externalvalue(io::IO, rawvalue, external_parameters) = rawvalue function externalvalue(rawvalue, external_parameters) io = IOBuffer() ev = externalvalue(io, rawvalue, external_parameters) iszero(io.size) || @info String(take!(io)) return ev end """ substitutevalue(module, rawvalue::AbstractString) -> value Substitute "\$MyLocalSetting\$" with the value of the MyLocalSetting key in the Julia LocalPreferences.toml file, from the section for `module` (for a Reaction Parameter value, this should be the Julia module of the Reaction containing the Parameter). """ function substitutevalue(mod::Module, rawvalue::AbstractString; dontsub=("\$fluxname\$",)) value = rawvalue for m in eachmatch(r"\$\w+\$", rawvalue) if m.match in dontsub # dont substitute continue end # look up in LocalPreferences.toml subval = m.match[2:end-1] # omit $ $ # if a Reaction is not part of a package (eg development code), use Preferences package instead to look for a key if isnothing(Base.PkgId(mod).uuid) @warn "substitutevalue $subval - Module $(mod) does not correspond to a loaded package, using a key from [PALEOboxes] instead" mod = PALEOboxes end Preferences.has_preference(mod, String(subval)) || error("substitutevalue: key [$(Base.PkgId(mod).name)] $subval not found in LocalPreferences.toml") replacestr = Preferences.load_preference(mod, String(subval)) value = replace(value, m.match => replacestr) end return value end "Return non-string values unmodified" substitutevalue(mod::Module, rawvalue) = rawvalue function setfrozen!(parameters::AbstractParameter...) for par in parameters setfield!(par, :frozen, true) end end """ ParametersTuple(parameters::AbstractParameter...) -> NamedTuple ParametersTuple(parameters) -> NamedTuple Create a NamedTuple of Parameters. """ function ParametersTuple(parameters::AbstractParameter...) return NamedTuple{Tuple(Symbol(par.name) for par in parameters)}(parameters) end ParametersTuple(parameters) = ParametersTuple(parameters...)
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
8343
############################################################################################ # ParameterAggregator ########################################################################################### """ 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. """ mutable struct ParameterAggregator{T} # Parameter full names parfullnames::Vector{String} # replacement Parameters to be used (order matches parfullnames) replacement_parameters::Vector{Union{Parameter{T, Nothing}, VecParameter{T, Nothing}}} # indices in flattened p Vector for each replacement parameter indices::Vector{UnitRange{Int64}} # normalization (as flattened vector) for parameters norm_values::Vector{Float64} # reactions with replacement parameter values (each entry is a Dict of :par_name => index in replacement_parameters) reactpars::Dict{AbstractReaction, Dict{Symbol, Int}} # replacement ParametersTuple (merging replacement parameters with all reaction parameters), # for those reactions that need parameter replacement reactpartuples::Dict{AbstractReaction, NamedTuple} end # compact form function Base.show(io::IO, pa::ParameterAggregator) print(io, "ParameterAggregator(parfullnames='", pa.parfullnames,"', indices='", pa.indices,"')") end # multiline form function Base.show(io::IO, ::MIME"text/plain", pa::ParameterAggregator) println(io, typeof(pa)) Printf.@printf(io, "%40s%20s\n", "parfullname", "indices") for (pfn, i) in IteratorUtils.zipstrict(pa.parfullnames, pa.indices) Printf.@printf(io, "%40s%20s\n", pfn, string(i)) end end function ParameterAggregator(model::AbstractModel, parfullnames::Vector{String}; eltype=Float64) reactpars = Dict{AbstractReaction, Dict{Symbol, Int}}() replacement_parameters = Vector{Union{Parameter{eltype, Nothing}, VecParameter{eltype, Nothing}}}() indices = UnitRange{Int}[] nextidx = 1 # iterate through parfullnames and assemble lists of replacement parameters and corresponding indices in flattened vector for (pidx, domreactpar) in enumerate(parfullnames) domainname, reactionname, parname = split(domreactpar, ".") react = get_reaction(model, domainname, reactionname; allow_not_found=false) p = get_parameter(react, parname) if p isa Parameter{Float64, Nothing} replace_p = Parameter{eltype, Nothing}( p.name, p.description, p.units, eltype(p.v), eltype(p.default_value), eltype[], false, p.external ) elseif p isa VecParameter{Float64, Nothing} replace_p = VecParameter{eltype, Nothing}( p.name, p.description, p.units, Vector{eltype}(p.v), Vector{eltype}(p.default_value), eltype[], false, p.external ) else error("parameter $domreactpar $p is not a ParDouble or ParDoubleVec") end rparsindices = get!(reactpars, react, Dict{Symbol, Int}()) rparsindices[Symbol(parname)] = pidx push!(replacement_parameters, replace_p) endidx = nextidx + length(replace_p) - 1 push!(indices, nextidx:endidx) nextidx = endidx + 1 end # generate new ParametersTuple for those reactions that need parameter replacement reactpartuples = Dict{AbstractReaction, NamedTuple}() for (react, rparsindices) in reactpars newparstuple = (haskey(rparsindices, k) ? replacement_parameters[rparsindices[k]] : v for (k, v) in pairs(react.pars)) reactpartuples[react] = NamedTuple{keys(react.pars)}(newparstuple) end norm_values = ones(indices[end][end]) return ParameterAggregator{eltype}( parfullnames, replacement_parameters, indices, norm_values, reactpars, reactpartuples, ) end Base.copy(pa::ParameterAggregator{old_eltype}) where {old_eltype} = copy_new_eltype(old_eltype, pa) function copy_new_eltype(new_eltype, pa::ParameterAggregator{old_eltype}) where {old_eltype} replacement_parameters = Vector{Union{Parameter{new_eltype, Nothing}, VecParameter{new_eltype, Nothing}}}() for p in pa.replacement_parameters if p isa Parameter{old_eltype, Nothing} replace_p = Parameter{new_eltype, Nothing}( p.name, p.description, p.units, new_eltype(p.v), new_eltype(p.default_value), new_eltype[], false, p.external ) elseif p isa VecParameter{old_eltype, Nothing} replace_p = VecParameter{new_eltype, Nothing}( p.name, p.description, p.units, Vector{new_eltype}(p.v), Vector{new_eltype}(p.default_value), new_eltype[], false, p.external ) else error("parameter $p is not a scalar or vector parameter with eltype $old_eltype") end push!(replacement_parameters, replace_p) end # generate new ParametersTuple for those reactions that need parameter replacement reactpartuples = Dict{AbstractReaction, NamedTuple}() for (react, rparsindices) in pa.reactpars newparstuple = (haskey(rparsindices, k) ? replacement_parameters[rparsindices[k]] : v for (k, v) in pairs(react.pars)) # @Infiltrator.infiltrate reactpartuples[react] = NamedTuple{keys(react.pars)}(newparstuple) end pa_net = ParameterAggregator{new_eltype}( pa.parfullnames, replacement_parameters, pa.indices, pa.norm_values, pa.reactpars, reactpartuples, ) return pa_net end # for use by solver: test whether `reaction` has modified parameters has_modified_parameters(pa::ParameterAggregator, reaction::AbstractReaction) = haskey(pa.reactpartuples, reaction) # for use by solver: retrieve modified parameters for `reaction`, or return `nothing` if no modified parameters get_parameters(pa::ParameterAggregator, reaction::AbstractReaction) = get(pa.reactpartuples, reaction, nothing) function Base.copyto!(pa::ParameterAggregator, newvalues::Vector) lastidx = pa.indices[end][end] lastidx == length(newvalues) || error("ParameterAggregator length $lastidx != length(newvalues) $(length(newvalues))") for (p, indices) in IteratorUtils.zipstrict(pa.replacement_parameters, pa.indices) if p isa Parameter # p.v = only(view(newvalues, indices)) setvalue!(p, only(view(newvalues, indices)) * only(view(pa.norm_values, indices))) elseif p isa VecParameter p.v .= view(newvalues, indices) .* view(pa.norm_values, indices) else error("invalid Parameter type $p") end end return pa end function Base.copyto!(currentvalues::Vector, pa::ParameterAggregator) lastidx = pa.indices[end][end] lastidx == length(currentvalues) || error("ParameterAggregator length $lastidx != length(currentvalues) $(length(currentvalues))") for (p, indices) in IteratorUtils.zipstrict(pa.replacement_parameters, pa.indices) currentvalues[indices] .= p.v ./ view(pa.norm_values, indices) end return currentvalues end function get_currentvalues(pa::ParameterAggregator{T}) where T currentvalues = Vector{T}(undef, pa.indices[end][end]) return Base.copyto!(currentvalues, pa) end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
25732
""" AbstractReaction Abstract base Type for Reactions. # Implementation Derived types should include a field `base::`[`ReactionBase`](@ref), and usually a [`ParametersTuple`](@ref), eg Base.@kwdef mutable struct ReactionHello{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParDouble("my_par", 42.0, units="yr", description="an example of a Float64-valued scalar parameter called 'my_par'"), ) some_additional_field::Float64 # additional fields to eg cache data read from disk etc end Derived types should implement [`register_methods!`](@ref), and may optionally implement [`create_reaction`](@ref), [`set_model_geometry`](@ref), [`check_configuration`](@ref), [`register_dynamic_methods!`](@ref). Methods should be registered using [`add_method_setup!`](@ref), [`add_method_initialize!`](@ref), [`add_method_do!`](@ref). Any parameters not included in `pars` should be added explicitly with [`add_par`](@ref) (this is rarely needed). """ AbstractReaction """ ReactionBase Base Type for a biogeochemical Reaction. # Implementation Include as field `base` in types derived from [`AbstractReaction`](@ref) """ Base.@kwdef mutable struct ReactionBase "domain containing this Reaction" domain::Union{Nothing, Domain} = nothing "operator ID (to allow operator splitting)" operatorID::Vector{Int} = [1] "name of this instance (from .yaml config)" name::String "classname (as defined for .yaml config)" classname::String "external parameters and values supplied from Model or Domain" external_parameters::Dict{String, Any} = Dict{String, Any}() "Reaction parameters" parameters::Vector{AbstractParameter} = Vector{AbstractParameter}() methods_setup::Vector{AbstractReactionMethod} = Vector{AbstractReactionMethod}() methods_initialize::Vector{AbstractReactionMethod}=Vector{AbstractReactionMethod}() methods_do::Vector{AbstractReactionMethod} = Vector{AbstractReactionMethod}() # temporary storage for Variable configuration (read from .yaml config and applied after Variables linked) _conf_variable_links = nothing _conf_variable_attributes = nothing end struct NoReaction <: AbstractReaction base::ReactionBase NoReaction() = new(ReactionBase(name="", classname="NoReaction")) end # helps type stability: even though we are using @nospecialize(AbstractReaction) everywhere, # we still know the type of base base(react::AbstractReaction) = getfield(react, :base)::ReactionBase """ Base.getproperty(react::AbstractReaction, s::Symbol) Forward to `react.base::ReactionBase` to define additional properties. """ function Base.getproperty(react::AbstractReaction, s::Symbol) if s == :base return base(react) elseif s == :name return base(react).name elseif s == :classname return base(react).classname elseif s == :domain return base(react).domain elseif s == :operatorID return base(react).operatorID elseif s == :external_parameters return base(react).external_parameters elseif s == :methods_setup return base(react).methods_setup elseif s == :methods_initialize return base(react).methods_initialize elseif s == :methods_do return base(react).methods_do else return getfield(react, s) end end ########################################################## # Query methods for Parameters, ReactionMethods, Variables ########################################################## "Get all parameters" get_parameters(@nospecialize(reaction::AbstractReaction)) = reaction.base.parameters "Get parameter by name" function get_parameter(@nospecialize(reaction::AbstractReaction), parname::AbstractString; allow_not_found=false) matchpars = filter(p -> p.name==parname, reaction.base.parameters) length(matchpars) <= 1 || error("coding error: duplicate parameter name '$(name)' for Reaction: ", reaction) !isempty(matchpars) || allow_not_found || error("configuration error, Reaction $(fullname(reaction)) $(reaction)\n", "has no parameter name='$(parname)' (available parameters $([p.name for p in get_parameters(reaction)]))") return isempty(matchpars) ? nothing : matchpars[1] end set_parameter_value!(@nospecialize(reaction::AbstractReaction), parname::AbstractString, value) = setvalue!(get_parameter(reaction, parname, allow_not_found=false), value) get_parameter_value(@nospecialize(reaction::AbstractReaction), parname::AbstractString) = get_parameter(reaction, parname, allow_not_found=false).v "Get method by name" get_method_setup(@nospecialize(reaction::AbstractReaction), methodname::AbstractString; allow_not_found=false) = _get_method(reaction.base.methods_setup, "setup", reaction, methodname, allow_not_found) get_method_initialize(@nospecialize(reaction::AbstractReaction), methodname::AbstractString; allow_not_found=false) = _get_method(reaction.base.methods_initialize, "initialize", reaction, methodname, allow_not_found) get_method_do(@nospecialize(reaction::AbstractReaction), methodname::AbstractString; allow_not_found=false) = _get_method(reaction.base.methods_do, "do", reaction, methodname, allow_not_found) function _get_method(methodlist, methodtype, reaction, methodname, allow_not_found) matchmethods = filter(m -> m.name==methodname, methodlist) length(matchmethods) <= 1 || error("coding error: duplicate method $(methodtype) name '$(name)' for Reaction: ", reaction) !isempty(matchmethods) || allow_not_found || error("configuration error in $(fullname(reaction)) parameters: $(reaction) has no method $(methodtype) name='$(methodname)'") return isempty(matchmethods) ? nothing : matchmethods[1] end """ get_variables(reaction, localname) -> Vector{VariableReaction} get_variables(reaction; [filterfn=v->true]) -> Vector{VariableReaction} Get matching Variables from all ReactionMethods. """ function get_variables( @nospecialize(reaction::AbstractReaction), localname::AbstractString ) return get_variables(reaction, filterfn = v -> v.localname==localname) end function get_variables( @nospecialize(reaction::AbstractReaction); filterfn = v -> true ) matchvars = VariableReaction[] for methodlist in (reaction.methods_setup, reaction.methods_initialize, reaction.methods_do) for m in methodlist append!(matchvars, get_variables(m; filterfn=filterfn)) end end return matchvars end """ get_variable(reaction, methodname, localname) -> VariableReaction or nothing Get a single VariableReaction or nothing if match not found. """ function get_variable( @nospecialize(reaction::AbstractReaction), methodname::AbstractString, localname::AbstractString; allow_not_found=false ) matchvars = get_variables(reaction, filterfn = v -> (v.method.name == methodname && v.localname==localname)) length(matchvars) <= 1 || error("duplicate variable localname", localname) !isempty(matchvars) || allow_not_found || error("method ", fullname(method), " no variable localname=", localname) return isempty(matchvars) ? nothing : matchvars[1] end ################################################## # Initialization callbacks ################################################# """ set_model_geometry(reaction, model) Optional: define [`Domain`](@ref) `grid`, `data_dims`. One Reaction per Domain may create a grid (an [`AbstractMesh`](@ref) subtype) and set the `domain.grid` field. Multiple Reactions per domain may call [`set_data_dimension!`](@ref) to define (different) named data dimensions (eg wavelength grids). """ function set_model_geometry(reaction::AbstractReaction, model::Model) end """ check_configuration(reaction, model) -> Bool Optional: check configuration is valid, log errors and return `false` if not """ function check_configuration(reaction::AbstractReaction, model::Model) return true end """ register_methods!(reaction) register_methods!(reaction, model) Add [`ReactionMethod`](@ref)s, using [`add_method_setup!`](@ref), [`add_method_initialize!`](@ref) [`add_method_do!`](@ref). See also [`register_dynamic_methods!`](@ref). """ register_methods!(reaction::AbstractReaction, model::Model) = register_methods!(reaction) register_methods!(reaction::AbstractReaction) = error("$(typename(reaction)) register_methods! not implemented") """ register_dynamic_methods!(reaction) register_dynamic_methods!(reaction, model) Optional: called after first variable link pass, to add [`ReactionMethod`](@ref)s that depend on Variables generated by other Reactions (see [`register_methods!`](@ref)). """ register_dynamic_methods!(reaction::AbstractReaction, model::Model) = register_dynamic_methods!(reaction) function register_dynamic_methods!(reaction::AbstractReaction) end ######################################################################################## # Helper functions to allow a Reaction implementation to populate Parameter and ReactionMethod lists ######################################################################################### """ 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::ParametersTuple`` will be added automatically, only needed if there are additional Parameters that are not members of `pars`. """ function add_par(@nospecialize(reaction::AbstractReaction), par::AbstractParameter) if isnothing(get_parameter(reaction, par.name, allow_not_found=true)) push!(reaction.base.parameters, par) else error("attempt to add duplicate parameter name=''", par.name, "'' to reaction", reaction) end return nothing end function add_par(@nospecialize(reaction::AbstractReaction), objectwithpars) for f in fieldnames(typeof(objectwithpars)) if getfield(objectwithpars, f) isa AbstractParameter add_par(reaction, getfield(objectwithpars, f)) end end end """ 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`](@ref). """ function add_method_setup!(@nospecialize(reaction::AbstractReaction), method::AbstractReactionMethod) push!(reaction.base.methods_setup, method) return nothing end add_method_setup!(@nospecialize(reaction::AbstractReaction), methodfn::Function, vars::Tuple{Vararg{AbstractVarList}}; kwargs...) = _add_method!(reaction, methodfn, vars, add_method_setup!; kwargs...) """ 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`](@ref). """ function add_method_initialize!(@nospecialize(reaction::AbstractReaction), method::AbstractReactionMethod) push!(reaction.base.methods_initialize, method) return nothing end add_method_initialize!(@nospecialize(reaction::AbstractReaction), methodfn::Function, vars::Tuple{Vararg{AbstractVarList}}; kwargs...) = _add_method!(reaction, methodfn, vars, add_method_initialize!; kwargs...) """ 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`](@ref). """ function add_method_do!(@nospecialize(reaction::AbstractReaction), @nospecialize(method::AbstractReactionMethod)) push!(reaction.base.methods_do, method) return nothing end add_method_do!(@nospecialize(reaction::AbstractReaction), @nospecialize(methodfn::Function), @nospecialize(vars::Tuple{Vararg{AbstractVarList}}); kwargs...) = _add_method!(reaction, methodfn, vars, add_method_do!; kwargs...) function _add_method!( @nospecialize(reaction::AbstractReaction), @nospecialize(methodfn::Function), @nospecialize(vars::Tuple{Vararg{AbstractVarList}}), add_method_fn; name=string(methodfn), p=nothing, preparefn=(m, vardata) -> vardata, operatorID=reaction.operatorID, domain=reaction.domain ) method = ReactionMethod( methodfn, reaction, name, vars, p, copy(operatorID), domain, preparefn=preparefn ) add_method_fn(reaction, method) return method end ################################### # creation from _cfg.yaml ################################## "Create new ReactionXXXX of specified classname from config file, set parameters, read variable mapping and initial values (to be set later by _configure_variables!)" function create_reaction_from_config( classname::AbstractString, rdict::Dict{String, Type}, domain::Domain, name, conf_reaction, external_parameters::Dict{String, Any} ) io = IOBuffer() local newreaction, conf_parameters # make available outside try block try println(io, "create_reaction_from_config: $(domain.name).$name classname $classname") newreaction = create_reaction(rdict, classname, name, external_parameters) newreaction.base.domain = domain for k in keys(conf_reaction) if !(k in ("operatorID", "parameters", "variable_links", "variable_attributes")) error("reaction $(fullname(newreaction)) configuration error invalid key '$k'") end end operatorID = get(conf_reaction, "operatorID", nothing) if !isnothing(operatorID) println(io, " operatorID=$(operatorID)") newreaction.base.operatorID = operatorID end # set parameters allpars = get_parameters(newreaction) conf_parameters_raw = get(conf_reaction, "parameters", Dict{Any,Any}()) # empty 'parameters:' will return nothing conf_parameters = isnothing(conf_parameters_raw) ? Dict{Any, Any}() : copy(conf_parameters_raw) for par in allpars rawvalue = par.v par_modified = false if par.external && haskey(newreaction.base.external_parameters, par.name) rawvalue = newreaction.base.external_parameters[par.name] par_modified = true end if haskey(conf_parameters, par.name) rawvalue = pop!(conf_parameters, par.name) par_modified = true end par_modstr = ("[Default] ", "[config.yaml] ")[1+par_modified] println(io, " set parameters: $par_modstr $(rpad(par.name,20))=$(rawvalue)") value = substitutevalue(parentmodule(typeof(newreaction)), externalvalue(io, rawvalue, newreaction.base.external_parameters)) if isa(rawvalue, AbstractString) && value != rawvalue par_modified = true println(io, " after substitution $(par.name)=$(value)") end if par_modified setvalue!(par, value) end end finally @info String(take!(io)) end if !isempty(conf_parameters) io = IOBuffer() println(io, "reaction $(fullname(newreaction)) has no Parameter(s):") for (k, v) in conf_parameters println(io, " $k: $v") end error(String(take!(io))) end # Read Variable configuration # These are applied later by _configure_variables! after Variables are created newreaction.base._conf_variable_links = get(conf_reaction, "variable_links", nothing) newreaction.base._conf_variable_attributes = get(conf_reaction, "variable_attributes", nothing) return newreaction end function _register_methods!(@nospecialize(reaction::AbstractReaction), model::Model) empty!(reaction.methods_setup) empty!(reaction.methods_initialize) empty!(reaction.methods_do) register_methods!(reaction, model) return nothing end "apply Variable configuration. NB: runs twice: - after register_methods! (with allow_missing true) - after register_dynamic_methods! (with allow_missing false)" function _configure_variables(@nospecialize(reaction::AbstractReaction); allow_missing::Bool, dolog::Bool) function sortstarfirst(x, y) if occursin("*", x) && !occursin("*", y) lt = true elseif !occursin("*", x) && occursin("*", y) lt = false else lt = x < y end return lt end io = devnull if !isnothing(reaction.base._conf_variable_links) # missing or empty 'variable_links:' will return nothing # sort Dict so wild cards (ending in *) are processed first, so they can be selectively overridden cvl = sort(reaction.base._conf_variable_links, lt=sortstarfirst) if dolog io = IOBuffer() println(io, "_configure_variables: $(nameof(typeof(reaction))) $(fullname(reaction)) variable_links:") end for (name, fullmapnameraw) in cvl try fullmapname = externalvalue(io, fullmapnameraw, reaction.base.external_parameters) linkreq_domain, linkreq_subdomain, mapname = split_link_name(fullmapname) match_vars = _gen_var_names(get_variables(reaction), name, mapname) uniquelocalnames = Set{String}() if isempty(match_vars) allow_missing || error(" set variable_links: $name -> $fullmapname no variables match $name\n", " available Variable local names: ", unique([v.localname for v in get_variables(reaction)])) else for (var, newname) = match_vars linkreq_fullname = combine_link_name(linkreq_domain, linkreq_subdomain, newname) # Variables may appear in multiple ReactionMethods, so just print a log message for the first one dolog && !(var.localname in uniquelocalnames) && println(io, " set variable_links: $(rpad(var.localname,20)) -> $linkreq_fullname") push!(uniquelocalnames, var.localname) var.linkreq_name = newname var.linkreq_domain = linkreq_domain var.linkreq_subdomain = linkreq_subdomain end end catch io === devnull || @info String(take!(io)) @warn "_configure_variables: error setting Variable link for $(nameof(typeof(reaction))) $(fullname(reaction)) $name" rethrow() end end end # set variable attributes if !isnothing(reaction.base._conf_variable_attributes) if dolog io = (io === devnull) ? IOBuffer() : io println(io, "_configure_variables: $(nameof(typeof(reaction))) $(fullname(reaction)) variable_attributes:") end cva = reaction.base._conf_variable_attributes for (nameattrib, rawvalue) in cva try split_na = split(nameattrib, (':', '%')) length(split_na) == 2 || error(" invalid variable:attribute or variable%attribute $nameattrib") name, attrib = split_na match_vars = _gen_var_names(get_variables(reaction), name, "not used") # no wild cards (trailing *) allowed uniquelocalnames = Set{String}() if isempty(match_vars) allow_missing || error(" $nameattrib = $rawvalue no variables match $name") else for (var, dummy) = match_vars # if isnothing(var.linkvar) # @warn " unable to set $(Symbol(attrib)) attribute, VariableReaction $(fullname(var)) not linked" # else # set_attribute!(var.linkvar, Symbol(attrib), value) # end # Variables may appear in multiple ReactionMethods, so just print a log message for the first one iofirstvar = (dolog && !(var.localname in uniquelocalnames)) ? io : devnull push!(uniquelocalnames, var.localname) println(iofirstvar, " set attribute: $(rpad(var.localname,20)) :$(rpad(attrib,20)) = $(rpad(rawvalue, 20)) ") value = externalvalue(iofirstvar, rawvalue, reaction.base.external_parameters) set_attribute!(var, Symbol(attrib), value) end end catch io === devnull || @info String(take!(io)) @warn "_configure_variables: error setting Variable attribute for $(nameof(typeof(reaction))) $(fullname(reaction)) $nameattrib" rethrow() end end end io === devnull || @info String(take!(io)) return nothing end """ _gen_var_names(variables, matchroot::AbstractString, newroot::AbstractString) -> Vector{Pair{VariableReaction, String}} Return a list of (variable => newname) for `variables` where localname matches `matchroot`, generating `newname` from `newroot`. If `matchroot` and `newroot` contain a *, treat this as a wildcard. If `matchroot` contains a * and `newroot` doesn't (legacy form), append a * to `newroot` first. """ function _gen_var_names(variables, matchroot::AbstractString, newroot::AbstractString) # variable => newname match_vars = Vector{Pair{VariableReaction, String}}() count("*", matchroot) <= 1 || error("matchroot $matchroot contains more than one *") if contains(newroot, "*") newrootstar = newroot else # legacy form without a * on the RHS - interpret as if had a trailing * newrootstar = newroot*"*" end for var in variables if contains(matchroot, "*") && (length(var.localname) >= length(matchroot) - 1) starpos = findfirst('*', matchroot) beforestar = matchroot[1:starpos-1] afterstar = matchroot[starpos+1:end] if startswith(var.localname, beforestar) && endswith(var.localname, afterstar) starmatched = var.localname[length(beforestar)+1:end-length(afterstar)] # string that * matched push!(match_vars, var => replace(newrootstar, "*"=>starmatched)) end else if var.localname == matchroot push!(match_vars, var => newroot) end end end return match_vars end ########################################### # Pretty printing ############################################ function Base.show(io::IO, react::AbstractReaction) print( io, typename(react), "(name='", react.name, "', classname='", react.classname, "', domain='", domainname(react) , ", operatorID=", react.operatorID, ")" ) end function Base.show(io::IO, ::MIME"text/plain", react::AbstractReaction) println(io, typename(react)) println(io, " name='", react.name, "'") println(io, " classname='", react.classname, "'") println(io, " domain='", domainname(react), "'") println(io, " operatorID=", react.operatorID) println(io, " parameters=", get_parameters(react)) println(io, " methods_setup=", react.methods_setup) println(io, " methods_initialize=", react.methods_initialize) println(io, " methods_do=", react.methods_do) end """ show_parameters(react::AbstractReaction) -> DataFrame show_parameters(classname::AbstractString) -> DataFrame list all parameters for a Reaction `react` instance or `classname` """ function show_parameters(react::AbstractReaction) pars = get_parameters(react) dfreact = DataFrames.DataFrame() dfreact.name = [p.name for p in pars] dfreact.v = [p.v for p in pars] dfreact.type = [typeof(p) for p in pars] dfreact.units = [p.units for p in pars] dfreact.description = [p.description for p in pars] DataFrames.sort!(dfreact, [:name]) return dfreact end show_parameters(classname::AbstractString) = show_parameters(_create_reaction(classname, "test", Dict{String,Any}())) "fully-qualified name" fullname(react::AbstractReaction) = domainname(react)*"."*react.name "safe Reaction Domain name" domainname(react::AbstractReaction) = isnothing(react.domain) ? "<no domain>" : react.domain.name "type name, excluding (verbose) template arguments" typename(react::AbstractReaction) = join(Base.fullname(parentmodule(typeof(react))), ".")*"."*String(nameof(typeof(react)))
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
4861
import InteractiveUtils """ 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). """ function find_all_reactions() rtypes = InteractiveUtils.subtypes(AbstractReaction) rdict = Dict{String, Type}() duplicate_keys = [] for ReactionType in rtypes rname = _classname(ReactionType) if haskey(rdict, rname) push!(duplicate_keys, (rname, ReactionType)) end rdict[rname] = ReactionType end for (rname, ReactionType) in duplicate_keys @warn "Duplicate reaction name $rname for Type $ReactionType (removing from Dict)" if haskey(rdict, rname) @warn "Duplicate reaction name $rname for Type $(rdict[rname]) (removing from Dict)" delete!(rdict, rname) end end return rdict end """ _classname(ReactionType::Type{<:AbstractReaction}) -> String Get Reaction classname from `ReactionType` (this is the Julia Type after stripping module prefixes and converting to String) """ _classname(ReactionType::Type{<:AbstractReaction}) = String(last(split(string(ReactionType), "."))) """ find_reaction(class::AbstractString) -> ReactionType Look up "class" in list of Reactions from [`find_all_reactions`](@ref), and return fully-qualified Reaction Type (including module prefixes). """ function find_reaction(class::AbstractString) rdict = find_all_reactions() if haskey(rdict, class) return rdict[class] else error("class \"$class\" not found") end end """ 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 """ function create_reaction(ReactionType::Type{<:AbstractReaction}, base::ReactionBase) return ReactionType(base=base) end """ create_reaction(rdict::Dict{String, Type}, classname::String, name::String, external_parameters::Dict{String, Any}) -> reaction::AbstractReaction create_reaction(ReactionType::Type{<:AbstractReaction}, name::String, external_parameters::Dict{String, Any}) -> reaction::AbstractReaction Create and configure a reaction. Sets `ReactionBase` with name, classname, external_parameters, and list of `Parameters` from `pars` field (if present) """ function create_reaction( ReactionType::Type{<:AbstractReaction}, name::String, external_parameters::Dict{String, Any}; classname=_classname(ReactionType), ) base=ReactionBase(;name, classname, external_parameters) rj = create_reaction(ReactionType, base) # Add parameters from pars field if hasproperty(rj, :pars) add_par(rj, rj.pars) end return rj end function create_reaction( rdict::Dict{String, Type}, classname::String, name::String, external_parameters::Dict{String, Any} ) if haskey(rdict, classname) return create_reaction(rdict[classname], name, external_parameters; classname) else error("create_reaction: name $name classname $classname not found") return nothing end end function add_reaction_factory(ReactionType::Type{<:AbstractReaction}) Base.depwarn("call to deprecated add_reaction_factory($ReactionType), this does nothing and can be removed", :add_reaction_factory, force=true) end """ show_all_reactions(classfilter="", typenamefilter="") List all registered Reactions with `classname` containing (`occursin`) `classfilter` and `typenamefilter` A Reaction is loaded when the module that defines it is imported. Examples: - `PB.show_all_reactions(r"reservoir"i)` case-insensitive match for classname containing "reservoir". - `PB.show_all_reactions("", "Reservoir")` all Reactions defined in a module name containing "Reservoir" """ function show_all_reactions(classnamefilter="", typenamefilter="") for (classname, ReactionType) in sort!(OrderedCollections.OrderedDict(find_all_reactions())) if occursin(classnamefilter, classname) println(classname) rtstring = Printf.@sprintf("%s", ReactionType) if occursin(typenamefilter, rtstring ) println(" ", ReactionType) # doc = Base.Docs.doc(rt) # a Markdown object? # display(doc) end end end end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
9238
""" ReactionMethod( methodfn::Function, reaction::AbstractReaction, name::String, varlists::Tuple{Vararg{AbstractVarList}}, p, 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 $(FIELDS) # 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 [`VariableReaction`](@ref)s 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. """ struct ReactionMethod{M, R, P, Nargs} <: AbstractReactionMethod "callback from Model framework" methodfn::M # NB: store function object, even though we have M (see https://discourse.julialang.org/t/is-there-a-way-to-get-f-from-typeof-f/18818/12) "the Reaction that created this ReactionMethod" reaction::R "a descriptive name, eg generated from the name of methodfn" name::String "Tuple of VarLists, each representing a list of [`VariableReaction`](@ref)s. 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" varlists::Tuple{Vararg{AbstractVarList}} "optional context field (of arbitrary type) to store data needed by methodfn." p::P operatorID::Vector{Int64} domain::Domain "preparefn(m::ReactionMethod, vardata::Tuple) -> modified_vardata::Tuple optionally modify `vardata` to eg add buffers. NB: not concretely typed as not performance-critical" preparefn::Function function ReactionMethod( methodfn::M, reaction::R, name, varlists::Tuple{Vararg{AbstractVarList}}, p::P, operatorID::Vector{Int64}, domain; preparefn = (m, vardata) -> vardata, ) where {M <: Function, R <: AbstractReaction, P} # Find number of arguments that methodfn takes # (in order to support two forms of 'methodfn', with and without Parameters) nargs = fieldcount(methods(methodfn).ms[1].sig) - 1 newmethod = new{M, R, P, nargs}( methodfn, reaction, name, varlists, p, operatorID, domain, preparefn, ) for v in get_variables(newmethod) v.method = newmethod set_attribute!(v, :operatorID, newmethod.operatorID, allow_create=true) end return newmethod end end get_nargs(method::ReactionMethod{M, R, P, Nargs}) where {M, R, P, Nargs} = Nargs get_nargs(methodref::Ref{ReactionMethod{M, R, P, Nargs}}) where {M, R, P, Nargs} = Nargs # deprecated methodfn form without pars @inline call_method(method::ReactionMethod{M, R, P, 4}, vardata, cr, modelctxt) where {M, R, P} = method.methodfn(method, vardata, cr, modelctxt) # updated methodfn form with pars @inline call_method(method::ReactionMethod{M, R, P, 5}, vardata, cr, modelctxt) where {M, R, P} = method.methodfn(method, method.reaction.pars, vardata, cr, modelctxt) @noinline call_method(methodref::Ref{<: ReactionMethod}, vardataref::Ref, cr, modelctxt) = call_method(methodref[], vardataref[], cr, modelctxt) # with modified pars for sensitivity studies: deprecated methodfn form without pars @inline call_method(method::ReactionMethod{M, R, P, 4}, pars, vardata, cr, modelctxt) where {M, R, P} = method.methodfn(method, vardata, cr, modelctxt) # with modified pars for sensitivity studies: updated methodfn form with pars @inline call_method(method::ReactionMethod{M, R, P, 5}, pars, vardata, cr, modelctxt) where {M, R, P} = method.methodfn(method, pars, vardata, cr, modelctxt) @noinline call_method(methodref::Ref{<: ReactionMethod}, pars, vardataref::Ref, cr, modelctxt) = call_method(methodref[], pars, vardataref[], cr, modelctxt) @inline has_modified_parameters(pa::ParameterAggregator, methodref::Ref{<: ReactionMethod}) = has_modified_parameters(pa, methodref[].reaction) @inline get_parameters(pa::ParameterAggregator, methodref::Ref{<: ReactionMethod}) = get_parameters(pa, methodref[].reaction) # for benchmarking etc: apply codefn to the ReactionMethod methodfn (without this, will just apply to the call_method wrapper) # codefn=code_warntype, code_llvm, code_native call_method_codefn(io::IO, codefn, method::ReactionMethod{M, R, P, 4}, vardata, cr, modelctxt; kwargs...) where {M, R, P} = codefn(io, method.methodfn, (typeof(method), typeof(vardata), typeof(cr), typeof(modelctxt)); kwargs...) call_method_codefn(io::IO, codefn, method::ReactionMethod{M, R, P, 5}, vardata, cr, modelctxt; kwargs...) where {M, R, P} = codefn(io, method.methodfn, (typeof(method), typeof(method.reaction.pars), typeof(vardata), typeof(cr), typeof(modelctxt)); kwargs...) """ get_variables_tuple(method::AbstractReactionMethod) -> (Vector{VariableReaction}, ...) Get all [`VariableReaction`](@ref)s from `method` as a Tuple of `Vector{VariableReaction}` """ get_variables_tuple(@nospecialize(method::ReactionMethod); flatten=true) = Tuple(get_variables(vl; flatten) for vl in method.varlists) """ 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` """ function get_variables( @nospecialize(method::ReactionMethod); filterfn = v -> true ) vars = VariableReaction[] for vl in method.varlists append!(vars, filter(filterfn, get_variables(vl))) end return vars end """ get_variable( method::AbstractReactionMethod, localname::AbstractString; allow_not_found=false ) -> v Get a single VariableReaction `v` by `localname`. If `localname` not present, returns `nothing` if `allow_not_found==true` otherwise errors. """ function get_variable( @nospecialize(method::ReactionMethod), localname::AbstractString; allow_not_found=false ) matchvars = get_variables(method; filterfn = v -> v.localname==localname) length(matchvars) <= 1 || error("duplicate variable localname", localname) !isempty(matchvars) || allow_not_found || error("method ", fullname(method), " no variable localname=", localname) return isempty(matchvars) ? nothing : matchvars[1] end fullname(@nospecialize(method::ReactionMethod)) = fullname(method.reaction)*"."*method.name is_method_setup(@nospecialize(method::ReactionMethod)) = (method in base(method.reaction).methods_setup) is_method_initialize(@nospecialize(method::ReactionMethod)) = (method in base(method.reaction).methods_initialize) is_method_do(@nospecialize(method::ReactionMethod)) = (method in base(method.reaction).methods_do) """ get_rate_stoichiometry(m::PB.ReactionMethod) -> Vector[(ratevarname, process, Dict(speciesname=>stoich, ...)), ...] DEPRECATED: Optionally provide rate Variable name(s), a process name ("photolysis", "reaction", ...) and stoichiometry of reactants and products, for postprocessing of results. Use attributes on rate variable instead: - `rate_processname::String`: a process name (eg "photolysis", "reaction", ...) - `rate_species::Vector{String}` names of reactant and product species - `rate_stoichiometry::Vector{Float64}` stoichiometry of reactant and product species """ get_rate_stoichiometry(@nospecialize(m::ReactionMethod)) = [] ########################################### # Pretty printing ############################################ "compact form" function Base.show(io::IO, @nospecialize(method::ReactionMethod)) print( io, "ReactionMethod(fullname='", fullname(method), "', methodfn=", string(method.methodfn), ", domain='", method.domain.name , "', operatorID=", method.operatorID, ")", ) end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
5805
""" MethodSort Sorted ReactionMethods. Each group of methods in `groups` has no internal dependencies, but depends on methods in previous groups in the Vector. # Fields - `methods::Vector{AbstractReactionMethod}`: (unsorted) ReactionMethods - `groups::Vector{BitSet}`: indices in `methods` of sequentially dependent groups of ReactionMethods (ReactionMethods in each group depend on the previous group, no dependencies within group) - `g::Graphs.SimpleDiGraph `: dependency graph (Vertices are numbered using indices in `methods`) - `depvars::Dict{Tuple{Int64, Int64}, Vector{PALEOboxes.VariableDomain}}`: Dict((modifier_idx, dependent_idx)=>var): Variables modified by method modifier_idx and required by method dependent_idx """ struct MethodSort methods::Vector{AbstractReactionMethod} groups::Vector{BitSet} g::Graphs.SimpleDiGraph depvars::Dict{Tuple{Int64, Int64}, Vector{PALEOboxes.VariableDomain}} end """ get_methods(ms::MethodSort; [method_barrier=nothing]) -> Vector{AbstractReactionMethod} Flatten MethodSort to a Vector of ReactionMethods, optionally inserting `method_barrier` between groups for a multithreaded timestepper. NB: adds a `method_barrier` before first group, no `method_barrier` after last group. """ function get_methods(ms::MethodSort; method_barrier=nothing) methods = AbstractReactionMethod[] for grp in ms.groups isnothing(method_barrier) || push!(methods, method_barrier) append!(methods, (ms.methods[midx] for midx in grp)) end return methods end function Base.show(io::IO, m::MethodSort) println(io, "MethodSort") for grp in m.groups println(io, " group=", grp) for midx in grp println(io, " ", fullname(m.methods[midx])) end end end """ dfs_methods(methods::Vector, all_domvars::Vector; verbose=false) -> MethodSort Depth-first topological sort based on dependencies from Variables. NB: No grouping of methods (returns each method in a group of 1). """ function dfs_methods(methods::Vector, all_domvars::Vector; verbose=false) g, depvars = _method_dependencies(methods, all_domvars) # topological sort groups = BitSet.(Graphs.topological_sort_by_dfs(g)) MethodSort(methods, groups, g, depvars) end """ group_methods(methods::Vector, all_domvars::Vector; verbose=false) -> MethodSort Group methods based on dependencies from Variables using a topological sort (using Kahn's algorithm, similar to a breadth-first search). Methods in each group have no dependencies (ie can run in any order). Each group must run after the previous groups in the list. """ function group_methods(methods::Vector, all_domvars::Vector; verbose=false) g, depvars = _method_dependencies(methods, all_domvars) num_vertices = Graphs.nv(g) # number of incoming edges for each Vertex inn = [length(Graphs.inneighbors(g,v)) for v in Graphs.vertices(g)] groups = BitSet[] num_grouped = 0 while true # find all vertices with no remaining incoming edges grp = BitSet(v for v in Graphs.vertices(g) if iszero(inn[v])) if isempty(grp) break else push!(groups, grp) num_grouped += length(grp) verbose && println(grp) for gv in grp verbose && println(" ", fullname(methods[gv])) inn[gv] -= 1 # now -1 (ie remove from further consideration) # remove an edge from all our dependents for ov in Graphs.outneighbors(g, gv) inn[ov] -= 1 end end end end num_grouped == num_vertices || error("The input graph contains at least one loop.") return MethodSort(methods, groups, g, depvars) end """ _method_dependencies(methods::Vector, all_domvars::Vector) -> (g::Graphs.SimpleDiGraph, depvars::Dict((modifier_idx, dependent_idx)=>Vector{VariableDomain}) Create ReactionMethod dependency graph based on dependencies from `all_domvars`. Vertices of directed graph `g` are numbered by index in `methods`. 'Out' edges from a method point to (are `in` edges to) methods that are dependent on Variables modified by it. Domain Variables generating dependencies are returned in `depvars::Dict((modifier_idx, dependent_idx)=>var)` where `modifier_idx`, `dependent_idx` are indices in `methods`. """ function _method_dependencies(methods::Vector, all_domvars::Vector) # invert to get map from ReactionMethod -> ReactionMethod index method_to_idx = Dict{AbstractReactionMethod, Int}( method=>idx for (idx, method) in enumerate(methods) ) g = Graphs.SimpleDiGraph(length(method_to_idx)) depvars = Dict{Tuple{Int64, Int64}, Vector{PALEOboxes.VariableDomain}}() # add edges for each variable Dependency for var in all_domvars modifying_methods = get_modifying_methods(var) # all methods (setup, initialize, do) dependent_methods = get_dependent_methods(var) # all methods (setup, initialize, do) for mod_m in modifying_methods for dep_m in dependent_methods # filter out methods to those we are interested in if haskey(method_to_idx, mod_m) && haskey(method_to_idx, dep_m) mod_idx = method_to_idx[mod_m] dep_idx = method_to_idx[dep_m] # Add edge to graph - duplicate edges will not be added and will return false Graphs.add_edge!(g, mod_idx, dep_idx) # keep track of all Variables generating dependencies push!(get!(depvars, (mod_idx, dep_idx), VariableDomain[]), var) end end end end return (g, depvars) end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
5245
# Get scalar value from variable x (discarding any AD derivatives) value_ad(x) = x # Model code should implement this for any AD types used, eg # value_ad(x::SparsityTracing.ADval) = SparsityTracing.value(x) # value_ad(x::ForwardDiff.Dual) = ForwardDiff.value(x) # get scalar or ad from variable x, as specified by first argument value_ad(::Type{T}, x::T) where {T} = x # pass through AD value_ad(::Type{T}, x::Float64) where {T} = x # pass through Float64 value_ad(::Type{Float64}, x) = value_ad(x) # strip AD value_ad(::Type{Float64}, x::Float64) = x # avoid method ambiguity # TODO there doesn't seem to be an easy way of parameterising ModelData by an Array type ? const PaleoArrayType = Array ################################ # Parameters ############################### abstract type AbstractParameter end ################################# # Reactions ################################### """ AbstractReactionMethod Base Type for Reaction Methods. """ abstract type AbstractReactionMethod end abstract type AbstractReaction end ############################################## # Variables ############################################### """ VariableBase A `Model` biogeochemical `Variable`. `Reaction`s access `Variable`s using derived Types [`VariableReaction`](@ref) which are links to [`VariableDomain`](@ref)s. """ abstract type VariableBase end """ show_variables(obj, ...) -> Table Show all Variables attached to PALEO object `obj` """ function show_variables end """ get_variable(obj, varname, ...) -> variable Get `variable <: VariableBase` by name from PALEO object """ function get_variable end """ has_variable(obj, varname, ...) -> Bool True if PALEO object containts `varname` """ function has_variable end """ @enum VariableType Enumeration of `VariableBase` subtypes. Allowed values: - `VariableReaction`: `VT_ReactProperty`, `VT_ReactDependency`, `VT_ReactContributor`, `VT_ReactTarget` - `VariableDomain` : `VT_DomPropDep`, `VT_DomContribTarget` """ @enum VariableType::Cint begin VT_Undefined = 0 VT_ReactProperty VT_ReactDependency VT_ReactContributor VT_ReactTarget VT_DomPropDep VT_DomContribTarget end abstract type VariableDomain <: VariableBase end abstract type AbstractModel end """ AbstractDomain A model region containing Fields and Reactions that act on them. """ abstract type AbstractDomain end abstract type AbstractSubdomain end abstract type AbstractMesh end """ function get_mesh(obj, ...) Return an [`AbstractMesh`](@ref) for PALEO object `obj` """ function get_mesh end abstract type AbstractCellRange end abstract type AbstractSpace end abstract type AbstractData end "parse eg \"ScalarData\" or \"PALEOboxes.ScalarData\" as ScalarData" function Base.parse(::Type{AbstractData}, str::AbstractString) dtype = tryparse(AbstractData, str) !isnothing(dtype) || throw(ArgumentError("$str is not a subtype of AbstractData")) return dtype end function Base.tryparse(::Type{AbstractData}, str::AbstractString) dtype = getproperty(@__MODULE__, Symbol(replace(str, "PALEOboxes."=>""))) return (dtype <: AbstractData) ? dtype : nothing end """ AbstractField Defines a Field in a Domain """ abstract type AbstractField end "`model` data arrays etc" abstract type AbstractModelData end "struct to hold Domain Field data" abstract type AbstractDomainData end """ function get_table(obj, ...) Return a Tables.jl data table view for PALEO object `obj` """ function get_table end ############################################# # ReactionMethodDispatchList ############################################# """ ReactionMethodDispatchList Defines a list of [`ReactionMethod`](@ref) with corresponding [`CellRange`](@ref) and views on Variable data (sub)arrays. """ struct ReactionMethodDispatchList{M <:Tuple, V <:Tuple, C <: Tuple} methods::M vardatas::V cellranges::C end ReactionMethodDispatchList(methods::Vector, vardatas::Vector, cellranges::Vector) = ReactionMethodDispatchList(Tuple(methods), Tuple(vardatas), Tuple(cellranges)) struct ReactionMethodDispatchListNoGen methods::Vector vardatas::Vector cellranges::Vector end # See https://discourse.julialang.org/t/pretty-print-of-type/19555 # Customize typeof function, as full type name is too verbose (as Tuples are of length ~ number of ReactionMethods to call) Base.show(io::IO, ::Type{PALEOboxes.ReactionMethodDispatchList{M, V, C}}) where {M, V, C} = print(io, "PALEOboxes.ReactionMethodDispatchList{M::Tuple, V::Tuple, C::Tuple each of length=$(fieldcount(M))}") function Base.show(io::IO, dispatchlist::ReactionMethodDispatchList) print(io, typeof(dispatchlist)) end function Base.show(io::IO, ::MIME"text/plain", dl::ReactionMethodDispatchList) println(io, typeof(dl)) for i in eachindex(dl.methodfns) println(io, " ", dl.methods[i], ", ", dl.cellranges[i]) end end """ infoerror(io::IOBuffer, message::AbstractString) Output accumulated log messages in io, then raise `ErrorException` with message """ function infoerror(io::IOBuffer, message::AbstractString) @info String(take!(io)) error(message) end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
13244
##################################################### # Attribute accessors ##################################################### """ set_attribute!(var::VariableBase, name::Symbol, value, allow_create=false) -> var Set Variable attribute. """ function set_attribute!(var::VariableBase, name::Symbol, value; allow_create=false) _set_attribute!(var.attributes, name, value, allow_create) return var end """ has_attribute(var::VariableBase, name::Symbol) Test Variable attribute present. """ has_attribute(var::VariableBase, name::Symbol) = haskey(var.attributes, name) """ get_attribute(var::VariableBase, name::Symbol, missing_value=missing) -> value Get Variable attribute. """ function get_attribute(var::VariableBase, name::Symbol, missing_value=missing) return get(var.attributes, name, missing_value) end """ num_components(var::VariableBase) -> Int Number of components in `var`. """ num_components(var::VariableBase) = num_components(get_attribute(var, :field_data)) ################################### # enum-valued VariableAttributes #################################### """ @enum VariableFunction Allowed values of `:vfunction` Variable [`Attribute`](@ref), defining the Variable function to the host ODE or DAE solver. Explicit ODE problems with dS/dt = F(S) consist of pairs of S::VF_StateExplicit, F::VF_Deriv 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::VF_Total and F::VF_Deriv Variables, and also the same number of S::VF_StateTotal (in no particular order). Algebraic constraints C(S) = 0 include variables C::VF_Constraint and the same number of S::VF_State, with no corresponding VF_Deriv. Not all solvers support all combinations. """ @enum VariableFunction::Cint begin VF_Undefined = 0 VF_StateExplicit = 1 VF_Total = 2 VF_Constraint = 3 VF_State = 4 VF_Deriv = 5 VF_StateTotal = 6 end "parse eg \"VF_Deriv\" as Enum VF_Deriv" function Base.parse(::Type{VariableFunction}, str::AbstractString) return getproperty(@__MODULE__, Symbol(str))::VariableFunction end """ @enum VariablePhase Allowed values of `:vphase` Variable [`Attribute`](@ref), defining the component phase this Variable belongs to for multiphase cells. """ @enum VariablePhase::Cint begin VP_Undefined = 0 VP_Solute = 1 VP_Solid = 2 end "parse eg \"VP_Solute\" as Enum VP_Solute" function Base.parse(::Type{VariablePhase}, str::AbstractString) return getproperty(@__MODULE__, Symbol(str))::VariablePhase end ################################################### # Standard Attributes ##################################################### """ 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!`](@ref). If `ParseFromString` is `true`, then [`set_attribute!`](@ref) 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) """ struct Attribute{T, ParseFromString} name::Symbol default_value::T required::Bool units::String description::String end attributeType(::Attribute{T}) where{T} = T """ 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> - units (where possible should follow the Unidata udunits package <https://docs.unidata.ucar.edu/udunits/current/>) - long_name CF conventions: <https://cfconventions.org/cf-conventions/cf-conventions.html#_description_of_the_data> - standard_name <http://cfconventions.org/Data/cf-standard-names/current/src/cf-standard-name-table.xml> """ const StandardAttributes = [ # name default_value required units description Attribute{Type, AbstractData}( :field_data, UndefinedData, true, "", "AbstractData type Variable contains") Attribute{Tuple{Vararg{String}}, Tuple{Vararg{String}}}( :data_dims, (), true, "", "Tuple of variable data dimension names, or empty for a scalar") Attribute{Type, AbstractSpace}( :space, CellSpace, true, "", "function space Variable is defined on") Attribute{String, Nothing}( :mesh, "default", false, "", "grid mesh on which Variable is defined (empty for Domain spatial scalar)") Attribute{Bool, Nothing}( :check_length, true, false, "", "true to check length matches length of linked VariableDomain") Attribute{Bool, Nothing}( :is_constant, false, true, "", "true if variable is not changed after initialisation") Attribute{VariableFunction, VariableFunction}( :vfunction, VF_Undefined, true, "", "host function (to label state variables etc)") Attribute{Vector{Int}, Nothing}( :operatorID, Int[], false, "", "Reaction operatorIDs that modify this Variable") Attribute{VariablePhase, VariablePhase}( :vphase, VP_Undefined, false, "", "phase for concentrations in multiphase cells") Attribute{Vector{String}, Nothing}( :totalnames, String[], false, "", "Vector of total Variable names for this species") Attribute{String, Nothing}( :rate_processname, "", false, "", "process name for this reaction rate variable") Attribute{Vector{String}, Nothing}( :rate_species, String[], false, "", "Vector of reactant and product species for this reaction rate variable") Attribute{Vector{Float64}, Nothing}( :rate_stoichiometry, Float64[], false, "", "Vector of reactant and product stoichiometries for this reaction rate variable") Attribute{String, Nothing}( :safe_name, "", false, "", "optional short or escaped name for compatibility with other software") Attribute{String, Nothing}( :long_name, "", false, "", "netcdf long descriptive name") Attribute{String, Nothing}( :units, "", true, "", "where possible should follow netcdf conventions") Attribute{String, Nothing}( :description, "", true, "", "human-readable description") Attribute{String, Nothing}( :standard_name, "", false, "", "netcdf CF conventions standard name") Attribute{Bool, Nothing}( :advect, false, false, "", "true to apply advective transport to this tracer") Attribute{Float64, Nothing}( :advect_zmin, 0.0, false, "m", "minimum height for transport") # Attribute{Bool, Nothing}( :optional, false, true, "", "") Attribute{Bool, Nothing}( :initialize_to_zero, false, false, "", "request initialize to zero at start of each timestep.") Attribute{Float64, Nothing}( :vertical_movement, 0.0, false, "m d-1", "vertical advective transport (+ve upwards) in column") Attribute{String, Nothing}( :diffusivity_speciesname, "", false, "", "species name to define diffusivity and charge") Attribute{Union{Float64,Missing}, Nothing}( :diffusivity, missing, false, "cm^2/s", "species diffusivity") Attribute{Union{Float64,Missing}, Nothing}( :charge, missing, false, "", "species charge") Attribute{Union{Float64,Vector{Float64}}, Nothing}( :initial_value, 0.0, true, "", "initial value to be applied eg to state or constant variable") Attribute{Union{Float64,Vector{Float64}}, Nothing}( :norm_value, 1.0, true, "", "normalisation value to be passed through to solver and optionally provided as model variable") Attribute{Float64, Nothing}( :initial_delta, 0.0, true, "per mil", "initial value for isotope variable to be applied eg to state or constant variable") Attribute{Float64, Nothing}( :specific_light_extinction, 0.0, false, "m^2 mol-1","wavelength-independent specific extinction in water column") Attribute{Union{Float64,Missing}, Nothing}( :deposition_velocity, missing, false, "cm s-1", "surface deposition velocity for atmospheric tracer") Attribute{Union{Float64,Missing}, Nothing}( :rainout, missing, false, "", "normalized rainout rate for atmospheric tracer") Attribute{Union{Float64,Missing}, Nothing}( :gamma, missing, false, "", "bioirrigation scaling factor for sediment solute") ] """ default_variable_attributes() Required attributes that should be present in all `VariableReaction` """ function default_variable_attributes() return Dict(a.name => a.default_value for a in StandardAttributes if a.required) end """ is_standard_attribute(attribute::Symbol) -> Bool ```jldoctest; setup = :(import PALEOboxes) julia> PALEOboxes.is_standard_attribute(:data_dims) true julia> PALEOboxes.is_standard_attribute(:foo) false ``` """ function is_standard_attribute(attribute::Symbol) return !isnothing(findfirst(a->a.name==attribute, StandardAttributes)) end """ standard_attribute_type(attribute::Symbol) -> DataType """ function standard_attribute_type(attribute::Symbol) idx = findfirst(a->a.name==attribute, StandardAttributes) if isnothing(idx) return nothing else return attributeType(StandardAttributes[idx]) end end ################################### # Internal implementation ################################## "Set attribute, with type conversion and checking" function _set_attribute!(attributes::Dict{Symbol, Any}, name::Symbol, value, allow_create) if haskey(attributes, name) || allow_create attributes[name] = _convert_standard_attribute_type(name, value) else error("invalid attempt to create new attribute ",name,"=",value) end return nothing end """ NB: conversion of :initial_value or :norm_value from an integer fails, eg julia> PALEOboxes._convert_standard_attribute_type(:initial_value, 1) as julia> convert(Union{Float64,Vector{Float64}}, 1) fails. ```jldoctest; setup = :(import PALEOboxes) julia> PALEOboxes._convert_standard_attribute_type(:initial_delta, 1) 1.0 julia> PALEOboxes._convert_standard_attribute_type(:my_new_attribute, 1) 1 julia> PALEOboxes._convert_standard_attribute_type(:vphase, "VP_Solute") VP_Solute::VariablePhase = 1 ``` """ function _convert_standard_attribute_type(attribute::Symbol, value) a_idx = findfirst(a->a.name==attribute, StandardAttributes) if isnothing(a_idx) return value # no type conversion else stdatt = StandardAttributes[a_idx] return convert(attributeType(stdatt), _parsevalue(stdatt, value)) end end # Default - no attempt to parse value from String function _parsevalue(attribute::Attribute{T, Nothing}, value) where {T} return value end function _parsevalue(attribute::Attribute{T, Nothing}, value::AbstractString) where {T} return value end # any (Data)Type - any subtype of PT is acceptable function _parsevalue(attribute::Attribute{T, PT}, value::Type{V}) where {T, PT, V <: PT} return value end # enum is a value of type T function _parsevalue(attribute::Attribute{T, T}, value::T) where {T} return value end # attempt to parse value from AbstractString into type PT function _parsevalue(attribute::Attribute{T, PT}, value::AbstractString) where {T, PT} return parse(PT, value) end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
20412
""" VariableDomain <: VariableBase Abstract base Type for a ([`Domain`](@ref)) model variable. Defines a named Variable and corresponding data [`Field`](@ref)s that are linked to by [`VariableReaction`](@ref)s. See [`VariableDomPropDep`](@ref), [`VariableDomContribTarget`](@ref) """ VariableDomain """ VariableDomPropDep <: VariableDomain [`Model`](@ref) ([`Domain`](@ref)) `VariableDomain` linking a single `VariableReaction{VT_ReactProperty}` to multiple `VariableReaction{VT_ReactDependency}`. """ Base.@kwdef mutable struct VariableDomPropDep <: VariableDomain ID::Int64 domain::AbstractDomain name::String master::VariableReaction var_property::Union{Nothing, VariableReaction{VT_ReactProperty}} = nothing var_property_setup::Union{Nothing, VariableReaction{VT_ReactProperty}} = nothing var_dependencies::Vector{VariableReaction{VT_ReactDependency}} = Vector{VariableReaction{VT_ReactDependency}}() end function get_properties(var::VariableDomPropDep) pvars = VariableReaction[] isnothing(var.var_property) || push!(pvars, var.var_property) isnothing(var.var_property_setup) || push!(pvars, var.var_property_setup) return pvars end get_var_type(var::VariableDomPropDep) = VT_DomPropDep """ VariableDomContribTarget <: VariableDomain [`Model`](@ref) ([`Domain`](@ref)) `VariableDomain` linking a single `VariableReaction{VT_ReactTarget}` to multiple `VariableReaction{VT_ReactContributor}` and `VariableReaction{VT_ReactDependency}`. """ Base.@kwdef mutable struct VariableDomContribTarget <: VariableDomain ID::Int64 domain::AbstractDomain name::String master::VariableReaction var_target::Union{Nothing, VariableReaction{VT_ReactTarget}} = nothing var_contributors::Vector{VariableReaction{VT_ReactContributor}} = Vector{VariableReaction{VT_ReactContributor}}() var_dependencies::Vector{VariableReaction{VT_ReactDependency}} = Vector{VariableReaction{VT_ReactDependency}}() end get_var_type(var::VariableDomContribTarget) = VT_DomContribTarget #################################### # Properties ################################### """ Base.getproperty(var::VariableDomain, s::Symbol) Define [`VariableDomain`](@ref) properties. `var.attributes` is forwarded to the linked [`VariableReaction`](@ref) defined by the `var.master` field. """ function Base.getproperty(var::VariableDomain, s::Symbol) if s == :attributes return var.master.attributes else return getfield(var, s) end end is_scalar(var::VariableDomain) = (var.attributes[:space] === ScalarSpace) "true if data array assigned" function is_allocated(var::VariableDomain, modeldata::AbstractModelData, arrays_idx::Int) return !isnothing(get_field(var, modeldata, arrays_idx)) end "fully qualified name" function fullname(var::VariableDomain) return var.domain.name*"."*var.name end function host_dependent(var::VariableDomPropDep) return isnothing(var.var_property) && isnothing(var.var_property_setup) end function host_dependent(var::VariableDomContribTarget) return isnothing(var.var_target) end ################################################ # Field and data access ################################################## """ set_field!(var::VariableDomain, modeldata, arrays_idx::Int, field::Field) Set `VariableDomain` data to `field` """ function set_field!(var::VariableDomain, modeldata::AbstractModelData, arrays_idx::Int, field::Field) variable_data = get_domaindata(modeldata, var.domain, arrays_idx).variable_data variable_data[var.ID] = field return nothing end """ set_data!(var::VariableDomain, modeldata, arrays_idx::Int, data) Set [`VariableDomain`](@ref) to a Field containing `data`. Calls [`wrap_field`](@ref) to create a new [`Field`](@ref). """ function set_data!(var::VariableDomain, modeldata::AbstractModelData, arrays_idx::Int, data) variable_data = get_domaindata(modeldata, var.domain, arrays_idx).variable_data variable_data[var.ID] = wrap_field( data, get_attribute(var, :field_data), Tuple(get_data_dimension(domain, dn) for dn in get_attribute(var, :data_dims)), get_attribute(var, :datatype), get_attribute(var, :space), var.domain.grid, ) return nothing end """ get_field(var::VariableDomain, modeldata::AbstractModelData, arrays_idx::Int) -> field::Field get_field(var::VariableDomain, domaindata::AbstractDomainData) -> field::Field Get Variable `var` `field` """ function get_field(var::VariableDomain, modeldata::AbstractModelData, arrays_idx::Int=1) domaindata = get_domaindata(modeldata, var.domain, arrays_idx) return get_field(var, domaindata) end function get_field(var::VariableDomain, domaindata::AbstractDomainData) return domaindata.variable_data[var.ID] end """ 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`](@ref).values """ get_data(var::VariableDomain, modeldata::AbstractModelData, arrays_idx::Int=1) = get_field(var, modeldata, arrays_idx).values get_data(var::VariableDomain, domaindata::AbstractDomainData) = get_field(var, domaindata).values """ 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`](@ref).values`)` """ get_data_output(var::VariableDomain, modeldata::AbstractModelData, arrays_idx::Int=1) = get_values_output(get_field(var, modeldata, arrays_idx)) get_data_output(var::VariableDomain, domaindata::AbstractDomainData) = get_values_output(get_field(var, domaindata)) #################################################################### # Create and add to Domain ################################################################## "create and add to Domain" function create_VariableDomPropDep(domain, name, master) newvar = VariableDomPropDep(domain=domain, name=name, master=master, ID=_next_variable_ID(domain)) if haskey(domain.variables, name) error("attempt to add duplicate VariableDomPropDep $(domain.name).$(name) to Domain") end domain.variables[name] = newvar _reset_master!(newvar, master) return newvar end "create and add to Domain" function create_VariableDomContribTarget(domain, name, master) newvar = VariableDomContribTarget(domain=domain, name=name, master=master, ID=_next_variable_ID(domain)) if haskey(domain.variables, name) error("attempt to add duplicate VariableDomContribTarget $(domain.name).$(name) to Domain") end domain.variables[name] = newvar _reset_master!(newvar, master) return newvar end ############################################################# # Allocate data arrays ############################################################# """ 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 [`VariableDomain`](@ref)s `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 (arrays_idx=1) - `use_base_transfer_jacobian=true` and Variable `:transfer_jacobian` attribute is set - Variable full name is in `use_base_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`). """ function allocate_variables!( vars, modeldata::AbstractModelData, arrays_idx::Int; eltypemap=Dict{String, DataType}(), default_host_dependent_field_data=ScalarData, allow_base_link=true, use_base_transfer_jacobian=true, use_base_vars=String[], check_units_opt=:no, ) for v in vars check_lengths(v) check_units(v; check_units_opt) data_dims = Tuple( get_data_dimension(v.domain, dimname) for dimname in get_attribute(v, :data_dims) ) # eltype usually is eltype(modeldata, arrays_idx), but can be overridden by :datatype attribute # (can be used by a Reaction to define a fixed type eg Float64 for a constant Property) mdeltype = get_attribute(v, :datatype, eltype(modeldata, arrays_idx)) if mdeltype isa AbstractString mdeltype_str = mdeltype mdeltype = get(eltypemap, mdeltype_str, Float64) @debug "Variable $(fullname(v)) mdeltype $mdeltype_str -> $mdeltype" end thread_safe = false if get_attribute(v, :atomic, false) && modeldata.threadsafe @info " $(fullname(v)) allocating Atomic data" thread_safe = true end field_data = get_attribute(v, :field_data) space = get_attribute(v, :space) if field_data == UndefinedData if host_dependent(v) && (get_attribute(v, :vfunction, VF_Undefined) == VF_Undefined) && !isnothing(default_host_dependent_field_data) set_attribute!(v, :field_data, default_host_dependent_field_data) field_data = get_attribute(v, :field_data) @info " set :field_data=$field_data for host-dependent Variable $(fullname(v))" else error("allocate_variables! :field_data=UndefinedData for Variable $(fullname(v)) $v") end end # allocate or link if (arrays_idx != 1 && allow_base_link) && ( mdeltype == eltype(modeldata, 1) || (use_base_transfer_jacobian && get_attribute(v, :transfer_jacobian, false)) || fullname(v) in use_base_vars ) # link to existing array v_field = get_field(v, modeldata, 1) else # allocate new field array v_field = allocate_field( field_data, data_dims, mdeltype, space, v.domain.grid, thread_safe=thread_safe, allocatenans=modeldata.allocatenans ) end set_field!(v, modeldata, arrays_idx, v_field) end return nothing end """ reallocate_variables!(vars, modeldata, arrays_idx, new_eltype) -> [(v, old_eltype), ...] Reallocate memory for [`VariableDomain`](@ref)s `vars` to `new_eltype`. Returns Vector of `(reallocated_variable, old_eltype)`. """ function reallocate_variables!(vars, modeldata::AbstractModelData, arrays_idx::Int, new_eltype) reallocated_variables = [] for v in vars v_data = get_data(v, modeldata) if v_data isa AbstractArray old_eltype = eltype(v_data) if old_eltype != new_eltype set_data!(v, modeldata, arrays_idx, similar(v_data, new_eltype)) push!(reallocated_variables, (v, old_eltype)) end end end return reallocated_variables end """ check_lengths(var::VariableDomain) Check that sizes of all linked Variables match """ function check_lengths(var::VariableDomain) var_space = get_attribute(var, :space) for lv in get_all_links(var) if get_attribute(lv, :check_length, true) try var_size = internal_size(var_space, var.domain.grid, lv.linkreq_subdomain) link_space = get_attribute(lv, :space) link_size = internal_size(link_space, lv.method.domain.grid) var_size == link_size || error("check_lengths: VariableDomain $(fullname(var)), :space=$var_space size=$var_size "* "!= $(fullname(lv)), :space=$link_space size=$link_size created by $(typename(lv.method.reaction)) (check size of Domains $(var.domain.name), $(lv.method.domain.name), "* "$(isempty(lv.linkreq_subdomain) ? "" : "subdomain "*lv.linkreq_subdomain*",") and Variables :space)") catch error("check_lengths: exception VariableDomain $(fullname(var)), :space=$var_space "* "linked by $(fullname(lv)), created by $(typename(lv.method.reaction)) (check size of Domains $(var.domain.name), $(lv.method.domain.name), "* "$(isempty(lv.linkreq_subdomain) ? "" : "subdomain "*lv.linkreq_subdomain*",") and Variables :space)") end end end return nothing end """ check_units(var::VariableDomain; check_units_opt=:warn) Check that units of all linked Variables match """ function check_units(var::VariableDomain; check_units_opt=:warn) check_units_opt in (:no, :warn, :error) || error("check_units(): unsupported option check_units_opt=$check_units_opt (allowed values are :no, :warn, :error)") check_units_opt == :no && return var_units = get_attribute(var, :units) num_errors = 0 for lv in get_all_links(var) lv_units = get_attribute(lv, :units) if !_compare_units(var_units, lv_units) num_errors += 1 @warn "check_units: VariableDomain $(fullname(var)), :units=\"$var_units\" (from master $(typename(var.master.method.reaction)) $(fullname(var.master)))"* " != $(fullname(lv)), :units=\"$lv_units\" (created by $(typename(lv.method.reaction)) $(fullname(lv.method.reaction)))" end end if check_units_opt == :error && !iszero(num_errors) error("check_units: VariableDomain $(fullname(var)), :units=$var_units units of linked variables do not match") end return num_errors end function _compare_units(units1, units2) # very crude regularization of unit strings: m^3 and m3 are both accepted units1 = replace(units1, "^"=>"") units2 = replace(units2, "^"=>"") return (units1 == units2) || (units1 == "unknown") || (units2 == "unknown") end #################################################################### # Manage linked VariableReactions ################################################################## function add_dependency(vardom::VariableDomPropDep, varreact::VariableReaction{VT_ReactDependency}) push!(vardom.var_dependencies, varreact) if get_attribute(varreact, :vfunction) in (VF_StateExplicit, VF_StateTotal, VF_State) @debug " Resetting master variable" _reset_master!(vardom, varreact) end return nothing end function add_dependency(vardom::VariableDomContribTarget, varreact::VariableReaction{VT_ReactDependency}) push!(vardom.var_dependencies, varreact) vf = get_attribute(varreact, :vfunction) if vf in (VF_StateExplicit, VF_StateTotal, VF_State) error("attempt to link Dependency with :vfunction==$vf to a VariableDomContribTarget "* "$(fullname(varreact)) --> $(fullname(vardom))") end return nothing end function add_contributor(vardom::VariableDomPropDep, varreact::VariableReaction{VT_ReactContributor}) error("configuration error: attempting to link a VariableReactContrib $(fullname(varreact)) "* "(usually a flux) which must link to a Target, to a Property VariableDomPropDep $(fullname(vardom))") return nothing end function add_contributor(vardom::VariableDomContribTarget, varreact::VariableReaction{VT_ReactContributor}) push!(vardom.var_contributors, varreact) if get_attribute(varreact, :vfunction) in (VF_Deriv, VF_Total, VF_Constraint) @debug " Resetting master variable" _reset_master!(vardom, varreact) end return nothing end # reset master variable function _reset_master!(var::VariableDomain, master::VariableReaction) var.master = master end function get_all_links(var::VariableDomPropDep) all_links = Vector{VariableReaction}() append!(all_links, get_properties(var)) append!(all_links, var.var_dependencies) return all_links end function get_all_links(var::VariableDomContribTarget) all_links = Vector{VariableReaction}() isnothing(var.var_target) || push!(all_links, var.var_target) append!(all_links, var.var_contributors) append!(all_links, var.var_dependencies) return all_links end function get_modifying_methods(var::VariableDomPropDep) methods = AbstractReactionMethod[rv.method for rv in get_properties(var)] return methods end function get_modifying_methods(var::VariableDomContribTarget) methods = AbstractReactionMethod[rv.method for rv in var.var_contributors] return methods end function get_dependent_methods(var::VariableDomPropDep) methods = AbstractReactionMethod[rv.method for rv in var.var_dependencies] return methods end function get_dependent_methods(var::VariableDomContribTarget) methods = AbstractReactionMethod[rv.method for rv in var.var_dependencies] if !isnothing(var.var_target) push!(methods, var.var_target.method) end return methods end ############################## # Pretty printing ############################ "compact display form" function Base.show(io::IO, var::VariableDomain) print(io, typeof(var), "(name='", var.name,"'", ", hostdep=", host_dependent(var), ")" ) end "multiline display form" function Base.show(io::IO, ::MIME"text/plain", var::VariableDomain) println(io, typeof(var)) println(io, " name='", var.name, "'") println(io, " hostdep=", host_dependent(var)) println(io, " attributes=", var.attributes) end """ 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 [`VariableReaction`](@ref)s linked to this [`VariableDomain`](@ref) `varnamefull` should be of form "<domain name>.<variable name>" Linked variables are shown as "<domain name>.<reaction name>.<method name>.<local name>" """ function show_links end show_links(vardom::VariableDomain) = show_links(stdout, vardom) # implementation of show_links(model::Model, varnamefull::AbstractString) is in Model.jl function show_links(io::IO, vardom::VariableDomPropDep) println(io, "\t$(typeof(vardom)) \"$(fullname(vardom))\" links:") println(io, "\t\tproperty:\t", if isnothing(vardom.var_property) "nothing" else "\""*fullname(vardom.var_property)*"\"" end) if !isnothing(vardom.var_property_setup) println(io, "\t\tproperty_setup:\t", "\""*fullname(vardom.var_property_setup)*"\"") end println(io, "\t\tdependencies:\t", String[fullname(var) for var in vardom.var_dependencies]) return nothing end function show_links(io::IO, vardom::VariableDomContribTarget) println(io, "\t$(typeof(vardom)) \"$(fullname(vardom))\" links:") println(io, "\t\ttarget:\t\t", if isnothing(vardom.var_target) "nothing" else "\""*fullname(vardom.var_target)*"\"" end) println(io, "\t\tcontributors:\t", String[fullname(var) for var in vardom.var_contributors]) println(io, "\t\tdependencies:\t", String[fullname(var) for var in vardom.var_dependencies]) return nothing end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
46132
# import Infiltrator ############################################# # VariableReaction ############################################# # define docstring, this is then attached to relevant functions (see further down in this file) const variable_reaction_docstr = """ 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} VarDep, VarDepColumn, VarDepScalar, VarDepStateIndep, VarDepColumnStateIndep, VarDepScalarStateIndep -> VariableReaction{VT_ReactDependency} VarTarget, VarTargetScalar -> VariableReaction{VT_ReactTarget} VarContrib, VarContribColumn, VarContribScalar -> VariableReaction{VT_ReactContributor} VarStateExplicit, VarStateExplicitScalar -> VariableReaction{VT_ReactDependency} VarDeriv, VarDerivScalar -> VariableReaction{VT_ReactContributor} VarState, VarStateScalar -> VariableReaction{VT_ReactDependency} VarConstraint, VarConstraintScalar -> VariableReaction{VT_ReactDependency} [deprecated] VariableReaction(VT, localname, units, description; link_namestr, attributes=Tuple()) -> VariableReaction{VT} Reaction view on a model variable. Reactions define [`AbstractVarList`](@ref)s of `VariableReaction`s when creating a [`ReactionMethod`](@ref). Within a `ReactionMethod`, a `VariableReaction` is referred to by `localname`. When the model is initialised, [`VariableDomain`](@ref) variables are created that link together `VariableReaction`s with the same `link_namestr`, and data Arrays are allocated. `views` on the `VariableDomain` data Arrays are then passed to the [`ReactionMethod`](@ref) 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 `VariableReaction`s with [`VariableDomain`](@ref)s: - Reaction Property and Dependency Variables, linked to a [`VariableDomPropDep`](@ref). 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`](@ref). 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`](@ref) (scalar, per-cell, etc) and data content `:field_data` [`AbstractData`](@ref), 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 name | VT | attributes | | | | | | |-----------------------|-----------------------|---------------|---------------|---------------|-----------------------|-----------|--------------| | | | `:space` | `:field_data` | `:vfunction` | `:initialize_to_zero` |`:datatype`|`:is_constant`| ||||||||| | `VarProp` | `VT_ReactProperty` | `CellSpace` | `ScalarData` | `VF_Undefined`| - | - | false | | `VarPropScalar` | `VT_ReactProperty` | `ScalarSpace` | `ScalarData` | `VF_Undefined`| - | - | false | | `VarPropStateIndep` | `VT_ReactProperty` | `CellSpace` | `ScalarData` | `VF_Undefined`| - | `Float64` | true | | `VarPropScalarStateIndep`|`VT_ReactProperty` | `ScalarSpace` | `ScalarData` | `VF_Undefined`| - | `Float64` | true | ||||||||| | `VarDep` | `VT_ReactDependency` | `CellSpace` | `UndefinedData`|`VF_Undefined`| - | - | false | | `VarDepColumn` | `VT_ReactDependency` | `ColumnSpace` | `UndefinedData`|`VF_Undefined`| - | - | false | | `VarDepScalar` | `VT_ReactDependency` | `ScalarSpace` | `UndefinedData`|`VF_Undefined`| - | - | false | | `VarDepStateIndep` | `VT_ReactDependency` | `CellSpace` | `UndefinedData`|`VF_Undefined`| - | `Float64` | true | | `VarDepColumnStateIndep`|`VT_ReactDependency` | `ColumnSpace` | `UndefinedData`|`VF_Undefined`| - | `Float64` | true | | `VarDepScalarStateIndep`| `VT_ReactDependency`| `ScalarSpace` | `UndefinedData`|`VF_Undefined`| - | `Float64` | true | ||||||||| | `VarTarget` | `VT_ReactTarget` | `CellSpace` | `ScalarData` | `VF_Undefined`| `true` | - | false | | `VarTargetScalar` | `VT_ReactTarget` | `ScalarSpace` | `ScalarData` | `VF_Undefined`| `true` | - | false | ||||||||| | `VarContrib` | `VT_ReactContributor` | `CellSpace` | `UndefinedData`|`VF_Undefined`| - | - | false | | `VarContribColumn` | `VT_ReactContributor` | `ColumnSpace` | `UndefinedData`|`VF_Undefined`| - | - | false | | `VarContribScalar` | `VT_ReactContributor` | `ScalarSpace` | `UndefinedData`|`VF_Undefined`| - | - | false | ||||||||| | `VarStateExplicit` | `VT_ReactDependency` | `CellSpace` | `ScalarData` | `VF_StateExplicit`| - | - | false | | `VarStateExplicitScalar`| `VT_ReactDependency`| `ScalarSpace` | `ScalarData` | `VF_StateExplicit`| - | - | false | | `VarDeriv` | `VT_ReactContributor` | `CellSpace` | `ScalarData` | `VF_Deriv` | `true` | - | false | | `VarDerivScalar` | `VT_ReactContributor` | `ScalarSpace` | `ScalarData` | `VF_Deriv` | `true` | - | false | ||||||||| | `VarState` | `VT_ReactDependency` | `CellSpace` | `ScalarData` | `VF_State` | - | - | false | | `VarStateScalar` | `VT_ReactDependency` | `ScalarSpace` | `ScalarData` | `VF_State` | - | - | false | | `VarConstraint` | `VT_ReactContributor` | `CellSpace` | `ScalarData` | `VF_Constraint`| `true` | - | false | | `VarConstraintScalar` | `VT_ReactContributor` | `ScalarSpace` | `ScalarData` | `VF_Constraint`| `true` | - | false | This illustrates some general principles for the use of attributes: - All Variables must define the `:space` VariableAttribute (a subtype of [`AbstractSpace`](@ref)) 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`](@ref)) 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!`](@ref)) 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 :initialize_to_zero 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`](@ref). 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`](@ref) 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`](@ref) 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 - `attributes::Tuple(:attrb1name=>attrb1value, :attrb2name=>attrb2value, ...)`: variable attributes, see [`StandardAttributes`](@ref), [`set_attribute!`](@ref), [`get_attribute`](@ref) """ Base.@kwdef mutable struct VariableReaction{VT} <: VariableBase method::Union{Nothing, AbstractReactionMethod} = nothing localname::String attributes::Dict{Symbol, Any} = default_variable_attributes() "Requested (ie set by config file) named domain-hosted variable to link to" linkreq_domain::String = "" linkreq_subdomain::String = "" linkreq_name::String = "" link_optional::Bool = false # VT_ReactDependency, VT_ReactContributor only "Link variable" linkvar::Union{Nothing, VariableDomain} = nothing end get_var_type(var::VariableReaction{VT}) where VT = VT const VarPropT = VariableReaction{VT_ReactProperty} const VarDepT = VariableReaction{VT_ReactDependency} const VarTargetT = VariableReaction{VT_ReactTarget} const VarContribT = VariableReaction{VT_ReactContributor} VariableReaction( VT::VariableType, localname_linkname::Pair{<:AbstractString, <:AbstractString}, units::AbstractString, description::AbstractString; attributes::Tuple{Vararg{Pair}}=(), # (:atrb1=>value1, :atrb2=>value2) ) = VariableReaction( VT, first(localname_linkname), units, description; link_namestr=last(localname_linkname), attributes=attributes ) function VariableReaction( VT::VariableType, linklocal_namestr::AbstractString, units::AbstractString, description::AbstractString; attributes::Tuple{Vararg{Pair}}=(), # (:atrb1=>value1, :atrb2=>value2) link_namestr = linklocal_namestr ) (_, _, localname, _) = parse_variablereaction_namestr(linklocal_namestr) localname = sub_variablereaction_linkreq_name(localname, "") # strip %reaction% if linklocal_namestr != link_namestr linklocal_namestr == localname || error("VariableReaction: invalid combination of explicit link_namestr=$link_namestr and localname=$linklocal_namestr") end (linkreq_domain, linkreq_subdomain, linkreq_name, link_optional) = parse_variablereaction_namestr(link_namestr) VT in (VT_ReactProperty, VT_ReactDependency, VT_ReactContributor, VT_ReactTarget) || error("VariableReaction $name invalid VT=$VT") newvar = VariableReaction{VT}( localname=localname, linkreq_domain=linkreq_domain, linkreq_subdomain=linkreq_subdomain, linkreq_name=linkreq_name, link_optional=link_optional, ) if ((get_var_type(newvar) == VT_ReactProperty) || (get_var_type(newvar) == VT_ReactTarget)) && link_optional error("VariableReaction $name invalid link_optional=$link_optional") end set_attribute!(newvar, :units, units) set_attribute!(newvar, :description, description) for (namesymbol, value) in attributes set_attribute!(newvar, namesymbol, value; allow_create=true) end return newvar end function Base.copy(v::VariableReaction{T}) where T vcopy = VariableReaction{T}( method = v.method, localname = v.localname, attributes = copy(v.attributes), # NB: no deepcopy # attributes = Dict{Symbol, Any}(k=>copy(v) for (k, v) in v.attributes), # linkreq_domain = v.linkreq_domain, linkreq_subdomain = v.linkreq_subdomain, linkreq_name = v.linkreq_name, link_optional = v.link_optional, linkvar = v.linkvar, ) return vcopy end """ get_domvar_attribute(var::VariableReaction, name::Symbol, missing_value=missing) -> value Get the 'master' Variable attribute from the VariableDomain a VariableReaction is linked to. TODO: this is almost always what is wanted, as only the 'master' VariableReaction will be updated by the configuration file. """ function get_domvar_attribute(var::VariableReaction, name::Symbol, missing_value=missing) domvar = var.linkvar !isnothing(domvar) || error("get_domvar_attribute: VariableReaction $(fullname(var)) not linked") return get_attribute(domvar, name, missing_value) end """ reset_link_namestr!(var, link_namestr) Reset `link_namestr` after Variable creation, but before Model link_variables """ function reset_link_namestr!(var, link_namestr) (linkreq_domain, linkreq_subdomain, linkreq_name, link_optional) = parse_variablereaction_namestr(link_namestr) var.linkreq_domain = linkreq_domain var.linkreq_subdomain = linkreq_subdomain var.linkreq_name = linkreq_name var.link_optional = link_optional return nothing end # convenience functions to create commonly-used VariableReaction subtypes, with appropriate attributes set # NB: order matters within the combined attributes list: later entries can overwrite earlier entries, so the order should be: # - default value for attributes eg :field_data that can be changed # - the supplied attributes argument # - attributes eg :vfunction that cannot be overridden by the supplied attributes argument VarPropScalar(localname, units, description; attributes::Tuple=(), kwargs...) = VarProp(localname, units, description; attributes=(attributes..., :space=>ScalarSpace), kwargs...) VarProp(localname, units, description; attributes::Tuple=(), kwargs... ) = VariableReaction(VT_ReactProperty, localname, units, description; attributes=(:field_data=>ScalarData, attributes...), kwargs...) VarPropScalarStateIndep(localname, units, description; attributes::Tuple=(), kwargs... ) = VarPropScalar(localname, units, description; attributes=(:datatype=>Float64, attributes..., :is_constant=>true), kwargs...) VarPropStateIndep(localname, units, description; attributes::Tuple=(), kwargs...) = VarProp(localname, units, description; attributes=(:datatype=>Float64, attributes..., :is_constant=>true), kwargs...) VarDepScalar(localname, units, description; attributes::Tuple=(), kwargs... ) = VarDep(localname, units, description; attributes=(attributes..., :space=>ScalarSpace), kwargs...) VarDepColumn(localname, units, description; attributes::Tuple=(), kwargs... ) = VarDep(localname, units, description; attributes=(attributes..., :space=>ColumnSpace), kwargs...) VarDep(localname, units, description; kwargs... ) = VariableReaction(VT_ReactDependency, localname, units, description; kwargs...) VarDepScalarStateIndep(localname, units, description; attributes::Tuple=(), kwargs... ) = VarDepScalar(localname, units, description; attributes=(:datatype=>Float64, attributes..., :is_constant=>true), kwargs...) VarDepColumnStateIndep(localname, units, description; attributes::Tuple=(), kwargs... ) = VarDepColumn(localname, units, description; attributes=(:datatype=>Float64, attributes..., :is_constant=>true), kwargs...) VarDepStateIndep(localname, units, description; attributes::Tuple=(), kwargs...) = VarDep(localname, units, description; attributes=(:datatype=>Float64, attributes..., :is_constant=>true), kwargs...) # create a VarDep suitable for linking to a VarProp or VarTarget VarDep(v::VarDepT) = v function VarDep(v::Union{VarPropT, VarTargetT}) vdep = VarDepT( localname = v.localname, attributes = copy(v.attributes), # NB: no deepcopy linkreq_domain = v.linkreq_domain, linkreq_subdomain = v.linkreq_subdomain, linkreq_name = v.linkreq_name ) # remove as v will handle this has_attribute(vdep, :initialize_to_zero) && set_attribute!(vdep, :initialize_to_zero, false) has_attribute(vdep, :calc_total) && set_attribute!(vdep, :calc_total, false) return vdep end VarTargetScalar(localname, units, description; attributes::Tuple=(), kwargs... ) = VarTarget(localname, units, description; attributes=(attributes..., :space=>ScalarSpace), kwargs...) # set :initialize_to_zero on VarTarget VarTarget(localname, units, description; attributes::Tuple=(), kwargs... ) = VariableReaction(VT_ReactTarget, localname, units, description; attributes=(:initialize_to_zero=>true, :field_data=>ScalarData, attributes...), kwargs...) VarContribScalar(localname, units, description; attributes::Tuple=(), kwargs... ) = VarContrib(localname, units, description; attributes=(attributes..., :space=>ScalarSpace), kwargs...) VarContribColumn(localname, units, description; attributes::Tuple=(), kwargs... ) = VarContrib(localname, units, description; attributes=(attributes..., :space=>ColumnSpace), kwargs...) VarContrib(localname, units, description; kwargs... ) = VariableReaction(VT_ReactContributor, localname, units, description; kwargs...) VarContrib(v::VarContribT) = v function VarContrib(v::VarTargetT) vcontrib = VarContribT( localname=v.localname, attributes=copy(v.attributes), # NB: no deepcopy linkreq_domain=v.linkreq_domain, linkreq_subdomain=v.linkreq_subdomain, linkreq_name=v.linkreq_name, ) # remove as v will handle this has_attribute(vcontrib, :initialize_to_zero) && set_attribute!(vcontrib, :initialize_to_zero, false) has_attribute(vcontrib, :calc_total) && set_attribute!(vcontrib, :calc_total, false) return vcontrib end VarStateExplicitScalar(localname, units, description; attributes::Tuple=(), kwargs...) = VarDepScalar(localname, units, description; attributes=(:field_data=>ScalarData, attributes..., :vfunction=>VF_StateExplicit), kwargs...) VarStateExplicit(localname, units, description; attributes::Tuple=(), kwargs... ) = VarDep(localname, units, description; attributes=(:field_data=>ScalarData, attributes..., :vfunction=>VF_StateExplicit), kwargs...) # set :initialize_to_zero as :vfunction VF_Total is host-dependent so there will be no VT_ReactTarget within the model to handle :initialize_to_zero VarTotalScalar(localname, units, description; attributes::Tuple=(), kwargs...) = VarContribScalar(localname, units, description; components, attributes=(:initialize_to_zero=>true, :field_data=>ScalarData, attributes..., :vfunction=>VF_Total), kwargs...) VarTotal(localname, units, description; attributes::Tuple=(), kwargs... ) = VarContrib(localname, units, description; attributes=(:initialize_to_zero=>true, :field_data=>ScalarData, attributes..., :vfunction=>VF_Total), kwargs...) VarStateTotalScalar(localname, units, description; attributes::Tuple=(), kwargs...) = VarDepScalar(localname, units, description; attributes=(:field_data=>ScalarData, attributes..., :vfunction=>VF_StateTotal), kwargs...) VarStateTotal(localname, units, description; attributes::Tuple=(), kwargs... ) = VarDep(localname, units, description; attributes=(:field_data=>ScalarData, attributes..., :vfunction=>VF_StateTotal), kwargs...) # set :initialize_to_zero as :vfunction VF_Deriv is host-dependent so there will be no VT_ReactTarget within the model to handle :initialize_to_zero VarDerivScalar(localname, units, description; attributes::Tuple=(), kwargs... ) = VarContribScalar(localname, units, description; attributes=(:initialize_to_zero=>true, :field_data=>ScalarData, attributes..., :vfunction=>VF_Deriv), kwargs...) VarDeriv(localname, units, description; attributes::Tuple=(), kwargs... ) = VarContrib(localname, units, description; attributes=(:initialize_to_zero=>true, :field_data=>ScalarData, attributes..., :vfunction=>VF_Deriv), kwargs...) # set :initialize_to_zero as :vfunction VF_Constraint is host-dependent so there will be no VT_ReactTarget within the model to handle :initialize_to_zero VarConstraintScalar(localname, units, description; attributes::Tuple=(), kwargs... ) = VarContribScalar(localname, units, description; attributes=(:initialize_to_zero=>true, :field_data=>ScalarData, attributes..., :vfunction=>VF_Constraint), kwargs...) VarConstraint(localname, units, description; attributes::Tuple=(), kwargs... ) = VarContrib(localname, units, description; attributes=(:initialize_to_zero=>true, :field_data=>ScalarData, attributes..., :vfunction=>VF_Constraint), kwargs...) VarStateScalar(localname, units, description; attributes::Tuple=(), kwargs...) = VarDepScalar(localname, units, description; attributes=(:field_data=>ScalarData, attributes..., :vfunction=>VF_State), kwargs...) VarState(localname, units, description; attributes::Tuple=(), kwargs... ) = VarDep(localname, units, description; attributes=(:field_data=>ScalarData, attributes..., :vfunction=>VF_State), kwargs...) # TODO: define a VarInit Type. Currently (ab)using VarDep VarInit(v::Union{VarPropT, VarTargetT, VarContribT}) = VarDepT( localname = v.localname, attributes = copy(v.attributes), # NB: no deepcopy linkreq_domain = v.linkreq_domain, linkreq_subdomain = v.linkreq_subdomain, linkreq_name = v.linkreq_name ) function VarInit(v::VarDepT) error("VarInit for VarDepT $(fullname(v))") end # attach docstring to relevant functions "$variable_reaction_docstr" VariableReaction, VarProp, VarPropScalar, VarPropStateIndep, VarPropScalarStateIndep, VarDep, VarDepColumn, VarDepScalar, VarDepStateIndep, VarDepColumnStateIndep, VarDepScalarStateIndep, VarTarget, VarTargetScalar, VarContrib, VarContribColumn, VarContribScalar, VarStateExplicit, VarStateExplicitScalar, VarTotal, VarTotalScalar, VarStateTotal, VarStateTotalScalar, VarDeriv, VarDerivScalar, VarState, VarStateScalar, VarConstraint, VarConstraintScalar """ VarVector(variable_ctorfn, variables_list) -> Vector{VariableReaction{T}} Create and return a `Vector{VariableReaction{T}}` defined by specified `variable_ctorfn` from `variables_list = [(linklocal_namestr, units, description), ...]`` """ VarVector(variable_ctorfn, variables_list) = [ variable_ctorfn(linklocal_namestr, units, description) for (linklocal_namestr, units, description) in variables_list ] ######################################################################### # VarLists ######################################################################### """ AbstractVarList Variables required by a [`ReactionMethod`](@ref) `methodfn` are specified by a Tuple of VarList_xxx <: AbstractVarList, each containing a collection of [`VariableReaction`](@ref). These are then converted (by the [`create_accessors`](@ref) method) to a corresponding Tuple of collections of views on Domain data arrays , which are then be passed to the [`ReactionMethod`](@ref) `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`](@ref), returning the views on Domain data arrays in a subtype-specific collection. - [`get_variables`](@ref), returning the collection of VariableReactions (as a flat list). """ abstract type AbstractVarList end """ 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. """ function create_accessors(va::AbstractVarList, modeldata::AbstractModelData, arrays_idx::Int) end """ get_variables(varlist::AbstractVarList; flatten=true) -> Vector{VariableReaction} Return VariableReaction in `varlist`. If `flatten=true`, a Vector-of-Vectors is flattened. """ function get_variables(va::AbstractVarList) end """ VarList_single(var; components=false) -> VarList_single Create a `VarList_single` describing a single `VariableReaction`, `create_accessors` will then return a single accessor. """ struct VarList_single <: AbstractVarList var::VariableReaction components::Bool VarList_single(var; components=false) = new(copy(var), components) end get_variables(vl::VarList_single; flatten=true) = [vl.var] create_accessors(vl::VarList_single, modeldata::AbstractModelData, arrays_idx::Int) = create_accessor(vl.var, modeldata, arrays_idx, vl.components) """ VarList_components(varcollection) -> VarList_components Create a `VarList_components` describing a collection of `VariableReaction`s, `create_accessors` will then return a Vector with data array components concatenated (flattened). """ struct VarList_components <: AbstractVarList vars::Vector{VariableReaction} allow_unlinked::Bool VarList_components(varcollection; allow_unlinked=false) = new([copy(v) for v in varcollection], allow_unlinked) end get_variables(vl::VarList_components; flatten=true) = vl.vars function create_accessors(vl::VarList_components, modeldata::AbstractModelData, arrays_idx::Int) accessors_generic = [] for v in vl.vars a = create_accessor(v, modeldata, arrays_idx, true) if isnothing(a) || isempty(a) if vl.allow_unlinked append!(accessors_generic, fill(nothing, num_components(v))) else error("create_accessors(::VarList_components, ) - unlinked variable $(fullname(v)) $v") end else append!(accessors_generic, a) end end accessors_typed = [a for a in accessors_generic] # narrow Type return accessors_typed end # _dynamic_svector(av) = _dynamic_svector(Val(length(av)), av) # _dynamic_svector(::Val{N}, av) where {N} = StaticArrays.SVector{N}(av) struct VarList_namedtuple <: AbstractVarList vars::Vector{VariableReaction} keys::Vector{Symbol} components::Bool end """ VarList_namedtuple(varcollection; components=false) -> VarList_namedtuple Create a `VarList_namedtuple` describing a collection of `VariableReaction`s, `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. """ function VarList_namedtuple(varcollection; components=false) keys = Symbol.([v.localname for v in varcollection]) vars = [copy(v) for v in varcollection] return VarList_namedtuple(vars, keys, components) end """ VarList_namedtuple_fields(objectwithvars; components=false) -> VarList_namedtuple Create a `VarList_namedtuple` describing `VariableReaction` fields in `objectwithvars`, `create_accessors` will then return a NamedTuple with field names = field names in `objectwithvars` and field values = corresponding data arrays. If `components = true`, each NamedTuple field will be a Vector of data array components. """ function VarList_namedtuple_fields(objectwithvars; components=false) # find field names and VariableReactions fieldnamesvars = [(f, getproperty(objectwithvars, f)) for f in propertynames(objectwithvars) if getproperty(objectwithvars, f) isa VariableReaction] keys = [f for (f,v) in fieldnamesvars] vars = [copy(v) for (f,v) in fieldnamesvars] return VarList_namedtuple(vars, keys, components) end get_variables(vl::VarList_namedtuple; flatten=true) = vl.vars create_accessors(vl::VarList_namedtuple, modeldata::AbstractModelData, arrays_idx::Int) = NamedTuple{Tuple(vl.keys)}(create_accessor(v, modeldata, arrays_idx, vl.components) for v in vl.vars) """ VarList_tuple(varcollection; components=false) -> VarList_tuple Create a `VarList_tuple` describing a collection of `VariableReaction`s, `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. """ struct VarList_tuple <: AbstractVarList vars::Vector{Union{VariableReaction, Nothing}} components::Bool VarList_tuple(varcollection; components=false) = new([isnothing(v) ? nothing : copy(v) for v in varcollection], components) end get_variables(vl::VarList_tuple; flatten=true) = filter(!isnothing, vl.vars) create_accessors(vl::VarList_tuple, modeldata::AbstractModelData, arrays_idx::Int) = Tuple(isnothing(v) ? nothing : create_accessor(v, modeldata, arrays_idx, vl.components) for v in vl.vars) Base.@deprecate VarList_tuple_nothing(nvec) VarList_tuple(fill(nothing, nvec)) """ VarList_ttuple(varcollection) -> VarList_ttuple Create a `VarList_ttuple` describing a collection of collections of `VariableReaction`s, `create_accessors` will then return a Tuple of Tuples of data arrays. """ struct VarList_ttuple <: AbstractVarList vars::Vector{Vector{VariableReaction}} VarList_ttuple(vars) = new([[copy(v) for v in vv] for vv in vars]) end get_variables(vl::VarList_ttuple; flatten=true) = flatten ? vcat(vl.vars...) : vl.vars create_accessors(vl::VarList_ttuple, modeldata::AbstractModelData, arrays_idx::Int) = Tuple(Tuple(create_accessor(v, modeldata, arrays_idx, false) for v in vv) for vv in vl.vars) """ VarList_vector(varcollection; components=false, forceview=false) -> VarList_vector Create a `VarList_vector` describing a collection of `VariableReaction`s, `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))) """ struct VarList_vector <: AbstractVarList vars::Vector{VariableReaction} components::Bool forceview::Bool VarList_vector(varcollection; components=false, forceview=false) = new([copy(v) for v in varcollection], components, forceview) end get_variables(vl::VarList_vector; flatten=true) = vl.vars create_accessors(vl::VarList_vector, modeldata::AbstractModelData, arrays_idx::Int) = [create_accessor(v, modeldata, arrays_idx, vl.components, forceview=vl.forceview) for v in vl.vars] """ VarList_vvector(Vector{Vector{VariableReaction}}::vars; components=false) -> VarList_vvector Create a `VarList_vvector` describing a Vector of Vectors of `VariableReaction`s, `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. """ struct VarList_vvector <: AbstractVarList vars::Vector{Vector{VariableReaction}} components::Bool VarList_vvector(vars; components=false) = new([[copy(v) for v in vv] for vv in vars], components) end get_variables(vl::VarList_vvector; flatten=true) = flatten ? vcat(vl.vars...) : vl.vars create_accessors(vl::VarList_vvector, modeldata::AbstractModelData, arrays_idx::Int) = [[create_accessor(v, modeldata, arrays_idx, vl.components) for v in vv] for vv in vl.vars] """ VarList_nothing() -> VarList_nothing Create a placeholder for a missing/unavailable VariableReaction. `create_accessors` will then return `nothing`. """ struct VarList_nothing <: AbstractVarList end get_variables(vl::VarList_nothing; flatten=true) = VariableReaction[] create_accessors(vl::VarList_nothing, modeldata::AbstractModelData, arrays_idx::Int) = nothing """ VarList_fields(varcollection) -> VarList_fields Create a `VarList_fields` describing a collection of `VariableReaction`s, `create_accessors` will then return a Tuple with unprocessed Fields. """ struct VarList_fields <: AbstractVarList vars::Vector{VariableReaction} VarList_fields(varcollection) = new([copy(v) for v in varcollection]) end get_variables(vl::VarList_fields; flatten=true) = vl.vars function create_accessors(vl::VarList_fields, modeldata::AbstractModelData, arrays_idx::Int) accessors = [] for v in vl.vars isempty(v.linkreq_subdomain) || error("variable $v subdomains not supported") if isnothing(v.linkvar) v.link_optional || error("unlinked variable $v") push!(accessors, nothing) else push!(accessors, get_field(v.linkvar, modeldata, arrays_idx)) end end return Tuple(accessors) end # convert Tuple of VarLists to Tuple of data array views create_accessors(method::AbstractReactionMethod, modeldata::AbstractModelData, arrays_idx::Int) = Tuple(create_accessors(vl, modeldata, arrays_idx) for vl in method.varlists) """ create_accessor(var::VariableReaction, modeldata, arrays_idx, components, [,forceview=false]) -> accessor or (accessor, subdomain_indices) Creates a `view` on a (single) [`VariableDomain`](@ref) data array linked by `var::`[`VariableReaction`](@ref). Called by an [`AbstractVarList`](@ref) [`create_accessors`](@ref) implementation to generate a collection of `views` for multiple [`VariableReaction`](@ref)s. 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 """ function create_accessor( var::VariableReaction, modeldata::AbstractModelData, arrays_idx::Int, components; forceview=false ) errstring = "create_accessor: VariableReaction $(fullname(var)) -> $(isnothing(var.linkvar) ? nothing : fullname(var.linkvar))" @debug errstring if isnothing(var.linkvar) var.link_optional || error("$errstring: unlinked variable") return nothing else linkvar_field = get_field(var.linkvar, modeldata, arrays_idx) # find subdomain (if requested) if !isempty(var.linkreq_subdomain) !isnothing(var.linkvar.domain.grid) || error("$errstring: linkreq_subdomain='$(var.linkreq_subdomain)' but Domain has no grid defined") linksubdomain = Grids.get_subdomain(var.linkvar.domain.grid, var.linkreq_subdomain) !isnothing(linksubdomain) || error("$errstring: linkreq_subdomain='$(var.linkreq_subdomain)' not found") subdomain_indices = Grids.subdomain_indices(linksubdomain) # nothing, unless accessing boundary from interior else linksubdomain = nothing subdomain_indices = nothing end try var_accessor = create_accessor( get_attribute(var, :field_data), # TODO - check space, data_dims, linkvar_field, linksubdomain, forceview=forceview, components=components, ) !isnothing(var_accessor) || error("$errstring: create_accessor returned $nothing") if isnothing(subdomain_indices) return var_accessor # usual case: no subdomain, or accessing interior from boundary as a view else return (var_accessor, subdomain_indices) # accessing boundary from interior end catch ex if isa(ex, MethodError) @warn "$errstring: invalid :field_data combination - attempting to link a Variable "* "with :field_data=$(get_attribute(var, :field_data)) to a Variable with :field_data=$(field_data(linkvar_field))" end rethrow(ex) end end end ################################################################### # Get / set / modify variable data arrays # (optional, provide convenient ways of handling unlinked variables) #################################################################### @Base.propagate_inbounds function add_if_available(vardata, idx, flux) vardata[idx] += flux return nothing end add_if_available(vardata::Nothing, idx, flux) = nothing @Base.propagate_inbounds function add_if_available(vardata, flux) vardata[] += flux return nothing end add_if_available(vardata::Nothing, flux) = nothing @Base.propagate_inbounds function set_if_available(vardata, idx, val) vardata[idx] = val return nothing end set_if_available(vardata::Nothing, idx, val) = nothing @Base.propagate_inbounds function set_if_available(vardata, val) vardata[] = val return nothing end set_if_available(vardata::Nothing, val) = nothing @Base.propagate_inbounds get_if_available(vardata, defaultval) = vardata[] get_if_available(vardata::Nothing, defaultval) = defaultval @Base.propagate_inbounds get_if_available(vardata, idx, defaultval) = vardata[idx] get_if_available(vardata::Nothing, idx, defaultval) = defaultval ########################################################### # Parsing of variable names into domain, subdomain etc ######################################################## "Split a name into component parts. name = domain.subdomain.name " function split_link_name(fullname::AbstractString) splitname = split(fullname, ".") if length(splitname) == 1 (domain, subdomain, name) = ("", "", splitname[1]) elseif length(splitname) == 2 (domain, subdomain, name) = (splitname[1], "", splitname[2]) elseif length(splitname) == 3 (domain, subdomain, name) = (splitname[1], splitname[2], splitname[3]) else error("invalid format $fullname") end return (domain, subdomain, name) end "Combine component parts to form name" function combine_link_name(domain::AbstractString, subdomain::AbstractString, name::AbstractString; sep=".") fullname = name if !isempty(subdomain) fullname = subdomain*sep*fullname end if !isempty(domain) fullname = domain*sep*fullname end return fullname end function combine_link_name(var::VariableReaction) return combine_link_name(var.linkreq_domain, var.linkreq_subdomain, var.linkreq_name) end function sub_variablereaction_linkreq_name(linkreq_name::AbstractString, reactionname::AbstractString) return replace(linkreq_name, "%reaction%" => reactionname) end function strip_brackets(linkstr::AbstractString) if linkstr[1]=='(' && linkstr[end] == ')' hasbrackets = true linkstr_core = linkstr[2:end-1] else hasbrackets = false linkstr_core = linkstr end return (hasbrackets, linkstr_core) end """ 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: ```jldoctest; setup = :(import PALEOboxes) julia> PALEOboxes.parse_variablereaction_namestr("foo") # Common case eg for a property that should be public ("", "", "foo", false) julia> PALEOboxes.parse_variablereaction_namestr("%reaction%foo") # Reaction-private by default ("", "", "%reaction%foo", false) julia> PALEOboxes.parse_variablereaction_namestr("ocean.foo") # Request link to variable of same name in ocean Domain ("ocean", "", "foo", false) julia> PALEOboxes.parse_variablereaction_namestr("(ocean.oceansurface.goo)") # Full syntax ("ocean", "oceansurface", "goo", true) ``` """ function parse_variablereaction_namestr(linkstr::AbstractString) any(occursin.([' ', '>', '<'], linkstr)) && error("invalid character in linkstr='$linkstr'") (link_optional, slink) = strip_brackets(linkstr) (linkreq_domain, linkreq_subdomain, linkreq_name) = split_link_name(slink) return (linkreq_domain, linkreq_subdomain, linkreq_name, link_optional) end ##################################### # Pretty printing ######################################## "fully qualified name (domainname.reactionname.methodname.varname)" function fullname(var::VariableReaction) if isnothing(var.method) return "<no method>."*var.localname else return fullname(var.method)*"."*var.localname end end "link name + link status" function show_link_name(var::VariableReaction) link_name = combine_link_name(var) if isnothing(var.linkvar) link_name = link_name*"[unlinked]" end return link_name end show_links(var::VariableReaction) = show_links(stdout, var) function show_links(io::IO, var::VariableReaction) if isnothing(var.linkvar) println(io, "\t$(typeof(var)) $(fullname(var)) not linked") else println(io, "\t$(typeof(var)) $(fullname(var)) --> $(fullname(var.linkvar))") show_links(var.linkvar) end return nothing end show_links(vars::AbstractVector) = foreach(show_links, vars) "compact form" function Base.show(io::IO, var::VariableReaction) print(io, typeof(var), "(localname='$(var.localname)', link_name='$(show_link_name(var))')") end "multiline form" function Base.show(io::IO, ::MIME"text/plain", var::VariableReaction) println(io, typeof(var)) println(io, " localname='$(var.localname)'") println(io, " link_name='$(show_link_name(var))'") println(io, " attributes=", var.attributes) end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
2456
############################################### # ArrayScalarData ################################################ """ 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. """ struct ArrayScalarData <: AbstractData end function allocate_values( field_data::Type{ArrayScalarData}, data_dims::Tuple{NamedDimension, Vararg{NamedDimension}}, data_type, space::Type{<:AbstractSpace}, spatial_size::Tuple{Integer, Vararg{Integer}}; thread_safe, allocatenans, ) !thread_safe || throw(ArgumentError("ArrayScalarData with thread_safe==true")) s = _size_arrayscalardata(data_dims, space, spatial_size) d = Array{data_type, length(s)}(undef, s...) if allocatenans fill!(d, NaN) end return d end function check_values( existing_values, field_data::Type{ArrayScalarData}, data_dims::Tuple{NamedDimension, Vararg{NamedDimension}}, data_type, space::Type{<:AbstractSpace}, spatial_size::Tuple{Integer, Vararg{Integer}}, ) check_data_type(existing_values, data_type) existing_size = size(existing_values) req_size = _size_arrayscalardata(data_dims, space, spatial_size) existing_size == req_size || throw(ArgumentError("size mismatch: supplied $existing_size, require $req_size")) return nothing end function zero_values!(values, field_data::Type{ArrayScalarData}, data_dims::Tuple{NamedDimension, Vararg{NamedDimension}}, space::Type{ScalarSpace}, cellrange) values .= 0.0 return nothing end function zero_values!(values, field_data::Type{ArrayScalarData}, data_dims::Tuple{NamedDimension, Vararg{NamedDimension}}, space::Type{CellSpace}, cellrange) data_dims_colons = ntuple(i->Colon(), fieldcount(typeof(data_dims))) @inbounds for i in cellrange.indices values[i, data_dims_colons...] .= 0.0 end return nothing end # NB: Tuple{Int, Vararg{Int}} is an NTuple with at least one element function _size_arrayscalardata(data_dims::Tuple{NamedDimension, Vararg{NamedDimension}}, space, spatial_size::Tuple{Integer, Vararg{Integer}}) size_data_dims = Tuple(d.size for d in data_dims) if space === ScalarSpace # Don't include a first dimension length 1 for ScalarSpace return size_data_dims else return (spatial_size..., size_data_dims...) end end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
1116
""" AtomicScalar{T} Provides an implementation of the Julia Array interface for a length 1 Vector that holds an atomic scalar variable. """ mutable struct AtomicScalar{T} <: AbstractArray{T, 1} value::Threads.Atomic{T} function AtomicScalar{T}() where T return new(Threads.Atomic{T}()) end end Base.size(as::AtomicScalar) = (1, ) Base.IndexStyle(::Type{<:AtomicScalar}) = IndexLinear() Base.getindex(as::AtomicScalar) = as.value[] function Base.getindex(as::AtomicScalar, i::Integer) @boundscheck(checkbounds(as, i)) return as.value[] end Base.setindex!(as::AtomicScalar, v) = (as.value[] = v) function Base.setindex!(as::AtomicScalar, v, i::Integer) @boundscheck(checkbounds(as, i)) as.value[] = v return v end """ atomic_add!(as::AtomicScalar, v) atomic_add!(a::Array, v) Add v to as[] using Thread-safe atomic operation, with fallback for normal Julia Arrays. Fallback adds v to a[] using standard addition. """ atomic_add!(as::AtomicScalar, v) = Threads.atomic_add!(as.value, v) @Base.propagate_inbounds atomic_add!(a::AbstractArray, v) = (a[] += v)
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
15626
# import Infiltrator import StructArrays ############################# # AbstractIsotopeScalar ################################ """ 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`](@ref) interface and optional isotope-specific functions, eg for a single isotope: - isotope_totaldelta(::Type{<: IsotopeScalar}, total, delta) -> IsotopeScalar() - get_delta(is::IsotopeScalar) -> delta """ abstract type AbstractIsotopeScalar <: AbstractData end num_components(is::AbstractIsotopeScalar) = num_components(typeof(is)) num_components(iv::AbstractArray) = num_components(eltype(iv)) Base.length(is::AbstractIsotopeScalar) = 1 Base.size(is::AbstractIsotopeScalar) = () """ @isotope_totaldelta(IsotopeType::Type, total, delta) -> Type Convenience macro to create either an `IsotopeXXX` of `IsotopeType::Type`, or a Float64 if `IsotopeType==ScalarData` (in which case `delta` argument is ignored). This generates code equivalent to: IsotopeType == ScalarData ? total : isotope_totaldelta(IsotopeType, total, delta) """ macro isotope_totaldelta(IsotopeType, total, delta) return :($(esc(IsotopeType)) == ScalarData ? $(esc(total)) : isotope_totaldelta($(esc(IsotopeType)), $(esc(total)), $(esc(delta)) ) ) end "generic get_total for non-isotope variable" function get_total(scalar) return scalar end """ get_property(data; propertyname::Union{Symbol, Nothing}=nothing, default_total=false) -> data Generic wrapper for test scripts etc to provide access to field `propertyname` (which can be `nothing`) from struct-valued `data`, or to always apply [`get_total`](@ref). This is intended for use in test scripts etc, where it is useful to have a function that can take arguments to control access either to a property or to the raw `data`. This is not efficient (it allocates), not recommended for use in application code. """ function get_property( data; propertyname::Union{Symbol, Nothing}=nothing, default_total=false ) if !isnothing(propertyname) if eltype(data) <: AbstractVector data = [getproperty.(d, propertyname) for d in data] else data = getproperty.(data, propertyname) end elseif default_total if eltype(data) <: AbstractVector data = [get_total.(d) for d in data] else data = get_total.(data) end end return data end ##################################################### # IsotopeLinear ##################################################### """ IsotopeLinear <: AbstractIsotopeScalar Linearized representation of isotopic composition, where `moldelta` = `total` * `delta`. """ struct IsotopeLinear{T1, T2} <: AbstractIsotopeScalar v::T1 v_moldelta::T2 end function Base.getproperty(obj::IsotopeLinear, sym::Symbol) if sym === :v_delta return get_delta(obj) else # fallback to getfield return getfield(obj, sym) end end function Base.propertynames(obj::IsotopeLinear, private::Bool=false) return (:v, :v_moldelta, :v_delta) end "compact form" function Base.show(io::IO, il::IsotopeLinear) print(io, "(v=", il.v,", v_moldelta=", il.v_moldelta,", ‰=", il.v_delta, ")") end """ isotope_totaldelta(::Type{IsotopeLinear}, total, delta) -> IsotopeLinear Create an `IsotopeLinear` from `total` and `delta` # Examples: ```jldoctest; setup = :(import PALEOboxes as PB) julia> a = PB.isotope_totaldelta(PB.IsotopeLinear, 10.0, -2.0) (v=10.0, v_moldelta=-20.0, ‰=-2.0) julia> b = a*2 (v=20.0, v_moldelta=-40.0, ‰=-2.0) julia> c = a + b (v=30.0, v_moldelta=-60.0, ‰=-2.0) julia> PB.get_total(c) 30.0 julia> PB.get_delta(c) -2.0 ``` """ isotope_totaldelta(::Type{IsotopeLinear}, total, delta) = IsotopeLinear(total, total*delta) isotope_totaldelta(::Type{IsotopeLinear{T, T}}, total::T, delta::T) where {T} = IsotopeLinear(total, total*delta) """ get_total(is::IsotopeLinear) Get isotope total """ function get_total(is::IsotopeLinear) return is.v end """ get_delta(is::IsotopeLinear) Get isotope delta (per mil) """ function get_delta(is::IsotopeLinear, add_eps_denom=0.0) delta = is.v_moldelta / (is.v + add_eps_denom) # (is.v + 1e-3*sign(is.v)*abs(is.v_moldelta)) return delta # min(max(delta, -100.0), 100.0) end function get_delta_limit(is::IsotopeLinear, add_eps_denom, delta_limit) if is.v < add_eps_denom delta = 0.0 else delta = is.v_moldelta / is.v # (is.v + 1e-3*sign(is.v)*abs(is.v_moldelta)) end return min(max(delta, -delta_limit), delta_limit) end Base.zero(x::IsotopeLinear{T1, T2}) where{T1,T2}= zero(typeof(x)) Base.zero(::Type{IsotopeLinear{T1, T2}}) where{T1,T2} = IsotopeLinear(zero(T1), zero(T2)) Base.eltype(::Type{IsotopeLinear{T1, T2}}) where {T1, T2} = IsotopeLinear{T1, T2} Base.:-(a::IsotopeLinear) = IsotopeLinear(-a.v, -a.v_moldelta) Base.:-(a::IsotopeLinear, b::IsotopeLinear) = IsotopeLinear(a.v-b.v, a.v_moldelta-b.v_moldelta) Base.:+(a::IsotopeLinear, b::IsotopeLinear) = IsotopeLinear(a.v+b.v, a.v_moldelta+b.v_moldelta) Base.:*(a::IsotopeLinear, b::Real) = IsotopeLinear(a.v*b, a.v_moldelta*b) Base.:*(a::Real, b::IsotopeLinear) = IsotopeLinear(a*b.v, a*b.v_moldelta) Base.:/(a::IsotopeLinear, b::Real) = IsotopeLinear(a.v/b, a.v_moldelta/b) # convert methods for cases (eg from Float64 to an AD type) where scalar components v, v_moldelta can be converted IsotopeLinear{T1, T2}(x::IsotopeLinear) where {T1, T2} = IsotopeLinear{T1, T2}(x.v, x.v_moldelta) Base.convert(::Type{IsotopeLinear{T1, T2}}, x::IsotopeLinear) where {T1, T2} = IsotopeLinear{T1, T2}(x) """ IsotopeTypes::Tuple Available [`AbstractIsotopeScalar`](@ref) types """ const IsotopeTypes = (ScalarData, IsotopeLinear) """ split_nameisotope( nameisotope::AbstractString, isotope_data::Dict=Dict(); default=UndefinedData, ) -> (name::AbstractString, field_data::AbstractData) Split `nameisotope` string of form <name>[::XIsotope], and look up `field_data` from key `XIsotope` in supplied Dict `isotope_data`. Returns ScalarData if ::XIsotope not present in `nameisotope`, `field_data = default` if `XIsotope` key is not present in `isotope_data`. # Examples ```jldoctest; setup = :(import PALEOboxes as PB) julia> PB.split_nameisotope("myflux::CIsotope", Dict("CIsotope"=>PB.IsotopeLinear)) ("myflux", PALEOboxes.IsotopeLinear) julia> PB.split_nameisotope("myflux::PALEOboxes.IsotopeLinear") ("myflux", PALEOboxes.IsotopeLinear) julia> PB.split_nameisotope("myflux", Dict("CIsotope"=>PB.IsotopeLinear)) ("myflux", PALEOboxes.ScalarData) julia> PB.split_nameisotope("::CIsotope", Dict("CIsotope"=>PB.IsotopeLinear)) ("", PALEOboxes.IsotopeLinear) ``` """ function split_nameisotope( nameisotope::AbstractString, isotope_data::Dict=Dict(); default=UndefinedData ) convertd(v_data::AbstractString) = parse(AbstractData, v_data) convertd(v_data::Type{D}) where {D <: AbstractData} = D convertd(v_data) = error("split_nameisotope: $v_data isotope_data must contain String or <:AbstractData") spfn = split(nameisotope, "::") name = spfn[1] if length(spfn) == 1 field_data = ScalarData elseif length(spfn) == 2 if haskey(isotope_data, spfn[2]) field_data = convertd(isotope_data[spfn[2]]) elseif !isnothing(tryparse(AbstractData, spfn[2])) field_data = parse(AbstractData, spfn[2]) elseif default != UndefinedData field_data = default else error("flux '$nameisotope' isotope not defined, isotope_data=$isotope_data") end else error("invalid flux '$nameisotope'") end return (name, field_data) end ##################################################### # IsotopeLinear AbstractData implementation ##################################################### function allocate_values( data::Type{IsotopeLinear}, data_dims::Tuple{}, data_type, space::Type{<:AbstractSpace}, spatial_size::Tuple{Integer, Vararg{Integer}}; thread_safe, allocatenans, ) v = allocate_values(ScalarData, data_dims, data_type, space, spatial_size, thread_safe=thread_safe, allocatenans=allocatenans) v_moldelta = allocate_values(ScalarData, data_dims, data_type, space, spatial_size, thread_safe=thread_safe, allocatenans=allocatenans) return StructArrays.StructArray{IsotopeLinear{data_type, data_type}}((v, v_moldelta)) end function check_values( existing_values, field_data::Type{IsotopeLinear}, data_dims::Tuple{}, data_type, space::Type{<:AbstractSpace}, spatial_size::Tuple{Integer, Vararg{Integer}} ) eltype(existing_values) <: IsotopeLinear || throw(ArgumentError("type mismatch: supplied eltype $(eltype(existing_values))")) check_data_type(existing_values, data_type) existing_size = size(existing_values) existing_size == spatial_size || throw(ArgumentError("size mismatch: supplied $existing_size, require spatial_size=$spatial_size")) return nothing end function init_values!( values, data::Type{IsotopeLinear}, data_dims::Tuple{}, space::Type{S}, init_value::Symbol, attribv::VariableBase, convertfn, convertvalues, cellrange, info::NTuple{3, String} ) where {S <: Union{ScalarSpace, CellSpace}} varinfo, convertinfo, trsfrinfo = info initial_value = get_attribute(attribv, init_value) if init_value == :norm_value initial_delta = 1.0 @info "init_values! :$(rpad(init_value, 20)) $(rpad(varinfo, 30)) "* "= $initial_value$convertinfo, delta=$initial_delta (fixed delta value to calculate norm)$trsfrinfo" else initial_delta = get_attribute(attribv, :initial_delta) @info "init_values! :$(rpad(init_value, 20)) $(rpad(varinfo, 30)) "* "= $initial_value$convertinfo, delta=$initial_delta$trsfrinfo" end # . as initial_value may be a Vector i_initial_value = isotope_totaldelta.(IsotopeLinear, initial_value, initial_delta) if S === ScalarSpace values[] = i_initial_value*convertfn(convertvalues, nothing) else if initial_value isa Real # ie not a Vector for i in cellrange.indices values[i] = i_initial_value*convertfn(convertvalues, i) end elseif length(initial_value) == length(values) for i in cellrange.indices values[i] = i_initial_value[i]*convertfn(convertvalues, i) end else error("init_values!: configuration error, Vector Variable $varinfo and Vector :initial_value lengths mismatch ($(length(values)) != $(length(initial_value)))") end end return nothing end function zero_values!(values, data::Type{IsotopeLinear}, data_dims::Tuple{}, space::Type{ScalarSpace}, cellrange) values[] = zero(eltype(values)) return nothing end function zero_values!(values, data::Type{IsotopeLinear}, data_dims::Tuple{}, space::Type{CellSpace}, cellrange) @inbounds for i in cellrange.indices values[i] = zero(eltype(values)) end return nothing end dof_values(data::Type{IsotopeLinear}, data_dims::Tuple{}, space::Type{ScalarSpace}, mesh, cellrange) = 2 dof_values(data::Type{IsotopeLinear}, data_dims::Tuple{}, space::Type{CellSpace}, mesh, cellrange) = 2*length(cellrange.indices) dof_values(data::Type{IsotopeLinear}, data_dims::Tuple{}, space::Type{CellSpace}, mesh, cellrange::Nothing) = 2*mesh.ncells function copyfieldto!(dest, doff, values, field_data::Type{IsotopeLinear}, data_dims::Tuple{}, space::Type{<:AbstractSpace}, cellrange) n1 = copyfieldto!(dest, doff, values.v, ScalarData, data_dims, space, cellrange) n2 = copyfieldto!(dest, doff+n1, values.v_moldelta, ScalarData, data_dims, space, cellrange) return n1 + n2 end function copytofield!(values, field_data::Type{IsotopeLinear}, data_dims::Tuple{}, space::Type{<:AbstractSpace}, cellrange, src, soff) n1 = copytofield!(values.v, ScalarData, data_dims, space, cellrange, src, soff) n2 = copytofield!(values.v_moldelta, ScalarData, data_dims, space, cellrange, src, soff+n1) return n1 + n2 end add_field!(dest, field_data::Type{IsotopeLinear}, data_dims::Tuple{}, space::Type{<:AbstractSpace}, a, cellrange, src) = add_field!(dest, ScalarData, data_dims::Tuple{}, space, a, cellrange, src) function add_field_vec!(dest, field_data::Type{IsotopeLinear}, data_dims::Tuple{}, space::Type{ScalarSpace}, a, cellrange, src, soff) dest[].v += a*IsotopeLinear(src[soff], src[soff+1]) return 2 end function add_field_vec!(dest, field_data::Type{IsotopeLinear}, data_dims::Tuple{}, space::Type{CellSpace}, a, cellrange, src, soff) # assume src layout matches that of copytofield! @inbounds for i in cellrange.indices dest[i] += a*IsotopeLinear(src[soff], src[soff+length(cellrange.indices)]) soff += 1 end return 2*length(cellrange.indices) end add_field_vec!(dest, field_data::Type{IsotopeLinear}, data_dims::Tuple{}, space::Type{CellSpace}, cellrange::Nothing, src, soff) = add_field_vec!(dest, field_data, data_dims, space, a, (indices=1:length(dest),), src, soff) num_components(field_data::Type{IsotopeLinear}) = 2 num_components(field_data::Type{IsotopeLinear{T1, T2}}) where {T1,T2} = num_components(IsotopeLinear) get_components(values, data::Type{IsotopeLinear}) = [values.v, values.v_moldelta] # provide a create_accessor method for ScalarData --> IsotopeLinear that takes just the first (total) component function create_accessor( output_data::Type{ScalarData}, # TODO - check space, data_dims, linkvar_field::Field{IsotopeLinear, S, V, W, M}, linksubdomain::Union{Nothing, AbstractSubdomain}; forceview, components, ) where {S, V, W, M} # create accessor if isnothing(linksubdomain) if forceview var_accessor = view(linkvar_field.values.v, 1:length(linkvar_field.values.v)) else var_accessor = linkvar_field.values.v end else var_accessor = Grids.subdomain_view(linkvar_field.values.v, linksubdomain) end if components return [var_accessor] else return var_accessor end end ############################################################# # Special cases for atomic scalar Vectors of IsotopeLinear ########################################################## "type of an atomic scalar Vector of IsotopeLinear" const AtomicIsotopeLinear = StructArrays.StructVector{ IsotopeLinear{Float64, Float64}, NamedTuple{(:v, :v_moldelta), Tuple{AtomicScalar{Float64}, AtomicScalar{Float64}}}, Int64 } atomic_add!(ias::AtomicIsotopeLinear, iv::IsotopeLinear) = (atomic_add!(ias.v, iv.v); atomic_add!(ias.v_moldelta, iv.v_moldelta)) function get_values_output(values::AtomicIsotopeLinear, data_type::Type{IsotopeLinear}, data_dims::Tuple{}, space::Type{<:AbstractSpace}, mesh) # convert to an IsotopeLinear for output return StructArrays.StructArray( [values[]]) end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
6006
################################################################ # ScalarData ################################################################# """ ScalarData <: AbstractData A Field scalar (eg a biogeochemical concentration) """ struct ScalarData <: AbstractData end num_components(field_data::Type{ScalarData}) = 1 get_components(values, field_data::Type{ScalarData}) = [values] function allocate_values( field_data::Type{ScalarData}, data_dims::Tuple{}, data_type, space::Type{<:AbstractSpace}, spatial_size::Tuple{Integer, Vararg{Integer}}; thread_safe, allocatenans, ) if thread_safe spatial_size == (1, ) || throw(ArgumentError("thread_safe with spatial_size != (1, )")) d = AtomicScalar{data_type}() else d = Array{data_type, length(spatial_size)}(undef, spatial_size...) end if allocatenans fill!(d, NaN) end return d end function get_values_output(values::AtomicScalar, data_type::Type{ScalarData}, data_dims::Tuple{}, space, mesh) return [values[]] end function check_values( existing_values, field_data::Type{ScalarData}, data_dims::Tuple{}, data_type, space::Type{<:AbstractSpace}, spatial_size::Tuple{Integer, Vararg{Integer}} ) check_data_type(existing_values, data_type) existing_size = size(existing_values) existing_size == spatial_size || throw(ArgumentError("size mismatch: supplied $existing_size, require spatial_size=$spatial_size")) return nothing end function init_values!( values, field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{S}, init_value::Symbol, attribv::VariableBase, convertfn, convertvalues, cellrange, info::NTuple{3, String} ) where {S <: Union{ScalarSpace, CellSpace}} varinfo, convertinfo, trsfrinfo = info initial_value = get_attribute(attribv, init_value) @info "init_values! :$(rpad(init_value, 20)) $(rpad(varinfo, 30)) "* "= $initial_value$convertinfo$trsfrinfo" if S === ScalarSpace values[] = initial_value*convertfn(convertvalues, nothing) else if initial_value isa Real # ie not a Vector for i in cellrange.indices values[i] = initial_value*convertfn(convertvalues, i) end elseif length(initial_value) == length(values) for i in cellrange.indices values[i] = initial_value[i]*convertfn(convertvalues, i) end else error("init_values!: configuration error, Vector Variable $varinfo and Vector :initial_value lengths mismatch ($(length(values)) != $(length(initial_value)))") end end return nothing end function zero_values!(values, field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{ScalarSpace}, cellrange) values[] = 0.0 return nothing end function zero_values!(values, field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{CellSpace}, cellrange) @inbounds for i in cellrange.indices values[i] = 0.0 end return nothing end dof_values(field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{ScalarSpace}, mesh, cellrange) = 1 dof_values(field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{CellSpace}, mesh, cellrange) = length(cellrange.indices) dof_values(field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{CellSpace}, mesh, cellrange::Nothing) = mesh.ncells function copyfieldto!(dest, doff, values, field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{ScalarSpace}, cellrange) dest[doff] = values[] return 1 end function copyfieldto!(dest, doff, values, field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{CellSpace}, cellrange) @inbounds for i in cellrange.indices dest[doff] = values[i] doff += 1 end return length(cellrange.indices) end function copyfieldto!(dest, doff, values, field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{CellSpace}, cellrange::Nothing) @inbounds copyto!(dest, doff, values, 1, length(values)) return length(values) end function copytofield!(values, field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{ScalarSpace}, cellrange, src, soff) values[] = src[soff] return 1 end function copytofield!(values, field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{CellSpace}, cellrange, src, soff) @inbounds for i in cellrange.indices values[i] = src[soff] soff += 1 end return length(cellrange.indices) end function copytofield!(values, field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{CellSpace}, cellrange::Nothing, src, soff) @inbounds copyto!(values, 1, src, soff, length(values)) return length(values) end function add_field!(dest, field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{ScalarSpace}, a, cellrange, src) dest[] += a*src[] return nothing end function add_field!(dest, field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{CellSpace}, a, cellrange, src) @inbounds for i in cellrange.indices dest[i] += a*src[i] end return nothing end function add_field!(dest, field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{CellSpace}, a, cellrange::Nothing, src) dest .+= a .* src return nothing end function add_field_vec!(dest, field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{ScalarSpace}, a, cellrange, src, soff) dest[] += a*src[soff] return 1 end function add_field_vec!(dest, field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{CellSpace}, a, cellrange, src, soff) @inbounds for i in cellrange.indices dest[i] += a*src[soff] soff += 1 end return length(cellrange.indices) end add_field_vec!(dest, field_data::Type{ScalarData}, data_dims::Tuple{}, space::Type{CellSpace}, cellrange::Nothing, src, soff) = add_field_vec!(dest, field_data, data_dims, space, a, (indices=1:length(dest),), src, soff)
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
1371
module Constants # Physical constants const k_CtoK = 273.15 # convert temperature in Celsius to Kelvin const k_molVolIdealGas= 22.4136 # l/mol molar volume of ideal gas at STP (0C, 1 atm) const k_Rgas = 8.3144621 # J/K/mol gas constant const k_Avogadro = 6.0221409e23 # molecules mol-1 # Earth system present-day constants const age_present_yr = 4.5e9 # Age of Earth at present-day const k_solar_presentday = 1368.0 # present-day solar insolation W/m^2 const k_secpyr = 3.15569e7 # present-day seconds per year const k_secpday = 24.0*3600.0 # sec per day const k_daypyr = k_secpyr/k_secpday # days in a year const k_g_earth = 9.80665 # gravitational field strength for Earth m/s^2 const k_SurfAreaEarth = 5.101e14 # Earth surface area in m const pCO2atm0 = 280e-6 # ppm pre-industrial pCO2 const k16_PANtoO = 3.762 # const k18_oceanmass = 1.397e21 # kg Ocean total mass const k_moles1atm = 1.77e20 # Moles in 1 atm const k_preindCO2atm = 280e-6 # pre-industrial pCO2 (atm) # Atmospheric composition from Sarmiento & Gruber (2006) Table 3.1.1 (which cites Weast & Astle 1982) const k_atmmixrN2 = 0.78084 # N2 atmospheric mixing ratio (moles / moles dry air) const k_atmmixrO2 = 0.20946 # O2 atmospheric mixing ratio (moles / moles dry air) end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
7242
module FluxPerturb import PALEOboxes as PB using ..DocStrings """ 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 $(PARS) # Methods and Variables $(METHODS_DO) """ Base.@kwdef mutable struct ReactionFluxPerturb{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParType(PB.AbstractData, "field_data", PB.ScalarData, allowed_values=PB.IsotopeTypes, description="disable / enable isotopes and specify isotope type"), PB.ParDoubleVec("perturb_times", [-1e30, 1e30], units="yr", description="interpolated perturbation times"), PB.ParDoubleVec("perturb_totals",[1.0, 1.0], units="mol yr-1", description="interpolated perturbation totals"), PB.ParDoubleVec("perturb_deltas",[0.0, 0.0], units="per mil", description="interpolated perturbation deltas"), PB.ParString("extrapolate", "throw", allowed_values=["throw", "constant"], description="behaviour if tforce is out of range"), PB.ParDouble("extrapolate_before", NaN, description="value to use if 'extrapolate=constant' and tforce < first(perturb_times)"), PB.ParDouble("extrapolate_before_delta", NaN, description="value to use if 'extrapolate=constant' and tforce < first(perturb_times)"), PB.ParDouble("extrapolate_after", NaN, description="value to use if 'extrapolate=constant' and tforce > last(perturb_times)"), PB.ParDouble("extrapolate_after_delta", NaN, description="value to use if 'extrapolate=constant' and tforce > last(perturb_times)"), ) end function PB.register_methods!(rj::ReactionFluxPerturb) @info "ReactionFluxPerturb.register_methods! $(PB.fullname(rj))" IsotopeType = rj.pars.field_data[] PB.setfrozen!(rj.pars.field_data) vars = [ PB.VarDepScalar( "global.tforce", "yr", "time at which to apply perturbation"), PB.VarContribScalar( "F", "mol yr-1", "interpolated flux perturbation", attributes=(:field_data=>IsotopeType,)), PB.VarPropScalar( "%reaction%FApplied", "mol yr-1", "flux perturbation applied, for diagnostic output", attributes=(:field_data=>IsotopeType,)), ] PB.add_method_do!( rj, do_flux_perturb, (PB.VarList_namedtuple(vars), ), p=IsotopeType, ) return nothing end function do_flux_perturb( m::PB.ReactionMethod, pars, (vars, ), cellrange::PB.AbstractCellRange, deltat ) IsotopeType = m.p tforce = vars.tforce[] f = zero(first(pars.perturb_totals.v)*vars.tforce[]) # ensure zero is of correct type for perturb_totals, tforce f_delta = zero(first(pars.perturb_deltas.v)*vars.tforce[]) idx_after = searchsortedfirst(pars.perturb_times.v, tforce) if tforce == first(pars.perturb_times.v) # extra check as searchsortedfirst uses >= idx_after += 1 end if idx_after == 1 (pars.extrapolate[] == "constant") || error("tforce $tforce out-of-range, < first(perturb_times) = $(first(pars.perturb_times.v))") f += pars.extrapolate_before[] f_delta += pars.extrapolate_before_delta[] elseif idx_after > length(pars.perturb_times.v) (pars.extrapolate[] == "constant") || error("tforce $tforce out-of-range, > last(perturb_times) = $(last(pars.perturb_times.v))") f += pars.extrapolate_after[] f_delta += pars.extrapolate_after_delta[] else # linearly interpolate t_l, t_h = pars.perturb_times.v[idx_after-1], pars.perturb_times.v[idx_after] x_l = (t_h-tforce)/(t_h - t_l) x_h = (tforce-t_l)/(t_h - t_l) f += x_l*pars.perturb_totals.v[idx_after-1] + x_h*pars.perturb_totals.v[idx_after] f_delta += x_l*pars.perturb_deltas.v[idx_after-1] + x_h*pars.perturb_deltas.v[idx_after] end F = @PB.isotope_totaldelta(IsotopeType, f, f_delta) vars.F[] += F vars.FApplied[] = F return nothing end """ ReactionRestore Adds `RestoringFlux` in response to discrepancy between Variable `WatchLevel` and Parameter `RequiredLevel` # Parameters $(PARS) # Methods and Variables $(METHODS_DO) """ Base.@kwdef mutable struct ReactionRestore{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParType(PB.AbstractData, "field_data", PB.ScalarData, allowed_values=PB.IsotopeTypes, description="disable / enable isotopes and specify isotope type"), PB.ParDouble("RequiredLevel", 0.0, units="mol", description="target value of WatchLevel"), PB.ParDouble("trestore", 1.0, units="yr", description="restoring timescale"), PB.ParDouble("RequiredDelta", 0.0, units="per mil", description="target value of WatchLevel delta"), PB.ParBool("source_only", false, description="false to allow input and output, true to allow input only"), ) end function PB.register_methods!(rj::ReactionRestore) PB.setfrozen!(rj.pars.field_data) IsotopeType = rj.pars.field_data[] vars = [ PB.VarDepScalar( "WatchLevel", "mol", "level to observe and restore", attributes=(:field_data=>IsotopeType,)), PB.VarContribScalar("RestoringFlux", "mol yr-1", "restoring flux", attributes=(:field_data=>IsotopeType,)), PB.VarPropScalar( "%reaction%RestoringApplied", "mol yr-1", "restoring flux for diagnostic output", attributes=(:field_data=>IsotopeType,)), ] PB.add_method_do!( rj, do_restore, (PB.VarList_namedtuple(vars), ), p=IsotopeType, ) return nothing end function do_restore(m::PB.ReactionMethod, (vars, ), cellrange::PB.AbstractCellRange, deltat) rj = m.reaction IsotopeType = m.p requiredlevelisotope = @PB.isotope_totaldelta(IsotopeType, rj.pars.RequiredLevel[], rj.pars.RequiredDelta[]) restoreflux = -(vars.WatchLevel[] - requiredlevelisotope)/rj.pars.trestore[] if !rj.pars.source_only[] || PB.get_total(restoreflux) > 0 vars.RestoringApplied[] = restoreflux vars.RestoringFlux[] += restoreflux else vars.RestoringApplied[] = 0.0*restoreflux vars.RestoringFlux[] += 0.0*restoreflux # multiply by zero so AD sparsity detection sees the restoring term end return nothing end end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
21277
""" 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`](@ref). Fluxes are then transferred (copied) by adding a [`Fluxes.ReactionFluxTransfer`](@ref) to each destination Domain. Naming conventions for Earth system fluxes: |Domain name | target prefix | flux_list (illustrative, add as needed) | |:----------------------|:---------------|:--------------------| |fluxAtoLand | flux_ | ["CO2::CIsotope", "O2"] | |fluxRtoOcean | flux_ | ["DIC::CIsotope", "TAlk", "Ca", "P", "SO4::SIsotope"]| |fluxOceanBurial | flux_ | ["Corg::CIsotope", "Ccarb::CIsotope", "Porg", "Pauth", "PFe", "P", "GYP::SIsotope", "PYR::SIsotope"]| |fluxSedCrusttoAOcean | flux_ | ["C::CIsotope", "S::SIsotope", "Redox"]| |fluxLandtoSedCrust | flux_ |["Ccarb::CIsotope", "Corg::CIsotope", "GYP::SIsotope", "PYR::SIsotope"]| |fluxOceanfloor | particulateflux_|["P", "N", "Corg::CIsotope", "Ccarb::CIsotope"] | | | soluteflux_ | ["DIC::CIsotope", "TAlk", "Ca", "P", "O2", "SO4::SIsotope", "H2S::SIsotope", "CH4::CIsotope"] | |fluxAtmtoOceansurface | flux_ | ["CO2::CIsotope", "CH4::CIsotope", "O2"] | """ module Fluxes import PALEOboxes as PB import SparseArrays import LinearAlgebra # for I import Infiltrator # Julia debugger using ..DocStrings """ FluxContrib( fluxprefix::AbstractString, flux_list; [, isotope_data::Dict] [, space=PB.CellSpace][, alloptional=true] ) -> vartuple::NamedTuple Create a `NamedTuple` of `VarContrib` from `flux_prefix.*flux_list`, needed for a Reaction to write to a flux coupler. Entries in `flux_list` of form `fluxname::isotope` are parsed to look up isotope type from `isotope_data` Dict. For each `fluxname` in `flux_list`, the generated `VarContrib` `vartuple.fluxname` have `link_namestr=\$(fluxprefix)\$(fluxname)"` and `localname="\$(fluxprefix)\$(fluxname)` (with any `.` in `fluxprefix` substituted to `_`). # Example: ```julia julia> fluxRtoOcean = PB.Fluxes.FluxContrib("fluxRtoOcean.flux_", ["P", "SO4::SIsotope"], isotope_data=Dict("SIsotope"=>PB.IsotopeLinear), space=PB.ScalarSpace); julia> fluxRtoOcean.P PALEOboxes.VariableReaction{PALEOboxes.VT_ReactContributor} localname='fluxRtoOcean_flux_P' link_name='fluxRtoOcean.flux_P[unlinked]' attributes=Dict{Symbol, Any}(:description => "flux P", :space => PALEOboxes.ScalarSpace, :standard_variable => false, :norm_value => 1.0, :data_dims => String[], :long_name => "", :vfunction => PALEOboxes.VF_Undefined, :field_data => PALEOboxes.ScalarData, :initial_delta => 0.0, :units => "mol yr-1"…) julia> fluxRtoOcean.SO4 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"…) ``` """ FluxContrib(fluxprefix::AbstractString, flux_list; alloptional=true, kwargs...) = _FluxVars(PB.VarContrib, fluxprefix, flux_list; alloptional=alloptional, kwargs...) FluxContribScalar(fluxprefix::AbstractString, flux_list; kwargs...) = _FluxVars(PB.VarContrib, fluxprefix, flux_list; space=PB.ScalarSpace, kwargs...) """ FluxTarget(fluxprefix::AbstractString, flux_list; [, isotope_data::Dict=Dict()] [, space=PB.CellSpace] ) -> vartuple::NamedTuple Create a `NamedTuple` of `VarTarget` from `flux_list`, needed for a Reaction to define a flux coupler. See [`FluxContrib`](@ref) for arguments. """ FluxTarget(fluxprefix::AbstractString, flux_list; kwargs...) = _FluxVars(PB.VarTarget, fluxprefix, flux_list; kwargs...) FluxTargetScalar(fluxprefix::AbstractString, flux_list; kwargs...) = _FluxVars(PB.VarTarget, fluxprefix, flux_list; space=PB.ScalarSpace, kwargs...) "Create a NamedTuple of Variables using `varctorfn`" function _FluxVars( varctorfn, fluxprefix::AbstractString, flux_list; isotope_data::Dict=Dict(), localname_prefix=nothing, alloptional=false, description="flux", space=PB.CellSpace, ) (fluxdomain, fluxsubdomain, fluxnameprefix) = PB.split_link_name(fluxprefix) if isnothing(localname_prefix) localname_prefix = PB.combine_link_name(fluxdomain, fluxsubdomain, fluxnameprefix, sep="_") end field_names = [] variables = [] for fluxnameisotopestr in flux_list optional, fluxnameisotope = PB.strip_brackets(fluxnameisotopestr) fluxname, IsotopeType = PB.split_nameisotope(fluxnameisotope, isotope_data) push!(field_names, Symbol(fluxname)) attributes = (:space=>space, :field_data=>IsotopeType) localname = localname_prefix*fluxname link_namestr = PB.combine_link_name(fluxdomain, fluxsubdomain, fluxnameprefix*fluxname) if alloptional || optional link_namestr = "("*link_namestr*")" end push!( variables, varctorfn( localname=>link_namestr, "mol yr-1", "$description $fluxname", attributes=attributes ) ) end return NamedTuple{Tuple(field_names)}(variables) end """ 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 $(PARS) # Methods and Variables for default Parameters $(METHODS_DO) """ Base.@kwdef mutable struct ReactionFluxTarget{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParStringVec("fluxlist", ["example"], description="available fluxes"), PB.ParString("target_prefix", "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)"), PB.ParBool("flux_totals", false, description="true to calculate flux totals (as \"<target_prefix>flux_total_<fluxname>\")"), PB.ParBool("const_stub", false, description="true to provide constant flux defined by :initial_value, :initial_delta attributes "* "on input Target Variables \"<target_prefix>flux_<fluxname>\""), ) end function PB.register_methods!(rj::ReactionFluxTarget) # Add flux targets and transfers target_variables = [] total_localnames = [] target_prefix = rj.pars.target_prefix[] if !isempty(target_prefix) && target_prefix[end] != '_' target_prefix = target_prefix*"_" @warn "Reaction $(PB.fullname(rj)) bodging target_prefix without trailing underscore $(rj.pars.target_prefix[]) -> $target_prefix" end for fluxnameisotope in rj.pars.fluxlist fluxname, IsotopeType = PB.split_nameisotope(fluxnameisotope, rj.external_parameters) targetname = target_prefix*fluxname if rj.pars.const_stub[] target_var = PB.VarPropStateIndep(targetname, "mol yr-1", "constant flux", attributes=(:field_data=>IsotopeType,)) else target_var = PB.VarTarget(targetname, "mol yr-1", "flux input", attributes=(:field_data=>IsotopeType,)) end if rj.pars.flux_totals[] PB.set_attribute!(target_var, :calc_total, true, allow_create=true) end push!(target_variables, target_var) push!(total_localnames, target_prefix*"total_"*fluxname) end if rj.pars.const_stub[] # method to set constant value # supply filterfn to initialize supplied Variables even though they aren't state variables PB.add_method_setup_initialvalue_vars_default!(rj, target_variables, filterfn = v->true) else # target_variables not used by us, but must appear in a method to be linked and created PB.add_method_do_nothing!(rj, target_variables) end if rj.pars.flux_totals[] totals_method = PB.create_totals_method(rj, target_variables, total_localnames=total_localnames) PB.add_method_do!(rj, totals_method) end PB.add_method_initialize_zero_vars_default!(rj) return nothing end """ 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 $(PARS) """ Base.@kwdef mutable struct ReactionFluxTransfer{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParString("input_fluxes", "[inputdomain.][inputsubdomain.]flux_\$fluxname\$", description="string to match to find input flux Variables. "* "These Variables will local names \"input_\$fluxname\$\"."), PB.ParString("output_fluxes", "[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)."), PB.ParDouble("transfer_multiplier", 1.0, description="scalar multiplier for transfer"), PB.ParString("transfer_matrix", "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"), ) input_domain = nothing transfer_matrix_tr::SparseArrays.SparseMatrixCSC{Float64, Int64} = SparseArrays.spzeros(0, 0) end PB.register_methods!(rj::ReactionFluxTransfer) = nothing function PB.register_dynamic_methods!(rj::ReactionFluxTransfer, model::PB.Model) (input_domain_name, input_subdomain_name, input_var_matchname) = PB.split_link_name(rj.pars.input_fluxes[]) # get Domain for input fluxes rj.input_domain = isempty(input_domain_name) ? rj.domain : PB.get_domain(model, input_domain_name) !isnothing(rj.input_domain) || error("$(PB.fullname(rj)) no Domain $input_domain_name") input_var_matchname_split = split(input_var_matchname, "\$fluxname\$") length(input_var_matchname_split) == 2 || error("$(PB.fullname(rj)) invalid input_fluxes: must contain \$fluxname\$ $(rj.pars.input_fluxes[])") # Regular expression so $fluxname$ matches any alphanumeric characters input_var_regex = input_var_matchname_split[1]*r"(\p{Xan}+)"*input_var_matchname_split[2] (output_domain_name, output_subdomain_name, output_var_patternname) = PB.split_link_name(rj.pars.output_fluxes[]) occursin("\$fluxname\$", output_var_patternname) || error("$(PB.fullname(rj)) invalid output_fluxes: must contain \$fluxname\$ $(rj.pars.output_fluxes[])") flux_names, var_inputs, var_outputs = [], [], [] @debug "register_dynamic_methods! $(PB.fullname(rj)):" for input_var in PB.get_variables(rj.input_domain) m = match(input_var_regex, input_var.name) # bodge in additional check as regex seems wrong when $fluxname is at end of string, # "prefix_$fluxname" apparently will also match "prefix_$fluxname_otherstuff" if !isnothing(m) && (input_var.name == input_var_matchname_split[1]*m.captures[1]*input_var_matchname_split[2]) fluxname = m.captures[1] push!(flux_names, fluxname) input_namestr = PB.combine_link_name( input_domain_name, input_subdomain_name, input_var.name ) input_attrb = Tuple(atnm=>PB.get_attribute(input_var, atnm) for atnm in (:field_data, :data_dims, :space)) v_input = PB.VarDep("input_"*fluxname => input_namestr, "mol yr-1", "flux input", attributes=input_attrb, ) if rj.pars.transfer_matrix[] != "Identity" PB.set_attribute!(v_input, :check_length, false; allow_create=true) end push!(var_inputs, v_input) output_namestr = "("*PB.combine_link_name( output_domain_name, output_subdomain_name, replace(output_var_patternname, "\$fluxname\$" => fluxname) )*")" v_output = PB.VarContrib("output_"*fluxname => output_namestr, "mol yr-1", "flux output", attributes=input_attrb, ) push!(var_outputs, v_output) else @debug " ignoring $(PB.fullname(input_var))" end end PB.add_method_do!( rj, do_transfer, (PB.VarList_components(var_inputs), PB.VarList_components(var_outputs, allow_unlinked=true)), p = flux_names, preparefn = prepare_do_transfer ) return nothing end "remove unlinked Variables and create transfer_matrix" function prepare_do_transfer(m::PB.ReactionMethod, (input_vardata, output_vardata)) io = IOBuffer() println(io, "prepare_do_transfer: ReactionMethod $(PB.fullname(m))") # write diagnostic output println(io, " active fluxes:") var_inputs, var_outputs = PB.get_variables_tuple(m) flux_names = m.p nactive = 0 for (var_input, var_output, fluxname) in PB.IteratorUtils.zipstrict(var_inputs, var_outputs, flux_names) if isnothing(var_output.linkvar) println(io, " $(rpad(fluxname, 20)) $(rpad(PB.fullname(var_input.linkvar),40)) output not linked") else println(io, " $(rpad(fluxname, 20)) $(rpad(PB.fullname(var_input.linkvar),40)) -> $(PB.fullname(var_output.linkvar))") nactive += 1 end end # check we have the same number of components length(input_vardata) == length(output_vardata) || PB.infoerror(io, "prepare_do_transfer: ReactionMethod $(PB.fullname(m)) number of input components != number of output components - check :field_data (ScalarData, IsotopeLinear etc) match") # remove unlinked Variables input_vardata_active = [] output_vardata_active = [] for (ainput, aoutput) in PB.IteratorUtils.zipstrict(input_vardata, output_vardata) if !isnothing(aoutput) push!(input_vardata_active, ainput) push!(output_vardata_active, aoutput) end end if !isempty(input_vardata_active) # figure out length of input and output arrays input_length = 0 output_length = 0 for (ainput, aoutput) in PB.IteratorUtils.zipstrict(input_vardata_active, output_vardata_active) if iszero(input_length) input_length = prod(size(ainput))::Int end input_length == prod(size(ainput)) || PB.infoerror(io, "$(PB.fullname(m)) input Variables are not all the same size") if iszero(output_length) output_length = prod(size(aoutput))::Int end output_length == prod(size(aoutput)) || PB.infoerror(io, "$(PB.fullname(m)) output Variables are not all the same size") end # define transpose of transfer matrix (for sparse CSR efficiency, so output = input * transfer_matrix_tr) rj = m.reaction if rj.pars.transfer_matrix[] == "Custom" # will be supplied (not yet implemented) PB.infoerror(io, "$(PB.fullname(m)) not implemented Custom transfer matrix * $(rj.pars.transfer_multiplier[])") elseif rj.pars.transfer_matrix[] == "Identity" input_length == output_length || PB.infoerror(io, "$(PB.fullname(m)) Identity transfer_matrix but Variable lengths don't match (input, output) $(input_length) != $(output_length)") rj.transfer_matrix_tr = SparseArrays.sparse(LinearAlgebra.I, input_length, output_length).*rj.pars.transfer_multiplier[] println(io, " using Identity transfer matrix * $(rj.pars.transfer_multiplier[])") elseif rj.pars.transfer_matrix[] == "Distribute" rj.transfer_matrix_tr = SparseArrays.sparse(ones(input_length, output_length)./output_length.*rj.pars.transfer_multiplier[]) println(io, " using Distribute transfer matrix size (input, output) $(size(rj.transfer_matrix_tr)) * $(rj.pars.transfer_multiplier[])") else PB.infoerror(io, "$(PB.fullname(m)) unknown transfer_matrix='$(rj.pars.transfer_matrix[])'") end @info String(take!(io)) else @info String(take!(io)) @warn "ReactionMethod $(PB.fullname(m)) no active fluxes found" end rt = ([v for v in input_vardata_active], [v for v in output_vardata_active]) # narrow Types of Vectors return rt end function do_transfer( m::PB.ReactionMethod, (input_vardata, output_vardata), cellrange::PB.AbstractCellRange, deltat ) tm_tr = m.reaction.transfer_matrix_tr # _transfer(acinput::Nothing, acoutput::Nothing, tm_tr, cr) = nothing function _transfer(acinput, acoutput, tm_tr, cr) if length(acoutput) == 1 # Scalar Variables, (we have already checked size(tm_tr, 2) == 1) for idx in SparseArrays.nzrange(tm_tr, 1) i = tm_tr.rowval[idx] acoutput[1] += acinput[i]*tm_tr.nzval[idx] end else for j in cr.indices for idx in SparseArrays.nzrange(tm_tr, j) i = tm_tr.rowval[idx] acoutput[j] += acinput[i]*tm_tr.nzval[idx] end end end return nothing end for (acinput, acoutput) in PB.IteratorUtils.zipstrict(input_vardata, output_vardata) _transfer(acinput, acoutput, tm_tr, cellrange) end return nothing end end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
3170
module Forcings import PALEOboxes as PB using ..DocStrings """ 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 $(PARS) # Methods and Variables $(METHODS_DO) """ Base.@kwdef mutable struct ReactionForceInterp{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParDoubleVec("force_times", [-1e30, 1e30], units="yr", description="interpolated forcing times"), PB.ParDoubleVec("force_values", [1.0, 1.0], units="", description="interpolated forcing values"), PB.ParString("extrapolate", "throw", allowed_values=["throw", "constant"], description="behaviour if tforce is out of range"), PB.ParDouble("extrapolate_before", NaN, description="value to use if 'extrapolate=constant' and tforce < first(perturb_times)"), PB.ParDouble("extrapolate_after", NaN, description="value to use if 'extrapolate=constant' and tforce > last(perturb_times)"), ) end function PB.register_methods!(rj::ReactionForceInterp) @info "ReactionForceInterp.register_methods! $(PB.fullname(rj))" vars = [ PB.VarDepScalar("global.tforce", "yr", "historical time at which to apply forcings, present = 0 yr"), PB.VarPropScalar("F", "", "interpolated forcing"), ] PB.add_method_do!(rj, do_forceinterp, (PB.VarList_namedtuple(vars), )) return nothing end function do_forceinterp(m::PB.ReactionMethod, pars, (vars, ), cellrange::PB.AbstractCellRange, deltat) tforce = vars.tforce[] idx_after = searchsortedfirst(pars.force_times.v, tforce) if tforce == first(pars.force_times.v) # extra check as searchsortedfirst uses >= idx_after += 1 end if idx_after == 1 (pars.extrapolate[] == "constant") || error("tforce $tforce out-of-range, < first(force_times) = $(first(pars.force_times.v))") vars.F[] = pars.extrapolate_before[] elseif idx_after > length(pars.force_times.v) (pars.extrapolate[] == "constant") || error("tforce $tforce out-of-range, > last(force_times) = $(last(pars.force_times.v))") vars.F[] = pars.extrapolate_after[] else # linearly interpolate t_l, t_h = pars.force_times.v[idx_after-1], pars.force_times.v[idx_after] x_l = (t_h-tforce)/(t_h - t_l) x_h = (tforce-t_l)/(t_h - t_l) vars.F[] = x_l*pars.force_values.v[idx_after-1] + x_h*pars.force_values.v[idx_after] end return nothing end end # module
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
15925
module GridForcings import NCDatasets import MAT import Interpolations import PALEOboxes as PB using ..DocStrings using Infiltrator # Julia debugger """ 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_vars`` x `time_var`, where order within `interp_vars` also must match netcdf order. # Parameters $(PARS) # Methods and Variables for default Parameters $(METHODS_DO) """ Base.@kwdef mutable struct ReactionForceGrid{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParString("netcdf_file", "", description="netcdf file with gridded time-series data"), PB.ParString("matlab_file", "", description="matlab file with gridded time-series data"), PB.ParString("matlab_key", "", description="Dictionary key in Matlab file to use (empty string to stay at top level Dict)"), PB.ParString("data_var", "", description="variable name in data file"), PB.ParString("time_var", "time", description="time variable name in data file (empty to generate evenly spaced times from cycle_time)"), PB.ParDouble("time_fac", 1.0, units="", description="multiplier to convert time_var to model time (yr)"), PB.ParInt("tidx_start", 1, description="first record in data file to use"), PB.ParInt("tidx_end", 1, description="last record in data file to use (set equal to tidx_start for constant forcing from single record)"), PB.ParBool("use_timeav", false, description="true to average records and provide constant forcing at time-averaged value"), PB.ParBool("time_extrap_const", false, description="true to extrapolate out-of-range times to first/last value, false to error if time out-of-range"), PB.ParDouble("cycle_time", 0.0, units="yr", description="time periodicity to apply (0.0 to disable periodic)"), PB.ParStringVec("interp_vars", 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"), PB.ParBoolVec("interp_log", Bool[], description="true to interpolate interp_vars in log space"), PB.ParDouble("data_replace_nan", NaN, units="", description="value to replace NaN in data"), PB.ParDouble("scale", 1.0, units="", description="scaling factor to apply"), PB.ParDouble("constant_offset", 0.0, units="", description="constant offset to apply"), PB.ParDouble("scale_offset_var", 0.0, units="", description="scaling for additional scalar offset from model variable (0.0 to disable)"), ) data_time = nothing data_var = nothing time_interp = nothing interp_interp = nothing interp_fn = nothing end function PB.register_methods!(rj::ReactionForceGrid) @info "register_methods! $(PB.fullname(rj))" vars = [ PB.VarDepScalar("global.tforce", "yr", "historical time at which to apply forcings, present = 0 yr"), PB.VarProp("F", "unknown", "interpolated forcing"), ] if rj.pars.scale_offset_var[] != 0.0 @info " adding scalar offset from Variable 'scalar_offset'" push!(vars, PB.VarDepScalar("scalar_offset", "unknown", "scalar offset")) end PB.setfrozen!(rj.pars.scale_offset_var) interp_vars = [] for (vname, vlog) in PB.IteratorUtils.zipstrict(rj.pars.interp_vars, rj.pars.interp_log; errmsg="length(interp_vars) != length(interp_log)") @info " adding interpolation Variable $vname log $vlog" push!(interp_vars, PB.VarDepScalar(vname, "unknown", "interpolation variable log $vlog")) end PB.setfrozen!(rj.pars.interp_vars, rj.pars.interp_log) PB.add_method_do!( rj, do_force_grid, (PB.VarList_namedtuple(vars), PB.VarList_tuple(interp_vars)), preparefn=prepare_do_force_grid, ) return nothing end function prepare_do_force_grid( m::PB.ReactionMethod, (vars, interp_vars), ) rj = m.reaction @info "prepare_do_force_grid: $(PB.fullname(rj))" if !isempty(rj.pars.netcdf_file[]) && isempty(rj.pars.matlab_file[]) @info " reading 'data_var' from variable '$(rj.pars.data_var[])' in netcdf file '$(rj.pars.netcdf_file[])'" NCDatasets.Dataset(rj.pars.netcdf_file[]) do ds _prepare_data(rj, ds) end elseif !isempty(rj.pars.matlab_file[]) && isempty(rj.pars.netcdf_file[]) @info " reading 'data_var' from variable '$(rj.pars.data_var[])' in matlab file '$(rj.pars.matlab_file[])' key '$(rj.pars.matlab_key[])'" ds = MAT.matread(rj.pars.matlab_file[]) # must return a Dict varname=>vardata if !isempty(rj.pars.matlab_key[]) ds = ds[rj.pars.matlab_key[]] end _prepare_data(rj, ds) else error(" both netcdf_file $(rj.pars.netcdf_file[]) and matlab_file $(rj.pars.matlab_file[]) are specified") end PB.setfrozen!(rj.pars.netcdf_file, rj.pars.matlab_file, rj.pars.data_var, rj.pars.time_var, rj.pars.tidx_start, rj.pars.tidx_end, rj.pars.use_timeav, rj.pars.cycle_time,) return (vars, interp_vars, rj.time_interp, rj.interp_interp, rj.interp_fn, rj.data_var) end """ _prepare_data(rj::ReactionForceGrid, ds) Read data variable from `ds[rj.pars.data_var[]]` and optional time values from `ds[rj.pars.time_var[]]`. Map data variable to PALEO internal array layout and store in `rj.data_var`, generate time interpolator in `rj.time_interp`. """ function _prepare_data(rj::ReactionForceGrid, ds) num_nc_time_recs = rj.pars.tidx_end[] - rj.pars.tidx_start[] + 1 if rj.pars.use_timeav[] num_time_recs = 1 else num_time_recs = num_nc_time_recs end # NB: A PALEO Cartesian Grid may define an internal_size for model Variables that has different dimensions (eg a linear Vector) # to the n-D cartesian_size of the forcings read from the NetCDF file ncartesiandims = length(PB.cartesian_size(rj.domain.grid)) # as read from NetCDF cartesiancolons = fill(Colon(), ncartesiandims) ninternaldims = length(PB.internal_size(PB.CellSpace, rj.domain.grid)) # PALEO array layout internalcolons = fill(Colon(), ninternaldims) ninterpdims = length(rj.pars.interp_vars) interpcolons = fill(Colon(), ninterpdims) interpdims = [length(ds[vn]) for vn in rj.pars.interp_vars] # map to grid internal storage (ie mapping ncartesiandims -> ninternaldims) # grid interp time data_ndims = ninternaldims + length(interpdims) + 1 rj.data_var = Array{Float64, data_ndims}(undef, PB.internal_size(PB.CellSpace, rj.domain.grid)..., interpdims..., num_time_recs) @info " size(data_var) = $(size(rj.data_var))" # TODO - reorder indices (currently require gridvars..., interpvars..., timevar) # read netcdf data, taking only the time records we need tmp_var = Array(ds[rj.pars.data_var[]][cartesiancolons..., interpcolons..., rj.pars.tidx_start[]:rj.pars.tidx_end[]]) # copy into data_var, mapping ngriddims -> 1 linear index and creating time average if necessary drn = rj.pars.data_replace_nan[] if rj.pars.use_timeav[] @views rj.data_var[internalcolons..., interpcolons..., 1] .= 0.0 for i in 1:num_nc_time_recs if length(interpdims) == 0 @views rj.data_var[internalcolons..., 1] .+= _replace_nan!(PB.Grids.cartesian_to_internal(rj.domain.grid, tmp_var[cartesiancolons..., i]), drn) ./num_nc_time_recs elseif length(interpdims) == 1 for id1 in 1:interpdims[1] @views rj.data_var[internalcolons..., id1, 1] .+= _replace_nan!(PB.Grids.cartesian_to_internal(rj.domain.grid, tmp_var[cartesiancolons..., id1, i]), drn) ./num_nc_time_recs end elseif length(interpdims) == 2 for id1 in 1:interpdims[1], id2 in 1:interpdims[2] @views rj.data_var[internalcolons..., id1, id2, 1] .+= _replace_nan!(PB.Grids.cartesian_to_internal(rj.domain.grid, tmp_var[cartesiancolons..., id1, id2, i]), drn) ./num_nc_time_recs end else error(" > 2 interpdims not supported") end end else for i in 1:num_nc_time_recs if length(interpdims) == 0 @views rj.data_var[internalcolons..., i] .= _replace_nan!(PB.Grids.cartesian_to_internal(rj.domain.grid, tmp_var[cartesiancolons..., i]), drn) elseif length(interpdims) == 1 for id1 in 1:interpdims[1] @views rj.data_var[internalcolons..., id1, i] .= _replace_nan!(PB.Grids.cartesian_to_internal(rj.domain.grid, tmp_var[cartesiancolons..., id1, i]), drn) end elseif length(interpdims) == 2 for id1 in 1:interpdims[1], id2 in 1:interpdims[2] @views rj.data_var[internalcolons..., id1, id2, i] .= _replace_nan!(PB.Grids.cartesian_to_internal(rj.domain.grid, tmp_var[cartesiancolons..., id1, id2, i]), drn) end else error(" > 2 interpdims not supported") end end end # create time interpolator if num_time_recs > 1 if !isempty(rj.pars.time_var[]) @info " reading 'data_time' from variable '$(rj.pars.time_var[])' * $(rj.pars.time_fac[]) to generate time-dependent forcing from $num_time_recs records out of $num_nc_time_recs in file" rj.data_time = Array(ds[rj.pars.time_var[]][rj.pars.tidx_start[]:rj.pars.tidx_end[]]) .* rj.pars.time_fac[] @info " data_time[1]: $(rj.data_time[1]) = $(ds[rj.pars.time_var[]][rj.pars.tidx_start[]]) * $(rj.pars.time_fac[])" @info " data_time[$(length(rj.data_time))]: $(rj.data_time[end]) = $(ds[rj.pars.time_var[]][rj.pars.tidx_end[]]) * $(rj.pars.time_fac[])" else @info " generating evenly spaced intervals in range 0.0 - $(rj.pars.time_fac[]) to apply time-dependent forcing from $num_time_recs records with no time axis defined" rj.data_time = collect(range(0.5/num_time_recs, step=1.0/num_time_recs, length=num_time_recs)) .* rj.pars.time_fac[] end # create time interpolation rj.time_interp = PB.LinInterp(rj.data_time, rj.pars.cycle_time[]; extrap_const=rj.pars.time_extrap_const[]) else @info " generating constant time forcing from $num_nc_time_recs time record(s)" rj.time_interp = nothing end # create variable interpolator(s) (if any) rj.interp_interp = [] rj.interp_fn = [] for (vidx, (vname, vlog)) in enumerate(PB.IteratorUtils.zipstrict(rj.pars.interp_vars, rj.pars.interp_log; errmsg="length(interp_vars) != length(interp_log)")) if vlog interp_fn = log else interp_fn = identity end push!(rj.interp_fn, interp_fn) vvalues = interp_fn.(Array(ds[vname])) @info " interpolate $vname (log $vlog) values $vvalues" length(vvalues) == size(rj.data_var)[ninternaldims+vidx] || error(" number of values != array size of dimension $(ninternaldims+vidx)") push!(rj.interp_interp, PB.LinInterp(vvalues[:], extrap_const=true)) end rj.interp_fn = tuple(rj.interp_fn...) rj.interp_interp = tuple(rj.interp_interp...) return nothing end function _replace_nan!(x::AbstractArray, rnan) for i in eachindex(x) if isnan(x[i]) x[i] = rnan end end return x end function do_force_grid( m::PB.ReactionMethod, pars, (vars, interp_vars, time_interp, interp_interp, interp_fn, data_var), cellrange::PB.AbstractCellRange, deltat, ) rj = m.reaction if !isnothing(time_interp) # time dependent forcing tforce = vars.tforce[] ((wt_lo, rec_lo), (wt_hi, rec_hi)) = PB.interp(time_interp, tforce) else # constant forcing wt_lo = 1.0 rec_lo = 1 wt_hi = 0.0 rec_hi = 1 end # apply scaling wt_lo *= pars.scale[] wt_hi *= pars.scale[] # apply scalar offset scalar_offset = pars.constant_offset[] if pars.scale_offset_var[] != 0.0 scalar_offset += pars.scale_offset_var[] * vars.scalar_offset[] end if length(interp_vars) == 0 _do_interp_0(vars, data_var, cellrange, wt_lo, wt_hi, rec_lo, rec_hi, scalar_offset) elseif length(interp_vars) == 1 _do_interp_1(vars, data_var, cellrange, wt_lo, wt_hi, rec_lo, rec_hi, scalar_offset, interp_interp, interp_fn, interp_vars) elseif length(interp_vars) == 2 _do_interp_2(vars, data_var, cellrange, wt_lo, wt_hi, rec_lo, rec_hi, scalar_offset, interp_interp, interp_fn, interp_vars) else error(" > 2 interp_vars not supported") end return nothing end function _do_interp_0(vars, data_var, cellrange, wt_lo, wt_hi, rec_lo, rec_hi, scalar_offset) @inbounds for i in cellrange.indices vars.F[i] = wt_lo*data_var[i, rec_lo] + wt_hi*data_var[i, rec_hi] + scalar_offset end end function _do_interp_1(vars, data_var, cellrange, wt_lo, wt_hi, rec_lo, rec_hi, scalar_offset, interp_interp, interp_fn, interp_vars) ((wt1_lo, rec1_lo), (wt1_hi, rec1_hi)) = PB.interp(interp_interp[1], interp_fn[1](interp_vars[1][])) @inbounds for i in cellrange.indices vars.F[i] = ( wt_lo*(wt1_lo*data_var[i, rec1_lo, rec_lo] + wt1_hi*data_var[i, rec1_hi, rec_lo]) + wt_hi*(wt1_lo*data_var[i, rec1_lo, rec_hi] + wt1_hi*data_var[i, rec1_hi, rec_hi]) + scalar_offset ) end end function _do_interp_2(vars, data_var, cellrange, wt_lo, wt_hi, rec_lo, rec_hi, scalar_offset, interp_interp, interp_fn, interp_vars) ((wt1_lo, rec1_lo), (wt1_hi, rec1_hi)) = PB.interp(interp_interp[1], interp_fn[1](interp_vars[1][])) ((wt2_lo, rec2_lo), (wt2_hi, rec2_hi)) = PB.interp(interp_interp[2], interp_fn[2](interp_vars[2][])) @inbounds for i in cellrange.indices vars.F[i] = ( wt_lo*( wt1_lo*(wt2_lo*data_var[i, rec1_lo, rec2_lo, rec_lo] + wt2_hi*data_var[i, rec1_lo, rec2_hi, rec_lo]) + wt1_hi*(wt2_lo*data_var[i, rec1_hi, rec2_lo, rec_lo] + wt2_hi*data_var[i, rec1_hi, rec2_hi, rec_lo]) ) + wt_hi*( wt1_lo*(wt2_lo*data_var[i, rec1_lo, rec2_lo, rec_hi] + wt2_hi*data_var[i, rec1_lo, rec2_hi, rec_hi]) + wt1_hi*(wt2_lo*data_var[i, rec1_hi, rec2_lo, rec_hi] + wt2_hi*data_var[i, rec1_hi, rec2_hi, rec_hi]) ) + scalar_offset ) end end end # module
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
5656
module GridReactions import PALEOboxes as PB using ..DocStrings import Infiltrator # Julia debugger """ ReactionUnstructuredVectorGrid Create an [`PB.Grids.UnstructuredVectorGrid`](@ref) with `ncells` (from `ncells` Parameter). # Parameters $(PARS) """ Base.@kwdef mutable struct ReactionUnstructuredVectorGrid{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParInt("ncells", 1, description="number of grid cells"), ) end function PB.set_model_geometry(rj::ReactionUnstructuredVectorGrid, model::PB.Model) @info "set_model_geometry $(PB.fullname(rj))" grid = PB.Grids.UnstructuredVectorGrid(ncells=rj.pars.ncells[]) rj.domain.grid = grid @info " set $(rj.domain.name) Domain size=$(grid.ncells) grid=$grid" return nothing end PB.register_methods!(rj::ReactionUnstructuredVectorGrid) = nothing """ ReactionCartesianGrid Create a [`PB.Grids.CartesianArrayGrid`](@ref) with `dims` and `dimnames`` # Parameters $(PARS) """ Base.@kwdef mutable struct ReactionCartesianGrid{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParStringVec("dimnames", ["lat", "lon", "z"], description="grid dimension names"), PB.ParIntVec("dims", [2, 3, 4], description="grid dimensions"), ) end function PB.set_model_geometry(rj::ReactionCartesianGrid, model::PB.Model) @info "set_model_geometry $(PB.fullname(rj))" grid = PB.Grids.CartesianGrid( PB.Grids.CartesianArrayGrid, rj.pars.dimnames.v, rj.pars.dims.v ) rj.domain.grid = grid @info " set $(rj.domain.name) Domain size=$(grid.ncells) grid=$grid" return nothing end PB.register_methods!(rj::ReactionCartesianGrid) = nothing """ ReactionGrid2DNetCDF Create a 2D [`PB.Grids.CartesianLinearGrid`](@ref) from grid information in a NetCDF file. # Parameters $(PARS) # Methods $(METHODS_SETUP) """ Base.@kwdef mutable struct ReactionGrid2DNetCDF{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParType(PB.AbstractMesh, "grid_type", PB.Grids.CartesianArrayGrid, allowed_values=(PB.Grids.CartesianArrayGrid, PB.Grids.CartesianLinearGrid), description="Cartesian grid type to create"), PB.ParString("grid_file", "", description="netcdf file with 2D grid information"), PB.ParStringVec("coordinate_names", ["longitude", "latitude"], description="coordinate names to read from netcdf file"), PB.ParBool("equalspacededges", false, description="true to calculate cell edges assuming an equal-spaced grid"), PB.ParString("area_var", "", description="netcdf variable with cell area (if available)"), PB.ParDouble("planet_radius", 6.371229e6, description="radius to calculate cell area from spherical geometry (if area_var = \"\")"), ) end function PB.set_model_geometry(rj::ReactionGrid2DNetCDF, model::PB.Model) @info "set_model_geometry $(PB.fullname(rj))" @info " reading 2D grid from $(rj.pars.grid_file[])" grid2D = PB.Grids.CartesianGrid( rj.pars.grid_type[], rj.pars.grid_file[], rj.pars.coordinate_names.v, equalspacededges=rj.pars.equalspacededges[] ) if rj.pars.grid_type[] == PB.Grids.CartesianLinearGrid # define a linear index including every cell, in column-major order (first indices are consecutive in memory) v_i = vec([i for i=1:grid2D.dims[1], j=1:grid2D.dims[2]]) v_j = vec([j for i=1:grid2D.dims[1], j=1:grid2D.dims[2]]) PB.Grids.set_linear_index(grid2D, v_i, v_j) end rj.domain.grid = grid2D @info " set $(rj.domain.name) Domain size=$(grid2D.ncells) grid=$grid2D" return nothing end function PB.register_methods!(rj::ReactionGrid2DNetCDF) @info "register_methods! $(PB.fullname(rj))" grid_vars = [ PB.VarPropStateIndep("Asurf", "m^2", "horizontal area of surface"), PB.VarPropScalarStateIndep("Asurf_total", "m^2", "total horizontal area of surface"), ] PB.add_method_setup!( rj, setup_grid_2DNetCDF, (PB.VarList_namedtuple(grid_vars),) ) return nothing end function setup_grid_2DNetCDF( m::PB.ReactionMethod, pars, (grid_vars, ), cellrange::PB.AbstractCellRange, attribute_name ) rj = m.reaction attribute_name == :setup || return @info "$(PB.fullname(m)):" grid2D = rj.domain.grid length(cellrange.indices) == grid2D.ncells || error("tiled cellrange not supported") if !isempty(pars.area_var[]) NCDatasets.Dataset(pars.grid_file[]) do ds area2D = Array(ds[pars.area_var[]][:, :, 1]) grid_vars.Asurf .= cartesian_to_internal(rj.domain.grid, area2D) end else for i in cellrange.indices lon_edges = PB.Grids.get_lon_edges(grid2D, i) lat_edges = PB.Grids.get_lat_edges(grid2D, i) area = calc_spherical_area(pars.planet_radius[], lon_edges, lat_edges) grid_vars.Asurf[i] = area end end grid_vars.Asurf_total[] = sum(grid_vars.Asurf) return nothing end "area of cell on regular spherical grid" function calc_spherical_area(r, (lond_l, lond_u), (latd_l, latd_u)) Astrip = 2*pi*r^2*(sind(latd_u) - sind(latd_l)) # area of strip between latitudes A = (lond_u - lond_l)/360.0 * Astrip # area of cell return A end end # module
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
203
include("Constants.jl") include("Fluxes.jl") include("FluxPerturb.jl") include("Forcings.jl") include("GridForcings.jl") include("GridReactions.jl") include("Reservoirs.jl") include("VariableStats.jl")
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
30452
# -*- coding: utf-8 -*- module Reservoirs import PALEOboxes as PB import Infiltrator # Julia debugger using ..DocStrings """ ReactionReservoirScalar A single scalar biogeochemical reservoir with optional paired isotope reservoir, for use in a 0D Domain (eg sedimentary or ocean reservoirs for COPSE [Bergman2004](@cite)). Creates State and associated Variables, depending on parameter settings: - `const=false`: usual case - `state_norm=false` create state variable `R` (units mol, with attribute `vfunction=VF_StateExplicit`) and `R_sms` (units mol yr-1, with attribute `vfunction=VF_Deriv`). - `state_norm=true` create state variable `R_solve` (`R` normalized by the values of attribute `R:norm_value`, with attribute `vfunction=VF_StateExplicit`) and `R_solve_sms` (units yr-1, with attribute `vfunction=VF_Deriv`). - `const=true`: a constant value, create `R` (a Property), and `R_sms` (a Target) In addition: - a Property `R_norm` (normalized value) is always created. - if parameter `field_data <: AbstractIsotopeScalar` (eg `IsotopeLinear`), a Property `R_delta` is created. The local name prefix `R` should then be renamed using `variable_links:` in the configuration file. # Initialisation Initial and norm value is set in the `variable_attributes:` section in the configuration file, using `R:initial_value`, `R:initial_delta`, and `R:norm_value`. # Example configuration in .yaml file reservoir_P: # 0D ocean Phosphorus class: ReactionReservoirScalar parameters: # field_data: ScalarData # change to IsotopeLinear to represent an isotope # const: false # true to fix to constant value variable_links: R*: P # rename to represent Phosphorus variable_attributes: R:norm_value: 3.1e15 # mol R:initial_value: 3.1e15 # mol # See also [`ReactionReservoir`](@ref) (one value per cell for a spatially resolved Domain eg ocean), [`ReactionReservoirWellMixed`](@ref) (one value for a whole spatially resolved Domain). # Parameters $(PARS) # Methods and Variables for default Parameters $(METHODS_DO) """ Base.@kwdef mutable struct ReactionReservoirScalar{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParType(PB.AbstractData, "field_data", PB.ScalarData, allowed_values=PB.IsotopeTypes, description="disable / enable isotopes and specify isotope type"), PB.ParBool("const", false, description="true to provide a constant value: R is not a state variable, fluxes in R_sms Variable are ignored"), PB.ParBool("state_norm", false, description="true to provide solver with normalized values"), ) norm_value::Float64 = NaN end function PB.register_methods!(rj::ReactionReservoirScalar) do_vars = PB.VariableReaction[PB.VarPropScalar("R_norm", "", "scalar reservoir normalized")] if rj.pars.const[] R = PB.VarPropScalar( "R", "mol", "scalar constant reservoir", attributes=(:field_data =>rj.pars.field_data[],)) push!(do_vars, R) PB.add_method_setup!( rj, setup_reactionreservoirscalar, (PB.VarList_fields([R]), PB.VarList_nothing() ), ) R_sms = PB.VarTargetScalar( "R_sms", "mol yr-1", "scalar reservoir source-sinks", attributes=(:field_data =>rj.pars.field_data[],)) # sms variable not used by us, but must appear in a method to be linked and created PB.add_method_do_nothing!(rj, [R_sms]) else if rj.pars.state_norm[] R = PB.VarPropScalar("R", "mol", "scalar reservoir", attributes=(:field_data =>rj.pars.field_data[],)) R_solve = PB.VarStateExplicitScalar("R_solve", "", "normalized scalar reservoir", attributes=(:field_data =>rj.pars.field_data[],)) append!(do_vars, [R, R_solve]) PB.add_method_setup!( rj, setup_reactionreservoirscalar, (PB.VarList_fields([R]), PB.VarList_fields([R_solve]) ), ) R_sms = PB.VarTargetScalar( "R_sms", "mol yr-1", "scalar reservoir source-sinks", attributes=(:field_data =>rj.pars.field_data[],)) R_solve_sms = PB.VarDerivScalar( "R_solve_sms", "yr-1", "normalized scalar reservoir source-sinks", attributes=(:field_data =>rj.pars.field_data[],)) PB.add_method_do!( rj, do_reactionreservoirscalar_sms, (PB.VarList_namedtuple([R_sms, R_solve_sms]), ), ) else R = PB.VarStateExplicitScalar("R", "mol", "scalar reservoir", attributes=(:field_data =>rj.pars.field_data[],)) push!(do_vars, R) PB.add_method_setup!( rj, setup_reactionreservoirscalar, (PB.VarList_fields([R]), PB.VarList_nothing() ), ) R_sms = PB.VarDerivScalar( "R_sms", "mol yr-1", "scalar reservoir source-sinks", attributes=(:field_data =>rj.pars.field_data[],)) # sms variable not used by us, but must appear in a method to be linked and created PB.add_method_do_nothing!(rj, [R_sms]) end PB.setfrozen!(rj.pars.state_norm) end PB.setfrozen!(rj.pars.const) if rj.pars.field_data[] <: PB.AbstractIsotopeScalar push!(do_vars, PB.VarPropScalar("R_delta", "per mil", "scalar reservoir isotope delta")) end PB.setfrozen!(rj.pars.field_data) PB.add_method_do!( rj, do_reactionreservoirscalar, (PB.VarList_namedtuple(do_vars), ), ) PB.add_method_initialize_zero_vars_default!(rj) return nothing end function setup_reactionreservoirscalar(m::PB.AbstractReactionMethod, pars, (R, R_solve, ), cellrange::PB.AbstractCellRange, attribute_name) rj = m.reaction # VariableReactions corresponding to (R, R_solve) R_vars, R_solve_vars = PB.get_variables_tuple(m) R_var = only(R_vars) R_domvar = R_var.linkvar rj.norm_value = PB.get_attribute(R_domvar, :norm_value) if pars.const[] && (attribute_name == :setup) PB.init_field!( only(R), :initial_value, R_domvar, (_, _)->1.0, [], cellrange, (PB.fullname(R_domvar), "", "") ) elseif attribute_name in (:norm_value, :initial_value) if pars.state_norm[] R_solve_var = only(R_solve_vars) R_solve_domvar = R_solve_var.linkvar PB.init_field!( only(R_solve), attribute_name, R_domvar, (_, _)->1/rj.norm_value, [], cellrange, (PB.fullname(R_solve_domvar), " / $(rj.norm_value)", " [from $(PB.fullname(R_domvar))]") ) else PB.init_field!( only(R), attribute_name, R_domvar, (_, _)->1.0, [], cellrange, (PB.fullname(R_domvar), "", "") ) end end return nothing end function do_reactionreservoirscalar(m::PB.AbstractReactionMethod, pars, (vars, ), cr::PB.AbstractCellRange, deltat) rj = m.reaction if pars.state_norm[] vars.R[] = vars.R_solve[]*rj.norm_value vars.R_norm[] = PB.get_total(vars.R_solve[]) else vars.R_norm[] = PB.get_total(vars.R[])/rj.norm_value end if hasfield(typeof(vars), :R_delta) vars.R_delta[] = PB.get_delta(vars.R[]) end return nothing end function do_reactionreservoirscalar_sms(m::PB.AbstractReactionMethod, pars, (vars, ), cr::PB.AbstractCellRange, deltat) rj = m.reaction vars.R_solve_sms[] += vars.R_sms[]/rj.norm_value return nothing end """ 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 'state_conc=false') or `R_conc:initial_value` and `R_conc:initial_delta` (for a 'state_conc=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 variable_links: 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`](@ref) (one value for the whole Domain), [`ReactionReservoirScalar`](@ref) (one value for a reservoir in a 0D Domain eg for COPSE [Bergman2004](@cite)), [`ReactionReservoirConst`](@ref) (constant time-independent value ie no state variable). # Parameters $(PARS) # Methods and Variables for default Parameters $(METHODS_DO) """ Base.@kwdef mutable struct ReactionReservoir{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParType(PB.AbstractData, "field_data", PB.ScalarData, allowed_values=PB.IsotopeTypes, description="disable / enable isotopes and specify isotope type"), PB.ParBool("total", false, description="true to calculate R_total"), PB.ParDouble("limit_delta_conc", 0.0, units="mol m-3", description="**EXPERIMENTAL** attempt to limit delta for low/-ve concentrations (0.0 to disable)"), PB.ParBool("state_conc", 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"), ) end abstract type ReactionReservoirTotal <: PB.AbstractReaction end function PB.create_reaction(::Type{ReactionReservoirTotal}, base::PB.ReactionBase) rj = ReactionReservoir(base=base) PB.setvalueanddefault!(rj.pars.total, true) PB.setfrozen!(rj.pars.total) return rj end function PB.register_methods!(rj::ReactionReservoir) PB.setfrozen!(rj.pars.field_data) PB.setfrozen!(rj.pars.total) R_attributes=( :field_data=>rj.pars.field_data[], :calc_total=>rj.pars.total[], ) R_conc_attributes = ( :field_data=>rj.pars.field_data[], :advect=>true, :vertical_movement=>0.0, :specific_light_extinction=>0.0, :vphase=>PB.VP_Undefined, :diffusivity_speciesname=>"", :diffusivity=>missing, :charge=>missing, :gamma=>missing, ) volume = PB.VarDep("volume", "m3", "cell volume (or cell phase volume eg for a sediment with solid and liquid phases)") if rj.pars.state_conc[] R = PB.VarProp("R", "mol", "vector reservoir"; attributes=R_attributes) R_conc = PB.VarStateExplicit("R_conc", "mol m-3", "concentration"; attributes=R_conc_attributes) PB.add_method_setup_initialvalue_vars_default!(rj, [R_conc]) else R = PB.VarStateExplicit("R", "mol", "vector reservoir"; attributes=R_attributes) PB.add_method_setup_initialvalue_vars_default!( rj, [R], convertvars = [volume], convertfn = ((volume,), i) -> volume[i], convertinfo = " * volume", ) R_conc = PB.VarProp("R_conc", "mol m-3", "concentration"; attributes=R_conc_attributes) end PB.setfrozen!(rj.pars.state_conc) do_vars = PB.VariableReaction[R, R_conc, volume,] if rj.pars.field_data[] <: PB.AbstractIsotopeScalar push!(do_vars, PB.VarProp("R_delta", "per mil", "isotopic composition")) if rj.pars.limit_delta_conc[] > 0.0 @warn "$(PB.fullname(rj)) using experimental limit_delta_conc $(rj.pars.limit_delta_conc[]) mol m-3" end end PB.add_method_do!(rj, do_reactionreservoir, (PB.VarList_namedtuple(do_vars),)) if rj.pars.state_conc[] R_conc_sms = PB.VarDeriv("R_conc_sms", "mol m-3 yr-1", "vector reservoir source-sinks", attributes=(:field_data=>rj.pars.field_data[], ), ) R_sms = PB.VarTarget("R_sms", "mol yr-1", "vector reservoir source-sinks", attributes=(:field_data=>rj.pars.field_data[], ), ) PB.add_method_do!(rj, do_reactionreservoirconc_sms, (PB.VarList_namedtuple([volume, R_conc_sms, R_sms]),)) else R_sms = PB.VarDeriv("R_sms", "mol yr-1", "vector reservoir source-sinks", attributes=(:field_data=>rj.pars.field_data[], ), ) # sms variable not used by us, but must appear in a method to be linked and created PB.add_method_do_nothing!(rj, [R_sms]) end if rj.pars.total[] PB.add_method_do_totals_default!(rj, [R]) end PB.setfrozen!(rj.pars.total) PB.add_method_initialize_zero_vars_default!(rj) return nothing end function do_reactionreservoir(m::PB.AbstractReactionMethod, pars, (vars, ), cellrange::PB.AbstractCellRange, deltat) if pars.state_conc[] @inbounds for i in cellrange.indices vars.R[i] = vars.R_conc[i]*vars.volume[i] end else @inbounds for i in cellrange.indices vars.R_conc[i] = vars.R[i]/vars.volume[i] end end if hasfield(typeof(vars), :R_delta) limit_value = pars.limit_delta_conc[] if limit_value > 0.0 # norm_value = PB.get_attribute(rj.var_R, :norm_value)::Float64 # limit_value = 1e-6 # mol m-3 @inbounds for i in cellrange.indices vars.R_delta[i] = PB.get_delta_limit(vars.R[i], limit_value*vars.volume[i], 100.0) end else @inbounds for i in cellrange.indices vars.R_delta[i] = PB.get_delta(vars.R[i]) end end end return nothing end function do_reactionreservoirconc_sms(m::PB.AbstractReactionMethod, pars, (vars, ), cellrange::PB.AbstractCellRange, deltat) @inbounds for i in cellrange.indices vars.R_conc_sms[i] += vars.R_sms[i]/vars.volume[i] end return nothing end """ ReactionReservoirConst A single (vector) constant tracer `R_conc` (constant replacement for a [`ReactionReservoir`](@ref)). 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 variable_links: R*: B variable_attributes: R_conc:initial_value: 0.4269239 # contemporary value R_conc:initial_delta: 34.0 # See also [`ReactionReservoir`](@ref) # Parameters $(PARS) # Methods and Variables $(METHODS_SETUP) """ Base.@kwdef mutable struct ReactionReservoirConst{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParType(PB.AbstractData, "field_data", PB.ScalarData, allowed_values=PB.IsotopeTypes, description="disable / enable isotopes and specify isotope type"), ) end function PB.register_methods!(rj::ReactionReservoirConst) var_R_conc = PB.VarProp("R_conc", "mol m-3", "concentration", attributes=(:field_data=>rj.pars.field_data[], :specific_light_extinction=>0.0,) ) # specify filterfn to initialize var_R_conc even though it isn't a state variables PB.add_method_setup_initialvalue_vars_default!(rj, [var_R_conc], filterfn = v->true) if rj.pars.field_data[] <: PB.AbstractIsotopeScalar vars = [ var_R_conc, PB.VarProp("R_delta", "per mil", "isotopic composition"), ] # use do, not setup, so we handle the case where the value is modified after setup PB.add_method_do!(rj, do_reactionreservoirconst, (PB.VarList_namedtuple(vars),) ) else # add a dummy method to block any other reaction from also setting a var_R_conc Property Variable PB.add_method_do_nothing!(rj, [var_R_conc]) end PB.setfrozen!(rj.pars.field_data) return nothing end function do_reactionreservoirconst(m::PB.ReactionMethod, (vars, ), cellrange::PB.AbstractCellRange, deltat) @inbounds for i in cellrange.indices vars.R_delta[i] = PB.get_delta(vars.R_conc[i]) end return nothing end """ ReactionReservoirForced A single (vector) constant tracer (constant replacement for a [`ReactionReservoir`](@ref)), 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`](@ref), [`ReactionReservoir`](@ref) # Parameters $(PARS) # Methods and Variables for default Parameters $(METHODS_DO) """ Base.@kwdef mutable struct ReactionReservoirForced{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParType(PB.AbstractData, "field_data", PB.ScalarData, allowed_values=PB.IsotopeTypes, description="disable / enable isotopes and specify isotope type"), ) end function PB.register_methods!(rj::ReactionReservoirForced) var_R_conc_initial = PB.VarProp("R_conc_initial", "mol m-3", "initial concentration", attributes=(:field_data=>rj.pars.field_data[], ) ) # specify filterfn to initialize var_R_conc_initial even though it isn't a state variable PB.add_method_setup_initialvalue_vars_default!( rj, [var_R_conc_initial], filterfn = v->true, ) do_vars = [ var_R_conc_initial, PB.VarProp("R_conc", "mol m-3", "concentration = initial * forcing", attributes=(:field_data=>rj.pars.field_data[], :specific_light_extinction=>0.0,)), # PB.VarDep( "volume", "m3", "cell volume"), PB.VarDepScalar( "R_FORCE", "", "forcing factor"), ] if rj.pars.field_data[] <: PB.AbstractIsotopeScalar push!(do_vars, PB.VarProp("R_delta", "per mil", "isotopic composition")) end PB.setfrozen!(rj.pars.field_data) PB.add_method_do!( rj, do_reactionreservoirconstforced, (PB.VarList_namedtuple(do_vars),), ) return nothing end function do_reactionreservoirconstforced(m::PB.ReactionMethod, (do_vardata, ), cellrange::PB.AbstractCellRange, deltat) force_fac = do_vardata.R_FORCE[] @inbounds for i in cellrange.indices do_vardata.R_conc[i] = do_vardata.R_conc_initial[i]*force_fac if hasfield(typeof(do_vardata), :R_delta) do_vardata.R_delta[i] = PB.get_delta(do_vardata.R_conc_initial[i]) end end return nothing end """ 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`](@ref) (one value per cell), [`ReactionReservoirScalar`](@ref) (one value for a reservoir in a 0D Domain eg for COPSE [Bergman2004](@cite)). # Parameters $(PARS) # Methods and Variables for default Parameters $(METHODS_DO) """ Base.@kwdef mutable struct ReactionReservoirWellMixed{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParType(PB.AbstractData, "field_data", PB.ScalarData, allowed_values=PB.IsotopeTypes, description="disable / enable isotopes and specify isotope type"), PB.ParString("initialization_type", "conc", allowed_values=["conc", "total"], description=":initial_value attribute represents conc (mol m-3) or total (mol)"), ) total_norm::Float64 = NaN end function PB.register_methods!(rj::ReactionReservoirWellMixed) R = PB.VarStateExplicitScalar( "R", "mol", "scalar reservoir", attributes=(:field_data=>rj.pars.field_data[],)) volume_total = PB.VarDepScalar("volume_total", "m^3", "total volume") vars = [ R, PB.VarPropScalar( "R_norm", "", "scalar reservoir normalized"), PB.VarProp( "R_conc", "mol m-3", "concentration", attributes=(:field_data=>rj.pars.field_data[], :specific_light_extinction=>0.0,)), volume_total, ] if rj.pars.field_data[] <: PB.AbstractIsotopeScalar push!(vars, PB.VarProp("R_delta", "per mil", "isotopic composition")) end PB.setfrozen!(rj.pars.field_data) # callback function to store Variable norm during setup function setup_callback(m, attribute_value, v, vdata) v.localname == "R" || error("setup_callback unexpected Variable $(PB.fullname(v))") if attribute_value == :norm_value m.reaction.total_norm = PB.value_ad(PB.get_total(vdata[])) end return nothing end if rj.pars.initialization_type[] == "total" PB.add_method_setup_initialvalue_vars_default!( rj, [R], setup_callback=setup_callback ) elseif rj.pars.initialization_type[] == "conc" PB.add_method_setup_initialvalue_vars_default!( rj, [R], convertvars=[volume_total], convertfn=((volume_total,), i) -> volume_total[], convertinfo=" * total_volume", setup_callback=setup_callback, ) end PB.setfrozen!(rj.pars.initialization_type) PB.add_method_do!(rj, do_reservoir_well_mixed, (PB.VarList_namedtuple(vars),)) # add method to sum per-cell vec_sms to scalar sms vars_sms = [ PB.VarDerivScalar( "R_sms", "mol yr-1", "scalar reservoir source-sinks", attributes=(:field_data=>rj.pars.field_data[], :atomic=>true,)), PB.VarTarget( "R_vec_sms","mol yr-1", "vector reservoir source-sinks", attributes=(:field_data=>rj.pars.field_data[],)) ] PB.add_method_do!(rj, do_reservoir_well_mixed_sms, (PB.VarList_namedtuple(vars_sms),)) PB.add_method_initialize_zero_vars_default!(rj) return nothing end function do_reservoir_well_mixed( m::PB.ReactionMethod, (vars, ), cellrange::PB.AbstractCellRange, deltat, ) rj = m.reaction if Threads.threadid() == 1 # only set once ! TODO implicitly assuming will always be called from threadid==1 vars.R_norm[] = PB.get_total(vars.R[])/rj.total_norm end @inbounds for i in cellrange.indices vars.R_conc[i] = vars.R[]/vars.volume_total[] end if hasfield(typeof(vars), :R_delta) delta = PB.get_delta(vars.R[]) @inbounds for i in cellrange.indices vars.R_delta[i] = delta end end return nothing end function do_reservoir_well_mixed_sms( m::PB.ReactionMethod, (vars, ), cellrange::PB.AbstractCellRange, deltat, ) # accumulate first into a subtotal, # in order to minimise time spent with lock held if this is one tile of a threaded model subtotal = zero(vars.R_sms[]) @inbounds for i in cellrange.indices subtotal += vars.R_vec_sms[i] end PB.atomic_add!(vars.R_sms, subtotal) return nothing end """ 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 parameters: constnames: ["O2_mr", "CH4_mr", "CO2_mr", "H2_mr"] #, "H2O_mr"] variable_attributes: 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`](@ref), [`ReactionReservoirScalar`](@ref). These provide additional variables (eg `R_delta`) to allow them to function as a drop-in replacement for a non-constant Reservoir. # Parameters $(PARS) # Methods and Variables for default Parameters $(METHODS_SETUP) """ Base.@kwdef mutable struct ReactionConst{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParStringVec("constnames", ["constvar"], description="vector of names for constant Variables. Isotopes use <name>::CIsotope syntax"), ) scalar::Bool = false end function PB.register_methods!(rj::ReactionConst) vars_const = [] for varnameisotope in rj.pars.constnames varname, IsotopeType = PB.split_nameisotope(varnameisotope, rj.external_parameters) if rj.scalar constvar = PB.VarPropScalarStateIndep(varname, "unknown", "constant value", attributes=(:field_data=>IsotopeType, )) else constvar = PB.VarPropStateIndep(varname, "unknown", "constant value", attributes=(:field_data=>IsotopeType, )) end push!(vars_const, constvar) end # add a dummy method to block any other reaction from also creating (and modifying!) a Property Variable PB.add_method_do_nothing!(rj, vars_const) # specify filterfn to initialize vars_const even though they aren't state variables PB.add_method_setup_initialvalue_vars_default!(rj, vars_const, filterfn = v->true) return nothing end abstract type ReactionScalarConst <: PB.AbstractReaction end function PB.create_reaction(::Type{ReactionScalarConst}, base::PB.ReactionBase) rj = ReactionConst(base=base, scalar=true) return rj end """ 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 """ function ReservoirLinksVector(isotope_data::Dict, reservoirlist) # create a list of required variables reservoirs = Vector{PB.VariableReaction}() sms = Vector{PB.VariableReaction}() diagnostics = Vector{PB.VariableReaction}() for reservoir in reservoirlist nameisotopebr, units, description = reservoir (var_optional, nameisotope) = PB.strip_brackets(nameisotopebr) name_root, IsotopeType = PB.split_nameisotope(nameisotope, isotope_data) if var_optional lb="("; rb=")" else lb=""; rb="" end push!( reservoirs, PB.VarDepScalar(lb*name_root*rb, units, description, attributes=(:field_data=>IsotopeType,)) ) push!( sms, PB.VarContribScalar(lb*name_root*"_sms"*rb, units*" yr-1", description*" source-sinks", attributes=(:field_data=>IsotopeType,)) ) push!( diagnostics, PB.VarDepScalar(lb*name_root*"_norm"*rb, "", "normalized "*description) ) if IsotopeType <: PB.AbstractIsotopeScalar push!( diagnostics, PB.VarDepScalar(lb*name_root*"_delta"*rb, "per mil", "isotope delta "*description) ) end end return (reservoirs, sms, diagnostics) end end # module
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
10484
# -*- coding: utf-8 -*- module VariableStats import PALEOboxes as PB using ..DocStrings import Infiltrator # Julia debugger """ 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 $(PARS) # Methods and Variables for default Parameters $(METHODS_DO) """ Base.@kwdef mutable struct ReactionSum{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParStringVec( "vars_to_add", ["2*myvar", "myothervar", "-1*mythirdvar"], description="vector of variable names to add, eg [2*myvar, myothervar, -1*mythirdvar]"), PB.ParString("vars_prefix", "", description="optional prefix for vars_to_add"), PB.ParInt("component_to_add", 0, description="component to add, 0 for all"), PB.ParBool("vectorsum", false, description="true to accumulate sum into vector Variable, "* "false to accumulate sum into scalar (adding vector cells if necessary)"), ) var_multipliers::Vector{Float64} = Float64[] comprange::UnitRange{Int64} = 0:-1 end abstract type ReactionVectorSum <: PB.AbstractReaction end function PB.create_reaction(::Type{ReactionVectorSum}, base::PB.ReactionBase) rj = ReactionSum(base=base) PB.setvalueanddefault!(rj.pars.vectorsum, true) PB.setfrozen!(rj.pars.vectorsum) return rj end function PB.register_methods!(rj::ReactionSum) io = IOBuffer() println(io, "register_methods: $(PB.fullname(rj)) $(PB.typename(rj))") vars_to_add = [] empty!(rj.var_multipliers) for varmultname in rj.pars.vars_to_add # parse multiplier svmn = split(varmultname, ['*', ' '], keepempty=false) if length(svmn) == 1 mult, varname = (1.0, rj.pars.vars_prefix[]*svmn[1]) elseif length(svmn) == 2 mult, varname = (parse(Float64, svmn[1]), rj.pars.vars_prefix[]*svmn[2]) else PB.infoerror(io, "reaction ", fullname(rj), "invalid field in vars_to_add ", varmultname) end println(io, " add $mult * $varname") push!(rj.var_multipliers, mult) # generate new name with domain prefix to disambiguate eg O2 in atm and ocean (linkreq_domain, linkreq_subdomain, linkreq_name, link_optional) = PB.parse_variablereaction_namestr(varname) localname = PB.combine_link_name(linkreq_domain, "", linkreq_name, sep="_") # mark all vars_to_add as optional to help diagnose config errors # default :field_data=>PB.UndefinedData to allow Variable to link to any data type (this is checked later) v = PB.VarDep(localname => "("*varname*")", "unknown", "") # no length check if scalar sum if !rj.pars.vectorsum[] PB.set_attribute!(v, :check_length, false; allow_create=true) end push!(vars_to_add, v) end if rj.pars.vectorsum[] methodfn = do_vectorsum var_sum = PB.VarProp("sum", "unknown", "sum of specified variables") else methodfn = do_scalarsum var_sum = PB.VarPropScalar("sum", "unknown", "sum of specified variables") end PB.add_method_do!( rj, methodfn, ( PB.VarList_single(var_sum, components=true), PB.VarList_tuple(vars_to_add, components=true) ), ) @info String(take!(io)) return nothing end function PB.register_dynamic_methods!(rj::ReactionSum) # update method now Variable are linked hence components known method_sum = PB.get_method_do(rj, rj.pars.vectorsum[] ? "do_vectorsum" : "do_scalarsum") var_sum = PB.get_variable(method_sum, "sum") vars_to_add = PB.get_variables(method_sum, filterfn = v->v.localname != "sum") # set units from sum variable # (may have been set explicitly in yaml file) sum_units = PB.get_attribute(var_sum, :units) for v in vars_to_add PB.set_attribute!(v, :units, sum_units) end # check variable components match and update var_sum.components if rj.pars.component_to_add[] == 0 # add all components of vars_to_add Variables # check all Variable have the same data firstvar_d = nothing for v in vars_to_add !isnothing(v.linkvar) || error("Reaction $(PB.fullname(rj)) variable $(v.localname) is not linked: check configuration") linkvar_d = PB.get_attribute(v.linkvar, :field_data) if v === first(vars_to_add) firstvar_d = linkvar_d PB.set_attribute!(var_sum, :field_data, firstvar_d) @info "Reaction $(PB.fullname(rj)) Variable $(PB.fullname(var_sum.linkvar)) adding data=$firstvar_d" end linkvar_d == firstvar_d || error("Reaction $(PB.fullname(rj)) not all variables to be summed have the same :field_data Type: $(PB.fullname(v.linkvar)) $(linkvar_d) != $(PB.fullname(first(vars_to_add).linkvar)) $(firstvar_d)") end else # add first component of vars_to_add Variables PB.set_attribute!(var_sum, :field_data, PB.ScalarData) @info "Reaction $(PB.fullname(rj)) Variable $(PB.fullname(var_sum.linkvar)) adding single component $(rj.pars.component_to_add[])" end if rj.pars.component_to_add[] == 0 rj.comprange = 1:PB.num_components(PB.get_attribute(var_sum, :field_data)) else rj.comprange = rj.pars.component_to_add[]:rj.pars.component_to_add[] end end function do_scalarsum( m::PB.ReactionMethod, (var_sum_data, vars_to_add_data), cellrange::PB.AbstractCellRange, deltat ) rj = m.reaction comprange = rj.comprange function _add_var(var_to_add, multiplier) for j in comprange var_sum_data[j][] += multiplier * sum(var_to_add[j]) end return nothing end for j in comprange var_sum_data[j][] = 0.0 end PB.IteratorUtils.foreach_longtuple(_add_var, vars_to_add_data, rj.var_multipliers) return nothing end function do_vectorsum( m::PB.ReactionMethod, (var_sum_data, vars_to_add_data), cellrange::PB.AbstractCellRange, deltat ) rj = m.reaction comprange = rj.comprange function _add_var(var_to_add, multiplier) @inbounds for j in comprange for i in cellrange.indices var_sum_data[j][i] += multiplier * var_to_add[j][i] end end return nothing end for j in comprange @inbounds for i in cellrange.indices var_sum_data[j][i] = 0.0 end end PB.IteratorUtils.foreach_longtuple(_add_var, vars_to_add_data, rj.var_multipliers) return nothing end """ ReactionWeightedMean Weighted mean (eg by area or volume) of Variable # Parameters $(PARS) # Methods and Variables $(METHODS_DO) """ Base.@kwdef mutable struct ReactionWeightedMean{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParType(PB.AbstractData, "field_data", PB.ScalarData, allowed_values=PB.IsotopeTypes, description="disable / enable isotopes and specify isotope type"), ) end function PB.register_methods!(rj::ReactionWeightedMean) vars = [ PB.VarDep( "var", "unknown", "variable to calculate weighted mean from", attributes=(:field_data=>rj.pars.field_data[],)), PB.VarDep( "measure", "unknown", "cell area or volume"), PB.VarDepScalar( "measure_total", "unknown", "total Domain area or volume"), PB.VarPropScalar("var_mean", "unknown", "weighted mean over Domain area or volume", attributes=(:field_data=>rj.pars.field_data[], :initialize_to_zero=>true, :atomic=>true)), ] PB.add_method_do!(rj, do_weighted_mean, (PB.VarList_namedtuple(vars),)) PB.add_method_initialize_zero_vars_default!(rj) return nothing end function do_weighted_mean(m::PB.ReactionMethod, (vars,), cellrange::PB.AbstractCellRange, deltat) rj = m.reaction # use a subtotal to minimise time lock held if this is one tile of a threaded model subtotal = zero(vars.var_mean[]) @inbounds for i in cellrange.indices subtotal += vars.var[i]*vars.measure[i] # normalisation by measure_total below end PB.atomic_add!(vars.var_mean, subtotal/vars.measure_total[]) return nothing end """ ReactionAreaVolumeValInRange Fraction of Domain area or volume with Variable in a range of values. # Parameters $(PARS) # Methods and Variables $(METHODS_DO) """ Base.@kwdef mutable struct ReactionAreaVolumeValInRange{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParDouble( "range_min", -Inf, units="mol m-3", description="minimum value to include in frac"), PB.ParDouble( "range_max", Inf, units="mol m-3", description="maximum value to include in frac"), ) end function PB.register_methods!(rj::ReactionAreaVolumeValInRange) vars = [ PB.VarDep( "rangevar", "unknown", "variable to check within range"; attributes=(:field_data=>PB.ScalarData, )), # total only, not isotope PB.VarDep( "measure", "unknown", "cell area or volume"), PB.VarDepScalar( "measure_total", "unknown", "total Domain area or volume"), PB.VarPropScalar("frac", "", "fraction of Domain area or volume in specified range", attributes=(:initialize_to_zero=>true, :atomic=>true)), ] PB.add_method_do!(rj, do_area_volume_in_range, (PB.VarList_namedtuple(vars),)) PB.add_method_initialize_zero_vars_default!(rj) return nothing end function do_area_volume_in_range(m::PB.ReactionMethod, pars, (vars,), cellrange::PB.AbstractCellRange, deltat) # use a subtotal to minimise time lock held if this is one tile of a threaded model frac_subtotal = zero(vars.frac[]) @inbounds for i in cellrange.indices if vars.rangevar[i] >= pars.range_min[] && vars.rangevar[i] <= pars.range_max[] frac_subtotal += vars.measure[i] # normalisation by measure_total below end end PB.atomic_add!(vars.frac, frac_subtotal/vars.measure_total[]) return nothing end end # module
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
9031
import Infiltrator """ 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`](@ref) and [`add_method_do!`](@ref). 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!`](@ref), 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!`](@ref) to add metadata to `ratevartemplate`. # Examples: Create a `RateStoich` representing the reaction 2 O2 + H2S -> H2SO4 ```jldoctest; setup = :(import PALEOboxes) julia> myratevar = PALEOboxes.VarProp("myrate", "mol yr-1", "a rate"); 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")) ``` """ mutable struct RateStoich "template to define rate variable name, units, etc" ratevartemplate::Union{VarPropT, VarDepT} "label for output analysis (ratevar :rate_processname attribute)" processname::String "Tuple of (stoich, statevarname) eg ((-2.0, \"O2\"), (-1.0, \"H2S\"), (1.0, \"SO4\"))" stoich_statevarname::Tuple sms_prefix::String sms_suffix::String "Tuple (delta_varname, eta)" deltavarname_eta isotope_data::Type "construct a new RateStoich" function RateStoich( ratevartemplate::Union{VarPropT, VarDepT}, stoich_statevarname; processname="", sms_prefix="", sms_suffix="_sms", deltavarname_eta=nothing, add_rate_stoichiometry=true, ) rs = new( ratevartemplate, processname, stoich_statevarname, sms_prefix, sms_suffix, deltavarname_eta, UndefinedData, ) if add_rate_stoichiometry add_rate_stoichiometry!(ratevartemplate, rs) end return rs end end """ get_stoich_statevarname(reactantnames, prodnames) -> stoich_statevarname Convert collections of reactant and product names (which may be duplicated) to reaction stoichiometry in form suitable to create a [`RateStoich`](@ref). Returns Tuple of (stoich, statevarname) eg ((-2.0, \"O2\"), (-1.0, \"H2S\"), (1.0, \"SO4\"))" """ function get_stoich_statevarname(reactantnames, prodnames) stoich = Dict{String, Float64}() for s in reactantnames stoich[s] = get(stoich, s, 0) - 1 end for s in prodnames stoich[s] = get(stoich, s, 0) + 1 end stoich_statevarname = Tuple((n, s) for (s, n) in stoich) return stoich_statevarname end function add_method_do!(reaction::AbstractReaction, ratestoich::RateStoich; kwargs...) method = create_ratestoich_method(reaction, ratestoich; kwargs...) add_method_do!(reaction, method) return method end """ create_ratestoich_method(reaction::AbstractReaction, ratestoich::RateStoich; isotope_data=ScalarData) -> ReactionMethod Create method (see [`RateStoich`](@ref)). """ function create_ratestoich_method( @nospecialize(reaction::AbstractReaction), ratestoich::RateStoich; isotope_data=ScalarData, ignore_unlinked=true, operatorID=reaction.operatorID, domain=reaction.domain ) ratevarlocalname = ratestoich.ratevartemplate.localname # used for diagnostic info space = get_attribute(ratestoich.ratevartemplate, :space) # if isotopes in use, create _delta variable do_isotopes = (isotope_data <: AbstractIsotopeScalar) && !isnothing(ratestoich.deltavarname_eta) if do_isotopes ratestoich.isotope_data = isotope_data delta_varname, tmpeta = ratestoich.deltavarname_eta if tmpeta isa Parameter etapar = tmpeta else etapar = ParDouble("eta", tmpeta, units="per mil", description="constant eta") end delta_var = VarDep(delta_varname, "per mil", "generated by RateStoich.rate="*ratevarlocalname, attributes=(:space=>space,)) else ratestoich.isotope_data = ScalarData etapar = nothing delta_var = nothing end isotope_dict = Dict("Isotope" => ratestoich.isotope_data) # iterate through the flux variables in stoich_statevarname and create if necessary vars_sms = VariableReaction[] vars_stoich = Float64[] for (stoich, statevarnamefull) in ratestoich.stoich_statevarname # parse out ::Isotope, substituting with ratestoich.isotope_data statevarname, disotope = split_nameisotope(statevarnamefull, isotope_dict) # construct name for flux variable smsname = ratestoich.sms_prefix*statevarname*ratestoich.sms_suffix smsname = ignore_unlinked ? "("*smsname*")" : smsname # create variable push!( vars_sms, VarContrib(smsname, "mol yr-1", "generated by RateStoich rate="*ratevarlocalname, attributes=(:field_data=>disotope, :space=>space,)) ) push!(vars_stoich, stoich) end p = ( etapar, vars_stoich, ratestoich, ) return ReactionMethod( do_react_ratestoich, reaction, "RateStoich_"*ratevarlocalname, ( VarList_single(VarDep(ratestoich.ratevartemplate)), isnothing(delta_var) ? VarList_nothing() : VarList_single(delta_var), VarList_tuple(vars_sms), ), p, operatorID, domain ) end """ 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` """ function add_rate_stoichiometry!( ratevar, ratestoich::RateStoich, ) isa(ratevar, VarPropT) || @warn "add_rate_stoichiometry! ratevar $(fullname(ratevar)) is not a Property Variable, metadata will be ignored" set_attribute!(ratevar, :rate_processname, ratestoich.processname; allow_create=true) rate_species = String[species for (stoich, species) in ratestoich.stoich_statevarname] set_attribute!(ratevar, :rate_species, rate_species; allow_create=true) rate_stoichiometry = Float64[stoich for (stoich, species) in ratestoich.stoich_statevarname] set_attribute!(ratevar, :rate_stoichiometry, rate_stoichiometry; allow_create=true) return nothing end """ do_react_ratestoich(m::ReactionMethod, vardata, cellrange, deltat) Calculate rates for reaction products defined by a [`RateStoich`](@ref). `ratestoich_accessor` should be a NamedTuple generated by [`create_accessors`](@ref). """ function do_react_ratestoich(m::ReactionMethod, (rate, delta, sms_data), cellrange, deltat) (etapar, sms_stoich, _) = m.p IteratorUtils.foreach_longtuple_p(_do_sms, sms_data, sms_stoich, (cellrange, etapar, rate, delta)) return nothing end function _do_sms(sms_data, stoich, (cellrange, etapar, rate, delta)) isotype = eltype(sms_data) # @Infiltrator.infiltrate if isotype <: AbstractIsotopeScalar eta = etapar[] @inbounds for idx in cellrange.indices sms_data[idx] += isotope_totaldelta(isotype, stoich*rate[idx], delta[idx] + eta) end else @inbounds for idx in cellrange.indices sms_data[idx] += stoich*rate[idx] end end return nothing end # ignore unlinked Variables function _do_sms(sms_data::Nothing, stoich, p) return nothing end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
8298
############################## # Default setup methods (optional) ############################## """ 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" """ function add_method_setup_initialvalue_vars_default!( react::AbstractReaction, variables; filterfn=var -> get_attribute(var, :vfunction) in (VF_StateExplicit, VF_State, VF_Total,VF_StateTotal, VF_Constraint), force_initial_norm_value=false, transfer_attribute_vars = [], convertvars = [], convertfn = (convertvars_tuple, i) -> 1.0, convertinfo = "", setup_callback = (method, attribute_name, var, vardata) -> nothing, ) isempty(transfer_attribute_vars) || length(variables) == length(transfer_attribute_vars) || error("transfer_attribute_vars list is not the same length as variables list") setup_vars = [] setup_transfer_vars = [] for i in eachindex(variables) var = variables[i] if filterfn(var) push!(setup_vars, var) isempty(transfer_attribute_vars) || push!(setup_transfer_vars, VarDep(transfer_attribute_vars[i])) end end add_method_setup!( react, setup_initialvalue_vars_default, (VarList_fields(setup_vars), VarList_tuple(setup_transfer_vars), VarList_tuple(convertvars)), p = (force_initial_norm_value, convertfn, convertinfo, setup_callback), ) return nothing end """ setup_initialvalue_vars_default Initialize Variables to (`:initial_value` or `:norm_value`) [* convertfn] at beginning of integration. """ function setup_initialvalue_vars_default( m::ReactionMethod, (varfields, transfervardata, convertvarsdata), cellrange::AbstractCellRange, attribute_name ) (force_initial_norm_value, convertfn, convertinfo, setup_callback) = m.p # VariableReactions corresponding to (vardata, transfervardata, convertvarsdata) vars, transfer_attribute_vars, convertvars = get_variables_tuple(m) domvars = [v.linkvar for v in vars] # get_attributes from Domain var, as only 'master' Reaction var will be updated if isempty(transfer_attribute_vars) attrbvars = domvars else attrbvars = [v.linkvar for v in transfer_attribute_vars] end first_var = true for (rv, v, attrbv, vfield) in IteratorUtils.zipstrict(vars, domvars, attrbvars, varfields) vfunction = get_attribute(v, :vfunction, VF_Undefined) if vfunction == VF_Undefined && !force_initial_norm_value # non-state Variables are initialized in :setup, from :initial_value attribute attribute_name == :setup || continue attribute_to_read = :initial_value else # state Variables etc are initialized in :initial_value, :norm_value, from that attribute attribute_name in (:initial_value, :norm_value) || continue attribute_to_read = attribute_name end if first_var @info "$(fullname(m)):" first_var = false end if v === attrbv trsfrinfo = "" else trsfrinfo = " [from $(fullname(attrbv))]" end init_field!( vfield, attribute_to_read, attrbv, convertfn, convertvarsdata, cellrange, (fullname(v), convertinfo, trsfrinfo) ) setup_callback(m, attribute_name, rv, vfield.values) end return nothing end ############################## # Default initialize methods (optional) ############################## """ 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?) """ function add_method_initialize_zero_vars_default!( react::AbstractReaction, variables=get_variables(react); filterfn=v->get_attribute(v, :initialize_to_zero, false) ) init_vars = [] for var in variables if filterfn(var) push!(init_vars, VarInit(var)) end end add_method_initialize!( react, initialize_zero_vars_default, ( VarList_fields(init_vars), ), ) return nothing end """ initialize_zero_vars_default Initialize variables at beginning of timestep """ function initialize_zero_vars_default( m::ReactionMethod, (init_fields,), cellrange::AbstractCellRange, deltat ) IteratorUtils.foreach_longtuple_p(zero_field!, init_fields, cellrange) return nothing end ################################ # do nothing method ################################# """ add_method_do_nothing!(react::AbstractReaction, variables) Create and add a dummy method to define Variables only. """ function add_method_do_nothing!(react::AbstractReaction, variables) add_method_do!( react, methodfn_do_nothing, (VarList_tuple(variables),) ) return nothing end methodfn_do_nothing(m::ReactionMethod, (vars, ), cellrange::AbstractCellRange, deltat) = nothing is_do_nothing(m::ReactionMethod) = false is_do_nothing(m::ReactionMethod{typeof(methodfn_do_nothing)}) = true ############################################### # Thread barrier method (PALEOboxes internal use only) ############################################### function do_method_barrier(m::ReactionMethod, _, _, _) (barrier, barrierfn) = m.p barrierfn(barrier) return nothing end """ reaction_method_thread_barrier(barrier) Create a ReactionMethod holding a thread barrier `barrier`. """ function reaction_method_thread_barrier(barrier, barrierfn) return ReactionMethod( do_method_barrier, NoReaction(), "thread_barrier", (VarList_nothing(),), (barrier, barrierfn), # p [-1], Domain(name="thread_barrier", ID=-1, parameters=Dict{String, Any}()), ) end is_do_barrier(m::ReactionMethod) = false is_do_barrier(m::ReactionMethod{typeof(do_method_barrier)}) = true
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
5398
""" 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!`](@ref) """ function add_method_do_totals_default!( reaction::AbstractReaction, total_candidates=get_variables(reaction); kwargs... ) return add_method_do!( reaction, create_totals_method(reaction, total_candidates; kwargs...), ) end """ create_totals_method(reaction, var; [methodname] [, total_localname] [, operatorID]) -> ReactionMethod Create a method to add a total variable (Scalar Property) to `reaction` for `var`. If `total_localname` is not supplied, it will be generated by appending `_total` to `var.localname`. NB: total Variables will require initialization to zero using [`add_method_initialize_zero_vars_default!`](@ref) """ function create_totals_method( reaction::AbstractReaction, var::VariableReaction; methodname="totals", total_localname=nothing, operatorID=reaction.operatorID ) return _create_totals_method( reaction, methodname, ([var], [create_totalvar(var, total_localname)]), operatorID ) end """ create_totals_method(reaction, total_candidates; [filterfn] [, methodname] [, total_localnames] [, operatorID]) -> ReactionMethod Create a method to add total variables (Scalar Properties), for Variables in `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!`](@ref) """ function create_totals_method( reaction::AbstractReaction, total_candidates; filterfn=v->get_attribute(v, :calc_total, false), methodname="totals", total_localnames=nothing, operatorID=reaction.operatorID ) if isnothing(total_localnames) # remove duplicates (eg from setup and do methods) vars_all = Dict(v.localname =>v for v in total_candidates if filterfn(v)) vars = [v for (k, v) in vars_all] else # check no filtering if total_localnames supplied vars = [v for v in total_candidates if filterfn(v)] length(vars) == length(total_candidates) || error("create_totals_method: configuration error, Reaction $(fullname(reaction)), filterfn not supported with total_localnames") length(total_localnames) == length(vars) || error("create_totals_method: configuration error, Reaction $(fullname(reaction)) length(total_localnames) != number of total Variables") end var_totals = [] for (idx, v) in enumerate(vars) if isnothing(total_localnames) total_localname = nothing else total_localname = total_localnames[idx] end push!(var_totals, create_totalvar(v, total_localname)) end return _create_totals_method( reaction, methodname, (vars, var_totals), operatorID ) end function create_totalvar(var, total_localname=nothing) if isnothing(total_localname) total_localname = var.localname*"_total" end return VarPropScalar(total_localname, get_attribute(var, :units), "total "*get_attribute(var, :description), attributes=(:field_data=>get_attribute(var, :field_data), :initialize_to_zero=>true, :atomic=>true), ) end """ do_vartotals(varstats, varstats_data, cellrange::AbstractCellRange) Calculate totals. `varstats_data` is `accessors` returned by `create_accessors`. Call from the `ReactionPhase` supplied to [`add_var`](@ref). """ function do_vartotals(m::AbstractReactionMethod, (vars_data, var_totals_data), cellrange::AbstractCellRange, deltat) function calc_total(data, total_data, cellrange) # accumulate first into a subtotal, and then into total_data[], in order to minimise time spent with lock held # if this is one tile of a threaded model subtotal = zero(total_data[]) @inbounds for i in cellrange.indices subtotal += data[i] end atomic_add!(total_data, subtotal) return nothing end length(vars_data) == length(var_totals_data) || error("do_vartotals: components length mismatch $(fullname(m)) $(get_variables_tuple(m)) (check :field_data (ScalarData, IsotopeLinear etc) match)") # if cellrange.operatorID == 0 || cellrange.operatorID in totals_method.operatorID for iv in eachindex(vars_data) calc_total(vars_data[iv], var_totals_data[iv], cellrange) end # end return nothing end function _create_totals_method( reaction::AbstractReaction, methodname::AbstractString, (vars, var_totals), operatorID, ) return ReactionMethod( do_vartotals, reaction, methodname, (VarList_components(VarDep.(vars)), VarList_components(var_totals)), nothing, operatorID, reaction.domain ) end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
4521
""" DocStrings Extends Julia `DocStringExtensions` package to provide PALEO-specific "Abbreviations" to list Reaction Parameters and Variables in docstrings. exports PARS, METHODS_SETUP, METHODS_INITIALIZE, METHODS_DO `\$(PARS)` expands to a list of Reaction Parameters `\$(METHODS_SETUP)`, `\$(METHODS_INITIALIZE)`, `\$(METHODS_DO)` expand to a list of ReactionMethods and Variables NB: a Reaction is created with `create_reaction`. In addition, `\$(METHODS_DO)` etc call `register_methods(rj::AbstractReaction)`, so may fail if this call fails with default parameters. """ module DocStrings import DocStringExtensions as DSE import PALEOboxes as PB struct Pars <: DSE.Abbreviation end const PARS = Pars() function DSE.format(::Pars, buf, doc) local docs = get(doc.data, :fields, Dict()) local binding = doc.data[:binding] local object = Docs.resolve(binding) # println(buf, "PARS binding $binding object $object") try rj = PB.create_reaction(object, PB.ReactionBase(name="test", classname="test", external_parameters=Dict{String, Any}())) if hasproperty(rj, :pars) PB.add_par(rj, rj.pars) end # println(buf, "$object $(length(PB.get_parameters(rj))) Parameters" ) for p in PB.get_parameters(rj) md = "- `$(p.name)[" md *= p.external ? "external, " : "" md *= "$(typeof(p.v))]`=" md *= md_value(p.v) md *= isempty(p.units) ? "," : " ($(p.units))," md *= " `default_value`="*md_value(p.default_value)*"," md *= isempty(p.allowed_values) ? "" : " `allowed_values`=$(p.allowed_values)," md *= " `description`=\"$(PB.escape_markdown(p.description))\"" println(buf, md) end catch e println(buf, PB.escape_markdown("PARS exception: $e")) end return nothing end struct Methods <: DSE.Abbreviation field::Symbol end const METHODS_SETUP = Methods(:methods_setup) const METHODS_INITIALIZE = Methods(:methods_initialize) const METHODS_DO = Methods(:methods_do) function DSE.format(methods::Methods, buf, doc) local docs = get(doc.data, :fields, Dict()) local binding = doc.data[:binding] local object = Docs.resolve(binding) try # println(buf, "PARS binding $binding object $object") rj = PB.create_reaction(object, PB.ReactionBase(name="test", classname="test", external_parameters=Dict{String, Any}())) if hasproperty(rj, :pars) PB.add_par(rj, rj.pars) end d = PB.Domain(name="test", ID=1, parameters=Dict{String, Any}()) rj.base.domain = d PB.register_methods!(rj) for m in getproperty(rj.base, methods.field) println(buf, "- `$(m.name)`") for v in PB.get_variables(m) md = " - " md *= v.link_optional ? "\\[" : "" md *= "`$(v.localname)`" md *= v.link_optional ? "\\]" : "" ln = PB.combine_link_name(v) md *= (ln == v.localname) ? "" : " --> $(PB.escape_markdown(ln))" units = PB.get_attribute(v, :units) md *= " ($(units))," md *= " `$(PB.get_var_type(v))`," vfunction = PB.get_attribute(v, :vfunction) md *= (ismissing(vfunction) || vfunction == PB.VF_Undefined) ? "" : " `$vfunction`," description = PB.get_attribute(v, :description) md *= " `description`=\"$(PB.escape_markdown(description))\"" println(buf, md) end end catch e println(buf, PB.escape_markdown("METHODS $methods exception: $e")) end return nothing end md_value(v) = "$v" md_value(v::AbstractString) = "\"$(PB.escape_markdown(v))\"" function md_value(vv::Vector{<:AbstractString}) evv = [PB.escape_markdown(v) for v in vv] return "$evv" end function md_value(vv::Vector) str = "$vv" str = replace(str, "["=>"\\[") str = replace(str, "]"=>"\\]") return str end export PARS, METHODS_SETUP, METHODS_INITIALIZE, METHODS_DO end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
3204
""" collate_markdown( io, inputpath, docspath, src_folderpath; includes=String[], includename="doc_include.jl", imagesdirs=["images"] ) -> (pages::Vector, includes::Vector{String}) Recursively look through `inputpath` and subfolders for: - markdown files (`.md` extension), - code files with name matching `includename` - folders with name in `imagesdirs` - a text file "doc_order.txt" and then: - copy markdown files and folders in `imagedirs` to subfolders under `<docspath>/src/<src_folderpath>` - return a `pages::Vector` suitable to build a tree structure for `Documenter.jl`, where each element is either a path to a markdown file, or a pair `folder_name => Vector`, sorted according to "doc_order.txt" if present, or otherwise with "README.md" first and then in lexographical order. - return an `includes::Vector` of code files that should be included to define modules etc """ function collate_markdown( io::IOBuffer, inputpath::AbstractString, docspath::AbstractString, src_folderpath::AbstractString; includes=String[], includename="doc_include.jl", imagesdirs=["images"], sortpref=["README.md"], ) docs = Any[] filenames_read = readdir(inputpath) # if a text file defining order is present, then that overrides sortpref if "doc_order.txt" in filenames_read orderpath = normpath(inputpath, "doc_order.txt") sortpref = readlines(orderpath) println(io, "sorting in order $sortpref from file $orderpath") end # put any names in sortpref at the front of the list filenames_sort = String[] for fn in sortpref if fn in filenames_read push!(filenames_sort, fn) end end for fn in filenames_read if ! (fn in filenames_sort) push!(filenames_sort, fn) end end for fn in filenames_sort inpath = normpath(inputpath, fn) src_relpath = joinpath(src_folderpath, fn) outpath = normpath(docspath, "src", src_relpath) if isdir(inpath) if fn in imagesdirs println(io, "cp $inpath --> $outpath") mkpath(dirname(outpath)) cp(inpath, outpath; force=true) else subdocs, _ = collate_markdown( io, inpath, docspath, src_relpath; includes=includes, imagesdirs=imagesdirs ) !isempty(subdocs) && push!(docs, escape_markdown(fn)=>subdocs) end else if length(fn) >= 3 && fn[end-2:end] == ".md" push!(docs, src_relpath) # path relative to <docspath>/src/ println(io, "cp $inpath --> $outpath") mkpath(dirname(outpath)) cp(inpath, outpath; force=true) elseif fn == includename push!(includes, inpath) end end end return (docs, includes) end function escape_markdown(str::AbstractString) str = replace(str, "_"=>"\\_") str = replace(str, "\$"=>"\\\$") str = replace(str, "*"=>"\\*") return str end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
4366
""" LinInterp(xvals, xperiod=0.0; require_sorted_input=true) -> LinInterp Create a `LinInterp` struct for generic linear interpolation for (scalar) value `xval` into a set of records at `xvals`. [`interp`](@ref) calculates weights and indices for the two records enclosing `xval`, hence allows use for arbitrary record types. # Args: - `xvals::Vector`: x values at which function is available. - `xperiod=0.0`: Periodicity of x values (0.0 for not periodic) - `require_sorted_input::Bool=true`: to check that input is sorted in ascending order, `false` to allow arbitrary order (which will then be sorted for internal use). """ struct LinInterp "supplied values at each record index" xvals::Vector{Float64} "optional periodicity (0.0 means not periodic)" xperiod::Float64 "modified values, mapped to `xperiod`, sorted in order, and padded at each end" _xvals::Vector{Float64} "record indices corresponding to _xvals" _recidx::Vector{Int} "out-of-range values set to constant" _extrap_const::Bool function LinInterp(xvals, xperiod=0.0; require_sorted_input=true, extrap_const=false) if require_sorted_input issorted(xvals) || error("`xvals` not sorted and `require_sorted_input==true`") end if xperiod > 0.0 && xperiod < Inf # periodic - normalize, sort, and pad normxvals = mod.(xvals, Float64(xperiod)) # all normxvals now in range 0 - xperiod p = sortperm(normxvals) # if xvals contained eg out-of-range values, normxvals will now be out of ascending order _xvals = zeros(length(normxvals)+2) _xvals[2:end-1] = normxvals[p] _recidx = zeros(Int, length(normxvals)+2) _recidx[2:end-1] = p # pad (these values will be outside range 0 - xperiod) _xvals[1] = _xvals[end-1] - xperiod _xvals[end] = _xvals[2] + xperiod _recidx[1] = _recidx[end-1] _recidx[end] = _recidx[2] # check sorted (failure not expected here) issorted(_xvals) || error("programming error: normalized periodic xvalues not sorted xvals=$xvals, _xvals=$_xvals") elseif xperiod == 0.0 p = sortperm(xvals) _xvals = xvals[p] _recidx = p else error("invalid `xperiod` $xperiod") end return new(copy(xvals), xperiod, _xvals, _recidx, extrap_const) end end """ interp(lininterp::LinInterp, xval) -> ((wt_lo, recidx_lo), (wt_hi, recidx_hi)) Linear interpolation for (scalar) value `xval`. See [`LinInterp`](@ref). """ function interp(lininterp::LinInterp, xval) if lininterp.xperiod != 0.0 # AD workaround (ForwardDiff generates NaN for derivative if on mod boundary ?) # as we know the solution is periodic. xval_val = mod(value_ad(xval), lininterp.xperiod) # sign of divisor ie +ve xval += xval_val - value_ad(xval) end # Return the index of the last value in a less than or equal to x idx = searchsortedlast(lininterp._xvals, xval) # exact equality to last record means we need the previous record (as we take a linear combination of idx and idx+1) if idx==length(lininterp._xvals) && xval == lininterp._xvals[end] idx -= 1 end if idx == 0 if lininterp._extrap_const idx = 1 xval = lininterp._xvals[1] else error("xval out of range") end end if idx == length(lininterp._xvals) if lininterp._extrap_const idx = length(lininterp._xvals) - 1 xval = lininterp._xvals[end] else error("xval out of range") end end x_lo = lininterp._xvals[idx] x_hi = lininterp._xvals[idx+1] rec_lo = lininterp._recidx[idx] rec_hi = lininterp._recidx[idx+1] wt_lo = (x_hi - xval)/(x_hi - x_lo) wt_hi = (xval - x_lo)/(x_hi - x_lo) return ((wt_lo, rec_lo), (wt_hi, rec_hi)) end """ interp(lininterp::LinInterp, xval, yvals) -> yval Linear interpolation for (scalar) value `xval`. See [`LinInterp`](@ref). """ function interp(lininterp::LinInterp, xval, yvals) (wt_lo, rec_lo), (wt_hi, rec_hi) = interp(lininterp, xval) yval = wt_lo*yvals[rec_lo] + wt_hi*yvals[rec_hi] return yval end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
15043
module IteratorUtils """ check_lengths_equal(it1, it2) check_lengths_equal(it1, it2, it3) check_lengths_equal(it1, it2, it3, it4) check_lengths_equal(it1, it2, it3, it4, it5) check_lengths_equal(it1, it2, it3, it4, it5, it6) Error if iterables it1 ... itn do not have the same length (length(t1) == length(t2) == ...) """ @inline check_lengths_equal(it1) = (length(it1); true) @inline check_lengths_equal(it1, it2; errmsg="lengths differ") = length(it1) == length(it2) || throw(ArgumentError(errmsg)) @inline check_lengths_equal(it1, it2, it3; errmsg="lengths differ") = length(it1) == length(it2) == length(it3) || throw(ArgumentError(errmsg)) @inline check_lengths_equal(it1, it2, it3, it4; errmsg="lengths differ") = length(it1) == length(it2) == length(it3) == length(it4) || throw(ArgumentError(errmsg)) @inline check_lengths_equal(it1, it2, it3, it4, it5; errmsg="lengths differ") = length(it1) == length(it2) == length(it3) == length(it4) == length(it5) || throw(ArgumentError(errmsg)) @inline check_lengths_equal(it1, it2, it3, it4, it5, it6; errmsg="lengths differ") = length(it1) == length(it2) == length(it3) == length(it4) == length(it5) == length(it6) || throw(ArgumentError(errmsg)) @inline check_lengths_equal(it1, it2, it3, it4, it5, it6, it7; errmsg="lengths differ") = length(it1) == length(it2) == length(it3) == length(it4) == length(it5) == length(it6) == length(it7) || throw(ArgumentError(errmsg)) @inline check_lengths_equal(it1, it2, it3, it4, it5, it6, it7, it8; errmsg="lengths differ") = length(it1) == length(it2) == length(it3) == length(it4) == length(it5) == length(it6) == length(it7) == length(it8) || throw(ArgumentError(errmsg)) """ zipstrict(iters...; errmsg="iterables lengths differ") `Base.zip` with additional check that lengths of iterables are equal. """ @inline zipstrict(iters...; errmsg="iterables lengths differ") = (check_lengths_equal(iters...; errmsg=errmsg); zip(iters...)) """ named_tuple_ref(keys, eltype) Construct a "mutable NamedTuple" with `keys` where `values` are of type Ref{eltype}. Access values as nt.x[] etc """ function named_tuple_ref(keys, eltype) return NamedTuple{keys}([Ref{eltype}() for i in 1:length(keys)]) end """ foreach_tuple(f, t1::Tuple; errmsg="iterables lengths differ") foreach_tuple(f, t1::Tuple, t2; errmsg="iterables lengths differ") Call `f(t1[n])` for each element `n` of `t1::Tuple`. Call `f(t1[n], t2[n])` for each element `n` of `t1::Tuple`, `t2::Tuple`. # Implementation Recursively generates inline code for speed and type stability. # Limitations As of Julia 1.6, slows down and allocates if `length(t1) > 32` due to Julia limitation. See [`foreach_longtuple`](@ref). See https://github.com/JuliaLang/julia/issues/31869 https://github.com/JuliaLang/julia/blob/master/base/tuple.jl (map implementation) """ @inline foreach_tuple(f::F, tuples...; errmsg="iterables lengths differ") where{F} = (check_lengths_equal(tuples...; errmsg=errmsg); foreach_tuple_unchecked(f, tuples...)) foreach_tuple_unchecked(f, t1::Tuple{}) = () foreach_tuple_unchecked(f, t1::Tuple{Any, }) = (@Base._inline_meta; f(t1[1]); nothing) foreach_tuple_unchecked(f, t1::Tuple) = (@Base._inline_meta; f(t1[1]); foreach_tuple_unchecked(f, Base.tail(t1)); nothing) foreach_tuple_unchecked(f, t1::Tuple{}, tv2) = () foreach_tuple_unchecked(f, i::Int64, t1::Tuple{Any, }, tv2) = (@Base._inline_meta; f(t1[1], tv2[i]); nothing) foreach_tuple_unchecked(f, i::Int64, t1::Tuple, tv2) = (@Base._inline_meta; f(t1[1], tv2[i]); foreach_tuple_unchecked(f, i+1, Base.tail(t1), tv2); nothing) foreach_tuple_unchecked(f, t1::Tuple, tv2) = (@Base._inline_meta; foreach_tuple_unchecked(f, 1, t1, tv2); nothing) @inline foreach_tuple_p(f::F, t1, p; errmsg="iterables lengths differ") where{F} = foreach_tuple_unchecked_p(f, t1, p) foreach_tuple_unchecked_p(f, t1::Tuple{}, p) = () foreach_tuple_unchecked_p(f, t1::Tuple{Any, }, p) = (@Base._inline_meta; f(t1[1], p); nothing) foreach_tuple_unchecked_p(f, t1::Tuple, p) = (@Base._inline_meta; f(t1[1], p); foreach_tuple_unchecked_p(f, Base.tail(t1), p); nothing) @inline foreach_tuple_p(f::F, t1, tv2, p; errmsg="iterables lengths differ") where{F} = (check_lengths_equal(t1, tv2; errmsg=errmsg); foreach_tuple_unchecked_p(f, 1, t1, tv2, p)) foreach_tuple_unchecked_p(f, t1::Tuple{}, tv2, p) = () foreach_tuple_unchecked_p(f, i::Int, t1::Tuple{Any, }, tv2, p) = (@Base._inline_meta; f(t1[1], tv2[i], p); nothing) foreach_tuple_unchecked_p(f, i::Int, t1::Tuple, tv2, p) = (@Base._inline_meta; f(t1[1], tv2[i], p); foreach_tuple_unchecked_p(f, i+1, Base.tail(t1), tv2, p); nothing) foreach_tuple_unchecked_p(f, t1::Tuple, tv2, p) = (@Base._inline_meta; foreach_tuple_unchecked_p(f, 1, t1, tv2, p); nothing) """ foreach_longtuple(f, t1::Tuple, t2, ... tm; errmsg="iterables lengths differ") foreach_longtuple_p(f, t1::Tuple, t2, ... tm, p; errmsg="iterables lengths differ") Call `f(t1[n], t2[n], ... tm[n])` or `f(t1[n], t2[n], ... tm[n], p)` for each element `n` of `t1::Tuple`, `t2`, ... `tm`. # Examples Here `input_concs_cell` and `input_concs` are `NamedTuple`s. PB.IteratorUtils.foreach_longtuple(values(input_concs_cell), values(input_concs)) do ic_cell, ic ic_cell[] = r_rhofac*ic[i] # generates a closure with r_rhofac as a captured variable end # closure with r_rhofac as a captured variable function f(ic_cell, ic) ic_cell[] = r_rhofac*ic[i] end PB.IteratorUtils.foreach_longtuple(f, values(input_concs_cell), values(input_concs)) PB.IteratorUtils.foreach_longtuple_p(values(input_concs_cell), values(input_concs), r_rhofac) do ic_cell, ic, _r_rhofac ic_cell[] = _r_rhofac*ic[i] # no closure with _r_rhofac as an argument end # no closure with _r_rhofac as an argument function f(ic_cell, ic, _r_rhofac) ic_cell[] = _r_rhofac*ic[i] end PB.IteratorUtils.foreach_longtuple_p(f, values(input_concs_cell), values(input_concs), r_rhofac) # Limitations See Julia performance tips: - There are potential problems with captured variables when using a closure as `f`, either explicitly or using do block syntax. It is usually safer to explicitly write out `f` with all arguments, and pass them in using `foreach_longtuple_p`, using `p::Tuple` for multiple arguments. - Passing type parameters to `f` is prone to creating additional problems if `f` is not specialized, which happens: - if `f` is either an explicit closure or is a closure created using do block syntax - if a type parameter is passed as a member of `p::Tuple` - if a type parameter is passed as `p`, but `f` is not explicitly specialized using `p::Type{MyType}` and `f` is not inlined (do block syntax does appear to work) It is safest to either explicitly specialize `f` on a type parameter using `p::Type{MyType}`, or avoid passing type parameters and eg use eltype to derive them. # Allocates: generates a closure with BufType as a captured variable, with no specialization PB.IteratorUtils.foreach_longtuple(values(input_concs_cell), values(input_concs)) do ic_cell, ic ic_cell[] = convert(BufType, ic[i]) # allocates end # OK: no closure, with explicit specialization on BufType argument function f(ic_cell, ic, ::Type{BufType}) where {BufType} # force specialization ic_cell[] = convert(BufType, ic[i]) end PB.IteratorUtils.foreach_longtuple_p(f, values(input_concs_cell), values(input_concs), BufType) # Allocates: no closure, but BufType is a Tuple member so is passed as a `DataType` hence no specialization function f(ic_cell, ic, (BufType, r_rhofac)) ic_cell[] = r_rhofac*convert(BufType, ic[i]) end PB.IteratorUtils.foreach_longtuple_p(f, values(input_concs_cell), values(input_concs), (r_rhofac, BufType)) # Implementation Uses `@generated` to generate unrolled code for speed and type stability without length restrictions on `tm`. See https://discourse.julialang.org/t/manually-unroll-operations-with-objects-of-tuple/11604 """ @inline foreach_longtuple(f::F, tuples...; errmsg="iterables lengths differ") where{F} = (check_lengths_equal(tuples...; errmsg=errmsg); foreach_longtuple_unchecked(f, tuples...)) @generated function foreach_longtuple_unchecked(f, t1::Tuple) ex = quote ; end # empty expression for j=1:fieldcount(t1) push!(ex.args, quote; f(t1[$j]); end) end push!(ex.args, quote; return nothing; end) return ex end @generated function foreach_longtuple_unchecked(f, t1::Tuple, t2) ex = quote ; end # empty expression for j=1:fieldcount(t1) push!(ex.args, quote; f(t1[$j], t2[$j]); end) end push!(ex.args, quote; return nothing; end) return ex end @generated function foreach_longtuple_unchecked(f, t1::Tuple, t2, t3) ex = quote ; end # empty expression for j=1:fieldcount(t1) push!(ex.args, quote; f(t1[$j], t2[$j], t3[$j]); end) end push!(ex.args, quote; return nothing; end) return ex end @generated function foreach_longtuple_unchecked(f, t1::Tuple, t2, t3, t4) ex = quote ; end # empty expression for j=1:fieldcount(t1) push!(ex.args, quote; f(t1[$j], t2[$j], t3[$j], t4[$j]); end) end push!(ex.args, quote; return nothing; end) return ex end @generated function foreach_longtuple_unchecked(f, t1::Tuple, t2, t3, t4, t5) ex = quote ; end # empty expression for j=1:fieldcount(t1) push!(ex.args, quote; f(t1[$j], t2[$j], t3[$j], t4[$j], t5[$j]); end) end push!(ex.args, quote; return nothing; end) return ex end @inline foreach_longtuple_p(f::F, t1, p; errmsg="iterables lengths differ") where{F} = foreach_longtuple_unchecked_p(f, t1, p) @generated function foreach_longtuple_unchecked_p(f, t1::Tuple, p) ex = quote ; end # empty expression for j=1:fieldcount(t1) push!(ex.args, quote; f(t1[$j], p); end) end push!(ex.args, quote; return nothing; end) return ex end @inline foreach_longtuple_p(f::F, t1, t2, p; errmsg="iterables lengths differ") where{F} = (check_lengths_equal(t1, t2; errmsg=errmsg); foreach_longtuple_unchecked_p(f, t1, t2, p)) @generated function foreach_longtuple_unchecked_p(f, t1::Tuple, t2, p) ex = quote ; end # empty expression for j=1:fieldcount(t1) push!(ex.args, quote; f(t1[$j], t2[$j], p); end) end push!(ex.args, quote; return nothing; end) return ex end @inline foreach_longtuple_p(f::F, t1, t2, t3, p; errmsg="iterables lengths differ") where{F} = (check_lengths_equal(t1, t2, t3; errmsg=errmsg); foreach_longtuple_unchecked_p(f, t1, t2, t3, p)) @generated function foreach_longtuple_unchecked_p(f, t1::Tuple, t2, t3, p) ex = quote ; end # empty expression for j=1:fieldcount(t1) push!(ex.args, quote; f(t1[$j], t2[$j], t3[$j], p); end) end push!(ex.args, quote; return nothing; end) return ex end @inline foreach_longtuple_p(f::F, t1, t2, t3, t4, p; errmsg="iterables lengths differ") where{F} = (check_lengths_equal(t1, t2, t3, t4; errmsg=errmsg); foreach_longtuple_unchecked_p(f, t1, t2, t3, t4, p)) @generated function foreach_longtuple_unchecked_p(f, t1::Tuple, t2, t3, t4, p) ex = quote ; end # empty expression for j=1:fieldcount(t1) push!(ex.args, quote; f(t1[$j], t2[$j], t3[$j], t4[$j], p); end) end push!(ex.args, quote; return nothing; end) return ex end @inline foreach_longtuple_p(f::F, t1, t2, t3, t4, t5, p; errmsg="iterables lengths differ") where{F} = (check_lengths_equal(t1, t2, t3, t4, t5; errmsg=errmsg); foreach_longtuple_unchecked_p(f, t1, t2, t3, t4, t5, p)) @generated function foreach_longtuple_unchecked_p(f, t1::Tuple, t2, t3, t4, t5, p) ex = quote ; end # empty expression for j=1:fieldcount(t1) push!(ex.args, quote; f(t1[$j], t2[$j], t3[$j], t4[$j], t5[$j], p); end) end push!(ex.args, quote; return nothing; end) return ex end @inline foreach_longtuple_p(f::F, t1, t2, t3, t4, t5, t6, p; errmsg="iterables lengths differ") where{F} = (check_lengths_equal(t1, t2, t3, t4, t5, t6; errmsg=errmsg); foreach_longtuple_unchecked_p(f, t1, t2, t3, t4, t5, t6, p)) @generated function foreach_longtuple_unchecked_p(f, t1::Tuple, t2, t3, t4, t5, t6, p) ex = quote ; end # empty expression for j=1:fieldcount(t1) push!(ex.args, quote; f(t1[$j], t2[$j], t3[$j], t4[$j], t5[$j], t6[$j], p); end) end push!(ex.args, quote; return nothing; end) return ex end @inline foreach_longtuple_p(f::F, t1, t2, t3, t4, t5, t6, t7, p; errmsg="iterables lengths differ") where{F} = (check_lengths_equal(t1, t2, t3, t4, t5, t6, t7; errmsg=errmsg); foreach_longtuple_unchecked_p(f, t1, t2, t3, t4, t5, t6, t7, p)) @generated function foreach_longtuple_unchecked_p(f, t1::Tuple, t2, t3, t4, t5, t6, t7, p) ex = quote ; end # empty expression for j=1:fieldcount(t1) push!(ex.args, quote; f(t1[$j], t2[$j], t3[$j], t4[$j], t5[$j], t6[$j], t7[$j], p); end) end push!(ex.args, quote; return nothing; end) return ex end @inline foreach_longtuple_p(f::F, t1, t2, t3, t4, t5, t6, t7, t8, p; errmsg="iterables lengths differ") where{F} = (check_lengths_equal(t1, t2, t3, t4, t5, t6, t7, t8; errmsg=errmsg); foreach_longtuple_unchecked_p(f, t1, t2, t3, t4, t5, t6, t7, t8, p)) @generated function foreach_longtuple_unchecked_p(f, t1::Tuple, t2, t3, t4, t5, t6, t7, t8, p) ex = quote ; end # empty expression for j=1:fieldcount(t1) push!(ex.args, quote; f(t1[$j], t2[$j], t3[$j], t4[$j], t5[$j], t6[$j], t7[$j], t8[$j], p); end) end push!(ex.args, quote; return nothing; end) return ex end """ reduce_longtuple(f, rinit, t1::Tuple, t2, ... tm; errmsg="iterables lengths differ") -> r Call `r += f(r, t1[n], t2[n], ... tm[n])` for each element `n` of `t1::Tuple`, `t2`, ... `tm`. Initial value of `r = rinit` # Implementation Uses `@generated` to generate unrolled code for speed and type stability without length restrictions on `tm`. See https://discourse.julialang.org/t/manually-unroll-operations-with-objects-of-tuple/11604 """ @inline reduce_longtuple(f::F, rinit, tuples...; errmsg="iterables lengths differ") where{F} = (check_lengths_equal(tuples...; errmsg=errmsg); reduce_longtuple_unchecked(f, rinit, tuples...)) @generated function reduce_longtuple_unchecked(f, rinit, t1::Tuple) ex = quote ; end # empty expression for j=1:fieldcount(t1) push!(ex.args, quote; rinit = f(rinit, t1[$j]); end) end push!(ex.args, quote; return rinit; end) return ex end @generated function reduce_longtuple_unchecked(f, rinit, t1::Tuple, t2) ex = quote ; end # empty expression for j=1:fieldcount(t1) push!(ex.args, quote; rinit = f(rinit, t1[$j], t2[$j]); end) end push!(ex.args, quote; return rinit; end) return ex end end # module
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
12632
""" SIMDutils Helper functions to pack and unpack vector data to enable use of SIMD instructions. """ module SIMDutils import SLEEF_jll import SIMD import Preferences ##################################### # Short names for packed vector Types ##################################### const FP64P4 = SIMD.Vec{4, Float64} const FP64P2 = SIMD.Vec{2, Float64} const FP32P8 = SIMD.Vec{8, Float32} const FP32P4 = SIMD.Vec{4, Float32} ###################################### # Iteration ###################################### """ SIMDIter(baseiter, Val{N}) SIMDIter(baseiter, ::Type{SIMD.Vec{N, U}}) SIMDIter(baseiter, ::Val{1}) # scalar fallback SIMDIter(baseiter, ::Type{U}) where {U <: Real} # scalar fallback Iterator that takes up to `N` SIMD elements at a time from `baseiter` (which should represent indices into a Vector). See Julia package [SIMD.jl](https://github.com/eschnett/SIMD.jl) If `baseiter` contained 1 or more but less then `N` elements, then `indices` is filled with repeats of the last available element. Returns Tuple of indices (length `N`). # Examples v_a = [1.0, 2.0, 3.0, 4.0, 5.0] v_b = similar(v_a) iter = eachindex(v_a) # iter should represent indices into a Vector # simplest version - Float64 x 4, ie type of v_a x 4 for i in SIMDIter(iter, Val(4)) x = v_a[i] # x is a packed SIMD vector v_b[i] = x end # with type conversion - Float32 x 8, ie explicitly change Type of SIMD vector ST = SIMD.Vec{8, Float32}} for i in SIMDIter(iter, ST) # v = vec[i] <--> vgatherind(ST, vec, i) # vec[i] = v <--> vscatterind!(v, vec, i) # vec[i] += v <--> vaddind!(v, vec, i) x = vgatherind(ST, v_a, i) # x is a packed SIMD vector with type conversion to Float32 vscatterind!(x, v_b, i) end """ struct SIMDIter{T, N} baseiter::T end SIMDIter(baseiter::T, ::Val{N}) where {T, N} = SIMDIter{T, N}(baseiter) SIMDIter(baseiter::T, ::Type{SIMD.Vec{N, U}}) where {T, N, U} = SIMDIter{T, N}(baseiter) # scalar fallback SIMDIter(baseiter, ::Val{1}) = baseiter SIMDIter(baseiter, ::Type{U}) where {U <: Real} = baseiter import Base.iterate iterate(iter::SIMDIter{T, N}) where {T, N} = _iterate(iter, iterate(iter.baseiter)) iterate(iter::SIMDIter{T, N}, state) where {T, N} = _iterate(iter, iterate(iter.baseiter, state)) _iterate(iter::SIMDIter{T, 2}, basenext::Nothing) where {T} = nothing function _iterate(iter::SIMDIter{T, 2}, basenext) where {T} local i1::Int64, i2::Int64 (i1, state) = basenext basenext = iterate(iter.baseiter, state) if isnothing(basenext); i2 = i1; else; (i2, state) = basenext; end return (SIMD.Vec((i1, i2)), state) end _iterate(iter::SIMDIter{T, 4}, basenext::Nothing) where {T} = nothing function _iterate(iter::SIMDIter{T, 4}, basenext) where {T} local i1::Int64, i2::Int64, i3::Int64, i4::Int64 (i1, state) = basenext basenext = iterate(iter.baseiter, state) if isnothing(basenext); i2 = i1; else; (i2, state) = basenext; end basenext = iterate(iter.baseiter, state) if isnothing(basenext); i3 = i2; else; (i3, state) = basenext; end basenext = iterate(iter.baseiter, state) if isnothing(basenext); i4 = i3; else; (i4, state) = basenext; end return (SIMD.Vec((i1, i2, i3, i4)), state) end _iterate(iter::SIMDIter{T, 8}, basenext::Nothing) where {T} = nothing function _iterate(iter::SIMDIter{T, 8}, basenext) where {T} local i1::Int64, i2::Int64, i3::Int64, i4::Int64, i5::Int64, i6::Int64, i7::Int64, i8::Int64 (i1, state) = basenext basenext = iterate(iter.baseiter, state) if isnothing(basenext); i2 = i1; else; (i2, state) = basenext; end basenext = iterate(iter.baseiter, state) if isnothing(basenext); i3 = i2; else; (i3, state) = basenext; end basenext = iterate(iter.baseiter, state) if isnothing(basenext); i4 = i3; else; (i4, state) = basenext; end basenext = iterate(iter.baseiter, state) if isnothing(basenext); i5 = i4; else; (i5, state) = basenext; end basenext = iterate(iter.baseiter, state) if isnothing(basenext); i6 = i5; else; (i6, state) = basenext; end basenext = iterate(iter.baseiter, state) if isnothing(basenext); i7 = i6; else; (i7, state) = basenext; end basenext = iterate(iter.baseiter, state) if isnothing(basenext); i8 = i7; else; (i8, state) = basenext; end return (SIMD.Vec((i1, i2, i3, i4, i5, i6, i7, i8)), state) end ################################# # Fill SIMD type from scalar Vector ##################################### """ vgatherind(vec, indices::Integer, mask) -> v # v[i], scalar fallback vgatherind(vec, indices::SIMD.Vec{N, <:Integer}, mask) -> v::SIMD.Vec{N, eltype(vec)} Fill SIMD type from scalar Vector, without type conversion See [`SIMDIter`](@ref) for example usage. """ @Base.propagate_inbounds function vgatherind(vec, indices::Integer, mask) return vec[indices] end @Base.propagate_inbounds function vgatherind(vec, indices::SIMD.Vec{N, <:Integer}, mask) where N return SIMD.vgather(vec, indices, mask) end """ vgatherind(::Type{T}, vec, indices::Integer, mask) -> v::T # v[i], scalar fallback vgatherind(::Type{SIMD.Vec{N, T}}, vec, indices::SIMD.Vec{N, <:Integer}) -> v::SIMD.Vec{N, T} Fill SIMD type from scalar Vector, with explicit type conversion to scalar type `T` NB: assumes all `indices` are valid See [`SIMDIter`](@ref) for example usage. """ @Base.propagate_inbounds function vgatherind(::Type{T}, vec, indices::Integer) where {T} return convert(T, vec[indices]) end @Base.propagate_inbounds function vgatherind(::Type{SIMD.Vec{2, T}}, vec, indices::SIMD.Vec{2, <:Integer}) where T return SIMD.Vec{2, T}((vec[indices[1]], vec[indices[2]])) end @Base.propagate_inbounds function vgatherind(::Type{SIMD.Vec{4, T}}, vec, indices::SIMD.Vec{4, <:Integer}) where T return SIMD.Vec{4, T}((vec[indices[1]], vec[indices[2]], vec[indices[3]], vec[indices[4]])) end @Base.propagate_inbounds function vgatherind(::Type{SIMD.Vec{8, T}}, vec, indices::SIMD.Vec{8, <:Integer}) where T return SIMD.Vec{8, T}( ( vec[indices[1]], vec[indices[2]], vec[indices[3]], vec[indices[4]], vec[indices[5]], vec[indices[6]], vec[indices[7]], vec[indices[8]] ) ) end ############################################### # Unpack SIMD type and write to scalar Vector ############################################# """ vscatterind!(v::T, vec::Array{T, N}, indices::Integer, mask) # scalar fallback, no type conversion vscatterind!(v::T, vec::Array{T, N}, indices::Integer) # scalar fallback, no type conversion vscatterind!(v::SIMD.Vec{N, T}, vec, indices::SIMD.Vec{N, <:Integer}, mask) # converts to eltype{vec} vscatterind!(v::SIMD.Vec{N, T}, vec, indices::SIMD.Vec{N, <:Integer}) # converts to eltype{vec} Unpack SIMD type and write to scalar Vector, with type conversion to `eltype(vec)`. Versions without `mask` assume all indices are valid (but may be repeated). See [`SIMDIter`](@ref) for example usage. """ @Base.propagate_inbounds function vscatterind!(v::T, vec::Array{T, N}, indices::Integer, mask) where {T,N} vec[indices] = v return nothing end @Base.propagate_inbounds function vscatterind!(v::T, vec::Array{T,N}, indices::Integer) where {T,N} vec[indices] = v return nothing end @Base.propagate_inbounds function vscatterind!(v::SIMD.Vec{N, T}, vec, indices::SIMD.Vec{N, <:Integer}, mask) where {N, T} SIMD.vscatter(convert(SIMD.Vec{N, eltype(vec)}, v), vec, indices, mask) return nothing end @Base.propagate_inbounds function vscatterind!(v::SIMD.Vec{N, T}, vec, indices::SIMD.Vec{N, <:Integer}) where {N, T} SIMD.vscatter(convert(SIMD.Vec{N, eltype(vec)}, v), vec, indices) return nothing end ############################################### # Unpack SIMD type and add to scalar Vector ############################################# """ vaddind!(v::T, vec::Array{T, N}, indices::Integer) # scalar fallback, no type conversion vaddind!(v::SIMD.Vec{N, T}, vec, indices::SIMD.Vec{N, <:Integer}) Unpack SIMD type and add to scalar Vector, with type conversion to `eltype(vec)`. Assumes all indices are valid (but may be repeated, which will still have the effect of one add). See [`SIMDIter`](@ref) for example usage. """ @Base.propagate_inbounds function vaddind!(v::T, vec::Array{T, N}, indices::Integer) where {T, N} vec[indices] += v return nothing end @Base.propagate_inbounds function vaddind!(v::SIMD.Vec{N, T}, vec, indices::SIMD.Vec{N, <:Integer}) where {N, T} tmp = vgatherind(SIMD.Vec{N, T}, vec, indices) vscatterind!(tmp + v, vec, indices) return nothing end ###################################################### # functions to call SLEEF library Sleef <https://sleef.org>, using binary from SLEEF_jll.jl # see <https://github.com/chriselrod/SLEEFPirates.jl/blob/master/src/svmlwrap32.jl> for ccall examples # # NB: need to provide specific Base.exp etc for each type in order to override the fallbacks in SIMD.jl ############################################################# # raw tuple data types held in Vec.data const FP64P4_d = NTuple{4,Core.VecElement{Float64}} const FP64P2_d = NTuple{2,Core.VecElement{Float64}} const FP32P8_d = NTuple{8,Core.VecElement{Float32}} const FP32P4_d = NTuple{4,Core.VecElement{Float32}} if [email protected]_preference("USE_SLEEF") @info "$(@__MODULE__) defining USE_SLEEF = false in LocalPreferences.toml" @Preferences.set_preferences!("USE_SLEEF"=>false) end const USE_SLEEF = @Preferences.load_preference("USE_SLEEF", false) @static if USE_SLEEF @info "$(@__MODULE__) defining Vectorized SIMD functions log, exp, log10 functions from Sleef library $(SLEEF_jll.libsleef)"* " - to disable Sleef, set USE_SLEEF = false in LocalPreferences.toml and restart your Julia session" # exp Sleef Vectorized double/single precision base-e exponential functions functions with 1.0 ULP error bound sleefexp(v::FP64P4_d) = ccall((:Sleef_expd4_u10, SLEEF_jll.libsleef), FP64P4_d, (FP64P4_d,), v) Base.exp(v::FP64P4) = SIMD.Vec(sleefexp(v.data)) sleefexp(v::FP64P2_d) = ccall((:Sleef_expd2_u10, SLEEF_jll.libsleef), FP64P2_d, (FP64P2_d,), v) Base.exp(v::FP64P2) = SIMD.Vec(sleefexp(v.data)) sleefexp(v::FP32P8_d) = ccall((:Sleef_expf8_u10, SLEEF_jll.libsleef), FP32P8_d, (FP32P8_d,), v) Base.exp(v::FP32P8) = SIMD.Vec(sleefexp(v.data)) sleefexp(v::FP32P4_d) = ccall((:Sleef_expf4_u10, SLEEF_jll.libsleef), FP32P4_d, (FP32P4_d,), v) Base.exp(v::FP32P4) = SIMD.Vec(sleefexp(v.data)) # log Sleef Vectorized double/single precision natural logarithmic functions with 1.0 ULP error bound sleeflog(v::FP64P4_d) = ccall((:Sleef_logd4_u10, SLEEF_jll.libsleef), FP64P4_d, (FP64P4_d,), v) Base.log(v::FP64P4) = SIMD.Vec(sleeflog(v.data)) sleeflog(v::FP64P2_d) = ccall((:Sleef_logd2_u10, SLEEF_jll.libsleef), FP64P2_d, (FP64P2_d,), v) Base.log(v::FP64P2) = SIMD.Vec(sleeflog(v.data)) sleeflog(v::FP32P8_d) = ccall((:Sleef_logf8_u10, SLEEF_jll.libsleef), FP32P8_d, (FP32P8_d,), v) Base.log(v::FP32P8) = SIMD.Vec(sleeflog(v.data)) sleeflog(v::FP32P4_d) = ccall((:Sleef_logf4_u10, SLEEF_jll.libsleef), FP32P4_d, (FP32P4_d,), v) Base.log(v::FP32P4) = SIMD.Vec(sleeflog(v.data)) # this should work, but isn't specific enough to override the fallbacks in SIMD.jl # Base.log(v::SIMD.Vec{N,T}) where {N,T} = SIMD.Vec(sleeflog(v.data)) # Vectorized double/single precision base-10 logarithmic functions with 1.0 ULP error bound sleeflog10(v::FP64P4_d) = ccall((:Sleef_log10d4_u10, SLEEF_jll.libsleef), FP64P4_d, (FP64P4_d,), v) Base.log10(v::FP64P4) = SIMD.Vec(sleeflog10(v.data)) sleeflog10(v::FP64P2_d) = ccall((:Sleef_log10d2_u10, SLEEF_jll.libsleef), FP64P2_d, (FP64P2_d,), v) Base.log10(v::FP64P2) = SIMD.Vec(sleeflog10(v.data)) sleeflog10(v::FP32P8_d) = ccall((:Sleef_log10f8_u10, SLEEF_jll.libsleef), FP32P8_d, (FP32P8_d,), v) Base.log10(v::FP32P8) = SIMD.Vec(sleeflog10(v.data)) sleeflog10(v::FP32P4_d) = ccall((:Sleef_log10f4_u10, SLEEF_jll.libsleef), FP32P4_d, (FP32P4_d,), v) Base.log10(v::FP32P4) = SIMD.Vec(sleeflog10(v.data)) else @info "$(@__MODULE__) Using defaults (probably slow scalar fallbacks) for SIMD log, exp, log10 functions"* " - to enable Sleef library, set USE_SLEEF = true in LocalPreferences.toml and restart your Julia session" end end # module
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
5277
""" TestUtils Utility functions for testing and benchmarking """ module TestUtils using BenchmarkTools using InteractiveUtils import PALEOboxes as PB "repeatedly call `dispatch_methodlist` `N` times to generate a long-duration run for profiling" function profile_dispatchlist(dispatchlist, N, deltat::Float64=0.0) for i in 1:N PB.dispatch_methodlist(dispatchlist..., deltat) end return nothing end """ bench_method( dispatchlist, domainname="", reactionname="", methodname=""; deltat::Float64=0.0, use_time=false, use_btime=true, do_code_llvm=false, do_code_native=true, do_code_warntype=false ) Benchmark or dump llvm code etc for specified method(s). Iterates through `dispatchlist`, if names match then benchmark method else just call method normally. """ function bench_method( dispatchlist, domainname="", reactionname="", methodname=""; deltat::Float64=0.0, call_all=true, use_time=false, use_btime=true, do_code_llvm=false, do_code_native=false, do_code_warntype=false, ) # fns, methods, vardatas, crs = dispatchlist # iterate through dispatchlist, if names match then benchmark method else just call method for (method, vardata, cr) in PB.IteratorUtils.zipstrict( dispatchlist.methods, dispatchlist.vardatas, dispatchlist.cellranges) if (isempty(domainname) || method[].domain.name == domainname) && (isempty(reactionname) || method[].reaction.name == reactionname) && (isempty(methodname) || method[].name == methodname) println(PB.fullname(method[]), ":") if use_time println(" @time:") @time PB.call_method(method[], vardata[], cr, deltat) end if use_btime println(" @btime:") @btime PB.call_method($method[], $vardata[], $cr, $deltat) end if do_code_llvm println(" @code_llvm:") b = IOBuffer() PB.call_method_codefn(IOContext(b, :color=>true), code_llvm, method[], vardata[], cr, deltat) println(String(take!(b))) end if do_code_native println(" @code_native:") b = IOBuffer() PB.call_method_codefn(IOContext(b, :color=>true), code_native, method[], vardata[], cr, deltat) println(String(take!(b))) end if do_code_warntype println(" @code_warntype:") b = IOBuffer() PB.call_method_codefn(IOContext(b, :color=>true), code_warntype, method[], vardata[], cr, deltat) println(String(take!(b))) # @code_warntype PB.call_method(method, vardata[], cr, deltat) end elseif call_all PB.call_method(method[], vardata[], cr, deltat) end end return nothing end """ bench_model(model, modeldata; bench_whole=true, domainname="", reactionname="", methodname="", [; kwargs...]) Optionally benchmark whole model, and then call [`bench_method`](@ref) to benchmark selected methods # Keywords - `bench_whole=true`: true to benchmark whole model (using `dispatch_methodlist` and `do_deriv`) - `domainname`, `reactionname`, `methodname`, `kwargs`: passed through to [`bench_method`](@ref) # Example Run @code_warntype on a single method: ```julia julia> PB.TestUtils.bench_model(run.model, modeldata; bench_whole=false, reactionname="atmtransport", methodname="calc_gas_floormrbc", use_btime=false, do_code_warntype=true) ```` """ function bench_model( model, modeldata; bench_whole=true, domainname="", reactionname="", methodname="", kwargs... ) dispatchlists = modeldata.dispatchlists_all if bench_whole println() println("@btime PB.dispatch_list initialize") @btime PB.dispatch_methodlist($dispatchlists.list_initialize) println() println("@btime PB.dispatch_list do") @btime PB.dispatch_methodlist($dispatchlists.list_do) println() println("@btime do_deriv") @btime PB.do_deriv($dispatchlists) end println() println("bench_method initialize") PB.TestUtils.bench_method(dispatchlists.list_initialize, domainname, reactionname, methodname; kwargs...) println() println("bench_method do") PB.TestUtils.bench_method(dispatchlists.list_do, domainname, reactionname, methodname; kwargs...) return nothing end function check_round(a, b, sigdigits; message="") lhs = round(a, sigdigits=sigdigits) rhs = round(b, sigdigits=sigdigits) result = lhs == rhs if !result println("check_round (", message, ") ",a, " != ",b, " sigdigits=", sigdigits, " round(a) ", lhs, " != round(b) ", rhs) end return result end # macro to validate output macro check_true(test_expression) message = string("check_true failed: ", test_expression) :($(esc(test_expression)) || error($message)) end end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
13204
# import Infiltrator ################################################################# # VariableAggregator ################################################################# struct VariableAggregator{T, F <: Tuple, C <: Tuple} # modeldata used for data arrays (for diagnostic output only) modeldata::AbstractModelData # not typed arrays_idx::Int # Variables vars::Vector{VariableDomain} # indices in contiguous Vector for each Variable indices::Vector{UnitRange{Int64}} # field and corresponding CellRange for each Variable fields::F cellranges::C end """ 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!`](@ref) """ function VariableAggregator(vars, cellranges, modeldata::AbstractModelData, arrays_idx::Int) IteratorUtils.check_lengths_equal(vars, cellranges; errmsg="'vars' and 'cellranges' must be of same length") fields = [] indices = UnitRange{Int64}[] nextidx = 1 for (v, cr) in IteratorUtils.zipstrict(vars, cellranges) f = get_field(v, modeldata, arrays_idx) dof = dof_field(f, cr) r = nextidx:(nextidx+dof-1) push!(fields, f) push!(indices, r) nextidx += dof end fields=Tuple(fields) cellranges=Tuple(cellranges) return VariableAggregator{eltype(modeldata, arrays_idx), typeof(fields), typeof(cellranges)}( modeldata, arrays_idx, copy(vars), indices, fields, cellranges, ) end # compact form function Base.show(io::IO, va::VariableAggregator) print(io, "VariableAggregator(modeldata=$(va.modeldata), arrays_idx=$(va.arrays_idx), length=$(length(va)), number of variables=$(length(va.vars)))") return nothing end # multiline form function Base.show(io::IO, ::MIME"text/plain", va::VariableAggregator) println(io, "VariableAggregator(modeldata=$(va.modeldata), arrays_idx=$(va.arrays_idx), length=$(length(va)), number of variables=$(length(va.vars))):") if length(va) > 0 println( io, " ", rpad("var", 6), rpad("indices", 14), rpad("name", 40), rpad("cellrange.indices", 14) ) for i in eachindex(va.vars) println( io, " ", rpad(i,6), rpad(va.indices[i], 14), rpad("$(fullname(va.vars[i]))", 40), rpad(isnothing(va.cellranges[i]) ? "-" : va.cellranges[i].indices, 14), ) end end return nothing end Base.eltype(va::VariableAggregator{T, F, C}) where{T, F, C} = T function Base.length(va::VariableAggregator) if isempty(va.indices) return 0 else return last(last(va.indices)) end end """ get_indices(va::VariableAggregator, varnamefull::AbstractString; allow_not_found=false) -> indices::UnitRange{Int64} Return indices in flattened Vector corresponding to Variable `varnamefull` """ function get_indices(va::VariableAggregator, varnamefull::AbstractString; allow_not_found=false) indices = nothing for (v, ind) in IteratorUtils.zipstrict(va.vars, va.indices) if fullname(v) == varnamefull indices = ind break end end !isnothing(indices) || allow_not_found || error("get_indices: Variable $varnamefull not found") return indices end """ 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. """ function Base.copyto!(dest::VariableAggregator, src::AbstractVector; sof::Int=1) function copy(si, field, cellrange) si += copyto!(field, cellrange, src, si) return si end fof = IteratorUtils.reduce_longtuple(copy, sof, dest.fields, dest.cellranges) return fof - sof end """ copyto!(dest::AbstractVector, va::VariableAggregator; dof=1) -> num_copied::Int Set (contiguous) Vector `dest` = aggregated Variables `src` Optional `dof` sets first index in `dest` """ function Base.copyto!(dest::AbstractVector, src::VariableAggregator; dof::Int=1) function copy(di, field, cellrange) di += copyto!(dest, di, field, cellrange) return di end fof = IteratorUtils.reduce_longtuple(copy, dof, src.fields, src.cellranges) return fof - dof end """ get_data(va::VariableAggregator) -> Vector Allocate Vector and set to values of aggregated Variables `va`. """ function get_data(va::VariableAggregator) x = Vector{eltype(va)}(undef, length(va)) copyto!(x, va) return x end "vay += a * vax" function add_data!(vay::VariableAggregator{T, F, C}, a, vax::VariableAggregator{T, F, C}) where {T, F, C} length(vay) == length(vax) || throw(ArgumentError("'vay' and 'vax' must be of same length")) adapt_add_field!(dest, cellrange, src) = add_field!(dest, a, cellrange, src) IteratorUtils.foreach_longtuple(adapt_add_field!, vay.fields, vay.cellranges, vax.fields) return nothing end "vay += a * vax" function add_data!(vay::VariableAggregator{T, F, C}, a, vax::AbstractArray) where {T, F, C} length(vay) == length(vax) || throw(ArgumentError("'vay' and 'vax' must be of same length")) function adapt_add_field_vec!(vidx, dest, cellrange) vidx += add_field_vec!(dest, a, cellrange, vax, vidx) return vidx end IteratorUtils.reduce_longtuple(adapt_add_field_vec!, 1, vay.fields, vay.cellranges) return nothing end "get Variables" get_vars(va::VariableAggregator) = va.vars num_vars(va::VariableAggregator) = length(va.vars) ################################################################# # VariableAggregatorNamed ################################################################# struct VariableAggregatorNamed{V <: NamedTuple, VV <: NamedTuple} # modeldata used for data arrays (for diagnostic output only) modeldata::AbstractModelData # not typed arrays_idx::Int # Variables as a NamedTuple vars::V # Values for each Variable as NamedTuple values::VV end function num_vars(va::VariableAggregatorNamed) nv = 0 for vnt in va.vars nv += length(vnt) end return nv end function Base.length(va::VariableAggregatorNamed) l = 0 for vnt in va.values for v in vnt l += length(v) end end return l end # compact form function Base.show(io::IO, van::VariableAggregatorNamed) print(io, "VariableAggregatorNamed(modeldata=$(van.modeldata), arrays_idx=$(van.arrays_idx), ") for (domainname, dvarsnt) in zip(keys(van.vars), van.vars) print(io, "$domainname.*$([k for k in keys(dvarsnt)]), ") end print(io, ")") return nothing end # multiline form function Base.show(io::IO, ::MIME"text/plain", van::VariableAggregatorNamed) println(io, "VariableAggregatorNamed(modeldata=$(van.modeldata), arrays_idx=$(van.arrays_idx):") for (domainname, dvaluesnt) in zip(keys(van.vars), van.values) println(io, " $domainname:") for (varname, varvalues) in zip(keys(dvaluesnt), dvaluesnt) println(io, " $(rpad(varname, 20))$varvalues") end end return nothing end """ 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. """ function VariableAggregatorNamed( modeldata::AbstractModelData, arrays_idx=1, ) # get all domain Variables all_domvars = Vector{VariableDomain}() for dom in modeldata.model.domains append!(all_domvars, get_variables(dom)) end return VariableAggregatorNamed(all_domvars, modeldata, arrays_idx) end function VariableAggregatorNamed(va::VariableAggregator, ignore_cellranges=false) all(va.cellranges .== nothing) || ignore_cellranges || error("VariableAggregatorNamed: VariableAggregator is using cellranges to select part of Domain") return VariableAggregatorNamed(va.vars, va.modeldata, va.arrays_idx) end function VariableAggregatorNamed( vars, modeldata::AbstractModelData, arrays_idx=1, ) # sort into Dicts of # domain.name => (Dict of v.name=>v) # domain.name => (Dict of v.name=>data) # Sort by name and then use OrderedDict to preserve alphabetical order (domainname, varname) domains_vars = OrderedCollections.OrderedDict() domains_values = OrderedCollections.OrderedDict() for v in sort(vars, by=fullname) sym_vname = Symbol(replace(v.name, "/"=>"__")) # Reaction-private Variables use <reactionname>/<varname>, but / isn't a legal Symbol name d_vars = get!(domains_vars, Symbol(v.domain.name), OrderedCollections.OrderedDict()) d_vars[sym_vname] = v d_values = get!(domains_values, Symbol(v.domain.name), OrderedCollections.OrderedDict()) d_values[sym_vname] = get_data(v, modeldata, arrays_idx) end # convert to nested NamedTuples, via a Dict of NamedTuples vars_dictnt = OrderedCollections.OrderedDict() for (dname, d_vars) in domains_vars vars_dictnt[dname] = NamedTuple{Tuple(keys(d_vars))}(Tuple(values(d_vars))) end vars_nt = NamedTuple{Tuple(keys(vars_dictnt))}(Tuple(values(vars_dictnt))) vars_values_dictnt = OrderedCollections.OrderedDict() for (dname, d_values) in domains_values vars_values_dictnt[dname] = NamedTuple{Tuple(keys(d_values))}(Tuple(values(d_values))) end vars_values_nt = NamedTuple{Tuple(keys(vars_values_dictnt))}(Tuple(values(vars_values_dictnt))) return VariableAggregatorNamed(modeldata, arrays_idx, vars_nt, vars_values_nt) end """ set_values!(van::VariableAggregatorNamed, domainname_sym::Symbol, varname_sym::Symbol, val; allow_not_found=false) set_values!(van::VariableAggregatorNamed, domainname::AbstractString, varname::AbstractString, val; allow_not_found=false) set_values!(van::VariableAggregatorNamed, ::Val{domainname_sym}, ::Val{varname_sym}, val; allow_not_found=false) Set a data array in `var`: ie set `van.values.domainname.varname .= val`. If Variable `domainname.varname` not present, errors if `allow_not_found==false`, or has no effect if `allow_not_found==true`. As an optimisation where `domainname` and `varname` are known at compile time, they can be passed as Val(domainname_sym), Val(varname_sym) to maintain type stability and avoid allocations. """ function set_values!( van::VariableAggregatorNamed, domainname::Symbol, varname::Symbol, val; allow_missing::Bool=false, # deprecated allow_not_found::Bool=allow_missing, ) # check Variable exists if hasfield(typeof(van.values), domainname) if hasfield(typeof(getfield(van.values, domainname)), varname) getfield(getfield(van.values, domainname), varname) .= val else allow_not_found || error("VariableAggregatorNamed has no Variable $domainame.$varname") end else allow_not_found || error("VariableAggregatorNamed has no Variable $domainame.$varname") end return nothing end set_values!( van::VariableAggregatorNamed, domainname::AbstractString, varname::AbstractString, val; allow_missing::Bool=false, # deprecated allow_not_found::Bool=allow_missing, ) = set_values!(van, Symbol(domainname), Symbol(varname), val; allow_not_found) # type stable version function set_values!( van::VariableAggregatorNamed, domainname::Val{DN}, varname::Val{VN}, val; allow_missing::Bool=false, # deprecated allow_not_found::Bool=allow_missing, ) where {DN, VN} # check Variable exists if hasfield(typeof(van.values), DN) if hasfield(typeof(getfield(van.values, DN)), VN) getfield(getfield(van.values, DN), VN) .= val else allow_not_found || error("VariableAggregatorNamed has no Variable $DN.$VN") end else allow_not_found || error("VariableAggregatorNamed has no Variable $DN.$VN") end return nothing end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
2177
module ReactionPaleoMockModule import PALEOboxes as PB # using Infiltrator # Julia debugger "Define variables, parameters, and any additional reaction state" Base.@kwdef mutable struct ReactionPaleoMock{P} <: PB.AbstractReaction base::PB.ReactionBase pars::P = PB.ParametersTuple( PB.ParDouble( "par1", 0.0, units="m-3", description="test parameter double"), PB.ParInt( "parint", 2, description="test parameter int"), PB.ParBool( "parbool", true, description="test parameter bool"), PB.ParString( "parstring", "a_string", description="test parameter string"), ) end function do_stateandeqb(m::PB.ReactionMethod, pars, (vars, ), cellrange::PB.AbstractCellRange, deltat) vars.scalar_prop[] = vars.scalar_dep[] # 25nS, 0 allocations return nothing end function do_react(m::PB.ReactionMethod, pars, (vars, ), cellrange::PB.AbstractCellRange, deltat) @inbounds for i in cellrange.indices vars.phy[i] = pars.par1[] end return nothing end function PB.register_methods!(rj::ReactionPaleoMock) println("ReactionPaleoMock.register_methods! rj=", rj) println(" parint=", rj.pars.parint[]) println(" parbool=", rj.pars.parbool[]) println(" parstring=", rj.pars.parstring[]) vars_stateandeqb = [ PB.VarDepScalar("scalar_dep", "mol m-3", "a scalar dependency"), PB.VarPropScalar("%reaction%scalar_prop", "mol m-3", "a scalar property") ] PB.add_method_do!(rj, do_stateandeqb, (PB.VarList_namedtuple(vars_stateandeqb),)) # default vector Variable vars_react = [ PB.VarProp( "phy", "mol m-3", "phytoplankton concentration") ] PB.add_method_do!(rj, do_react, (PB.VarList_namedtuple(vars_react),)) return nothing end # contiguous range is faster than using indices array # @btime ReactionPaleoMockModule.do_react_kernel(reaction.var_phy._data, 1:1000, reaction.pars.par1.value) # 168.262 ns (1 allocation: 16 bytes) function do_react_kernel(v, indices, p) for i in indices @inbounds v[i] = p end return nothing end end # module
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
940
module ReactionRateStoichMockModule import PALEOboxes as PB "Mock Reaction to test RateStoich" Base.@kwdef mutable struct ReactionRateStoichMock <: PB.AbstractReaction base::PB.ReactionBase # a biogeochemically implausible fractionating H2S oxidation # H2S + 2O2 -> SO4, with -10 per mil fractionation ratestoich = PB.RateStoich( PB.VarProp("myrate", "mol yr-1", "a rate"), ((-2.0, "O2"), (-1.0,"H2S::Isotope"), (1.0, "SO4::Isotope")), deltavarname_eta=("H2S_delta", -10.0), processname="redox" ) end function PB.register_methods!(rj::ReactionRateStoichMock) PB.add_method_do!(rj, do_rate, (PB.VarList_single(rj.ratestoich.ratevartemplate),)) PB.add_method_do!(rj, rj.ratestoich, isotope_data=PB.IsotopeLinear) return nothing end function do_rate(m, (rate, ), cellrange::PB.AbstractCellRange, deltat) rate .= 42.0 return nothing end end # module
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
748
module ReactionRateStoichMockModule import PALEOboxes as PB "Mock Reaction to test calculating a flux that depends on a reservoir" Base.@kwdef mutable struct ReactionReservoirFlux <: PB.AbstractReaction base::PB.ReactionBase end function PB.register_methods!(rj::ReactionReservoirFlux) vars = [ PB.VarDepScalar("R", "mol", "a scalar reservoir"), PB.VarContribScalar("R_sms", "mol yr-1", "a scalar reservoir source-sink"), ] PB.add_method_do!(rj, do_reservoirflux, (PB.VarList_namedtuple(vars),)) return nothing end function do_reservoirflux(m, (vars, ), cellrange::PB.AbstractCellRange, deltat) flux = 1.0*vars.R[] # first order rate vars.R_sms[] -= flux return nothing end end # module
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
4822
import PALEOboxes as PB using Test using BenchmarkTools include("ReactionPaleoMockModule.jl") @testset "PALEOboxes base" begin model = PB.create_model_from_config("configbase.yaml", "model1") PB.show_methods_setup(model) PB.show_methods_initialize(model) PB.show_methods_do(model) @test length(model.domains) == 3 ocean_domain = model.domains[1] @test ocean_domain.name == "ocean" @test ocean_domain.ID == 1 @test length(ocean_domain.reactions) == 2 reaction = PB.get_reaction(ocean_domain, "julia_paleo_mock") @test reaction.name == "julia_paleo_mock" println(reaction) @test length(PB.get_parameters(reaction)) == 4 par = PB.get_parameter(reaction, "par1") @test par.name == "par1" @test par.v == 0.15 @test length(PB.get_variables(reaction)) == 3 var = PB.get_variable(reaction, "do_react", "phy") @test var.localname == "phy" @test var.linkreq_name == "mock_phy" @test length(PB.get_variables(ocean_domain)) == 5 modelvars = Dict((var.name, var) for var in PB.get_variables(ocean_domain, hostdep=false)) @test length(modelvars) == 4 @test !isnothing(PB.get_variable(ocean_domain, "mock_phy")) @test haskey(modelvars, "mock_phy") @test haskey(modelvars, "julia_paleo_mock/scalar_prop") @test haskey(modelvars, "mock2_phy") @test haskey(modelvars, "julia_paleo_mock2/scalar_prop") hostvars = PB.get_variables(ocean_domain, hostdep=true) @test length(hostvars) == 1 @test hostvars[1].name == "scalar_dep" @test PB.is_scalar(hostvars[1]) domain_size = 1000 # domain_size = 10 ocean_domain.grid = PB.Grids.UnstructuredVectorGrid(ncells=domain_size) @test PB.get_length(ocean_domain) == domain_size modeldata = PB.create_modeldata(model) @test length(PB.get_unallocated_variables(ocean_domain, modeldata, 1)) == 5 PB.allocate_variables!(ocean_domain, modeldata, 1; hostdep=false, check_units_opt=:error) @test length(PB.get_unallocated_variables(ocean_domain, modeldata, 1)) == 1 @test PB.check_ready(ocean_domain, modeldata, throw_on_error=false) == false hostvardata = Float64[NaN] PB.set_data!(hostvars[1], modeldata, 1, hostvardata) @test PB.check_ready(ocean_domain, modeldata, throw_on_error=false) == true @test PB.check_configuration(model, throw_on_error=false) == true PB.initialize_reactiondata!(model, modeldata; create_dispatchlists_all=true) cellrange = PB.Grids.create_default_cellrange(ocean_domain, ocean_domain.grid) cellranges = [cellrange] PB.dispatch_setup(model, :setup, modeldata, cellranges) PB.dispatch_setup(model, :norm_value, modeldata, cellranges) PB.dispatch_setup(model, :initial_value, modeldata, cellranges) dispatchlists = modeldata.dispatchlists_all hostvardata[] = 27.3 PB.do_deriv(dispatchlists) allvars = PB.VariableAggregatorNamed(modeldata) println(allvars) @test PB.num_vars(allvars) == 5 @test length(allvars) == 3 + 2*domain_size @test PB.get_data(modelvars["julia_paleo_mock/scalar_prop"], modeldata) == hostvardata @test PB.get_data(modelvars["julia_paleo_mock2/scalar_prop"], modeldata) == hostvardata # NB: / in name --> __ in field, so "ocean.julia_paleo_mock/scalar_prop" -> field ocean.julia_paleo_mock__scalar_prop @test allvars.values.ocean.julia_paleo_mock__scalar_prop == hostvardata @test allvars.values.ocean.julia_paleo_mock2__scalar_prop == hostvardata @test allvars.values.ocean.mock_phy == fill(0.15, domain_size) end @testset "PALEOboxes base loop" begin @test_throws ErrorException("The input graph contains at least one loop.") PB.create_model_from_config("configbase.yaml", "model_with_loop") end @testset "PALEOboxes base invalid parameter name" begin @test_throws ErrorException("reaction ocean.julia_paleo_mock has no Parameter(s):\n misspelt_par: something\n") PB.create_model_from_config("configbase.yaml", "model_with_invalid_parameter") end @testset "PALEOboxes base empty parameters" begin model = PB.create_model_from_config("configbase.yaml", "model_with_empty_parameters") @test length(model.domains) == 3 end @testset "PALEOboxes base empty variable link" begin @test_throws MethodError PB.create_model_from_config("configbase.yaml", "model_with_empty_variable_link") end @testset "PALEOboxes base invalid variable attribute" begin @test_throws ErrorException PB.create_model_from_config("configbase.yaml", "model_with_invalid_variable_attribute") end # test parsing concatenated yaml files @testset "PALEOboxes base concatenate" begin model = PB.create_model_from_config(["configbase_pt1.yaml", "configbase_pt2.yaml"], "model1") @test length(model.domains) == 3 end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
1644
# Tests for Tuple iteration and dispatch # see https://github.com/JuliaLang/julia/issues/31869 # https://github.com/JuliaLang/julia/blob/master/base/tuple.jl (map implementation) # # (looking for a simple way to dispatch a Tuple of similar Reactions (do_ in Model.jl) # or Variables (RateStoich.jl, several other places) that uses the Julia type # system to eliminate dynamic dispatch overhead, both speed and spurious allocations) using BenchmarkTools foreach_test(f, t::Tuple{}) = () # foreach_test(f, t::Tuple{Any, }) = (f(t[1]); nothing) # foreach_test(f, t::Tuple) = (f(t[1]); foreach_test(f, Base.tail(t)); nothing) foreach_test(f, t::Tuple{Any, }) = (@Base._inline_meta; f(t[1]); nothing) foreach_test(f, t::Tuple) = (@Base._inline_meta; f(t[1]); foreach_test(f, Base.tail(t)); nothing) # benchmarks demonstrate Base.tail hits some arbitrary limit at 32 ?? t2 = Tuple(ones(32)) @btime foreach_test(sin, $t2) # no allocations t2 = Tuple(ones(33)) @btime foreach_test(sin, $t2) # allocates fprint(a) = println("a=$a typeof(a)=$(typeof(a))") foreach_test2(f, t1::Tuple{}, t2::Tuple{}) = () # foreach_test(f, t::Tuple{Any, }) = (f(t[1]); nothing) # foreach_test(f, t::Tuple) = (f(t[1]); foreach_test(f, Base.tail(t)); nothing) foreach_test2(f, t1::Tuple{Any, }, t2::Tuple{Any,}) = (@Base._inline_meta; f(t1[1], t2[1]); nothing) foreach_test2(f, t1::Tuple, t2::Tuple) = (@Base._inline_meta; f(t1[1], t2[1]); foreach_test2(f, Base.tail(t1), Base.tail(t2)); nothing) t2 = Tuple(ones(32)) @btime foreach_test2(min, $t2, $t2 ) # no allocations t2 = Tuple(ones(33)) @btime foreach_test2(min, $t2, $t2) # allocates
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
80
using Test, Documenter import PALEOboxes doctest(PALEOboxes; manual=false)
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
2165
using Test using Logging import PALEOboxes as PB @testset "Fields" begin @testset "ScalarData, ScalarSpace" begin f = PB.allocate_field(PB.ScalarData, (), Float64, PB.ScalarSpace, nothing; thread_safe=false, allocatenans=true) @test isnan(f.values[]) end @testset "ScalarData, CellSpace, no grid" begin # check that a CellSpace Field with no grid behaves as a ScalarSpace Field f = PB.allocate_field(PB.ScalarData, (), Float64, PB.CellSpace, nothing; thread_safe=false, allocatenans=true) @test isnan(f.values[]) end @testset "ScalarData, CellSpace, UnstructuredColumnGrid" begin g = PB.Grids.UnstructuredColumnGrid(ncells=5, Icolumns=[collect(1:5)]) f = PB.allocate_field(PB.ScalarData, (), Float64, PB.CellSpace, g; thread_safe=false, allocatenans=true) @test isnan.(f.values) == [true for i in 1:5] end @testset "ArrayScalarData, ScalarSpace" begin f = PB.allocate_field(PB.ArrayScalarData, (PB.NamedDimension("test", 2, []), ), Float64, PB.ScalarSpace, nothing; thread_safe=false, allocatenans=true) @test isnan.(f.values) == [true, true] end @testset "ArrayScalarData, CellSpace, no grid" begin # TODO this is possibly inconsistent with (ScalarData, CellSpace, no grid), # as Field.values here is a (1, 2) Array, not a (2,) Vector f = PB.allocate_field(PB.ArrayScalarData, (PB.NamedDimension("test", 2, []), ), Float64, PB.CellSpace, nothing; thread_safe=false, allocatenans=true) @test_broken size(f.values) == (2, ) # TODO should be a Vector ? @test size(f.values) == (1, 2) @test isnan.(f.values) == [true true] # TODO 1x2 Array or Vector ? end @testset "ArrayScalarData, CellSpace, UnstructuredColumnGrid" begin g = PB.Grids.UnstructuredColumnGrid(ncells=5, Icolumns=[collect(1:5)]) f = PB.allocate_field(PB.ArrayScalarData, (PB.NamedDimension("test", 2, []), ), Float64, PB.CellSpace, g; thread_safe=false, allocatenans=true) @test size(f.values) == (5, 2) end end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
2131
using Test using Logging import PALEOboxes as PB @testset "Fluxes" begin model = PB.create_model_from_config("configfluxes.yaml", "model1") global_domain = PB.get_domain(model, "global") @test PB.get_length(global_domain) == 1 ocean_domain = PB.get_domain(model, "ocean") ocean_domain.grid = PB.Grids.UnstructuredVectorGrid(ncells=1000) ocean_length = PB.get_length(ocean_domain) @test ocean_length == 1000 modeldata = PB.create_modeldata(model) PB.allocate_variables!(model, modeldata, 1; check_units_opt=:error) @test PB.check_ready(model, modeldata) == true # get variables all_vars = PB.VariableAggregatorNamed(modeldata) @test PB.num_vars(all_vars) == 9 @info "all_vars: $all_vars" all_data = all_vars.values PB.initialize_reactiondata!(model, modeldata; create_dispatchlists_all=true) @info "dispatch_setup" PB.dispatch_setup(model, :setup, modeldata) PB.dispatch_setup(model, :norm_value, modeldata) PB.dispatch_setup(model, :initial_value, modeldata) @info "const fluxes:" @test all_data.ocean.flux_A == fill(10.0, ocean_length) @test all_data.ocean.flux_B == fill(20.0, ocean_length) @test all_data.ocean.flux_C == fill(PB.isotope_totaldelta(PB.IsotopeLinear, 2.0, -1.0), ocean_length) dispatchlists = modeldata.dispatchlists_all PB.do_deriv(dispatchlists) PB.do_deriv(dispatchlists) @info "transferred fluxes" @test all_data.ocean.tflux_A == fill(2*10.0, ocean_length) @test all_data.ocean.tflux_C == fill(2*PB.isotope_totaldelta(PB.IsotopeLinear, 2.0, -1.0), ocean_length) @info "transferred flux totals" @test all_data.ocean.tflux_total_A[] == ocean_length*2*10.0 @test all_data.ocean.tflux_total_C[] == ocean_length*2*PB.isotope_totaldelta(PB.IsotopeLinear, 2.0, -1.0) @info "global transferred fluxes" @test all_data.global.tflux_B[] == ocean_length*-1*20.0 @test all_data.global.tflux_C[] == ocean_length*-1*PB.isotope_totaldelta(PB.IsotopeLinear, 2.0, -1.0) @info "test complete" end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
4147
using Test import PALEOboxes as PB include("ReactionPaleoMockModule.jl") @testset "Grids" begin @testset "Cartesian Grid" begin model = PB.create_model_from_config(joinpath(@__DIR__, "configgrids.yaml"), "cartesiangrid") # Test domains @test PB.get_num_domains(model) == 1 ocean_domain = PB.get_domain(model, "ocean") dsize = (2, 3, 4) @test PB.get_length(ocean_domain) == prod(dsize) hostvars = PB.get_variables(ocean_domain, hostdep=true) modeldata = PB.create_modeldata(model) PB.allocate_variables!(ocean_domain, modeldata, 1; hostdep=false, check_units_opt=:error) @test length(PB.get_unallocated_variables(ocean_domain, modeldata, 1)) == 1 @test length(hostvars) == 1 @test hostvars[1].name == "scalar_dep" @test PB.is_scalar(hostvars[1]) hostvardata = Float64[NaN] PB.set_data!(hostvars[1], modeldata, 1, hostvardata) @test PB.check_ready(ocean_domain, modeldata, throw_on_error=false) == true @test PB.check_configuration(model, throw_on_error=false) == true PB.initialize_reactiondata!(model, modeldata; create_dispatchlists_all=true) cellrange = PB.Grids.create_default_cellrange(ocean_domain, ocean_domain.grid) cellranges = [cellrange] PB.dispatch_setup(model, :setup, modeldata, cellranges) PB.dispatch_setup(model, :norm_value, modeldata, cellranges) PB.dispatch_setup(model, :initial_value, modeldata, cellranges) dispatchlists = modeldata.dispatchlists_all hostvardata[] = 23.0 PB.do_deriv(dispatchlists) all_vars = PB.VariableAggregatorNamed(modeldata) @info "allvars: $all_vars" all_data = all_vars.values # NB: "ocean.julia_paleo_mock/scalar_prop" substitute / --> __ @test all_data.ocean.julia_paleo_mock__scalar_prop == hostvardata @test all_data.ocean.mock_phy == fill(0.15, dsize) model = nothing end @testset "Cartesian Linear 2D" begin model = PB.create_model_from_config(joinpath(@__DIR__, "configgrids.yaml"), "cartesianlinear2D") # Test domains @test PB.get_num_domains(model) == 1 surface_domain = PB.get_domain(model, "surface") dsize = (144, 90) @test PB.get_length(surface_domain) == prod(dsize) modeldata = PB.create_modeldata(model) PB.allocate_variables!(model, modeldata, 1; check_units_opt=:error) @test PB.check_ready(model, modeldata; throw_on_error=false) == true modelcreated_vars_dict = Dict([(var.name, var) for var in PB.get_variables(surface_domain, hostdep=false)]) PB.initialize_reactiondata!(model, modeldata; create_dispatchlists_all=true) PB.dispatch_setup(model, :setup, modeldata) PB.dispatch_setup(model, :norm_value, modeldata) PB.dispatch_setup(model, :initial_value, modeldata) Asurf = PB.get_data(modelcreated_vars_dict["Asurf"], modeldata) @test length(Asurf) == prod(dsize) @test size(Asurf) == (prod(dsize), ) # linear Vector @test isapprox(sum(Asurf), 4*pi*6.371229e6^2, rtol=1e-14) model = nothing end @testset "Cartesian Array 2D" begin model = PB.create_model_from_config(joinpath(@__DIR__, "configgrids.yaml"), "cartesianarray2D") # Test domains @test PB.get_num_domains(model) == 1 surface_domain = PB.get_domain(model, "surface") dsize = (144, 90) @test PB.get_length(surface_domain) == prod(dsize) modeldata = PB.create_modeldata(model) PB.allocate_variables!(model, modeldata, 1; check_units_opt=:error) @test PB.check_ready(model, modeldata, throw_on_error=false) == true modelcreated_vars_dict = Dict([(var.name, var) for var in PB.get_variables(surface_domain, hostdep=false)]) PB.initialize_reactiondata!(model, modeldata; create_dispatchlists_all=true) PB.dispatch_setup(model, :setup, modeldata) PB.dispatch_setup(model, :norm_value, modeldata) PB.dispatch_setup(model, :initial_value, modeldata) Asurf = PB.get_data(modelcreated_vars_dict["Asurf"], modeldata) @test length(Asurf) == prod(dsize) @test size(Asurf) == dsize # 2D Array @test isapprox(sum(Asurf), 4*pi*6.371229e6^2, rtol=1e-14) model = nothing end end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
2196
import PALEOboxes as PB using Test # import Infiltrator include("ReactionRateStoichMock.jl") @testset "RateStoich" begin model = PB.create_model_from_config("configratestoich.yaml", "model1") domain = PB.get_domain(model, "ocean") domain.grid = PB.Grids.UnstructuredVectorGrid(ncells=10) @test PB.get_length(domain) == 10 modeldata = PB.create_modeldata(model) PB.allocate_variables!(model, modeldata, 1; check_units_opt=:error) PB.check_ready(model, modeldata) all_vars = PB.VariableAggregatorNamed(modeldata) all_data = all_vars.values PB.initialize_reactiondata!(model, modeldata; create_dispatchlists_all=true) PB.dispatch_setup(model, :setup, modeldata) PB.dispatch_setup(model, :norm_value, modeldata) PB.dispatch_setup(model, :initial_value, modeldata) dispatchlists = modeldata.dispatchlists_all PB.do_deriv(dispatchlists) ocean_H2S = all_data.ocean.H2S # @Infiltrator.infiltrate @test PB.get_total.(ocean_H2S) == fill(10.0, 10) @test PB.get_delta.(ocean_H2S) == fill(-30.0, 10) ocean_H2S_delta = all_data.ocean.H2S_delta @test maximum(ocean_H2S_delta .- fill(-30.0, 10)) < 1e-13 ocean_myrate = all_data.ocean.myrate @test ocean_myrate == fill(42.0, 10) ocean_H2S_sms = all_data.ocean.H2S_sms @test PB.get_total.(ocean_H2S_sms) == fill(-1.0*42.0, 10) deltaabserr = abs.(PB.get_delta.(ocean_H2S_sms) .- fill(-30.0 - 10.0, 10)) @test maximum(deltaabserr) < 1e-13 ocean_SO4_sms = all_data.ocean.SO4_sms @test PB.get_total.(ocean_SO4_sms) == fill(1.0*42.0, 10) deltaabserr = abs.(PB.get_delta.(ocean_SO4_sms) .- fill(-30.0 - 10.0, 10)) @test maximum(deltaabserr) < 1e-13 @info "stoichiometry" ratevars = PB.get_variables(domain, v->PB.has_attribute(v, :rate_processname)) @test length(ratevars) == 1 rv = ratevars[1] @test rv.name == "myrate" @test PB.get_attribute(rv, :rate_processname) == "redox" speciesstoich = Dict(zip(PB.get_attribute(rv, :rate_species), PB.get_attribute(rv, :rate_stoichiometry))) @test speciesstoich == Dict("SO4::Isotope" => 1.0, "H2S::Isotope" => -1.0, "O2" => -2.0) end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
5448
using Test using Logging import PALEOboxes as PB import Infiltrator include("ReactionReservoirFlux.jl") @testset "Reactions" begin @test PB.find_reaction("ReactionReservoirScalar") == PB.Reservoirs.ReactionReservoirScalar PB.show_all_reactions() # just check runs without error end @testset "Reservoirs" begin # logfile = open("Reservoirs_log.txt", "w") # println("writing log output to ", logfile) # global_logger(SimpleLogger(logfile)) model = PB.create_model_from_config("configreservoirs.yaml", "model1") # Test domains @test PB.get_num_domains(model) == 2 global_domain = PB.get_domain(model, "global") @test global_domain.name == "global" @test PB.get_length(global_domain) == 1 ocean_domain = PB.get_domain(model, "ocean") @test PB.get_length(ocean_domain) == 1000 ocean_length = PB.get_length(ocean_domain) # test variable attribute access @test PB.get_variable_attribute(model, "global.A", :norm_value) == 3.193e17 # allocate internal variables modeldata = PB.create_modeldata(model) PB.allocate_variables!(model, modeldata, 1; hostdep=false, check_units_opt=:error) @test length( PB.get_unallocated_variables(global_domain, modeldata, 1)) == 4 @test PB.check_ready(global_domain, modeldata, throw_on_error=false) == false # allocate arrays for host dependencies and set data pointers PB.allocate_variables!(model, modeldata, 1; hostdep=true, check_units_opt=:error) @test PB.check_ready(global_domain, modeldata) == true # get all variable data arrays all_vars = PB.VariableAggregatorNamed(modeldata) @info "all_vars: $all_vars\n" all_data = all_vars.values # check state variables stateexplicit_vars, stateexplicit_sms_vars = PB.get_host_variables(global_domain, PB.VF_StateExplicit, match_deriv_suffix="_sms") @test length(stateexplicit_vars) == 2 # A and O # get global state variable aggregator global_stateexplicit_va = PB.VariableAggregator(stateexplicit_vars, fill(nothing, length(stateexplicit_vars)), modeldata, 1) stateexplicit_vars, stateexplicit_sms_vars = PB.get_host_variables(ocean_domain, PB.VF_StateExplicit, match_deriv_suffix="_sms") @test length(stateexplicit_vars) == 2 # get ocean state variable aggregator ocean_stateexplicit_va = PB.VariableAggregator(stateexplicit_vars, fill(nothing, length(stateexplicit_vars)), modeldata, 1) # get host-dependent variables global_hostdep_vars_vec = PB.get_variables(global_domain, hostdep=true) @test length(global_hostdep_vars_vec) == 4 ocean_hostdep_vars_vec = PB.get_variables(ocean_domain, hostdep=true) @test length(ocean_hostdep_vars_vec) == 4 PB.initialize_reactiondata!(model, modeldata; create_dispatchlists_all=true) @info "dispatch_setup" PB.dispatch_setup(model, :setup, modeldata) PB.dispatch_setup(model, :norm_value, modeldata) PB.dispatch_setup(model, :initial_value, modeldata) @info "global stateexplicit variables:\n" @test all_data.global.A.v[] == 3.193e18 # A @test all_data.global.A.v_moldelta[] == 2.0*3.193e18 # A_moldelta # test access via flattened vector (as used eg by an ODE solver) global_A_indices = PB.get_indices(global_stateexplicit_va, "global.A") @test global_A_indices == 2:3 stateexplicit_vector = PB.get_data(global_stateexplicit_va) @test stateexplicit_vector[global_A_indices] == [all_data.global.A.v[], all_data.global.A.v_moldelta[]] # test VariableAggregatorNamed created from VariableAggregator global_stateexplicit_data = PB.VariableAggregatorNamed(global_stateexplicit_va).values @test global_stateexplicit_data.global.A == all_data.global.A @info "global const variables:" @test all_data.global.ConstS[] == 1.0 @info "ocean host-dependent variable initialisation:\n" @test all_data.ocean.T[1] == 1.0*10.0 @test all_data.ocean.C_conc == fill(2.0, ocean_length) # take a time step dispatchlists = modeldata.dispatchlists_all PB.do_deriv(dispatchlists) @info "global model-created variables:\n" @test all_data.global.A_norm[] == 10.0 @test all_data.global.A_delta[] == 2.0 @info "ocean model-created variables:\n" @test all_data.ocean.T_conc == fill(1.0, ocean_length) @test all_data.ocean.C[1] == 2.0*10.0 PB.do_deriv(dispatchlists) # repeat do_deriv to check total is reinitialized each time step @test all_data.ocean.T_total[] == 1.0*10.0*ocean_length @test all_data.ocean.C_total[] == 2.0*10.0*ocean_length @info "sum variables:" @test all_data.ocean.vectorsum == fill(30.0, ocean_length) @test all_data.global.scalarsum[] == 4.0 @info "ocean constant concentrations" const_conc_data = all_data.ocean.const_conc @test const_conc_data.v == fill(0.1, ocean_length) @test const_conc_data.v_moldelta == fill(-0.2, ocean_length) @info "weighted mean" @test all_data.ocean.const_conc_mean[] == PB.IsotopeLinear(0.1, -0.2) @info "volume in range" @test all_data.ocean.frac[] == 1.0 @info "test complete" # close(logfile) end @testset "ReservoirsFluxes" begin # test is just that the model links correctly with flux and a constant ReactionReservoirScalar model = PB.create_model_from_config("configreservoirsfluxes.yaml", "model1") end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
1272
using Test import PALEOboxes as PB function copy_simd_fillindex!(b, a, ::Type{T}) where T # N = Val{4}() # indvec = [0,0,0,0] iter = eachindex(a) @inbounds for indices in PB.SIMDutils.SIMDIter(iter, T) # println(" indices=", indices) xs = PB.SIMDutils.vgatherind(T, a, indices) PB.SIMDutils.vscatterind!(xs, b, indices) end return nothing end function copy_scalar_fillindex!(b, a) iter = eachindex(a) ST = eltype(a) for i in PB.SIMDutils.SIMDIter(iter, ST) # println(" i=", i) xs = PB.SIMDutils.vgatherind(ST, a, i) PB.SIMDutils.vscatterind!(xs, b, i) end return nothing end function copy_fillindex!(b, a) iter = eachindex(a) for i in iter b[i] = a[i] end return nothing end @testset "scatter gather" begin a = zeros(7) a .= 42 .+ (1:length(a)) b = similar(a) fill!(b, 0.0) copy_simd_fillindex!(b, a, PB.SIMDutils.FP64P4) @test b == a b = similar(a) fill!(b, 0.0) copy_scalar_fillindex!(b, a) @test b == a b = similar(a) fill!(b, 0.0) copy_fillindex!(b, a) @test b == a a = zeros(Float32, 27) a .= 42 .+ (1:length(a)) b = similar(a) fill!(b, 0.0) copy_simd_fillindex!(b, a, PB.SIMDutils.FP32P8) @test b == a end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
357
using Test # using NBInclude import PALEOboxes as PB @testset "PALEOboxes" begin include("runfieldtests.jl") include("rundoctests.jl") include("runyamltests.jl") include("runbasetests.jl") include("rungridstests.jl") include("runreservoirtests.jl") include("runfluxtests.jl") include("runratestoichtests.jl") include("runsimdtests.jl") end # @testset
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
1302
using Test import YAML @testset "YAML.jl" begin # test YAML.jl handling of merge keys and duplicate keys # see comments in merge.yaml test file data = YAML.load_file("merge.yaml") @test length(data) == 11 # CENTER @test data[1] == Dict("x" => 1, "y" => 2) # LEFT @test data[2] == Dict("x" => 0, "y" => 2) # BIG @test data[3] == Dict("r" => 10) # SMALL @test data[4] == Dict("r" => 1) # All the following maps are equal: # explicit keys @test data[5] == Dict("label" => "center/big", "x" => 1, "r" => 10, "y" => 2) # Merge one map @test data[6] == Dict("label" => "center/big", "x" => 1, "r" => 10, "y" => 2) # Merge multiple maps @test data[7] == Dict("label" => "center/big", "x" => 1, "r" => 10, "y" => 2) # Override @test data[8] == Dict("label" => "center/big", "x" => 1, "r" => 10, "y" => 2) # SD added: testing key yaml.jl key override and merge # yaml.jl merge keys don't override explicit keys (as spec) @test data[9] == Dict("r" => 10) # yaml.jl issue ? duplicates are allowed, and later keys override earlier ones @test data[10] == Dict("r" => 10) # yaml.jl issue ? allows duplicate merge keys, and later ones override earlier ones ! @test data[11] == Dict("r" => 1) end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
code
1179
# code from https://github.com/cdsousa/SingleDispatchJuliaVsCXX # demonstrating Julia dynamic dispatch overhead using BenchmarkTools abstract type AbstrType end struct ConcrType1 <: AbstrType; x::Int; end struct ConcrType2 <: AbstrType; x::Int; end @noinline f(a) = a.x const n = 1_000_000 const arrconcr = [ConcrType1(i) for i=1:n] const arrabstr = AbstrType[rand(Bool) ? ConcrType1(i) : ConcrType2(i) for i=1:n] const arrunion = Union{ConcrType1, ConcrType2}[rand(Bool) ? ConcrType1(i) : ConcrType2(i) for i=1:n] println() println("concr") sum_arrconcr = 0::Int @btime for i=1:n @inbounds $sum_arrconcr += f($arrconcr[i]) end println("abstr") sum_arrabstr = 0::Int @btime for i=1:n @inbounds $sum_arrabstr += f($arrabstr[i]) end println("manual dispatch") # manual dispatch sum_arrabstr2 = 0::Int @btime for i=1:n @inbounds a = $arrabstr[i] T = typeof(a) if T === ConcrType1 $sum_arrabstr2 += f(a::ConcrType1) elseif T === ConcrType2 $sum_arrabstr2 += f(a::ConcrType2) else $sum_arrabstr2 += f(a) end end println("union") sum_arrunion = 0::Int @btime for i=1:n @inbounds $sum_arrunion += f($arrunion[i]) end
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
docs
1544
# PALEOboxes.jl [![CI](https://github.com/PALEOtoolkit/PALEOboxes.jl/actions/workflows/CI.yml/badge.svg)](https://github.com/PALEOtoolkit/PALEOboxes.jl/actions/workflows/CI.yml) [![](https://img.shields.io/badge/docs-dev-blue.svg)](https://PALEOtoolkit.github.io/PALEOboxes.jl/dev) 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. A [YAML](https://en.wikipedia.org/wiki/YAML) format configuration file defines both the model structure (spatial domains containing biogeochemical variables and reactions that operate on them) and model parameter values, making it straightforward to add and remove biogeochemical tracers and their interactions, change the representation of eg ocean circulation, and couple components together. Biogeochemical reaction networks can be embedded in a Fortran or C host model providing the dynamics and transport, or combined with an offline transport representation to provide a standalone model. PALEOboxes creates the model and 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.
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
docs
6723
# Control flow ```@meta CurrentModule = PALEOboxes ``` ## Model Creation A [YAML](https://en.wikipedia.org/wiki/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`](@ref)) 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`](@ref) which reads the configuration file, and then: - creates model [`Domain`](@ref)s and Reactions (subtypes of [`AbstractReaction`](@ref)), applying any [`Parameter`](@ref)s settings from the `parameters:` sections in the config file. - calls [`set_model_geometry`](@ref) allowing Reactions to create and attach Grids ([`AbstractMesh`](@ref) subtypes) defining [`Domain`](@ref) sizes. - calls [`register_methods!`](@ref) on each Reaction, allowing Reactions to define local [`VariableReaction`](@ref)s and register [`ReactionMethod`](@ref)s. [`ReactionMethod`](@ref)s can be added to one of three groups, by calling [`add_method_setup!`](@ref) (called during model setup), [`add_method_initialize!`](@ref) (called at start of main loop) [`add_method_do!`](@ref) (called during main loop). - links [`VariableReaction`](@ref)s to [`VariableDomain`](@ref)s, applying any renaming from the `variable_links:` sections in the config file. - calls [`register_dynamic_methods!`](@ref) on each Reaction, allowing Reactions to create [`VariableReaction`](@ref)s and register [`ReactionMethod`](@ref)s that depend on [`VariableDomain`](@ref)s created by other Reactions. - relinks [`VariableReaction`](@ref)s to [`VariableDomain`](@ref)s to include these additional [`VariableReaction`](@ref)s - sorts each group of [`ReactionMethod`](@ref)s into dispatch order based on dependencies between Variables, storing the sorted lists in the [`Model`](@ref) struct. ## Model initialisation To initialise the model, the numerical solver or host should then: - call [`create_modeldata`](@ref) to create a [`ModelData`](@ref) struct that will store data Arrays for model Variables. A default Vector of [`CellRange`](@ref)s covering the whole model, generated by [`create_default_cellrange`](@ref), is also stored in the `cellranges_all` field of the [`ModelData`](@ref) struct. - call [`allocate_variables!`](@ref) to allocate memory for model Variables, storing these Array references in the [`ModelData`](@ref) struct. - call [`check_ready`](@ref) to check that all Variables are allocated. - call [`initialize_reactiondata!`](@ref) to: - store sorted lists of [`ReactionMethod`](@ref)s and corresponding Variable array accessors in the [`ModelData`](@ref) struct. A [`ReactionMethod`](@ref) may include a prepare function to include additional buffers etc. - call [`create_dispatch_methodlists`](@ref) to compile default model-wide lists of `initialize` and `do` methods + corresponding Variable array accessors and [`CellRange`](@ref)s. This is stored as the in the `dispatchlists_all` of the [`ModelData`](@ref) struct. - call [`check_configuration`](@ref) to call any optional [`check_configuration`](@ref) Reaction methods to validate the model configuration. - call [`dispatch_setup`](@ref) with `attribute_name = :setup`, which calls Reaction setup methods (registered by [`add_method_setup!`](@ref)) to initialise any internal Reaction state and any non-state Variables (eg grid variables). ## State Variable initialization To initialise state Variables and perform any Reaction-specific initialisation, the numerical solver or host should: - call [`dispatch_setup`](@ref) 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`](@ref) to the solver. - optionally call [`dispatch_setup`](@ref) 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: - call [`do_deriv`](@ref) to call lists of `initialize` and `do` methods created by [`create_dispatch_methodlists`](@ref) ## 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`](@ref) struct. A custom Vector of [`CellRange`](@ref)s can be used to select a subset of [`ReactionMethod`](@ref)s by [`Domain`](@ref) and `operatorID`, eg to implement operator splitting. Tiles within [`Domain`](@ref) eg to implement Domain decomposition for a multithreaded model can be defined by specifying [`CellRange`](@ref)s with a subset of cell indices within [`Domain`](@ref)s. The custom Vector of [`CellRange`](@ref)s should then be supplied to - [`create_dispatch_methodlists`](@ref) to create lists of methods + corresponding [`CellRange`](@ref)s which can then be supplied to [`do_deriv`](@ref) for the model main loop. - Optionally to [`VariableAggregator`](@ref)s to create subsets of Variables and tiles within [`Domain`](@ref)s for a numerical solver. ### Multithreaded models To use with a multithreaded solver eg for a spatially tiled model: - Set `threadsafe=true` when calling [`create_modeldata`](@ref). The subsequent call to [`allocate_variables!`](@ref) 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!`](@ref). 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`](@ref) to the appropriate dual number type for a (forward) automatic differentation implementation. All model arrays are held in the created [`ModelData`](@ref) struct and multiple [`ModelData`](@ref) instances can be created, allowing a combination of eg AD Jacobian and standard derivative calculations with different array types.
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
docs
9715
# PALEOboxes coupler design ```@meta CurrentModule = PALEOboxes ``` A PALEO [`Model`](@ref) contains [`Domain`](@ref)s, each of which contain Variables defining [`Field`](@ref)s containing `Data` arrays, and Reactions with [`ReactionMethod`](@ref)s 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`](@ref)), 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](https://en.wikipedia.org/wiki/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`](@ref) ###### Figure 1 ![](images/ocean_domain.png) *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 [`Parameter`](@ref)s and are implemented as subtypes of [`AbstractReaction`](@ref) along with associated methods. [`ReactionMethod`](@ref)s and [`VariableReaction`](@ref)s 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 [`ReactionMethod`](@ref)s as they are called during the model main loop. ### Biogeochemical Variables Variables defined as [`VariableReaction`](@ref)s are then linked within (or across) Domains, creating corresponding [`VariableDomain`](@ref)s. 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](@ref), linked at run time to [`Domain`](@ref) [`VariableDomPropDep`](@ref)s), or flux Targets and Contributors (shaded pink in [Figure 1](@ref), linked at run-time to [`Domain`](@ref) [`VariableDomContribTarget`](@ref)s). 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`](@ref)) and filtered on (using [`get_variables`](@ref)) 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`](@ref)) to define a spatially-resolved Domain containing multiple cells. Three-dimensional [`Domain`](@ref)s (eg ocean) are associated with two-dimensional boundary [`Domain`](@ref)s (eg oceansurface, oceanfloor), and also provide [Subdomains](@ref) (subtypes of [`AbstractSubdomain`](@ref), eg ocean.oceansurface, ocean.oceanfloor) that specify the subset of 3D ocean cells adjacent to the 2D boundaries. ### Fields and Data Variables contain [`Field`](@ref)s which represent data (a subtype of [`AbstractData`](@ref) defined by the `:field_data` ttribute) in a function space (a subtype of [`AbstractSpace`](@ref) defined by the `:space` attribute). The [`AbstractSpace`](@ref) subtype (see [Spaces](@ref)) can define a per-Domain ([`ScalarSpace`](@ref)) or per-cell ([`CellSpace`](@ref)) quantity, where the number of cells is defined by the Domain grid. The [`AbstractData`](@ref) subtype (see [Data types](@ref)) defines the information that is stored per Domain or per grid cell. [`ScalarData`](@ref) defines one value, [`ArrayScalarData`](@ref) an array of scalar values eg for intensity on a wavelength grid, and [`AbstractIsotopeScalar`](@ref) a multiple-component isotope system (see [Isotopes](@ref)). ## Coupling Spatial Domains ###### Figure 2 ![](images/multiple_domains.png) *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 flux_O2. 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](@ref), implemented by [`Fluxes.ReactionFluxTarget`](@ref)s ([Figure 2](@ref)) that provide a set of flux Target Variables in nominated flux coupler [`Domain`](@ref)s, and [`Fluxes.ReactionFluxTransfer`](@ref) that then transfer fluxes (with appropriate mapping) to a different [`Domain`](@ref). Variable text names may be referred to from other [`Domain`](@ref)s 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 ![](images/solver_domains.png) *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`](@ref) to implement a high-level interface to aggregated lists. A host dynamical model can alternatively use [`get_variables`](@ref) 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](@ref)). 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
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
docs
4686
# Domains, Variables, Fields, and Data arrays. ```@meta CurrentModule = PALEOboxes ``` A [`Model`](@ref) contains [`Domain`](@ref)s, each of which contain [Variables](@ref) defining [`Field`](@ref)s which contain `Data` arrays, and `Reactions` with [`ReactionMethod`](@ref)s that operate on the [`Field`](@ref)s to calculate model time evolution. ## Model ```@meta CurrentModule = PALEOboxes ``` ```@docs Model ``` ## Domains ```@meta CurrentModule = PALEOboxes ``` ```@docs Domain ``` ### Grids ```@meta CurrentModule = PALEOboxes ``` ```@docs AbstractMesh internal_size cartesian_size ``` ```@meta CurrentModule = PALEOboxes.Grids ``` ```@docs set_subdomain! get_subdomain UnstructuredVectorGrid UnstructuredColumnGrid CartesianLinearGrid CartesianArrayGrid ``` #### Subdomains ```@meta CurrentModule = PALEOboxes ``` ```@docs AbstractSubdomain ``` ```@meta CurrentModule = PALEOboxes.Grids ``` ```@docs BoundarySubdomain InteriorSubdomain subdomain_view subdomain_indices ``` #### Regions, Dimensions and Coordinates ```@meta CurrentModule = PALEOboxes.Grids ``` ```@docs get_region ``` 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. ```@meta CurrentModule = PALEOboxes ``` ```@docs NamedDimension FixedCoord ``` ## Variables ```@meta CurrentModule = PALEOboxes ``` PALEO `Variables` exist in [`Domain`](@ref)s and represent biogeochemical or other quantities. They are defined by `Reactions` as [`VariableReaction`](@ref)s which are then linked to create [`VariableDomain`](@ref)s, and contain [`Field`](@ref)s which represent data (a subtype of [`AbstractData`](@ref)) in a function space (a subtype of [`AbstractSpace`](@ref)) with dimensions defined by the Domain grid (a subtype of [`AbstractMesh`](@ref)) Dataflow dependency between `Variables` is represented by two pairings: - [`VariableReaction`](@ref)s of [`VariableType`](@ref) `VT_ReactProperty` and `VT_ReactDependency` which are linked to create [`VariableDomPropDep`](@ref)s - [`VariableReaction`](@ref)s of [`VariableType`](@ref) `VT_ReactTarget` and `VT_ReactContributor` which are linked to create [`VariableDomContribTarget`](@ref)s. ```@docs VariableBase VariableType VariableDomain VariableDomPropDep VariableDomContribTarget ``` ### Variable Attributes ```@meta CurrentModule = PALEOboxes ``` ```@docs Attribute StandardAttributes ``` ```@example import PALEOboxes as PB # hide import DataFrames # hide show( # hide DataFrames.sort!( # hide DataFrames.DataFrame((s=>getproperty.(PB.StandardAttributes, s) for s in (:name, :default_value, :required, :units, :description))...), # hide [DataFrames.order(:required, rev=true), :name] # hide ); # hide allcols=true, allrows=true, truncate=96, show_row_number=false #hide ) # hide ``` ```@docs get_attribute VariableFunction VariablePhase ``` TODO standard Variable names. Use NetCDF CF standard names <https://cfconventions.org/Data/cf-standard-names/76/build/cf-standard-name-table.html> ? ## Fields ```@meta CurrentModule = PALEOboxes ``` Field, data and function space are defined by Variable [`Attribute`](@ref)s in combination with an [`AbstractMesh`](@ref) - `:field_data` and optionally `:data_dims` define the subtype of [`AbstractData`](@ref) - `:space` defines the subtype of [`AbstractSpace`](@ref) Examples: - `:field_data` = [`ScalarData`](@ref), `:space` = [`ScalarSpace`](@ref) defines a Domain scalar (0D) quantity. - `:field_data` = [`IsotopeLinear`](@ref), `:space` = [`ScalarSpace`](@ref) defines a Domain scalar (0D) isotope quantity. - `:field_data` = [`ScalarData`](@ref), `:space` = [`CellSpace`](@ref) defines a per-cell quantity in a spatial Domain. - `:field_data` = [`ArrayScalarData`](@ref), `:data_dims =("wgrid",)` `:space` = [`ScalarSpace`](@ref) defines a Domain scalar (0D) quantity on a wavelength grid, a Vector of length given by the value of the Domain "wgrid" data dimension (see [`set_data_dimension!`](@ref)) ```@docs Field get_field wrap_field ``` ## Spaces ```@meta CurrentModule = PALEOboxes ``` ```@docs AbstractSpace ScalarSpace CellSpace ColumnSpace ``` ## Data types ```@meta CurrentModule = PALEOboxes ``` ```@docs AbstractData UndefinedData ScalarData ArrayScalarData allocate_values check_values zero_values! dof_values get_values_output init_values! copyfieldto! copytofield! add_field! add_field_vec! num_components(field_data::Type{<:AbstractData}) get_components ``` ### Isotopes ```@meta CurrentModule = PALEOboxes ``` ```@docs AbstractIsotopeScalar IsotopeLinear isotope_totaldelta get_total get_delta ```
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
docs
6767
# Reaction API ```@meta CurrentModule = PALEOboxes ``` API calls used by [`AbstractReaction`](@ref) implementations. Implementations should create a subclass of [`AbstractReaction`](@ref) containing a [`ReactionBase`](@ref) and [`Parameter`](@ref)s, optionally provide a [`create_reaction`](@ref), and implement callbacks to define [`VariableReaction`](@ref)s and register [`ReactionMethod`](@ref)s. ## Reaction struct ```@meta CurrentModule = PALEOboxes ``` ```@docs AbstractReaction ReactionBase ``` ## Parameters ```@docs AbstractParameter Parameter VecParameter VecVecParameter ParametersTuple add_par setvalue! ``` ## Registering Reactions with the PALEOboxes framework All subtypes of [`AbstractReaction`](@ref) that are present in loaded modules are available to the PALEO framework. Available Reactions can be listed with [`find_reaction`](@ref) and [`find_all_reactions`](@ref). The default [`create_reaction`](@ref) is called to create Reactions when the model is created (this method can be overridden if needed). ```@docs create_reaction(ReactionType::Type{<:AbstractReaction}, base::ReactionBase) find_reaction find_all_reactions ``` ## Defining Domain Grids and array sizes ```@docs set_model_geometry set_data_dimension! ``` ## Creating and registering Reaction methods All Reactions should implement [`register_methods!`](@ref), and may optionally implement [`register_dynamic_methods!`](@ref). ```@docs register_methods! register_dynamic_methods! ``` These methods should then define one or more [`ReactionMethod`](@ref)s, which requires: - Defining collections of [`VariableReaction`](@ref)s (see [Defining VariableReactions](@ref), [Defining collections of VariableReactions](@ref)). - Implementing a function to iterate over model cells and calculate the required fluxes etc (see [Implementing method functions](@ref)) - Adding methods (see [Adding ReactionMethods](@ref)). In addition it is possible to add [Predefined ReactionMethods](@ref) for some common operations (Variable initialisation, calculating totals, etc). ### Defining VariableReactions ```@docs VariableReaction parse_variablereaction_namestr set_attribute! ``` ### Defining collections of VariableReactions ```@docs AbstractVarList VarList_single VarList_namedtuple VarList_tuple VarList_ttuple VarList_vector VarList_vvector VarList_nothing ``` ### 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 # etc end return nothing end #### Iterating over cells in columns If necessary (eg to calculate vertical transport), provided the model grid and cellrange allow, it is possible to iterate over columns and then cells within columns (in order from top to bottom): function do_something_columnwise(m::PB.AbstractReactionMethod, pars, (vars, ), cellrange::PB.AbstractCellRange, deltat) @inbounds for (icol, colindices) in cellrange.columns accum = zero(vars.A[first(colindices)]) # accumulator of appropriate type for i in colindices # order is top to bottom accum += vars.A[i] vars.C[i] = accum # C = sum of A in cells above # etc end vars.floor_C[icol] = vars.C[last(colindices)] # assumes model has a floor domain with one floor cell per column in the interior domain end return nothing end Iteration from bottom to top within a column can be implemented using `Iterators.reverse`, eg function do_something_columnwise(m::PB.AbstractReactionMethod, pars, (vars, ), cellrange::PB.AbstractCellRange, deltat) @inbounds for (icol, colindices) in cellrange.columns colreverse = Iterators.reverse(colindices) for i in colreverse # order is bottom to top # etc end end return nothing end !!! note The method function shouldn't make any assumptions about `colindices` other than that it is a list of indices ordered from top to bottom in a column. Depending on the grid in use, the indices may not be contiguous, and may not be integers. !!! note The example above made the additional assumption that a `floor` domain had been defined (containing Variable `floor_C`) with one floor cell per column. This is determined by the model configuration, and is not true in general. In rare cases where it is necessary to operate on a Vector representing a quantity for the whole column (rather than just iterate through it), this can be implemented using `view`, eg function do_something_columnwise(m::PB.AbstractReactionMethod, pars, (vars, ), cellrange::PB.AbstractCellRange, deltat) @inbounds for (icol, colindices) in cellrange.columns A_col = view(vars.A, colindices) # A_col is an AbstractVector with contiguous indices 1:length(colindices) B_col = view(vars.B, colindices) # B_col is an AbstractVector with contiguous indices 1:length(colindices) # do something that needs a vector of cells for a whole column end return nothing end #### Optimising loops over cells using explicit SIMD instructions Reactions with simple loops over `cellindices` that implement time-consuming per-cell calculations may be optimised by using explicit SIMD instructions. ```@docs SIMDutils.SIMDIter ``` ### Adding ReactionMethods ```@docs ReactionMethod add_method_setup! add_method_initialize! add_method_do! ``` ## Predefined ReactionMethods ### Setup and initialization of Variables ```@docs add_method_setup_initialvalue_vars_default! add_method_initialize_zero_vars_default! ``` ### Adding totals for Variables ```@docs add_method_do_totals_default! ``` ### Chemical reactions ```@docs RateStoich create_ratestoich_method add_rate_stoichiometry! ``` ## Internal details of Variable arrays accessor generation [`VariableReaction`](@ref)s in the [`AbstractVarList`](@ref)s for a [`ReactionMethod`](@ref) are processed by [`create_accessor`](@ref) to supply `view`s on arrays as corresponding arguments to the [`ReactionMethod`](@ref) function. ```@docs create_accessor create_accessors ```
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
docs
1552
# Generic Reaction catalog ```@meta CurrentModule = PALEOboxes ``` PALEOboxes includes a catalog of generic Reactions as a starting point for model construction. ## Reservoirs ```@meta CurrentModule = PALEOboxes.Reservoirs ``` ```@docs ReactionReservoirScalar ReactionReservoir ReactionReservoirWellMixed ReactionReservoirConst ReactionReservoirForced ReactionConst ``` ### Linking to Reservoirs from a Reaction ```@docs ReservoirLinksVector ``` ## Variable Statistics ```@meta CurrentModule = PALEOboxes.VariableStats ``` ```@docs ReactionSum ReactionWeightedMean ReactionAreaVolumeValInRange ``` ## Fluxes ```@meta CurrentModule = PALEOboxes ``` ```@docs Fluxes ``` ```@meta CurrentModule = PALEOboxes.Fluxes ``` ```@docs ReactionFluxTarget ReactionFluxTransfer ``` ### Contributing to flux couplers from a Reaction ```@docs FluxContrib ``` ```@meta CurrentModule = PALEOboxes ``` ## Forcings ```@docs Forcings.ReactionForceInterp GridForcings.ReactionForceGrid FluxPerturb.ReactionFluxPerturb FluxPerturb.ReactionRestore ``` ## 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). ```@meta CurrentModule = PALEOboxes.GridReactions ``` ```@docs ReactionUnstructuredVectorGrid ReactionCartesianGrid ReactionGrid2DNetCDF ```
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
docs
35
# References ```@bibliography ```
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
docs
2498
# Solver API ```@meta CurrentModule = PALEOboxes ``` A [`Model`](@ref) contains [`Domain`](@ref)s, each of which contain [Variables](@ref) defining [`Field`](@ref)s, and `Reactions` with [`ReactionMethod`](@ref)s that operate on the [`Field`](@ref)s to calculate model time evolution. ## Create and initialise ```@meta CurrentModule = PALEOboxes ``` ```@docs create_model_from_config(config_file::AbstractString, configmodel::AbstractString) create_modeldata(model::Model, vectype::DataType=Array{Float64,1}) ModelData add_arrays_data! push_arrays_data! allocate_variables! check_ready(model::Model, modeldata::AbstractModelData; throw_on_error=true) check_configuration(model::Model) initialize_reactiondata!(model::Model, modeldata::AbstractModelData) dispatch_setup create_dispatch_methodlists ReactionMethodDispatchList ``` ## Attaching numerical solvers High-level access to aggregated collections of Variables is provided by [`VariableAggregator`](@ref) and [`VariableAggregatorNamed`](@ref) (see [Accessing model objects](@ref) for low-level access). ```@docs VariableAggregator get_indices copyto!(dest::VariableAggregator, src::AbstractVector; sof::Int=1) copyto!(dest::AbstractVector, src::VariableAggregator; dof::Int=1) VariableAggregatorNamed ``` Aggregated collections of a subset of Parameters as a flattened Vector (eg for sensitivity studies) is provided by [`ParameterAggregator`](@ref): ```@docs ParameterAggregator ``` ## Defining CellRanges ```@meta CurrentModule = PALEOboxes ``` ```@docs AbstractCellRange CellRange CellRangeColumns create_default_cellrange ``` ```@meta CurrentModule = PALEOboxes.Grids ``` ```@docs create_default_cellrange cellrange_cartesiantile ``` ## Main loop ```@meta CurrentModule = PALEOboxes ``` ```@docs do_deriv dispatch_methodlist ``` ## Diagnostics ```@meta CurrentModule = PALEOboxes ``` ```@docs show_methods_setup show_methods_initialize show_methods_do show_variables show_links show_parameters ``` ## Accessing model objects ### [`Model`](@ref) ```@docs get_domain get_reaction(model::Model, domainname, reactionname) set_parameter_value! get_parameter_value set_variable_attribute! get_variable_attribute ``` ### [`Domain`](@ref)s ```@docs get_variable get_variables get_host_variables get_unallocated_variables get_reaction(domain::Domain, reactname::String) ``` ### VariableDomain Low-level access to individual [Variables](@ref). ```@meta CurrentModule = PALEOboxes ``` ```@docs set_data! get_data get_data_output ```
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
docs
540
# 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.
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.21.29
52cfdf2df400205dd8912e997224331d6d185f6a
docs
25
# Index ```@index ```
PALEOboxes
https://github.com/PALEOtoolkit/PALEOboxes.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
code
1596
using Documenter, Sisyphus, QuantumOptics sourcedir = "examples/" markdowndir = "markdown" targetpath_examples = "docs/src/examples/" names = filter(name -> endswith(name, ".ipynb"), readdir(sourcedir)) function convert2markdown(name) sourcepath = joinpath(sourcedir, name) println(sourcepath) run( `jupyter-nbconvert --to markdown --output-dir=$markdowndir $sourcepath --template=docs/markdown_template.tpl`, ) end for name in names convert2markdown(name) end cp(markdowndir, targetpath_examples; force = true) rm(markdowndir; recursive = true) makedocs( sitename = "Sisyphus.jl", format = Documenter.HTML(prettyurls = false), pages = [ "Home" => "index.md", "Installation" => "installation.md", "Introduction" => "introduction.md", "Gradient-based QOC" => "gbqoc.md", "Open quantum systems" => "noisy.md", "Tutorial" => "tutorial.md", "Examples" => [ "DRAG" => "examples/DRAG.md", "Two-level system" => "examples/TwoLevelSystem.md", "Noisy two-level system" => "examples/TwoLevelSystemNoisy.md", "Rₓ(π/2)" => "examples/RXpi2.md", "√iSWAP" => "examples/SQRTiSWAP.md", "CZ" => "examples/CZ2.md", "GHZ state" => "examples/GHZState.md", "GHZ state 12 atoms (CUDA)" => "examples/GHZStateCUDANeuralNetwork.md", "GHZ state 16 atoms (CUDA)" => "examples/GHZStateCUDALinearInterp.md", ], "API" => "api.md", ], ) deploydocs(repo = "github.com/SatyaBade12/Sisyphus.jl.git")
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
code
970
module Sisyphus import QuantumOpticsBase using QuantumOpticsBase: IncompatibleBases using QuantumOptics using SparseArrays using MKLSparse using LinearAlgebra using OrdinaryDiffEq using Flux: jacobian using Flux using CUDA import CUDA: cu using CUDA.CUSPARSE using ProgressMeter: Progress, next! using DataStructures using NLopt: Opt import NLopt import CommonSolve: solve!, init, solve import Base: convert include("hamiltonian.jl") include("transforms.jl") include("cost.jl") include("problem.jl") include("solver.jl") include("evolution.jl") include("vectorization.jl") include("utils.jl") export Transform, StateTransform, Hamiltonian, UnitaryTransform, Solution, CostFunction, QOCProblem, schroedinger_dynamic, master_dynamic, AdjointSolver, solve!, init, solve, cu, CuKet, convert, vectorize, heaviside, interval, piecewise_const_interp, linear_interp, cubic_spline_interp end
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
code
896
""" CostFunction(distance, constraints) Defines a cost function used for optimization. # Arguments `distance` denotes a distance measure between quantum states, it should be a real valued function for e.g. `d(x,y) = 1 - real(x'*y)` where `x` and `y` are two complex valued vectors. `constraints` (optional) denotes the constraints on the shapes of pulses, it should be a real valued function NOTE: During the optimization we minimize the total cost given by the sum of average distance (considering all states in the transform) evaluated for a given set of parameters and the constraints. i.e. `d(x,y) + constraints(params)`. """ mutable struct CostFunction distance::Function constraints::Union{Function,Nothing} function CostFunction( distance::Function, constraints::Union{Function,Nothing} = nothing, ) new(distance, constraints) end end
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
code
1498
""" schroedinger_dynamic(tspan, psi, h, params; kwargs) Wraps `schroedinger_dynamic` from QuantumOptics by accepting our custom [`Hamiltonian`](@ref) structure and the parameters. """ function schroedinger_dynamic( tspan, psi::Ket, h::Hamiltonian{T}, params::Vector{T}; kwargs..., ) where {T<:Real} n_coeffs = length(h.operators) const_op = Operator(h.basis_l, h.basis_r, h.const_op) ops = [Operator(h.basis_l, h.basis_r, op) for op in h.operators] func(t, psi) = let coeffs = h.drives(params, t) const_op + sum([coeffs[i] * ops[i] for i = 1:n_coeffs]) end timeevolution.schroedinger_dynamic(tspan, psi, func; kwargs...) end """ master_dynamic(tspan, psi, h, params, J, rates; kwargs) Wraps `master_dynamic` from QuantumOptics by accepting our custom [`Hamiltonian`](@ref) structure and the parameters. """ function master_dynamic( tspan, psi, h::Hamiltonian, params::Vector{T}, J::Vector{<:AbstractOperator}, rates::Vector{T}; kwargs..., ) where {T<:Real} n_coeffs = length(h.operators) const_op = Operator(h.basis_l, h.basis_r, h.const_op) ops = [Operator(h.basis_l, h.basis_r, op) for op in h.operators] Jdagger = [dagger(op) for op in J] func(t, psi) = let coeffs = h.drives(params, t) (const_op + sum([coeffs[i] * ops[i] for i = 1:n_coeffs]), J, Jdagger, rates) end timeevolution.master_dynamic(tspan, psi, func; kwargs...) end
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
code
1989
""" Hamiltonian(const_op::op, ops::Vector{op}), drives::Function) where {op<:AbstractOperator} Structure to represent a time-dependent Hamiltonian. NOTE: Drives are required to be real-valued functions and should be of the form `drives(p::Vector{T}, t::T) where {T<:Real}`, where `p` is a vector of real values parametrizing the control knobs and `t` is the time. """ mutable struct Hamiltonian{T<:Real} const_op::AbstractMatrix{Complex{T}} basis_l::Basis basis_r::Basis operators::Vector{AbstractMatrix{Complex{T}}} drives::Function function Hamiltonian( const_op::op, ops::Vector{op}, drives::Function, ) where {op<:AbstractOperator} h = new{real(eltype(const_op.data))}() h.basis_l = const_op.basis_l h.basis_r = const_op.basis_r h.const_op = const_op.data h.operators = [op.data for op in ops] h.drives = drives h end function Hamiltonian( const_op::mat, basis_l::Basis, basis_r::Basis, operators::Vector{mat}, drives::Function, ) where {T<:Real,mat<:AbstractMatrix{Complex{T}}} h = new{T}() h.basis_l = basis_l h.basis_r = basis_r h.const_op = const_op h.operators = operators h.drives = drives h end end """ cu(h::Hamiltonian) Converts the Hamiltonian with the operators allocated on GPU memory. """ cu(h::Hamiltonian) = Hamiltonian( CuSparseMatrixCSC(h.const_op), h.basis_l, h.basis_r, [CuSparseMatrixCSC(op) for op in h.operators], h.drives, ) """ convert(::Type{Float32}, h::Hamiltonian) Returns a Hamiltonian with all operators in single precision. """ Base.convert(::Type{Float32}, h::Hamiltonian) = Hamiltonian( SparseMatrixCSC{ComplexF32,Int64}(h.const_op), h.basis_l, h.basis_r, [SparseMatrixCSC{ComplexF32,Int64}(op) for op in h.operators], h.drives, )
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
code
901
""" QOCProblem(hamiltonian::Hamiltonian{T}, transform::Transform, tspan::Tuple{T,T}}, cost::CostFunction) where {T<:Real} Defines a quantum optimal control problem to be solved. """ struct QOCProblem{T<:Real} hamiltonian::Hamiltonian{T} transform::Transform tspan::Tuple{T,T} cost::CostFunction end """ cu(prob) Turns a quantum optimal control problem into a form suitable for running on GPU. """ cu(prob::QOCProblem) = QOCProblem(cu(prob.hamiltonian), cu(prob.transform), prob.tspan, prob.cost) """ convert(::Type{Float32}, prob::QOCProblem) Returns a QOCProblem with all data in single precision. """ Base.convert(::Type{Float32}, prob::QOCProblem) = QOCProblem( convert(Float32, prob.hamiltonian), convert(ComplexF32, prob.transform), (Float32(prob.tspan[1]), Float32(prob.tspan[2])), prob.cost, )
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
code
11063
""" Solution(params) Contains the optimized parameters after solving the QOCProblem. It also contains traces of distance and constraints specified in the CostFunction. Optionally, it contains the full trace of parameters. """ mutable struct Solution{T<:Real} params::Vector{T} distance_trace::Vector{T} constraints_trace::Vector{T} params_trace::Vector{Vector{T}} function Solution(params::Vector{T}) where {T<:Real} s = new{T}() s.params = params s.distance_trace = T[] s.constraints_trace = T[] s.params_trace = T[] s end end """ AdjointSolver Solver to evaluate gradients by solving the coupled equations, defined for compatibility with CommonSolve interface. """ mutable struct AdjointSolver{T<:Real} initial_params::Vector{T} ode_prob::ODEProblem opt::Any alg::Any drives::Function gradients::Function const_op::AbstractMatrix{Complex{T}} ops::Vector{AbstractMatrix{Complex{T}}} target::AbstractMatrix{Complex{T}} cost::CostFunction n_dim::Integer n_iter::Integer save_iters::AbstractRange kwargs::Any end """ init(prob, args; kwargs) Initializes the [`QOCProblem`](@ref) by providing the arguments for the choice of the optimizer and differential equations solver. Used for the common solve abstraction. """ function init(prob::QOCProblem{T}, args...; kwargs...) where {T<:Real} initial_params, opt = args alg = :alg in keys(kwargs) ? kwargs[:alg] : Tsit5() maxiter = :maxiter in keys(kwargs) ? kwargs[:maxiter] : 100 save_iters = :save_iters in keys(kwargs) ? kwargs[:save_iters] : 1:-1 kwargs_dict = Dict() for k in collect(Base.pairs(kwargs)) if k[1] ∉ [:alg, :maxiter, :save_iters] kwargs_dict[k[1]] = k[2] end end const_op = prob.hamiltonian.const_op ops = prob.hamiltonian.operators drives = prob.hamiltonian.drives n_params = length(initial_params) check_compatibility(drives, length(ops), n_params, T) psi, n_dim, wf_dim = input_data(prob.transform, n_params) check_compatibility(prob.cost, wf_dim, n_params, T) gradients(ps, t) = jacobian((_ps, _t) -> drives(_ps, _t), ps, t)[1] ode_prob = ODEProblem{true}( adjoint_system!, psi, prob.tspan, ((const_op, ops), (drives, gradients), n_dim, initial_params), ) target = output_data(prob.transform) AdjointSolver( copy(initial_params), ode_prob, opt, alg, drives, gradients, const_op, ops, target, prob.cost, n_dim, maxiter, save_iters, (;kwargs_dict...), ) end """ solve!(solver::AdjointSolver{T}) where {T<:Real} Solves the quantum optimal control problem. """ function solve!(solver::AdjointSolver{T}) where {T<:Real} drives = solver.drives cost = solver.cost constraint_gradient(θ) = cost.constraints == nothing ? T(0) : gradient(ps -> cost.constraints(ps), θ)[1] distance_gradient(x, y) = gradient((_x, _y) -> cost.distance(_x, _y), x, y)[2] drives_gradients(ps, t) = jacobian((_ps, _t) -> drives(_ps, _t), ps, t)[1] sol = Solution(solver.initial_params) optimize!( sol, solver.opt, solver, drives_gradients, constraint_gradient, distance_gradient, ) end function adjoint_system!( dpsi::AbstractMatrix{Complex{T}}, psi::AbstractMatrix{Complex{T}}, p::Tuple{Tuple{op,Vector{op}},Tuple{Function,Function},Vector{T},Integer}, t::T, ) where {T<:Real,op<:AbstractMatrix{Complex{T}}} ops, (_ct, _gt), params, n_dim = p n_ops = length(ops[2]) ct = _ct(params, t) mul!(dpsi, ops[1], psi, -T(1)im, T(0)im) @inbounds for i = 1:n_ops mul!(dpsi, ops[2][i], psi, -T(1)im * T(ct[i]), T(1) + T(0)im) end gt = _gt(params, t) _psi = @view psi[:, 1:n_dim] @inbounds for i = 1:length(params) _dpsi = @view dpsi[:, n_dim*i+1:n_dim*(i+1)] @inbounds for j = 1:n_ops mul!(_dpsi, ops[2][j], _psi, -T(1)im * T(gt[j, i]), T(1) + T(0)im) end end end function input_data(t::UnitaryTransform, n_params::Integer) n_dim = length(t.inputs) wf_size = length(t.inputs[1]) psi = hcat([elm.data for elm in t.inputs]...) psi = hcat([psi, zeros(eltype(t.inputs[1].data), wf_size, n_dim * n_params)]...) psi, n_dim, wf_size end function input_data(t::StateTransform, n_params::Integer) n_dim = 1 wf_size = length(t.input) psi = hcat([t.input.data]...) psi = hcat([psi, zeros(eltype(t.input.data), wf_size, n_params)]...) psi, n_dim, wf_size end output_data(t::StateTransform) = hcat([t.output.data]...) output_data(t::UnitaryTransform) = hcat([k.data for k in t.outputs]...) function augmented_ode_problem( prob::QOCProblem{T}, initial_params::Vector{T}, ) where {T<:Real} H = prob.hamiltonian n_coeffs = length(H.operators) n_params = length(initial_params) psi, n_dim = input_data(prob.transform, n_params) gradients(ps, t) = jacobian((_ps, _t) -> H.drives(_ps, _t), ps, t)[1] ODEProblem{true}( adjoint_system!, psi, prob.tspan, (H.const_op, H.operators, (H.drives, gradients), n_dim, initial_params), ) end function evaluate_distance( cost::CostFunction, result::AbstractMatrix{Complex{T}}, target::AbstractMatrix{Complex{T}}, n_dim::Integer, ) where {T<:Real} c = T(0) final_states = @view result[:, 1:n_dim] for (x, y) in zip(eachcol(target), eachcol(final_states)) c += real(cost.distance(x, y) / T(n_dim)) end c end function evaluate_gradient( distance_gradient::Function, result::AbstractMatrix{Complex{T}}, target::AbstractMatrix{Complex{T}}, n_dim::Integer, n_params::Integer, ) where {T<:Real} final_states = @view result[:, 1:n_dim] gradients = [] @inbounds for i = 1:n_params res = @view result[:, n_dim*i+1:n_dim*(i+1)] _c = T(0) for (j, (x, y)) in enumerate(zip(eachcol(target), eachcol(res))) _c += real(distance_gradient(x, final_states[:, j])' * y) end push!(gradients, _c / T(n_dim)) end gradients end dimension(t::UnitaryTransform) = length(t.inputs) dimension(t::StateTransform) = 1 function optimize!( sol::Solution{T}, opt, #flux optimizer solver::AdjointSolver{T}, drives_gradients::Function, constraint_gradient::Function, distance_gradient::Function, ) where {T<:Real} p = Progress(solver.n_iter) n_params = length(solver.initial_params) for i = 1:solver.n_iter res = solve( solver.ode_prob, solver.alg, p = ( (solver.const_op, solver.ops), (solver.drives, drives_gradients), sol.params, solver.n_dim, ), save_start = false, save_everystep = false; solver.kwargs..., ) distance = evaluate_distance(solver.cost, res.u[1], solver.target, solver.n_dim) constraints = solver.cost.constraints == nothing ? T(0) : solver.cost.constraints(sol.params) push!(sol.distance_trace, distance) push!(sol.constraints_trace, constraints) grads = evaluate_gradient( distance_gradient, res.u[1], solver.target, solver.n_dim, n_params, ) if i ∈ solver.save_iters push!(sol.params_trace, copy(sol.params)) end grads .+= constraint_gradient(sol.params) Flux.Optimise.update!(opt, sol.params, grads) next!(p, showvalues = [(:distance, distance), (:constraints, constraints)]) GC.gc() end sol end function optimize!( sol::Solution{T}, opt::Opt, #NLopt optimizer solver::AdjointSolver{T}, drives_gradients::Function, constraint_gradient::Function, distance_gradient::Function, ) where {T<:Real} if string(opt.algorithm)[2] != 'D' @warn "$(opt.algorithm) does not use the computed gradient" end p = Progress(solver.n_iter) n_params = length(solver.initial_params) opt.maxeval = solver.n_iter function opt_function(x::Vector{T}, g::Vector{T}) @inbounds for i = 1:n_params sol.params[i] = x[i] end res = solve( solver.ode_prob, solver.alg, p = ( (solver.const_op, solver.ops), (solver.drives, drives_gradients), sol.params, solver.n_dim, ), save_start = false, save_everystep = false; solver.kwargs..., ) distance = evaluate_distance(solver.cost, res.u[1], solver.target, solver.n_dim) constraints = solver.cost.constraints == nothing ? T(0) : solver.cost.constraints(sol.params) grads = evaluate_gradient( distance_gradient, res.u[1], solver.target, solver.n_dim, n_params, ) grads .+= constraint_gradient(sol.params) if length(g) > 0 for i = 1:n_params g[i] = grads[i] end end push!(sol.distance_trace, distance) push!(sol.constraints_trace, constraints) next!(p, showvalues = [(:distance, distance), (:constraints, constraints)]) GC.gc() return distance + constraints end opt.min_objective = opt_function (minf, minx, ret) = NLopt.optimize(opt, sol.params) sol.params[:] = minx sol end function check_compatibility(drives::Function, n_ops::Integer, n_params::Integer, T::DataType) if !applicable(drives, rand(T, n_params), rand(T)) throw(ArgumentError("drives should be of the form: f(params, t)")) end if length(drives(rand(T, n_params), rand(T))) != n_ops throw( ArgumentError( "drives must return a vector of length equal to the number of operators", ), ) end end function check_compatibility(cost::CostFunction, n_dim::Integer, n_params::Integer, T::DataType) if cost.constraints != nothing if !applicable(cost.constraints, rand(T, n_params)) throw( ArgumentError( "constraints in the cost function should be of the form: f(params)", ), ) end if !isreal(cost.constraints(rand(T, n_params))) throw(ArgumentError("constraints function must return real value")) end end if !applicable(cost.distance, rand(Complex{T}, n_dim), rand(Complex{T}, n_dim)) throw(ArgumentError("invalid distance in the cost function")) end if !isreal(cost.distance(rand(Complex{T}, n_dim), rand(Complex{T}, n_dim))) throw(ArgumentError("distance function must return a real value")) end end
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
code
4631
""" Abstract base class for transformations between states. """ abstract type Transform end """ StateTransform(input::Ket{B,T}, output::Ket{B,T}) where {B, T} Represents a state to state transformation between two pure states. """ struct StateTransform <: Transform basis::Basis input::Ket output::Ket StateTransform(input::Ket{B,T}, output::Ket{B,T}) where {B,T} = new(input.basis, input, output) StateTransform(p::Pair{<:Ket,<:Ket}) = StateTransform(p[1], p[2]) StateTransform(input::Ket, output::Ket) = throw(IncompatibleBases()) end """ UnitaryTransform(inputs::Vector{Ket{B, T}}, U::Matrix) where {B, T} Represents a unitary transformation between two sets of states. The tranformation can be initialized with a vector of kets and a unitary matrix representing the desired transformation. """ mutable struct UnitaryTransform <: Transform basis::Basis inputs::Vector{Ket} outputs::Vector{Ket} UnitaryTransform(p::Pair{<:Ket,<:Ket}) = UnitaryTransform(p[1], p[2]) UnitaryTransform(input::Ket{B,T}, output::Ket{B,T}) where {B,T} = new(input.basis, [input], [output]) UnitaryTransform(input::Ket, output::Ket) = throw(IncompatibleBases()) function UnitaryTransform(inputs::Vector{Ket{B,T}}, U::Matrix) where {B,T} size(U)[1] == size(U)[2] || throw(DimensionMismatch("U is not a square matrix")) length(inputs) == size(U)[1] || throw(DimensionMismatch("Matrix dimensions do not correspond to the inputs")) U * U' ≈ one(U) || throw(ArgumentError("Matrix is not unitary")) outputs = Ket{B,T}[] for r in eachrow(U) output = 0.0 * inputs[1] for (j, e) in enumerate(r) output += e * inputs[j] end push!(outputs, output) end tr = UnitaryTransform(inputs[1].basis) for (in, out) in zip(inputs, outputs) tr += in => out end tr end UnitaryTransform(inputs::Vector{<:Ket}, U::Matrix) = throw(IncompatibleBases()) UnitaryTransform(bs::Basis) = new(bs, Vector{Ket}[], Vector{Ket}[]) end Base.:+(a::UnitaryTransform, p::Pair{<:Ket,<:Ket}) = throw(IncompatibleBases()) function Base.:+(a::UnitaryTransform, p::Pair{Ket{B,T},Ket{B,T}}) where {B,T} a.basis == p[1].basis || throw(IncompatibleBases()) a.basis == p[2].basis || throw(IncompatibleBases()) for k in a.inputs dagger(k) * p[1] == 0.0 || @warn("The transformation is not unitary $(dagger(k)*p[1])") end for k in a.outputs dagger(k) * p[2] == 0.0 || @warn("The transformation is not unitary $(dagger(k)*p[2])") end push!(a.inputs, p[1]) push!(a.outputs, p[2]) a end """ CuKet(k::Ket) Returns a Ket with the data allocated on GPU memory. """ CuKet(k::Ket) = Ket(k.basis, CuVector(k.data)) """ cu(trans::UnitaryTransform) Returns a unitary transformation with the kets allocated on GPU memory. """ function cu(trans::UnitaryTransform) UnitaryTransform([ CuKet(in) => CuKet(out) for (in, out) in zip(trans.inputs, trans.outputs) ]) end """ cu(trans::StateTransform) Returns a state to state transformation with the kets allocated on GPU memory. """ cu(trans::StateTransform) = StateTransform(CuKet(trans.input) => CuKet(trans.output)) """ vectorize(k::Ket) Returns a ket representing the vectorized form of the density matrix of ket `k`. """ function vectorize(k::Ket) basis = k.basis ⊗ k.basis N = length(k.data) Ket(basis, reshape(dm(k).data, N * N)) end """ vectorize(trans::StateTransform) Returns a vectorized form of the state to state transformation. """ vectorize(trans::StateTransform) = StateTransform(vectorize(trans.input) => vectorize(trans.output)) """ vectorize(trans::UnitaryTransform) Returns a vectorized form of the unitary transformation. """ function vectorize(trans::UnitaryTransform) t = UnitaryTransform(trans.basis ⊗ trans.basis) for (k1, k2) in zip(trans.inputs, trans.outputs) t += vectorize(k1) => vectorize(k2) end t end Base.convert(::Type{ComplexF32}, k::Ket) = Ket(k.basis, Vector{ComplexF32}(k.data)) Base.convert(::Type{ComplexF32}, trans::StateTransform) = StateTransform(convert(ComplexF32, trans.input) => convert(ComplexF32, trans.output)) function Base.convert(::Type{ComplexF32}, trans::UnitaryTransform) trans_F32 = UnitaryTransform(trans.basis) for (in, out) in zip(trans.inputs, trans.outputs) trans_F32 += convert(ComplexF32, in) => convert(ComplexF32, out) end trans_F32 end
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
code
1812
""" heaviside(t::T) where {T <: Real} Heaviside step function ```math H(t) = \\begin{cases} 1, & t > 0 \\\\ 0, & t \\leq 0 \\end{cases}. ``` """ heaviside(t::T) where {T <: Real} = T(t > T(0)) """ interval(t::T, a::T, b::T) where {T <: Real} Interval function ```math I(t; a, b) = H(t - a) - H(t - b). ``` """ interval(t::T, a::T, b::T) where {T <: Real} = heaviside(t - a) - heaviside(t - b) """ piecewise_const_interp(p, t; t0, t1) Piecewise constant interpolation of equidistant samples `p`. """ function piecewise_const_interp(p::Vector{T}, t::T; t0=T(0), t1=T(1)) where {T <: Real} ts = t0:(t1 - t0)/length(p):t1 sum(p[i] * interval(t, ts[i], ts[i + 1]) for i=1:length(ts) - 1) end """ linear_interp(p, t; t0, t1) Linear interpolation of equidistant samples `p`. """ function linear_interp(p::Vector{T}, t::T; t0=T(0), t1=T(1)) where {T <: Real} Δt = (t1 - t0)/(length(p) - 1) ts = t0:Δt:t1 sum((p[i] + (t - ts[i]) * (p[i + 1] - p[i]) / Δt) * interval(t, ts[i], ts[i + 1]) for i=1:length(ts) - 1) end """ cubic_spline_interp(p, t; t0, t1) Cubic spline interpolation of equidistant samples `p` with natural boundary conditions. """ function cubic_spline_interp(p::Vector{T}, t::T; t0=T(0), t1=T(1)) where {T <: Real} Δt = (t1 - t0)/(length(p) - 1) ts = t0:Δt:t1 v = 4 * ones(T, length(p) - 2) h = ones(T, length(p) - 3) b = [p[i + 1] - p[i] for i=1:length(p) - 1] / Δt u = 6 * [b[i] - b[i - 1] for i=2:length(b)] z = vcat([T(0)], inv(SymTridiagonal(v, h)) * u / Δt, [T(0)]) sum(interval(t, ts[i], ts[i + 1]) * (z[i + 1] * (t - ts[i])^3 + z[i] * (ts[i + 1] - t)^3 + (6 * p[i + 1] - z[i + 1] * Δt^2) * (t - ts[i]) + (6 * p[i] - z[i] * Δt^2) * (ts[i + 1] - t)) / (6Δt) for i=1:length(ts) - 1) end
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
code
1478
""" vectorize(H, J, rates) Vectorizes the Hamiltonian and jump operators so that they can be submitted to the Schroedinger time evolution solver. Uses the vectorization identity ``\\text{vec}(ABC) = (C^T \\otimes A)\\text{vec}(B)``. """ function vectorize( H::Hamiltonian, J::Vector{<:AbstractOperator}, rates::Vector{T}, ) where {T<:Real} for op in J op.basis_r == H.basis_r ? nothing : throw(IncompatibleBases) op.basis_l == H.basis_l ? nothing : throw(IncompatibleBases) end const_op = vectorize_constant_op(H.const_op, [op.data for op in J], rates) ops = [vectorize_operator(op) for op in H.operators] Hamiltonian(const_op, J[1].basis_l, J[1].basis_r, ops, H.drives) end function vectorize_operator(op::AbstractMatrix) id = one(op) sparse(kron(id, op) - kron(transpose(op), id)) end function vectorize_jump_operators( ops::Vector{<:AbstractMatrix{Complex{T}}}, rates::Vector{T}, ) where {T<:Real} id = one(ops[1]) res = T(0) * kron(id, id) for (Op, r) in zip(ops, rates) res += r * kron(conj(Op), Op) res -= r * T(0.5) * kron(id, Op' * Op) res -= r * T(0.5) * kron(transpose(Op) * conj(Op), id) end T(1)im * sparse(res) end function vectorize_constant_op( H0::op, ops::Vector{op}, rates::Vector{T}, ) where {T<:Real,op<:AbstractMatrix{Complex{T}}} Op = vectorize_operator(H0) sparse(Op + vectorize_jump_operators(ops, rates)) end
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
code
233
using Test using Sisyphus using QuantumOpticsBase: IncompatibleBases using QuantumOptics using Flux: Adam @testset "Transform" begin include("test_transforms.jl") end @testset "Problem" begin include("test_problem.jl") end
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
code
1426
bs = SpinBasis(1 // 2) H = Hamiltonian(sigmaz(bs), [sigmax(bs), sigmay(bs)], a -> [1.0, 2.0]) trans = StateTransform(spindown(bs) => spinup(bs)) cost = CostFunction((x, y) -> 1.0 - real(x' * y), a -> 0.0) prob = QOCProblem(H, trans, (0.0, 1.0), cost) @test_throws ArgumentError solve(prob, [1.0], Adam(0.1)) H = Hamiltonian(sigmaz(bs), [sigmax(bs), sigmay(bs)], (a, t) -> [1.0]) trans = StateTransform(spindown(bs) => spinup(bs)) cost = CostFunction((x, y) -> 1.0 - real(x' * y), a -> 0.0) prob = QOCProblem(H, trans, (0.0, 1.0), cost) @test_throws ArgumentError solve(prob, [1.0], Adam(0.1)) H = Hamiltonian(sigmaz(bs), [sigmax(bs), sigmay(bs)], (a, t) -> [1.0, 2.0]) trans = StateTransform(spindown(bs) => spinup(bs)) cost = CostFunction((x, y) -> 1.0 - x' * y) prob = QOCProblem(H, trans, (0.0, 1.0), cost) @test_throws ArgumentError solve(prob, [1.0], Adam(0.1)) H = Hamiltonian(sigmaz(bs), [sigmax(bs), sigmay(bs)], (a, t) -> [1.0, 2.0]) trans = StateTransform(spindown(bs) => spinup(bs)) cost = CostFunction(x -> x) prob = QOCProblem(H, trans, (0.0, 1.0), cost) @test_throws ArgumentError solve(prob, [1.0], Adam(0.1)) H = Hamiltonian(sigmaz(bs), [sigmax(bs), sigmay(bs)], (a, t) -> [1.0, 2.0]) trans = StateTransform(spindown(bs) => spinup(bs)) cost = CostFunction((x, y) -> 1.0 - real(x' * y), p -> p * 1.0im) prob = QOCProblem(H, trans, (0.0, 1.0), cost) @test_throws ArgumentError solve(prob, [1.0], Adam(0.1))
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
code
776
bs1 = SpinBasis(1 // 2) bs2 = SpinBasis(2 // 2) @test_throws IncompatibleBases StateTransform(spinup(bs1) => spinup(bs2)) @test_throws IncompatibleBases UnitaryTransform(spinup(bs1) => spinup(bs2)) t = UnitaryTransform(spinup(bs1) => spindown(bs1)) @test_throws IncompatibleBases global t += spindown(bs1) => spinup(bs2) @test_throws ArgumentError UnitaryTransform( [spinup(bs1), spindown(bs1)], [[1.0, 2.0][3.0, 4.0]], ) @test_throws ArgumentError UnitaryTransform( [spinup(bs1), spindown(bs1)], [[1.0 0.0]; [0.0 2.0]], ) @test_throws DimensionMismatch UnitaryTransform( [spinup(bs1), spindown(bs1)], [[1.0 0.0 1.0]; [0.0 2.0 1.0]], ) @test_throws IncompatibleBases UnitaryTransform( [spinup(bs1), spindown(bs2)], [[1.0 0.0]; [0.0 1.0]], )
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
docs
412
# Sisyphus A high-performance library for gradient based quantum optimal control # Installation Sisyphus is not yet available in the official registry of Julia packages. You can install Sisyphus and it's dependencies in the REPL (press `]` to enter the `Pkg` mode) with the github link, ``` pkg> add [email protected]:SatyaBade12/Sisyphus.jl.git ``` # Documentation https://satyabade12.github.io/Sisyphus.jl
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
docs
622
# API ## Types ```@docs Hamiltonian ``` ```@docs Transform ``` ```@docs StateTransform ``` ```@docs UnitaryTransform ``` ```@docs CostFunction ``` ```@docs QOCProblem ``` ```@docs AdjointSolver ``` ```@docs Solution ``` ## Functions ```@docs schroedinger_dynamic ``` ```@docs master_dynamic ``` ```@docs vectorize ``` ### Utilities ```@docs heaviside ``` ```@docs interval ``` ```@docs piecewise_const_interp ``` ```@docs linear_interp ``` ```@docs cubic_spline_interp ``` ## GPU ```@docs CuKet(k::Ket) ``` ```@docs cu ``` ## Single precision ```@docs convert(::Type{Float32}, prob::QOCProblem) ```
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
docs
3731
# Gradient-based quantum optimal control In this section, we describe in detail the optimization algorithm implemented in `Sisyphus.jl`. A general QOC problem aims to find time-dependent control knobs to simultaneously guide the evolution of a given set of input states to some chosen target states subject to physical and hardware constraints. Let us denote the input and target states of the problem $|\psi^{(1)}_i\rangle, |\psi^{(2)}_i\rangle, \dots |\psi^{(N)}_i\rangle$ and $|\psi^{(1)}_f\rangle, |\psi^{(2)}_f\rangle, \dots |\psi^{(N)}_f\rangle$ respectively. Without loss of generality, the time-dependent Hamiltonian governing the dynamics of a quantum system can be written as, $$H(t) = H_0 + H_c(t) = H_0 + \sum_{m=1}^{M} c_m(t) H_m.$$ The control drives $c_1(t), c_2(t), \dots c_M(t)$ define the unitary transformation: $$U(\{c_m\}, T) = e^{-i \int_0^T H(t) \mathrm{d}t}.$$ The drives $\{c_k(t)\}$ are designed by optimizing a certain cost function. In practice, the cost function is chosen to reflect the quality of the desired transformation and by constraining the pulses: $$C(\{c_m\}) = \frac{1}{N}\sum_{j=1}^{N} d(|\psi^{(j)}_f\rangle, U(\{c_m\}, T)|\psi^{(j)}_i\rangle) + F(\{c_m(t)\}),$$ where $d(|\psi^{(j)}_f\rangle, U(\{c_m\}, T)|\psi^{(j)}_i\rangle)$ is some distance measure and $F$ takes into account the experimental constraints such as bounds on control signals, finite bandwidth and power etc. The gradient of the cost function wrt the parameters is, $$\frac{\partial C(\{c_m\})}{\partial w_k} = \frac{1}{N}\sum_{j=1}^{N} \frac{\partial}{\partial w_k}d\left(|\psi^{(j)}_f\rangle, |\psi^{(j)}(T)\rangle\right) + \frac{\partial F}{\partial w_k}.$$ where $|\psi^{(j)}(T)\rangle = U(\{c_m\}, T)|\psi^{(j)}_i\rangle$ and $w_k$ parameterize the control signals $\{c_m\}$. The second term in the above equation can be evaluated with standard AD techniques. The first term can be efficiently calculated without propagating the derivative through the ODE solver using the [adjoint sensitivity method](https://arxiv.org/abs/1806.07366). We have, $$\frac{\partial}{\partial w_k}d\left(|\psi^{(j)}_f\rangle, |\psi^{(j)}(T)\rangle\right) = \frac{\partial d(x,y)}{\partial y} \Big|_{x=|\psi^{(j)}_f\rangle, y = |\psi^{(j)}(T)\rangle} \frac{\partial|\psi^{(j)}(T)\rangle}{\partial w_k}.$$ Therefore, the gradient $\partial C(\{c_m\})/\partial w_k$ can be computed from $|\psi^{(j)}(T)\rangle$ and $\partial|\psi^{(j)}(T)\rangle/ \partial w_k$. For a closed quantum system, we get the following augmented system of equations, $$\frac{\mathrm{d}|\psi^{(j)}\rangle}{\mathrm{d}t} = -i H(t) |\psi^{(j)}\rangle$$ $$\frac{\mathrm{d}}{\mathrm{d}t} \frac{\partial|\psi^{(j)}\rangle}{\partial w_k} = -i\left[H(t) \frac{\partial|\psi^{(j)}\rangle}{\partial w_k} + \sum_{m=1}^{M}\frac{\partial c_m(t)}{\partial w_k} H_m |\psi^{(j)}\rangle\right],$$ with initial conditions $|\psi^{(j)}(0)\rangle = |\psi^{(j)}_i\rangle$ and $\partial|\psi^{(j)}(0)\rangle/\partial w_k = 0$. These coupled equations can be solved using a higher-order ODE solver and gradients wrt the parameters can be evaluated to the desired numerical accuracy. For a given set of parameters, knowing the cost function and the gradients, one could then use any gradient based optimization method to iteratively update the parameters, until a satisfactory solution is found. Note that the algorithm presented here is quite similar to [GOAT](https://doi.org/10.1103/physrevlett.120.150401), except that the equations we solve are expressed only in terms of states instead of the evolution operator. Therefore, effectively `Sisyphus.jl` requires less memory compared to GOAT! ![Schematic diagram of gradient-based optimal control](assets/nn_qoc.png)
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
docs
1298
# Sisyphus `Sisyphus.jl` is a flexible high-performance Julia package for gradient based quantum optimal control. It is well integrated into the Julia ecosystem by supporting definitions of quantum objects from the [QuantumOptics.jl](https://qojulia.org/) library, automatic differentiation through [Flux.jl](https://fluxml.ai/), it relies on [OrdinaryDiffEq.jl](https://github.com/SciML/OrdinaryDiffEq.jl) to simulate the dynamics of quantum systems and can be used in conjunction with any optimizer in the [Flux](https://fluxml.ai/Flux.jl/stable/training/optimisers/) or [NLopt](https://github.com/JuliaOpt/NLopt.jl)[^1] packages. The solver is implemented with the [CommonSolve](https://github.com/SciML/CommonSolve.jl) API. The simulation backend is multi-threaded (uses [MKLSparse](https://github.com/JuliaSparse/MKLSparse.jl) library) and autoscales on multicore CPUs depending on the problem size. It can also be seamlessly run on a GPU and it is suitable for solving large scale quantum optimal control problems. ## Examples *optimization of a two level state transfer problem* ![](assets/anim_two_level_system.gif) *optimization of GHZ state preparation in a linear chain of 12 atoms on a GPU* ![](assets/anim_GHZ_12_atoms.gif) [^1]: including derivative free optimization algorithms
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
docs
182
# Installation You can install `Sisyphus.jl` and it's dependencies in the REPL (press `]` to enter the `Pkg` mode) with ``` pkg> add https://github.com/entropy-lab/Sisyphus.git ```
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
docs
4438
# Introduction Optimal control strategies pervade a wide range of fields in science and engineering. In particular, quantum optimal control (QOC) has the potential to extract the best of the quantum technologies. QOC techniques are routinely employed to coherently manipulate and drive the quantum system to a given state or to perform a given quantum operation (or gate). In practice, the system dynamics and/or objective function to be minimized in QOC problems can be quite involved and often they do not yield to a simple analytical treatment (except in a few cases such as DRAG, STIRAP etc.). Therefore, one must often resort to computational methods. Numerical techniques to solve QOC problems fall into two categories: gradient based and gradient free methods. As a general rule of thumb, gradient free methods such as [CRAB](https://arxiv.org/abs/1103.0855) and [dCRAB](https://arxiv.org/abs/1506.04601) are suitable for problems involving few tens of parameters. However, they require large number of iterations to converge as the parameter size increases and gradient based techniques should be preferred, whenever it is possible to evaluate the gradients efficiently. Among the gradient based methods, [GRAPE](https://qutip.org/docs/4.0.2/guide/guide-control.html) and [Krotov](https://qucontrol.github.io/krotov/v1.0.0/01_overview.html) solve QOC problems by representing the drive signals as piece-wise constant functions and iteratively optimize these discrete values based on the gradient of the cost function with respect to the control parameters. In these approaches, for a given set of control signals, the resulting unitary transformation is computed by first-order Trotterization of each time slice. These methods are inherently prone to discretization errors and one must sample the control signals sufficiently to obtain high fidelity protocols. A continuous parametrization of drive signals, combined with higher-order ordinary differential equation solvers are indispensible for solving optimal control problems when accuracy can not be traded with computational effort (see Gradient Optimization of Analytical conTrols [(GOAT)](https://doi.org/10.1103/physrevlett.120.150401) for a thorough discussion). In this library, we implement a gradient based approach to solve a generic QOC problem. We rely on automatic differentiation (AD) to automatically write the [adjoint equations](https://arxiv.org/abs/1806.07366), necessary to calculate the gradients for any user defined parametrized control knobs and objective function. These equations coupled with the dynamical equations of the system are then efficiently solved to evaluate gradients. The control parameters can then be updated iteratively using any gradient based method to optimize the objective function. ## Why do we need a dedicated library for quantum optimal control? SciML ecosystem already supports solving [optimal control problems](https://diffeqflux.sciml.ai/dev/examples/optimal_control/) via sensitivity analysis. In principle, quantum optimal control problems can be solved with this approach, however, it has two shortcomings: a) Time evolution of Schrodinger or Master equation must be expressed only in terms of real numbers i.e. by separating the real and imaginary parts of operators and kets (it also means that we can not easily interface with `QuantumOptics.jl`). Otherwise, we'll run into errors while calculating gradients of cost function (loss) using AD. b) The size of Hilbert space and/or the number of parameters in QOC problems can be large. In such cases, it is beneficial to implement the RHS of time evolution equations with Intel MKL or CUBLAS libraries. However, AD once again fails if the equations contain calls to functions not written in pure Julia (for e.g. when `mul!` points to Intel MKL library). In `Sisyphus.jl` package we solve these problems by separating the AD part from the time evolution. The result is a high-performance library for quantum optimal control that enables users to: describe a general quantum optimal control problem in the familiar language of [QuantumOptics.jl](https://docs.qojulia.org/) with almost any objective for optimization, select any [ODE solver](https://diffeq.sciml.ai/dev/solvers/ode_solve/), optimizer (in [Flux.jl](https://fluxml.ai/Flux.jl/stable/training/optimisers/#Optimiser-Reference) and [NLopt.jl](https://github.com/JuliaOpt/NLopt.jl)) and solve it fast!
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
docs
1302
# Open quantum systems Quantum systems interacting with the environment can be modelled with the Master equation, $$\dot{\rho} = -i[H, \rho] + \sum_k \gamma_k \big( J_k \rho J_k^\dagger - \frac{1}{2} J_k^\dagger J_k \rho - \frac{1}{2} \rho J_k^\dagger J_k \big),$$ where $J_k$ are the jump operators and $\gamma_k$ the respective jump rates. Using the vectorization identity ($\text{vec}(A B C) = (C^T \otimes A)\text{vec}(B)$), we can cast a quantum optimal control problem in the presence of Lindbladian noise into a `QOCProblem` in the absence of noise, but with an effective Hamiltonian, $$H^{e} = I \otimes H - H^T \otimes I + i\sum_k \gamma_k[J_k^*\otimes J_k - \frac{1}{2} I \otimes J_k^{\dagger}J_k - \frac{1}{2}J_k^TJ_k^*\otimes I],$$ acting on the vectorized form of the density matrix. This trick allows us to use the same solver to solve optimal control problems in the presence of noise. For a general time-dependent Hamiltonian $H(t) = H_0 + H_c(t)$, the effective time-dependent Hamiltonian is, $$H^{e}(t) = H^{e}_{0} + I \otimes H_c(t) - H_c(t)^T \otimes I,$$ where the constant part of the effective Hamiltonian is, $$H^{e}_{0} = I \otimes H_0 - H_0^T \otimes I + i\sum_k \gamma_k[J_k^*\otimes J_k - \frac{1}{2} I \otimes J_k^{\dagger}J_k - \frac{1}{2}J_k^TJ_k^*\otimes I].$$
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.0
60f3af90297538750462943668651f3e457d1364
docs
7097
# Tutorial The main goal of this tutorial is to introduce the terminology and workflow of the package. ## Constructing a [`Hamiltonian`](@ref) We split the Hamiltonian into time-independent and time-dependent parts. Operators constituting the Hamiltonian are represented by QuantumOptics operators. For a list of operators we submit a drives function that returns the corresponding list of real-valued drives that multiplies the operators respectively. Below is a construction of a simple two-level Hamiltonian with a parameterized Gaussian shaped drive $$H(t)/\hbar\omega_0 = -\frac{1}{2}\sigma_z + \Omega(p, t)\sigma_x$$ ```julia bs = SpinBasis(1//2) Ω(p, t) = [p[1] * exp(-p[2] * t^2) + p[3]] H = Hamiltonian(-0.5*sigmaz(bs), [sigmax(bs)], Ω) ``` The real valued drives can be any function in Julia, as long as it is differentiable. You can find some examples showcasing the use of neural networks, piecewise constant and linear functions in the notebooks. ## Defining a [`Transform`](@ref) ### a) [`StateTransform`](@ref) Transformation can be defined between two Kets as in the following code. ```julia bs = SpinBasis(1//2) trans = StateTransform(spindown(bs) => spinup(bs)) ``` ### b) [`UnitaryTransform`](@ref) It can alternatively be defined on a vector of Kets by providing unitary matrix that acts on the subspace spanned by them and represents the desired unitary evolution. ```julia bs = FockBasis(5) states = [fockstate(bs, 0)⊗fockstate(bs, 0), fockstate(bs, 0)⊗fockstate(bs, 1), fockstate(bs, 1)⊗fockstate(bs, 0), fockstate(bs, 1)⊗fockstate(bs, 1)] trans = UnitaryTransform(states, [[1.0 0.0 0.0 0.0]; [0.0 1.0 1.0im 0.0]/√2; [0.0 1.0im 1.0 0.0]/√2; [0.0 0.0 0.0 1.0]]) ``` ## Constructing a [`CostFunction`](@ref) Cost function is composed of a distance function measuring the overlap of the quantum states and the optional constraints on the shape of pulses. The following code defines a cost function that measures the infidelity between quantum states and constrains the pulse to zero at initial and final times `t0` and `t1`. ```julia (t0, t1) = (0.0, 1.0) Ω(p, t) = [p[1] * exp(-p[2] * t^2) + p[3]] cost = CostFunction((x, y) -> 1.0 - abs2(x' * y), p -> Ω(p, t0)[1]^2 + Ω(p, t1)[1]^2) ``` The solver automatically calculates the gradient of the distance and constraints function wrt the parameters of the problem. Therefore, the `CostFunction` arguments have to be differentiable real valued functions (`Zygote` handles most functions, just try!). ## Creating and solving a [`QOCProblem`](@ref) Once we have constructed the Hamiltonian, cost function, and target unitary transformation, we can define a quantum optimal control problem by submitting a timeframe `(t0, t1)` for the evolution along the previously mentioned objects and functions. `QOCProblem` can be solved by invoking the `solve` method that can further be customized, e.g. through the selection of an optimizer or by setting optimization hyperparameters like below. ```julia prob = QOCProblem(H, trans, (t0, t1), cost) sol = solve(prob, initial_params, ADAM(0.01);) ``` The [`Solution`](@ref) returned by the solver contains the optimal parameters and also the values of distance metric and constraints during the optimization process. Optionally, you can use the following keywords while invoking the `solve` method: a) `maxiter` allows to set the maximum number of iterations, the default value is `100`. b) `save_iters` to save the parameters tried by the optimizer at the specified iterations (useful for visualization of optimization). By default, the [`Solution`](@ref) object returned by the solver does not contain intermediate results. ## Selecting an optimizer User can pick any of the available optimizers from the Flux or NLopt packages, for example ```julia using Flux.Optimise: RMSProp sol = solve(prob, initial_params, RMSProp(0.01); maxiter=100) ``` ## Selecting a differential equation solver The ODE solver used to compute the system dynamics and gradients can be chosen with the keyword `alg`. ```julia sol = solve(prob, initial_params, ADAM(0.01); maxiter=100, alg=DP5(), abstol=1e-6, reltol=1e-6) ``` You may select appropriate ODE solvers available in `OrdinaryDiffEq` package. By default `Sisyphus.jl` uses `Tsit5()` algorithm, we encourage you to go through the documentation of [ODE Solvers](https://diffeq.sciml.ai/stable/solvers/ode_solve/#ode_solve) and try different algorithms to identify the algorithm best suited for your problem. In addition, you can also control the solver tolerances by setting `abstol` and `reltol`. ## Optimization in the presence of noise Optimal control problems in the presence of Lindbladian noise can be solved by converting them into an equivalent [closed system problem](noisy.md) by vectorizing the master equation. Here, we only provide tools to convert [`Hamiltonian`](@ref) and [`Transform`](@ref)s into their vectorized forms. However, it is the responsibility of the users to provide an appropriate distance measure between the two density matrices in the [`CostFunction`](@ref) (check examples) while working with the vectorized forms. For example, one can write Frobenius norm in its vectorized form as $$\|\rho - \sigma\|_F = \sqrt{\text{Tr}(\rho - \sigma)^\dagger(\rho - \sigma)} = \sqrt{\text{vec}(\rho - \sigma)^\dagger\text{vec}(\rho - \sigma)},$$ and define a correspoding distance function as `(x, y) -> 1.0 - sqrt((x - y)' * (x - y))`. ## Solving problems on GPU Usually, all the kets and operators in `QOCProblem` are allocated on the CPU. In order to solve the problem on a GPU, we need to move the data to GPU memory, this can be done simply with the [`cu`](@ref) function as shown below. Once the data is moved to the GPU, the problem can be solved with the `solve` method as usual ```julia cu_prob = cu(QOCProblem(H, trans, (t0, t1), cost)) solve(cu_prob, init_params, ADAM(0.1); maxiter=100) ``` GPUs have better single precision performance, if your problem does not require double precision, it is better to use single precision to obtain results quicker (it also reduces the memory footprint). We provide [`convert`](@ref) method to automatically convert all data types to single precision, ```julia prob = cu(convert(Float32, QOCProblem(H, trans, (t0, t1), cost))) ``` notebooks demonstrating these features can be found in the examples. ### How to choose a `CostFunction`? We have to bear in mind that the distance function (specified in `CostFunction`) must operate on arrays allocated on GPU. Most of the time, Julia's GPU compiler automatically generates CUDA kernels behind the scenes, both for distance and it's gradient! However it fails sometimes, for example, you should use, ```julia cost = CostFunction((x, y) -> 1.0 - real(sum(conj(x) .* y)) ``` instead of, ```julia cost = CostFunction((x, y) -> 1.0 - real(x' * y) ``` eventhough they are equivalent. Solving this in general is beyond the scope of `Sisyphus.jl`.
Sisyphus
https://github.com/SatyaBade12/Sisyphus.jl.git
[ "MIT" ]
0.1.2
60341f3f9a9f7634574034d06740914489f12317
code
1380
# Source this script as e.g. # # include("PATH/TO/devrepl.jl") # # from *any* Julia REPL or run it as e.g. # # julia -i --banner=no PATH/TO/devrepl.jl # # from anywhere. This will change the current working directory and # activate/initialize the correct Julia environment for you. # # You may also run this in vscode to initialize a development REPL # using Pkg using Downloads: download cd(@__DIR__) Pkg.activate("test") function _instantiate() installorg_script = joinpath("..", "scripts", "installorg.jl") if !isfile(installorg_script) @warn "$(@__DIR__) should be inside the JuliaQuantumControl development environment. See https://github.com/JuliaQuantumControl/JuliaQuantumControl#readme" installorg_script = download( "https://raw.githubusercontent.com/JuliaQuantumControl/JuliaQuantumControl/master/scripts/installorg.jl", ) end if !isfile(joinpath("..", ".JuliaFormatter.toml")) download( "https://raw.githubusercontent.com/JuliaQuantumControl/JuliaQuantumControl/master/.JuliaFormatter.toml", ".JuliaFormatter.toml" ) end include(installorg_script) eval(:(installorg())) Pkg.develop(path=".") # XXX end if !isfile(joinpath("test", "Manifest.toml")) _instantiate() end include("test/init.jl") if abspath(PROGRAM_FILE) == @__FILE__ help() end
ParameterizedQuantumControl
https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl.git
[ "MIT" ]
0.1.2
60341f3f9a9f7634574034d06740914489f12317
code
3943
using Pkg DOCUMENTER_VERSION = [p for (uuid, p) in Pkg.dependencies() if p.name == "Documenter"][1].version if DOCUMENTER_VERSION <= v"1.3.0" Pkg.develop("Documenter") end using QuantumControl using QuantumPropagators using ParameterizedQuantumControl using Documenter using DocumenterCitations using DocumenterInterLinks using Plots gr() ENV["GKSwstype"] = "100" PROJECT_TOML = Pkg.TOML.parsefile(joinpath(@__DIR__, "..", "Project.toml")) VERSION = PROJECT_TOML["version"] NAME = PROJECT_TOML["name"] AUTHORS = join(PROJECT_TOML["authors"], ", ") * " and contributors" GITHUB = "https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl" DEV_OR_STABLE = "stable/" if endswith(VERSION, "dev") DEV_OR_STABLE = "dev/" end links = InterLinks( "Julia" => "https://docs.julialang.org/en/v1/", "QuantumControl" => "https://juliaquantumcontrol.github.io/QuantumControl.jl/$DEV_OR_STABLE", "QuantumPropagators" => "https://juliaquantumcontrol.github.io/QuantumPropagators.jl/$DEV_OR_STABLE", "QuantumGradientGenerators" => "https://juliaquantumcontrol.github.io/QuantumGradientGenerators.jl/$DEV_OR_STABLE", "QuantumControl" => "https://juliaquantumcontrol.github.io/QuantumControl.jl/$DEV_OR_STABLE", "GRAPE" => "https://juliaquantumcontrol.github.io/GRAPE.jl/$DEV_OR_STABLE", "Krotov" => "https://juliaquantumcontrol.github.io/Krotov.jl/$DEV_OR_STABLE", "Examples" => "https://juliaquantumcontrol.github.io/QuantumControlExamples.jl/$DEV_OR_STABLE", "Optimization" => "https://docs.sciml.ai/Optimization/stable/", "ComponentArrays" => "https://jonniedie.github.io/ComponentArrays.jl/stable/", "RecursiveArrayTools" => "https://docs.sciml.ai/RecursiveArrayTools/stable/", ) fallbacks = ExternalFallbacks( "get_parameters" => "@extref QuantumControl :jl:function:`QuantumPropagators.Controls.get_parameters`", "QuantumControl.Generators.Generator" => "@extref QuantumControl :jl:type:`QuantumPropagators.Generators.Generator`", "QuantumControl.hamiltonian" => "@extref QuantumControl :jl:function:`QuantumPropagators.Generators.hamiltonian`", "QuantumControl.liouvillian" => "@extref QuantumControl :jl:function:`QuantumPropagators.Generators.liouvillian`", "QuantumControl.Controls.ParameterizedFunction" => "@extref QuantumControl :jl:type:`QuantumPropagators.Controls.ParameterizedFunction`", "QuantumControl.init_prop" => "@extref QuantumControl :jl:function:`QuantumPropagators.init_prop`", "QuantumControl.prop_step!" => "@extref QuantumControl :jl:function:`QuantumPropagators.prop_step!`", ) println("Starting makedocs") bib = CitationBibliography(joinpath(@__DIR__, "src", "refs.bib"); style=:numeric) PAGES = [ "Home" => "index.md", "Overview" => "overview.md", "API" => "api.md", "References" => "references.md", ] makedocs(; plugins=[bib, links, fallbacks], modules=[ParameterizedQuantumControl], authors=AUTHORS, sitename="ParameterizedQuantumControl.jl", doctest=false, # we have no doctests (but trying to run them is slow) format=Documenter.HTML(; prettyurls=true, canonical="https://juliaquantumcontrol.github.io/ParameterizedQuantumControl.jl", assets=[ "assets/citations.css", asset( "https://juliaquantumcontrol.github.io/QuantumControl.jl/dev/assets/topbar/topbar.css" ), asset( "https://juliaquantumcontrol.github.io/QuantumControl.jl/dev/assets/topbar/topbar.js" ), ], mathengine=KaTeX(Dict(:macros => Dict("\\Op" => "\\hat{#1}"))), footer="[$NAME.jl]($GITHUB) v$VERSION docs powered by [Documenter.jl](https://github.com/JuliaDocs/Documenter.jl).", ), pages=PAGES, warnonly=true, ) println("Finished makedocs") deploydocs(; repo="github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl", devbranch="master" )
ParameterizedQuantumControl
https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl.git
[ "MIT" ]
0.1.2
60341f3f9a9f7634574034d06740914489f12317
code
2941
#using QuantumPropagators.Interfaces: check_generator using QuantumControl.Interfaces: check_generator using ComponentArrays: ComponentVector, Axis using QuantumControl.Controls: get_parameters using QuantumControl.QuantumPropagators: propagate import OrdinaryDiffEq using UnPack: @unpack const 𝕚 = 1im; # # Definition of the Hamiltonian include("enantiomer_ham.jl") using .EnantiomerHams: EnantiomerHam # # Testing the Hamiltonian H = EnantiomerHam(; sign=+1, ΔT₁=0.3, ΔT₂=0.4, ΔT₃=0.3, ϕ₁=0.0, ϕ₂=0.0, ϕ₃=0.0, E₀₁=4.5, E₀₂=4.0, E₀₃=5.0 ) tlist = collect(range(0, 1; length=101)); Ψ₀ = ComplexF64[1, 0, 0]; check_generator( H; tlist, state=Ψ₀, for_mutable_state=true, for_parameterization=true, for_gradient_optimization=false, for_time_continuous=true ) # # Defining the control problem using QuantumControl: ControlProblem, Trajectory Ψ₊tgt = ComplexF64[1, 0, 0]; Ψ₋tgt = ComplexF64[0, 0, 1]; parameters = ComponentVector(ΔT₁=0.2, ΔT₂=0.4, ΔT₃=0.3, ϕ₁=π, ϕ₂=π, ϕ₃=π, E₀₁=4.0, E₀₂=4.0, E₀₃=4.0) H₊ = EnantiomerHam(parameters; sign=+1) H₋ = EnantiomerHam(parameters; sign=-1) @assert get_parameters(H₊) === get_parameters(H₋) @assert get_parameters(H₊) === parameters using QuantumControl.Functionals: J_T_ss function J_T(ϕ, trajectories; τ=nothing) Ψ₊, Ψ₋ = ϕ[1], ϕ[2] return 1 - (abs(Ψ₊[1]) + abs(Ψ₋[3])) / 2 end problem = ControlProblem( [Trajectory(Ψ₀, H₊; target_state=Ψ₊tgt), Trajectory(Ψ₀, H₋; target_state=Ψ₋tgt)], tlist; parameters=parameters, lb=ComponentVector( ΔT₁=0.1, ΔT₂=0.1, ΔT₃=0.1, ϕ₁=0.0, ϕ₂=0.0, ϕ₃=0.0, E₀₁=1.0, E₀₂=1.0, E₀₃=1.0, ), ub=ComponentVector( ΔT₁=1.0, ΔT₂=1.0, ΔT₃=1.0, ϕ₁=2π, ϕ₂=2π, ϕ₃=2π, E₀₁=5.0, E₀₂=5.0, E₀₃=5.0, ), J_T=J_T_ss, #J_T, prop_method=OrdinaryDiffEq, prop_reltol=1e-9, prop_abstol=1e-9, iter_stop=500, check_convergence=res -> begin ((res.J_T < 1e-5) && (res.converged = true) && (res.message = "J_T < 10⁻⁵")) end, ) @assert get_parameters(problem) === parameters using QuantumControl: propagate_trajectory Ψ₊out = propagate_trajectory( problem.trajectories[1], tlist; method=OrdinaryDiffEq, reltol=1e-9, abstol=1e-9 ) Ψ₋out = propagate_trajectory( problem.trajectories[2], tlist; method=OrdinaryDiffEq, reltol=1e-9, abstol=1e-9 ) # # Running the Optimization using QuantumControl: optimize using ParameterizedQuantumControl using Optimization using OptimizationNLopt import NLopt res = optimize( problem; method=ParameterizedQuantumControl, backend=Optimization, optimizer=NLopt.LN_NELDERMEAD(), info_hook=( ((wrk, iter) -> (1.0 - wrk.J_parts[1],)), ParameterizedQuantumControl.print_table, ) )
ParameterizedQuantumControl
https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl.git
[ "MIT" ]
0.1.2
60341f3f9a9f7634574034d06740914489f12317
code
2232
module EnantiomerHams using ComponentArrays: ComponentVector, Axis using UnPack: @unpack const 𝕚 = 1im struct EnantiomerHam a::Float64 sign::Int64 parameters::ComponentVector{ Float64, Vector{Float64}, Tuple{Axis{(ΔT₁=1, ΔT₂=2, ΔT₃=3, ϕ₁=4, ϕ₂=5, ϕ₃=6, E₀₁=7, E₀₂=8, E₀₃=9)}} } end function EnantiomerHam(; a=1000.0, sign=1, kwargs...) EnantiomerHam(a, sign, ComponentVector(; kwargs...)) end function EnantiomerHam(parameters; a=1000.0, sign=1) EnantiomerHam(a, sign, parameters) end import QuantumControl.Controls: get_controls, evaluate, evaluate!, get_parameters, get_control_deriv get_controls(::EnantiomerHam) = tuple() function evaluate(G::EnantiomerHam, args...; kwargs...) H = zeros(ComplexF64, 3, 3) evaluate!(H, G, args...; kwargs...) end # Midpoint of n'th interval of tlist, but snap to beginning/end (that's # because any S(t) is likely exactly zero at the beginning and end, and we # want to use that value for the first and last time interval) function _t(tlist, n) @assert 1 <= n <= (length(tlist) - 1) # n is an *interval* of `tlist` if n == 1 t = tlist[begin] elseif n == length(tlist) - 1 t = tlist[end] else dt = tlist[n+1] - tlist[n] t = tlist[n] + dt / 2 end return t end E(t; E₀, t₁, t₂, a) = (E₀ / 2) * (tanh(a * (t - t₁)) - tanh(a * (t - t₂))) function evaluate!(H, G::EnantiomerHam, tlist, n; _...) t = _t(tlist, n) evaluate!(H, G, t) end function evaluate!(H, G::EnantiomerHam, t; _...) @unpack a, sign = G @unpack ΔT₁, ΔT₂, ΔT₃, ϕ₁, ϕ₂, ϕ₃, E₀₁, E₀₂, E₀₃ = G.parameters T₁ = ΔT₁ T₂ = ΔT₁ + ΔT₂ T₃ = ΔT₁ + ΔT₂ + ΔT₃ μ = sign E₁ = E(t; E₀=E₀₁, t₁=0.0, t₂=T₁, a) E₂ = E(t; E₀=E₀₂, t₁=T₁, t₂=T₂, a) E₃ = E(t; E₀=E₀₃, t₁=T₂, t₂=T₃, a) copyto!( H, µ * [ 0.0 E₁*exp(𝕚 * ϕ₁) E₃*exp(𝕚 * ϕ₃) E₁*exp(-𝕚 * ϕ₁) 0.0 E₂*exp(𝕚 * ϕ₂) E₃*exp(-𝕚 * ϕ₃) E₂*exp(-𝕚 * ϕ₂) 0.0 ] ) return H end get_parameters(G::EnantiomerHam) = G.parameters get_control_deriv(G::EnantiomerHam, ::Any) = nothing # does not have controls end
ParameterizedQuantumControl
https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl.git
[ "MIT" ]
0.1.2
60341f3f9a9f7634574034d06740914489f12317
code
1304
module ParameterizedQuantumControlOptimizationExt using Dates: now using Optimization: Optimization, OptimizationProblem import ParameterizedQuantumControl: run_optimizer, update_result! function run_optimizer( backend::Val{:Optimization}, optimizer, wrk, f, info_hook, check_convergence! ) u0 = copy(wrk.result.guess_parameters) #kwargs = ... # TODO: optimization_kwargs function callback(state, loss_val) wrk.optimizer_state = state iter = wrk.result.iter update_result!(wrk, iter) #update_hook!(...) # TODO info_tuple = info_hook(wrk, iter) wrk.fg_count .= 0 (info_tuple !== nothing) && push!(wrk.result.records, info_tuple) check_convergence!(wrk.result) wrk.result.iter += 1 # next iteration return wrk.result.converged end prob = OptimizationProblem( (u, _) -> f(u), u0, nothing; lb=get(wrk.kwargs, :lb, nothing), ub=get(wrk.kwargs, :ub, nothing) ) try sol = Optimization.solve(prob, optimizer; callback) catch exc exc_msg = sprint(showerror, exc) if !contains(exc_msg, "Optimization halted by callback") rethrow() end end wrk.result.end_local_time = now() end end
ParameterizedQuantumControl
https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl.git
[ "MIT" ]
0.1.2
60341f3f9a9f7634574034d06740914489f12317
code
109
module ParameterizedQuantumControl include("workspace.jl") include("result.jl") include("optimize.jl") end
ParameterizedQuantumControl
https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl.git
[ "MIT" ]
0.1.2
60341f3f9a9f7634574034d06740914489f12317
code
7187
import QuantumControl: optimize using LinearAlgebra using QuantumControl: @threadsif using QuantumControl: set_atexit_save_optimization using QuantumControl: propagate_trajectories @doc raw""" ```julia using ParameterizedQuantumControl result = optimize(problem; method=ParameterizedQuantumControl, kwargs...) ``` optimizes the given control [`problem`](@ref QuantumControl.ControlProblem) by varying a set of control parameters in order to minimize the functional ```math J(\{u_{n}\}) = J_T(\{|ϕ_k(T)⟩\}) ``` where ``|ϕ_k(T)⟩`` is the result of propagating the initial state of the ``k``'th trajectory under the parameters ``\{u_n\}`` Returns a [`ParameterizedOptResult`](@ref). Keyword arguments that control the optimization are taken from the keyword arguments used in the instantiation of `problem`; any of these can be overridden with explicit keyword arguments to `optimize`. # Required problem keyword arguments * `backend`: A package to perform the optimization, e.g., `Optimization` (for [Optimization.jl](https://github.com/SciML/Optimization.jl)) * `optimizer`: A backend-specific object to perform the optimizatino, e.g., `NLopt.LN_NELDERMEAD()` from `NLOpt`/`OptimizationNLOpt` * `J_T`: A function `J_T(ϕ, trajectories; τ=τ)` that evaluates the final time functional from a vector `ϕ` of forward-propagated states and `problem.trajectories`. For all `trajectories` that define a `target_state`, the element `τₖ` of the vector `τ` will contain the overlap of the state `ϕₖ` with the `target_state` of the `k`'th trajectory, or `NaN` otherwise. # Optional problem keyword arguments * `parameters`: An `AbstractVector` of parameters to tune in the optimization. By default, [`parameters=get_parameters(problem)`](@ref get_parameters). If given explicitly, the vector must alias values inside the generators used in `problem.trajectories` so that mutating the `parameters` array directly affects any subsequent propagation. * `lb`: An `AbstractVector` of lower bound values for a box constraint. Must be a vector similar to (and of the same size as `parameters`) * `ub`: An `AbstractVector` of upper bound values for a box constraint, cf. `lb` * `use_threads`: If given a `true`, propagate trajectories in parallel * `iter_stop`: The maximum number of iterations """ function optimize_parameters(problem) verbose = get(problem.kwargs, :verbose, false) wrk = ParameterizedOptWrk(problem; verbose) J_T_func = wrk.kwargs[:J_T] initial_states = [traj.initial_state for traj ∈ wrk.trajectories] Ψtgt = Union{eltype(initial_states),Nothing}[ (hasproperty(traj, :target_state) ? traj.target_state : nothing) for traj ∈ wrk.trajectories ] τ = wrk.result.tau_vals J = wrk.J_parts # loss function function f(u; count_call=true) copyto!(wrk.parameters, u) Ψ = propagate_trajectories( wrk.trajectories, problem.tlist; use_threads=wrk.use_threads, _prefixes=["prop_"], _filter_kwargs=true, problem.kwargs... ) for k in eachindex(wrk.trajectories) Ψtgt = wrk.trajectories[k].target_state τ[k] = isnothing(Ψtgt) ? NaN : (Ψtgt ⋅ Ψ[k]) end wrk.states = Ψ J[1] = J_T_func(Ψ, wrk.trajectories; τ=τ) if count_call wrk.fg_count[2] += 1 end return sum(J) end backend = wrk.backend optimizer = wrk.optimizer info_hook = get(problem.kwargs, :info_hook, print_table) check_convergence! = get(problem.kwargs, :check_convergence, res -> res) atexit_filename = get(problem.kwargs, :atexit_filename, nothing) # atexit_filename is undocumented on purpose: this is considered a feature # of @optimize_or_load if !isnothing(atexit_filename) set_atexit_save_optimization(atexit_filename, wrk.result) if !isinteractive() @info "Set callback to store result in $(relpath(atexit_filename)) on unexpected exit." # In interactive mode, `atexit` is very unlikely, and # `InterruptException` is handles via try/catch instead. end end try run_optimizer(Val(backend), optimizer, wrk, f, info_hook, check_convergence!) catch exc # Primarily, this is intended to catch Ctrl-C in interactive # optimizations (InterruptException) exc_msg = sprint(showerror, exc) wrk.result.message = "Exception: $exc_msg" end if !isnothing(atexit_filename) popfirst!(Base.atexit_hooks) end # restore guess parameters - we don't want to mutate the problem; # the optimized parameters are in result.optimized_parameters copyto!(wrk.parameters, wrk.result.guess_parameters) return wrk.result end # backend code stub (see extensions) function run_optimizer end """Print optimization progress as a table. This functions serves as the default `info_hook` for an optimization with `ParameterizedQuantumControl`. """ function print_table(wrk, iteration, args...) # TODO: make_print_table that precomputes headers and such, and maybe # allows for more options. # TODO: should we report ΔJ instead of ΔJ_T? J_T = wrk.result.J_T ΔJ_T = J_T - wrk.result.J_T_prev secs = wrk.result.secs headers = ["iter.", "J_T", "ΔJ_T", "FG(F)", "secs"] @assert length(wrk.J_parts) == 1 iter_stop = "$(get(wrk.kwargs, :iter_stop, 5000))" width = Dict( "iter." => max(length("$iter_stop"), 6), "J_T" => 11, "|∇J_T|" => 11, "|∇J_a|" => 11, "|∇J|" => 11, "ΔJ" => 11, "ΔJ_T" => 11, "FG(F)" => 8, "secs" => 8, ) if iteration == 0 for header in headers w = width[header] print(lpad(header, w)) end print("\n") end strs = [ "$iteration", @sprintf("%.2e", J_T), (iteration > 0) ? @sprintf("%.2e", ΔJ_T) : "n/a", @sprintf("%d(%d)", wrk.fg_count[1], wrk.fg_count[2]), @sprintf("%.1f", secs), ] for (str, header) in zip(strs, headers) w = width[header] print(lpad(str, w)) end print("\n") flush(stdout) end # Transfer information from `wrk` to `wrk.result` in each iteration (before the # `info_hook`) function update_result!(wrk::ParameterizedOptWrk, i::Int64) res = wrk.result for (k, Ψ) in enumerate(wrk.states) copyto!(res.states[k], Ψ) end copyto!(wrk.result.optimized_parameters, wrk.parameters) res.f_calls += wrk.fg_count[2] res.fg_calls += wrk.fg_count[1] res.J_T_prev = res.J_T res.J_T = wrk.J_parts[1] (i > 0) && (res.iter = i) if i >= res.iter_stop res.converged = true res.message = "Reached maximum number of iterations" # Note: other convergence checks are done in user-supplied # check_convergence routine end prev_time = res.end_local_time res.end_local_time = now() res.secs = Dates.toms(res.end_local_time - prev_time) / 1000.0 end optimize(problem, method::Val{:ParameterizedQuantumControl}) = optimize_parameters(problem)
ParameterizedQuantumControl
https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl.git
[ "MIT" ]
0.1.2
60341f3f9a9f7634574034d06740914489f12317
code
2913
using QuantumControl.QuantumPropagators.Controls: get_parameters using Printf using Dates """Result object returned by [`optimize_parameters`](@ref).""" mutable struct ParameterizedOptResult{STST,PT} tlist::Vector{Float64} iter_start::Int64 # the starting iteration number iter_stop::Int64 # the maximum iteration number iter::Int64 # the current iteration number secs::Float64 # seconds that the last iteration took tau_vals::Vector{ComplexF64} J_T::Float64 # the current value of the final-time functional J_T J_T_prev::Float64 # previous value of J_T guess_parameters::PT optimized_parameters::PT states::Vector{STST} start_local_time::DateTime end_local_time::DateTime records::Vector{Tuple} # storage for info_hook to write data into at each iteration converged::Bool f_calls::Int64 fg_calls::Int64 message::String function ParameterizedOptResult(problem) tlist = problem.tlist iter_start = get(problem.kwargs, :iter_start, 0) iter_stop = get(problem.kwargs, :iter_stop, 5000) iter = iter_start secs = 0 tau_vals = zeros(ComplexF64, length(problem.trajectories)) J_T = 0.0 J_T_prev = 0.0 parameters = get(problem.kwargs, :parameters, get_parameters(problem)) optimized_parameters = copy(parameters) guess_parameters = copy(parameters) states = [similar(traj.initial_state) for traj in problem.trajectories] start_local_time = now() end_local_time = now() records = Vector{Tuple}() converged = false message = "in progress" f_calls = 0 fg_calls = 0 PT = typeof(optimized_parameters) STST = eltype(states) new{STST,PT}( tlist, iter_start, iter_stop, iter, secs, tau_vals, J_T, J_T_prev, guess_parameters, optimized_parameters, states, start_local_time, end_local_time, records, converged, f_calls, fg_calls, message ) end end Base.show(io::IO, r::ParameterizedOptResult) = print(io, "ParameterizedOptResult<$(r.message)>") Base.show(io::IO, ::MIME"text/plain", r::ParameterizedOptResult) = print( io, """ Parameterized Optimization Result --------------------------------- - Started at $(r.start_local_time) - Number of trajectories: $(length(r.states)) - Number of iterations: $(max(r.iter - r.iter_start, 0)) - Number of pure func evals: $(r.f_calls) - Number of func/grad evals: $(r.fg_calls) - Value of functional: $(@sprintf("%.5e", r.J_T)) - Reason for termination: $(r.message) - Ended at $(r.end_local_time) ($(Dates.canonicalize(Dates.CompoundPeriod(r.end_local_time - r.start_local_time)))) """ )
ParameterizedQuantumControl
https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl.git
[ "MIT" ]
0.1.2
60341f3f9a9f7634574034d06740914489f12317
code
2607
import QuantumControl using QuantumControl.QuantumPropagators.Controls: get_parameters """Parameterized Optimization Workspace.""" mutable struct ParameterizedOptWrk{O} # a copy of the trajectories trajectories # parameters: AbstractVector of parameters in the problem. This must # aliases into the problem, so that mutating the vector directly affects # the propgation parameters::AbstractVector # The kwargs from the control problem kwargs # vector [J_T, …] (parts other than J_T for future use) J_parts::Vector{Float64} fg_count::Vector{Int64} # The backend (name of package/module) backend::Symbol # The states from the most recent evaluation of the functional states # The optimizer optimizer::O optimizer_state result use_threads::Bool end function ParameterizedOptWrk(problem::QuantumControl.ControlProblem; verbose=false) use_threads = get(problem.kwargs, :use_threads, false) kwargs = Dict(problem.kwargs) # creates a shallow copy; ok to modify trajectories = [traj for traj in problem.trajectories] states = [traj.initial_state for traj in trajectories] parameters = get(problem.kwargs, :parameters, get_parameters(problem)) J_parts = zeros(1) fg_count = zeros(Int64, 2) backend = Symbol(nothing) if haskey(kwargs, :backend) if !(kwargs[:backend] isa Module) throw(ArgumentError("`backend` must be a module")) end backend = nameof(kwargs[:backend]) else error("no backend: cannot optimize") end optimizer = nothing if haskey(kwargs, :optimizer) optimizer = kwargs[:optimizer] else error("no optimizer: cannot optimize") end optimizer_state = nothing if haskey(kwargs, :continue_from) @info "Continuing previous optimization" result = kwargs[:continue_from] if !(result isa ParameterizedOptResult) # account for continuing from a different optimization method result = convert(ParameterizedOptResult, result) end result.iter_stop = get(kwargs, :iter_stop, 5000) result.converged = false result.start_local_time = now() result.message = "in progress" else result = ParameterizedOptResult(problem) end O = typeof(optimizer) ParameterizedOptWrk{O}( trajectories, parameters, kwargs, J_parts, fg_count, backend, states, optimizer, optimizer_state, result, use_threads ) end
ParameterizedQuantumControl
https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl.git
[ "MIT" ]
0.1.2
60341f3f9a9f7634574034d06740914489f12317
code
2201
""" clean([distclean=false]) Clean up build/doc/testing artifacts. Restore to clean checkout state (distclean) """ function clean(; distclean=false, _exit=true) _exists(name) = isfile(name) || isdir(name) _push!(lst, name) = _exists(name) && push!(lst, name) function _glob(folder, ending) if !_exists(folder) return [] end [name for name in readdir(folder; join=true) if (name |> endswith(ending))] end function _glob_star(folder; except=[]) if !_exists(folder) return [] end [ joinpath(folder, name) for name in readdir(folder) if !(name |> startswith(".") || name ∈ except) ] end ROOT = dirname(@__DIR__) ########################################################################### CLEAN = String[] _push!(CLEAN, joinpath(ROOT, "coverage")) _push!(CLEAN, joinpath(ROOT, "docs", "build")) _push!(CLEAN, joinpath(ROOT, "docs", "LocalPreferences.toml")) _push!(CLEAN, joinpath(ROOT, "test", "LocalPreferences.toml")) append!(CLEAN, _glob(ROOT, ".info")) append!(CLEAN, _glob(joinpath(ROOT, ".coverage"), ".info")) ########################################################################### ########################################################################### DISTCLEAN = String[] for folder in ["", "docs", "test"] _push!(DISTCLEAN, joinpath(joinpath(ROOT, folder), "Manifest.toml")) end _push!(DISTCLEAN, joinpath(ROOT, "docs", "Project.toml")) append!(DISTCLEAN, _glob_star(joinpath(ROOT, "test", "data"))) append!(DISTCLEAN, _glob_star(joinpath(ROOT, "docs", "data"))) _push!(DISTCLEAN, joinpath(ROOT, ".JuliaFormatter.toml")) ########################################################################### for name in CLEAN @info "rm $name" rm(name, force=true, recursive=true) end if distclean for name in DISTCLEAN @info "rm $name" rm(name, force=true, recursive=true) end if _exit @info "Exiting" exit(0) end end end distclean() = clean(distclean=true)
ParameterizedQuantumControl
https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl.git
[ "MIT" ]
0.1.2
60341f3f9a9f7634574034d06740914489f12317
code
1214
# init file for "make devrepl" using Revise using Plots unicodeplots() using JuliaFormatter using QuantumControlTestUtils: test, show_coverage, generate_coverage_html using LiveServer: LiveServer, serve, servedocs include(joinpath(@__DIR__, "clean.jl")) REPL_MESSAGE = """ ******************************************************************************* DEVELOPMENT REPL Revise, JuliaFormatter, LiveServer, Plots with unicode backend are active. * `help()` – Show this message * `include("test/runtests.jl")` – Run the entire test suite * `test()` – Run the entire test suite in a subprocess with coverage * `show_coverage()` – Print a tabular overview of coverage data * `generate_coverage_html()` – Generate an HTML coverage report * `include("docs/make.jl")` – Generate the documentation * `format(".")` – Apply code formatting to all files * `servedocs([port=8000, verbose=false])` – Build and serve the documentation. Automatically recompile and redisplay on changes * `clean()` – Clean up build/doc/testing artifacts * `distclean()` – Restore to a clean checkout state ******************************************************************************* """ """Show help""" help() = println(REPL_MESSAGE)
ParameterizedQuantumControl
https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl.git
[ "MIT" ]
0.1.2
60341f3f9a9f7634574034d06740914489f12317
code
435
using Test using SafeTestsets using Plots unicodeplots() # Note: comment outer @testset to stop after first @safetestset failure @time @testset verbose = true "ParameterizedQuantumControl.jl Package" begin @test "Hello World" isa String #= println("\n* TLS Optimization (test_tls_optimization.jl)") @time @safetestset "TLS Optimization" begin include("test_tls_optimization.jl") end =# end nothing
ParameterizedQuantumControl
https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl.git
[ "MIT" ]
0.1.2
60341f3f9a9f7634574034d06740914489f12317
docs
2345
# ParameterizedQuantumControl.jl [![Version](https://juliahub.com/docs/ParameterizedQuantumControl/version.svg)](https://juliahub.com/ui/Packages/ParameterizedQuantumControl/W0mna) [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://juliaquantumcontrol.github.io/ParameterizedQuantumControl.jl/) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://juliaquantumcontrol.github.io/ParameterizedQuantumControl.jl/dev) [![Build Status](https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl/workflows/CI/badge.svg)](https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl/actions) [![Coverage](https://codecov.io/gh/JuliaQuantumControl/ParameterizedQuantumControl.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/JuliaQuantumControl/ParameterizedQuantumControl.jl) Implementation of control methods for analytical parameterized control fields. Part of [`QuantumControl.jl`][QuantumControl] and the [JuliaQuantumControl][] organization. ## Installation As usual, the package can be installed with ~~~ pkg> add ParameterizedQuantumControl ~~~ ## Usage * Define a `QuantumControl.ControlProblem` that contains parameterized generators or control fields: `get_parameters(problem)` must return a vector of control parameters. * Call `QuantumControl.optimize` using `method=ParameterizedQuantumControl`, and give an appropriate backend and optimizer, e.g., ``` optimize( problem; method=ParameterizedQuantumControl, backend=Optimization, optimizer=NLopt.LN_NELDERMEAD(), ) ``` Currently, only [`Optimization.jl`](https://github.com/SciML/Optimization.jl) is supported as a backend, and only with gradient-free optimizers. In the future, this will be extended to gradient-based optimizers (i.e., the "GOAT" method), as well as specific pulse parametrizations (e.g., CRAB). ## Documentation A minimal standalone documentation of `ParameterizedQuantumControl.jl` is available at <https://juliaquantumcontrol.github.io/ParameterizedQuantumControl.jl>. For a broader perspective, see the [documentation of the `QuantumControl.jl` package](https://juliaquantumcontrol.github.io/QuantumControl.jl/). [QuantumControl]: https://github.com/JuliaQuantumControl/QuantumControl.jl#readme [JuliaQuantumControl]: https://github.com/JuliaQuantumControl
ParameterizedQuantumControl
https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl.git
[ "MIT" ]
0.1.2
60341f3f9a9f7634574034d06740914489f12317
docs
105
```@meta CollapsedDocStrings = true ``` # API ```@autodocs Modules = [ParameterizedQuantumControl] ```
ParameterizedQuantumControl
https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl.git
[ "MIT" ]
0.1.2
60341f3f9a9f7634574034d06740914489f12317
docs
2099
```@meta CurrentModule = ParameterizedQuantumControl ``` # ParameterizedQuantumControl.jl ```@eval using Markdown using Pkg VERSION = Pkg.dependencies()[Base.UUID("409be4c9-afa4-4246-894e-472b92a1ed06")].version github_badge = "[![Github](https://img.shields.io/badge/JuliaQuantumControl-ParameterizedQuantumControl.jl-blue.svg?logo=github)](https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl)" version_badge = "![v$VERSION](https://img.shields.io/badge/version-v$(replace(string(VERSION), "-" => "--"))-green.svg)" Markdown.parse("$github_badge $version_badge") ``` Implementation of control methods for analytical parameterized control fields. Part of [`QuantumControl.jl`](https://github.com/JuliaQuantumControl/QuantumControl.jl#readme) and the [JuliaQuantumControl](https://github.com/JuliaQuantumControl) organization. ## Installation As usual, the package can be installed with ~~~ pkg> add ParameterizedQuantumControl ~~~ ## Usage * Define a [`QuantumControl.ControlProblem`](@ref) that contains parameterized generators or control fields: [`get_parameters(problem)`](@ref get_parameters) must return a vector of control parameters. * Call [`QuantumControl.optimize`](@extref) using `method=ParameterizedQuantumControl`, and give an appropriate backend and optimizer, e.g., ``` optimize( problem; method=ParameterizedQuantumControl, backend=Optimization, optimizer=NLopt.LN_NELDERMEAD(), ) ``` See [`ParameterizedQuantumControl.optimize_parameters`](@ref) for details. Currently, only [`Optimization.jl`](@extref Optimization :doc:`index`) is supported as a backend, and only with gradient-free optimizers. In the future, this will be extended to gradient-based optimizers (i.e., the "GOAT" method [MachnesPRL2018](@cite)), as well as specific pulse parametrizations (e.g., CRAB [CanevaPRA2011](@cite)). ## Contents ```@contents Depth = 2 Pages = [pair[2] for pair in Main.PAGES[2:end-1]] ``` ## History See the [Releases](https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl/releases) on Github.
ParameterizedQuantumControl
https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl.git
[ "MIT" ]
0.1.2
60341f3f9a9f7634574034d06740914489f12317
docs
8535
# Overview ## Control Parameters The `ParameterizedQuantumControl` package optimizes a set ``\{u_n\}`` of arbitrary [control parameters](@extref QuantumControl Control-Parameters) associated with a given [control problem](@ref ControlProblem). The dynamic generators ``\Op{H} = \Op{H}(\{u_n\}, t)`` from the different [trajectories](@ref Trajectory) implicitly depend on these parameter values in arbitrary ways. Contrast this with the form ```math \Op{H} = \Op{H}_0 + \sum_l \Op{H}_l(\{ϵ_{l′}(t)\}, t) \quad\text{or}\quad \Op{H}_0 + \sum_l a_l(\{ϵ_{l′}(t)\}, t) \Op{H}_l \quad\text{or}\quad \Op{H}_0 + \sum_l ϵ_l(t) \Op{H}_l ``` of a [Generator](@extref QuantumControl :label:`Generator`), where ``\Op{H}_0`` is the drift term, ``\Op{H}_l`` are the control terms, and ``a_l(t)`` and ``ϵ_l(t)`` are the [control amplitudes](@extref QuantumControl :label:`Control-Amplitude`) and [control functions](@extref QuantumControl :label:`Control-Function`), respectively. Methods such as [GRAPE](@extref GRAPE :doc:`index`) and [Krotov's method](@extref Krotov :doc:`index`) optimize each ``ϵ_l(t)`` as a time-continuous function. Control amplitudes or control functions still play a conceptual role: Even though in the most general case, the generator ``\Op{H}`` can directly depend on the parameters, the most common case is for that dependency to be inside of the controls, ``ϵ_l(t) → ϵ_l(\{u_n\}, t)``. The crucial difference is that in `ParameterizedQuantumControl`, we solve the optimization problem by tuning the values ``u_n``, not ``ϵ_l(t)`` as arbitrary time-continuous control functions. The `ParameterizedQuantumControl` package evaluates an arbitrary optimization functional ``J(\{u_n\})`` and optionally the gradient ``\frac{∂J}{∂ u_n}`` and feeds that information to an optimization backend, e.g. [Optimization.jl](@extref Optimization :doc:`index`) with its large collection of solvers. We may again contrast this with [GRAPE](@extref GRAPE :doc:`index`) and [Krotov's method](@extref Krotov :doc:`index`) which conceptually optimize time-continuous control functions ``ϵ_l(t)`` but in practice discretize these functions as piecewise-constant on a time grid. One might be tempted to think if this discretization as the use of control parameters ``ϵ_l(t) = ϵ_l(\{ϵ_{nl}\})`` where each parameter ``ϵ_{nl}`` is the amplitude of ``ϵ_l(t)`` on the ``n``'th interval of the time grid (what we refer to as a ["pulse"](@extref QuantumControl :label:`Pulse`)). However, GRAPE and Krotov have a specific numerical scheme to evaluate the gradients of the optimization functional with respect to the pulse values. That scheme is dramatically more efficient than the [more general scheme to determine gradients](@ref gradients) with respect to *arbitrary* parameters that is used in `ParameterizedQuantumControl`. ## Parameter API `ParameterizedQuantumControl` manages the evaluation of functionals and gradients, and organizes feeding that information into an optimization backend. However, the structures for working with control parameters are already provided by the [`QuantumPropagators`](@extref QuantumPropagators :doc:`index`) and [`QuantumControl`](@extref QuantumControl :doc:`index`) packages. We summarize them here in the context of optimal control. Generally, the vector of `parameters` is obtained from `problem` via the [`get_parameters`](@ref) function. This delegates to `get_parameters(traj)` for each [`Trajectory`](@ref) in `problem.trajectories`, which in turn delegates to `get_parameters(traj.generator)`. This makes it possible to define a custom datatype for the dynamic generator for which a `get_parameters` method is defined. It is recommended for `get_parameters` to return a [`ComponentArrays.ComponentVector`](@extref) `parameters`. That makes it easy to keep track of which value is which parameters. However, in general, `get_parameters` can return an arbitrary [`AbstractVector`](@extref Julia `Base.AbstractVector`). What is important is that the returned `parameters` alias into the generator. That is, mutating `parameters` and then calling [`QuantumControl.Controls.evaluate(generator, args...; kwargs...)`](@extref QuantumControl `QuantumPropagators.Controls.evaluate`) must return an operator that takes into account the current values in `parameters`. The easiest way to achieve this is to have `parameters` be a field in the custom `struct` of the generator and have `get_parameters` return a reference to that field. The `QuantumControl.Interfaces.check_parameterized` function of `QuantumControl.Interfaces.check_generator` with `for_parameterization=true` can be used to verify the implementation of a custom generator. ```@raw todo As soon as we figure out the interface for the gradients, `QuantumControl.Interfaces.check_generator` needs to be implemented separately from the version in `QuantumPropagators`, and then we can properly link the above references ``` When there are multiple trajectories (and thus multiple generators) in the [`ControlProblem`](@ref), these are automatically combined into a [`RecursiveArrayTools.ArrayPartition`](@extref). The parameters from different generators are considered independent unless they are the same object. When using a built-in [`QuantumControl.Generators.Generator`](@ref) as returned by [`QuantumControl.hamiltonian`](@ref) or [`QuantumControl.liouvillian`](@ref), the [`get_parameters`](@ref) function delegates to the `get_parameters(control)` for any control returned by [`get_controls(generator)`](@extref QuantumControl `QuantumPropagators.Controls.get_controls`). The recommended way to implement a custom parameterized control is to subtype [`QuantumControl.Controls.ParameterizedFunction`](@ref). Just like parameters from different generators in the same control problem are automatically combined, the parameters from different controls are also automatically combined into a [`RecursiveArrayTools.ArrayPartition`](@extref), taking into account if `get_parameters` returns the same object for two different controls. In any case, for any custom implementation of a parameterized system, and especially if control parameters are aliased between different components of the system, it is important to carefully check that the result of `get_parameters` contains all the independent parameters of the problem. ```@raw todo The is a connection to be made with the `parameters` field of a propagator and the paremters of the dynamic generators for the propagation. ``` ```@raw todo Explain pulse parameterization ``` ## Evaluation of the Functional In order to evaluate an optimization functional ``J(\{u_n\})``, the `ParameterizedQuantumControl` package simply uses [`QuantumControl.propagate_trajectories`](@ref) and passes the resulting states to a `J_T` function. Running costs are a work in progress. Again, the dynamic generators are assumed to have been implemented in such a way that mutating the values in the array returned by [`get_parameters`](@ref) are automatically taken into account. In principle, any [propagation method](@extref QuantumPropagators :doc:`methods`) can be used for the evaluation of the functional. However, parameterized controls are typically time-continuous functions, and using piecewise-constant propagators such as [`ExpProp`](@extref QuantumPropagators :label:`method_expprop`), [`Cheby`](@extref QuantumPropagators :label:`method_cheby`), or [`Newton`](@extref QuantumPropagators :label:`method_newton`) is unnecessary and introduces a discretization error. Usually, using an ODE solver with [`method=OrdinaryDiffEq`](@extref QuantumPropagators :label:`method_ode`) is more appropriate. It is also worth noting that the time discretization that happens in piecewise-constant propagators severs the connection between the control parameters and the pulse amplitudes at each interval of the time grid. Thus, any changes to the `parameters` after [`QuantumControl.init_prop`](@ref) will not be reflected in subsequent calls to [`QuantumControl.prop_step!`](@ref). This is not an issue inside of `ParameterizedQuantumControl`, as [`QuantumControl.propagate_trajectories`](@ref) initializes a new propagator for every evaluation of the functional. ```@raw todo * Can we guarantee that the `OrdinaryDiffEq` propagator is reusable? * Test that reinit_prop! updates the parameters ``` ## [Gradient Evaluation](@id gradients) Optimizers that rely on gradient information will be supported in a future release. ## Running costs Running costs are planned in a future release.
ParameterizedQuantumControl
https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl.git