Class GibbsReactor
- All Implemented Interfaces:
Serializable, Runnable, ProcessEquipmentInterface, TwoPortInterface, ProcessElementInterface, SimulationInterface, NamedInterface
This reactor computes chemical equilibrium compositions by minimizing the total Gibbs free energy of the system subject to elemental mass balance constraints. The implementation uses the Newton-Raphson method with Lagrange multipliers to solve the constrained optimization problem.
Key Features
- Supports both isothermal and adiabatic operation modes
- Handles multi-component systems with element balance constraints
- Allows marking specific components as inert (excluded from reactions)
- Provides detailed convergence diagnostics and mass balance verification
Algorithm
The reactor minimizes the objective function:
G = Σ nᵢ(μᵢ⁰ + RT ln(φᵢyᵢP)) - Σ λⱼ(Σ aᵢⱼnᵢ - bⱼ)
where nᵢ are molar amounts, μᵢ⁰ is standard chemical potential, φᵢ is fugacity coefficient, yᵢ is mole fraction, λⱼ are Lagrange multipliers, aᵢⱼ are stoichiometric coefficients, and bⱼ are element totals.
Usage Example
GibbsReactor reactor = new GibbsReactor("reactor", inletStream);
reactor.setEnergyMode(EnergyMode.ISOTHERMAL);
reactor.setMaxIterations(5000);
reactor.setConvergenceTolerance(1e-6);
reactor.setDampingComposition(0.01);
reactor.run();
if (reactor.hasConverged()) {
Stream outlet = reactor.getOutletStream();
double enthalpyChange = reactor.getEnthalpyOfReactions();
}
- Version:
- $Id: $Id
- Author:
- Sviatoslav Eroshkin
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enumReactor energy mode: isothermal (constant temperature) or adiabatic (no heat exchange).classInner class representing a component in the Gibbs reaction database. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate intprivate doubleArmijo sufficient decrease parameter c1 in (0, 1).private intMaximum number of backtracking steps in Armijo line search.private doubleBacktracking contraction factor rho in (0, 1).private double[]Column scaling factors from the NASA CEA log-mole transformation applied to the Jacobian.private Map<String, GibbsReactor.GibbsComponent> Record of condition numbers during iterations for diagnostics.private booleanprivate doubleprivate doubleprivate doubleprivate doubleprivate doubleprivate static final doubleSmall threshold for detecting zero element coefficients.Record of element balance errors during iterations for diagnostics.private double[]private double[]private double[]private String[]private GibbsReactor.EnergyModeprivate double(package private) doubleprivate doubleprivate doubleprivate List<GibbsReactor.GibbsComponent> Record of Gibbs energy values during iterations for diagnostics.private doubleprivate doubleprivate static final PatternPattern to identify ionic species (names ending with + or -).private double[][]private double[][]private double[]private static final org.apache.logging.log4j.LoggerLogger object for class.private static final doubleMaximum relative change per step in moles, following NASA CEA step limiting (Gordon & McBride, 1994, NASA RP-1311).private intprivate Stringprivate static final doubleMinimum value for Jacobian calculations to avoid division by zero.private static final doubleMinimum mole amount to prevent numerical issues with log(0).private intprivate double[]private doubleprivate static final doubleUniversal gas constant in kJ/(mol·K).private static final doubleReference temperature in Kelvin for thermodynamic calculations (298.15 K = 25°C).private doubleTikhonov regularization parameter tau.private doubleCondition number threshold above which regularization is applied.private static final longSerialization version UID.Record of step sizes used during iterations for diagnostics.private SystemInterfaceprivate doubleprivate ThreadLocal<SystemInterface> private intprivate booleanprivate booleanprivate booleanEnable Armijo backtracking line search for guaranteed Gibbs energy decrease.private booleanEnable Tikhonov regularization for ill-conditioned Jacobians.Fields inherited from class TwoPortEquipment
inStream, outStreamFields inherited from class ProcessEquipmentBaseClass
conditionAnalysisMessage, energyStream, hasController, isSolved, properties, reportFields inherited from class SimulationBaseClass
calcIdentifier, calculateSteadyState, timeFields inherited from class NamedBaseClass
name -
Constructor Summary
ConstructorsConstructorDescriptionGibbsReactor(String name) Constructor for GibbsReactor.GibbsReactor(String name, StreamInterface stream) Constructor for GibbsReactor. -
Method Summary
Modifier and TypeMethodDescriptionprivate doubleApply Tikhonov regularization to the Jacobian matrix if the condition number exceeds the threshold.private doublearmijoLineSearch(double[] deltaX, double alphaMax, double currentG) Perform Armijo backtracking line search to find a step size that guarantees sufficient decrease in the total Gibbs free energy.private doublecalculateAdaptiveAlpha(double[] deltaX, double requestedAlpha) Calculate adaptive step size using NASA CEA-style step limiting (Gordon & McBride, 1994).private voidcalculateElementMoleBalance(SystemInterface system, double[] elementBalance, boolean isInput) Calculate element mole balance for a system.private voidCalculate the Jacobian matrix for the Newton-Raphson method.private double[][]Calculate the inverse of the Jacobian matrix using JAMA Matrix library.doublecalculateMixtureEnthalpy(List<String> componentNames, List<Double> n, double T, Map<String, GibbsReactor.GibbsComponent> componentMap) Calculate the total enthalpy of a mixture: sum_i n_i * enthalpy_i(T).doublecalculateMixtureEnthalpy(List<String> componentNames, List<Double> n, Map<String, GibbsReactor.GibbsComponent> componentMap, double T) Calculate the total standard enthalpy of a mixture: sum_i n_i * enthalpy_i(T).doublecalculateMixtureEnthalpyStandard(List<String> componentNames, List<Double> n, Map<String, GibbsReactor.GibbsComponent> componentMap) Calculate the total standard enthalpy of a mixture: sum_i n_i * enthalpy_i(T).doublecalculateMixtureGibbsEnergy(List<String> componentNames, List<Double> n, Map<String, GibbsReactor.GibbsComponent> componentMap, double T) Calculate the total Gibbs energy of a mixture: sum_i n_i * gibbs_i(T).private voidCalculate objective function values for each component.private voidCalculate the objective minimization vector.private voidEnforce minimum concentration threshold to prevent numerical issues.private voidEnsures tempFugacitySystem is initialized (handles deserialization case).private doubleCompute the total Gibbs free energy including mixing terms for the current outlet composition.Find which elements are actually present in the system (have non-zero coefficients).Get the indices of active elements (elements that have non-zero coefficients in any component).intGet actual number of iterations performed.Get the condition number history from the last solve (one entry per iteration).doubleGet convergence tolerance for Newton-Raphson iterations.doubleGet damping factor for composition updates.Get detailed mole balance information for each component.Get the element balance error history from the last solve.double[]Get the element mole balance difference (in - out).double[]Get the element mole balance for input streams.double[]Get the element mole balance for output streams.String[]Get the element names.Gets the current energy mode of the reactor.doubleGet the cumulative enthalpy of reaction (sum of dH for all iterations).doubleGet final convergence error.double[]getFugacityCoefficient(Object phaseNameOrIndex) Get the fugacity coefficient array for all components in a specified phase using the current outlet composition.Get the Gibbs energy history from the last solve (one entry per iteration).Get the inlet mole list.Get the inlet mole list for debugging.Get the Jacobian column labels.double[][]Get the Jacobian inverse matrix.double[][]Get the Jacobian matrix.Get the Jacobian row labels.Get the Lagrange contributions (legacy method).Get the Lagrange multiplier contributions for each component.double[]Get the Lagrange multiplier values.booleanReturns true if the relative mass balance error is less than 0.001%.doubleGet the relative mass balance error as a percentage.intGet maximum number of Newton-Raphson iterations.Get the method used for Gibbs minimization.intGet minimum number of iterations before convergence is checked.doubleGet the last calculated mixture enthalpy (kJ).doubleGet the last calculated mixture Gibbs energy (kJ).Get the objective function values for each component.double[]Get the objective minimization vector.Get the labels for the objective minimization vector.private double[]Build objective vector matching the optimization variables (variableComponents) and active element balances.Get the outlet mole list.Get the outlet mole list for debugging.doublegetPower()Get the reactor power (default: W, negative enthalpyOfReactions*1000).doubleGet the reactor power in the specified unit ("W", "kW", or "MW").Get the step size history from the last solve (one entry per iteration).doubleGet the cumulative temperature change during the reaction (sum of dT for all iterations).booleanGet whether using all database species or only species in the system.booleanCheck if iterations converged.booleanisComponentInert(String componentName) Check if a component is inert.private booleanisIonicComponent(String moleculeName) booleanCheck if adaptive step sizing is enabled.booleanCheck if Armijo backtracking line search is enabled.booleanDeprecated.The consistent off-diagonal formulation is now always enabled.booleanCheck if Tikhonov regularization is enabled.private voidLoad the Gibbs reaction database from resources.private voidPerform Gibbs free energy minimization.booleanperformIterationUpdate(double[] deltaX, double alphaComposition) Perform a Newton-Raphson iteration update.double[]Perform one Newton-Raphson iteration step to calculate the delta vector (dX).voidPrint loaded database components for debugging.voidIn this method all thermodynamic and unit operations will be calculated in a steady state calculation.voidsetArmijoC1(double c1) Set the Armijo sufficient decrease parameter c1.voidsetArmijoMaxBacktracks(int maxBacktracks) Set maximum number of backtracking steps.voidsetArmijoRho(double rho) Set the Armijo backtracking contraction factor.voidsetComponentAsInert(int index) Mark a component as inert by index in inlet system.voidsetComponentAsInert(String componentName) Mark a component as inert by name.voidsetConvergenceTolerance(double convergenceTolerance) Set convergence tolerance for Newton-Raphson iterations.voidsetDampingComposition(double dampingComposition) Set damping factor for composition updates in Newton-Raphson iterations.voidsetEnergyMode(String mode) Set the energy mode of the reactor using a string (case-insensitive).voidSet the energy mode of the reactor (isothermal or adiabatic).voidsetLagrangeMultiplier(int index, double value) Set a Lagrange multiplier value.voidsetMaxIterations(int maxIterations) Set maximum number of Newton-Raphson iterations.voidSet the method used for Gibbs minimization.voidsetMinIterations(int minIterations) Set minimum number of iterations before convergence is checked.voidsetRegularizationTau(double tau) Set the Tikhonov regularization parameter tau.voidsetRegularizationThreshold(double threshold) Set the condition number threshold above which regularization is applied.voidsetUseAdaptiveStepSize(boolean useAdaptive) Enable or disable NASA CEA-style adaptive step sizing (Gordon & McBride, 1994, NASA RP-1311).voidsetUseAllDatabaseSpecies(boolean useAllDatabaseSpecies) Set whether to use all database species or only species in the system.voidsetUseArmijoLineSearch(boolean useArmijo) Enable or disable Armijo backtracking line search.voidsetUseConsistentOffDiagonal(boolean useConsistent) Deprecated.The consistent off-diagonal formulation is now always enabled.voidsetUseRegularization(boolean useReg) Enable or disable Tikhonov regularization for ill-conditioned Jacobians.booleanSolve Gibbs equilibrium using Newton-Raphson iterations with default damping factor.booleansolveGibbsEquilibrium(double alphaComposition) Solve Gibbs equilibrium using Newton-Raphson iterations with specified step size.private double[]solveNewtonSystem(double[] objectiveVector) Solve the Newton-Raphson linear system J_scaled * deltaX_scaled = -F using LU decomposition, then unscale using the column scaling factors from the NASA CEA log-mole transformation.private voidunscaleNewtonStep(double[] deltaX) Unscale a Newton step vector using the column scaling factors from the log-mole transformation.private booleanUpdate the thermodynamic system with the new outlet compositions.booleanVerify that the Jacobian inverse is correct by multiplying J * J^-1.Methods inherited from class TwoPortEquipment
getInletPressure, getInletStream, getInletStreams, getInletTemperature, getMassBalance, getOutletPressure, getOutletStream, getOutletStreams, getOutletTemperature, setInletPressure, setInletStream, setInletTemperature, setOutletPressure, setOutletPressure, setOutletStream, setOutletTemperature, setOutletTemperature, toJson, toJson, validateSetupMethods inherited from class ProcessEquipmentBaseClass
addCapacityConstraint, addController, copy, displayResult, equals, getAvailableMargin, getAvailableMarginPercent, getBottleneckConstraint, getCapacityConstraints, getConditionAnalysisMessage, getConstraintEvaluationReport, getController, getController, getControllers, getEffectiveCapacityFactor, getEnergyStream, getEntropyProduction, getExergyChange, getFailureMode, getMassBalance, getMaxUtilization, getMaxUtilizationPercent, getMechanicalDesign, getMinimumFlow, getPressure, getPressure, getProperty, getReferenceDesignation, getReport_json, getResultTable, getSpecification, getTemperature, getTemperature, getThermoSystem, getUtilizationSummary, hashCode, initElectricalDesign, initializeDefaultConstraints, initInstrumentDesign, initMechanicalDesign, isActive, isActive, isCapacityAnalysisEnabled, isCapacityExceeded, isFailed, isHardLimitExceeded, isNearCapacityLimit, isSetEnergyStream, reportResults, restoreFromFailure, run_step, runConditionAnalysis, setCapacityAnalysisEnabled, setController, setEnergyStream, setEnergyStream, setFailureMode, setFlowValveController, setMinimumFlow, setPressure, setReferenceDesignation, setRegulatorOutSignal, setSpecification, setTemperature, simulateDegradedOperation, simulateTrip, solvedMethods inherited from class SimulationBaseClass
getCalculateSteadyState, getCalculationIdentifier, getTime, increaseTime, isRunInSteps, setCalculateSteadyState, setCalculationIdentifier, setRunInSteps, setTimeMethods inherited from class NamedBaseClass
getName, getTagNumber, setName, setTagNumberMethods inherited from class Object
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface NamedInterface
getName, getTagName, getTagNumber, setName, setTagName, setTagNumberMethods inherited from interface ProcessEquipmentInterface
getCapacityDuty, getCapacityMax, getElectricalDesign, getEquipmentState, getExergyChange, getExergyDestruction, getExergyDestruction, getFluid, getInstrumentDesign, getOperatingEnvelopeViolation, getOutletFlowRate, getOutletPressure, getOutletTemperature, getReferenceDesignationString, getRestCapacity, getSimulationValidationErrors, isSimulationValid, isWithinOperatingEnvelope, needRecalculationMethods inherited from interface SimulationInterface
getCalculateSteadyState, getCalculationIdentifier, getTime, increaseTime, isRunInSteps, run, run_step, runTransient, runTransient, setCalculateSteadyState, setCalculationIdentifier, setRunInSteps, setTimeMethods inherited from interface TwoPortInterface
getInStream, getOutStream, setOutPressure, setOutPressure, setOutTemperature, setOutTemperature
-
Field Details
-
tempFugacitySystem
-
serialVersionUID
private static final long serialVersionUIDSerialization version UID.- See Also:
-
REFERENCE_TEMPERATURE
private static final double REFERENCE_TEMPERATUREReference temperature in Kelvin for thermodynamic calculations (298.15 K = 25°C).- See Also:
-
R_KJ
private static final double R_KJUniversal gas constant in kJ/(mol·K).- See Also:
-
MIN_MOLES
private static final double MIN_MOLESMinimum mole amount to prevent numerical issues with log(0).- See Also:
-
MIN_JACOBIAN_MOLES
private static final double MIN_JACOBIAN_MOLESMinimum value for Jacobian calculations to avoid division by zero.- See Also:
-
ELEMENT_ZERO_THRESHOLD
private static final double ELEMENT_ZERO_THRESHOLDSmall threshold for detecting zero element coefficients.- See Also:
-
logger
private static final org.apache.logging.log4j.Logger loggerLogger object for class. -
ION_NAME_PATTERN
Pattern to identify ionic species (names ending with + or -). -
energyMode
-
componentAliases
-
method
-
useAllDatabaseSpecies
private boolean useAllDatabaseSpecies -
gibbsDatabase
-
componentMap
-
lambda
private double[] lambda -
lagrangeContributions
-
elementNames
-
processedComponents
-
objectiveFunctionValues
-
inertComponents
-
initialMoles
-
finalMoles
-
elementMoleBalanceIn
private double[] elementMoleBalanceIn -
elementMoleBalanceOut
private double[] elementMoleBalanceOut -
elementMoleBalanceDiff
private double[] elementMoleBalanceDiff -
inlet_mole
-
outlet_mole
-
processedComponentIndexMap
-
objectiveMinimizationVector
private double[] objectiveMinimizationVector -
objectiveMinimizationVectorLabels
-
jacobianMatrix
private double[][] jacobianMatrix -
jacobianInverse
private double[][] jacobianInverse -
jacobianRowLabels
-
jacobianColLabels
-
variableComponents
-
maxIterations
private int maxIterations -
convergenceTolerance
private double convergenceTolerance -
dampingComposition
private double dampingComposition -
actualIterations
private int actualIterations -
converged
private boolean converged -
finalConvergenceError
private double finalConvergenceError -
minIterations
private int minIterations -
useAdaptiveStepSize
private boolean useAdaptiveStepSize -
useArmijoLineSearch
private boolean useArmijoLineSearchEnable Armijo backtracking line search for guaranteed Gibbs energy decrease.When enabled, the Newton step is scaled by alpha in (0, 1] such that the Armijo sufficient decrease condition is satisfied: G(n + alpha * dn) <= G(n) + c1 * alpha * grad^T * dn. This replaces fixed damping with an adaptive, globally convergent strategy.
Reference: Nocedal & Wright, Numerical Optimization (2006), Algorithm 3.1.
-
armijoC1
private double armijoC1Armijo sufficient decrease parameter c1 in (0, 1). Typical value 1e-4. -
armijoRho
private double armijoRhoBacktracking contraction factor rho in (0, 1). Step is multiplied by rho each backtrack. -
armijoMaxBacktracks
private int armijoMaxBacktracksMaximum number of backtracking steps in Armijo line search. -
useRegularization
private boolean useRegularizationEnable Tikhonov regularization for ill-conditioned Jacobians.When the condition number of the Jacobian exceeds
regularizationThreshold, a regularization term tau * I is added to the Hessian block: H_reg = H + tau * I. This prevents divergence near phase boundaries where the Hessian becomes singular.Reference: Tikhonov, A. N. (1963). Dokl. Akad. Nauk SSSR, 151, 501-504.
-
regularizationThreshold
private double regularizationThresholdCondition number threshold above which regularization is applied. -
regularizationTau
private double regularizationTauTikhonov regularization parameter tau. Added to Hessian diagonal. -
conditionNumberHistory
-
gibbsEnergyHistory
-
stepSizeHistory
-
elementBalanceErrorHistory
-
columnScaleFactors
private transient double[] columnScaleFactorsColumn scaling factors from the NASA CEA log-mole transformation applied to the Jacobian. Each entry j stores the factor by which Jacobian column j was multiplied. The Newton step deltaX_scaled must be divided by these factors to obtain the true deltaX in mole units. -
MAX_STEP_LIMIT
private static final double MAX_STEP_LIMITMaximum relative change per step in moles, following NASA CEA step limiting (Gordon & McBride, 1994, NASA RP-1311). Prevents overshooting in Newton-Raphson iterations:max |alpha * deltaX[i]| / n_i < MAX_STEP_LIMIT. -
system
-
inletEnthalpy
private double inletEnthalpy -
outletEnthalpy
private double outletEnthalpy -
dT
private double dT -
tempUpdateIter
private int tempUpdateIter -
enthalpyOld
double enthalpyOld -
enthalpyOfReactions
private double enthalpyOfReactions -
temperatureChange
private double temperatureChange -
deltaNorm
private double deltaNorm -
GOLD
private double GOLD -
G
private double G -
dG
private double dG -
formulaToComponent
-
-
Constructor Details
-
GibbsReactor
Constructor for GibbsReactor.- Parameters:
name- Name of GibbsReactor
-
GibbsReactor
Constructor for GibbsReactor.- Parameters:
name- Name of GibbsReactorstream- Stream to set as inlet Stream. A clone of stream is set as outlet stream.
-
-
Method Details
-
getMassBalanceError
public double getMassBalanceError()Get the relative mass balance error as a percentage. Computed as100 * |massIn - massOut| / massIn.- Returns:
- relative mass balance error in percent (e.g., 0.001 means 0.001%)
-
getMassBalanceConverged
public boolean getMassBalanceConverged()Returns true if the relative mass balance error is less than 0.001%.- Returns:
- true if mass balance is converged, false otherwise
-
ensureTempFugacitySystemInitialized
private void ensureTempFugacitySystemInitialized()Ensures tempFugacitySystem is initialized (handles deserialization case). -
getEnthalpyOfReactions
public double getEnthalpyOfReactions()Get the cumulative enthalpy of reaction (sum of dH for all iterations).- Returns:
- enthalpyOfReactions in kJ
-
getTemperatureChange
public double getTemperatureChange()Get the cumulative temperature change during the reaction (sum of dT for all iterations).- Returns:
- temperatureChange in K
-
getPower
public double getPower()Get the reactor power (default: W, negative enthalpyOfReactions*1000).- Returns:
- Power in Watts (W)
-
getPower
Get the reactor power in the specified unit ("W", "kW", or "MW").- Parameters:
unit- Power unit: "W", "kW", or "MW" (case-insensitive, default is W)- Returns:
- Power in the specified unit
-
calculateMixtureEnthalpy
public double calculateMixtureEnthalpy(List<String> componentNames, List<Double> n, double T, Map<String, GibbsReactor.GibbsComponent> componentMap) Calculate the total enthalpy of a mixture: sum_i n_i * enthalpy_i(T).- Parameters:
componentNames- List of component names (order matches n_i)n- List of moles for each componentT- Temperature in KcomponentMap- Map from component name (lowercase) to GibbsComponent- Returns:
- Total enthalpy (kJ)
-
calculateMixtureGibbsEnergy
public double calculateMixtureGibbsEnergy(List<String> componentNames, List<Double> n, Map<String, GibbsReactor.GibbsComponent> componentMap, double T) Calculate the total Gibbs energy of a mixture: sum_i n_i * gibbs_i(T).- Parameters:
componentNames- List of component names (order matches n_i)n- List of moles for each componentcomponentMap- Map from component name (lowercase) to GibbsComponentT- Temperature in K- Returns:
- Total Gibbs energy (kJ)
-
getMixtureEnthalpy
public double getMixtureEnthalpy()Get the last calculated mixture enthalpy (kJ).- Returns:
- a double
-
getMixtureGibbsEnergy
public double getMixtureGibbsEnergy()Get the last calculated mixture Gibbs energy (kJ).- Returns:
- a double
-
calculateMixtureEnthalpyStandard
public double calculateMixtureEnthalpyStandard(List<String> componentNames, List<Double> n, Map<String, GibbsReactor.GibbsComponent> componentMap) Calculate the total standard enthalpy of a mixture: sum_i n_i * enthalpy_i(T).- Parameters:
componentNames- List of component names (order matches n_i)n- List of moles for each componentcomponentMap- Map from component name (lowercase) to GibbsComponent- Returns:
- Total enthalpy (kJ)
-
calculateMixtureEnthalpy
public double calculateMixtureEnthalpy(List<String> componentNames, List<Double> n, Map<String, GibbsReactor.GibbsComponent> componentMap, double T) Calculate the total standard enthalpy of a mixture: sum_i n_i * enthalpy_i(T).- Parameters:
componentNames- List of component names (order matches n_i)n- List of moles for each componentcomponentMap- Map from component name (lowercase) to GibbsComponentT- a double- Returns:
- Total enthalpy (kJ)
-
setEnergyMode
Set the energy mode of the reactor (isothermal or adiabatic).- Parameters:
mode- EnergyMode.ISOTHERMAL or EnergyMode.ADIABATIC
-
setEnergyMode
Set the energy mode of the reactor using a string (case-insensitive). Accepts "adiabatic" or "isothermal" (case-insensitive).- Parameters:
mode- String representing the energy mode- Throws:
IllegalArgumentException- if the mode is not recognized
-
getEnergyMode
Gets the current energy mode of the reactor.- Returns:
- the current EnergyMode (ISOTHERMAL or ADIABATIC)
-
setComponentAsInert
Mark a component as inert by name.- Parameters:
componentName- component name as in the thermo system
-
setComponentAsInert
public void setComponentAsInert(int index) Mark a component as inert by index in inlet system.- Parameters:
index- component index in inlet system
-
isComponentInert
Check if a component is inert.- Parameters:
componentName- the name of the component to check- Returns:
- true if the component is inert, false otherwise
-
isIonicComponent
-
loadGibbsDatabase
private void loadGibbsDatabase()Load the Gibbs reaction database from resources. -
setUseAllDatabaseSpecies
public void setUseAllDatabaseSpecies(boolean useAllDatabaseSpecies) Set whether to use all database species or only species in the system.- Parameters:
useAllDatabaseSpecies- true to use all database species, false to use only system species
-
getUseAllDatabaseSpecies
public boolean getUseAllDatabaseSpecies()Get whether using all database species or only species in the system.- Returns:
- true if using all database species, false if using only system species
-
getMethod
-
setMethod
Set the method used for Gibbs minimization.- Parameters:
method- The method name
-
getLagrangeContributions
-
run
In this method all thermodynamic and unit operations will be calculated in a steady state calculation.
- Parameters:
id- UUID
-
performGibbsMinimization
Perform Gibbs free energy minimization.- Parameters:
system- The thermodynamic system
-
calculateElementMoleBalance
private void calculateElementMoleBalance(SystemInterface system, double[] elementBalance, boolean isInput) Calculate element mole balance for a system.- Parameters:
system- The thermodynamic systemelementBalance- Array to store the element balanceisInput- true if this is input balance, false if output balance
-
calculateObjectiveFunctionValues
Calculate objective function values for each component.- Parameters:
system- The thermodynamic system
-
setLagrangeMultiplier
public void setLagrangeMultiplier(int index, double value) Set a Lagrange multiplier value.- Parameters:
index- The element index (0=O, 1=N, 2=C, 3=H, 4=S, 5=Ar)value- The Lagrange multiplier value
-
getLagrangianMultipliers
public double[] getLagrangianMultipliers()Get the Lagrange multiplier values.- Returns:
- Array of Lagrange multiplier values [O, N, C, H, S, Ar]
-
getElementNames
-
getLagrangeMultiplierContributions
-
getObjectiveFunctionValues
-
getElementMoleBalanceIn
public double[] getElementMoleBalanceIn()Get the element mole balance for input streams.- Returns:
- Array of total moles for each element in input [O, N, C, H, S, Ar]
-
getElementMoleBalanceOut
public double[] getElementMoleBalanceOut()Get the element mole balance for output streams.- Returns:
- Array of total moles for each element in output [O, N, C, H, S, Ar]
-
getElementMoleBalanceDiff
public double[] getElementMoleBalanceDiff()Get the element mole balance difference (in - out).- Returns:
- Array of mole differences for each element [O, N, C, H, S, Ar]
-
getDetailedMoleBalance
-
calculateObjectiveMinimizationVector
private void calculateObjectiveMinimizationVector()Calculate the objective minimization vector. This vector contains the F values for each component and the mass balance constraints. The system is in equilibrium when this vector is zero. Only includes elements that are actually present in the system. -
getObjectiveMinimizationVector
public double[] getObjectiveMinimizationVector()Get the objective minimization vector.- Returns:
- The objective minimization vector
-
getObjectiveVectorForVariables
private double[] getObjectiveVectorForVariables()Build objective vector matching the optimization variables (variableComponents) and active element balances. This excludes inert components from the variable part but keeps balances.- Returns:
- the objective vector for optimization variables
-
getObjectiveMinimizationVectorLabels
-
calculateJacobian
private void calculateJacobian()Calculate the Jacobian matrix for the Newton-Raphson method. The Jacobian represents the derivatives of the objective function with respect to the variables. Only includes elements that are actually present in the system to avoid singular matrices. -
getJacobianMatrix
public double[][] getJacobianMatrix()Get the Jacobian matrix.- Returns:
- The Jacobian matrix
-
getJacobianRowLabels
-
getJacobianColLabels
-
getJacobianInverse
public double[][] getJacobianInverse()Get the Jacobian inverse matrix.- Returns:
- The Jacobian inverse matrix, or null if it couldn't be calculated
-
calculateJacobianInverse
private double[][] calculateJacobianInverse()Calculate the inverse of the Jacobian matrix using JAMA Matrix library.- Returns:
- Inverse matrix, or null if matrix is singular
-
solveNewtonSystem
private double[] solveNewtonSystem(double[] objectiveVector) Solve the Newton-Raphson linear system J_scaled * deltaX_scaled = -F using LU decomposition, then unscale using the column scaling factors from the NASA CEA log-mole transformation.The Jacobian was column-scaled: J_scaled[:,j] = J[:,j] * n_j. Solving gives deltaX_scaled, and the true step is deltaX[j] = deltaX_scaled[j] / n_j. Falls back to pseudo-inverse if LU solve fails (e.g., singular matrix).
- Parameters:
objectiveVector- the right-hand side vector F- Returns:
- the Newton step deltaX = -J^{-1} F (unscaled), or null if solve fails
-
unscaleNewtonStep
private void unscaleNewtonStep(double[] deltaX) Unscale a Newton step vector using the column scaling factors from the log-mole transformation. The scaled system solves J_s * Δξ = -F where J_s = J * D (D = diag(n_j)). Recovering the original step: Δn = D * Δξ, so Δn_j = n_j * Δξ_j. Lagrange multiplier entries have scale factor 1.0 (no change).- Parameters:
deltaX- the Newton step vector to unscale in place
-
enforceMinimumConcentrations
Enforce minimum concentration threshold to prevent numerical issues. If any component has moles less than MIN_MOLES, it will be set to MIN_MOLES.- Parameters:
system- The thermodynamic system to check and modify
-
getInletMole
-
getOutletMole
-
getInletMoles
-
getOutletMoles
-
printDatabaseComponents
public void printDatabaseComponents()Print loaded database components for debugging. -
findActiveElements
-
getActiveElementIndices
-
verifyJacobianInverse
public boolean verifyJacobianInverse()Verify that the Jacobian inverse is correct by multiplying J * J^-1. Should return the identity matrix if the inverse is correct.- Returns:
- True if the inverse is correct (within tolerance)
-
performNewtonRaphsonIteration
public double[] performNewtonRaphsonIteration()Perform one Newton-Raphson iteration step to calculate the delta vector (dX). Uses LU decomposition to solve J * dX = -F directly (Nocedal & Wright, 2000), falling back to J^{-1} * F if LU solve is not available. The LU approach is ~3x faster and more numerically stable than explicit matrix inversion.- Returns:
- The delta vector (dX) for updating variables, or null if calculation fails
-
performIterationUpdate
public boolean performIterationUpdate(double[] deltaX, double alphaComposition) Perform a Newton-Raphson iteration update. Updates outlet compositions with damping factor and Lagrange multipliers directly.- Parameters:
deltaX- The delta vector from Newton-Raphson iterationalphaComposition- Damping factor for composition updates (e.g., 0.0001)- Returns:
- True if update was successful, false otherwise
-
updateSystemWithNewCompositions
private boolean updateSystemWithNewCompositions()Update the thermodynamic system with the new outlet compositions.- Returns:
- True if update was successful, false otherwise
-
getFugacityCoefficient
Get the fugacity coefficient array for all components in a specified phase using the current outlet composition. Uses direct phase composition assignment for efficiency.- Parameters:
phaseNameOrIndex- Name or index of the phase (e.g., "gas", "oil", "aqueous", or 0/1/2)- Returns:
- Fugacity coefficient (phi) array for all components in the specified phase, or Double.NaN if not found
-
setMaxIterations
public void setMaxIterations(int maxIterations) Set maximum number of Newton-Raphson iterations.- Parameters:
maxIterations- Maximum number of iterations
-
getMaxIterations
public int getMaxIterations()Get maximum number of Newton-Raphson iterations.- Returns:
- Maximum number of iterations
-
setConvergenceTolerance
public void setConvergenceTolerance(double convergenceTolerance) Set convergence tolerance for Newton-Raphson iterations.- Parameters:
convergenceTolerance- Convergence tolerance
-
getConvergenceTolerance
public double getConvergenceTolerance()Get convergence tolerance for Newton-Raphson iterations.- Returns:
- Convergence tolerance
-
setDampingComposition
public void setDampingComposition(double dampingComposition) Set damping factor for composition updates in Newton-Raphson iterations.- Parameters:
dampingComposition- Damping factor (typically 0.0001 to 0.01)
-
getDampingComposition
public double getDampingComposition()Get damping factor for composition updates.- Returns:
- Damping factor for composition updates
-
setUseConsistentOffDiagonal
Deprecated.The consistent off-diagonal formulation is now always enabled. This setter is a no-op.Enable the mathematically consistent off-diagonal Jacobian formulation. This is now always enabled (the RT-corrected formulation is the only implementation). This method is retained for backward compatibility but has no effect.- Parameters:
useConsistent- ignored — consistent formulation is always active
-
isUseConsistentOffDiagonal
Deprecated.The consistent off-diagonal formulation is now always enabled.Check if the consistent off-diagonal Jacobian formulation is enabled. Always returns true.- Returns:
- always true
-
getActualIterations
public int getActualIterations()Get actual number of iterations performed.- Returns:
- Actual iterations performed
-
hasConverged
public boolean hasConverged()Check if iterations converged.- Returns:
- true if converged, false otherwise
-
getFinalConvergenceError
public double getFinalConvergenceError()Get final convergence error.- Returns:
- Final convergence error
-
setMinIterations
public void setMinIterations(int minIterations) Set minimum number of iterations before convergence is checked. Default is 100. The solver will not declare convergence before completing this many iterations, even if the convergence criterion is satisfied. Setting this too high wastes iterations; too low may cause premature termination.- Parameters:
minIterations- Minimum iterations before convergence check (must be at least 1)
-
getMinIterations
public int getMinIterations()Get minimum number of iterations before convergence is checked.- Returns:
- Minimum iterations before convergence check
-
setUseAdaptiveStepSize
public void setUseAdaptiveStepSize(boolean useAdaptive) Enable or disable NASA CEA-style adaptive step sizing (Gordon & McBride, 1994, NASA RP-1311). When enabled, the step size is automatically computed each iteration to limit the maximum relative change in component moles, allowing larger steps when safe and smaller steps near steep gradients. When disabled, the fixeddampingCompositionfactor is used for all iterations.- Parameters:
useAdaptive- true to enable adaptive step sizing
-
isUseAdaptiveStepSize
public boolean isUseAdaptiveStepSize()Check if adaptive step sizing is enabled.- Returns:
- true if adaptive step sizing is active
-
setUseArmijoLineSearch
public void setUseArmijoLineSearch(boolean useArmijo) Enable or disable Armijo backtracking line search.When enabled, the Newton step is adaptively scaled to guarantee sufficient decrease in the total Gibbs free energy at each iteration. This provides a globally convergent algorithm replacing fixed damping.
- Parameters:
useArmijo- true to enable Armijo line search
-
isUseArmijoLineSearch
public boolean isUseArmijoLineSearch()Check if Armijo backtracking line search is enabled.- Returns:
- true if Armijo line search is active
-
setArmijoC1
public void setArmijoC1(double c1) Set the Armijo sufficient decrease parameter c1.- Parameters:
c1- value in (0, 1), typically 1e-4
-
setArmijoRho
public void setArmijoRho(double rho) Set the Armijo backtracking contraction factor.- Parameters:
rho- value in (0, 1), typically 0.5
-
setArmijoMaxBacktracks
public void setArmijoMaxBacktracks(int maxBacktracks) Set maximum number of backtracking steps.- Parameters:
maxBacktracks- maximum number of backtracks
-
setUseRegularization
public void setUseRegularization(boolean useReg) Enable or disable Tikhonov regularization for ill-conditioned Jacobians.- Parameters:
useReg- true to enable regularization
-
isUseRegularization
public boolean isUseRegularization()Check if Tikhonov regularization is enabled.- Returns:
- true if regularization is active
-
setRegularizationThreshold
public void setRegularizationThreshold(double threshold) Set the condition number threshold above which regularization is applied.- Parameters:
threshold- condition number threshold
-
setRegularizationTau
public void setRegularizationTau(double tau) Set the Tikhonov regularization parameter tau.- Parameters:
tau- regularization parameter added to Hessian diagonal
-
getConditionNumberHistory
-
getGibbsEnergyHistory
-
getStepSizeHistory
-
getElementBalanceErrorHistory
-
evaluateTotalGibbsEnergy
private double evaluateTotalGibbsEnergy()Compute the total Gibbs free energy including mixing terms for the current outlet composition.G_total = sum_i n_i * [Gf0_i(T) + RT*ln(phi_i) + RT*ln(y_i) + RT*ln(P/Pref)]
This method evaluates the actual objective function for line search, distinct from
calculateMixtureGibbsEnergywhich only uses standard Gibbs energies.- Returns:
- total Gibbs free energy (kJ) including mixing and non-ideality contributions
-
armijoLineSearch
private double armijoLineSearch(double[] deltaX, double alphaMax, double currentG) Perform Armijo backtracking line search to find a step size that guarantees sufficient decrease in the total Gibbs free energy.Starting from alpha = alpha_max, the step is contracted by factor rho until the Armijo condition is satisfied: G(n + alpha*dn) <= G(n) + c1*alpha*grad^T*dn.
Reference: Nocedal & Wright, Numerical Optimization (2006), Algorithm 3.1.
- Parameters:
deltaX- the full Newton step vector (composition components only, not Lagrange portion)alphaMax- the maximum step size (from adaptive step or fixed damping)currentG- current total Gibbs energy- Returns:
- the accepted step size satisfying the Armijo condition
-
applyRegularization
private double applyRegularization()Apply Tikhonov regularization to the Jacobian matrix if the condition number exceeds the threshold. Adds tau*I to the Hessian (composition-composition) block of the Jacobian.This converts the saddle-point system into a positive-definite system when the Hessian is nearly singular, ensuring the Newton direction remains well-defined.
- Returns:
- the condition number of the (possibly regularized) Jacobian
-
calculateAdaptiveAlpha
private double calculateAdaptiveAlpha(double[] deltaX, double requestedAlpha) Calculate adaptive step size using NASA CEA-style step limiting (Gordon & McBride, 1994). Limits the maximum relative mole change so that no major component changes by more than a factor ofe^MAX_STEP_LIMIT(~5x) in a single step. Components with moles below a significance threshold are excluded from the limiting (they are growing from near-zero and need large relative steps).- Parameters:
deltaX- The raw Newton step vectorrequestedAlpha- The starting step size (typically 1.0)- Returns:
- The step size bounded to prevent overshooting (clamped to [1e-4, requestedAlpha])
-
solveGibbsEquilibrium
public boolean solveGibbsEquilibrium(double alphaComposition) Solve Gibbs equilibrium using Newton-Raphson iterations with specified step size.- Parameters:
alphaComposition- Step size for composition updates- Returns:
- true if converged, false otherwise
-
solveGibbsEquilibrium
public boolean solveGibbsEquilibrium()Solve Gibbs equilibrium using Newton-Raphson iterations with default damping factor.- Returns:
- true if converged, false otherwise
-