C++ Interface Reference
-
class ChemicalEngine
- #include <ChemicalEngine.hpp>
Class for equilibrium computations and thermodynamic analysis.
The ChemicalEngine performs Gibbs energy minimization to compute the equilibrium state of a chemical system. Its API provides methods to load system data, update component amounts, set options, and query resulting thermodynamic properties.
Public Functions
-
ChemicalEngine()
Default constructor.
Creates an empty ChemicalEngine instance. Use one of the initialization routines (such as initialize() or initializeFromJsonStrings()) to configure the system.
// Example: Create an engine and then initialize it with a system file. xGEMS::ChemicalEngine engine; engine.initialize("my-system-dat.lst"); // Temperature in K, Pressure in Pa.
-
ChemicalEngine(std::string filename)
Constructs a ChemicalEngine instance by loading a GEM-Selektor project file.
// Example: Directly initialize the engine from a project file. xGEMS::ChemicalEngine engine("my-system-dat.lst");
- Parameters:
filename – The file path for the chemical system definition (e.g., “my-system-dat.lst”).
-
virtual ~ChemicalEngine()
Destructor.
Cleans up resources. No explicit example is necessary.
-
ChemicalEngine(const ChemicalEngine &other) = delete
Deleted copy constructor.
-
auto operator=(ChemicalEngine other) -> ChemicalEngine& = delete
Deleted assignment operator.
-
auto reallocateEngineArrays() -> void
Reallocates internal arrays.
Should be invoked after the system composition changes to ensure proper memory configuration.
// Example: After modifying system composition, reallocate arrays. engine.reallocateEngineArrays();
-
auto initialize(std::string filename) -> void
Initializes the ChemicalEngine from a GEM-Selektor project file.
Reads the file and configures the chemical system defined inside it.
// Example: Initialize using the system definition file. xGEMS::ChemicalEngine engine; engine.initialize("my-system-dat.lst");
- Parameters:
filename – Path to the system definition file (e.g., “my-system-dat.lst”).
-
auto initializeFromJsonStrings(std::string dch_json, std::string ipm_json, std::string dbr_json) -> void
Initializes the ChemicalEngine using JSON strings.
Configures the engine from three JSON strings:
dch_json: Defines the chemical system.
ipm_json: Contains calculation parameters and settings.
dbr_json: Specifies the input node composition. These strings can be obtained from the GEM-Selektor exported GEMS3K system files as JSON (*-imp.json, *-dbc.json, *-dbr.json).
// Example: Initialize using JSON-based input. std::string dch = "{}"; std::string ipm = "{}"; std::string dbr = "{}"; engine.initializeFromJsonStrings(dch, ipm, dbr);
- Parameters:
dch_json – JSON string describing the chemical system.
ipm_json – JSON string with parameter and algorithm settings.
dbr_json – JSON string containing node composition details.
-
auto readDbrFromFile(std::string filename) -> void
Reads a DBR file from disk.
Loads system composition and parameter data from a DBR file.
// Example: Read system composition from a DBR file. engine.readDbrFromFile("my-system-dbr-0-0000.json");
- Parameters:
filename – Path to the input DBR file (e.g., “*-dbr.json/.dat”).
-
auto readDbrFromJsonString(std::string dbr_json) -> void
Reads System DBR composition from a JSON string.
Updates the system composition using JSON information.
// Example: Update composition dynamically from a JSON string. engine.readDbrFromJsonString("{}");
- Parameters:
dbr_json – JSON string containing DBR composition data.
-
auto writeDbrToFile(std::string filename) -> void
Writes the current DBR to a file (key-value format).
Saves the state of the system (after equilibrium calculations) into a DBR file.
// Example: Save the current state to"my-system-dbr-0-0001.dat". engine.writeDbrToFile("my-system-dbr-0-0001.dat");
- Parameters:
filename – Path to the output DBR file (e.g., “my-system-dbr-0-0001.dat”).
-
auto writeDbrToJsonString() -> const std::string
Returns the current DBR as a JSON string.
// Example: Retrieve the system state as JSON. std::string json_state = engine.writeDbrToJsonString(); std::cout << json_state << std::endl;
- Returns:
A JSON string representing the system composition.
-
auto numElements() const -> Index
Returns the number of elements in the system.
// Example: Get the number of elements. Index nElements = engine.numElements(); std::cout << "Elements: " << nElements << std::endl;
- Returns:
(Index) Total number of elements.
-
auto numSpecies() const -> Index
Returns the number of species in the system.
// Example: Display the number of species. Index speciesCount = engine.numSpecies(); std::cout << "Species: " << speciesCount << std::endl;
- Returns:
(Index) Total number of chemical species.
-
auto numPhases() const -> Index
Returns the number of phases in the system.
// Example: Print the number of phases. Index phases = engine.numPhases(); std::cout << "Phases: " << phases << std::endl;
- Returns:
(Index) Total number of phases.
-
auto numSpeciesInPhase(Index iphase) const -> Index
Returns the number of species in a given phase.
// Example: For phase with index 0. Index sppInPhase = engine.numSpeciesInPhase(0); std::cout << "Species in phase 0: " << sppInPhase << std::endl;
- Parameters:
iphase – (Index) Index of the phase.
- Returns:
(Index) Number of species in that phase.
-
auto elementName(Index ielement) const -> std::string
Returns the name of an element.
// Example: Get the name of the first element. std::string element = engine.elementName(0); std::cout << "Element 0: " << element << std::endl;
- Parameters:
ielement – (Index) Index of the element.
- Returns:
(std::string) Element name.
-
auto speciesName(Index ispecies) const -> std::string
Returns the name of a species.
// Example: Retrieve the name of species 0. std::string spName = engine.speciesName(0); std::cout << "Species 0: " << spName << std::endl;
- Parameters:
ispecies – (Index) Index of the species.
- Returns:
(std::string) Species name.
-
auto speciesCharge(Index ispecies) const -> double
Returns the electrical charge of a species.
// Example: Get the charge of species with index 0. double charge = engine.speciesCharge(0); std::cout << "Charge: " << charge << std::endl;
- Parameters:
ispecies – (Index) Index of the species.
- Returns:
(double) Charge of the species.
-
auto phaseName(Index iphase) const -> std::string
Returns the name of the phase.
// Example: Retrieve the name of phase 0. std::string phase = engine.phaseName(0); std::cout << "Phase 0: " << phase << std::endl;
- Parameters:
iphase – (Index) Index of the phase.
- Returns:
(std::string) Phase name.
-
auto indexElement(std::string element) const -> Index
Returns the index of an element by name.
// Example: Get the index of Oxygen ("O"). Index idx = engine.indexElement("O"); std::cout << "Index of O: " << idx << std::endl;
- Parameters:
element – (std::string) Element symbol or name.
- Returns:
(Index) Index of the element (or total elements if not found).
-
auto indexSpecies(std::string species) const -> Index
Returns the index of a species by name.
// Example: Get the index of water ("H2O@"). Index idx = engine.indexSpecies("H2O@"); std::cout << "Index of H2O@: " << idx << std::endl;
- Parameters:
species – (std::string) Name of the species.
- Returns:
(Index) Index of the species (or total species if not found).
-
auto indexSpeciesAll(std::string species) const -> VectorXi
Returns all indices of species matching the specified name.
// Example: Retrieve all indices where the species "H2O@" appears. VectorXi allIndices = engine.indexSpeciesAll("H2O@");
- Parameters:
species – (std::string) Name of the species.
- Returns:
(VectorXi) Vector of indices.
-
auto indexPhase(std::string phase) const -> Index
Returns the index of a phase by name.
// Example: Get index for the "aq_gen" phase. Index aqueousIndex = engine.indexPhase("aq_gen");
- Parameters:
phase – (std::string) Name of the phase.
- Returns:
(Index) Index of the phase.
-
auto indexPhaseAll(std::string phase) const -> VectorXi
Returns all indices for phases that match the given name.
// Example: Retrieve all indices for phase "SiO2". VectorXi phaseIndices = engine.indexPhaseAll("SiO2");
- Parameters:
phase – (std::string) Name of the phase.
- Returns:
(VectorXi) Vector of indices for matching phases.
-
auto indexPhaseWithSpecies(Index ispecies) const -> Index
Returns the index of the phase containing a given species.
// Example: Find the phase of the species with index 0. Index phaseIdx = engine.indexPhaseWithSpecies(0);
- Parameters:
ispecies – (Index) Index of the species.
- Returns:
(Index) Index of the phase that contains the species.
-
auto indexFirstSpeciesInPhase(Index iphase) const -> Index
Returns the index of the first species in a specified phase.
// Example: Get the first species index in phase 0. Index firstSpec = engine.indexFirstSpeciesInPhase(0);
- Parameters:
iphase – (Index) Index of the phase.
- Returns:
(Index) Index of the first species in that phase.
-
auto elementMolarMasses() const -> VectorConstRef
Returns molar masses of elements.
// Example: Retrieve the element molar masses vector. auto molarMasses = engine.elementMolarMasses();
- Returns:
(VectorConstRef) Vector of molar masses (kg/mol) for each element.
-
auto speciesMolarMasses() const -> VectorConstRef
Returns molar masses of species.
// Example: Get the species molar masses. auto spMolarMasses = engine.speciesMolarMasses();
- Returns:
(VectorConstRef) Vector of species molar masses (kg/mol).
-
auto formulaMatrix() const -> MatrixConstRef
Returns the formula matrix (elements x species).
// Example: Retrieve the formula matrix. auto fMatrix = engine.formulaMatrix();
- Returns:
(MatrixConstRef) Formula matrix where rows correspond to elements and columns correspond to species.
-
auto setSpeciesAmounts(VectorConstRef n) -> void
Sets the complete species amounts vector.
// Example: Set all species amounts to 1.0 mol. Eigen::VectorXd n(engine.numSpecies()); n.setOnes(); engine.setSpeciesAmounts(n);
- Parameters:
n – (VectorConstRef) Vector of species amounts (mol).
-
auto setSpeciesAmount(std::string name, double amount) -> void
Sets the amount for a species identified by name (as in the GEMS system).
// Example: Set the amount of "CaSO4@" to 0.01 mol. engine.setSpeciesAmount("CaSO4@", 0.01);
- Parameters:
name – (std::string) Species name.
amount – (double) New amount in mol.
-
auto setSpeciesAmount(Index ispecies, double amount) -> void
Sets the amount for a species identified by its index.
// Example: Set species at index 0 to 0.01 mol. engine.setSpeciesAmount(0, 0.01);
- Parameters:
ispecies – (Index) Index of the species.
amount – (double) New amount in mol.
-
auto setOptions(const ChemicalEngineOptions &options) -> void
Sets the options for the ChemicalEngine.
// Example: Disable warm start for higher accuracy. xGEMS::ChemicalEngineOptions opt; opt.warmstart = false; engine.setOptions(opt);
- Parameters:
options – (const ChemicalEngineOptions&) Configuration options.
-
auto options() const -> const ChemicalEngineOptions&
Get the current chemical engine options.
Returns a constant reference to the internal ChemicalEngineOptions, which control solver behavior, convergence criteria, and output flags. These options can be inspected or copied for modification.
// Example: Disable warm start for higher accuracy. xGEMS::ChemicalEngineOptions opt = engine.options(); opt.warmstart = false; engine.setOptions(opt);
- Returns:
const ChemicalEngineOptions& The current engine options.
-
auto setWarmStart() -> void
Configures the engine to use a warm (smart) start.
Uses previous equilibrium as initial guess (faster convergence).
// Example: Set smart initial approximation. engine.setWarmStart();
-
auto setColdStart() -> void
Configures the engine to use a cold start.
Uses a simplex LP initial guess (slower but may yield more accurate results).
// Example: Force a cold start. engine.setColdStart();
-
auto setSpeciesUpperLimit(std::string name, double amount) -> void
Sets an upper bound for a species identified by name.
If amount < 0, resets to default 1e6.
// Example: Set the upper limit for "SiO2" to 0.1 mol. engine.setSpeciesUpperLimit("SiO2", 0.1);
- Parameters:
name – (std::string) Species name.
amount – (double) Upper limit in mol.
-
auto setSpeciesLowerLimit(std::string name, double amount) -> void
Sets a lower bound for a species identified by name.
If amount < 0, resets to default 0.
// Example: Set the lower limit for "SiO2" to 0.05 mol. engine.setSpeciesLowerLimit("SiO2", 0.05);
- Parameters:
name – (std::string) Species name.
amount – (double) Lower limit in mol.
-
auto setSpeciesUpperLimit(Index ispecies, double amount) -> void
Sets an upper bound (maximum amount allowed to form) for a species identified by its index.
If amount < 0, resets to default 1e6.
// Example: Set upper limit for species index 0. engine.setSpeciesUpperLimit(0, 0.1);
- Parameters:
ispecies – (Index) Species index.
amount – (double) Upper limit in mol.
-
auto setSpeciesLowerLimit(Index ispecies, double amount) -> void
Sets a lower bound (minimum amount allowed to form) for a species identified by its index.
If amount < 0, resets to default 0.
// Example: Set lower limit for species index 0. engine.setSpeciesLowerLimit(0, 0.05);
- Parameters:
ispecies – (Index) Species index.
amount – (double) Lower limit in mol.
-
auto setStandardMolarGibbsEnergy(std::string name, double value) -> void
Sets the standard molar Gibbs energy for a species (@ T, P of the system).
// Example: Set the standard molar Gibbs energy of H2O. engine.setStandardMolarGibbsEnergy("H2O", -237140); // Value in J/mol.
- Parameters:
name – (std::string) Species name.
value – (double) Standard molar Gibbs energy in J/mol.
-
auto setSpeciesUpperLimits(VectorConstRef n) -> void
Sets upper limits for all species.
// Example: Set all species' upper limits to values provided in vector "limits". engine.setSpeciesUpperLimits(limits);
- Parameters:
n – (VectorConstRef) Vector of upper limits in mol.
-
auto setSpeciesLowerLimits(VectorConstRef n) -> void
Sets lower limits for all species.
// Example: Set all species' lower limits. engine.setSpeciesLowerLimits(lowerLimits);
- Parameters:
n – (VectorConstRef) Vector of lower limits in mol.
-
auto setPT(double P, double T) const -> bool
Sets the pressure and temperature without computing equilibrium.
// Example: Set PT to 101325 Pa and 298.15 K. bool error = engine.setPT(101325, 298.15); std::cout << (error ? "PT error" : "PT set correctly") << std::endl;
- Parameters:
P – Pressure in Pascals (Pa).
T – Temperature in Kelvin (K).
- Returns:
(bool) False if PT was set correctly, true if out of range.
-
auto setB(VectorConstRef b) -> void
Sets the amounts of elements (vector b) without computing equilibrium.
// Example: Set elements amounts of a solution with 0.001 M MgCl2 0.001 M CO2 // elements order: C, Ca, Cl, H, Mg, O, Zz (charge) Eigen::VectorXd b(7); b << 0.001, 1e-09, 0.004, 110.6837, 0.002, 55.34405, 0; // in mol engine.setB(b);
- Parameters:
b – (VectorConstRef) Vector of element amounts in mol (order based on the index of elements in the chemical system).
-
auto reequilibrate(bool warmstart) -> int
Re-equilibrates the system with (or without) a warm start.
// Example: Re-equilibrate with a warm start. int status = engine.reequilibrate(true);
0: No GEM re-calculation needed
1: Need GEM calculation with LPP (automatic) initial approximation (AIA)
2: OK after GEM calculation with LPP AIA
3: Bad (not fully trustful) result after GEM calculation with LPP AIA
4: Failure (no result) in GEM calculation with LPP AIA
5: Need GEM calculation with no-LPP (smart) IA, SIA using the previous speciation
6: OK after GEM calculation with SIA
7: Bad (not fully trustful) result after GEM calculation with SIA
8: Failure (no result) in GEM calculation with SIA
9: Terminal error in GEMS3K (e.g., memory corruption). Restart required.
- Parameters:
warmstart – (bool) If true, uses previous data as an initial guess.
- Returns:
(int) Return code of the re-equilibration.
-
auto reequilibrate() -> int
Re-equilibrates the system with (or without) a warm start.
// Example: Re-equilibrate. int status = engine.reequilibrate();
0: No GEM re-calculation needed
1: Need GEM calculation with LPP (automatic) initial approximation (AIA)
2: OK after GEM calculation with LPP AIA
3: Bad (not fully trustful) result after GEM calculation with LPP AIA
4: Failure (no result) in GEM calculation with LPP AIA
5: Need GEM calculation with no-LPP (smart) IA, SIA using the previous speciation
6: OK after GEM calculation with SIA
7: Bad (not fully trustful) result after GEM calculation with SIA
8: Failure (no result) in GEM calculation with SIA
9: Terminal error in GEMS3K (e.g., memory corruption). Restart required.
- Returns:
(int) Return code of the re-equilibration.
-
auto equilibrate(double T, double P, VectorConstRef b) -> int
Computes the equilibrium state.
Uses temperature (K), pressure (Pa), and element amounts (in mol) to compute equilibrium.
// Example: This vector need to be defined and assembled by the user with the number of elements in the system. // The order of the elements in the vector is based on the index of elements in the chemical system. // Example: Set elements amounts of a solution with 0.001 M MgCl2 0.001 M CO2 // elements order: C, Ca, Cl, H, Mg, O, Zz (charge) Eigen::VectorXd b(7); b << 0.001, 1e-09, 0.004, 110.6837, 0.002, 55.34405, 0; // in mol int retcode = engine.equilibrate(298.15, 101325, b);
0: No GEM re-calculation needed
1: Need GEM calculation with LPP (automatic) initial approximation (AIA)
2: OK after GEM calculation with LPP AIA
3: Bad (not fully trustful) result after GEM calculation with LPP AIA
4: Failure (no result) in GEM calculation with LPP AIA
5: Need GEM calculation with no-LPP (smart) IA, SIA using the previous speciation
6: OK after GEM calculation with SIA
7: Bad (not fully trustful) result after GEM calculation with SIA
8: Failure (no result) in GEM calculation with SIA
9: Terminal error in GEMS3K (e.g., memory corruption). Restart required.
- Parameters:
T – Temperature in Kelvin (K).
P – Pressure in Pascals (Pa).
b – Vector of element amounts (mol).
- Returns:
(int) Return code of the equilibrium solver.
-
auto converged() const -> bool
Checks if the equilibrium calculation converged.
// Example: Check convergence status. bool isConverged = engine.converged();
- Returns:
(bool) True if converged, false otherwise.
-
auto numIterations() const -> Index
Returns the number of iterations performed during equilibrium.
// Example: Display the number of iterations. Index iters = engine.numIterations(); std::cout << "Iterations: " << iters << std::endl;
- Returns:
(Index) The number of iterations.
-
auto elapsedTime() const -> double
Returns the elapsed time of the equilibrium computation.
// Example: Get the computation time. double timeSec = engine.elapsedTime(); std::cout << "Time: " << timeSec << " s" << std::endl;
- Returns:
(double) Elapsed time in seconds.
-
auto temperature() const -> double
Returns the current temperature of the system.
// Example: Get the system temperature. double temp = engine.temperature(); std::cout << "Temperature: " << temp << " K" << std::endl;
- Returns:
(double) Temperature in Kelvin (K).
-
auto pressure() const -> double
Returns the current pressure of the system.
// Example: Retrieve the system pressure. double press = engine.pressure(); std::cout << "Pressure: " << press << " Pa" << std::endl;
- Returns:
(double) Pressure in Pascals (Pa).
-
auto elementAmounts() const -> VectorConstRef
Returns the amounts of the elements.
The order of the elements in the vector is based on the index of elements in the chemical system.
// Example: Get element amounts. auto eAmounts = engine.elementAmounts();
- Returns:
(VectorConstRef) Vector of element amounts in mol.
-
auto elementAmountsInPhase(Index iphase) const -> Vector
Returns the amounts of elements in a specified phase.
The order of the elements in the vector is based on the index of elements in the chemical system.
Example usage:
// Retrieve the element amounts in phase index 0. Eigen::VectorXd elementAmounts = engine.elementAmountsInPhase(0); std::cout << "Element amounts in phase 0: " << elementAmounts.transpose() << std::endl;
- Parameters:
iphase – Index of the phase.
- Returns:
A vector containing the amounts of each element in the phase (in mol).
-
auto elementAmountsInSpecies(VectorXiConstRef ispecies) const -> Vector
Returns the amounts of elements in a specified group of species.
The order of the elements in the vector is based on the index of elements in the chemical system.
Example usage:
// Retrieve element amounts contributed by species indices {0, 2, 5}. Eigen::VectorXi speciesIndices(3); speciesIndices << 0, 2, 5; Eigen::VectorXd elementAmounts = engine.elementAmountsInSpecies(speciesIndices); std::cout << "Element amounts from selected species: " << elementAmounts.transpose() << std::endl;
- Parameters:
ispecies – A vector containing the indices of the species whose elemental amounts should be retrieved.
- Returns:
A vector containing the amounts of each element corresponding to the selected species (in mol).
-
auto speciesAmounts() const -> VectorConstRef
Returns the amounts of the species.
// Example: Retrieve the species amounts. auto spAmounts = engine.speciesAmounts();
- Returns:
(VectorConstRef) Vector of species amounts in mol.
-
auto speciesAmount(Index ispecies) const -> double
Returns the amount of a species by index.
// Example: Get the species amount at index 0. double amount = engine.speciesAmount(0);
- Parameters:
ispecies – (Index) Index of the species.
- Returns:
(double) Amount in mol.
-
auto speciesAmount(std::string name) const -> double
Returns the amount of a species identified by name.
// Example: Get the amount of "OH-". double waterAmt = engine.speciesAmount("OH-");
- Parameters:
name – (std::string) Species name.
- Returns:
(double) Amount in mol.
-
auto speciesUpperLimits() const -> VectorConstRef
Returns the upper limits for all species.
// Example: Fetch all species upper limits. auto upperLimits = engine.speciesUpperLimits();
- Returns:
(VectorConstRef) Vector of upper limits in mol.
-
auto speciesLowerLimits() const -> VectorConstRef
Returns the lower limits for all species.
// Example: Get the species lower limits. auto lowerLimits = engine.speciesLowerLimits();
- Returns:
(VectorConstRef) Vector of lower limits in mol.
-
auto speciesMolalities() const -> VectorConstRef
Returns the molalities of the species.
Assumes the aqueous phase is the first phase.
// Example: Retrieve species molalities. auto molalities = engine.speciesMolalities();
- Returns:
(VectorConstRef) Species molalities (mol/kg H2O@).
-
auto moleFractions() const -> VectorConstRef
Returns the mole fractions of the species.
// Example: Get species mole fractions. auto moleFrac = engine.moleFractions();
- Returns:
(VectorConstRef) Mole fractions.
-
auto lnActivityCoefficients() const -> VectorConstRef
Returns the ln activity coefficients of the species (mole fraction scale).
// Example: Retrieve ln activity coefficients. auto lnActCoeff = engine.lnActivityCoefficients();
- Returns:
(VectorConstRef) ln Activity coefficients.
-
auto lnActivities() const -> VectorConstRef
Returns the ln activities of the species.
// Example: Fetch ln activities. auto lnActivities = engine.lnActivities();
- Returns:
(VectorConstRef) ln Activities.
-
auto lnConcentrations() const -> VectorConstRef
Returns the ln of species concentrations.
// Example: Get ln concentrations. auto lnConcs = engine.lnConcentrations();
- Returns:
(VectorConstRef) ln concentrations.
-
auto chemicalPotentials() const -> VectorConstRef
Returns the chemical potentials of the species.
// Example: Retrieve species chemical potentials. auto chemPot = engine.chemicalPotentials();
- Returns:
(VectorConstRef) Chemical potentials in J/mol.
-
auto standardMolarGibbsEnergy(Index ispecies) const -> double
Returns the standard molar Gibbs energy of a species.
// Example: For species 0. double stdGibbs = engine.standardMolarGibbsEnergy(0);
- Parameters:
ispecies – (Index) Species index.
- Returns:
(double) Standard molar Gibbs energy in J/mol.
-
auto standardMolarEnthalpy(Index ispecies) const -> double
Returns the standard molar enthalpy of a species.
double stdEnthalpy = engine.standardMolarEnthalpy(0);
- Parameters:
ispecies – (Index) Species index.
- Returns:
(double) Standard molar enthalpy in J/mol.
-
auto standardMolarVolume(Index ispecies) const -> double
Returns the standard molar volume of a species.
double stdVolume = engine.standardMolarVolume(0);
- Parameters:
ispecies – (Index) Species index.
- Returns:
(double) Standard molar volume in m³/mol.
-
auto standardMolarEntropy(Index ispecies) const -> double
Returns the standard molar entropy of a species.
double stdEntropy = engine.standardMolarEntropy(0);
- Parameters:
ispecies – (Index) Species index.
- Returns:
(double) Standard molar entropy in J/(mol·K).
-
auto standardMolarHeatCapacityConstP(Index ispecies) const -> double
Returns the standard molar isobaric heat capacity of a species.
double heatCap = engine.standardMolarHeatCapacityConstP(0);
- Parameters:
ispecies – (Index) Species index.
- Returns:
(double) Heat capacity in J/(mol·K).
-
auto phaseMolarGibbsEnergy(Index iphase) const -> double
Returns the molar Gibbs energy of a phase.
double phaseGibbs = engine.phaseMolarGibbsEnergy(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Molar Gibbs energy in J/mol.
-
auto phaseMolarEnthalpy(Index iphase) const -> double
Returns the molar enthalpy of a phase.
double phaseEnthalpy = engine.phaseMolarEnthalpy(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Molar enthalpy in J/mol.
-
auto phaseMolarVolume(Index iphase) const -> double
Returns the molar volume of a phase.
double phaseVol = engine.phaseMolarVolume(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Molar volume in m³/mol.
-
auto phaseMolarEntropy(Index iphase) const -> double
Returns the molar entropy of a phase.
double phaseEnt = engine.phaseMolarEntropy(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Molar entropy in J/(mol·K).
-
auto phaseMolarHeatCapacityConstP(Index iphase) const -> double
Returns the molar isobaric heat capacity of a phase.
double phaseCp = engine.phaseMolarHeatCapacityConstP(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Heat capacity in J/(mol·K).
-
auto phaseSpecificGibbsEnergy(Index iphase) const -> double
Returns the specific Gibbs energy of a phase.
double specGibbs = engine.phaseSpecificGibbsEnergy(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Specific Gibbs energy in J/kg.
-
auto phaseSpecificEnthalpy(Index iphase) const -> double
Returns the specific enthalpy of a phase.
double specEnthalpy = engine.phaseSpecificEnthalpy(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Specific enthalpy in J/kg.
-
auto phaseSpecificVolume(Index iphase) const -> double
Returns the specific volume of a phase.
double specVolume = engine.phaseSpecificVolume(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Specific volume in m³/kg.
-
auto phaseSpecificEntropy(Index iphase) const -> double
Returns the specific entropy of a phase.
double specEntropy = engine.phaseSpecificEntropy(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Specific entropy in J/(kg·K).
-
auto phaseSpecificHeatCapacityConstP(Index iphase) const -> double
Returns the specific isobaric heat capacity of a phase.
double specCp = engine.phaseSpecificHeatCapacityConstP(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Heat capacity in J/(kg·K).
-
auto phaseDensities() const -> VectorConstRef
Returns the densities of all phases.
auto densities = engine.phaseDensities();
- Returns:
(VectorConstRef) Vector of densities in kg/m³.
-
auto phaseDensity(Index iphase) const -> double
Returns the density of a specified phase.
double density = engine.phaseDensity(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Density in kg/m³.
-
auto phaseMasses() const -> VectorConstRef
Returns the masses of all phases.
auto masses = engine.phaseMasses();
- Returns:
(VectorConstRef) Vector of masses in kg.
-
auto phaseMass(Index iphase) const -> double
Returns the mass of a specified phase.
double mass = engine.phaseMass(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Mass in kg.
-
auto phaseAmounts() const -> VectorConstRef
Returns the molar amounts of all phases.
auto phaseMol = engine.phaseAmounts();
- Returns:
(VectorConstRef) Vector of phase amounts in mol.
-
auto phaseAmount(Index iphase) const -> double
Returns the molar amount of a specific phase.
double amt = engine.phaseAmount(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Amount in mol.
-
auto phaseVolumes() const -> VectorConstRef
Returns the volumes of all phases.
auto volumes = engine.phaseVolumes();
- Returns:
(VectorConstRef) Vector of volumes in m³.
-
auto phaseVolume(Index iphase) const -> double
Returns the volume of a specific phase.
double vol = engine.phaseVolume(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Volume in m³.
-
auto phaseEnthalpies() const -> VectorConstRef
Returns the enthalpies of all phases.
auto enth = engine.phaseEnthalpies();
- Returns:
(VectorConstRef) Vector of enthalpies in J.
-
auto phaseEnthalpy(Index iphase) const -> double
Returns the enthalpy of a specific phase.
double enth0 = engine.phaseEnthalpy(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Enthalpy in J.
-
auto phaseEntropies() const -> VectorConstRef
Returns the entropies of all phases.
auto ents = engine.phaseEntropies();
- Returns:
(VectorConstRef) Vector of entropies in J/K.
-
auto phaseEntropy(Index iphase) const -> double
Returns the entropy of a specified phase.
double ent0 = engine.phaseEntropy(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Entropy in J/(K).
-
auto phaseHeatCapacitiesConstP() const -> VectorConstRef
Returns the heat capacities (Cp) of all phases.
auto cps = engine.phaseHeatCapacitiesConstP();
- Returns:
(VectorConstRef) Vector of heat capacities in J/K.
-
auto phaseHeatCapacityConstP(Index iphase) const -> double
Returns the heat capacity of a specified phase.
double cp0 = engine.phaseHeatCapacityConstP(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Heat capacity in J/K.
-
auto phaseSatIndices() const -> VectorConstRef
Returns the saturation indices of all phases (log₁₀ units).
auto satIdx = engine.phaseSatIndices();
- Returns:
(VectorConstRef) Vector of saturation indices.
-
auto phaseSatIndex(Index iphase) const -> double
Returns the saturation index of a specific phase (log₁₀ units).
double sat0 = engine.phaseSatIndex(0);
- Parameters:
iphase – (Index) Phase index.
- Returns:
(double) Saturation index.
-
auto systemMass() const -> double
Returns the total mass of the system.
double sysMass = engine.systemMass(); std::cout << "System mass: " << sysMass << " kg" << std::endl;
- Returns:
(double) System mass in kg.
-
auto systemVolume() const -> double
Returns the total volume of the system.
double sysVol = engine.systemVolume(); std::cout << "System volume: " << sysVol << " m³" << std::endl;
- Returns:
(double) Volume in m³.
-
auto ionicStrength() const -> double
Returns the ionic strength of the aqueous phase.
double ionicStr = engine.ionicStrength();
- Returns:
(double) Ionic strength in molal.
-
auto pH() const -> double
Returns the pH of the aqueous phase.
double ph = engine.pH();
- Returns:
(double) pH (in the activity scale (-log10 molal)).
-
auto pe() const -> double
Returns the pe of the aqueous phase.
double pe = engine.pe();
- Returns:
(double) pe (in the activity scale (-log10 molal)).
-
auto Eh() const -> double
Returns the Eh of the aqueous phase.
double eh = engine.Eh();
- Returns:
(double) Eh (V).
-
auto systemGibbsEnergy() const -> double
Returns the total Gibbs energy of the system.
double sysGibbs = engine.systemGibbsEnergy();
- Returns:
(double) Gibbs energy in J/mol.
-
auto systemEnthalpy() const -> double
Returns the total enthalpy of the system.
double sysEnthalpy = engine.systemEnthalpy();
- Returns:
(double) Enthalpy in J.
-
auto systemEntropy() const -> double
Returns the total entropy of the system.
double sysEntropy = engine.systemEntropy();
- Returns:
(double) Entropy in J/K.
-
auto systemHeatCapacityConstP() const -> double
Returns the total isobaric heat capacity of the system.
double sysCp = engine.systemHeatCapacityConstP();
- Returns:
(double) Heat capacity in J/K.
-
auto aqueousPhaseName() const -> std::string
Returns the aqueous phase name.
auto aqueous_name = engine.aqueousPhaseName();
- Returns:
(string) aqueous phase name. If empty, the aqueous phase is not in system.
-
auto gasPhaseName() const -> std::string
Returns the gaseous phase name.
auto gaseous_name = engine.gasPhaseName();
- Returns:
(string) gaseous phase name. If empty, the gaseous phase is not in system.
Private Members
-
std::unique_ptr<Impl> pimpl
-
ChemicalEngine()
-
class ChemicalEngineMaps
- #include <ChemicalEngineMaps.hpp>
Class for equilibrium computations and thermodynamic analysis using dictionaries.
The ChemicalEngineMaps is a more convenient wrapper for Gibbs energy minimization to compute the equilibrium state of a chemical system with a Pythonic naming convention and dictionaries. Its API provides methods to load system data, update component amounts, and query resulting thermodynamic properties as a dictionary map. Gems interface in calculator format for easy using dictionaries.
Public Functions
-
ChemicalEngineMaps(const std::string &input_file, bool reset_calc = false, bool cold_start = true)
Constructs a ChemicalEngineMaps instance by loading a GEM-Selektor project file.
xGEMS::ChemicalEngineMaps engine("my-system-dat.lst");
- Parameters:
input_file – The file path for the chemical system definition (e.g., “my-system-dat.lst”).
reset_calc – (bool) If true, clear the amounts of all elements, default false.
cold_start – (bool) If true, configures the engine to use a cold start, default true.
-
auto equilibrate() -> std::string
Computes the equilibrium stateof the current system.
Uses current temperature (K), pressure (Pa), and element amounts (in mol) to compute equilibrium.
engine.T = 298.15; engine.P = 100000.0; xGEMS::ValuesMap bulk_composition = { {"C", 1e-08}, {"Ca", 1e-08}, {"Cl", 0.002}, {"H", 111.016746657646}, {"Mg", 0.001}, {"O", 55.5083933588231}, {"Sn", 130.841288437146}, {"Zz", 0.0} }; engine.set_bulk_composition(bulk_composition); std::string retcode = engine.equilibrate();
No GEM re-calculation needed
Need GEM calculation with LPP (automatic) initial approximation (AIA)
OK after GEM calculation with LPP AIA
Bad (not fully trustful) result after GEM calculation with LPP AIA
Failure (no result) in GEM calculation with LPP AIA
Need GEM calculation with no-LPP (smart) IA, SIA using the previous speciation
OK after GEM calculation with SIA
Bad (not fully trustful) result after GEM calculation with SIA
Failure (no result) in GEM calculation with SIA
Terminal error in GEMS3K (e.g., memory corruption). Restart required.
- Returns:
(std::string) Return result string of the equilibrium solver.
-
inline auto cold_start() -> void
Configures the engine to use a cold start.
Uses a simplex LP initial guess (slower but may yield more accurate results).
engine.cold_start();
-
inline void warm_start()
Configures the engine to use a warm (smart) start.
Uses previous equilibrium as initial guess (faster convergence).
engine.warm_start();
-
auto clear(double min_amount = 1e-15) -> void
Clear the amounts of elements (set the default amount for all components).
engine.clear(1e-15);
- Parameters:
min_amount – (double) The minimum amount of element in mole, default 1e-15.
-
auto set_species_G0(std::string symbol, double value) -> void
Sets the standard molar Gibbs energy for a species (@ T, P of the system).
engine.set_species_G0("H2O", -237140); // Value in J/mol.
- Parameters:
symbol – (std::string) Species symbol.
value – (double) Standard molar Gibbs energy in J/mol.
-
auto set_bulk_composition(ValuesMap b_input, double min_amount = 1e-15) -> void
Sets the amounts of elements (vector b).
xGEMS::ValuesMap bulk_composition = { {"C", 1e-08}, {"Ca", 1e-08}, {"Cl", 0.002}, {"H", 111.016746657646}, {"Mg", 0.001}, {"O", 55.5083933588231}, {"Sn", 130.841288437146}, {"Zz", 0.0} }; engine.set_bulk_composition(bulk_composition);
- Parameters:
b_input – (ValuesMap) Dictionary of elements amounts in mol.
min_amount – (double) min amount of element in mol, default 1e-15.
-
auto reset_aq_composition(double min_amount = 1e-12) -> void
Removes bulk elemental aqueous solution composition from vector b.
Be careful as this will also remove water i.e H+ and OH-.
engine.reset_aq_composition();
- Parameters:
min_amount – (double) min amount of element in mol, default 1e-12.
-
inline auto nelements() -> int
Returns the number of elements in the system.
Index count = engine.nelements(); std::cout << "Elements: " << count << std::endl;
- Returns:
(Index) Total number of elements.
-
inline auto nphases() -> int
Returns the number of phases in the system.
Index count = engine.nphases(); std::cout << "Phases: " << count << std::endl;
- Returns:
(Index) Total number of phases.
-
inline auto nspecies() -> int
Returns the number of species in the system.
Index count = engine.nspecies(); std::cout << "Species: " << count << std::endl;
- Returns:
(Index) Total number of chemical species.
-
inline auto element_names() -> std::vector<std::string>
Returns the names of all elements in the system.
auto names = engine.element_names(); std::cout << "Element 0: " << names[0] << std::endl;
- Returns:
(std::vector<std::string>) Element names.
-
inline auto species_names() -> std::vector<std::string>
Returns the names of all species in the system.
auto names = engine.species_names(); std::cout << "Species 0: " << names[0] << std::endl;
- Returns:
(std::vector<std::string>) Species names.
-
inline auto phase_names() -> std::vector<std::string>
Returns the names of all phases in the system.
auto names = engine.phase_names(); std::cout << "Phase 0: " << names[0] << std::endl;
- Returns:
(std::vector<std::string>) Phase names.
-
inline auto aq_phase_symbol() -> std::string
Returns the aqueous phase name.
auto aqueous_name = engine.aq_phase_symbol();
- Returns:
(std::string) aqueous phase name. If empty, the aqueous phase is not in system.
-
inline auto gas_phase_symbol() -> std::string
Returns the gaseous phase name.
auto gaseous_name = engine.gas_phase_symbol();
- Returns:
(std::string) gaseous phase name. If empty, the gaseous phase is not in system.
-
inline auto element_molar_masses() -> ValuesMap
Returns molar masses of elements.
auto values = engine.element_molar_masses(); std::cout << "Molar mass of 'Fe': " << values["Fe"] << std::endl;
- Returns:
(ValuesMap) Dictionary of molar masses (kg/mol) for each element.
-
inline auto species_in_phase() -> std::map<std::string, std::vector<std::string>>
Returns the names of all species for each phase in the system.
auto map_names = engine.species_in_phase();
- Returns:
(std::map<std::string, std::vector<std::string>>) Dictionary of species names.
-
inline auto species_charges() -> ValuesMap
Returns the electrical charge of a species.
auto charge = engine.species_charges(); std::cout << "Charge of 'OH-': " << charge["OH-"] << std::endl;
- Returns:
(ValuesMap) Dictionary charges of the species.
-
inline auto species_molar_mass() -> ValuesMap
Returns molar masses of species.
auto values = engine.species_molar_mass(); std::cout << "Molar mass of 'H2O@': " << values["H2O@"] << std::endl;
- Returns:
(ValuesMap) Dictionary of species molar masses (kg/mol).
-
inline auto species_molar_volumes() -> ValuesMap
Returns the standard molar volumes of a species.
auto values = engine.species_molar_volumes(); std::cout << "Molar volume of 'H2O@': " << values["H2O@"] << std::endl;
- Returns:
(ValuesMap) Dictionary of species standard molar volumes in m³/mol.
-
auto bulk_composition() -> ValuesMap
Returns the amounts of the elements.
auto amounts = engine.bulk_composition();
- Returns:
(ValuesMap) Dictionary of elements amounts in mol.
-
auto pH() -> double
Returns the pH of the aqueous phase.
double ph = engine.pH();
- Returns:
(double) pH (in the activity scale (-log10 molal)).
-
auto pE() -> double
Returns the pe of the aqueous phase.
double pe = engine.pE();
- Returns:
(double) pe (in the activity scale (-log10 molal)).
-
auto ionic_strength() -> double
Returns the ionic strength of the aqueous phase.
double ionicStr = engine.ionic_strength();
- Returns:
(double) Ionic strength in molal.
-
auto system_volume() -> double
Returns the total volume of the system.
double volume = engine.system_volume();
- Returns:
(double) Volume in m³.
-
auto system_mass() -> double
Returns the total mass of the system.
double mass = engine.system_mass();
- Returns:
(double) System mass in kg.
-
auto phases_molar_volume() -> ValuesMap
Returns the molar volumes of the phases.
auto volumes = engine.phases_molar_volume(); std::cout << "Molar volume of 'aq_gen': " << volumes["aq_gen"] << std::endl;
- Returns:
(ValuesMap) Dictionary of phases molar volumes in m³/mol.
-
auto phase_sat_indices() -> ValuesMap
Returns the saturation indices of all phases (log₁₀ units).
auto sat_indices = engine.phase_sat_indices(); std::cout << "Saturation indice of 'aq_gen': " << sat_indices["aq_gen"] << std::endl;
- Returns:
(ValuesMap) Dictionary of phases saturation indices.
-
auto aq_elements_molarity() -> ValuesMap
Returns the aq solution composition in mol/L aq solution.
auto molarity = engine.aq_elements_molarity(); std::cout << "Molarity of 'O': " << molarity["O"] << std::endl;
- Returns:
(ValuesMap) Dictionary for aq elements.
-
auto aq_elements_molality() -> ValuesMap
Returns the aq solution elemental composition in mol/kgH2O.
auto molality = engine.aq_elements_molality(); std::cout << "Molality of 'O': " << molality["O"] << std::endl;
- Returns:
(ValuesMap) Dictionary for aq elements.
-
auto aq_species_molarity() -> ValuesMap
Returns the aq solution composition in mol/L of aqueous species.
auto molarity = engine.aq_species_molarity(); std::cout << "Molarity of 'H2O@': " << molarity["H2O@"] << std::endl;
- Returns:
(ValuesMap) Dictionary for aq species.
-
auto aq_species_molality() -> ValuesMap
Returns the aq solution composition in mol/kg H2O of aqueous species (speciation).
auto molality = engine.aq_species_molality(); std::cout << "Molality of 'Mg(CO3)@': " << molality["Mg(CO3)@"] << std::endl;
- Returns:
(ValuesMap) Dictionary for aq species.
-
auto aq_elements_moles() -> ValuesMap
Returns the amounts of elements in a aqueous phase.
auto amount = engine.aq_elements_moles(); std::cout << "Amount of 'O' in the aqueous phase: " << amount["O"] << std::endl;
- Returns:
(ValuesMap) Dictionary containing the amounts of each element in the aqueous phase (in mol).
-
auto solids_elements_moles(double min_amount_phase = 1e-12, double min_amount_element = 1e-14) -> ValuesMap
Returns the mole amounts of elements in all solids together.
auto amount = engine.solids_elements_moles(); std::cout << "Amount of 'Sn' in the solids phases: " << amount["Sn"] << std::endl;
- Parameters:
min_amount_phase – (double) min amount of phase in mol, default 1e-12.
min_amount_element – (double) min amount of element in mol, default 1e-14.
- Returns:
(ValuesMap) Dictionary containing mole amounts of elements in all solids together.
-
auto phases_elements_moles() -> PhaseValuesMap
Returns a dictionary (table) containing amounts of elements in phases in moles.
auto phase_el_moles = engine.phases_elements_moles(); std::cout << "Amount of 'Ca' in 'aq_gen' phase: " << phase_el_moles["aq_gen"]["Ca"] << std::endl;
- Returns:
(PhaseValuesMap) A dictionary of dictionaries containing mole amounts of elements for each phase.
-
auto phases_moles() -> ValuesMap
Returns the molar amounts of all phases.
auto amounts = engine.phases_moles(); std::cout << "Amount of 'aq_gen' phase: " << amounts["aq_gen"] << std::endl;
- Returns:
(ValuesMap) Dictionary of phases amounts in mol.
-
auto species_moles() -> ValuesMap
Returns the amounts of all species.
auto amounts = engine.species_moles(); std::cout << "Amount of 'H2O@': " << amounts2["H2O@"] << std::endl;
- Returns:
(ValuesMap) Dictionary of species amounts in mol.
-
auto species_ln_activities() -> ValuesMap
Returns the ln activities of all species.
auto lnActivities = engine.species_ln_activities(); std::cout << "ln Activity of 'H2O@': " << lnActivities["H2O@"] << std::endl;
- Returns:
(ValuesMap) Dictionary of species ln Activities.
-
auto species_ln_activity_coefficients() -> ValuesMap
Returns the ln activity coefficients of all species (mole fraction scale).
auto lnActCoeff = engine.species_ln_activity_coefficients(); std::cout << "ln Activity coeff of 'H2O@': " << lnActCoeff["H2O@"] << std::endl;
- Returns:
(ValuesMap) Dictionary of species ln Activity coefficients.
-
auto species_upper_bounds() -> ValuesMap
Returns the upper limits for all species.
auto upperLimits = engine.species_upper_bounds(); std::cout << "Upper bounds of 'Mg(HCO3)+': " << upperLimits["Mg(HCO3)+"] << std::endl;
- Returns:
(ValuesMap) Dictionary of species upper limits in mol.
-
auto species_lower_bounds() -> ValuesMap
Returns the lower limits for all species.
auto lowerLimits = engine.species_lower_bounds(); std::cout << "Lower bounds of 'Mg(HCO3)+': " << lowerLimits["Mg(HCO3)+"] << std::endl;
- Returns:
(ValuesMap) Dictionary of species lower limits in mol.
-
auto phase_species_moles(std::string phase_symbol) -> ValuesMap
Returns the amounts of the phase species.
auto amounts = engine.phase_species_moles("aq_gen"); std::cout << "Amount of 'H2O@' in 'aq_gen' phase:" << amounts["H2O@"] << std::endl;
- Parameters:
phase_symbol – (std::string) phase name.
- Returns:
(ValuesMap) Dictionary of phase species amounts in mol.
-
auto solids_mass_frac() -> ValuesMap
Returns the mass(phase)/mass(system) ratios for [solid] phases.
auto mas_frac = engine.solids_mass_frac(); std::cout << "Mass fraction of 'Tin' phase: " << mas_frac["Tin"] << std::endl;
- Returns:
(ValuesMap) Dictionary of solids phases mass fraction.
-
auto solids_volume_frac() -> ValuesMap
Returns the volume(phase)/volume(total) ratio for solid phases.
auto vol_frac = engine.solids_volume_frac(); std::cout << "Volume fraction of 'Tin' phase from total system volume: " << vol_frac["Tin"] << std::endl;
- Returns:
(ValuesMap) Dictionary of solids phases volume fraction from total system volume.
-
auto aq_volume_frac() -> double
Returns the volume fraction of aqueous phase from total system volume.
auto volume = engine.aq_volume_frac();
- Returns:
(double) Volume fraction of aqueous phase from total system volume.
-
auto phases_volume() -> ValuesMap
Returns the volumes of all phases.
auto volumes = engine.phases_volume(); std::cout << "Volume of 'Tin' phase: " << volumes["Tin"] << std::endl;
- Returns:
(ValuesMap) Dictionary of phases volumes in m³.
-
auto phases_mass() -> ValuesMap
Returns the masses of all phases.
auto masses = engine.phases_mass(); std::cout << "Mass of 'Tin' phase: " << masses["Tin"] << std::endl;
- Returns:
(ValuesMap) Dictionary of phases masses in kg.
-
auto phases_volume_frac() -> ValuesMap
Returns the volume fractions of all phases from total system volume.
auto volumes = engine.phases_volume_frac(); std::cout << "Volume fraction from total system volume of 'aq_gen' phase: " << volumes["aq_gen"] << std::endl;
- Returns:
(ValuesMap) Dictionary of phases and their volume fractions from total system volume.
-
auto add_multiple_species_amt(const ValuesMap &input_dict, const std::string &units = "moles") -> void
Add multiple species amounts in the system useful for adding aqueous solution composition.
engine.add_multiple_species_amt({ {"HCl@",0.01}, {"H2@",2} }, "moles");
- Parameters:
input_dict – (ValuesMap) Dictionary of species amount in units.
units – (std::string) Units of amount (“moles”, “kg”, “m3”), default “moles”.
-
auto add_species_amt(const std::string &species, double val, const std::string &units = "moles") -> void
Add species amount in the system useful for adding aqueous solution composition.
engine.add_species_amt("H2O@", 0.01, "kg");
- Parameters:
species – (std::string) Species symbol.
val – (double) Species amount in units.
units – (std::string) Units of amount (“moles”, “kg”, “m3”), default “moles”.
-
auto add_element_amt(const std::string &element_name, double val, const std::string &units = "moles") -> void
Add element amount in the system.
engine.add_element_amt("Al", 0.3, "moles");
- Parameters:
element_name – (std::string) Element symbol.
val – (double) Element amount in units.
units – (std::string) Units of amount (“moles”, “kg”), default “moles”.
-
auto add_multiple_elements_amt(const ValuesMap &input_dict, const std::string &units = "moles") -> void
Add multiple elements amount in the system useful for adding aqueous solution composition.
engine.add_multiple_elements_amt({ {"Na",1.013077}, {"Si",1.013077} }, "moles");
- Parameters:
input_dict – (ValuesMap) Dictionary of elements amount in units.
units – (std::string) Units of amount (“moles”, “kg”), default “moles”.
-
auto add_amt_from_formula(const ValuesMap &formula, double val, const std::string &units = "moles") -> void
Add multiple elements using user defined formula.
engine.add_amt_from_formula( { {"K",2}, {"O",1} }, 4.108*1e-3, "kg");
- Parameters:
formula – (ValuesMap) User defined formula.
val – (double) Component amount in units.
units – (std::string) Units of amount (“moles”, “kg”), default “moles”.
-
auto get_b_from_formula(const ValuesMap &formula, double val = 1, const std::string &units = "moles", double min_amount = 1e-15) -> Vector
Returns a bulk vector b from user-defined formula (as dict.
{“H”:2,”O”:1} ) and amount of the formula [object] in units of ‘moles’ or ‘kg’.
auto vect = engine.get_b_from_formula( {{"H",2},{"O",1}}, 0.1, "kg");
- Parameters:
formula – (ValuesMap) User defined formula.
val – (double) Amount of the formula [object] in units, default 1.
units – (std::string) Units of amount (“moles”, “kg”), default “moles”.
min_amount – (double) min amount of element in mol, default 1e-15.
- Returns:
(VectorConstRef) Vector of element amounts in mol.
-
auto set_multiple_species_lower_bound(const ValuesMap &input_dict, const std::string &units = "moles") -> void
Sets an lower bound for multiple species.
engine.set_multiple_species_lower_bound( {{"Mg(CO3)@",30}, {"Mg(HCO3)+",40}, {"Mg+2",50}});
- Parameters:
input_dict – (ValuesMap) Dictionary of species lower bound.
units – (std::string) Units of lower bound (“moles”, “kg”, “m3”), default “moles”.
-
auto set_multiple_species_upper_bound(const ValuesMap &input_dict, const std::string &units = "moles") -> void
Sets an upper bounds for multiple species.
engine.set_multiple_species_upper_bound( {{"Mg(CO3)@",300}, {"Mg(HCO3)+",400}, {"Mg+2",500}}, "moles");
- Parameters:
input_dict – (ValuesMap) Dictionary of species upper bound.
units – (std::string) Units of upper bound (“moles”, “kg”, “m3”), default “moles”.
-
auto set_species_lower_bound(const std::string &name, double val, const std::string &units = "moles") -> void
Sets a lower bound for a species identified by name.
engine.set_species_lower_bound( "Ca(HCO3)+", 200, "moles");
- Parameters:
name – (std::string) Species name.
val – (double) Lower limit in units.
units – (std::string) Units of amount (“moles”, “kg”, “m3”), default “moles”.
-
auto set_species_upper_bound(const std::string &name, double val, const std::string &units = "moles") -> void
Sets an upper bound for a species identified by name.
engine.set_species_upper_bound("CaOH+", 500, "kg");
- Parameters:
name – (std::string) Species name.
val – (double) Upper limit in units.
units – (std::string) Units of amount (“moles”, “kg”, “m3”), default “moles”.
-
auto set_species_lower_bound(Index ispecies, double val, const std::string &units = "moles") -> void
Sets a lower bound (minimum amount allowed to form) for a species identified by its index (phase depended case).
engine.set_species_lower_bound(8, 400, "moles");
- Parameters:
ispecies – (Index) Species index.
val – (double) Lower limit in units.
units – (std::string) Units of amount (“moles”, “kg”, “m3”), default “moles”.
-
auto set_species_upper_bound(Index ispecies, double val, const std::string &units = "moles") -> void
Sets an upper bound (maximum amount allowed to form) for a species identified by its index (phase depended case).
engine.set_species_upper_bound( 8, 900, "kg");
- Parameters:
ispecies – (Index) Species index.
val – (double) Upper limit in units.
units – (std::string) Units of amount (“moles”, “kg”, “m3”), default “moles”.
-
auto suppress_phase(const std::string &phase_name, double min_amount = 0, double max_amount = 1e-15) -> void
Suppresses a phase in GEM calculation.
engine.suppress_phase("gas_gen");
- Parameters:
phase_name – (std::string) Phase name.
min_amount – (double) Lower amount of specie in mol, default 0.
max_amount – (double) Upper amount of specie in mol, default 1e-15.
-
auto suppress_multiple_phases(const std::vector<std::string> &phase_name_list, double min_amount = 0, double max_amount = 1e-15) -> void
Suppresses multiple phases in calculation as given in phase names list.
engine.suppress_multiple_phases({"Dolomite-dis", "Tin"});
- Parameters:
phase_name_list – (std::vector<std::string>) Phases name list.
min_amount – (double) Lower amount of specie in mol, default 0.
max_amount – (double) Upper amount of specie in mol, default 1e-15.
-
auto suppress_species(const std::string &species_name, double min_amount = 0, double max_amount = 1e-15) -> void
Suppresses a specie in calculation.
engine.suppress_species("Ca(CO3)@");
- Parameters:
species_name – (std::string) Species name.
min_amount – (double) Lower amount of specie in mol, default 0.
max_amount – (double) Upper amount of specie in mol, default 1e-15.
-
auto suppress_multiple_species(const std::vector<std::string> &species_list, double min_amount = 0, double max_amount = 1e-15) -> void
Suppresses multiple species in in GEM calculation as given in species name list.
engine.suppress_multiple_species({"ClO4-", "Cl-"});
- Parameters:
species_list – (std::vector<std::string>) Species name list.
min_amount – (double) Lower amount of specie in mol, default 0.
max_amount – (double) Upper amount of specie in mol, default 1e-15.
-
auto activate_phase(const std::string &phase_name) -> void
Activate suppressed phase in GEM calculation.
engine.activate_phase("gas_gen");
- Parameters:
phase_name – (std::string) Phase name.
-
auto activate_multiple_phases(const std::vector<std::string> &phase_name_list) -> void
Activate multiple suppressed phases given in list.
engine.activate_multiple_phases({"Dolomite-dis", "Tin"});
- Parameters:
phase_name_list – (std::vector<std::string>) Phases name list.
-
auto activate_multiple_species(const std::vector<std::string> &species_list) -> void
Activate multiple suppressed species given in the list.
engine.activate_multiple_species({"Ca(HCO3)+", "CaOH+", "Mg(CO3)@", "Mg(HCO3)+", "Mg+2", "ClO4-", "Cl-"});
- Parameters:
species_list – (std::vector<std::string>) Species name list.
-
auto activate_species(const std::string &species_name) -> void
Activate a suppressed species in phase.
engine.activate_species("Ca(CO3)@");
- Parameters:
species_name – (std::string) Species name.
-
auto phase_species_moles() -> PhaseValuesMap
Returns all species amounts in moles.
auto amounts = engine.phase_species_moles(); std::cout << "Amount of 'CaOH+' in 'aq_gen' phase: " << amounts["aq_gen"]["CaOH+"] << std::endl;
- Returns:
(PhaseValuesMap) A dictionary of dictionaries containing species amounts in mol for each phase.
-
auto phase_species_ln_activities() -> PhaseValuesMap
Returns the ln activities of the species.
auto lnActivities = engine.phase_species_ln_activities(); std::cout << "ln activities of 'CaOH+' in 'aq_gen' phase: " << lnActivities["aq_gen"]["CaOH+"] << std::endl;
- Returns:
(PhaseValuesMap) A dictionary of dictionaries containing species ln Activities for each phase.
-
auto phase_species_ln_activity_coefficients() -> PhaseValuesMap
Returns the ln activity coefficients of the species (mole fraction scale).
auto lnActCoeff = engine.phase_species_ln_activity_coefficients(); std::cout << "ln activities coeff of 'CaOH+' in 'aq_gen' phase: " << lnActCoeff["aq_gen"]["CaOH+"] << std::endl;
- Returns:
(PhaseValuesMap) A dictionary of dictionaries containing species ln Activity coefficients for each phase.
-
auto phase_species_upper_bounds() -> PhaseValuesMap
Returns the upper limits for all species.
auto upperLimits = engine.phase_species_upper_bounds(); std::cout << "Upper limits of 'CaOH+' in 'aq_gen' phase: " << upperLimits["aq_gen"]["CaOH+"] << std::endl;
- Returns:
(PhaseValuesMap) A dictionary of dictionaries containing species upper limits in mol for each phase.
-
auto phase_species_lower_bounds() -> PhaseValuesMap
Returns the lower limits for all species.
auto lowerLimits = engine.phase_species_lower_bounds(); std::cout << "Lower limits of 'CaOH+' in 'aq_gen' phase: " << lowerLimits["aq_gen"]["CaOH+"] << std::endl;
- Returns:
(PhaseValuesMap) A dictionary of dictionaries containing species lower limits in mol for each phase.
Public Members
-
double T
Sets and gets the temperature without computing equilibrium.
T Temperature in Kelvin (K).
engine.T = 298.15;
-
double P
Sets and gets the pressure without computing equilibrium.
P Pressure in Pascals (Pa).
engine.P = 100000.0;
Protected Functions
-
auto to_phase_species_map(Vector values) -> PhaseValuesMap
Protected Attributes
-
std::string input_file
-
ChemicalEngine gem
-
std::vector<std::string> m_element_names
-
std::vector<std::string> m_species_names
-
std::vector<std::string> m_phase_names
-
std::string m_aq_phase_symbol
-
std::string m_gas_phase_symbol
-
std::map<std::string, std::vector<std::string>> m_species_in_phase
dictionary containing species in phase
-
ChemicalEngineMaps(const std::string &input_file, bool reset_calc = false, bool cold_start = true)
-
struct ChemicalEngineOptions
- #include <ChemicalEngine.hpp>
Options for configuring a ChemicalEngine instance.
This structure contains settings (e.g., initial approximation method) that affect the performance and accuracy of the equilibrium computations.
// Example: Disable warm start when a more robust (cold start) solution is needed. xGEMS::ChemicalEngineOptions options; options.warmstart = false;
Note
The member
warmstartindicates whether a “smart” (fast but possibly less accurate) initial approximation is used.
-
namespace xGEMS
Typedefs
-
using ValuesMap = std::map<std::string, double>
ValuesMap is a sorted associative dictionary that contains name-value pairs.
-
using PhaseValuesMap = std::map<std::string, ValuesMap>
PhaseValuesMap is a sorted associative container that contains dictionaries for all phase species.
-
using Vector = Eigen::VectorXd
-
using VectorXd = Eigen::VectorXd
Alias to Eigen type Eigen::VectorXd.
-
using VectorXi = Eigen::VectorXi
Alias to Eigen type Eigen::VectorXd.
-
using VectorXdConstRef = Eigen::Ref<const VectorXd>
Alias to Eigen type Eigen::Ref<const VectorXd>.
-
using VectorXiConstRef = Eigen::Ref<const VectorXi>
Alias to Eigen type Eigen::Ref<const VectorXi>.
-
using VectorXdConstMap = Eigen::Map<const VectorXd>
Alias to Eigen type Eigen::Map<const VectorXd>.
-
using VectorXiConstMap = Eigen::Map<const VectorXi>
Alias to Eigen type Eigen::Map<const VectorXi>.
-
using Matrix = Eigen::MatrixXd
-
using MatrixXd = Eigen::MatrixXd
Alias to Eigen type Eigen::MatrixXd.
-
using MatrixXi = Eigen::MatrixXi
Alias to Eigen type Eigen::MatrixXd.
-
using MatrixXdConstRef = Eigen::Ref<const MatrixXd>
Alias to Eigen type Eigen::Ref<const MatrixXd>.
-
using MatrixXiConstRef = Eigen::Ref<const MatrixXi>
Alias to Eigen type Eigen::Ref<const MatrixXi>.
-
using MatrixXdConstMap = Eigen::Map<const MatrixXd>
Alias to Eigen type Eigen::Map<const MatrixXd>.
-
using MatrixXiConstMap = Eigen::Map<const MatrixXi>
Alias to Eigen type Eigen::Map<const MatrixXi>.
-
using Index = std::ptrdiff_t
Functions
-
void update_loggers(bool use_cout, const std::string &logfile_name, size_t log_level)
Updates logger settings.
Configures logging behavior for the ChemicalEngine.
// Example: Enable stdout logging and log to "chemical_log.txt" with verbosity level 2. xGEMS::update_loggers(true, "chemical_log.txt", 2);
- Parameters:
use_cout – If true, prints log messages to stdout.
logfile_name – The filename for a rotating log file. If empty, file logging is disabled.
log_level – Verbosity level for logging (trace = 0, debug = 1, info = 2, warn = 3, err = 4, critical = 5, off = 6 ).
-
void printWrappedTable(std::ostream &out, const std::string &row_label, const std::vector<std::string> &column_names, const std::vector<std::string> &row_names, const std::vector<Vector> &rows, std::size_t max_width = 175, std::size_t col_width = 25)
-
auto operator<<(std::ostream &out, const ChemicalEngine &engine) -> std::ostream&
Outputs the state of the ChemicalEngine.
Overloaded stream operator for convenient printing of engine details.
// Example: Print the engine state. std::cout << engine << std::endl;
- Parameters:
out – Output stream.
engine – ChemicalEngine instance.
- Returns:
(std::ostream&) Updated output stream.
Variables
-
static std::map<int, std::string> _status_encoder = {{0, "No GEM re-calculation needed"}, {1, "Need GEM calculation with LPP (automatic) initial approximation (AIA)"}, {2, "OK after GEM calculation with LPP AIA"}, {3, "Bad (not fully trustful) result after GEM calculation with LPP AIA"}, {4, "Failure (no result) in GEM calculation with LPP AIA"}, {5, "Need GEM calculation with no-LPP (smart) IA, SIA using the previous speciation (full DATABR lists only)"}, {6, "OK after GEM calculation with SIA"}, {7, "Bad (not fully trustful) result after GEM calculation with SIA"}, {8, "Failure (no result) in GEM calculation with SIA"}, {9, "Terminal error has occurred in GEMS3K (e.g. memory corruption). Restart is required."},}
-
const auto all = Eigen::all
Alias to Eigen placeholder value Eigen::placeholder::all.
-
using ValuesMap = std::map<std::string, double>
- file ChemicalEngine.cpp
- #include “ChemicalEngine.hpp”#include <chrono>#include <iomanip>#include <memory>#include <GEMS3K/node.h>#include <GEMS3K/gems3k_impex.h>#include <GEMS3K/jsonconfig.h>
- file ChemicalEngine.hpp
- #include <iostream>#include <memory>#include <string>#include <xGEMS/Index.hpp>#include <xGEMS/Eigen.hpp>
Header file for the ChemicalEngine class.
xGEMS is a C++ and Python library for thermodynamic modeling by Gibbs energy minimization This file defines the classes and functions for Gibbs-energy minimization thermodynamic modeling with xGEMS. Units used throughout the API are:
Temperature: Kelvin (K)
Pressure: Pascals (Pa)
Amounts: moles (mol)
Mass: kilograms (kg)
Volume: cubic meters (m³)
Energies: Joules (J) or Joules per mole (J/mol) as appropriate.
Example applications of these functions can be found in the demos at: /demos/
license GNU General Public License v3 or later
- Author
Allan Leal, Dmtrii Kulik, G.D. Miron
- Date
2025
Note
The examples below are indicative; please ensure that your vectors and matrices (such as VectorConstRef) are properly defined (e.g., using Eigen).
- file ChemicalEngineMaps.cpp
- #include <map>#include “ChemicalEngineMaps.hpp”
- file ChemicalEngineMaps.hpp
- #include <vector>#include <map>#include “ChemicalEngine.hpp”
Header file for the ChemicalEngineMaps class.
xGEMS is a C++ and Python library for thermodynamic modeling by Gibbs energy minimization This file defines the classes and functions for Gibbs-energy minimization thermodynamic modeling with xGEMS. Units used throughout the API are:
Temperature: Kelvin (K)
Pressure: Pascals (Pa)
Amounts: moles (mol)
Mass: kilograms (kg)
Volume: cubic meters (m³)
Energies: Joules (J) or Joules per mole (J/mol) as appropriate.
Example applications of these functions can be found in the demos at: /demos/
license GNU General Public License v3 or later
- Author
R.A.Patel, Dmtrii Kulik, G.D. Miron, S.Dmytriieva
- Date
2025
- file Eigen.hpp
- #include <eigen3/Eigen/Core>
- file Index.hpp
- #include <cstddef>
- dir xGEMS