API
MAGEMin_C.ALWAYS_ACTIVE_PP Constant
ALWAYS_ACTIVE_PP
Pure-phase names of the buffer/activity indicators (oxygen-fugacity buffers and
fixed-activity phases). At most one of these can ever be active in a given calculation,
governed solely by the `buffer="..."` keyword of `Initialize_MAGEMin` (C-side:
`pp_min_function.c` force-deactivates every buffer-type pure phase whose name doesn't
match `gv.buffer`, regardless of any phase-selection list). `select_phases` therefore
never deactivates these names, so callers never need to list them explicitly.MAGEMin_C.DEW_DB_CODE Constant
DEW_DB_CODE
Maps a "tc" research-group database short name to its numeric `EM_database`
code (the convention `gbase_data.dtb`/`W_data.dtb` use, documented on
[`gbase_data`](@ref)). Only the databases that carry a DEW aqueous phase are
listed - DEW doesn't exist in the "sb"/"gh"/"br" research groups.MAGEMin_C.EM_COMP_BASIS Constant
EM_COMP_BASIS
Common oxide basis the generated end-member compositions are expressed in: the "all"
database's 14 oxides plus `Fe`. The extra column exists for `sb24`, which recomputes
FeO + O into metallic Fe + O and so carries an oxide the "all" database does not have;
every other database uses a subset of the first 14 and leaves `Fe` at zero.MAGEMin_C.MAGEMIN_DATABASES Constant
MAGEMIN_DATABASES
Registry of every thermodynamic database the library implements - the single place
where a database acronym, its research group, its `gv.EM_database` code, its
human-readable name and its dataset options are written down.
Everything else about a database (oxide list, solution- and pure-phase lists,
end-member / compositional-variable / site-fraction names) is *not* listed here:
it is harvested straight from the C library by `gen/generate_db_infos.jl` into
`julia/db_infos_generated.jl`, and `test/test_db_infos.jl` fails the build if the
two ever disagree.
The row order is significant: `db_infos_generated.jl` is emitted in this order.MAGEMin_C.SOLVUS_FAMILY Constant
SOLVUS_FAMILY
For each database and solution phase that straddles a solvus, every mineral name
[`get_mineral_name`](@ref) can return for it, including the parent name where that is
still reachable.
This is the declared counterpart of `get_mineral_name`'s branches: the function picks
*which* name applies at a given composition, this table states which names are
*possible*. Code that needs the whole family up front - building a phase list, or
matching a phase along a path where `name_solvus=true` has already renamed it - reads
this instead of keeping its own copy.
Keys are `(database, solution phase)`, the phase spelled as that database spells it, so
the "all" database uses citation-tagged names. Only pairs the database actually has are
listed. `test/test_db_infos.jl` sweeps `get_mineral_name` over random compositional
variables and fails if it ever returns a name this table does not list.MAGEMin_C.AMR_data Type
AMR_data
Mutable structure holding the state of an Adaptive Mesh Refinement (AMR) grid.
Fields
------
cells : Vector{Vector{Int64}}
Current quadrilateral cells, each defined by 4 point indices (counter-clockwise).
ncells : Vector{Vector{Int64}}
Newly generated cells from the last refinement step.
points : Vector{Vector{Float64}}
All grid point coordinates [X, Y].
npoints : Vector{Vector{Float64}}
Newly generated point coordinates from the last refinement step.
npoints_ig : Vector{Tuple}
Parent point index tuples for each new point (used for initial guess interpolation).
hash_map : Dict{Vector{Float64}, Int}
Map from point coordinates to their index, used to avoid duplicate points.
bnd_cells : Vector{Tuple}
Boundary information for kept cells: tuples of (cell_index, midpoint_indices...).
split_cell_list : Vector{Int64}
Indices of cells to be split in the next refinement pass.
keep_cell_list : Vector{Int64}
Indices of cells to be kept unchanged in the next refinement pass.
Xrange : Vector{Float64}
X-axis bounds of the domain [Xmin, Xmax].
Yrange : Vector{Float64}
Y-axis bounds of the domain [Ymin, Ymax].MAGEMin_C.MAGEMin_Data Type
MAGEMin_Data{TypeGV, TypeZB, TypeDB, TypeSplxData}
Mutable structure holding the MAGEMin databases and required structures for every thread.
Fields
------
db : String
Database name.
gv : TypeGV
Global variables (one per thread).
z_b : TypeZB
Bulk info structures (one per thread).
DB : TypeDB
Database structures (one per thread).
splx_data : TypeSplxData
Simplex data structures (one per thread).MAGEMin_C.SaturationConfig Type
SaturationConfig
Configuration struct for saturation models used in `TE_prediction` and `solve_with_saturation`.
All fields default to `"none"` (disabled).
Fields
------
Zr : String — zirconium saturation model. Options: "none", "CB", "WH", "B".
S : String — sulfur saturation model. Options: "none", "Liu07", "Oneill21", "<N>ppm".
P2O5 : String — phosphate saturation model. Options: "none", "Klein26", "HWBea92", "Tollari06".
CO2 : String — CO₂ saturation model. Options: "none", "SY26".
Mnz : String — monazite (ΣLREE) saturation model. Options: "none", "Stepanov12", "Montel93", "Maimaiti19".MAGEMin_C.W_data Type
W_data{T, I}
Mutable structure holding overriding Margules (Ws) parameters.
Database mapping is independent per research group (`gv.research_group`):
for "tc", 0 = "mp", 1 = "mb", 11 = "mbe", 2 = "ig", 22 = "igd", 3 = "igad", 4 = "um", 5 = "ume", 6 = "mtl", 7 = "mpe", 8 = "all";
for "sb", 0 = "sb11", 1 = "sb21", 2 = "sb24";
for "br", 0 = "po".
Fields
------
dtb : I
Database identifier.
ss_ids : I
Solution phase identifier.
n_Ws : I
Number of Margules parameters.
Ws : Matrix{T}
Margules parameters matrix (S, T, P × n_Ws).MAGEMin_C.custom_KDs_database Type
custom_KDs_database
Structure holding a trace element partitioning coefficient (KD) database.
Fields
------
infos : String
Description or citation for the database.
element_name : Vector{String}
Names of the trace elements.
phase_name : Vector{String}
Names of the mineral phases for which KDs are defined.
KDs_expr : Matrix{Function}
Matrix of compiled KD functions (phases × elements). Each function takes a `gmin_struct` as input and returns a Float64.MAGEMin_C.db_infos Type
db_infos
Mutable structure holding general information about the thermodynamic database.
Fields
------
db_name : String
Database short name.
db_info : String
Database description.
db_dataset : Int64
Dataset identifier.
dataset_opt : Union{Nothing, Int64, NTuple{5,Int64}, NTuple{4,Int64}}
Available dataset options.
data_ss : Array{ss_infos}
Solution phase information array.
ss_name : Array{String}
Solution phase names.
data_pp : Array{String}
Pure phase names.MAGEMin_C.db_registry Type
db_registry
One row of [`MAGEMIN_DATABASES`], the single hand-maintained description of a
MAGEMin thermodynamic database.
Fields
------
db_name : String
Database acronym, as passed to `Initialize_MAGEMin`/`init_MAGEMin` and to the
CLI `--db` flag (e.g. "mp", "ig", "sb21").
research_group : String
Research group the database belongs to, as expected by `gv.research_group`:
"tc" (THERMOCALC), "sb" (Stixrude & Lithgow-Bertelloni), "gh" (Ghiorso/MELTS)
or "br" (Berman).
EM_database : Int64
Numeric database code written into `gv.EM_database`. Unique within a research
group only - the same code means different databases in different groups.
db_info : String
Human-readable database name and reference, used by `print_phase_info` and
written into the metadata header of every CSV export.
db_dataset : Int64
End-member dataset the library falls back to when none is requested
(`gv.EM_dataset == -1`). `-1` where the research group has no dataset choice.
dataset_opt : NTuple{5,Int64}
End-member datasets that may be requested for this database.MAGEMin_C.gbase_data Type
gbase_data{T, I}
Mutable structure holding additive overrides ("shifts") for the reference
Gibbs energy (`gbase`) of individual endmembers of a solution phase.
Unlike `W_data` (which *replaces* the Margules parameters), `gbase_data`
is applied as an *additive delta* on top of the endmember `gbase` value
already computed by the thermodynamic database at the current (P,T):
`gbase[em_id] += dG[k,1] + dG[k,2]*T + dG[k,3]*P`. Only the endmembers
listed in `em_ids` are touched - every other endmember of the phase keeps
its default, unmodified value.
Database mapping is independent per research group (`gv.research_group`):
for "tc", 0 = "mp", 1 = "mb", 11 = "mbe", 2 = "ig", 22 = "igd", 3 = "igad", 4 = "um", 5 = "ume", 6 = "mtl", 7 = "mpe", 8 = "all";
for "sb", 0 = "sb11", 1 = "sb21", 2 = "sb24";
for "br", 0 = "po".
Fields
------
dtb : I
Database identifier.
ss_ids : I
Solution phase identifier.
n_Gs : I
Number of endmembers being overridden (must equal `length(em_ids)` and
`size(dG,1)`).
em_ids : Vector{I}
1-based indices (within the solution phase, i.e. into `1:n_em`) of the
endmembers being overridden.
dG : Matrix{T}
Additive shift coefficients (`length(em_ids)` × 3), columns = [constant, T-coeff, P-coeff].MAGEMin_C.gmin_struct Type
gmin_struct{T, I}
Structure that holds the result of the pointwise Gibbs energy minimization.
Fields
------
MAGEMin_ver : String
MAGEMin version string.
dataset : String
Dataset name.
database : String
Database name.
buffer : String
Buffer type.
buffer_n : T
Buffer value.
G_system : T
Gibbs free energy of the system.
Gamma : Vector{T}
Chemical potentials of oxides.
P_kbar : T
Pressure [kbar].
T_C : T
Temperature [°C].
X : Vector{T}
Compositional variable(s).
M_sys : T
Molar mass of the system.
bulk : Vector{T}
Bulk rock composition [mol].
bulk_M : Vector{T}
Bulk melt composition [mol].
bulk_S : Vector{T}
Bulk solid composition [mol].
bulk_F : Vector{T}
Bulk fluid composition [mol].
bulk_wt : Vector{T}
Bulk rock composition [wt].
bulk_M_wt : Vector{T}
Bulk melt composition [wt].
bulk_S_wt : Vector{T}
Bulk solid composition [wt].
bulk_F_wt : Vector{T}
Bulk fluid composition [wt].
frac_M : T
Melt fraction [mol].
frac_S : T
Solid fraction [mol].
frac_F : T
Fluid fraction [mol].
frac_M_wt : T
Melt fraction [wt].
frac_S_wt : T
Solid fraction [wt].
frac_F_wt : T
Fluid fraction [wt].
frac_M_vol : T
Melt fraction [vol].
frac_S_vol : T
Solid fraction [vol].
frac_F_vol : T
Fluid fraction [vol].
entropy_S : T
Entropy of solid [J/K].
entropy_M : T
Entropy of melt [J/K].
entropy_F : T
Entropy of fluid [J/K].
alpha : Vector{T}
Thermal expansivity.
V : T
Volume [J/bar].
V_cm3 : T
Volume [cm³].
s_cp : Vector{T}
Heat capacity.
rho : T
System density [kg/m³].
rho_M : T
Melt density [kg/m³].
rho_S : T
Solid density [kg/m³].
rho_F : T
Fluid density [kg/m³].
eta_M : T
Melt viscosity [Pa·s].
fO2 : T
Oxygen fugacity.
dQFM : T
Delta QFM buffer.
aH2O : T
Activity of H2O.
aSiO2 : T
Activity of SiO2.
aTiO2 : T
Activity of TiO2.
aAl2O3 : T
Activity of Al2O3.
aMgO : T
Activity of MgO.
aFeO : T
Activity of FeO.
n_PP : Int64
Number of pure phases.
n_SS : Int64
Number of solution phases.
n_mSS : Int64
Number of metastable solution phases.
ph_frac : Vector{T}
Phase fractions [mol].
ph_frac_wt : Vector{T}
Phase fractions [wt].
ph_frac_1at : Vector{T}
Phase fractions [mol, 1 atom basis].
ph_frac_vol : Vector{T}
Phase fractions [vol].
ph_type : Vector{I}
Type of phase (SS or PP).
ph_id : Vector{I}
Phase identifier.
ph_id_db : Vector{I}
Phase identifier in database.
ph : Vector{String}
Phase names.
sol_name : Vector{String}
Solution phase names.
SS_syms : Dict{Symbol, Int64}
Symbol-to-index mapping for solution phases.
PP_syms : Dict{Symbol, Int64}
Symbol-to-index mapping for pure phases.
PH_vec : Dict{Symbol, Union{LibMAGEMin.SS_data, LibMAGEMin.PP_data}}
Symbol-to-data mapping for stable phases (solution or pure); use `haskey(PH_vec, sym)` to check if a phase is stable before indexing.
SS_vec : Vector{LibMAGEMin.SS_data}
Solution phase data.
mSS_vec : Vector{LibMAGEMin.mSS_data}
Metastable solution phase data.
PP_vec : Vector{LibMAGEMin.PP_data}
Pure phase data.
oxides : Vector{String}
Oxide names.
elements : Vector{String}
Element names.
Vp : T
P-wave velocity [km/s].
Vs : T
S-wave velocity [km/s].
Vp_S : T
P-wave velocity of solid aggregate [km/s].
Vs_S : T
S-wave velocity of solid aggregate [km/s].
bulkMod : T
Elastic bulk modulus [GPa].
shearMod : T
Elastic shear modulus [GPa].
bulkModulus_M : T
Bulk modulus of melt [GPa].
bulkModulus_S : T
Bulk modulus of solid [GPa].
shearModulus_S : T
Shear modulus of solid [GPa].
Vp_cor : T
Seismic-corrected P-wave velocity of solid aggregate [km/s] (melt + anelastic corrections; NaN if `seismic_cor=false`).
Vs_cor : T
Seismic-corrected S-wave velocity of solid aggregate [km/s] (melt + anelastic corrections; NaN if `seismic_cor=false`).
entropy : Vector{T}
Entropy [J/K].
enthalpy : Vector{T}
Enthalpy [J].
iter : I
Number of iterations required.
bulk_res_norm : T
Bulk residual norm.
time_ms : T
Computational time [ms].
status : I
Status of calculations (0 = converged, 5 = not converged).MAGEMin_C.light_gmin_struct Type
light_gmin_struct{T, I, S}
Lightweight structure holding a reduced set of MAGEMin minimization outputs (Float32/Int8 types) for memory-efficient storage.
Fields
------
P_kbar : T
Pressure [kbar].
T_C : T
Temperature [°C].
ph_frac_wt : Vector{T}
Phase fractions [wt].
ph_name : Vector{S}
Phase names.
frac_S_wt : T
Solid fraction [wt].
frac_F_wt : T
Fluid fraction [wt].
frac_M_wt : T
Melt fraction [wt].
bulk_S_wt : Vector{T}
Bulk solid composition [wt].
bulk_F_wt : Vector{T}
Bulk fluid composition [wt].
bulk_M_wt : Vector{T}
Bulk melt composition [wt].
rho_S : T
Solid density [kg/m³].
rho_F : T
Fluid density [kg/m³].
rho_M : T
Melt density [kg/m³].
eta_M : T
Melt viscosity [Pa·s].
s_cp : Vector{T}
Heat capacity.MAGEMin_C.light_gmin_struct_ig Type
light_gmin_struct_ig{T, I, S}
Lightweight structure holding a reduced set of MAGEMin minimization outputs for igneous databases (Float32/Int8 types). Extends `light_gmin_struct` with volumetric fractions, metastable solution phase data, and convergence information.
Fields
------
P_kbar : T
Pressure [kbar].
T_C : T
Temperature [°C].
ph_frac_wt : Vector{T}
Phase fractions [wt].
ph_name : Vector{S}
Phase names.
frac_S_wt : T
Solid fraction [wt].
frac_F_wt : T
Fluid fraction [wt].
frac_M_wt : T
Melt fraction [wt].
frac_S_vol : T
Solid fraction [vol].
frac_F_vol : T
Fluid fraction [vol].
frac_M_vol : T
Melt fraction [vol].
bulk_S_wt : Vector{T}
Bulk solid composition [wt].
bulk_F_wt : Vector{T}
Bulk fluid composition [wt].
bulk_M_wt : Vector{T}
Bulk melt composition [wt].
rho_S : T
Solid density [kg/m³].
rho_F : T
Fluid density [kg/m³].
rho_M : T
Melt density [kg/m³].
eta_M : T
Melt viscosity [Pa·s].
s_cp : Vector{T}
Heat capacity.
mSS_vec : Vector{LibMAGEMin.mSS_data}
Metastable solution phase data.
bulk_res_norm : T
Bulk residual norm.
status : I
Status of calculations (0 = converged, 5 = not converged).MAGEMin_C.out_tepm Type
out_tepm
Structure holding the output of the trace element (TE) partitioning routine.
Fields
------
elements : Vector{String}
Names of the trace elements.
C0 : Vector{Float64}
Initial bulk trace element composition [ppm].
Cliq : Vector{Float64}
Trace element concentrations in the melt phase [ppm].
Csol : Vector{Float64}
Trace element concentrations in the bulk solid [ppm].
Cmin : Matrix{Float64}
Trace element concentrations in each individual mineral phase [ppm] (phases × elements).
ph_TE : Vector{String}
Names of the phases included in the partitioning calculation.
ph_wt_norm : Vector{Float64}
Normalized weight fractions of the solid phases.
liq_wt_norm : Float64
Normalized weight fraction of the melt.
bulk_D : Float64
Bulk partition coefficient.
bulk_cor_wt : Vector{Float64}
Corrected bulk oxide weight fractions (accounting for saturation phases).
bulk_cor_mol : Vector{Float64}
Corrected bulk oxide molar fractions.
Sat_Zr_liq : Float64
Zirconium saturation concentration in the melt [ppm] (NaN if not computed).
zrc_wt : Float64
Weight fraction of zircon precipitated (NaN if not computed).
Sat_S_liq : Float64
Sulfur saturation concentration in the melt [ppm] (NaN if not computed).
sulf_wt : Float64
Weight fraction of sulfide precipitated (NaN if not computed).
Sat_P2O5_liq : Float64
P₂O₅ saturation concentration in the melt [ppm] (NaN if not computed).
fapt_wt : Float64
Weight fraction of fluorapatite precipitated (NaN if not computed).
Sat_CO2_liq : Float64
CO₂ saturation concentration in the melt [ppm] (NaN if not computed).
fl_CO2_wt : Float64
Weight fraction of CO₂ fluid formed (NaN if not computed).
Sat_LREE_liq : Float64
ΣLREE (monazite) saturation concentration in the melt [ppm] (NaN if not computed).
mnz_wt : Float64
Weight fraction of monazite precipitated (NaN if not computed).
X_mnz_LREE : Float64
Molar ratio of LREE to all cations (LREE, Y, Th, U) in monazite, updated from `Cmin` (NaN if not computed).MAGEMin_C.ss_infos Type
ss_infos
Mutable structure holding general information about a solution phase.
Fields
------
ss_fName : String
Full name of the solution phase.
ss_name : String
Short name of the solution phase.
n_em : Int64
Number of endmembers.
n_xeos : Int64
Number of compositional variables.
n_sf : Int64
Number of site fractions.
ss_em : Vector{String}
Endmember names.
ss_xeos : Vector{String}
Compositional variable names.
ss_sf : Vector{String}
Site fraction names.MAGEMin_C.AMR Method
AMR(data)
Perform one adaptive mesh refinement step on the quadrilateral grid.
Each cell in `data.split_cell_list` is subdivided into four child cells by
inserting five new points: one at the cell centroid and one at each edge
midpoint. Duplicate midpoints shared by adjacent cells are detected via
`data.hash_map` and reused rather than duplicated. Cells in
`data.keep_cell_list` are retained unchanged; their edge midpoints that were
created by neighbouring splits are recorded in `data.bnd_cells` for use in
the next `split_and_keep` call.
Parameters
----------
data : AMR_data
AMR state structure. `data.cells`, `data.points`, `data.hash_map`,
`data.split_cell_list`, and `data.keep_cell_list` are read and updated.
Returns
-------
data : AMR_data
Updated AMR state with:
- `data.cells` — combined list of kept cells followed by new child cells.
- `data.points` — extended point list including all new midpoints.
- `data.ncells` — child cells generated in this step.
- `data.npoints` — new point coordinates generated in this step.
- `data.npoints_ig`— parent-point index tuples for each new point, used for
initial-guess interpolation.
- `data.bnd_cells` — boundary midpoint records for each kept cell.
- `data.hash_map` — updated coordinate-to-index map.MAGEMin_C.AMR_minimization Method
AMR_minimization(init_sub, ref_lvl, Prange, Trange, MAGEMin_db; test=0, X=nothing, B=0.0, scp=0, dT=2.0, iguess=false, rm_list=nothing, W=nothing, gbase=nothing, Xoxides=Vector{String}, sys_in="mol", rg="tc", progressbar=true)
Perform an Adaptive Mesh Refinement (AMR) minimization for a range of points as a function of pressure, temperature and/or composition.
Parameters
----------
init_sub : Int64
Initial number of subdivisions.
ref_lvl : Int64
Number of refinement levels.
Prange : Union{Float64, NTuple{2, Float64}}
Pressure range [kbar] as a tuple (Pmin, Pmax) or single value.
Trange : Union{Float64, NTuple{2, Float64}}
Temperature range [°C] as a tuple (Tmin, Tmax) or single value.
MAGEMin_db : MAGEMin_Data
Initialized MAGEMin data structure.
test : Int64, optional
Build-in test case number (default: 0).
X : VecOrMat, optional
Bulk rock composition(s) (default: nothing).
B : Union{Nothing, Float64, Vector{Float64}}, optional
Buffer value(s) (default: 0.0).
scp : Int64, optional
Sub-solidus computation parameter (default: 0).
dT : Float64, optional
Temperature increment for sub-solidus detection (default: 2.0).
iguess : Union{Vector{Bool}, Bool}, optional
Whether to use initial guess (default: false).
rm_list : Union{Nothing, Vector{Int64}}, optional
List of phase indexes to remove (default: nothing). Mutually exclusive with
`pp_list`/`ss_list`.
pp_list : Union{Nothing, Vector{String}}, optional
Pure phases to keep active; every other pure phase is deactivated (default: nothing,
i.e. no pure-phase selection). See [`select_phases`](@ref). Mutually exclusive with
`rm_list`. The buffer/activity pure phases in `ALWAYS_ACTIVE_PP` never need to be
listed - they remain governed by `buffer="..."` regardless.
ss_list : Union{Nothing, Vector{String}}, optional
Solution phases to keep active; every other solution phase is deactivated (default:
nothing, i.e. no solution-phase selection). See [`select_phases`](@ref). Mutually
exclusive with `rm_list`.
W : Union{Nothing, Vector{W_data{Float64, Int64}}}, optional
Overriding Margules parameters (default: nothing).
gbase : Union{Nothing, Vector{gbase_data{Float64, Int64}}}, optional
Additive shifts to endmember reference Gibbs energies (default: nothing).
Xoxides : Vector{String}
Oxide names corresponding to `X`.
sys_in : String, optional
Input system units, "mol" or "wt" (default: "mol").
rg : String, optional
Research group, "tc" or "sb" (default: "tc").
progressbar : Bool, optional
Show progress bar (default: true).
seismic_cor : Bool, optional
If true, compute melt + anelastic corrected seismic velocities of the
solid aggregate (`Vp_cor`, `Vs_cor`) (default: false).
aspect_ratio : Float64, optional
Aspect ratio of the melt/pore geometry, used when `seismic_cor=true` (default: 0.3).
seismic_water : Int, optional
Water content mode passed to [`anelastic_correction`](@ref) when `seismic_cor=true`:
`0` = dry mantle, `1` = damp mantle, `2` = wet mantle (default: 0).
Returns
-------
Out_XY : Vector{gmin_struct{Float64, Int64}}
Vector of minimization results for each refined P-T point.
Examples
--------
```julia
data = Initialize_MAGEMin("mp", verbose=-1, solver=0);
init_sub = 1
ref_lvl = 2
Prange = (1.0,10.0)
Trange = (400.0,800.0)
Xoxides = ["SiO2","Al2O3","CaO","MgO","FeO","K2O","Na2O","TiO2","O","MnO","H2O"]
X = [70.999,12.805,0.771,3.978,6.342,2.7895,1.481,0.758,0.72933,0.075,30.0]
sys_in = "mol"
out = AMR_minimization(init_sub, ref_lvl, Prange, Trange, data, X=X, Xoxides=Xoxides, sys_in=sys_in)
```MAGEMin_C.CO2_from_dissolved_H2O Method
CO2_from_dissolved_H2O(out, S_H2O_wt; tol=1e-6)Given a known dissolved H₂O content in the melt, compute the CO₂ saturation concentration using the M2Fluid model of Sun & Yao (2026).
Assumes a binary H₂O-CO₂ fluid so that P_CO₂ = P - P_H₂O. P_H₂O is found by numerically inverting Eq. (7) via bisection on [0, P].
Parameters
out : MAGEMin_C.gmin_struct{Float64, Int64} MAGEMin minimization output (must contain a melt phase). S_H2O_wt : Float64 Total dissolved H₂O content in the melt [wt%]. tol : Float64, optional Convergence tolerance on P_H₂O (in bar; default 1e-6).
Returns
P_H2O : Float64 H₂O partial pressure [bar]. P_CO2 : Float64 CO₂ partial pressure (in bar; = P - P_H₂O). S_CO2 : Float64 CO₂ saturation in the melt [ppm], or NaN if P_CO₂ ≤ 0.
sourceMAGEMin_C.CO2_from_dissolved_H2O Method
CO2_from_dissolved_H2O(out)Convenience overload: reads dissolved H₂O directly from the melt phase of out (in wt%) and forwards to CO2_from_dissolved_H2O(out, S_H2O_wt).
Returns (NaN, NaN, NaN) if no melt is present or the melt contains no H₂O.
MAGEMin_C.D_amph Method
D_amph(T, P, melt, min_wt)Amphibole/melt partition coefficients after Tiepolo et al. (2007) and Dalpe & Baker (2000). Site fractions from hb_G16 (Green et al. 2016).
sourceMAGEMin_C.D_cpx Method
D_cpx(T, P, melt, min_wt)Clinopyroxene/melt partition coefficients after Blundy & Wood (1994), Sun & Liang (2012), Corgne et al. (2012), and Hill et al. (2011). Site fractions from cpx_G23 (Green et al., in prep).
sourceMAGEMin_C.D_gt Method
D_gt(T, P, melt, min_wt)Garnet/melt partition coefficients after van Westrenen & Draper (2007), and Sun & Liang (2013). Site fractions from g_G23 (Green et al., in prep).
sourceMAGEMin_C.D_ol Method
D_ol(T, P, melt, min_wt)Olivine/melt partition coefficients after Yao et al. (2012) and Bédard (2005). Site fractions from ol_H18 (Holland et al. 2018).
sourceMAGEMin_C.D_opx Method
D_opx(T, P, melt, min_wt)Orthopyroxene/melt partition coefficients after Bédard (2007), Frei et al. (2009), and Wood & Blundy (2013). Site fractions from opx_G23 (Green et al., in prep).
sourceMAGEMin_C.D_pl Method
D_pl(T, P, melt, min_wt)Plagioclase/melt partition coefficients after Dohmen & Blundy (2014). Site fractions from fsp_H21 (Holland et al. 2021).
sourceMAGEMin_C.FeO2Fe_O! Method
FeO2Fe_O!(bulk_mol, bulk_ox)
Convert bulk-rock composition from FeO + extra oxygen to total Fe + total O (used for SB24). Modifies `bulk_mol` and `bulk_ox` in place.
Parameters
----------
bulk_mol : AbstractVector{Float64}
Bulk rock composition in molar fraction (modified in place).
bulk_ox : AbstractVector{String}
Oxide names corresponding to `bulk_mol` (modified in place).
Returns
-------
bulk_mol : AbstractVector{Float64}
Updated bulk rock composition with Fe and O instead of FeO.
bulk_ox : AbstractVector{String}
Updated oxide names with "Fe" and "O" replacing "FeO".MAGEMin_C.Finalize_MAGEMin Method
Finalize_MAGEMin(dat)
Finalize MAGEMin and free all allocated memory.
Parameters
----------
dat : MAGEMin_Data
MAGEMin data structure to finalize.
Returns
-------
nothingMAGEMin_C.Initialize_MAGEMin Function
Initialize_MAGEMin(db="ig"; verbose=0, dataset=nothing, limitCaOpx=0, CaOpxLim=0.0, mbCpx=1, mbIlm=0, mpSp=0, mpIlm=0, ig_ed=0, buffer="NONE", solver=0)
Initialize MAGEMin on one or more threads for the specified database.
Parameters
----------
db : String, optional
Database name (default: "ig"). Options: "mp", "mb", "mbe", "ig", "igad", "um", "ume", "mtl", "mpe", "all", "po", "sb11", "sb21", "sb24".
verbose : Union{Int64, Bool}, optional
Verbosity level (default: 0). `false` or `-1` suppresses output, `true` or `0` gives a brief summary, `1` gives detailed output.
dataset : Union{Nothing, Int64}, optional
Dataset identifier (default: nothing). Must be in `available_TC_ds` if specified.
limitCaOpx : Int64, optional
Flag to limit Ca in orthopyroxene (default: 0).
CaOpxLim : Float64, optional
Ca limit value for orthopyroxene (default: 0.0).
mbCpx : Int64, optional
Metabasite clinopyroxene model flag (default: 1).
mbIlm : Int64, optional
Metabasite ilmenite model flag (default: 0).
mpSp : Int64, optional
Metapelite spinel model flag (default: 0).
mpIlm : Int64, optional
Metapelite ilmenite model flag (default: 0).
ig_ed : Int64, optional
Igneous extended database flag (default: 0).
buffer : String, optional
Buffer type (default: "NONE").
mu_fix_idx : Vector{String}, optional
Oxide names (e.g. `["MgO","K2O"]`) whose chemical potential should be
fixed directly (native mu-mu mechanism). Each fixed oxide's bulk content must be
set generously in excess of what its target implies (same
requirement `buffer`/`buffer_n` already has) - see
`point_wise_minimization`'s `mu_fix_val` docs (default: `String[]`,
i.e. off).
solver : Int64, optional
Solver type (default: 0).
Returns
-------
data : MAGEMin_Data
Initialized MAGEMin data structure containing per-thread databases and variables.MAGEMin_C.MAGEMin_data2dataframe Method
MAGEMin_data2dataframe(out, dtb, fileout)
Export MAGEMin minimization results to a CSV file in long (stacked) format,
writing one row per phase per point.
Each row contains point index, X fraction, P [kbar], T [°C], phase name,
modal abundances (mol%, wt%, vol%), system thermodynamic properties
(ρ, Vp, Vs, Cp, α, S, H, K, G), activity/fugacity variables, and oxide
compositions (mol% and wt%) plus apfu element compositions for each phase.
System-level rows (`"system"`) additionally carry fO₂, ΔQFM, melt
viscosity, and the seismically-corrected solid-aggregate velocities
(`Vp_cor`, `Vs_cor`, NaN if seismic corrections were not requested).
A companion metadata file is written at `fileout_metadata.txt`.
Parameters
----------
out : Union{Vector{gmin_struct{Float64, Int64}}, gmin_struct{Float64, Int64}}
MAGEMin minimization output for one or more points.
dtb : String
Database identifier used to retrieve database metadata (e.g., `"ig"`, `"mp"`).
fileout : String
Base path for output files. Two files are created: `fileout.csv` and
`fileout_metadata.txt`.
use_Warr2021 : Bool, optional
If `true`, mineral phase names are converted to IMA-CNMNC approved symbols
following Warr (2021). Names with no official symbol are returned with a
trailing `"*"`. Default is `false`.
use_GPA : Bool, optional
If `true`, pressure is reported in GPa (column `"P[GPa]"`) instead of kbar
(column `"P[kbar]"`). Default is `false`.
Returns
-------
nothingMAGEMin_C.MAGEMin_data2dataframe_inlined Method
MAGEMin_data2dataframe_inlined(out, dtb, fileout)
Export MAGEMin minimization results to a CSV file in wide (inlined) format,
with one row per point and all phase data spread across columns.
The output DataFrame is built in three blocks that are horizontally
concatenated: system-level properties (`sys_*` prefix), solution-phase
columns (`<ph>_*` prefix, `NaN`-filled when a phase is absent at a given
point), and pure-phase columns (same convention). System-level properties
additionally include the solid-aggregate seismic velocities (`Vp_S`,
`Vs_S`) and their seismically-corrected counterparts (`Vp_cor`, `Vs_cor`,
NaN if seismic corrections were not requested). Column groups per phase
include modal fractions (mol%, wt%, vol%), thermodynamic properties
(ρ, Vp, Vs, Cp, α, S, H, K, G), and oxide compositions (mol%, wt%) plus
apfu element compositions. A companion metadata file is written at
`fileout_metadata.txt`; the CSV is written to `fileout_inlined.csv`.
Parameters
----------
out : Union{Vector{gmin_struct{Float64, Int64}}, gmin_struct{Float64, Int64}}
MAGEMin minimization output for one or more points.
dtb : String
Database identifier used to retrieve database metadata (e.g., `"ig"`, `"mp"`).
fileout : String
Base path for output files. Two files are created: `fileout_inlined.csv`
and `fileout_metadata.txt`.
use_Warr2021 : Bool, optional
If `true`, mineral phase names used as column prefixes are converted to
IMA-CNMNC approved symbols following Warr (2021). Names with no official
symbol are returned with a trailing `"*"`. Default is `false`.
use_GPA : Bool, optional
If `true`, pressure is reported in GPa (column `"P[GPa]"`) instead of kbar
(column `"P[kbar]"`). Default is `false`.
Returns
-------
nothingMAGEMin_C.MAGEMin_dataTE2dataframe Method
MAGEMin_dataTE2dataframe(out, out_te, dtb, fileout)
Export MAGEMin minimization results together with trace element partitioning
output to a CSV file, writing one row per phase per point.
The CSV contains columns for P, T, X, phase name, mode [wt%], Zr saturation
[μg/g], corrected bulk oxide composition [wt%], and per-element concentrations
[μg/g]. A companion metadata text file recording the MAGEMin version, database,
date, and time is written alongside the CSV.
Rows are written for the bulk system (`"system"`), the melt (`"liq"`), the
bulk solid aggregate (`"sol"`), and each individual mineral phase.
Parameters
----------
out : Union{Vector{gmin_struct{Float64, Int64}}, gmin_struct{Float64, Int64}}
MAGEMin minimization output for one or more points.
out_te : Union{Vector{out_tepm}, out_tepm}
Trace element partitioning output corresponding to each point in `out`.
dtb : String
Database identifier used to retrieve database metadata (e.g., `"ig"`, `"mp"`).
fileout : String
Base path for output files. Two files are created: `fileout.csv` and
`fileout_metadata.txt`.
use_Warr2021 : Bool, optional
If `true`, mineral phase names are converted to IMA-CNMNC approved symbols
following Warr (2021). Names with no official symbol are returned with a
trailing `"*"`. Default is `false`.
use_GPA : Bool, optional
If `true`, pressure is reported in GPa (column `"P[GPa]"`) instead of kbar
(column `"P[kbar]"`). Default is `false`.
Returns
-------
nothingMAGEMin_C.TE_prediction Method
TE_prediction(out, C0, KDs_database, dtb; ZrSat_model="none", SSat_model="none", P2O5Sat_model="none", MnzSat_model="none", norm_TE=false)
Perform trace element partitioning, optionally with zircon, sulfide, apatite, and/or monazite saturation corrections.
Phases are classified via `mineral_classification`, elements are partitioned using the batch melting equation, and saturation corrections are applied when the corresponding model is not `"none"`. The corrected bulk composition (accounting for precipitated saturation phases) is also returned.
Parameters
----------
out : MAGEMin_C.gmin_struct{Float64, Int64}
MAGEMin minimization output.
C0 : Vector{Float64}
Initial bulk trace element composition [ppm], in the order of `KDs_database.element_name`.
KDs_database : custom_KDs_database
Compiled trace element partitioning coefficient database.
dtb : String
Database identifier used for mineral classification (e.g., "ig", "mp").
ZrSat_model : String, optional
Zirconium saturation model — "none" disables Zr correction (default: "none"). Valid options: "CB", "W85", "BD92", "RZ93", "CZLD08".
SSat_model : String, optional
Sulfur saturation model — "none" disables S correction (default: "none"). Valid option: "1000ppm".
P2O5Sat_model : String, optional
Phosphate saturation model — "none" disables P₂O₅ correction (default: "none"). Valid options: "Klein26", "HWBea92", "Tollari06".
MnzSat_model : String, optional
Monazite saturation model — "none" disables ΣLREE correction (default: "none"). Valid options: "Stepanov12", "Montel93", "Maimaiti19".
X_mnz_LREE : Float64, optional
Molar ratio of LREE to all cations (LREE, Y, Th, U) in monazite, carried over from a previous
`TE_prediction`/`solve_with_saturation` iteration (default: 1.0, i.e. no Y/Th/U substitution).
norm_TE : Bool, optional
Normalize phase fractions before computing KDs (default: false).
Returns
-------
out_TE : out_tepm
Structure containing melt/solid/mineral TE concentrations, saturation values, and corrected bulk compositions.MAGEMin_C._augment_KDs_for_saturation Method
_augment_KDs_for_saturation(KDs_database, sat)Internal helper. When sat is a SaturationConfig, append a column of KD functions for each active saturation phase that is not already present in KDs_database.phase_name. Every saturation phase gets zero-KD functions (its budget is handled entirely through the saturation front, not Nernst partitioning), except monazite ("mnz"), which gets the literature Kd row _MNZ_KD so that it competes for Y/Th/U (and La–Gd) against every other modal phase through the ordinary partitioning machinery. Returns the (possibly augmented) database; the original is never mutated.
MAGEMin_C._filter_DEW_species Function
_filter_DEW_species(ss, eps=1e-40)
Drop chemically infeasible species (endmembers with `emFrac <= eps`) from a `DEW_S24`
aqueous speciation phase's per-endmember fields, shrinking `emNames`, `molality`,
`activity`, `emFrac`, `emFrac_wt`, `emChemPot`, `emComp`, `emComp_wt`, and
`emComp_apfu` together (same kept-index set for all of them). The phase-level fields
(`Comp`, `compVariables`, `siteFractions`, etc.) are untouched, since those describe
the phase as a whole rather than individual species.
Parameters
----------
ss : LibMAGEMin.SS_data
Solution-phase data for a `DEW_S24` entry.
eps : Float64, optional
Species with `emFrac <= eps` are dropped (default: 1e-40, i.e. essentially exact
zero rather than "small but present").
Returns
-------
ss_filtered : LibMAGEMin.SS_data
Copy of `ss` with infeasible species removed from its per-endmember fields.MAGEMin_C._montel_maimaiti_M Method
_montel_maimaiti_M(out)
Dry cation-mole-fraction melt compositional parameter (Na+K+2Ca)/(Al·(Al+Si))
used by the Montel (1993) and Maimaiti et al. (2019) monazite saturation
models (Montel's own "D" omits the Li term here, since Li2O is not a
tracked oxide in MAGEMin's databases). Reuses the same dry-cation-fraction
extraction as `zirconium_saturation`'s M-value.
Parameters
----------
out : MAGEMin_C.gmin_struct{Float64, Int64}
MAGEMin minimization output (must contain a melt phase).
Returns
-------
M : Float64
(Na+K+2Ca)/(Al·(Al+Si)), computed from dry cation mole fractions (summing to 1).MAGEMin_C._rescale_Cmin! Method
_rescale_Cmin!(Cmin, Cliq, Cliq_pre)
Internal helper. Brings `Cmin` back into agreement with `Cliq` after a
saturation model has overwritten one or more melt concentrations: each column
whose `Cliq` differs from the snapshot `Cliq_pre` is scaled by
`Cliq / Cliq_pre`, and `Cliq_pre` is advanced to match.
Idempotent, and a no-op when `Cmin` is not a matrix (no melt, or no solid).MAGEMin_C.adjust_bulk_4_fapatite Method
adjust_bulk_4_fapatite(P2O5_liq, sat_liq, liq_wt)
Compute the weight fractions of fluorapatite and CaO returned to the bulk when the melt exceeds P₂O₅ saturation.
Parameters
----------
P2O5_liq : Float64
P₂O₅ concentration in the melt [ppm].
sat_liq : Float64
P₂O₅ saturation concentration in the melt [ppm].
liq_wt : Float64
Melt weight fraction.
Returns
-------
fapt_wt : Float64
Weight fraction of precipitated fluorapatite (scaled by `liq_wt`).
CaO_wt : Float64
CaO weight returned to the bulk (scaled by `liq_wt`).MAGEMin_C.adjust_bulk_4_fluid Method
adjust_bulk_4_fluid(CO2_liq, sat_liq, liq_wt)
Compute the weight fractions of CO₂ fluid and the oxide correction when the
melt exceeds CO₂ saturation.
Unlike mineral saturation phases (zircon, sulfide, apatite), the excess CO₂
is not converted to a stoichiometrically distinct solid — it degasses into a
CO₂-bearing fluid. The same CO₂ weight is therefore both the fluid weight
and the amount returned to the bulk CO₂ oxide budget for the next iteration.
Parameters
----------
CO2_liq : Float64
CO₂ concentration in the melt [ppm].
sat_liq : Float64
CO₂ saturation concentration in the melt [ppm].
liq_wt : Float64
Melt weight fraction.
Returns
-------
fluid_wt : Float64
Weight fraction of CO₂ fluid formed (scaled by `liq_wt`).
CO2_wt : Float64
CO₂ weight returned to the bulk oxide budget (scaled by `liq_wt`);
equals `fluid_wt` for a pure CO₂ fluid.MAGEMin_C.adjust_bulk_4_monazite Method
adjust_bulk_4_monazite(Cliq_LREE, sat_liq, liq_wt)
Compute the weight fractions of monazite, P₂O₅, and each LREE removed from the melt when the melt exceeds ΣLREE (monazite) saturation.
The ΣLREE excess over saturation is apportioned across La, Ce, Pr, Nd, and Sm in proportion to their current melt concentrations, preserving the melt's REE pattern. The apportioned excess is then converted to monazite and consumed P₂O₅ through 2 REEPO₄ ⇌ REE₂O₃ + P₂O₅ stoichiometry (1 mole P₂O₅ per 2 moles LREE removed), using the actual atomic masses of La/Ce/Pr/Nd/Sm rather than a lumped average.
Parameters
----------
Cliq_LREE : Vector{Float64}
Current melt concentrations of [La, Ce, Pr, Nd, Sm] [ppm].
sat_liq : Float64
ΣLREE saturation concentration in the melt [ppm].
liq_wt : Float64
Melt weight fraction.
Returns
-------
mnz_wt : Float64
Weight fraction of precipitated monazite (scaled by `liq_wt`).
P2O5_wt : Float64
P₂O₅ weight consumed from the melt (scaled by `liq_wt`).
LREE_wt : Vector{Float64}
Weight of each of [La, Ce, Pr, Nd, Sm] removed from the melt (scaled by `liq_wt`).MAGEMin_C.adjust_bulk_4_sulfide Method
adjust_bulk_4_sulfide(S_liq, sat_liq, liq_wt)
Compute the weight fractions of sulfide, FeO, and O returned to the bulk when the melt exceeds sulfur saturation.
Parameters
----------
S_liq : Float64
Sulfur concentration in the melt [ppm].
sat_liq : Float64
Sulfur saturation concentration in the melt [ppm].
liq_wt : Float64
Melt weight fraction.
Returns
-------
sulfide_wt : Float64
Weight fraction of precipitated sulfide (scaled by `liq_wt`).
FeO_wt : Float64
FeO weight returned to the bulk (scaled by `liq_wt`).
O_wt : Float64
O weight correction (negative, scaled by `liq_wt`).MAGEMin_C.adjust_bulk_4_zircon Method
adjust_bulk_4_zircon(zr_liq, sat_liq, liq_wt)
Compute the weight fractions of zircon, SiO₂, and O returned to the bulk when the melt exceeds Zr saturation.
Parameters
----------
zr_liq : Float64
Zr concentration in the melt [ppm].
sat_liq : Float64
Zr saturation concentration in the melt [ppm].
liq_wt : Float64
Melt weight fraction.
Returns
-------
zircon_wt : Float64
Weight fraction of precipitated zircon (scaled by `liq_wt`).
SiO2_wt : Float64
SiO₂ weight returned to the bulk (scaled by `liq_wt`).
O2_wt : Float64
O weight returned to the bulk (scaled by `liq_wt`).MAGEMin_C.adjust_chemical_system Method
adjust_chemical_system(KDs_dtb, bulk_TE, elem_TE)
Reorder and subset a bulk trace element composition vector to match the element order defined in a KD database.
Elements present in `KDs_dtb` but absent from `elem_TE` are set to zero.
Parameters
----------
KDs_dtb : custom_KDs_database
KD database whose `element_name` field defines the target element order.
bulk_TE : Vector{Float64}
Input bulk trace element concentrations [ppm].
elem_TE : Vector{String}
Element names corresponding to `bulk_TE`.
Returns
-------
C0_TE : Vector{Float64}
Bulk trace element concentrations reordered to match `KDs_dtb.element_name` [ppm].MAGEMin_C.all_identical Method
all_identical(arr::Vector{UInt64})
Check whether all elements in a `UInt64` vector are identical.
Parameters
----------
arr : Vector{UInt64}
Vector of hash values to compare.
Returns
-------
result : Bool
`true` if all elements equal `arr[1]`, `false` otherwise.MAGEMin_C.allocate_output Method
allocate_output(n)
Allocate memory for the output vector of minimization results.
Parameters
----------
n : Int64
Number of output structures to allocate.
Returns
-------
output : Vector{gmin_struct{Float64, Int64}}
Uninitialized vector of `gmin_struct` with length `n`.MAGEMin_C.amph_sites Method
amph_sites(wt)hb_G16 — Green et al. (2016). Sites: A(v Na K), M13(Mg Fe), M2(Mg Fe Al Fe³⁺ Ti), M4(Ca Mg Fe Na), T1*(Si Al). Normalised to 23 oxygens (8 T1 positions per formula unit). TC variables: y = xAlM2, z = xNaM4, c = xCaM4, a = total A-site occupancy. xAlT1 ≈ y/2 + a/4 (simplified: ignoring small f, t, z contributions)
sourceMAGEMin_C.anelastic_correction Method
anelastic_correction(water, Vs0, P_kbar, T_K)
Anelastic (attenuation) correction for the S-wave velocity, following the
model of Behn et al. (2009), with frequency/grain-size terms from
Cobden et al. (2018).
Parameters
----------
water : Int
Water content mode: `0` = dry mantle, `1` = damp mantle, `2` = wet mantle (saturated).
Vs0 : Float64
Unrelaxed (elastic) S-wave velocity [km/s].
P_kbar : Float64
Pressure [kbar].
T_K : Float64
Temperature [K].
Returns
-------
Vs_anel : Float64
Anelastically corrected S-wave velocity [km/s].
Reference
---------
Behn M.D., Hirth G., Elsenbeck J.R. (2009); Cobden L. et al. (2018)MAGEMin_C.anhydrous_renormalization Method
anhydrous_renormalization(bulk, oxide)
Renormalize the bulk rock composition to remove water (H2O) if present.
Parameters
----------
bulk : Vector{Float64}
Bulk rock composition vector.
oxide : Vector{String}
List of oxide names corresponding to `bulk`.
Returns
-------
bulk_dry : Vector{Float64}
Renormalized anhydrous bulk rock composition.MAGEMin_C.bi_Li_CB_model Method
bi_Li_CB_model(y, f, T)
Compute the Li partition coefficient between biotite and melt, after Beard (2025).
Parameters
----------
y : Float64
Biotite Al-content compositional variable (Al on T site).
f : Float64
Biotite Fe/(Fe+Mg) compositional variable.
T : Float64
Temperature [°C].
Returns
-------
KD_Li : Float64
Li partition coefficient (biotite/melt).MAGEMin_C.bi_Li_IL_model Method
bi_Li_IL_model(T)
Compute the Li partition coefficient between biotite and melt using a linear temperature model (Imai & Liang, unpublished).
Parameters
----------
T : Float64
Temperature [°C].
Returns
-------
KD_Li : Float64
Li partition coefficient (biotite/melt).MAGEMin_C.cd_Li_IL_model Method
cd_Li_IL_model(T)
Compute the Li partition coefficient between cordierite and melt using a linear temperature model (Imai & Liang, unpublished).
Parameters
----------
T : Float64
Temperature [°C].
Returns
-------
KD_Li : Float64
Li partition coefficient (cordierite/melt).MAGEMin_C.co2_saturation Method
co2_saturation(out; model="SY26")
Compute the CO₂ saturation concentration in the melt phase [ppm].
Reads dissolved H₂O from the melt phase of `out`, inverts the SY26 H₂O
equation to find P_H₂O, then evaluates CO₂ solubility at
P_CO₂ = P_total − P_H₂O (binary H₂O–CO₂ fluid assumption).
Parameters
----------
out : MAGEMin_C.gmin_struct{Float64, Int64}
MAGEMin minimization output (must contain a melt phase with dissolved H₂O).
model : String, optional
Saturation model (default: "SY26"). Currently only "SY26" is supported.
Returns
-------
S_CO2 : Float64
CO₂ saturation concentration in the melt [ppm], or NaN if H₂O is
unavailable or the model is unrecognised.MAGEMin_C.compute_CO2_sat_n_part Method
compute_CO2_sat_n_part(out, KDs_database, Cliq, bulk_cor_wt, C0, liq_wt; CO2Sat_model="SY26")
Check CO₂ saturation and adjust the corrected bulk composition if the melt exceeds the CO₂ saturation limit.
If CO₂ in the melt exceeds the saturation concentration, the excess degasses into a CO₂-bearing fluid and the
corresponding weight is added back to the bulk CO₂ oxide entry in `bulk_cor_wt`. Unlike mineral saturation
phases, no stoichiometrically distinct oxide is returned — the excess CO₂ re-enters the CO₂ oxide budget directly.
Parameters
----------
out : MAGEMin_C.gmin_struct{Float64, Int64}
MAGEMin minimization output.
KDs_database : custom_KDs_database
Trace element partitioning coefficient database (must include "CO2").
Cliq : Vector{Float64}
Current trace element concentrations in the melt [ppm].
bulk_cor_wt : Vector{Float64}
Corrected bulk oxide weight fractions (modified in place).
C0 : Vector{Float64}
Initial bulk trace element composition [ppm].
liq_wt : Float64
Melt weight fraction.
CO2Sat_model : String, optional
CO₂ saturation model (default: "SY26"). Passed to `co2_saturation`.
Returns
-------
Sat_CO2_liq : Float64
CO₂ saturation concentration in the melt [ppm].
fl_CO2_wt : Float64
Weight fraction of CO₂ fluid formed.
bulk_cor_wt : Vector{Float64}
Updated corrected bulk oxide weight fractions.MAGEMin_C.compute_Mnz_sat_n_part Method
compute_Mnz_sat_n_part(out, KDs_database, Cliq, C0, liq_wt, Sat_P2O5_liq; MnzSat_model="Stepanov12", X_mnz_LREE=1.0)
Check monazite (ΣLREE) saturation and compute the precipitated monazite weight fraction.
If ΣLa+Ce+Pr+Nd+Sm in the melt exceeds the ΣLREE saturation concentration, the excess is converted to
monazite. Monazite draws on the same melt P₂O₅ budget as apatite: the P₂O₅ available to monazite is
capped at whatever remains once apatite saturation (`Sat_P2O5_liq`) is satisfied, and if that is not
enough to precipitate the full LREE excess, `Sat_LREE_liq` is raised so the P₂O₅ actually consumed
matches what is available. Unlike zircon/apatite/sulfide, monazite does not return any oxide to
`bulk_cor_wt`: La–Sm and P₂O₅ are trace elements that never enter MAGEMin's modeled major-oxide system,
so their mass balance is self-contained within `C0`/`Cliq`/`Csol` (see `TE_prediction`).
Parameters
----------
out : MAGEMin_C.gmin_struct{Float64, Int64}
MAGEMin minimization output.
KDs_database : custom_KDs_database
Trace element partitioning coefficient database (must include "La", "Ce", "Pr", "Nd", "Sm", "P2O5").
Cliq : Vector{Float64}
Current trace element concentrations in the melt [ppm].
C0 : Vector{Float64}
Initial bulk trace element composition [ppm].
liq_wt : Float64
Melt weight fraction.
Sat_P2O5_liq : Float64
Apatite P₂O₅ saturation concentration in the melt [ppm] (NaN if apatite saturation was not computed).
MnzSat_model : String, optional
Monazite saturation model (default: "Stepanov12"). Passed to `monazite_saturation`.
Valid options: "Stepanov12", "Montel93", "Maimaiti19".
X_mnz_LREE : Float64, optional
Molar ratio of LREE to all cations (LREE, Y, Th, U) in monazite, from the previous iteration (default: 1.0).
Returns
-------
Sat_LREE_liq : Float64
ΣLREE saturation concentration in the melt [ppm].
mnz_wt : Float64
Weight fraction of precipitated monazite.MAGEMin_C.compute_P2O5_sat_n_part Method
compute_P2O5_sat_n_part(out, KDs_database, Cliq, bulk_cor_wt, C0, liq_wt; P2O5Sat_model="Klein26")
Check phosphate saturation and adjust the corrected bulk composition if the melt exceeds the P₂O₅ saturation limit.
If P₂O₅ in the melt exceeds the saturation concentration, the excess is removed and the corresponding CaO is returned to the bulk. If there is no melt, all P₂O₅ is assumed to have precipitated as fluorapatite.
Parameters
----------
out : MAGEMin_C.gmin_struct{Float64, Int64}
MAGEMin minimization output.
KDs_database : custom_KDs_database
Trace element partitioning coefficient database (must include "P2O5").
Cliq : Vector{Float64}
Current trace element concentrations in the melt [ppm].
bulk_cor_wt : Vector{Float64}
Corrected bulk oxide weight fractions (modified in place).
C0 : Vector{Float64}
Initial bulk trace element composition [ppm].
liq_wt : Float64
Melt weight fraction.
P2O5Sat_model : String, optional
Phosphate saturation model (default: "Klein26"). Passed to `phosphate_saturation`.
Returns
-------
Sat_P2O5_liq : Float64
P₂O₅ saturation concentration in the melt [ppm].
fapt_wt : Float64
Weight fraction of precipitated fluorapatite.
bulk_cor_wt : Vector{Float64}
Updated corrected bulk oxide weight fractions.MAGEMin_C.compute_S_sat_n_part Method
compute_S_sat_n_part(out, KDs_database, Cliq, bulk_cor_wt, C0, liq_wt; SSat_model="1000ppm")
Check sulfur saturation and adjust the corrected bulk composition if the melt exceeds the S saturation limit.
If S in the melt exceeds the saturation concentration, the excess is removed and the corresponding FeO and O are returned to the bulk. If there is no melt, all S is assumed to have precipitated as sulfide.
Parameters
----------
out : MAGEMin_C.gmin_struct{Float64, Int64}
MAGEMin minimization output.
KDs_database : custom_KDs_database
Trace element partitioning coefficient database (must include "S").
Cliq : Vector{Float64}
Current trace element concentrations in the melt [ppm].
bulk_cor_wt : Vector{Float64}
Corrected bulk oxide weight fractions (modified in place).
C0 : Vector{Float64}
Initial bulk trace element composition [ppm].
liq_wt : Float64
Melt weight fraction.
SSat_model : String, optional
Sulfur saturation model (default: "1000ppm"). Passed to `sulfur_saturation`.
Returns
-------
Sat_S_liq : Float64
S saturation concentration in the melt [ppm].
sulf_wt : Float64
Weight fraction of precipitated sulfide.
bulk_cor_wt : Vector{Float64}
Updated corrected bulk oxide weight fractions.MAGEMin_C.compute_TE_partitioning Method
compute_TE_partitioning(KDs_database, out, C0, ph, ph_wt, liq_wt, sol_wt; norm_TE=true)
Partition trace elements between melt and solid phases using the supplied KD database.
Handles three end-member cases: fully molten (`liq_wt == 1.0`), fully solid (`liq_wt == 0.0`), and mixed (`0 < liq_wt < 1`). In the mixed case the batch melting equation is applied.
Parameters
----------
KDs_database : custom_KDs_database
Compiled trace element partitioning coefficient database.
out : MAGEMin_C.gmin_struct{Float64, Int64}
MAGEMin minimization output used to evaluate P-T-composition-dependent KDs.
C0 : Vector{Float64}
Initial bulk trace element composition [ppm].
ph : Vector{String}
Phase names from `mineral_classification`.
ph_wt : Vector{Float64}
Weight fractions of each phase.
liq_wt : Float64
Melt weight fraction.
sol_wt : Float64
Solid weight fraction.
norm_TE : Bool, optional
Normalize phase fractions before computing KDs (default: true).
Returns
-------
Cliq : Vector{Float64}
Trace element concentrations in the melt [ppm].
Csol : Vector{Float64}
Trace element concentrations in the bulk solid [ppm].
Cmin : Matrix{Float64}
Trace element concentrations in each mineral phase [ppm].
ph_TE : Vector{String}
Phase names included in the calculation.
ph_wt_norm : Vector{Float64}
Normalized solid phase weight fractions.
liq_wt_norm : Float64
Normalized melt weight fraction.
bulk_D : Float64
Bulk partition coefficient.MAGEMin_C.compute_Zr_sat_n_part Method
compute_Zr_sat_n_part(out, KDs_database, Cliq, bulk_cor_wt, C0, liq_wt; ZrSat_model="CB")
Check zircon saturation and adjust the corrected bulk composition if the melt exceeds the Zr saturation limit.
If Zr in the melt exceeds the saturation concentration, the excess is removed from the melt and the corresponding SiO₂ and O are returned to the bulk. If there is no melt (`liq_wt == 0`), all Zr is assumed to have precipitated as zircon.
Parameters
----------
out : MAGEMin_C.gmin_struct{Float64, Int64}
MAGEMin minimization output.
KDs_database : custom_KDs_database
Trace element partitioning coefficient database (must include "Zr").
Cliq : Vector{Float64}
Current trace element concentrations in the melt [ppm].
bulk_cor_wt : Vector{Float64}
Corrected bulk oxide weight fractions (modified in place).
C0 : Vector{Float64}
Initial bulk trace element composition [ppm].
liq_wt : Float64
Melt weight fraction.
ZrSat_model : String, optional
Zirconium saturation model (default: "CB"). Passed to `zirconium_saturation`.
Returns
-------
Sat_Zr_liq : Float64
Zr saturation concentration in the melt [ppm].
zrc_wt : Float64
Weight fraction of precipitated zircon.
bulk_cor_wt : Vector{Float64}
Updated corrected bulk oxide weight fractions.MAGEMin_C.compute_index Method
compute_index(value, min_value, delta)
Compute the 1-based grid index of a coordinate value along one axis.
Parameters
----------
value : Float64
Coordinate value to index.
min_value : Float64
Minimum value of the axis.
delta : Float64
Grid spacing along the axis.
Returns
-------
index : Int64
1-based index of `value` in the uniform grid.MAGEMin_C.compute_melt_viscosity_G08 Method
compute_melt_viscosity_G08(oxides, M_mol, T_C; A = -4.55)
Compute melt viscosity using the Giordano, Russell & Dingwell (2008) model.
Oxide compositions are mapped onto the 12-component GRD08 system
(SiO₂, Al₂O₃, TiO₂, FeO, CaO, MgO, MnO, Na₂O, K₂O, P₂O₅, H₂O, F₂O₋₁),
re-normalised to 100 mol%, and combined via the VTF equation:
log₁₀(η) = A + B / (T_K − C)
Viscosity is capped at 10¹⁴ Pa·s.
Parameters
----------
oxides : Vector{String}
Oxide names for the melt composition (MAGEMin ordering).
M_mol : Vector{Float64}
Melt composition in mol fractions, indexed to match `oxides`.
T_C : Float64
Temperature [°C].
A : Float64
Pre-exponential constant (default: −4.55, after Giordano et al. 2008).
Returns
-------
eta : Float64
Melt viscosity [Pa·s], capped at 10¹⁴ Pa·s.MAGEMin_C.convertBulk4MAGEMin Method
convertBulk4MAGEMin(bulk_in, bulk_in_ox, sys_in, db)
Convert a bulk-rock composition (in mol or wt fraction) and its associated oxide list into the format expected by MAGEMin.
Parameters
----------
bulk_in : AbstractVector{Float64}
Input bulk rock composition.
bulk_in_ox : Vector{String}
Oxide names corresponding to `bulk_in`.
sys_in : String
Input system units, "mol" or "wt".
db : String
Database identifier, e.g. "ig", "mp", "mb", "sb24".
Returns
-------
MAGEMin_bulk : Vector{Float64}
Bulk rock composition converted and normalized for MAGEMin (summing to 100).
MAGEMin_ox : Vector{String}
Oxide names in the order expected by MAGEMin for the given database.MAGEMin_C.convert_SS_eval_TE Method
convert_SS_eval_TE(str)
Rewrite `[:phase]` subscript tokens in a KD expression string to fully-qualified `gmin_struct` accessor calls.
The pattern `[:name]` is replaced with `out.SS_vec[find_ss_idx(out, :name)]`, allowing KD expressions to reference solution phase data by short name (e.g., `[:liq].compVariables[1]` → `out.SS_vec[find_ss_idx(out, :liq)].compVariables[1]`). `find_ss_idx` resolves an exact `out.SS_syms` match first, falling back to any symbol with a matching prefix — needed because databases such as `all` carry citation-tagged phase symbols (e.g. `:liq_G16`) rather than the bare name.
Parameters
----------
str : String
KD expression string potentially containing `[:phase]` tokens.
Returns
-------
str : String
Expression string with all `[:phase]` tokens replaced.MAGEMin_C.cpx_sites Method
cpx_sites(wt)cpx_G23 — Green et al. (in prep), after Holland et al. (2018). Sites: T*(Si Al), M1(Mg Fe Al Fe³⁺ Cr Ti), M2(Ca Na K Mg Fe). Normalised to 6 oxygens. TC composition variables: y = 2·xAlT (= Al_T count per f.u. = XAl4) x = Fe/(Fe+Mg), o = xMgM2+xFeM2, n = xNaM2, k = xKM2 Q = order variable → set to 0 (disordered approximation).
sourceMAGEMin_C.create_custom_KDs_database Method
create_custom_KDs_database(el_name, phase_name, KDs_expr_str; info="Custom KDs database")
Create a custom trace element partitioning coefficient (KD) database from string expressions.
Each expression in `KDs_expr_str` may reference `T_C`, `P_kbar`, `oxides`, and solution phase compositional variables using the syntax `[:phase_name]` (e.g., `[:liq].compVariables[1]`). These are resolved against the `gmin_struct` output at evaluation time.
Parameters
----------
el_name : Vector{String}
Names of the trace elements.
phase_name : Vector{String}
Names of the mineral phases.
KDs_expr_str : Union{Matrix{String}, Vector{String}}
Matrix (phases × elements) or vector of KD expressions as strings.
info : String, optional
Description or citation for the database (default: "Custom KDs database").
Returns
-------
db : custom_KDs_database
Compiled KD database ready for use in `TE_prediction`.MAGEMin_C.create_custom_KDs_database Method
create_custom_KDs_database(el_name, phase_name; info)
Create a KDs database with the given elements and phases, all KDs set to zero.
Useful when phases are known but partition coefficients are saturation-controlled.MAGEMin_C.create_custom_KDs_database Method
create_custom_KDs_database(el_name; info)
Create an elements-only KDs database with no phases. Phases (and zero KDs) are added
automatically by `_augment_KDs_for_saturation` when a `SaturationConfig` is provided
to `TE_prediction` or `solve_with_saturation`.MAGEMin_C.create_gmin_struct Method
create_gmin_struct(DB, gv, time; name_solvus=false, seismic_cor=false, aspect_ratio=0.3)
Extract the output of a pointwise MAGEMin optimization into a Julia structure.
Parameters
----------
DB : LibMAGEMin.Database
Database structure.
gv : LibMAGEMin.global_variables
Global variables structure.
time : Float64
Elapsed computation time [s].
name_solvus : Bool, optional
Resolve solvus naming (default: false).
seismic_cor : Bool, optional
If true, compute melt + anelastic corrected seismic velocities of the
solid aggregate (`Vp_cor`, `Vs_cor`) using [`wave_melt_correction`](@ref)
and [`anelastic_correction`](@ref) (default: false).
aspect_ratio : Float64, optional
Aspect ratio of the melt/pore geometry, passed to
[`wave_melt_correction`](@ref) when `seismic_cor=true` (default: 0.3).
seismic_water : Int, optional
Water content mode passed to [`anelastic_correction`](@ref) when `seismic_cor=true`:
`0` = dry mantle, `1` = damp mantle, `2` = wet mantle (default: 0).
filter_DEW_species : Bool, optional
If true, drop chemically infeasible species (those with `emFrac <= 1e-40`,
i.e. essentially exact zero) from the `DEW_S24` aqueous speciation phase's
per-endmember arrays (`emNames`, `molality`, `activity`, `emFrac`, `emFrac_wt`,
`emChemPot`, `emComp`, `emComp_wt`, `emComp_apfu`), rather than returning the
full ~100+ possible species regardless of whether the bulk composition can
actually form them. Only applies to the phase named "DEW_S24"; all other
solution phases are left untouched. Default: false (unchanged behavior).
Returns
-------
out : gmin_struct{Float64, Int64}
Structure containing the full minimization results.MAGEMin_C.create_light_gmin_struct Method
create_light_gmin_struct(DB, gv)
Extract a lightweight output of a pointwise MAGEMin optimization into a Julia structure (Float32/Int8 types).
Parameters
----------
DB : LibMAGEMin.Database
Database structure.
gv : LibMAGEMin.global_variables
Global variables structure.
Returns
-------
out : light_gmin_struct{Float32, Int8, String}
Lightweight structure containing essential minimization results.MAGEMin_C.create_light_gmin_struct_ig Method
create_light_gmin_struct_ig(DB, gv)
Extract a lightweight output of a pointwise MAGEMin optimization into a Julia structure (Float32/Int8 types).
Parameters
----------
DB : LibMAGEMin.Database
Database structure.
gv : LibMAGEMin.global_variables
Global variables structure.
Returns
-------
out : light_gmin_struct_ig{Float32, Int8, String}
Lightweight extended structure containing essential minimization results for igneous databases.MAGEMin_C.define_bulk_rock Method
define_bulk_rock(gv, bulk_in, bulk_in_ox, sys_in, db)
Define the bulk-rock composition in the global variables structure, converting it to the appropriate format for MAGEMin.
Parameters
----------
gv : LibMAGEMin.global_variables
Global variables structure.
bulk_in : AbstractVector{Float64}
Input bulk rock composition.
bulk_in_ox : Vector{String}
Oxide names corresponding to `bulk_in`.
sys_in : String
Input system units, "mol" or "wt".
db : String
Database identifier, e.g. "ig", "mp", "mb".
Returns
-------
gv : LibMAGEMin.global_variables
Updated global variables with normalized bulk rock composition.MAGEMin_C.exclude_DEW_species Method
exclude_DEW_species(dtb, species; shift=1.0e6)
Build a `gbase_data` override (see [`gbase_data`](@ref)) that keeps the named
DEW aqueous species out of the stable assemblage, even when they are
compositionally feasible for the current oxide set. Works by shifting each
named species' reference Gibbs energy by `+shift` kJ/mol (default matches
the `1.0e6` penalty MAGEMin's own C code already uses internally for
compositionally-infeasible DEW species - see `tc_gss_function.c`), applied
before pseudocompound generation - a real exclusion from the search space,
not a post-hoc output filter (contrast `filter_DEW_species`, which only
trims output).
Species names and their index within the DEW phase are resolved from
`retrieve_solution_phase_information(dtb)` (`db_infos`/`ss_infos`, the same
table `print_phase_info`/`remove_phases`/`select_phases` already use) - no
initialized database or prior minimization needed, so this can be called
right after picking a database name, before `Initialize_MAGEMin`.
Caveat: `db_infos`' species list/order for the DEW phase reflects that
database's own full/standard oxide list. If the minimization this override
is used in tracks a *narrower* `Xoxides` set (missing oxides the database
otherwise supports), some species earlier in the canonical DEW ordering
drop out and everything after them shifts index - so the resolved `em_id`
could point at the wrong species for that run. This is a non-issue for the
common case (`Xoxides` covering the database's usual oxide list); for a
deliberately reduced oxide set, verify afterward that the named species is
actually absent from the result (`out.SS_vec[i].emNames`/`emFrac`).
Parameters
----------
dtb : String
Database name (e.g. `"mp"`, `"ig"`, `"all"`) - same string passed to
`Initialize_MAGEMin`.
species : Union{String, Vector{String}}
DEW species name(s) to deactivate, e.g. `"HCOOH"` or `["HCOOH","CH3COOH"]`.
shift : Float64, optional
Additive Gibbs-energy penalty in kJ/mol (default: 1.0e6).
Returns
-------
gbase : Vector{gbase_data{Float64,Int64}}
Pass directly as `gbase=exclude_DEW_species(...)` to
`single_point_minimization`/`multi_point_minimization`/
`point_wise_minimization`. Combine with other overrides via `vcat`.
Examples
--------
```julia
excl = exclude_DEW_species("mp", ["HCOOH"])
data = Initialize_MAGEMin("mp", verbose=-1)
out = single_point_minimization(P, T, data; X=X, Xoxides=Xoxides, gbase=excl)
Finalize_MAGEMin(data)
```MAGEMin_C.finalize_MAGEMin Method
finalize_MAGEMin(gv, DB, z_b, splx_data)
Free the memory allocated by `init_MAGEMin`.
Parameters
----------
gv : global_variables
Global variables structure.
DB : Database
Thermodynamic database structure.
z_b : bulk_infos
Bulk rock information structure.
splx_data : TypeSplxData
Simplex levelling structure.
Returns
-------
nothingMAGEMin_C.fsp_sites Method
fsp_sites(wt)fsp_H21 — Holland et al. (2021), ternary feldspar. Sites: A(Na Ca K), TB*(Si Al with 1/4 entropy contribution). Normalised to 8 oxygens. TC variables: ca = xCaA = XAn, k = xKA = XOr. xAlTB = (1 + ca)/4, xSiTB = (3 - ca)/4
sourceMAGEMin_C.get_CO_KDs_database Method
get_CO_KDs_database()Build a custom_KDs_database using the lattice strain models of Cornet (2017) with Thermocalc a-x solution model site fractions (cpx_G23, g_G23, opx_G23, ol_H18, fsp_H21, hb_G16).
Requires lattice_strain.jl to be included before calling this function.
Element order (28 elements, fixed): Cs Rb K | Ba Sr | La…Lu Sc | Ti Hf Zr | U Th | Ta Nb
Phase names after mineral_classification that are handled: "cpx", "gt", "opx", "pl", "ol", "hb", "amp"
Returns a custom_KDs_database ready to pass directly to TE_prediction.
MAGEMin_C.get_MAGEMin_version Method
get_MAGEMin_version()
Version string of the MAGEMin C library actually loaded in this session, e.g.
"2.0.3 [11/11/2026]" - the `gv.version` the library reports, not a value baked into
the Julia package, so it stays truthful if `libMAGEMin` is swapped underneath.
Obtained from a single point minimization (metapelite database, predefined bulk 0,
4 kbar, 400 °C) through the regular `Initialize_MAGEMin` / `point_wise_minimization`
path, reading `out.MAGEMin_ver`. Memoised after the first call.
Returns
-------
version : String
The library's version string.MAGEMin_C.get_TE_database Function
get_TE_database(tedb="OL12")
Return the built-in trace element (TE) partitioning coefficient database.
Parameters
----------
tedb : String, optional
Database identifier (default: "OL12"). Valid options: "OL12" (Laurent, 2012),
"CO" (Cornet, lattice strain — see `get_CO_KDs_database`), "Yak25" (Yakymchuk,
Gareau & Williams 2025 Table S1 — see `get_Yak25_KDs_database`).
Returns
-------
db : custom_KDs_database
Trace element partitioning coefficient database containing element names, phase names, and partition coefficient expressions.MAGEMin_C.get_Warr_name Method
get_Warr_name(name)
Convert a MAGEMin mineral/endmember abbreviation to its IMA-CNMNC approved
symbol following Warr (2021).
Names with no official Warr equivalent (composite endmembers, model-specific
components, buffer assemblages, activities) are returned as `name * "*"` so
that downstream code always receives a plain `String` without special-casing.
Parameters
----------
name : String
MAGEMin internal phase or endmember name (e.g. `"ab"`, `"phl"`, `"q4L"`).
Returns
-------
symbol : String
Warr (2021) symbol (e.g. `"Ab"`, `"Phl"`) or `name * "*"` when not listed.
Reference
---------
Warr L.N. (2021) IMA-CNMNC approved mineral symbols.
Mineralogical Magazine 85, 291–320. doi:10.1180/mgm.2021.43MAGEMin_C.get_Warr_names Method
get_Warr_names(names)
Vectorised form of `get_Warr_name`: convert a vector of MAGEMin names to
their Warr (2021) symbols in one call. Entries with no mapping are returned
as `name * "*"`.
Parameters
----------
names : Vector{String}
Vector of MAGEMin phase or endmember names.
Returns
-------
symbols : Vector{String}
Corresponding Warr (2021) symbols.MAGEMin_C.get_Yak25_KDs_database Method
get_Yak25_KDs_database()Build a custom_KDs_database from Table S1 of Yakymchuk, Gareau & Williams (2025, J. Metamorphic Geol.) — mineral/melt Kd's for La, Ce, Pr, Nd, Sm, Eu, Gd, Y, Th, U across the full UHT-granulite assemblage plus the three accessory saturation phases (zircon, apatite, monazite), so that all of them compete for these elements through the ordinary Nernst partitioning in partition_TE, matching the worked-example spreadsheet's "Bulk Kd calcs" table.
Values are from Bédard (2006) unless noted; where Table S1 cites a different source (Taylor et al. 2015, Bea et al. 1994, Stepanov et al. 2012, Yakymchuk et al. 2018) that value is used instead. Quartz, sapphirine, sillimanite, and kyanite are set to 0.0001 for every element, per the paper's stated simplification. Magnetite and spinel share the paper's single "Mt / Sp" value since mineral_classification resolves the spinel-group solvus into "sp"/"smt" where Table S1 only distinguishes bulk oxide-mode.
Phase names after mineral_classification (dtb == "mp"/"mpe"/"mb"/"ume"/"mbe") that are handled: "g", "pl", "afs", "opx", "cd", "FeTiOx", "ru", "sp", "smt", "zrc", "fapt", "mnz", "q", "sa", "sill", "ky".
Returns a custom_KDs_database ready to pass directly to TE_prediction/ solve_with_saturation (with a SaturationConfig for Zr/P2O5/Mnz on top, since this only supplies the Nernst Kd's — the saturation-front modal abundances of zrc/fapt/mnz still come from zirconium_saturation/phosphate_saturation/ monazite_saturation as usual).
MAGEMin_C.get_all_stable_phases Method
get_all_stable_phases(out)
Collect the unique set of stable phase names across all minimization points.
Solution phases are sorted alphabetically and listed first; pure phases follow
in their own sorted block. For example:
`["amp", "bi", "chl", "cpx", "ep", "fl", "fsp", "liq", "opx", "sph", "q", "ru"]`
Parameters
----------
out : Union{Vector{gmin_struct{Float64, Int64}}, gmin_struct{Float64, Int64}}
MAGEMin minimization output for one or more points.
Returns
-------
ph_names : Vector{String}
Sorted unique phase names (solution phases first, then pure phases).
n_ss : Int64
Number of unique solution phases.
n_pp : Int64
Number of unique pure phases.MAGEMin_C.get_db Method
get_db(dtb)
Registry entry ([`db_registry`](@ref)) of database `dtb`. Throws if the acronym is
unknown - use [`is_db`](@ref) to test first.MAGEMin_C.get_db_label Method
get_db_label(dtb)
Human-readable name and reference of database `dtb` (`db_registry.db_info`).MAGEMin_C.get_db_list Method
get_db_list(; research_group=nothing)
Acronyms of every implemented thermodynamic database, in registry order, optionally
restricted to one research group ("tc", "sb", "gh" or "br").
Examples
--------
```julia
get_db_list() # all 18
get_db_list(research_group = "sb") # ["sb11", "sb21", "sb24"]
```MAGEMin_C.get_mineral_name Method
get_mineral_name(db, ss, SS_vec)
Return a mineralogically meaningful name for a solution phase based on its compositional variables (solvus disambiguation).
For solution phases that straddle a solvus (e.g., feldspar → plagioclase or alkali feldspar; spinel → spinel, magnetite, or ulvöspinel), the returned name reflects the dominant endmember rather than the generic solution phase label.
Parameters
----------
db : String
Database identifier (e.g., "ig", "igad", "mp", "mpe", "mb", "ume", "mbe").
ss : String
Solution phase short name (e.g., "fsp", "spl", "amp", "ilm").
SS_vec : LibMAGEMin.SS_data
Solution phase data structure containing `compVariables`.
Returns
-------
mineral_name : String
Disambiguated mineral name (e.g., "pl", "afs", "mgt", "ilm", "hem").MAGEMin_C.get_mineral_name_Warr Method
get_mineral_name_Warr(db, ss, SS_vec)
Return the Warr (2021) IMA-CNMNC symbol for the solvus-disambiguated name of
a solution phase. Internally calls `get_mineral_name` for solvus logic, then
maps the result through `get_Warr_name`.
Parameters
----------
db : String — database identifier (e.g. `"ig"`, `"mp"`).
ss : String — solution phase short name (e.g. `"fsp"`, `"amp"`).
SS_vec : LibMAGEMin.SS_data — solution phase data structure.
Returns
-------
symbol : String — Warr (2021) symbol, or the disambiguated name * "*"` if
no official symbol is defined.MAGEMin_C.get_molar_mass Method
get_molar_mass(oxide)
Retrieve the molar mass of a given oxide.
Parameters
----------
oxide : String
Name of the oxide (e.g., "SiO2", "Al2O3").
Returns
-------
molar_mass : Float64
Molar mass of the specified oxide [g/mol].MAGEMin_C.get_oxide_list Method
get_oxide_list(db::String)
Canonical oxide-name order for a given MAGEMin database, exactly as `gv.ox`
holds it on the C side. Read from `DB_OXIDES_GENERATED`
(`julia/db_infos_generated.jl`), which `gen/generate_db_infos.jl` harvests
from the compiled library and `test/test_db_infos.jl` re-checks against
`gv.ox` for every database.
Used by `convertBulk4MAGEMin` (bulk-rock reindexing) and by `init_MAGEMin`'s
`mu_fix_idx` oxide-name resolution (native mu-mu chemical-potential fixing).
Returns an empty vector, after printing a message, for an unknown database.MAGEMin_C.get_phase_oxide_support Function
get_phase_oxide_support(dtb="all")
Which oxides each phase of database `dtb` actually needs, i.e. the oxides that appear
with a non-zero coefficient in the composition of at least one of its end-members
(solution phases) or in its own composition (pure phases).
Use it to tell which phases can survive a reduced `Xoxides` set: a phase whose support
contains an oxide the caller is not tracking cannot be stable and is worth
deactivating up front (see `remove_phases`/`select_phases`).
This is a property of the thermodynamic model, not of any bulk composition, P or T, so
it is harvested from the library at build time into `DB_PHASE_OXIDES_GENERATED`
(`julia/db_infos_generated.jl`) and read back here as a table lookup - no initialized
database needed. `test/test_db_infos.jl` re-harvests it and fails on drift.
Parameters
----------
dtb : String, optional
Database acronym (default: "all", the union database, which covers every phase of
the "tc" research group).
Returns
-------
support : Dict{String, Set{String}}
Phase name (as `gv.SS_list`/`gv.PP_list` spell it: the short name for every
database except "all", where it carries the citation tag) to the set of oxide
names it needs.
Examples
--------
```julia
sup = get_phase_oxide_support("all")
sup["liq_W14"] # oxides the metapelite melt model needs
keep = [p for (p,ox) in sup if ox ⊆ Set(Xoxides)]
```MAGEMin_C.get_research_group Method
get_research_group(dtb)
Research group ("tc", "sb", "gh" or "br") database `dtb` belongs to.MAGEMin_C.get_ss_from_mineral Function
get_ss_from_mineral(db, mrl, mbCpx, active_ss=String[])
Return the solution phase name corresponding to a disambiguated mineral name (inverse of `get_mineral_name`).
For `db == "all"`, some generic mineral names are ambiguous: several solution-phase models
disambiguate to the same mineral name (e.g., `ilm_T21`, `ilm_W24`, and `ilm_W00` all disambiguate
to "ilm"/"hem"; `cpx_T21` and `cpx_W24` both disambiguate to "cpx"/"pig"/"Na-cpx"). When `active_ss`
is supplied (e.g., the list of solution phases actually available/used in the current database
configuration or computation), the first matching candidate is returned; otherwise a fixed default
is used for backward compatibility. For `db == "all"` mineral names with no dedicated solvus rule
(e.g. "opx", "ol"), `active_ss` is searched for an entry whose prefix before "_" equals `mrl`, so the
exact underlying solution-phase name (including its dataset tag) is recovered whenever available.
Parameters
----------
db : String
Database identifier (e.g., "ig", "igad", "mp", "mpe", "mb", "ume", "mbe").
mrl : String
Disambiguated mineral name (e.g., "pl", "afs", "mgt", "hem", "omph").
mbCpx : Int64
Metabasite clinopyroxene model flag. Controls whether omphacite/diopside maps to "dio" (0) or "aug" (1).
active_ss : AbstractVector{<:AbstractString}
Optional list of solution phase names to disambiguate against when a mineral name maps to
more than one candidate solution phase (only relevant for `db == "all"`). Defaults to empty.
Returns
-------
ss : String
Solution phase short name (e.g., "fsp", "spl", "amp", "ilm").MAGEMin_C.gt_sites Method
gt_sites(wt)g_G23 — Green et al. (in prep), after Holland et al. (2018). Sites: M1(Mg Fe Ca) dodecahedral, M2(Al Cr Fe³⁺ Mg Ti) octahedral. Normalised to 12 oxygens. TC composition variables: c = xCaM1 (= XGr), x = xFeM1/(xFeM1+xMgM1) = Fe/(Fe+Mg). Note: TC labels the dodecahedral site M1 and octahedral site M2; xAlM2 ≈ 1 for typical igneous garnets.
sourceMAGEMin_C.harvest_db_infos Method
harvest_db_infos(dtb)
Build the [`db_infos`](@ref) of database `dtb` by reading the phase inventory out of
the compiled library, rather than from the committed `DB_INFOS_GENERATED` table.
Initializes the database, computes the reference Gibbs energies at one arbitrary
(P,T) - which is what populates `SS_ref.fName`/`EM_list`/`CV_list`/`SF_list` on the
C side - reads everything back, then frees it again. Roughly 10 ms per database.
This is the source `gen/generate_db_infos.jl` writes `julia/db_infos_generated.jl`
from, and the reference `test/test_db_infos.jl` checks that file against. Normal
callers want `retrieve_solution_phase_information`, which is a table lookup.
Parameters
----------
dtb : String
Database acronym, e.g. "mp", "ig", "sb21".
Returns
-------
db_inf : db_infos
Freshly harvested database information.MAGEMin_C.harvest_default_dataset Method
harvest_default_dataset(dtb)
End-member dataset (`gv.EM_dataset`) the library falls back to for database `dtb`
when none is requested. Reference against which `test/test_db_infos.jl` checks
`db_registry.db_dataset` for the "tc" research group.MAGEMin_C.harvest_em_compositions Method
harvest_em_compositions(dtb)
Composition of every end-member and pure phase of database `dtb`, expressed in
[`EM_COMP_BASIS`](@ref), read from the reference database's `SS_ref.Comp` /
`PP_ref.Comp` after one reference-Gibbs-energy evaluation.
Note that the same abbreviation can denote genuinely different components in different
databases (`cfm`, `ab`, `hem`, `sp`, ... - see the `_ambiguous_` list the generator
writes into `em_name.json`), so compositions are only comparable within one database.
Returns
-------
comps : Dict{String, Vector{Float64}}
Name to its composition, one entry per `EM_COMP_BASIS` oxide.MAGEMin_C.harvest_oxide_list Method
harvest_oxide_list(dtb)
Oxide names of database `dtb` read straight out of `gv.ox`, in the order the C side
expects a bulk-rock array in. Reference against which `test/test_db_infos.jl` checks
`get_oxide_list`.MAGEMin_C.harvest_phase_oxide_support Method
harvest_phase_oxide_support(dtb; eps=1e-8)
Which oxides each phase of database `dtb` needs, read straight out of the reference
database's composition arrays (`SS_ref.Comp` for every end-member of a solution
phase, `PP_ref.Comp` for a pure phase) after one reference-Gibbs-energy evaluation.
This is what `gen/generate_db_infos.jl` writes `DB_PHASE_OXIDES_GENERATED` from, and
the reference `test/test_db_infos.jl` checks that table against. Normal callers want
[`get_phase_oxide_support`](@ref), which is a table lookup.MAGEMin_C.has_dataset_choice Method
has_dataset_choice(dtb)
Whether the end-member dataset can be chosen for database `dtb`. Only the "tc"
research group offers a choice (`available_TC_ds`); the others pin the dataset to
the database itself, so a dataset selector should be hidden for them.MAGEMin_C.health_check_TE Method
health_check_TE(C0, KDs_database)
Validate that the initial composition vector and KD database are consistent before running TE partitioning.
Parameters
----------
C0 : Vector{Float64}
Initial bulk trace element composition [ppm].
KDs_database : custom_KDs_database
KD database to validate against `C0`.
Returns
-------
status : Int64
1 if all checks pass, 0 if any check fails (errors are also thrown).MAGEMin_C.init_MAGEMin Function
init_MAGEMin(db="ig"; verbose=0, dataset=nothing, mbCpx=0, mbIlm=0, mpSp=0, mpIlm=0, ig_ed=0, limitCaOpx=0, CaOpxLim=1.0, buffer="NONE", solver=0)
Initialize MAGEMin (including setting global options) and load the database for a single thread.
Parameters
----------
db : String, optional
Database name (default: "ig").
verbose : Union{Int64, Bool}, optional
Verbosity level (default: 0).
dataset : Union{Nothing, Int}, optional
Dataset identifier (default: nothing).
mbCpx : Int64, optional
Metabasite clinopyroxene model flag (default: 0).
mbIlm : Int64, optional
Metabasite ilmenite model flag (default: 0).
mpSp : Int64, optional
Metapelite spinel model flag (default: 0).
mpIlm : Int64, optional
Metapelite ilmenite model flag (default: 0).
ig_ed : Int64, optional
Igneous extended database flag (default: 0).
limitCaOpx : Int64, optional
Flag to limit Ca in orthopyroxene (default: 0).
CaOpxLim : Float64, optional
Ca limit value for orthopyroxene (default: 1.0).
buffer : String, optional
Buffer type (default: "NONE").
mu_fix_idx : Vector{String}, optional
Oxide names (e.g. `["MgO","K2O"]`) whose chemical potential should be
fixed directly (native mu-mu mechanism), instead of solved for from
the bulk composition. Resolved against this database's canonical
oxide order; an unknown name errors immediately. Structural for the
whole diagram/grid (like `buffer`) - the per-point target values are
passed separately as `mu_fix_val` to `point_wise_minimization`/
`multi_point_minimization`. Each fixed oxide's bulk content must be
set generously in excess of what its target implies (same
requirement `buffer`/`buffer_n` already has) - see
`point_wise_minimization`'s `mu_fix_val` docs (default: `String[]`,
i.e. off).
solver : Int64, optional
Solver type (default: 0).
Returns
-------
gv : global_variables
Global variables structure.
z_b : bulk_infos
Bulk rock information structure.
DB : Database
Thermodynamic database structure.
splx_data : simplex_data
Simplex data structure.MAGEMin_C.initialize_AMR Method
initialize_AMR(Xrange, Yrange, igs)
Create an initial uniform quadrilateral grid for Adaptive Mesh Refinement.
The grid has `2^igs` cells per dimension, covering the rectangular domain defined by `Xrange` and `Yrange`.
Parameters
----------
Xrange : Union{Tuple{Float64,Float64}, Vector{Float64}}
X-axis bounds of the domain [Xmin, Xmax].
Yrange : Union{Tuple{Float64,Float64}, Vector{Float64}}
Y-axis bounds of the domain [Ymin, Ymax].
igs : Int64
Initial subdivision level; produces `2^igs × 2^igs` cells.
Returns
-------
data : AMR_data
Initialized AMR data structure with the uniform grid.MAGEMin_C.lm_convert Method
lm_convert(gv, z_b, DB, ph_name, gamma, xeos)
Run MAGEMin's own per-model local minimization (NLopt) for one solution
phase, starting from a given compositional-variable guess (`xeos`) and
with that phase's endmembers' reference energies rotated against a
caller-supplied Gamma (`gamma`) - the C-side `LM_convert_function`, the
same `rotate_hyperplane` + `NLopt_opt` + `PC_function` +
`SS_UPDATE_function` pipeline `ss_min_PGE`/`ss_min_LP` run internally
during a full equilibrium solve, but for a single phase driven by an
externally-supplied Gamma instead of the solver's own, and without
restricting the search hypervolume (uses the phase's full bounds).
Intended for thermodynamic database inversion/calibration workflows:
given a candidate Gamma (e.g. from a previous equilibrium solve, or a
trial value under test), find each solution model's own locally stable
composition/energy against that Gamma directly, without running a full
multi-phase equilibrium solve.
Currently only supported for the "tc" (THERMOCALC) research group, i.e.
any of MAGEMin's THERMOCALC-derived databases ("ig", "igd", "igad",
"mp", "mb", "um", ... or the combined "all" database).
Parameters
----------
gv : LibMAGEMin.global_variables
Global variables structure (from `Initialize_MAGEMin`/`init_MAGEMin`).
z_b : LibMAGEMin.bulk_infos
`z_b.P`/`z_b.T` must already match the P-T at which `DB.SS_ref_db`'s
endmember reference energies were computed (via `pwm_init`/
`LibMAGEMin.ComputeG0_point`, not by this function).
DB : LibMAGEMin.Database
Database structure (from `Initialize_MAGEMin`/`init_MAGEMin`).
ph_name : String
Solution phase name as it appears in `gv.SS_list` (e.g. `"fsp_H22"`).
gamma : Vector{Float64}
Chemical potential of each component, length `gv.len_ox`, in the
same order as `gv.ox` (same convention as `gv.gam_tot`).
xeos : Vector{Float64}
Starting guess for the phase's compositional variables, length
matching the phase's `n_xeos` (see `.CV_list`/`.n_xeos` on the
returned struct, or on the phase's entry in `DB.SS_ref_db`).
Returns
-------
SS_ref_db : LibMAGEMin.SS_ref
The phase's reference struct after local minimization:
- `.xeos`/`.p` - the minimized compositional variables/endmember
fractions.
- `.df` - the phase's Gibbs energy [kJ/mol] at that composition,
relative to the supplied `gamma` hyperplane.
- `.status` - the NLopt return status (`3` = converged; anything
else means the local minimization did not converge cleanly).
- `.sf_ok`/`.sum_xi`/`.xi_em`/`.ss_comp` - as in `pc_convert`.
Examples
--------
```julia
gv, z_b, DB, splx_data = init_MAGEMin("all");
gv = use_predefined_bulk_rock(gv, 0, "all") # see p2x_convert's notes
gv, z_b, DB, splx_data = pwm_init(2.0, 700.0, gv, z_b, DB, splx_data);
gamma = zeros(gv.len_ox) # e.g. from a previous equilibrium solve
xeos = [0.3, 0.3, 0.4] # starting guess, length n_xeos for "fsp_H22"
SS_ref_db = lm_convert(gv, z_b, DB, "fsp_H22", gamma, xeos)
println(SS_ref_db.xeos, SS_ref_db.df)
```MAGEMin_C.logish Method
logish(x)
Safe natural logarithm that returns 0.0 for non-positive inputs instead of `-Inf` or `NaN`.
Parameters
----------
x : Float64
Input value.
Returns
-------
Float64
`log(x)` if `x > 0`, otherwise `0.0`.MAGEMin_C.make_composition Method
make_composition(names, wt; Fe2O3=0.0) -> NamedTupleBuild the oxide wt% NamedTuple expected by every D_* and *_sites function from parallel vectors of oxide names and wt% values.
Names recognised (case-sensitive): "SiO2" "TiO2" "Al2O3" "FeO" "MnO" "MgO" "CaO" "Na2O" "K2O" "H2O"
Any oxide not listed defaults to 0.0.
If your analysis reports total iron as Fe₂O₃, pass Fe2O3=<wt%> and it is converted to FeO-equivalent (×0.8998) and added to any existing "FeO" entry.
Example
oxides = ["SiO2","TiO2","Al2O3","FeO","MgO","CaO","Na2O"]
cpx = make_composition(oxides, [50.45, 1.45, 6.30, 9.38, 13.53, 18.10, 0.70])
melt = make_composition(
["SiO2","TiO2","Al2O3","FeO","MgO","CaO","Na2O","K2O","H2O"],
[67.67, 1.27, 15.30, 2.79, 1.39, 4.17, 3.13, 1.94, 13.8])
D = D_cpx(1273.0, 1.0, melt, cpx)MAGEMin_C.mineral_classification Method
mineral_classification(out, dtb)
Classify the stable phases from a MAGEMin minimization result into mineralogical names compatible with the trace element partitioning coefficient database.
Solution phases that straddle a solvus (e.g., feldspar, spinel, ilmenite) are disambiguated using their compositional variables. Duplicate phases resulting from solvus splitting are merged by summing their weight fractions.
Parameters
----------
out : MAGEMin_C.gmin_struct{Float64, Int64}
MAGEMin minimization output structure.
dtb : String
Database identifier (e.g., "ig", "igad", "mp", "mpe", "mb", "ume", "mbe").
Returns
-------
ph : Vector{String}
Classified phase names compatible with the TE partitioning database.
ph_wt : Vector{Float64}
Weight fractions corresponding to each phase.MAGEMin_C.mol2wt Method
mol2wt(bulk_mol, bulk_ox)
Convert bulk-rock composition from molar fraction to weight fraction.
Parameters
----------
bulk_mol : AbstractVector{Float64}
Bulk rock composition in molar fraction.
bulk_ox : AbstractVector{String}
Oxide names corresponding to `bulk_mol`.
Returns
-------
bulk_wt : Vector{Float64}
Bulk rock composition in weight fraction (normalized to 100).MAGEMin_C.monazite_saturation Function
monazite_saturation(out, X_mnz_LREE=1.0; model="Stepanov12")
Compute the ΣLREE (La+Ce+Pr+Nd+Sm) saturation concentration in the melt phase [ppm].
Parameters
----------
out : MAGEMin_C.gmin_struct{Float64, Int64}
MAGEMin minimization output (must contain a melt phase).
X_mnz_LREE : Float64, optional
Molar ratio of LREE to all cations (LREE, Y, Th, U) in monazite (default: 1.0, i.e. no Y/Th/U substitution).
For "Montel93" this doubles as X_REEPO4, Montel's mole fraction of REE-phosphate end-member in monazite —
the two are treated as equivalent here rather than tracked as separate composition variables.
model : String, optional
Saturation model (default: "Stepanov12"). Valid options:
- "Stepanov12" — Stepanov et al. (2012), following the worked-example spreadsheet
of Yakymchuk et al. (2025) exactly: a sqrt(wt%H2O) term and a log10(X_mnz_LREE)
term inside exp(...) (the spreadsheet mixes log bases; reproduced verbatim here
rather than the ln-based form given in that paper's supplementary text).
- "Montel93" — Montel (1993), Chem. Geol. 110, 127-146, Eq. 1:
ln(REEt/X_REEPO4) = 9.50 + 2.34·D + 0.3879·√(wt%H2O) − 13318/T, with
REEt = Σ REEᵢ(ppm)/atomic_weightᵢ over La-Gd excluding Eu, D = (Na+K+Li+2Ca)/Al · 1/(Al+Si)
(dry cation mole fractions). No pressure term (Montel found P has little/no effect).
Adapted here to this codebase's La+Ce+Pr+Nd+Sm (dropping Gd) ΣLREE-ppm convention rather
than the paper's own La-Gd-excl-Eu molar sum, so it can plug into the same pipeline as the
other models: REEt is still computed as a genuine molar sum of the tracked LREE (preserving
the calibration), then converted back to a ppm-equivalent using the mean La-Sm atomic mass
(~142.9 g/mol) — a disclosed approximation, not a literal reproduction of the paper's own units.
- "Maimaiti19" — Maimaiti et al. (2019), Eur. J. Mineral. 31(1), 49-59:
ln ΣLREE = 12.77 + 1.52·M + 0.44·√(wt%H2O) − 9934/T − 36.79·(P_kbar/T) + ln(X_mnz_LREE),
ΣLREE = La-Sm ppm sum (same convention as "Stepanov12"), M = (Na+K+2Ca)/(Al·(Al+Si))
(dry cation mole fractions, same form used for "Montel93" with Li omitted). Calibrated over
a broader peraluminous-to-peralkaline range than Stepanov (2012)'s UHT-metapelite dataset.
Returns
-------
C_LREE_liq : Float64
ΣLREE saturation concentration in the melt [ppm], or -1 if no melt is present.MAGEMin_C.multi_point_minimization Method
multi_point_minimization(P, T, MAGEMin_db; X=nothing, ...)
Matrix overload for 2D model grids. `P` and `T` are matrices of the same
size (e.g. `(nx, ny)`) representing a spatial grid of pressures [kbar] and
temperatures [°C]. They are flattened internally, computed in parallel, and
the results are returned as a matrix of the same shape.
The bulk-rock composition `X` can be:
- `nothing` (use a built-in test case, set via `test=`)
- `Vector{Float64}` of length `noxides` — same composition for every node
- `Matrix{Float64}` of size `(nx*ny, noxides)` — per-node composition,
where row `i` corresponds to the linearised index of the grid
All other keyword arguments are forwarded to the vector-based method.
Examples
--------
```julia
data = Initialize_MAGEMin("ig", verbose=false);
Xoxides = ["SiO2","Al2O3","CaO","MgO","FeO","Fe2O3","K2O","Na2O","TiO2","Cr2O3","H2O"]
X = [48.43, 15.19, 11.57, 10.13, 6.65, 1.64, 0.59, 1.87, 0.68, 0.0, 3.0]
# 2-D P-T grid (uniform bulk)
P_grid = [8.0 9.0; 10.0 11.0] # (2×2)
T_grid = [800.0 850.0; 900.0 950.0]
out = multi_point_minimization(P_grid, T_grid, data, X=X, Xoxides=Xoxides, sys_in="wt")
# out is a (2×2) Matrix{gmin_struct}
Finalize_MAGEMin(data)
```MAGEMin_C.multi_point_minimization Method
multi_point_minimization(P, T, MAGEMin_db; light=false, name_solvus=false, fixed_bulk=false, calibration=false, test=0, X=nothing, B=nothing, G=nothing, scp=0, dT=2.0, iguess=false, rm_list=nothing, W=nothing, gbase=nothing, Xoxides=Vector{String}, sys_in="mol", rg="tc", progressbar=true, callback_fn=nothing, callback_int=1)
Perform (parallel) MAGEMin calculations for a range of points as a function of pressure, temperature and/or composition.
The bulk-rock composition can either be set to be one of the pre-defined build-in test cases, or can be specified specifically by passing `X`, `Xoxides` and `sys_in`.
Parameters
----------
P : AbstractVector{Float64}
Pressure vector [kbar].
T : AbstractVector{Float64}
Temperature vector [°C].
MAGEMin_db : MAGEMin_Data
Initialized MAGEMin data structure.
light : Bool, optional
If true, return a light output structure (default: false).
name_solvus : Bool, optional
If true, rename phases with solvus names (default: false).
fixed_bulk : Bool, optional
calibration : Bool, optional
When true, after the normal solve also locally minimizes every structurally-feasible-but-not-stable
solution phase and appends non-duplicate results to `out.mSS_vec`, tagged `info="calib"`. Default false.
If true, use fixed bulk composition (default: false).
test : Int64, optional
Build-in test case number (default: 0).
X : VecOrMat, optional
Bulk rock composition(s). Single vector for all points, or vector of vectors for per-point composition (default: nothing).
B : Union{Nothing, Vector{Float64}}, optional
Buffer values per point (default: nothing).
G : Union{Nothing, Vector{LibMAGEMin.mSS_data}, Vector{Vector{LibMAGEMin.mSS_data}}}, optional
Initial guess data (default: nothing).
scp : Int64, optional
Sub-solidus computation parameter (default: 0).
dT : Float64, optional
Temperature increment for sub-solidus detection (default: 2.0).
iguess : Union{Vector{Bool}, Bool}, optional
Whether to use initial guess (default: false).
rm_list : Union{Nothing, Vector{Int64}}, optional
List of phase indexes to remove (default: nothing). Mutually exclusive with
`pp_list`/`ss_list`.
pp_list : Union{Nothing, Vector{String}}, optional
Pure phases to keep active; every other pure phase is deactivated (default: nothing,
i.e. no pure-phase selection). See [`select_phases`](@ref). Mutually exclusive with
`rm_list`. The buffer/activity pure phases in `ALWAYS_ACTIVE_PP` never need to be
listed - they remain governed by `buffer="..."` regardless.
ss_list : Union{Nothing, Vector{String}}, optional
Solution phases to keep active; every other solution phase is deactivated (default:
nothing, i.e. no solution-phase selection). See [`select_phases`](@ref). Mutually
exclusive with `rm_list`.
W : Union{Nothing, Vector{W_data{Float64, Int64}}}, optional
Overriding Margules parameters (default: nothing).
gbase : Union{Nothing, Vector{gbase_data{Float64, Int64}}}, optional
Additive shifts to endmember reference Gibbs energies (default: nothing).
Xoxides : Vector{String}
Oxide names corresponding to `X`.
sys_in : String, optional
Input system units, "mol" or "wt" (default: "mol").
rg : String, optional
Research group, "tc" or "sb" (default: "tc").
progressbar : Bool, optional
Show progress bar (default: true).
seismic_cor : Bool, optional
If true, compute melt + anelastic corrected seismic velocities of the
solid aggregate (`Vp_cor`, `Vs_cor`) (default: false).
aspect_ratio : Float64, optional
Aspect ratio of the melt/pore geometry, used when `seismic_cor=true` (default: 0.3).
seismic_water : Int, optional
Water content mode passed to [`anelastic_correction`](@ref) when `seismic_cor=true`:
`0` = dry mantle, `1` = damp mantle, `2` = wet mantle (default: 0).
callback_fn : Union{Nothing, Function}, optional
Callback function called periodically (default: nothing).
callback_int : Int64, optional
Callback interval in number of points (default: 1).
Returns
-------
Out_PT : Vector{gmin_struct{Float64, Int64}} or Vector{light_gmin_struct{Float32, Int8}}
Vector of minimization results for each P-T point.
Examples
--------
```julia
data = Initialize_MAGEMin("ig", verbose=false);
n = 10
P = rand(8:40.0,n)
T = rand(800:1500.0,n)
out = multi_point_minimization(P, T, data, test=0)
Finalize_MAGEMin(data)
```MAGEMin_C.ol_sites Method
ol_sites(wt)ol_H18 — Holland et al. (2018). Sites: M1(Mg Fe), M2(Mg Fe Ca). Normalised to 4 oxygens. TC variables: x = Fe/(Fe+Mg), c = xCaM2, Q=0. xMgM1 = 1-x, xFeM1 = x, xMgM2 = 1-c-x, xFeM2 = x*(1-c), xCaM2 = c
sourceMAGEMin_C.opx_sites Method
opx_sites(wt)opx_G23 — Green et al. (in prep), after Holland et al. (2018). Sites: T*(Si Al), M1(Mg Fe Al Fe³⁺ Cr Ti), M2(Ca Na Mg Fe). Normalised to 6 oxygens. TC composition variables: y = 2·xAlT, c = xCaM2, j = xNaM2, x = Fe/(Fe+Mg), Q=0.
sourceMAGEMin_C.p2x_convert Method
p2x_convert(gv, DB, ph_name, p)
Convert endmember fractions to compositional variables (xeos) for one
solution phase, via MAGEMin's own per-model P2X conversion (the C-side
`P2X_convert_function`, itself a thin wrapper around whatever `p2x_*`
function that model is registered with). Intended for thermodynamic
database inversion/calibration workflows, alongside `pc_convert` -
given a phase composition (e.g. from an EPMA analysis converted to
endmember fractions) and a target P-T, this pair lets you evaluate that
phase's Gibbs energy directly, without running a full multi-phase
equilibrium solve.
Parameters
----------
gv : LibMAGEMin.global_variables
Global variables structure (from `Initialize_MAGEMin`/`init_MAGEMin`).
DB : LibMAGEMin.Database
Database structure (from `Initialize_MAGEMin`/`init_MAGEMin`).
ph_name : String
Solution phase name as it appears in `gv.SS_list` (e.g. `"fsp_H22"`).
p : Dict{String, Float64}
Endmember fraction for each of the phase's endmembers, keyed by
name (e.g. `Dict("ab"=>0.2,"an"=>0.2,"san"=>0.6)` for `"fsp_H22"`,
whose endmembers are albite/anorthite/sanidine) - must cover every
endmember MAGEMin registers for that model, or this errors; the
endmember names/order for a given phase can be read from the
returned struct's `.EM_list`/`.n_em`. Not required to sum to
exactly 1 for MAGEMin to accept it, but should for the result to be
physically meaningful.
Returns
-------
SS_ref_db : LibMAGEMin.SS_ref
The phase's reference struct with `.p`/`.iguess`/`.xeos` set to the
requested composition - pass this directly into `pc_convert` next
(its `.EM_list`/`.CV_list`/`.n_em`/`.n_xeos` describe what's in
`.p`/`.xeos`, for inspection).
Notes
-----
Some models pin an endmember's compositional variable(s) to a fixed
value when the relevant oxide is absent from the current bulk-rock
composition (e.g. `"fsp_H22"` pins `ca`/`k` to 0 or 1 when `CaO`/`K2O`/
`Na2O` are zero, to keep the ternary feldspar simplex non-degenerate) -
these bounds are (re-)computed from the bulk composition set on `gv`/
`z_b` at the time `pwm_init`/`ComputeG0_point` last ran, so set a
realistic bulk rock (e.g. via `use_predefined_bulk_rock` or
`define_bulk_rock`) *before* that call, or `p2x_convert` may clamp the
requested fractions to a degenerate range instead of converting them.
Examples
--------
```julia
gv, z_b, DB, splx_data = init_MAGEMin("all");
gv = use_predefined_bulk_rock(gv, 0, "all") # or define_bulk_rock(...)
p = Dict("ab"=>0.2, "an"=>0.2, "san"=>0.6)
SS_ref_db = p2x_convert(gv, DB, "fsp_H22", p)
```MAGEMin_C.partition_TE Method
partition_TE(KDs_database, out, C0, ph, ph_wt, liq_wt; norm_TE=true)
Apply the batch melting equation to partition trace elements between melt and solid phases for the subset of phases present in both the MAGEMin output and the KD database.
Parameters
----------
KDs_database : custom_KDs_database
Compiled KD database.
out : MAGEMin_C.gmin_struct{Float64, Int64}
MAGEMin minimization output used to evaluate P-T-composition-dependent KDs.
C0 : Vector{Float64}
Initial bulk trace element composition [ppm].
ph : Vector{String}
Phase names from `mineral_classification`.
ph_wt : Vector{Float64}
Weight fractions of each phase.
liq_wt : Float64
Melt weight fraction.
norm_TE : Bool, optional
Normalize phase fractions to the phases present in the KD database (default: true).
Returns
-------
Cliq : Vector{Float64}
Trace element concentrations in the melt [ppm].
Cmin : Matrix{Float64}
Trace element concentrations in each mineral phase [ppm] (phases × elements).
Csol : Vector{Float64}
Trace element concentrations in the bulk solid [ppm].
ph_TE : Vector{String}
Names of phases included in the calculation.
ph_wt_norm : Vector{Float64}
Normalized solid phase weight fractions.
liq_wt_norm : Float64
Normalized melt weight fraction.
bulk_D : Float64
Bulk partition coefficient.MAGEMin_C.pc_convert Method
pc_convert(gv, z_b, DB, ph_name, SS_ref_db)
Given a solution phase's compositional variables (from `p2x_convert`)
and P-T-dependent endmember reference energies already computed on
`DB.SS_ref_db` (e.g. via `pwm_init(P, T, gv, z_b, DB, splx_data)` or
`LibMAGEMin.ComputeG0_point` directly), compute that phase's Gibbs
energy at that composition - MAGEMin's own `PC_function` +
`SS_UPDATE_function` pipeline (the C-side `PC_convert_function`), the
same one used internally during a normal minimization, evaluated
against the phase's absolute (non-Gamma-rotated) reference energies -
i.e. an absolute molar Gibbs energy, not a value relative to some other
phase assemblage's chemical potentials.
Parameters
----------
gv : LibMAGEMin.global_variables
z_b : LibMAGEMin.bulk_infos
`z_b.P`/`z_b.T` must already match the P-T the reference energies in
`DB.SS_ref_db` were computed at (set via `pwm_init`/
`ComputeG0_point`, not by this function).
DB : LibMAGEMin.Database
ph_name : String
Solution phase name, as passed to `p2x_convert`.
SS_ref_db : LibMAGEMin.SS_ref
The struct returned by `p2x_convert` for the same phase.
Returns
-------
SS_ref_db : LibMAGEMin.SS_ref
Updated struct:
- `.df` - the phase's Gibbs energy [kJ/mol] at the given
composition and P-T (this is what the workflow wants).
- `.ss_comp` (length `gv.len_ox`) - the phase's bulk composition
(oxide amounts per formula unit) at this `p`.
- `.sf_ok` - `1` if all site fractions are physically valid at this
composition, `0` otherwise (e.g. a fraction outside `[0,1]`).
- `.sum_xi`/`.xi_em` - phase-fraction-expression terms (PGE
internals), populated but not generally needed by this workflow.
`SS_ref` has no `.entropy`/`.enthalpy`/`.rho`/`.bulkMod`/
`.shearMod` fields at all, and while `.phase_density`/`.volume`/
`.mass` do exist on the struct, this pipeline does not compute
them (that requires the separate density/volume/modulus step run
during a full minimization) - reading them here returns stale or
uninitialized data, not a value for this composition.
Examples
--------
```julia
gv, z_b, DB, splx_data = init_MAGEMin("all");
gv = use_predefined_bulk_rock(gv, 0, "all") # see p2x_convert's notes
gv, z_b, DB, splx_data = pwm_init(2.0, 700.0, gv, z_b, DB, splx_data);
p = Dict("ab"=>0.2, "an"=>0.2, "san"=>0.6)
SS_ref_db = p2x_convert(gv, DB, "fsp_H22", p)
SS_ref_db = pc_convert(gv, z_b, DB, "fsp_H22", SS_ref_db)
println(SS_ref_db.df) # Gibbs energy
```MAGEMin_C.phosphate_saturation Method
phosphate_saturation(out; model="Klein26")
Compute the P₂O₅ saturation concentration in the melt phase [ppm].
Parameters
----------
out : MAGEMin_C.gmin_struct{Float64, Int64}
MAGEMin minimization output (must contain a melt phase with a "liq" solution phase).
model : String, optional
Saturation model (default: "Klein26"). Valid options:
- "Klein26" — Klein et al. (2026)
- "HWBea92" — Harrison & Watson (1984) + correction from Bea et al. (1992); for hydrous systems
- "Tollari06" — Tollari et al. (2006); calibrated for dry systems
Returns
-------
C_P2O5_liq : Float64
P₂O₅ saturation concentration in the melt [ppm], or -1 if the model is unrecognized.MAGEMin_C.point_wise_metastability Method
point_wise_metastability(out, P, T, gv, z_b, DB, splx_data)
Compute the metastability of the solution phases from a previous minimization result at new pressure and temperature conditions.
Parameters
----------
out : gmin_struct{Float64, Int64}
Output structure from a previous MAGEMin minimization.
P : Float64
Pressure [kbar].
T : Float64
Temperature [°C].
gv : LibMAGEMin.global_variables
Global variables structure.
z_b : LibMAGEMin.bulk_infos
Bulk rock information structure.
DB : LibMAGEMin.Database
Database structure.
splx_data : LibMAGEMin.simplex_datas
Simplex data structure.
seismic_cor : Bool, optional
If true, compute melt + anelastic corrected seismic velocities of the
solid aggregate (`Vp_cor`, `Vs_cor`) (default: false).
aspect_ratio : Float64, optional
Aspect ratio of the melt/pore geometry, used when `seismic_cor=true` (default: 0.3).
seismic_water : Int, optional
Water content mode passed to [`anelastic_correction`](@ref) when `seismic_cor=true`:
`0` = dry mantle, `1` = damp mantle, `2` = wet mantle (default: 0).
Returns
-------
out : gmin_struct{Float64, Int64}
Structure containing the metastability results at the new P-T conditions.
Examples
--------
```julia
using MAGEMin_C
data = Initialize_MAGEMin("mp", verbose=-1; solver=0);
P, T = 6.0, 630.0
Xoxides = ["SiO2"; "TiO2"; "Al2O3"; "FeO"; "MnO"; "MgO"; "CaO"; "Na2O"; "K2O"; "H2O"; "O"];
X = [58.509, 1.022, 14.858, 4.371, 0.141, 4.561, 5.912, 3.296, 2.399, 10.0, 0.0];
sys_in = "wt"
out = single_point_minimization(P, T, data, X=X, Xoxides=Xoxides, sys_in=sys_in)
Pmeta, Tmeta = 6.0, 500.0
out2 = point_wise_metastability(out, Pmeta, Tmeta, data)
```MAGEMin_C.point_wise_minimization Method
point_wise_minimization(P, T, gv, z_b, DB, splx_data; light=false, name_solvus=false, fixed_bulk=false, calibration=false, buffer_n=0.0, Gi=nothing, scp=0, dT=2.0, iguess=false, rm_list=nothing, W=nothing, gbase=nothing, seismic_cor=false, aspect_ratio=0.3)
Compute the stable mineral assemblage at given pressure and temperature for a specified bulk rock composition.
Parameters
----------
P : Float64
Pressure [kbar].
T : Float64
Temperature [°C].
gv : LibMAGEMin.global_variables
Global variables structure (must have bulk rock composition set).
z_b : LibMAGEMin.bulk_infos
Bulk rock information structure.
DB : LibMAGEMin.Database
Database structure.
splx_data : LibMAGEMin.simplex_datas
Simplex data structure.
light : Bool, optional
Return a lightweight output structure (default: false).
light_ig : Bool, optional
Return an extended lightweight structure for igneous databases (default: false).
name_solvus : Bool, optional
Resolve solvus naming (default: false).
fixed_bulk : Bool, optional
calibration : Bool, optional
When true, after the normal solve also locally minimizes every structurally-feasible-but-not-stable
solution phase and appends non-duplicate results to `out.mSS_vec`, tagged `info="calib"`. Default false.
Use fixed bulk composition (default: false).
buffer_n : Float64, optional
Buffer value (default: 0.0).
mu_fix_val : Vector{Float64}, optional
Target chemical potential [J/mol] for each oxide named in
`mu_fix_idx` (same order, same length as `mu_fix_idx` - errors if
not). Ignored if `mu_fix_idx` was empty at `Initialize_MAGEMin`
time. Safe to vary per point/per thread, exactly like `buffer_n`
(each call writes directly into the caller's own `gv`, so no
synchronization is needed across a `multi_point_minimization`
`@threads` sweep). The fixed oxide's bulk content must be set well
in excess of what the target implies - e.g. several times its
"natural" amount - or the fictive phase that enforces the target
won't reliably become stable and `out.Gamma` for that oxide can
silently miss the target; there is currently no automatic check or
warning for this, so verify `out.Gamma[idx]` against the intended
target when in doubt, especially for physically extreme targets
that may exceed what any real phase in the database can support at
that pressure/temperature (default: `Float64[]`).
Gi : Union{Nothing, Vector{LibMAGEMin.mSS_data}}, optional
Initial guess from previous minimization (default: nothing).
scp : Int64, optional
Sub-solidus computation parameter (default: 0).
dT : Float64, optional
Temperature increment for sub-solidus detection (default: 2.0).
iguess : Bool, optional
Whether to use initial guess (default: false).
rm_list : Union{Nothing, Vector{Int64}}, optional
List of phase indexes to remove (default: nothing).
W : Union{Nothing, Vector{W_data{Float64, Int64}}}, optional
Overriding Margules parameters (default: nothing).
gbase : Union{Nothing, Vector{gbase_data{Float64, Int64}}}, optional
Additive shifts to endmember reference Gibbs energies (default: nothing).
seismic_cor : Bool, optional
If true, compute melt + anelastic corrected seismic velocities of the
solid aggregate (`Vp_cor`, `Vs_cor`) (default: false).
aspect_ratio : Float64, optional
Aspect ratio of the melt/pore geometry, used when `seismic_cor=true` (default: 0.3).
seismic_water : Int, optional
Water content mode passed to [`anelastic_correction`](@ref) when `seismic_cor=true`:
`0` = dry mantle, `1` = damp mantle, `2` = wet mantle (default: 0).
Returns
-------
out : gmin_struct{Float64, Int64}
Structure containing the minimization results (stable phases, fractions, thermodynamic properties, etc.).
Examples
--------
Using a predefined bulk rock composition:
```julia
db = "ig"
gv, z_b, DB, splx_data = init_MAGEMin(db);
test = 0;
sys_in = "mol"
gv = use_predefined_bulk_rock(gv, test, db)
P = 8.0;
T = 800.0;
gv.verbose = -1;
out = point_wise_minimization(P, T, gv, z_b, DB, splx_data, sys_in)
```
Using a custom bulk rock composition:
```julia
db = "ig"
gv, z_b, DB, splx_data = init_MAGEMin(db);
bulk_in_ox = ["SiO2"; "Al2O3"; "CaO"; "MgO"; "FeO"; "Fe2O3"; "K2O"; "Na2O"; "TiO2"; "Cr2O3"; "H2O"];
bulk_in = [48.43; 15.19; 11.57; 10.13; 6.65; 1.64; 0.59; 1.87; 0.68; 0.0; 3.0];
sys_in = "wt"
gv = define_bulk_rock(gv, bulk_in, bulk_in_ox, sys_in, db);
P, T = 10.0, 1100.0;
gv.verbose = -1;
out = point_wise_minimization(P, T, gv, z_b, DB, splx_data, sys_in)
finalize_MAGEMin(gv, DB)
```MAGEMin_C.point_wise_minimization Method
point_wise_minimization(P, T, data::MAGEMin_Data)
Perform a point-wise Gibbs energy minimization for a given pressure and temperature using the `MAGEMin_Data` structure.
Parameters
----------
P : Number
Pressure [kbar].
T : Number
Temperature [°C].
data : MAGEMin_Data
Initialized MAGEMin data structure (composition must be set beforehand).
Returns
-------
out : gmin_struct{Float64, Int64}
Structure containing the minimization results.MAGEMin_C.point_wise_minimization_with_guess Method
point_wise_minimization_with_guess(mSS_vec, P, T, gv, z_b, DB, splx_data)
Perform a point-wise Gibbs energy minimization using an initial guess from metastable solution phase data.
Parameters
----------
mSS_vec : Vector{LibMAGEMin.mSS_data}
Vector of metastable solution phase data used as initial guess.
P : Float64
Pressure [kbar].
T : Float64
Temperature [°C].
gv : LibMAGEMin.global_variables
Global variables structure.
z_b : LibMAGEMin.bulk_infos
Bulk rock information structure.
DB : LibMAGEMin.Database
Database structure.
splx_data : LibMAGEMin.simplex_datas
Simplex data structure.
seismic_cor : Bool, optional
If true, compute melt + anelastic corrected seismic velocities of the
solid aggregate (`Vp_cor`, `Vs_cor`) (default: false).
aspect_ratio : Float64, optional
Aspect ratio of the melt/pore geometry, used when `seismic_cor=true` (default: 0.3).
seismic_water : Int, optional
Water content mode passed to [`anelastic_correction`](@ref) when `seismic_cor=true`:
`0` = dry mantle, `1` = damp mantle, `2` = wet mantle (default: 0).
Returns
-------
out : gmin_struct{Float64, Int64}
Structure containing the minimization results.MAGEMin_C.print_endmember_line Method
print_endmember_line(name, n_em, em_list; name_w, em_w, em_colwidth, width=140)
Print one `<name> : <n_em> em -> <endmembers...>` row, with `name`/`n_em` padded to
`name_w`/`em_w` so this row lines up vertically against every other row printed with the
same widths, and each endmember slot padded to `em_colwidth` so the 1st/2nd/3rd/...
endmember columns line up vertically ACROSS rows too (not just the `->` prefix) -
`em_colwidth` must therefore be computed once from every phase's endmembers, not
per-row, and passed in shared by every call. Stays on a single line for ordinary
endmember counts; only wraps onto indent-aligned continuation lines once a phase has
enough endmembers to exceed `width` (in practice this only kicks in for outliers like
DEW's ~100-species aqueous model). A single outlier phase whose own endmember names
exceed `em_colwidth` (again, DEW) locally loses column alignment within its own
already-wrapped block, without forcing every short mineral endmember list to pad out to
its width. Internal formatting helper for `print_phase_info`.MAGEMin_C.print_info Method
print_info(g::gmin_struct)
Print an extensive overview of the minimization results, including stable phases, compositions, thermodynamic properties, and numerics.
Parameters
----------
g : gmin_struct
Output structure from a MAGEMin minimization.MAGEMin_C.print_name_columns Method
print_name_columns(names; indent=4, width=100)
Print a list of names wrapped into evenly-padded columns, `indent` spaces from the
left margin, each line kept under `width` characters. Internal formatting helper for
`print_phase_info`.MAGEMin_C.print_phase_info Method
print_phase_info(dtb; level=0)
print_phase_info(db_inf::db_infos; level=0)
Pretty-print the database information returned by `retrieve_solution_phase_information`.
Parameters
----------
dtb : String
Database name (e.g., "mp", "ig"). Alternatively, pass an already-retrieved
`db_infos` struct (as returned by `retrieve_solution_phase_information`) directly.
level : Int64, optional
Verbosity level (default: 0):
- `0` : database info + dataset + solution-phase names + pure-phase names.
- `1` : same as level 0, plus the endmember list of every solution phase.
Examples
--------
```julia
print_phase_info("mp")
print_phase_info("mp"; level=1)
db_inf = retrieve_solution_phase_information("all")
print_phase_info(db_inf; level=1)
```MAGEMin_C.pwm_init Method
pwm_init(P, T, gv, z_b, DB, splx_data; G0=true)
Initialize a single point minimization and optionally compute G0 and Margules (W) parameters. Intended for thermodynamic database inversion/calibration workflows.
Parameters
----------
P : Float64
Pressure [kbar].
T : Float64
Temperature [°C].
gv : LibMAGEMin.global_variables
Global variables structure.
z_b : LibMAGEMin.bulk_infos
Bulk rock information structure.
DB : LibMAGEMin.Database
Database structure.
splx_data : LibMAGEMin.simplex_datas
Simplex data structure.
G0 : Bool, optional
Whether to compute G0 (default: true).
Returns
-------
gv : LibMAGEMin.global_variables
Updated global variables.
z_b : LibMAGEMin.bulk_infos
Updated bulk rock information.
DB : LibMAGEMin.Database
Updated database.
splx_data : LibMAGEMin.simplex_datas
Updated simplex data.
Examples
--------
```julia
dtb = "mp"
gv, z_b, DB, splx_data = init_MAGEMin(dtb);
Xoxides = ["SiO2"; "TiO2"; "Al2O3"; "FeO"; "MnO"; "MgO"; "CaO"; "Na2O"; "K2O"; "H2O"; "O"];
X = [58.509, 1.022, 14.858, 4.371, 0.141, 4.561, 5.912, 3.296, 2.399, 10.0, 0.0];
sys_in = "wt"
gv = define_bulk_rock(gv, X, Xoxides, sys_in, dtb);
P, T = 6.0, 500.0
gv, z_b, DB, splx_data = pwm_init(P, T, gv, z_b, DB, splx_data);
out = pwm_run(gv, z_b, DB, splx_data);
```MAGEMin_C.pwm_run Method
pwm_run(gv, z_b, DB, splx_data; name_solvus=false, seismic_cor=false, aspect_ratio=0.3)
Run the equilibrium computation and post-processing after `pwm_init`. Intended for thermodynamic database inversion/calibration workflows.
Parameters
----------
gv : LibMAGEMin.global_variables
Global variables structure (initialized via `pwm_init`).
z_b : LibMAGEMin.bulk_infos
Bulk rock information structure.
DB : LibMAGEMin.Database
Database structure.
splx_data : LibMAGEMin.simplex_datas
Simplex data structure.
name_solvus : Bool, optional
Resolve solvus naming (default: false).
seismic_cor : Bool, optional
If true, compute melt + anelastic corrected seismic velocities of the
solid aggregate (`Vp_cor`, `Vs_cor`) (default: false).
aspect_ratio : Float64, optional
Aspect ratio of the melt/pore geometry, used when `seismic_cor=true` (default: 0.3).
seismic_water : Int, optional
Water content mode passed to [`anelastic_correction`](@ref) when `seismic_cor=true`:
`0` = dry mantle, `1` = damp mantle, `2` = wet mantle (default: 0).
Returns
-------
out : gmin_struct{Float64, Int64}
Structure containing the minimization results.
Examples
--------
```julia
dtb = "mp"
gv, z_b, DB, splx_data = init_MAGEMin(dtb);
Xoxides = ["SiO2"; "TiO2"; "Al2O3"; "FeO"; "MnO"; "MgO"; "CaO"; "Na2O"; "K2O"; "H2O"; "O"];
X = [58.509, 1.022, 14.858, 4.371, 0.141, 4.561, 5.912, 3.296, 2.399, 10.0, 0.0];
sys_in = "wt"
gv = define_bulk_rock(gv, X, Xoxides, sys_in, dtb);
P, T = 6.0, 500.0
gv, z_b, DB, splx_data = pwm_init(P, T, gv, z_b, DB, splx_data);
out = pwm_run(gv, z_b, DB, splx_data);
```MAGEMin_C.remove_phases Method
remove_phases(list, dtb)
Retrieve the list of indexes of the solution phases to be removed from the minimization.
Parameters
----------
list : Union{Nothing, Vector{String}}
List of phase names to remove, or `nothing` to remove none.
dtb : String
Database name (e.g., "mp", "ig").
Returns
-------
rm_list : Union{Nothing, Vector{Int64}}
Vector of phase indexes to remove (negative for pure phases), or `nothing` if no phases to remove.MAGEMin_C.retrieve_eval_rules_TE Method
retrieve_eval_rules_TE()
Return the token substitution rules used when compiling KD expression strings.
Plain tokens such as `T_C` and `P_kbar` are replaced with their fully-qualified counterparts on a `gmin_struct` (e.g., `out.T_C`), so that compiled functions can be called with a single `out` argument.
Returns
-------
in_eval_TE : Vector{String}
Tokens to search for in the expression string.
out_eval_TE : Vector{String}
Replacement strings referencing the `out` argument.MAGEMin_C.retrieve_solution_phase_information Method
retrieve_solution_phase_information(dtb)
Retrieve the general information of the thermodynamic databases (solution phases, endmembers, pure phases).
Parameters
----------
dtb : String
Database name (e.g., "mp", "mb", "ig", "igad", "um", "ume", "mtl", "mpe", "all", "po", "sb11", "sb21", "sb24").
Returns
-------
db_inf : db_infos
Structure containing database information (solution phases, pure phases, endmembers).MAGEMin_C.select_phases Method
select_phases(dtb; pp_list=nothing, ss_list=nothing)
Inverse of `remove_phases`: given the pure phases and/or solution phases the caller
wants to keep active, returns the index list of every OTHER phase to deactivate, in the
same `rm_list` encoding `remove_phases` produces (positive = solution-phase index,
negative = pure-phase index). `pp_list` and `ss_list` are independent - passing only one
of them leaves the other phase category untouched. The buffer/activity pure phases in
`ALWAYS_ACTIVE_PP` (qfm, mw, qif, nno, hm, iw, cco, aH2O, aO2, aMgO, aFeO, aAl2O3, aTiO2)
are never added to the deactivation list, so they never need to be listed in `pp_list`;
whether one of them is actually computed remains governed by `buffer="..."`.
Parameters
----------
dtb : String
Database name (e.g., "mp", "ig").
pp_list : Union{Nothing, Vector{String}}
Pure phases to keep active, or `nothing` to leave all pure phases untouched.
ss_list : Union{Nothing, Vector{String}}
Solution phases to keep active, or `nothing` to leave all solution phases untouched.
Accepts either the bare name (`db_infos.ss_name`, e.g. "liq") or the citation-tagged
name (`ss_infos.ss_fName`, e.g. "liq_W14", the identifier `print_phase_info` shows).
Returns
-------
rm_list : Union{Nothing, Vector{Int64}}
Vector of phase indexes to deactivate (negative for pure phases), or `nothing` if
neither `pp_list` nor `ss_list` was given (or the resulting list is empty).MAGEMin_C.single_point_minimization Method
single_point_minimization(P, T, MAGEMin_db; light=false, light_ig=false, name_solvus=false, fixed_bulk=false, calibration=false, test=0, X=nothing, B=nothing, G=nothing, scp=0, dT=2.0, iguess=false, rm_list=nothing, W=nothing, gbase=nothing, Xoxides=Vector{String}, sys_in="mol", rg="tc", progressbar=true)
Perform a MAGEMin Gibbs energy minimization at a single pressure-temperature point.
This is a convenience wrapper around `multi_point_minimization` for scalar `P` and `T` inputs.
Parameters
----------
P : Float64
Pressure [kbar].
T : Float64
Temperature [°C].
MAGEMin_db : MAGEMin_Data
Initialized MAGEMin data structure.
light : Bool, optional
Return a lightweight output structure (default: false).
light_ig : Bool, optional
Return an extended lightweight structure for igneous databases (default: false).
name_solvus : Bool, optional
Resolve solvus naming (default: false).
fixed_bulk : Bool, optional
calibration : Bool, optional
When true, after the normal solve also locally minimizes every structurally-feasible-but-not-stable
solution phase and appends non-duplicate results to `out.mSS_vec`, tagged `info="calib"`. Default false.
Use fixed bulk composition (default: false).
test : Int64, optional
Built-in test case number (default: 0).
X : VecOrMat, optional
Bulk rock composition. Single vector of length `noxides` (default: nothing).
B : Union{Nothing, Float64}, optional
Buffer value (default: nothing).
G : Union{Nothing, Vector{LibMAGEMin.mSS_data}}, optional
Initial guess data (default: nothing).
scp : Int64, optional
Sub-solidus computation parameter (default: 0).
dT : Float64, optional
Temperature increment for sub-solidus detection (default: 2.0).
iguess : Bool, optional
Whether to use initial guess (default: false).
rm_list : Union{Nothing, Vector{Int64}}, optional
List of phase indexes to remove (default: nothing). Mutually exclusive with
`pp_list`/`ss_list`.
pp_list : Union{Nothing, Vector{String}}, optional
Pure phases to keep active; every other pure phase is deactivated (default: nothing,
i.e. no pure-phase selection). See [`select_phases`](@ref). Mutually exclusive with
`rm_list`. The buffer/activity pure phases in `ALWAYS_ACTIVE_PP` never need to be
listed - they remain governed by `buffer="..."` regardless.
ss_list : Union{Nothing, Vector{String}}, optional
Solution phases to keep active; every other solution phase is deactivated (default:
nothing, i.e. no solution-phase selection). See [`select_phases`](@ref). Mutually
exclusive with `rm_list`.
W : Union{Nothing, Vector{W_data{Float64, Int64}}}, optional
Overriding Margules parameters (default: nothing).
gbase : Union{Nothing, Vector{gbase_data{Float64, Int64}}}, optional
Additive shifts to endmember reference Gibbs energies (default: nothing).
Xoxides : Vector{String}
Oxide names corresponding to `X`.
sys_in : String, optional
Input system units, "mol" or "wt" (default: "mol").
rg : String, optional
Research group, "tc" or "sb" (default: "tc").
progressbar : Bool, optional
Show progress bar (default: true).
seismic_cor : Bool, optional
If true, compute melt + anelastic corrected seismic velocities of the
solid aggregate (`Vp_cor`, `Vs_cor`) (default: false).
aspect_ratio : Float64, optional
Aspect ratio of the melt/pore geometry, used when `seismic_cor=true` (default: 0.3).
seismic_water : Int, optional
Water content mode passed to [`anelastic_correction`](@ref) when `seismic_cor=true`:
`0` = dry mantle, `1` = damp mantle, `2` = wet mantle (default: 0).
filter_DEW_species : Bool, optional
If true, drop chemically infeasible species (`emFrac <= 1e-40`) from the `DEW_S24`
aqueous speciation phase's per-endmember output, instead of returning the full
~100+ possible species regardless of whether the bulk can actually form them.
Only affects a phase named "DEW_S24"; all other phases are unaffected
(default: false). See [`create_gmin_struct`](@ref).
Returns
-------
out : gmin_struct{Float64, Int64}
Structure containing the minimization result at the given P-T point.
Examples
--------
```julia
data = Initialize_MAGEMin("ig", verbose=false);
Xoxides = ["SiO2","Al2O3","CaO","MgO","FeO","Fe2O3","K2O","Na2O","TiO2","Cr2O3","H2O"]
X = [48.43, 15.19, 11.57, 10.13, 6.65, 1.64, 0.59, 1.87, 0.68, 0.0, 3.0]
out = single_point_minimization(10.0, 1100.0, data, X=X, Xoxides=Xoxides, sys_in="wt")
Finalize_MAGEMin(data)
```MAGEMin_C.solve_with_saturation Method
solve_with_saturation(P, T, data, X_mol, Xoxides, C0, KDs_dtb, dtb; sat, sys_in, tol, max_iter)
Run the MAGEMin minimization + TE partitioning loop with saturation corrections
until the corrected bulk composition converges.
Parameters
----------
P, T : Float64
Pressure [kbar] and temperature [°C].
data : MAGEMin data handle
Initialised with `Initialize_MAGEMin`.
X_mol : Vector{Float64}
Normalised bulk molar composition (will not be mutated).
Xoxides : Vector{String}
Oxide names matching `X_mol`.
C0 : Vector{Float64}
Initial bulk trace-element composition [ppm].
KDs_dtb : custom_KDs_database
Trace-element partitioning database (real mineral phases only;
saturation phases are appended automatically when `sat` is provided).
dtb : String
MAGEMin database identifier (e.g. "mp", "ig").
sat : SaturationConfig, optional
Saturation model selection. Defaults to all "none".
sys_in : String, optional
Composition input units for MAGEMin: "mol" (default) or "wt".
tol : Float64, optional
Convergence tolerance on the L2-norm of `bulk_cor_mol` (default 1e-6).
max_iter : Int, optional
Maximum number of iterations (default 32).
Returns
-------
out : MAGEMin output at convergence.
out_TE : out_tepm at convergence.
converged : Bool — true if `tol` was reached.
n_iter : Int — number of iterations performed.MAGEMin_C.solve_with_saturation Method
solve_with_saturation(P, T, data, X_mol, Xoxides, C0, KDs_dtb, dtb; sat, sys_in, tol, max_iter, progressbar, kwargs...)
Vectorised form of `solve_with_saturation`: solves the bulk-composition /
saturation fixed point for a whole set of P-T points, using
`multi_point_minimization` for the equilibrium step so the minimisations of one
iteration run across all available threads.
Each point carries its own corrected bulk composition and its own residual.
Points drop out of the active set as they converge, so later iterations only
minimise what is still moving.
Parameters
----------
P, T : Vector{Float64}
Pressures [kbar] and temperatures [C], same length.
data : MAGEMin_Data
Initialised MAGEMin database.
X_mol : Vector{Float64} or Vector{Vector{Float64}}
Starting bulk composition — one shared composition, or one per point.
Xoxides : Vector{String}
Oxide names of `X_mol`.
C0 : Vector{Float64}
Initial bulk trace element composition [ppm], shared by all points.
KDs_dtb : custom_KDs_database
Compiled KD database.
dtb : String
Database identifier for mineral classification (e.g. "ig", "mp").
sat : SaturationConfig, optional
Saturation models to apply (default: all disabled).
sys_in : String, optional
"mol" (default) or "wt". The saturation feedback subtracts `bulk_cor_mol`,
so only "mol" is self-consistent.
tol : Float64, optional
Convergence tolerance on the change in `norm(bulk_cor_mol)` (default 1e-6).
max_iter : Int, optional
Maximum iterations (default 32).
progressbar : Bool, optional
Forwarded to `multi_point_minimization` (default false).
kwargs...
Any other keyword accepted by `multi_point_minimization`.
Returns
-------
out : Vector{gmin_struct}
Minimisation output per point.
out_TE : Vector{out_tepm}
Trace element output per point.
converged : Vector{Bool}
Per-point convergence flag.
n_iter : Vector{Int}
Iterations used per point (`max_iter` for points that never converged).MAGEMin_C.split_and_keep Method
split_and_keep(data, Hash_XY)
Categorise cells into the split or keep list based on phase assembly uniformity.
For each cell in `data.keep_cell_list` (from the previous refinement step) and
any remaining cells beyond that list, the function collects the phase-assembly
hash values at all corner points (and any boundary midpoints already stored in
`data.bnd_cells`). If all hashes are identical the cell is stable and added to
`keep_cell_list`; otherwise it straddles a reaction boundary and is added to
`split_cell_list`.
Parameters
----------
data : AMR_data
AMR state structure. `data.cells`, `data.keep_cell_list`, and
`data.bnd_cells` are read; `data.split_cell_list` and
`data.keep_cell_list` are overwritten.
Hash_XY : Vector{UInt64}
Per-point phase-assembly hash values, indexed by point index.
Returns
-------
data : AMR_data
Updated AMR state with refreshed `split_cell_list` and `keep_cell_list`.MAGEMin_C.sulfur_saturation Method
sulfur_saturation(out; model="1000ppm")
Compute the sulfur concentration at sulfide saturation (SCSS) in the melt phase [ppm].
Parameters
----------
out : MAGEMin_C.gmin_struct{Float64, Int64}
MAGEMin minimization output (must contain a melt phase with a "liq" solution phase).
model : String, optional
Saturation model (default: "1000ppm"). Valid options:
- `"<N>ppm"` — Fixed saturation value of N ppm (e.g., "1000ppm", "500ppm")
- "Liu07" — Liu et al. (2007); SCSS model, may be unreliable for anhydrous conditions
- "Oneill21" — O'Neill (2021); thermodynamic SCSS model using fO₂ from the minimization
Returns
-------
C_s_liq : Float64
Sulfur saturation concentration in the melt [ppm].MAGEMin_C.use_predefined_bulk_rock Function
use_predefined_bulk_rock(gv, test=0, db="ig")
Return the pre-defined bulk rock composition for a given built-in test case.
Parameters
----------
gv : LibMAGEMin.global_variables
Global variables structure.
test : Int64, optional
Built-in test case number (default: 0).
db : String, optional
Database identifier, e.g. "ig", "mp", "mb" (default: "ig").
Returns
-------
gv : LibMAGEMin.global_variables
Updated global variables with bulk rock composition set.MAGEMin_C.use_predefined_bulk_rock Function
use_predefined_bulk_rock(data::MAGEMin_Data, test=0)
Return the pre-defined bulk rock composition for a given built-in test case (multi-threaded version).
Parameters
----------
data : MAGEMin_Data
Initialized MAGEMin data structure.
test : Int64, optional
Built-in test case number (default: 0).
Returns
-------
data : MAGEMin_Data
Updated MAGEMin data structure with bulk rock composition set for all threads.MAGEMin_C.volatile_saturation_SY26 Method
volatile_saturation_SY26(out; P_H2O=NaN, P_CO2=NaN)Compute H2O and CO2 solubility in the melt using the M2Fluid model of Sun & Yao (2026).
If P_H2O or P_CO2 are not provided and a fluid phase is present in out, partial pressures are estimated from the fluid mole fractions assuming ideal mixing. If neither a value nor a fluid phase is available for a volatile species, the corresponding saturation is returned as NaN.
Parameters
out : MAGEMin_C.gmin_struct{Float64, Int64} MAGEMin minimization output (must contain a melt phase). P_H2O : Float64, optional Partial pressure of H₂O [bar]. When NaN (default), derived from fluid composition if a fluid phase is present. P_CO2 : Float64, optional Partial pressure of CO₂ [bar]. When NaN (default), derived from fluid composition if a fluid phase is present.
Returns
S_H2O : Float64 H₂O solubility in the melt [wt%], or NaN if P_H2O cannot be determined. S_CO2 : Float64 CO₂ solubility in the melt [ppm], or NaN if P_CO2 cannot be determined.
MAGEMin_C.wave_melt_correction Method
wave_melt_correction(gv, P_kbar, solid_Vp, solid_Vs, aspectRatio=0.3)
Melt-fraction correction for P- and S-wave velocities of the solid aggregate.
Uses the reduction formulation of Clark et al. (2017), based on the
equilibrium geometry model for the solid skeleton of Takei (1997).
If `gv.melt_fraction == 0.0`, a fixed near-surface porosity correction
(aspect ratio 0.25, Poisson ratio 0.25) is applied instead, using `P_kbar`
to estimate depth.
Parameters
----------
gv : LibMAGEMin.global_variables
Global variables structure (melt/solid fractions, densities and moduli).
P_kbar : Float64
Pressure [kbar], used for the depth/porosity estimate when `melt_fraction == 0`.
solid_Vp : Float64
P-wave velocity of the solid aggregate [km/s] (uncorrected, or anelastically corrected).
solid_Vs : Float64
S-wave velocity of the solid aggregate [km/s] (uncorrected, or anelastically corrected).
aspectRatio : Float64, optional
Coefficient defining the geometry of the solid framework (contiguity):
0.0 (layered melt) < 0.1 (grain boundary melt) < 1.0 (melt in separated
bubble pockets) (default: 0.3).
Returns
-------
(Vp_cor, Vs_cor) : Tuple{Float64, Float64}
Melt-corrected P- and S-wave velocities of the solid aggregate [km/s].
Reference
---------
Clark A.N. and Lesher C.E. (2017)MAGEMin_C.wt2mol Method
wt2mol(bulk_wt, bulk_ox)
Convert bulk-rock composition from weight fraction to molar fraction.
Parameters
----------
bulk_wt : AbstractVector{Float64}
Bulk rock composition in weight fraction.
bulk_ox : AbstractVector{String}
Oxide names corresponding to `bulk_wt`.
Returns
-------
bulk_mol : Vector{Float64}
Bulk rock composition in molar fraction (normalized to 100).MAGEMin_C.zirconium_saturation Method
zirconium_saturation(out; model="WH")
Compute the zirconium saturation concentration in the melt phase [ppm].
Parameters
----------
out : MAGEMin_C.gmin_struct{Float64, Int64}
MAGEMin minimization output (must contain a melt phase).
model : String, optional
Saturation model (default: "WH"). Valid options:
- "WH" — Watson & Harrison (1983)
- "B" — Boehnke et al. (2013)
- "CB" — Crisp & Berry (2022)
Returns
-------
C_zr_liq : Float64
Zr saturation concentration in the melt [ppm], or -1 if no melt is present.