TMI
Documentation for TMI.
TMI.BoundaryConditionTMI.FieldTMI.GridTMI.GridTMI.GridTMI.MassFractionTMI.SourceBase.:\Base.lengthBase.oneBase.oneBase.onesBase.onesBase.onesBase.propertynamesBase.sumBase.vecBase.vecBase.zeroBase.zerosBase.zerosBase.zerosBase.zerosLinearAlgebra.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_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.gadjustboundarycondition!TMI.gadjustboundarycondition!TMI.gaussiandistancematrixTMI.getboundaryconditionTMI.getboundaryconditionTMI.getboundaryconditionTMI.gobserveTMI.gobserveTMI.grid2ncTMI.grid2ncTMI.griddictsTMI.griddictsTMI.gridsizeTMI.gsetboundaryconditionTMI.gsetboundaryconditionTMI.gsetboundaryconditionTMI.gsetsource!TMI.gsteadyinversionTMI.gsteadyinversionTMI.horizontaldistanceTMI.horizontaldistanceTMI.interiormaskTMI.interpindexTMI.interpindexTMI.interpweightsTMI.interpweightsTMI.latindexTMI.latindexTMI.linearindexTMI.linearindexTMI.local_watermass_matrixTMI.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.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.Γsfc!
TMI.Field — Typestruct Field
This structure permits the grid to be
automatically passed to functions with
the tracer field.
This structure assumes the Tracer type to be
three-dimensional.
tracer::AbstractArray{T,N}
γ::Grid{A,N}
name::Symbol
longname::String
units::StringTMI.Grid — Typestruct 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 — Methodfunction Grid(TMIfile)
Construct the Grid given a file nameArguments
TMIfile::String: NetCDF file name for TMI version
Output
γ::Grid: TMI grid struct
TMI.Grid — Methodfunction 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 — Typestruct MassFraction
store mass fractions in a Field-like array
fraction::Array{T,3}γ::Gridname::Symbollongname::Stringunits::Stringposition::CartesianIndex{3}
TMI.Source — Typestruct Source
This structure describes Sources, which are
similar to Fields, but they may be
1) non-negative
2) have only interior maskBase.:\ — Method`function \(A,d::Field)::Field`
Define left division for Fields
Need two slashes to prevent invalid escapeBase.length — MethodBase.length(c::Union{Field,Source,BoundaryCondition}) = length(c.tracer[wet(c)])
Extend `length` to give the number of wet (i.e., ocean) gridcells.Base.one — Methodfunction oneunit, help for gridded Interpolations
Base.one — Methodfunction oneunit, help for gridded Interpolations
Base.ones — Functionfunction ones(γ::Grid,name=:none,longname="unknown",units="unknown")::Field
initialize tracer field of ones on TMI grid
using a Field struct and constructorArguments
γ::TMI.Grid
Output
d::Field, 3d tracer field with NaN on dry points
Base.ones — Methodfunction ones(dim::Int64,dimval::Int64,γ::Grid)::BoundaryCondition
Initialize boundary condition with onesBase.propertynames — MethodBase.propertynames(γ::Grid) = (I,R,fieldnames(typeof(x))...)
Do not store Cartesian and linear indices.
Compute them on demand.Base.sum — MethodSpecialize Base.sum(c::Field)
so that it doesn't use the slow iteration methodBase.vec — Methodfunction vec(u)
Turn a collection of controls into a vector
for use with Optim.jl.
An in-place version of this function would be handy.Base.zero — Methodzero(c::Field) = zeros(c.γ)Base.zeros — Functionfunction 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 — Methodfunction 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 — Methodfunction 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.add! — Method`function +(c::BoundaryCondition,d::BoundaryCondition)::BoundaryCondition`
Define addition for FieldsTMI.adjustboundarycondition! — Methodfunction 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 — Methodfunction adjustboundarycondition!(b::Union{BoundaryCondition,NamedTuple},u::Union{BoundaryCondition,NamedTuple})
adjust all boundary conditions b that are described in uTMI.axislabels — Methodfunction axislabels(file)
Read and assemble the grid properties.Arguments
file: TMI NetCDF file name
Output
grid: TMI grid coordinates
TMI.boundaryconditionatts — Methodfunction boundaryconditionatts(dim::Int64,dimval::Int64,γ::Grid)
Help initialize boundary condition by getting some attributesTMI.boundarymask — Method function boundarymask(b, γ::Grid)TMI.boundarymask — Methodfunction 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 — MethodSave boundary matrix for transient model to NetCDF file
TMI.cartesianindex — Methodfunction 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 — Methodfunction 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 — MethodHorizontal area of grid cellTMI.cellvolume — Methodfunction cellvolume(γ)::Field
Volume of each grid cell.TMI.checkgrid! — Methodfunction checkgrid!(c,wet)
perform a check of file compatibility
with gridTMI.circulationmatrix — Methodfunction 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 — Methodfunction 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 — MethodSave circulation matrix L to NetCDF file.
TMI.config — Methodfunction 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 — MethodSave TMI configuration to NetCDF format for non-proprietary access
TMI.control2state — Methodfunction 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! — Methodfunction 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 — Methodfunction 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_point_obs! — Methodfunction 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 — Methodfunction 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 — Methodfunction 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 — Methodfunction 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 — Methodfunction 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 — Methodfunction 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 — Methodfunction 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 — MethodAll variable names and attributes. Useful for writing NetCDF files.
TMI.gadjustboundarycondition! — Methodfunction 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.gaussiandistancematrix — Methodfunction gaussiandistancematrix(γ,σ,L)
uses distance matrix plus a lengthscale `L` (km)
and a size of the diagonal `σ`
returns values with inverse gaussian weightingTMI.getboundarycondition — Methodfunction 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 — MethodGet boundary condition by extracting from N-dimensional tracer and returning (N-1)-dimensional array
TMI.gobserve — Methodfunction 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 — MethodPut grid properties (Cartesian index) into NetCDF file
TMI.griddicts — MethodSave grid dictionaries of attributes for writing to NetCDF file
TMI.gridsize — Methodfunction gridsize(TMIversion)
Parse the TMIversion string for the grid size
Will break if the prefix contains underscores or 'x'
TMI.gsetboundarycondition — Methodfunction 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 — Methodfunction 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! — Methodfunction gsetsource!(gq::Field{T},gd::Field{T},r=1.0)
Adjoint to `setsource!`TMI.gsteadyinversion — Methodfunction 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 — Methodfunction horizontaldistance(loc,γ)Arguments
loc: 3-tuple of lon,lat,depth locationγ: TMI.grid
Output
hordist: horizontal distance to nearest tracer grid points
TMI.interiormask — Methodfunction interiormask(A,wet,nx,ny,nz)
TMI.interpindex — Methodfunction 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 — Methodfunction 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.latindex — Methodfunction latindex(I)
Get the j-index (latitude index) from the Cartesian indexTMI.linearindex — Methodfunction 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 — Methodfunction 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.lonindex — Methodfunction lonindex(I)
Get the i-index (lon index) from the Cartesian indexTMI.matfields2nc_orig — MethodRead 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 — Methodfunction 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 — Methodfunction 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.ncurl — Methodfunction ncurl(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
TMIversion: version of TMI water-mass/circulation model
Output
url: location (URL) for download
TMI.nearestneighbor — Functionfunction 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 — Functionfunction 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 — Functionfunction 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 — Methodfunction 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 — Methodfunction 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 — Methodfunction northindex(I)
Get the vector index on the northern open boundaryTMI.observe — Methodfunction observe
Take a observation at location given by weights wisTMI.observe — Methodfunction observe(c,loc,γ)
Extend the TMI.observe method to use locations rather than weighted interpolations.TMI.optim2nc — MethodSave optimization parameters to NetCDF file)
Future considerations: split into 2 functions
- read from mat
- save to nc
TMI.preformedcarbon13 — Methodpreformedcarbon13(TMIversion,Alu,γ) = preformednutrient("δ¹³C",TMIversion,Alu,γ)
TMI.preformednitrate — Methodpreformednitrate(TMIversion,Alu,γ) = preformednutrient("NO₃",TMIversion,Alu,γ)
TMI.preformednutrient — Methodfunction 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 — Methodpreformedoxygen(TMIversion,Alu,γ) = preformednutrient("O₂",TMIversion,Alu,γ)
TMI.preformedphosphate — Methodpreformedphosphate(TMIversion,Alu,γ) = preformednutrient("PO₄",TMIversion,Alu,γ)
TMI.readfield — Methodfunction 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 — Methodfunction 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 — Methodfunction 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 — Methodfunction regions2nc(TMIversion,γ)
Read vectors from mat file, translate to 3D, and save surface field to NetCDF file.
Consider deprecating this function.
TMI.regionurl — Methodfunction 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 — Methodfunction 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! — Methodfunction 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! — Methodfunction setboundarycondition!(d::Field{T},b::NamedTuple{<:Any, NTuple{N,BoundaryCondition{T}}}) where {N, T <: Real}
set all boundary conditions in a Named TupleTMI.setsource! — Methodfunction 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 — Methodfunction shiftloc(loc)
sometimes loc longitudes are outside of grid due to different conventions
assumption: 360° shift is enough to get back on gridTMI.southindex — Methodfunction southindex(I)
Get the vector-index on the southern open boundaryTMI.sparsedatamap_optim — Methodfunction 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 — Methodfunction mat2ncfield
Rename MATLAB variables to NetCDF variablesTMI.steadyclimatology_optim — Methodfunction 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 — Methodfunction 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 — Methodfunction 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! — Methodfunction 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! — Methodfunction 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 — Methodfunction 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 — Methodfunction surfaceindex(I)
Get the vector-index where depth level == 1 and it is ocean.TMI.surfaceorigin — Methodfunction 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 — Methodfunction 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 — Functionfunction 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 — Methodfunction 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 — Methodfunction 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 — Methodfunction 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! — Methodfunction unvec!(u,uvec)
Undo the operations by vec(u)
Needs to update u because attributes of
u need to be known at runtime.TMI.unvec — Methodfunction unvec(u,uvec)
Replace u with new u
Undo the operations by vec(u)
Needs to update u because attributes of
u need to be known at runtime.TMI.vec2fld — Methodfunction 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 — Methodfunction 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 — Methodfunction 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 — Methodfunction watermassmatrix(file)
Read and assemble the water-mass matrix.Arguments
file: TMI NetCDF or MATLAB file name
Output
A: water-mass matrix
TMI.watermassmatrix — Methodupdate water-mass matrix to agree with new boundaries in γ
TMI.watermassmatrix — Methodfunction 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 — Methodfunction westindex(I)
Get the vector index on the western open boundaryTMI.wetlocation — Methodfunction 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.write — Methodfunction writefield(file,field)
Write a Field to NetCDF.
Use NCDatasets so that Unicode is correctArguments
file: TMI NetCDF file namefield::Field: a TMI.Field struct
Output
- none
Side-effect
- write to
file
TMI.write — Methodfunction write(file,b)
Write a BoundaryCondition to NetCDF.
Use NCDatasets so that Unicode is correctArguments
file: TMI NetCDF file nameb::BoundaryCondition: a TMI.BoundaryCondition struct
Output
- none
Side-effect
- write to
file
TMI.Γsfc! — Functionfunction Γsfc!
Γsfc! anonymously calls surfacecontrol2field!