TMI
Documentation for TMI.
TMI.BoundaryCondition
TMI.Field
TMI.Grid
TMI.Grid
TMI.Grid
TMI.MassFraction
TMI.Source
Base.:\
Base.length
Base.one
Base.one
Base.ones
Base.ones
Base.ones
Base.propertynames
Base.sum
Base.vec
Base.vec
Base.zero
Base.zeros
Base.zeros
Base.zeros
Base.zeros
LinearAlgebra.dot
Statistics.mean
TMI.add!
TMI.adjustboundarycondition
TMI.adjustboundarycondition!
TMI.adjustboundarycondition!
TMI.axislabels
TMI.boundaryconditionatts
TMI.boundarymatrix
TMI.boundarymatrix
TMI.boundarymatrix2nc
TMI.boundarymatrix2nc
TMI.cartesianindex
TMI.cartesianindex
TMI.cartesianindex
TMI.cellarea
TMI.cellarea
TMI.cellvolume
TMI.cellvolume
TMI.checkgrid!
TMI.circulationmatrix
TMI.circulationmatrix
TMI.circulationmatrix
TMI.circulationmatrix2nc
TMI.circulationmatrix2nc
TMI.config2nc
TMI.config2nc
TMI.config_from_mat
TMI.config_from_mat
TMI.config_from_nc
TMI.config_from_nc
TMI.control2state
TMI.control2state
TMI.costfunction_gridded_model
TMI.costfunction_gridded_model!
TMI.costfunction_point_obs
TMI.costfunction_point_obs
TMI.costfunction_point_obs!
TMI.costfunction_point_obs!
TMI.depthindex
TMI.depthindex
TMI.distancematrix
TMI.download_matfile
TMI.download_ncfile
TMI.download_regionfile
TMI.eastindex
TMI.eastindex
TMI.fieldsatts
TMI.fieldsatts
TMI.gadjustboundarycondition!
TMI.gadjustboundarycondition!
TMI.gaussiandistancematrix
TMI.getboundarycondition
TMI.getboundarycondition
TMI.getboundarycondition
TMI.gobserve
TMI.gobserve
TMI.grid2nc
TMI.grid2nc
TMI.griddicts
TMI.griddicts
TMI.gridsize
TMI.gsetboundarycondition
TMI.gsetboundarycondition
TMI.gsetboundarycondition
TMI.gsetsource!
TMI.gsteadyinversion
TMI.gsteadyinversion
TMI.horizontaldistance
TMI.horizontaldistance
TMI.interiormask
TMI.interpindex
TMI.interpindex
TMI.interpweights
TMI.interpweights
TMI.latindex
TMI.latindex
TMI.linearindex
TMI.linearindex
TMI.local_solve
TMI.local_watermass_matrix
TMI.lonindex
TMI.lonindex
TMI.massfractions
TMI.mat2ncfield
TMI.matfields2nc
TMI.matfields2nc
TMI.matfields2nc_orig
TMI.matrix_zyx2xyz
TMI.matrix_zyx2xyz
TMI.matsource2nc
TMI.maturl
TMI.maturl
TMI.meanage
TMI.meanage
TMI.ncurl
TMI.ncurl
TMI.nearestneighbor
TMI.nearestneighbor
TMI.nearestneighbormask
TMI.nearestneighbormask
TMI.neighbor_indices
TMI.neighbors
TMI.neighbors
TMI.northindex
TMI.northindex
TMI.observe
TMI.observe
TMI.observe
TMI.optim2nc
TMI.optim2nc
TMI.preformedcarbon13
TMI.preformednitrate
TMI.preformednutrient
TMI.preformedoxygen
TMI.preformedphosphate
TMI.readfield
TMI.readtracer
TMI.regeneratednutrient
TMI.regions_mat2nc
TMI.regionurl
TMI.section
TMI.section
TMI.setboundarycondition!
TMI.setboundarycondition!
TMI.setboundarycondition!
TMI.setsource!
TMI.shiftloc
TMI.shiftloc
TMI.southindex
TMI.southindex
TMI.sparsedatamap_optim
TMI.steadyclimatology_optim
TMI.steadyinversion
TMI.steadyinversion
TMI.step_cartesian
TMI.surfacecontrol2field
TMI.surfacecontrol2field
TMI.surfacecontrol2field!
TMI.surfacecontrol2field!
TMI.surfacecontrol2field!
TMI.surfaceindex
TMI.surfaceindex
TMI.surfaceorigin
TMI.surfaceorigin
TMI.surfacepatch
TMI.surfacepatch
TMI.surfaceregion
TMI.surfaceregion
TMI.surfaceregion
TMI.synthetic_observations
TMI.synthetic_observations
TMI.synthetic_observations
TMI.tracerinit
TMI.tracerinit
TMI.trackpathways
TMI.trackpathways
TMI.unvec
TMI.unvec
TMI.unvec!
TMI.unvec!
TMI.updatelinearindex
TMI.updatelinearindex
TMI.vec2fld
TMI.volumefilled
TMI.volumefilled
TMI.watermassdistribution
TMI.watermassdistribution
TMI.watermassmatrix
TMI.watermassmatrix
TMI.watermassmatrix
TMI.westindex
TMI.westindex
TMI.wetlocation
TMI.wetlocation
TMI.write
TMI.write
TMI.Γ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::String
TMI.Grid
— Typestruct Grid
TMI grid with accounting for wet/dry points
Fields
axes::NTuple{N,Vector{A}}
: labels for axis such as lon, lat, depth with element typeA
wet::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 name
Arguments
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::String
maskname::String
lonname::String
latname::String
depthname::String
Output
γ::Grid
: TMI grid struct
TMI.MassFraction
— Typestruct MassFraction
store mass fractions in a Field-like array
fraction::Array{T,3}
γ::Grid
name::Symbol
longname::String
units::String
position::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 mask
Base.:\
— Method`function \(A,d::Field)::Field`
Define left division for Fields
Need two slashes to prevent invalid escape
Base.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 constructor
Arguments
γ
::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 ones
Base.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 method
Base.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 array
Arguments
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 constructor
Arguments
γ
::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 zeroes
Arguments
dim
:dimval
γ::Grid
name::Symbol
longname::String
units::String
Output
b::BoundaryCondition
LinearAlgebra.dot
— Method`function *(c::Field,d::Field)::Field`
Field by field multiplication is element-by-element.
Statistics.mean
— Methodfunction Statistics.mean(c::Field)
Take the volume-weighted mean of a `Field`
TMI.add!
— Method`function +(c::BoundaryCondition,d::BoundaryCondition)::BoundaryCondition`
Define addition for Fields
TMI.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 u
TMI.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 attributes
TMI.boundarymatrix
— Method function boundarymatrix(file,γ)
Read and assemble the boundary matrix from MATLAB.
Transfer to updated x,y,z version
Arguments
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 order
Arguments
wet
: BitArray logical mask for wet points
Output
I
: 3D Cartesian indices
TMI.cellarea
— MethodHorizontal area of grid cell
TMI.cellvolume
— Methodfunction cellvolume(γ)::Field
Volume of each grid cell.
TMI.checkgrid!
— Methodfunction checkgrid!(c,wet)
perform a check of file compatibility
with grid
TMI.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 MATLAB.
Transfer to updated x,y,z version
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.config2nc
— MethodSave TMI configuration to NetCDF format for non-proprietary access
TMI.config_from_mat
— MethodConfigure TMI environment from original MATLAB output
TMI.config_from_nc
— Methodfunction config_from_nc(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.control2state
— Methodfunction control2state(tracer2D,γ)
turn 2D surface field into 3D field with zeroes below surface
Arguments
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.jl
Arguments
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 index
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_matfile
— Methodfunction download_matfile(TMIversion::String)
Download MATLAB file for given TMI version
Arguments
TMIversion::String
Output
TMIfile::String
: TMI file name
Side-effect
- download TMI input file if necessary
TMI.download_ncfile
— Methodfunction download_ncfile(TMIversion::String)
Download NetCDF file for given TMI version
Arguments
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 boundary
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 type
TMI.gaussiandistancematrix
— Methodfunction gaussiandistancematrix(γ,σ,L)
uses distance matrix plus a lengthscale `L` (km)
and a size of the diagonal `σ`
returns values with inverse gaussian weighting
TMI.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 dimensiondim
that 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 operator
TMI.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 constraints
Arguments
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 constraints
Arguments
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 distribution
Arguments
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 index
TMI.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_solve
— Methodfunction local_solve(c::NamedTuple, w::NamedTuple)
Given tracers, solve for mass fractions using a repeated local algorithm.
local_solve!
is the workhorse for this algorithm and specifies a default inverse tapering parameter of α=100_000
.
Arguments
c::NamedTuple
:Field
tracers (observations or model output)w::NamedTuple
: scale size of tracers (for weighting observational fits)
Output
m̃::NamedTuple
:MassFraction
in a NamedTuple collection
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 index
TMI.massfractions
— Methodfunction massfractions(c::NamedTuple, w::NamedTuple; alg = :local)
Create NamedTuple of mass fractions from observations c
Doesn't produce a MassFraction
struct and thus is named in lower case.
Arguments
c::NamedTuple
: input observationsw::NamedTuple
: scale size of observations (used if obs not fit exactly)alg=:local
: default algorithm is:local
Output
m::NamedTuple
: collection of mass fractions
TMI.mat2ncfield
— Methodfunction mat2ncfield
Rename MATLAB variables to NetCDF variables
TMI.matfields2nc
— MethodRead 3D fields from mat file and save to NetCDF file.
TMI.matfields2nc_orig
— MethodRead 3D fields from mat file and save to NetCDF file.
TMI.matrix_zyx2xyz
— Method function matrix_zyx2xyz(TMIfile,Azyx,γ)
Transfer zyx format water-mass matrix A to xyz format
Arguments
Azyx
: water-mass matrix in zyx formatγ
: TMI grid
Output
Axyz
: water-mass matrix in xyz format
TMI.matsource2nc
— MethodRead 3D source field from mat file and save to NetCDF file.
TMI.maturl
— Methodfunction maturl(TMIversion)
Find *mat file here.
placeholder function to give location (URL) of 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.meanage
— Methodfunction meanage(TMIversion,Alu,γ)
Mean or ideal age
Arguments
TMIversion
: version of TMI water-mass/circulation modelAlu
: LU decomposition of water-mass matrix Aγ
: TMI grid
Output
a
: mean age [yr]
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 neighbors
Arguments
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 elsewhere
Arguments
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 boundary
TMI.observe
— Methodfunction observe
Take a observation at location given by weights wis
TMI.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) nutrient
Arguments
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 correct
Arguments
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 xyz
TMI.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) nutrient
Arguments
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 field
Arguments
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 constraints
Arguments
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 Tuple
TMI.setsource!
— Methodfunction setsource!(d::Field,q::Field,r::Number)
apply interior source q to the equation constraints d
Arguments
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 grid
TMI.southindex
— Methodfunction southindex(I)
Get the vector-index on the southern open boundary
TMI.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.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 distribution
Arguments
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 field
Arguments
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 vector
Arguments
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 surface
Arguments
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 patch
Arguments
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 field
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
TMI.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 sampling
Arguments
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 observations
Arguments
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 constructor
Arguments
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.updatelinearindex
— Methodfunction updatelinearindex(izyx,Izyx,R)
Linear index translated from z,y,x to x,y,z accounting
get Izyx Cartesian index stored from legacy MATLAB code
Arguments
izyx
: index of interest in z,y,x accountingIzyx
: wet Cartesian Index for z,y,xR
: Linear indices for x,y,z
Output
ixyz
: index of interest in x,y,z accounting
TMI.vec2fld
— Methodfunction vec2fld
Transfer a vector to a 3D field with accounting for ocean bathymetry
Arguments
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
— Methodfunction watermassmatrix(m::Union{NamedTuple,Vector}, γ::Grid)
Produce water-mass matrix from mass fractions and grid.
Arguments
m::NamedTuple
: collection ofMassFraction
sγ::TMI.Grid
Output
A
: sparse water-mass matrix
TMI.westindex
— Methodfunction westindex(I)
Get the vector index on the western open boundary
TMI.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 correct
Arguments
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 correct
Arguments
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!