TMI
Documentation for TMI.
TMI.BoundaryConditionTMI.FieldTMI.GridTMI.GridTMI.MassFractionTMI.SourceBase.:\Base.lengthBase.oneBase.oneBase.onesBase.onesBase.onesBase.propertynamesBase.sumBase.vecBase.vecBase.zeroBase.zerosBase.zerosBase.zerosBase.zerosLinearAlgebra.dotLinearAlgebra.dotTMI.add!TMI.adjustboundaryconditionTMI.adjustboundarycondition!TMI.adjustboundarycondition!TMI.axislabelsTMI.boundaryconditionattsTMI.boundarymaskTMI.boundarymaskTMI.boundarymatrixTMI.boundarymatrixTMI.boundarymatrix2ncTMI.boundarymatrix2ncTMI.cartesianindexTMI.cartesianindexTMI.cartesianindexTMI.cellareaTMI.cellareaTMI.cellvolumeTMI.cellvolumeTMI.checkgrid!TMI.circulationmatrixTMI.circulationmatrixTMI.circulationmatrixTMI.circulationmatrix2ncTMI.circulationmatrix2ncTMI.configTMI.config2ncTMI.config2ncTMI.control2stateTMI.control2stateTMI.costfunction_gridded_modelTMI.costfunction_gridded_model!TMI.costfunction_gridded_obsTMI.costfunction_gridded_obsTMI.costfunction_gridded_obs!TMI.costfunction_gridded_obs!TMI.costfunction_point_obsTMI.costfunction_point_obsTMI.costfunction_point_obs!TMI.costfunction_point_obs!TMI.depthindexTMI.depthindexTMI.dirichletmatrixTMI.distancematrixTMI.download_fileTMI.download_regionfileTMI.eastindexTMI.eastindexTMI.effective_endmemberTMI.effective_endmember_sumsTMI.fieldsattsTMI.fieldsattsTMI.gadjustboundaryconditionTMI.gadjustboundaryconditionTMI.gadjustboundarycondition!TMI.gadjustboundarycondition!TMI.gaussiandistancematrixTMI.getboundaryconditionTMI.getboundaryconditionTMI.getboundaryconditionTMI.geteastboundaryTMI.geteastboundaryTMI.getnorthboundaryTMI.getnorthboundaryTMI.getsouthboundaryTMI.getsouthboundaryTMI.getsurfaceboundaryTMI.getsurfaceboundaryTMI.getwestboundaryTMI.getwestboundaryTMI.gobserveTMI.gobserveTMI.grid2ncTMI.grid2ncTMI.griddictsTMI.griddictsTMI.gridsizeTMI.gsetboundaryconditionTMI.gsetboundaryconditionTMI.gsetboundaryconditionTMI.gsetsource!TMI.gsteadyinversionTMI.gsteadyinversionTMI.horizontaldistanceTMI.horizontaldistanceTMI.interiormaskTMI.interpindexTMI.interpindexTMI.interpweightsTMI.interpweightsTMI.iswetTMI.iswetTMI.latindexTMI.latindexTMI.linearindexTMI.linearindexTMI.local_watermass_matrixTMI.location_obsTMI.location_obsTMI.lonindexTMI.lonindexTMI.matfields2nc_origTMI.matrix_modern2glacialTMI.meanageTMI.meanageTMI.mixedlayermaskTMI.mixedlayermatrixTMI.ncurlTMI.ncurlTMI.nearestneighborTMI.nearestneighborTMI.nearestneighbormaskTMI.nearestneighbormaskTMI.neighbor_indicesTMI.neighborsTMI.neighborsTMI.northindexTMI.northindexTMI.observeTMI.observeTMI.observeTMI.oneeastboundaryTMI.onenorthboundaryTMI.onesouthboundaryTMI.onesurfaceboundaryTMI.onesurfaceboundaryTMI.onewestboundaryTMI.optim2ncTMI.optim2ncTMI.preformedcarbon13TMI.preformednitrateTMI.preformednutrientTMI.preformedoxygenTMI.preformedphosphateTMI.readfieldTMI.readtracerTMI.regeneratednutrientTMI.regions_mat2ncTMI.regionurlTMI.sectionTMI.sectionTMI.setboundarycondition!TMI.setboundarycondition!TMI.setboundarycondition!TMI.setsource!TMI.shiftlocTMI.shiftlocTMI.southindexTMI.southindexTMI.sparsedatamap_optimTMI.standardize_fieldnamesTMI.steadyclimatology_optimTMI.steadyinversionTMI.steadyinversionTMI.step_cartesianTMI.surfacecontrol2fieldTMI.surfacecontrol2fieldTMI.surfacecontrol2field!TMI.surfacecontrol2field!TMI.surfacecontrol2field!TMI.surfaceindexTMI.surfaceindexTMI.surfaceoriginTMI.surfaceoriginTMI.surfacepatchTMI.surfacepatchTMI.surfaceregionTMI.surfaceregionTMI.surfaceregionTMI.synthetic_observationsTMI.synthetic_observationsTMI.synthetic_observationsTMI.tracerinitTMI.tracerinitTMI.trackpathwaysTMI.trackpathwaysTMI.unvecTMI.unvecTMI.unvec!TMI.unvec!TMI.vec2fldTMI.volumefilledTMI.volumefilledTMI.watermassdistributionTMI.watermassdistributionTMI.watermassmatrixTMI.watermassmatrixTMI.watermassmatrixTMI.watermassmatrixTMI.westindexTMI.westindexTMI.wetlocationTMI.wetlocationTMI.writeTMI.writeTMI.zeroeastboundaryTMI.zeroeastboundaryTMI.zeronorthboundaryTMI.zeronorthboundaryTMI.zerosouthboundaryTMI.zerosouthboundaryTMI.zerosurfaceboundaryTMI.zerosurfaceboundaryTMI.zerowestboundaryTMI.zerowestboundaryTMI.Γsfc!
TMI.BoundaryCondition — Type
struct BoundaryCondition
a plane defined at `dim=dimval`Attributes
`tracer::Array{T,2}`: values on plane
`i::Vector{T}`: coordinate values on local x-plane
`j::Vector{T}`: coordinate values on local y-plane
`k::T`: fixed coordinate value on local z-plane that defines the Boundary Condition plane
`dim::Int64`: dimension (1,2, or 3) along which the plane's index is fixed
`dimval::Int64`: plane defined at dim = dimval where dimval is a 1-based index number
`wet::BitArray{2}`: ocean mask for boundary conditionTMI.Grid — Type
struct GridTMI grid with accounting for wet/dry points
Fields
axes::NTuple{N,Vector{A}}: labels for axis such as lon, lat, depth with element typeAwet::BitArray{N}: mask for ocean pointsinterior::BitArray{N}: mask for interior ocean pointswrap::NTuple{N,Bool}: does the domain wraparound in each dim?Δ::Vector{CartesianIndex{N}}: defines computational stencil relative to central cell
TMI.Grid — Method
function Grid(TMIfile)Construct the Grid given a file name
Arguments
TMIfile::String: NetCDF file name for TMI version
Output
γ::Grid: TMI grid structfunction Grid(foreign_file, maskname, lonname, latname, depthname)
Construct the Grid from a non-TMI file given the names of relevant fields.
Assumes that an ocean mask is available. Assumes an input NetCDF file. Assumes everything below the top layer is part of the interior. Tested for Float32 fields (should work for other types).
Arguments
foreign_file::Stringmaskname::Stringlonname::Stringlatname::Stringdepthname::String
Output
γ::Grid: TMI grid struct
TMI.MassFraction — Type
struct MassFraction
store mass fractions in a Field-like array
fraction::Array{T,3}γ::Gridname::Symbollongname::Stringunits::Stringposition::CartesianIndex{3}
TMI.Source — Type
struct Source
This structure describes Sources, which are
similar to Fields, but they may be
1) non-negative
2) have only interior maskBase.length — Method
Base.length(c::Union{Field,Source,BoundaryCondition}) = length(c.tracer[wet(c)])
Extend `length` to give the number of wet (i.e., ocean) gridcells.Base.propertynames — Method
Base.propertynames(γ::Grid) = (I,R,fieldnames(typeof(x))...)
Do not store Cartesian and linear indices.
Compute them on demand.Base.zeros — Function
function zeros(wet,ltype=Float64)
initialize tracer field on TMI grid
This version will give an arrayArguments
wet::BitArray mask of ocean pointsltype:: optional type argument, default=Float64
Output
d:: 3d tracer field with NaN on dry points
Base.zeros — Method
function zeros(γ::Grid,name=:none,longname="unknown",units="unknown")::Field
initialize tracer field on TMI grid
using a Field struct and constructorArguments
γ::TMI.Grid
Output
d::Field, 3d tracer field with NaN on dry points
Base.zeros — Method
function zeros(dim::Int64,dimval::Int64,γ::Grid,name::Symbol,longname::String,units::String)::BoundaryCondition
Initialize boundary condition with zeroesArguments
dim:dimvalγ::Gridname::Symbollongname::Stringunits::String
Output
b::BoundaryCondition
LinearAlgebra.dot — Method
`function *(c::Field,d::Field)::Field`
Field by field multiplication is element-by-element.TMI.adjustboundarycondition! — Method
function adjustboundarycondition!(b::Union{BoundaryCondition,NamedTuple},u::Union{BoundaryCondition,NamedTuple})
adjust all boundary conditions b that are described in u
warning: if u doesn't contain any boundary condition adjustments,
nothing will change.TMI.adjustboundarycondition — Method
function adjustboundarycondition!(b::Union{BoundaryCondition,NamedTuple},u::Union{BoundaryCondition,NamedTuple})
adjust all boundary conditions b that are described in uTMI.axislabels — Method
function axislabels(file)Read and assemble the grid properties.
Arguments
file: TMI NetCDF file name
Output
grid: TMI grid coordinates
TMI.boundaryconditionatts — Method
function boundaryconditionatts(dim::Int64,dimval::Int64,γ::Grid)
Help initialize boundary condition by getting some attributesTMI.boundarymask — Method
function boundarymask(b, γ::Grid)TMI.boundarymask — Method
function boundarymask(γ)
TMI.boundarymatrix — Method
function boundarymatrix(file,γ)
Read and assemble the boundary matrix from MATLAB.
Transfer to updated x,y,z versionArguments
file: TMI MATLAB file nameγ: TMI grid
Output
B: boundary condition matrix
TMI.boundarymatrix2nc — Method
Save boundary matrix for transient model to NetCDF file
TMI.cartesianindex — Method
function cartesianindex(file)Read and assemble the grid coordinates according to the legacy MATLAB code (z,y,x order).
Arguments
file: TMI NetCDF file name
Output
I: TMI Cartesian index for wet points
TMI.cartesianindex — Method
function cartesianindex(wet)
Read and assemble the grid coordinates
according to a 3D tracer in x,y,z orderArguments
wet: BitArray logical mask for wet points
Output
I: 3D Cartesian indices
TMI.cellarea — Method
Horizontal area of grid cellTMI.cellvolume — Method
function cellvolume(γ)::Field
Volume of each grid cell.TMI.checkgrid! — Method
function checkgrid!(c,wet)
perform a check of file compatibility
with gridTMI.circulationmatrix — Method
function circulationmatrix(file,A,γ)
Read and assemble the circulation matrix from the efficient storage of A and F₀ variables.Arguments
file: TMI MATLAB file nameA: TMI water-mass matrixγ: TMI grid
Output
L: circulation matrix in xyz format
TMI.circulationmatrix — Method
function circulationmatrix(file,γ)
Read and assemble the circulation matrix from NetCDF.Arguments
file: TMI MATLAB file nameγ: TMI grid
Output
L: circulation matrix in xyz format
TMI.circulationmatrix2nc — Method
Save circulation matrix L to NetCDF file.
TMI.config — Method
function config(TMIversion; compute_lu = true)
Configure TMI environment from NetCDF input file.Arguments
TMIversion: TMI version for water-mass/circulation model
Output
A: TMI steady-state water-mass matrixAlu: LU decomposition of Aγ: TMI grid propertiesTMIfile: TMI file name
TMI.config2nc — Method
Save TMI configuration to NetCDF format for non-proprietary access
TMI.control2state — Method
function control2state(tracer2D,γ)
turn 2D surface field into 3D field with zeroes below surfaceArguments
tracer2D:: 2D surface tracer fieldwet::BitArray mask of ocean points
Output
tracer3D:: 3d tracer field with NaN on dry points
TMI.costfunction_gridded_model! — Method
function costfunction_gridded_model!(J,guvec,convec::Vector{T},non_zero_indices,u₀::Union{BoundaryCondition{T},NamedTuple{<:Any, NTuple{N2,BoundaryCondition{T}}}},c,y::Field{T},Wⁱ::Diagonal{T, Vector{T}},Qⁱ::Diagonal{T, Vector{T}},γ::Grid) where {N1, N2, T <: Real}TMI.costfunction_gridded_model — Method
function costfunction_gridded_model(convec::Vector{T},non_zero_indices,y::Field{T},u,A0,c,q,Wⁱ::Diagonal{T, Vector{T}},Qⁱ::Diagonal{T, Vector{T}},γ::Grid) where T <: Real
squared model-data misfit for gridded data
controls are a vector input for Optim.jlArguments
convec: concatenated control vecotr incuding u and fJ: cost function of sum of squared misfitsgJ: derivative of cost function wrt to controlsu: tracer controls, field formatnon_zero_indices: Non-zero indices for reconstruction of water-mass matrix Ac: tracer concentrations from GCMWⁱ: inverse of W weighting matrix for observationsQⁱ: inverse of Q weighting matrix for tracer conservationγ: grid
TMI.costfunction_gridded_obs! — Method
function costfunction_gridded_obs!(J,guvec,uvec::Vector{T},Alu,b₀::Union{BoundaryCondition{T},NamedTuple{<:Any, NTuple{N1,BoundaryCondition{T}}}},u₀::Union{BoundaryCondition{T},NamedTuple{<:Any, NTuple{N2,BoundaryCondition{T}}}},y::Field{T},Wⁱ::Diagonal{T, Vector{T}},γ::Grid) where {N1, N2, T <: Real}TMI.costfunction_gridded_obs — Method
function costfunction_gridded_obs(uvec::Vector{T},Alu,b::BoundaryCondition{T},y::Field{T},Wⁱ::Diagonal{T, Vector{T}},γ::Grid) where T <: Real
squared model-data misfit for gridded data
controls are a vector input for Optim.jlArguments
J: cost function of sum of squared misfitsgJ: derivative of cost function wrt to controlsu: controls, field formatAlu: LU decomposition of water-mass matrixb: boundary conditionsy: observations on gridWⁱ: inverse of W weighting matrix for observationsγ: grid
TMI.costfunction_point_obs! — Method
function costfunction_point_obs!(J,guvec,uvec::Vector{T},Alu,b₀::BoundaryCondition{T},u₀::BoundaryCondition{T},y::Vector{T},Wⁱ::Diagonal{T, Vector{T}},wis,locs,Q⁻,γ::Grid) where T <: Real
squared model-data misfit for pointwise data
controls are a vector input for Optim.jl
Issue #1: couldn't figure out how to nest with costfunction_obs!Arguments
J: cost function of sum of squared misfitsguvec: derivative of cost function wrt to controlsuvec: controls, vector formatAlu: LU decomposition of water-mass matrixb: boundary conditiony: pointwise observationsWⁱ: inverse of W weighting matrix for observationswis: weights for interpolation (data sampling, E)locs: data locations (lon,lat,depth)Q⁻: weights for control vectorγ: grid
TMI.costfunction_point_obs — Method
function costfunction_point_obs(uvec::Vector{T},Alu,b₀::BoundaryCondition{T},u₀::BoundaryCondition{T},y::Vector{T},Wⁱ::Diagonal{T, Vector{T}},wis,locs,Q⁻,γ::Grid;q=nothing,r=1.0) where T <: Real
Squared model-data misfit for pointwise data.
Controls are a vector input for Optim.jl.
Core numerics handled by `costfunction_point_obs`.Arguments
uvec: controls, vector formatAlu: LU decomposition of water-mass matrixb: boundary conditiony: pointwise observationsWⁱ: inverse of W weighting matrix for observationswis: weights for interpolation (data sampling, E)locs: data locations (lon,lat,depth)Q⁻: weights for control vectorγ: grid
Optional
q::Field: interior sourcer::Number: scalar factor for source
Output
J: cost function of sum of squared misfitsgJ: derivative of cost function wrt to controls
TMI.depthindex — Method
function depthindex(I)
Get the k-index (depth level) from the Cartesian indexTMI.dirichletmatrix — Method
function dirichletmatrix(γ, τ)Dirichlet surface boundary matrix with uniform timescale. Assumes that the Dirichlet boundary condition is zero.
Arguments
γ: TMI gridτ: uniform restoring timescale (years) for all boundary points
Output
Ldir: circulation matrix in xyz format for boundary points
TMI.distancematrix — Method
function distancematrix(γ;surface = true)
Matrix with size of surface points squared
Each entry gives distance in km between surface points
Gives only horizontal distance.TMI.download_file — Method
function download_file(TMIversion::String)
Download NetCDF file for given TMI versionArguments
TMIversion::String
Output
TMIfile::String: TMI file name
Side-effect
- download TMI input file if necessary
TMI.download_regionfile — Method
function download_regionfile(TMIversion::String)
Return file name of regional masks.
Also download file from Google Drive, if not already done.
File name refers to the 2D size of domain. It is the same for modern and LGM configs and only depends on number of points in Nx and Ny directions.
TMI.eastindex — Method
function eastindex(I)
Get the vector index on the northern open boundaryTMI.effective_endmember — Method
function effective_endmember(TMIversion,Alu,field,region,γ)Effective (i.e., importance-weighted) endmember tracer value calculated according to Gebbie and Huybers 2011.
TMI.effective_endmember_sums — Method
function effective_endmember_sums(Alu,field::Field,b::BoundaryCondition,γ::Grid)Intermediate quantities for computing effective endmembers
TMI.fieldsatts — Method
All variable names and attributes. Useful for writing NetCDF files.
TMI.gadjustboundarycondition! — Method
function gadjustboundarycondition!(b::BoundaryCondition{T},u::BoundaryCondition{T}) where T <: Real
adjust the (one) boundary condition
Just copy the variable.
Keep this function so that calling functions can look alike.
Could probably combine with lower function, use Union typeTMI.gadjustboundarycondition — Method
function gadjustboundarycondition(gb::BoundaryCondition{T},u::BoundaryCondition{T}) where T <: RealTMI.gaussiandistancematrix — Method
function gaussiandistancematrix(γ,σ,L)
uses distance matrix plus a lengthscale `L` (km)
and a size of the diagonal `σ`
returns values with inverse gaussian weightingTMI.getboundarycondition — Method
function getboundarycondition(field::Field,dim,dimval)::BoundaryCondition Get boundary condition by extracting from Field (i.e., 3D tracer)
Arguments
field::Field: 3D tracer field with metadata and griddim: dimension number (1,2,3) that the boundary plane has constant valuedimval: index number in dimensiondimthat defines boundary plane
Output
b::BoundaryCondition: boundary condition on a plane with metadata and grid
TMI.getboundarycondition — Method
Get boundary condition by extracting from N-dimensional tracer and returning (N-1)-dimensional array
TMI.geteastboundary — Method
geteastboundary(c::Field) = getboundarycondition(c,1,eastindex(c.γ))::BoundaryCondition
TMI.getnorthboundary — Method
getnorthboundary(c::Field) = getboundarycondition(c,2,northindex(c.γ))::BoundaryCondition
TMI.getsouthboundary — Method
getsouthboundary(c::Field) = getboundarycondition(c,2,southindex(c.γ))::BoundaryCondition
TMI.getsurfaceboundary — Method
getsurfaceboundary(c::Field) = getboundarycondition(c,3,surfaceindex(c.γ))::BoundaryCondition
TMI.getwestboundary — Method
getwestboundary(c::Field) = getboundarycondition(c,1,westindex(c.γ))::BoundaryCondition
TMI.gobserve — Method
function gobserve(gy::Vector{T},c::Field{T},wis,γ) where T <: Real
ADJOINT Take a observation at location given by weights wis
Arguments not symmetric with `observe` due to splat operatorTMI.grid2nc — Method
Put grid properties (Cartesian index) into NetCDF file
TMI.griddicts — Method
Save grid dictionaries of attributes for writing to NetCDF file
TMI.gridsize — Method
function gridsize(TMIversion)Parse the TMIversion string for the grid size
Will break if the prefix contains underscores or 'x'
TMI.gsetboundarycondition — Method
function gsetboundarycondition(gd::Field{T},b::BoundaryCondition{T}) where T<: Real
ADJOINT: apply boundary condition to the equation constraintsArguments
d::Field, equation constraints (i.e., right hand side)b::BoundaryCondition
TMI.gsetboundarycondition — Method
function gsetboundarycondition(gd::Field{T},b::BoundaryCondition{T}) where T<: Real
ADJOINT: apply boundary condition to the equation constraintsArguments
d::Field, equation constraints (i.e., right hand side)b::BoundaryCondition
TMI.gsetsource! — Method
function gsetsource!(gq::Field{T},gd::Field{T},r=1.0)
Adjoint to `setsource!`TMI.gsteadyinversion — Method
function gsteadyinversion(gc,Alu,b;q=nothing,r=1.0)
ADJOINT invert for a steady-state tracer distributionArguments
Alu: LU decomposition of water-mass matrixb: BoundaryConditionγ::Grid
Optional Arguments
q: interior sources/sinks of phosphater: stochiometric ratio of tracer:phosphate
Output
c::Field, steady-state tracer distribution
TMI.horizontaldistance — Method
function horizontaldistance(loc,γ)Arguments
loc: 3-tuple of lon,lat,depth locationγ: TMI.grid
Output
hordist: horizontal distance to nearest tracer grid points
TMI.interiormask — Method
function interiormask(A,wet,nx,ny,nz)
TMI.interpindex — Method
function interpindex(loc,γ) Weights for linear interpolation. The derivative of linear interpolation is needed in sensitivity studies. ReverseDiff.jl could find this quantity automatically. Instead we dig into the Interpolations.jl package to find the weights that are effectively the partial derivatives of the function.
Arguments
c: a temporary tracer field, would be nice to make it unnecessaryloc: (lon,lat,depth) tuple of a location of interestγ: TMI grid
Output
δ: weights on a 3D tracer field grid
TMI.interpweights — Method
function interpweights(loc,γ) Weights for linear interpolation. The derivative of linear interpolation is needed in sensitivity studies. ReverseDiff.jl could find this quantity automatically. Instead we dig into the Interpolations.jl package to find the weights that are effectively the partial derivatives of the function.
Arguments
loc: (lon,lat,depth) tuple of a location of interestγ: TMI grid
Output
δ: weights on a 3D tracer field grid
TMI.iswet — Method
function iswet(loc, γ, neighbors)
Get (lon,lat,depth) tuples of wet locations.
Allow a location to be wet if at least one out of 8 nearby gridpoints is wet.
Certainly "wet" gridpoints could be defined more strictly.Arguments
loc: lon,lat,depthγneighbors
Output
- Boolean (true for ocean point)
TMI.latindex — Method
function latindex(I)
Get the j-index (latitude index) from the Cartesian indexTMI.linearindex — Method
function linearindex(wet)
Read and assemble the grid coordinates.Arguments
wet: 3D mask for wet points
Output
R: array of linear indices, but not a LinearIndices type
TMI.local_watermass_matrix — Method
function local_watermass_matrix(c::NamedTuple, m::NamedTuple, I::CartesianIndex, neighbors::Field) Find local water-mass matrix with singularity checker (true if one neighbor only has a single connection to the rest of the ocean)
Arguments
c::NamedTuple: input tracersm::NamedTuple: mass fractions for grid stencilI::CartesianIndex: local "location"neighbors::Field: integer number of neighbors
Output
A::Matrix: local water-mass matrixsingle_connection::Bool: true if flagged for singularity warning
TMI.location_obs — Method
function location_obs(field, locs, γ)TMI.lonindex — Method
function lonindex(I)
Get the i-index (lon index) from the Cartesian indexTMI.matfields2nc_orig — Method
Read 3D fields from mat file and save to NetCDF file.
TMI.matrix_modern2glacial — Method
function matrix_mod2glacial(Amodern,γmodern,γglacial)
Transfer modern water-mass matrix Amod to glacial water-mass matrix AglacialArguments
Amodern: modern water-mass matrixγmodern: modern TMI gridγglacial: glacial TMI grid
Output
Aglacial: glacial water-mass matrix
TMI.meanage — Method
function meanage(TMIversion,Alu,γ)
Mean or ideal ageArguments
TMIversion: version of TMI water-mass/circulation modelAlu: LU decomposition of water-mass matrix Aγ: TMI grid
Output
a: mean age [yr]
TMI.mixedlayermask — Method
function mixedlayermask(A,γ)
TMI.mixedlayermatrix — Method
function mixedlayermatrix(A, γ, τ)Read and assemble the circulation matrix from the efficient storage of A and F₀ variables.
Arguments
A: TMI water-mass matrixγ: TMI gridτ: uniform residence timescale (years) for all mixed layer points
Output
Lmix: circulation matrix in xyz format for mixed layer points
TMI.nearestneighbor — Function
function nearestneighbor(loc,γ)
return the Cartesian index and linear index
of the nearest N neighborsArguments
loc: 3-tuple of lon,lat,depth locationγ: TMI.grid
Output
Inn: Cartesian indices of nearest neighbor
#- Rnn: linear indices of nearest neighbor, Removed from code
TMI.nearestneighbormask — Function
function nearestneighbormask
Make a 3D tracer field that is 1 at location
of nearest neighbor, 0 elsewhereArguments
loc: location in a 3-tuple (lon,lat,depth)γ: TMI.grid
Output
δ: nearest neighbor mask 3D field
TMI.neighbor_indices — Function
function neighbor_indices(n::Integer)
Direction (step) of neighbors away from a central point. Choose n = 6 (default) or n=26.
Argument
n=6: max number of neighbors
Output
In::Vector{CartesianIndex}: indices of neighbors
TMI.neighbors — Method
function neighbors(γ::Grid; longname = "number of neighbors")
How many neighbors does each grid cell have? Conceptually, it only depends on the grid, but this algorithm is slower than the one that takes mass fractions as input.
Arguments
γ::TMI.Grid
Output
n::Field: integer number of neighbors
TMI.neighbors — Method
function neighbors(m::NamedTuple,γ::Grid)
How many neighbors does each grid cell have?
Arguments
m::NamedTuple: input mass fractions to obtain their stencil (opportunity to simplify)γ::TMI.Grid
Output
n::Field: integer number of neighbors
TMI.northindex — Method
function northindex(I)
Get the vector index on the northern open boundaryTMI.observe — Method
function observe
Take a observation at location given by weights wisTMI.observe — Method
function observe(c,loc,γ)
Extend the TMI.observe method to use locations rather than weighted interpolations.TMI.oneeastboundary — Function
oneeastboundary(γ,name=:none,longname="unknown",units="unknown") = ones(1,eastindex(γ),γ,name,longname,units)::BoundaryCondition
TMI.onenorthboundary — Function
onenorthboundary(γ,name=:none,longname="unknown",units="unknown") = ones(2,northindex(γ),γ,name,longname,units)::BoundaryCondition
TMI.onesouthboundary — Function
onesouthboundary(γ,name=:none,longname="unknown",units="unknown") = ones(2,southindex(γ),γ,name,longname,units)::BoundaryCondition
TMI.onesurfaceboundary — Function
onesurfaceboundary(γ,name=:none,longname="unknown",units="unknown") = ones(3,surfaceindex(γ),γ,name,longname,units)::BoundaryCondition
TMI.onewestboundary — Function
onewestboundary(γ,name=:none,longname="unknown",units="unknown") = ones(1,westindex(γ),γ,name,longname,units)::BoundaryCondition
TMI.optim2nc — Method
Save optimization parameters to NetCDF file)
Future considerations: split into 2 functions
- read from mat
- save to nc
TMI.preformedcarbon13 — Method
preformedcarbon13(TMIversion,Alu,γ) = preformednutrient("δ¹³C",TMIversion,Alu,γ)
TMI.preformednitrate — Method
preformednitrate(TMIversion,Alu,γ) = preformednutrient("NO₃",TMIversion,Alu,γ)
TMI.preformednutrient — Method
function preformednutrient(tracer::Union{String,Symbol},TMIversion,Alu,γ)
Preformed (i.e., NO accumulation or remineralization) nutrientArguments
tracer::Union{Symbol,String}: tracer nameTMIversion: version of TMI water-mass/circulation modelAlu: LU decomposition of water-mass matrix Aγ: TMI grid
Output
c★: preformed tracer
TMI.preformedoxygen — Method
preformedoxygen(TMIversion,Alu,γ) = preformednutrient("O₂",TMIversion,Alu,γ)
TMI.preformedphosphate — Method
preformedphosphate(TMIversion,Alu,γ) = preformednutrient("PO₄",TMIversion,Alu,γ)
TMI.readfield — Method
function readfield(file,tracername,γ)
Read a tracer field from NetCDF but return it
as a Field.
Use NCDatasets so that Unicode is correctArguments
file: TMI NetCDF file nametracername: name of tracerγ::Grid, TMI grid specification
Output
c::Field
MATLAB version
function readfield(matfile,mattracername,γ::Grid,Izyx) # for MATLAB
read MATLAB field and transfer zyx format to xyzTMI.readtracer — Method
function readtracer(file,tracername)
Read a tracer field from NetCDF.Arguments
file: TMI NetCDF file nametracername: name of tracer
Output
c: 3D tracer field
TMI.regeneratednutrient — Method
function regeneratednutrient(TMIversion,Alu,γ)
Regenerated (i.e., accumulated, remineralized) nutrientArguments
tracer::Union{String,Symbol}: tracer nameTMIversion: version of TMI water-mass/circulation modelAlu: LU decomposition of water-mass matrix Aγ: TMI gridr: optional stoichiometric ratio relative to PO₄
Output
PO₄ᴿ: regenerated phosphate
TMI.regions_mat2nc — Method
function regions2nc(TMIversion,γ)
Read vectors from mat file, translate to 3D, and save surface field to NetCDF file.
Consider deprecating this function.
TMI.regionurl — Method
function regionurl(TMIversion)
placeholder function to give location (URL) of NetCDF Google Drive input
in the future, consider a struct or Dict that describes all TMI versions.Arguments
file: name of file to look for on Google Drive
Output
regionurl: location (URL) for download of regional mask file
TMI.section — Method
function section
View latitude-depth slice of fieldArguments
c::Field, 3D tracer field plus meta datalon: longitude of section
Output
csection: 2d slice of field
TMI.setboundarycondition! — Method
function setboundarycondition!(d::Field,b::BoundaryCondition)
apply boundary condition to the equation constraintsArguments
d::Field, equation constraints (i.e., right hand side)b::BoundaryCondition
TMI.setboundarycondition! — Method
function setboundarycondition!(d::Field{T},b::NamedTuple{<:Any, NTuple{N,BoundaryCondition{T}}}) where {N, T <: Real}
set all boundary conditions in a Named TupleTMI.setsource! — Method
function setsource!(d::Field,q::Field,r::Number)
apply interior source q to the equation constraints dArguments
d::Field, equation constraints (i.e., right hand side)q::Field, interior sourcer::Number, default = 1.0, stoichiometric ratio
TMI.shiftloc — Method
function shiftloc(loc)
sometimes loc longitudes are outside of grid due to different conventions
assumption: 360° shift is enough to get back on gridTMI.southindex — Method
function southindex(I)
Get the vector-index on the southern open boundaryTMI.sparsedatamap_optim — Method
function sparsedatamap(u₀::Vector{T},Alu,b::BoundaryCondition{T},u::BoundaryCondition{T},y::Vector{T},W⁻,wis,locs,Q⁻,γ::Grid;iterations=10) where T <: Real
Find the distribution of a tracer given:
(a) the pathways described by A or its LU decomposition Alu,
(b) first-guess boundary conditions and interior sources given by d₀,
(c) perturbations to the surface boundary condition u₀
that best fits observations, y,
according to the cost function,
J = (ỹ - y)ᵀ W⁻¹ (ỹ - y)
subject to Aỹ = d₀ + Γ u₀.
W⁻ is a (sparse) weighting matrix.
See Supplementary Section 2, Gebbie & Huybers 2011.Arguments
u₀:Alu:b: first guess of boundary conditions and interior sourcesy: observations on 3D gridW⁻: weighting matrix best chosen as inverse error covariance matrixfg!: compute cost function and gradient in placeγ: grid
TMI.standardize_fieldnames — Method
function mat2ncfield
Rename MATLAB variables to NetCDF variablesTMI.steadyclimatology_optim — Method
function steadyclimatology_optim(u₀,fg!,iterations) Find the distribution of a tracer given: (a) the pathways described by A or its LU decomposition Alu, (b) first-guess boundary conditions and interior sources given by d₀, (c) perturbations to the surface boundary condition u₀ that best fits observations, y, according to the cost function, J = (ỹ - y)ᵀ W⁻¹ (ỹ - y) subject to Aỹ = d₀ + Γ u₀. W⁻ is a (sparse) weighting matrix. See Supplementary Section 2, Gebbie & Huybers 2011.
Arguments
u₀:fg!: compute cost function and gradient in placeiterations: number of optimization iterations
TMI.steadyinversion — Method
function steadyinversion(Alu,b;q=nothing,r=1.0)
invert for a steady-state tracer distributionArguments
Alu: LU decomposition of water-mass matrixb: boundary condition, assumed to be surface boundary conditionγ::Grid
Optional Arguments
q: interior sources/sinks of phosphater: stochiometric ratio of tracer:phosphate
Output
c::Field, steady-state tracer distribution
TMI.step_cartesian — Method
function step_cartesian(I, Δ, γ)
Arguments
I::CartesianIndex: starting pointΔ::CartesianIndex: stepγ::Grid: TMI-defined grid
Output
Istep::CartesianIndex: new locationinbounds::Bool: inside the domain bounds?
TMI.surfacecontrol2field! — Method
function surfacecontrol2field!(c,u,γ)
Add surface control vector to existing 3D fieldArguments
c:: state field, 3d tracer field with NaN on dry points, modified by functionusfc:: surface control vectorwet::BitArray mask of ocean points
TMI.surfacecontrol2field! — Method
function surfacecontrol2field!(c,u,γ)
Add surface control vector to tracer vectorArguments
c:: state field, 3d tracer field with NaN on dry points, modified by functionu:: surface control vectorwet::BitArray mask of ocean points
TMI.surfacecontrol2field — Method
function surfacecontrol2field(usfc,γ.wet)
turn surface control vector into 3D field with zeroes below surfaceArguments
usfc:: surface control vectorwet::BitArray mask of ocean points
Output
tracer3D:: 3d tracer field with NaN on dry points
TMI.surfaceindex — Method
function surfaceindex(I)
Get the vector-index where depth level == 1 and it is ocean.TMI.surfaceorigin — Method
function surfaceorigin(TMIversion,loc)
Find the surface origin of water for some interior box
This is equivalent to solving a sensitivity problem:
The mass fraction at a location `loc` of interest is
`c[loc] = δᵀ c`, where `δ` samples the location of the global mass-fraction variable, c.
Then the sensitivity of `c[loc]` is: d(c[loc])/d(d) = A⁻ᵀ δ.
The derivative is solved using the constraint: Ac = d.
The sensitivity is exactly the mass fraction originating from each source.
This problem is mathematically similar to determining how the ocean is filled.Arguments
loc: location (lon,lat,depth) of location of interestAlu: LU decomposition of water-mass matrix Aγ: TMI grid
Output
origin: surface map of fraction of source water for a given location, log10 of effective depth, in terms of a BoundaryCondition
TMI.surfacepatch — Method
function surfacepatch
Make a surface boundary condition
with a rectangular patchArguments
lonbox: longitudes of box edgeslatbox: latitudes of box edgesγ: TMI.grid
Output
d: vector that describes surface patch
TMI.surfaceregion — Method
function surfaceregion(TMIversion::String,region::String,γ::Grid)::BoundaryCondition
Read an oceanographically-relevant surface region from NetCDF file. (Also could be read from mat file.)Return a BoundaryCondition
Version 1: operates on a 2D Float fieldTMI.surfaceregion — Method
function surfaceregion(TMIversion::String,region::String,γ::Grid)::BoundaryCondition
Read an oceanographically-relevant surface region from NetCDF file. (Also could be read from mat file.)
Return a BoundaryConditionTMI.synthetic_observations — Function
function synthetic_observations(TMIversion,variable,locs)
Synthetic observations that are a contaminated version of real observations
This version: observations with random (uniform) spatial samplingArguments
TMIversion::String: version of TMI water-mass/circulation modelvariable::String: variable name to use as templateN: number of observations
Output
y: contaminated observations on 3D gridW⁻: appropriate weighting (inverse covariance) matrix for these observations,ytrue: uncontaminated observations, 3D fieldlocs: 3-tuples of locations for observationswis: weighted indices for interpolation to locs sites
TMI.synthetic_observations — Method
function synthetic_observations(TMIversion,variable)
Synthetic observations that are a contaminated version of real observations
This version: gridded observationsArguments
TMIversion::String: version of TMI water-mass/circulation modelvariable::String: variable name to use as template
Output
y: contaminated observations on 3D gridW⁻: appropriate weighting (inverse covariance) matrix for these observations,θtrue: real observations, 3D field
TMI.tracerinit — Method
function tracerinit(wet,vec,I)
initialize tracer field on TMI grid
perhaps better to have a tracer struct and constructorArguments
wet:: BitArray mask of ocean pointsvec:: vector of values at wet pointsI:: Cartesian Index for vector
Output
field:: 3d tracer field with NaN on dry points
TMI.trackpathways — Method
function trackpathways(TMIversion,latbox,lonbox)
Track the pathways of a user-defined water mass.
Steps: (a) define the water mass by a rectangular surface patch dyed with passive tracer concentration of (b) propagate the dye with the matrix A, with the result being the fraction of water originating from the surface region.
See Section 2b of Gebbie & Huybers 2010, esp. eqs. (15)-(17).Arguments
TMIversion: version of TMI water-mass/circulation modellatbox: min and max latitude of boxlonbox: min and max longitude of boxγ: TMI grid
Output
c: fraction of water from surface source
TMI.unvec! — Method
function unvec!(u,uvec)
Undo the operations by vec(u)
Needs to update u because attributes of
u need to be known at runtime.TMI.vec2fld — Method
function vec2fld
Transfer a vector to a 3D field with accounting for ocean bathymetryArguments
vector: field in vector form (no land points)I: cartesian indices of ocean points
Output
field: field in 3d form including land points (NaN)
TMI.volumefilled — Method
function volumefilled(TMIversion)
Find the ocean volume that has originated from each surface box.
This is equivalent to solving a sensitivity problem:
The total volume is V = vᵀ c , where v is the volume of each box
and c is the fraction of volume from a given source which
satisfies the equation A c = d.
Next, dV/d(d) = A⁻ᵀ v, and dV/d(d) is exactly the volume originating from each source.
See Section 3 and Supplementary Section 4, Gebbie & Huybers 2011.Arguments
TMIversion: version of TMI water-mass/circulation modelAlu: LU decomposition of water-mass matrix Aγ: TMI.grid
Output
volume: log10 of global ocean volume filled by a surface region, exists at surface, therefore given BoundaryCondition type
TMI.watermassdistribution — Method
function watermassdistribution(TMIversion,latbox,lonbox)
Track the pathways of a user-defined water mass.
Steps: (a) define the water mass by an oceanographically-relevant surface patch dyed with passive tracer concentration of one
(b) propagate the dye with the matrix A, with the result being the fraction of water originating from the surface region.
See Section 2b of Gebbie & Huybers 2010, esp. eqs. (15)-(17).Arguments
TMIversion: version of TMI water-mass/circulation modelAlu: LU decomposition of water-mass matrix Aregion: name of pre-defined surface regionγ: TMI grid
Output
g: water-mass fraction
TMI.watermassmatrix — Method
function watermassmatrix(file)
Read and assemble the water-mass matrix.Arguments
file: TMI NetCDF or MATLAB file name
Output
A: water-mass matrix
TMI.watermassmatrix — Method
update water-mass matrix to agree with new boundaries in γ
TMI.watermassmatrix — Method
function watermassmatrix(m::Union{NamedTuple,Vector}, γ::Grid)
Produce water-mass matrix from mass fractions and grid.
Arguments
m::NamedTuple: collection ofMassFractionsγ::TMI.Grid
Output
A: sparse water-mass matrix
TMI.westindex — Method
function westindex(I)
Get the vector index on the western open boundaryTMI.wetlocation — Method
function wetlocation(γ)
Get (lon,lat,depth) tuples of wet locations.
Allow a location to be wet if at least one out of 8 nearby gridpoints is wet.
Certainly "wet" gridpoints could be defined more strictly.Arguments
γ: TMI.grid
Output
loc: lon,lat,depth
TMI.zeroeastboundary — Function
zeroeastboundary(γ,name=:none,longname="unknown",units="unknown") = zeros(1,eastindex(γ),γ,name,longname,units)::BoundaryCondition
TMI.zeronorthboundary — Function
zeronorthboundary(γ,name=:none,longname="unknown",units="unknown") = zeros(2,northindex(γ),γ,name,longname,units)::BoundaryCondition
TMI.zerosouthboundary — Function
zerosouthboundary(γ,name=:none,longname="unknown",units="unknown") = zeros(2,southindex(γ),γ,name,longname,units)::BoundaryCondition
TMI.zerosurfaceboundary — Function
zerosurfaceboundary(γ::Grid,name=:none,longname="unknown",units="unknown") = zeros(3,surfaceindex(γ),γ,name,longname,units)::BoundaryCondition
TMI.zerowestboundary — Function
zerowestboundary(γ,name=:none,longname="unknown",units="unknown") = zeros(1,westindex(γ),γ,name,longname,units)::BoundaryCondition