Coder package¶
The Coder module provides code generation for symbolically defined thermodynamics.
This module implements a Python interface that enables the symbolic specification of the thermodynamic properties of a phase with code generation of the resulting model. Code may be produced for either fast computation of results or model parameter calibration.
- Code generation options:
Fast computation optimization: fixed parameters
Model calibration optimization: variable parameters
Classes are defined to implement standard state properties of pure components, thermodynamic properties of simple solutions, and thermodynamic properties of complex solid solutions that exhibit both convergent and non-convergent cation order-disorder.
- Thermodynamic properties are implemented for:
Pure phases at standard state
Simple solutions (asymmetric regular)
Complex solutions (convergent & non-convergent cation order-disorder)
By default, models are formulated in terms of the Gibbs free energy, with independent variables temperature, pressure, and (for solutions) mole numbers of components. Alternatively, models may be implemented in terms of the Helmholtz free energy, with independent variables temperature, volume, and mole numbers of components.
- Model formulation options:
Gibbs Free Energy G(T, P, mols) [default]
Helmholtz Free Energy A(T, V, mols)
-
class
coder.
StdStateModel
(model_type='TP')[source]¶ Class creates representation of standard state properties of pure phase.
- Parameters
- model_typestr
Model type of ‘TP’ implies that expressions are of the form of the Gibbs free energy.
Model type of ‘TV’ implies that expressions are of the form of the Helmholtz energy. This option is infrequently used.
Notes
Class for creating a representation of the standard state properties of a stoichiometric phase. The principal use of the class is to construct a model symbolically and to generate code that implements the model for model parameter calibration and thermodynamic property calculation.
The class supports standard state models that involve integrals of the Debye function, implicit functions for equations of state, and models that require Born functions for estimation of the dielectric properties of water.
- Attributes
a_list
Array of tuples used internally by the class
expression_parts
Array of Expression class instances
g_list
Array of tuples used internally by the class
implicit_functions
Array of Implicit_Function class instances
module
Name of module
params
Array of Parameter class instances
printer
Instance of a SymPy code printer class used in code generation
variables
Array of Parameter class instances
Methods
add_expression_to_model
(self, expression, params)Adds an expression and associated parameters to the model.
create_calc_h_file
(self[, language, module_type])Creates an include file implementing model calculations.
create_calib_h_file
(self[, language])Creates a C-code include file implementing model calibration functions.
create_code_module
(self[, phase, formula, …])Creates and writes an include and code file for a model instance.
get_berman_std_state_database
(self[, …])Retrieves priors from the thermodynamic database of Berman (1988).
get_include_born_code
(self)Retrieves a boolean flag specifying whether code implementing the Born functions will be linked to the generated module.
get_include_debye_code
(self)Retrieves a boolean flag specifying whether a block of code implementing the Debye integral function will be generated.
get_model_param_names
(self)Retrieves a list of strings of model parameter names.
get_model_param_symbols
(self)Retrieves a list of SymPy symbols for model parameters.
get_model_param_units
(self)Retrieves a list of strings of model parameter units.
get_module_name
(self)Retrieves module name.
get_symbol_for_p
(self)Retrieves SymPy symbol for pressure.
get_symbol_for_pr
(self)Retrieves SymPy symbol for reference pressure.
get_symbol_for_t
(self)Retrieves SymPy symbol for temperature.
get_symbol_for_tr
(self)Retrieves SymPy symbol for reference temperature.
get_symbol_for_v
(self)Retrieves SymPy symbol for volume.
get_symbol_for_vr
(self)Retrieves SymPy symbol for reference volume.
parse_formula
(self[, formula_string])Parses a chemical formula, and returns a molecular weight and an array of elemental concentrations.
set_include_born_code
(self[, include])Sets a boolean flag controlling the inclusion of code implementing the Born functions.
set_include_debye_code
(self[, include])Sets a boolean flag controlling the inclusion of a block of code implementing the Debye integral function.
set_module_name
(self, module_s)Retrieves module name.
set_reference_origin
(self[, Tr, Pr, Vr])Sets the reference conditions for the model.
-
property
a_list
¶ Array of tuples used internally by the class
Each tuple contains the following entries:
[0] str - Function name for derivatives of the Helmholtz energy
[1] int - Order of temperature derivative
[2] int - Order of volume derivative
- Returns
- Array of tuples
-
add_expression_to_model
(self, expression, params, exp_type='unrestricted', lower_limits=(None, None), upper_limits=(None, None), implicit_functions=None, extend_restricted_functions=True)[source]¶ Adds an expression and associated parameters to the model.
Adds an expression for the Gibbs or Helmholtz energy to the standard state model along with a description of expression parameters.
- Parameters
- expressionsympy.core.symbol.Symbol
A SymPy expression for the Gibbs free energy (if model_type is ‘TP’) or the Helmholtz energy (if model_type is ‘TV’).
The expression may contain an implicit variable, f, whose value is a function of T,P or T,V. The value of f is determined numerically by solving the implicit_function expression (defined below) at runtime using Newton’s method.
- paramsAn array of tuples
Structure (string, string, SymPy expression):
[0] str - Name of the parameter
[1] str - Units of parameter
[2] sympy.core.symbol.Symbol - SymPy symbol for the parameter
- exp_typestr, default=’unrestricted’
‘unrestricted’ - Expression is applicable over the whole of T,P or T,V space.
‘restricted’ - Expression applies only between the specified lower_limits and upper_limits.
- lower_limitstuple
A tuple of SymPy expressions defining the inclusive lower (T,P) or (T,V) limit of applicability of the expression. Used only if exp_type is set to ‘restricted’.
- upper_limitstuple
A tuple of SymPy expressions defining the inclusive upper (T,P) or (T,V) limit of applicability of the expression. Used only if exp_type is set to ‘restricted’.
- implicit_functionsarray of tuples
A tuple element contains three parts:
[0] sympy.core.symbol.Symbol - SymPy expression for an implicit function in two independent (T,P or T,V) variables and one dependent variable (f). The function is equal to zero.
[1] sympy.core.symbol.Symbol - SymPy symbol for the dependent variable f.
[2] sympy.core.symbol.Symbol - SymPy expression that initializes f in the iterative routine. This expression must be defined in terms of known parameters and Tr, Pr, T, P.
- extend_restricted_functionsbool, default=True
A boolean that controls whether a “restricted” exp_type is extended beyond its upper_limits. By default, temperature and pressure/volume derivatives of expression are evaluated at the upper_limits, and these constants are added as linear functions of T and P/V applicable and restricted to conditions above the upper_limits. You can disable the default behavior by setting extend_restricted_functions to False. Note that, in general, the default behavior is desired as it allows entropic and volumetric contributions developed over the restricted domain of expression to contribute to the energy potential beyond the domain. Such behavior is consistent with SymPy Piecewise functions. Special circumstances, however, may require the default behavior to be disabled.
-
create_calc_h_file
(self, language='C', module_type='fast')[source]¶ Creates an include file implementing model calculations.
Note that this include file contains code for functions that implement the model for the generic case. It is meant to be included into a file that implements a specific parameterized instance of the model. See create_fast_code_module().
The user does not normally call this function directly.
- Parameters
- languagestr
Language syntax for generated code. (“C” is the C99 programming language.)
- module_typestr
Generate code that executes “fast” but does not expose hooks for model parameter calibration. Alternately, generate code suitable for “calib”ration of parameters in the model, which executes more slowly and exposes additional functions that allow setting of parameters and generation of derivatives of thermodynamic functions with respect to model parameters.
-
create_calib_h_file
(self, language='C')[source]¶ Creates a C-code include file implementing model calibration functions.
- Parameters
- languagestring
Language syntax for generated code. (“C” is the C99 programming language.)
Notes
The calib_h include file contains code for functions that implement the model for the generic case. It is meant to be included into a file that implements a specific parameterized instance of the model. See create_calib_code_module().
The user does not normally call this function directly.
-
create_code_module
(self, phase='Quartz', formula='Si(1)O(2)', params={}, identifier=None, prefix='cy', module_type='fast', silent=False, language='C')[source]¶ Creates and writes an include and code file for a model instance.
- Parameters
- phasestr
Model instance title (e.g., phase name). Used to name the generated function. Cannot contain blank spaces or special characters; underscore (“_”) is permitted. Convention capitalizes the first letter and the letter following an underscore (“_”) character.
- formulastr
Chemical formula of the model instance, in standard notation. Standard notation is of the form: Element Symbol followed by parentheses enclosing a number, which may be decimalized. E.g., SiO2 is written as Si(1)O(2); CaMg1/2Ti1/2AlO6 is written as Ca(1)Mg(0.5)Ti(0.5)Al(1)Si(1)O(6); CaMg(CO3)2 is written as Ca(1)Mg(1)C(2)O(6).
- paramsdict
Parameter values for the model instance. The keys of this dictionary are validated against parameter symbols stored for the model.
- identifierstr
A unique identifier for the model instance. Defaults to local date and time when module is created (rounded to the second).
- prefixstr
Prefix to function names for Python bindings, e.g., {prefix}_{phase}_{module}_g(T,P).
- module_typestr
Generate code that executes “fast” but does not expose hooks for model parameter calibration. Alternately, generate code suitable for “calib”ration of parameters in the model, which executes more slowly and exposes additional functions that allow setting of parameters and generation of derivatives of thermodynamic functions with respect to model parameters.
- silentbool
Print (True) or do not print (False) status messages.
- languagestring
Language syntax for generated code. (“C” is the C99 programming language; “C++” is the C++ programming language.)
- Returns
- resultBoolean
True if module is succesfully generated, False if some error occurred
-
property
expression_parts
¶ Array of Expression class instances
A model is built by layering expression instances. Each instance may be applicable over all or a portion of the domain space of variables.
- Returns
- Array of Expression class instances, [str,…]
-
property
g_list
¶ Array of tuples used internally by the class
Each tuple contains the following entries:
[0] str - Function name for derivatives of the Gibbs free energy
[1] int - Order of temperature derivative
[2] int - Order of pressure derivative
Generally for internal use by the class
- Returns
- Array of tuples
-
get_berman_std_state_database
(self, identifier=None, extend_defs=False)[source]¶ Retrieves priors from the thermodynamic database of Berman (1988).
- Parameters
- identifierint
Value may be None or an integer in the range (0, length of Berman database).
- extend_defsbool
False: The standard set of Berman parameters are retrieved.
True: Additional parameters are computed, including ‘K’ and ‘K_P’, the bulk modulus and its pressure derivative.
- Returns
- resultvariable
If identifier is None, then the function returns an array of tuples, one for each phase in the database:
[0] database index
[1] name of the phase
[2] formula of the phase, in standard notation
If identifier is an integer, then the function returns a dictionary with keys, corresponding parameter names, and values corresponding to parameter values.
-
get_include_born_code
(self)[source]¶ Retrieves a boolean flag specifying whether code implementing the Born functions will be linked to the generated module.
- Returns
- booleanbool
True or False (default)
-
get_include_debye_code
(self)[source]¶ Retrieves a boolean flag specifying whether a block of code implementing the Debye integral function will be generated.
- Returns
- booleanbool
True or False (default)
-
get_model_param_names
(self)[source]¶ Retrieves a list of strings of model parameter names.
- Returns
- resultlist of str
Names of model parameters
-
get_model_param_symbols
(self)[source]¶ Retrieves a list of SymPy symbols for model parameters.
- Returns
- resultlist of sym.Symbol
SymPy symbols for model parameters
-
get_model_param_units
(self)[source]¶ Retrieves a list of strings of model parameter units.
- Returns
- resultlist of str
Units of model parameters
-
get_module_name
(self)[source]¶ Retrieves module name.
The module name is used in creating file names for coded functions. Maintained for backward compatibility.
- Returns
- stringstr
The name of the module.
-
get_symbol_for_p
(self)[source]¶ Retrieves SymPy symbol for pressure.
- Returns
- Psympy symbol
SymPy symbol for pressure
-
get_symbol_for_pr
(self)[source]¶ Retrieves SymPy symbol for reference pressure.
- Returns
- Prsympy symbol
SymPy symbol for reference pressure
-
get_symbol_for_t
(self)[source]¶ Retrieves SymPy symbol for temperature.
- Returns
- Tsympy.core.symbol.Symbol
SymPy symbol for temperature
-
get_symbol_for_tr
(self)[source]¶ Retrieves SymPy symbol for reference temperature.
- Returns
- Trsympy symbol
SymPy symbol for reference temperature
-
get_symbol_for_v
(self)[source]¶ Retrieves SymPy symbol for volume.
- Returns
- Vsympy symbol
SymPy symbol for volume
-
get_symbol_for_vr
(self)[source]¶ Retrieves SymPy symbol for reference volume.
- Returns
- Vrsympy symbol
SymPy symbol for reference volume
-
property
implicit_functions
¶ Array of Implicit_Function class instances
A model may require that one or more implicit function expressions be satisfied prior to evaluation of the model expressions.
- Returns
- Array of Implicit_Function class instances, [str,…]
-
property
module
¶ Name of module
- Returns
- Name of module (str)
-
property
params
¶ Array of Parameter class instances
Parameters are calibrated quantities that define the model, like T_r and P_r.
- Returns
- Array of Parameter class instances, [Parameter,…]
-
parse_formula
(self, formula_string='Si(1)O(2)')[source]¶ Parses a chemical formula, and returns a molecular weight and an array of elemental concentrations.
- Parameters
- formula_stringstr
Formula of compound specified in the standard form SiO2 -> Si(1)O(2)
- Returns
- mw, elmvectortuple
[0] mw is a float containing the molecular weight in grams.
[1] elmvector is a numpy array of length 120 containing the mole numbers of each element in the compound.
-
property
printer
¶ Instance of a SymPy code printer class used in code generation
- Returns
- C99CodePrinter
-
set_include_born_code
(self, include=False)[source]¶ Sets a boolean flag controlling the inclusion of code implementing the Born functions.
- Parameters
- includebool
True or False
-
set_include_debye_code
(self, include=False)[source]¶ Sets a boolean flag controlling the inclusion of a block of code implementing the Debye integral function.
- Parameters
- includebool
True or False
-
set_module_name
(self, module_s)[source]¶ Retrieves module name.
The module name is used in creating file names for coded functions. Maintained for backward compatibility.
- Parameters
- module_sstr
The name of the module
-
set_reference_origin
(self, Tr=298.15, Pr=1.0, Vr=2.5)[source]¶ Sets the reference conditions for the model.
Tr must be specified along with one of Pr or Vr.
- Parameters
- Trfloat
Reference temperature for the model (in Kelvins)
- Prfloat
Reference pressure for the model (in bars)
- Vrfloat
Reference volume of the model (in J/bar)
-
property
variables
¶ Array of Parameter class instances
This property returns or sets an array of variables, either T, P, T_r and P_r (if model_type is ’TP’) or T, V, T_r and V_r (if model type is equal to ’TV’). Array elements are encapsulated as instances of the Parameter class object. This is simply done as a convenience wrapper. Note that SymPy symbols that are suitable for developing model expressions using these variables are probably more easily accessed using the methods:
get_symbol_for_t()
get_symbol_for_p()
and so on.
- Returns
- Array of Parameter class instances, [Parameter,…]
-
class
coder.
SimpleSolnModel
(nc=None, model_type='TP')[source]¶ Class creates a model of the thermodynamic properties of a simple solution.
- Parameters
- ncint
Number of thermodynamic components in the solution
- model_typestr
Model type of ‘TP’ implies that expressions are of the form of the Gibbs free energy.
Model type of ‘TV’ implies that expressions are of the form of the Helmholtz energy. This option is infrequently used.
Notes
This class is for creating a representation of the thermodynamic properties of a simple solution phase. The principal use of the class is to construct a model symbolically and to generate code that implements the model for model parameter calibration and thermodynamic property calculation.
A simple solution is one that does not contain implicit variables that need be determined via solution of conditions of homogeneous equilibrium. Examples of simple solutions include regular solutions, asymmetric binary and ternary Margules expansions, and high order Taylor series expansions of the Gibbs free energy of mixing. Examples of solutions not compatible with this class are aqueous or liquid solutions involving complex formation (speciation) or solid solutions that include cation-ordering or composition dependent symmetry-breaking phase transitions.
- Attributes
a_list
Array of tuples used internally by the class
conversion_string
List of strings that describe how to assign mole numbers to phase components
d2n_g_list
List of strings that identify second order compositional derivatives produced
d3n_g_list
List of strings that identify third order compositional derivatives produced
dn_g_list
List of strings that identify first order compositional derivatives produced
expression_parts
Array of Expression class instances
formula_string
String that describes how the chemical formula of a phase will be displayed
g_list
Array of tuples used internally by the class
implicit_functions
Array of ImplicitFunction class instances
module
Name of module
mu
1-d matrix of SymPy symbols for the chemical potentials of thermodynamic
n
1-d matrix of SymPy symbols for the mole numbers of thermodynamic
nc
Number of thermodynamic components in the solution
nT
SymPy expression for the total number of moles of all thermodynamic
params
Array of Parameter class instances
printer
Instance of a SymPy code printer class used in code generation
test_string
List of strings that describe feasible limits on the mole numbers of phase
variables
Array of Parameter class instances
Methods
add_expression_to_model
(self, expression, params)Adds an expression and associated parameters to the model.
create_code_module
(self[, phase, params, …])Creates include and code file for a model instance.
Creates a block of code that computes moles of endmember components from moles of elements according to a specified recipe.
Creates a block of code that computes a formula for this phase.
create_soln_calc_h_file
(self[, language, …])Creates an include file implementing model calculations.
create_soln_calib_h_file
(self[, language])Creates an include file implementing model parameter derivatives.
create_test_code_block
(self)Creates a block of code that tests moles of endmember components according to a specified recipe to ensure that values are viable.
get_include_dh_code
(self)Retrieves boolean flag specifying whether code implementing the Debye-Hückel functions will be included in generated code.
get_model_param_names
(self)Retrieves a list of strings of model parameter names.
get_model_param_symbols
(self)Retrieves a list of SymPy symbols for model parameters.
get_model_param_units
(self)Retrieves a list of strings of model parameter units.
get_symbol_for_p
(self)Retrieves SymPy symbol for pressure.
get_symbol_for_pr
(self)Retrieves SymPy symbol for reference pressure.
get_symbol_for_t
(self)Retrieves SymPy symbol for temperature.
get_symbol_for_tr
(self)Retrieves SymPy symbol for reference temperature.
get_symbol_for_v
(self)Retrieves SymPy symbol for volume.
get_symbol_for_vr
(self)Retrieves SymPy symbol for reference volume.
set_include_dh_code
(self[, include])Sets a boolean flag controlling the inclusion code implementing the Debye-Hückel functions.
set_reference_origin
(self[, Tr, Pr, Vr])Sets the reference conditions for the model.
symmetric_index_from_2d_array
(self[, elm])Given a 2D array index, retrieves a 1D symmetric storage index.
symmetric_index_from_3d_array
(self[, elm])Given a 3D array index, retrieves a 1D symmetric storage index.
-
property
a_list
¶ Array of tuples used internally by the class
Each tuple contains the following entries:
[0] str - Function name for derivatives of the Helmholtz energy
[1] int - Order of temperature derivative
[2] int - Order of volume derivative
Generally for internal use by the class
- Returns
- Array of tuples
-
add_expression_to_model
(self, expression, params, exp_type='unrestricted', lower_limits=(None, None), upper_limits=(None, None), implicit_functions=None)[source]¶ Adds an expression and associated parameters to the model.
Adds an expression for the Gibbs or Helmholtz energy to the solution model along with a description of expression parameters.
- Parameters
- expressionsympy.core.symbol.Symbol
A SymPy expression for the Gibbs free energy (if model_type is ‘TP’) or the Helmholtz energy (if model_type is ‘TV’).
The expression may contain an implicit variable, f, whose value is a function of T,P or T,V. The value of f is determined numerically by solving the implicit_function expression (defined below) at runtime using Newton’s method.
- paramsAn array of tuples
Structure (string, string, SymPy expression):
[0] str - Name of the parameter
[1] str - Units of parameter
[2] sympy.core.symbol.Symbol - SymPy symbol for the parameter
- exp_typestr, default=’unrestricted’
‘unrestricted’ - Expression is applicable over the whole of T,P or T,V space.
‘restricted’ - Expression applies only between the specified lower_limits and upper_limits.
- lower_limitstuple, default (None, None)
A tuple of SymPy expressions defining the inclusive lower (T,P) or (T,V) limit of applicability of the expression. Used only if exp_type is set to ‘restricted’.
- upper_limitstuple, default (None, None)
A tuple of SymPy expressions defining the inclusive upper (T,P) or (T,V) limit of applicability of the expression. Used only if exp_type is set to ‘restricted’.
- implicit_functionsArray of tuples
A tuple element contains three parts:
[0] sympy.core.symbol.Symbol - SymPy expression for an implicit function in two independent (T,P or T,V) variables and one dependent variable (f). The function is equal to zero.
[1] sympy.core.symbol.Symbol - SymPy symbol for the dependent variable f.
[2] sympy.core.symbol.Symbol - SymPy expression that initializes f in the iterative routine. This expression must be defined in terms of known parameters and Tr, Pr, T, P.
-
property
conversion_string
¶ List of strings that describe how to assign mole numbers to phase components
Each string in the list equates the bracketed component number to a mathematical expression involving mole numbers of elements in the bulk composition of the solution. For example, [‘[0]=[Na]’, ‘[1]=[Ca]’, ‘[2]=[K]’], which says that all the sodium in the solution defines the moles of the 1st comment (components are indexed starting with 0), all the calcium the 2nd component, and all the potassium the 3rd.
The righthand side of each expression in the list may be more complex, for example [Ca]-[Na]/2+[K], if appropriate. The conversion strings are used to convert bulk composition of the solution when expressed as elemental concentrations to concentrations of the endmember components.
- Returns
- List of strings, [str,…]
-
create_code_module
(self, phase='Feldspar', params={}, endmembers=[], identifier=None, prefix='cy', module_type='fast', silent=False, language='C', minimal_deriv_set=False)[source]¶ Creates include and code file for a model instance.
- Parameters
- phasestr
Model instance title (e.g., phase name). Used to name the generated function. Cannot contain blank spaces or special characters; underscore (“_”) is permitted. Convention capitalizes the first letter and letter following an underscore (“_”) character.
- paramsdict
Parameter values for the model instance. The keys of this dictionary are validated against parameter symbols stored for the model.
- endmemberslist of str
A list of prefixes for standard state property functions for the endmember components of this solution. E.g., “Albite_berman” will be used to call functions with names like Albite_berman_g(…) If the standard state property routines are coded by the StdStateModel Class in this module, all required functions will be generated and they will automatically be compliant with this naming convention.
- identifierstr
A unique identifier for the model instance. Defaults to local when module is created (rounded to the second).
- prefixstr
Prefix to function names for Python bindings, e.g., {prefix}_{phase}_{module}_g(T,P)
- module_typestr
Generate code that executes “fast”, but does not expose hooks for model parameter calibration. Alternately, generate code suitable for “calib”ration of parameters in the model, which executes more slowly and exposes additional functions that allow setting of parameters and generation of derivatives of thermodynamic functions with respect to model parameters.
- silentbool
Do not print status messages.
- languagestr
Language syntax for generated code. (“C” is the C99 programming language.)
- minimal_deriv_setbool
Generate a minimal set of compositional derivatives: dgdn, d2gdndt, d2gdndp, d3gdndt2, d3gdndtdp, d3gdndp2, d4gdndt3, d4gdndt2dp, d4gdndtdp2, d4gdndp3, d2gdn2, d3gdn2dt, d3gdn2dp, d3gdn3. This is the subset of derivatives currently required for solution phases that are imported into the phases module. Remaining derivatives are returned with values of zero.
- Returns
- resultBoolean
True if module is succesfully generated, False if some error occurred
-
create_conversion_code_block
(self)[source]¶ Creates a block of code that computes moles of endmember components from moles of elements according to a specified recipe.
The recipe is read from the property conversion_string.
The code block has access to the variables: T, P, and e, where e is a numpy array containing mole numbers of elements.
- Returns
- textstr
A block of C code that renders the conversion
Notes
The recipe looks like: [‘[0]=[Na]’, ‘[1]=[Ca]’, ‘[2]=[K]’], a list whose elements describe how to assign moles to each endmember. The entries in the list may contain algebraic combinations of elements [Na] and moles of endmember components [0].
-
create_formula_code_block
(self)[source]¶ Creates a block of code that computes a formula for this phase.
The formula is formatted as specified in the property formula_string.
The code block has access to the variables: T, P, and n, where n is a numpy array containing mole numbers of endmember components.
- Returns
- textstr
A block of C code that renders the formula
Notes
The formula string looks like: Ca[Ca]Na[Na]K[K]Al[Al]Si[Si]O8
-
create_soln_calc_h_file
(self, language='C', module_type='fast', minimal_deriv_set=False)[source]¶ Creates an include file implementing model calculations.
Note that this include file contains code for functions that implement the model for the generic case. It is meant to be included into a file that implements a specific parameterized instance of the model. See create_code_module().
The user does not normally call this function directly.
- Parameters
- languagestring
Language syntax for generated code. (“C” is the C99 programming language.)
- module_typestring
Generate code that executes “fast” but does not expose hooks for model parameter calibration. Alternately, generate code suitable for “calib”ration of parameters in the model, which executes more slowly and exposes additional functions that allow setting of parameters and generation of derivatives of thermodynamic functions with respect to model parameters.
- minimal_deriv_setbool
Generate a minimal set of compositional derivatives: dgdn, d2gdndt, d2gdndp, d3gdndt2, d3gdndtdp, d3gdndp2, d4gdndt3, d4gdndt2dp, d4gdndtdp2, d4gdndp3, d2gdn2, d3gdn2dt, d3gdn2dp, d3gdn3. This is the subset of derivatives currently required for solution phases that are imported into the phases module. Remaining derivatives are returned with values of zero.
-
create_soln_calib_h_file
(self, language='C')[source]¶ Creates an include file implementing model parameter derivatives.
Note that this include file contains code for functions that implement the model for the generic case. It is meant to be included into a file that implements a specific parameterized instance of the model. See create_code_module().
The user does not normally call this function directly.
- Parameters
- languagestring
Language syntax for generated code. (“C” is the C99 programming language.)
-
create_test_code_block
(self)[source]¶ Creates a block of code that tests moles of endmember components according to a specified recipe to ensure that values are viable.
The recipe is read from the property test_string.
The code block has access to the variables: T, P, and n, where n is a numpy array containing moles of endmember components.
- Returns
- textstr
A block of C code that renders the testing
Notes
The recipe looks like: [‘[0] > 0.0’, ‘[1] > 0.0’, ‘[2] > 0.0’], a list whose elements describe how to assign moles to each endmember. The entries in the list may contain algebraic combinations of moles of endmember components [0], and the length of the list (i.e., the number of tests) is unbounded.
-
property
d2n_g_list
¶ List of strings that identify second order compositional derivatives produced by the class
The create_code_module(…) method generates temperature, pressure, and compositional derivatives of the Gibbs free energy of solution. This property returns a list of all the second order compositional derivatives callable from the generated module. The majority of these derivatives will evaluate to zero if the minimal_deriv_set method parameter is initialized to True.
- Returns
- List of strings, [str,…]
-
property
d3n_g_list
¶ List of strings that identify third order compositional derivatives produced by the class
The create_code_module(…) method generates temperature, pressure, and compositional derivatives of the Gibbs free energy of solution. This property returns a list of all the third order compositional derivatives callable from the generated module. Most of these derivatives will evaluate to zero if the minimal_deriv_set method parameter is initialized to True.
- Returns
- List of strings, [str,…]
-
property
dn_g_list
¶ List of strings that identify first order compositional derivatives produced by the class
The create_code_module(…) method generates temperature, pressure and compositional derivatives of the Gibbs free energy of solution. This property returns a list of all the first order compositional derivatives callable from the generated module. Some of these derivatives will evaluate to zero if the minimal_deriv_set method parameter is initialized to True.
- Returns
- List of strings, [str,…]
-
property
expression_parts
¶ Array of Expression class instances
Builds a model by layering expression instances. Each instance may be applicable over all or a portion of the domain space of variables.
- Returns
- Array of Expression class instances, [Expression,…]
-
property
formula_string
¶ String that describes how the chemical formula of a phase will be displayed
The formula string consists of a concatenation of descriptors that allow the formula of the phase to be generated from its bulk composition. An example is: ‘Ca[Ca]Na[Na]K[K]Al[Al]Si[Si]O8’, suitable for describing the compositions of feldspars in the system NaAlSi3O8 - CaAl2Si2O8 - KAlSi3O8. The terms in square brackets within the string must contain standard element symbols. These bracketed quantities are replaced by the actual number of moles of the indicated element present in one mole of the solution when the formula of the phase is requested in the generated module. Other than the bracketed quantities, the content of the string is arbitrary.
- Returns
- str
-
property
g_list
¶ Array of tuples used internally by the class
Each tuple contains the following entries:
[0] str - Function name for derivatives of the Gibbs free energy
[1] int - Order of temperature derivative
[2] int - Order of pressure derivative
Generally for internal use by the class
- Returns
- Array of tuples
-
get_include_dh_code
(self)[source]¶ Retrieves boolean flag specifying whether code implementing the Debye-Hückel functions will be included in generated code.
- Returns
- boolean :
True or False (default)
-
get_model_param_names
(self)[source]¶ Retrieves a list of strings of model parameter names.
- Returns
- resultlist of str
Names of model parameters
-
get_model_param_symbols
(self)[source]¶ Retrieves a list of SymPy symbols for model parameters.
- Returns
- resultlist of sym.Symbol
SymPy symbols for model parameters
-
get_model_param_units
(self)[source]¶ Retrieves a list of strings of model parameter units.
- Returns
- resultlist of str
Units of model parameters
-
get_symbol_for_p
(self)[source]¶ Retrieves SymPy symbol for pressure.
- Returns
- Psympy symbol
SymPy symbol for pressure
-
get_symbol_for_pr
(self)[source]¶ Retrieves SymPy symbol for reference pressure.
- Returns
- Prsympy symbol
SymPy symbol for reference pressure
-
get_symbol_for_t
(self)[source]¶ Retrieves SymPy symbol for temperature.
- Returns
- Tsympy.core.symbol.Symbol
SymPy symbol for temperature
-
get_symbol_for_tr
(self)[source]¶ Retrieves SymPy symbol for reference temperature.
- Returns
- Trsympy symbol
SymPy symbol for reference temperature
-
get_symbol_for_v
(self)[source]¶ Retrieves SymPy symbol for volume.
- Returns
- Vsympy symbol
SymPy symbol for volume
-
get_symbol_for_vr
(self)[source]¶ Retrieves SymPy symbol for reference volume.
- Returns
- Vrsympy symbol
SymPy symbol for reference volume
-
property
implicit_functions
¶ Array of ImplicitFunction class instances
A model may require that one or more implicit function expressions be satisfied prior to evaluation of the model expressions.
- Returns
- Array of ImplicitFunction class instances, [ImplicitFunction,…]
-
property
module
¶ Name of module
- Returns
- Name of module (str)
-
property
mu
¶ 1-d matrix of SymPy symbols for the chemical potentials of thermodynamic components in the model
- Returns
- SymPy Matrix object (sympy.Matrix)
-
property
n
¶ 1-d matrix of SymPy symbols for the mole numbers of thermodynamic components in the model
- Returns
- SymPy Matrix object (sympy.Matrix)
-
property
nT
¶ SymPy expression for the total number of moles of all thermodynamic components in the solution (expressed as elements of n)
- Returns
- SymPy symbol object (sympy.Symbol)
-
property
nc
¶ Number of thermodynamic components in the solution
- Returns
- Number of components (int)
-
property
params
¶ Array of Parameter class instances
Parameters are calibrated quantities that define the model, like T_r and P_r.
- Returns
- Array of Parameter class instances, [Parameter,…]
-
property
printer
¶ Instance of a SymPy code printer class used in code generation
- Returns
- C99CodePrinter
-
set_include_dh_code
(self, include=False)[source]¶ Sets a boolean flag controlling the inclusion code implementing the Debye-Hückel functions.
- Parameters
- includebool
True or False
-
set_reference_origin
(self, Tr=298.15, Pr=1.0, Vr=2.5)[source]¶ Sets the reference conditions for the model.
Tr must be specified along with one of Pr or Vr.
- Parameters
- Trfloat
Reference temperature for the model (in Kelvins)
- Prfloat
Reference pressure for the model (in bars)
- Vrfloat
Reference volume of the model (in J/bar)
-
symmetric_index_from_2d_array
(self, elm=(0, 0))[source]¶ Given a 2D array index, retrieves a 1D symmetric storage index.
- Parameters
- elmtuple of int
Two element tuple containing the array index
Values must be in the range 1 to nc.
- Returns
- Index of 1D compact array corresponding to the specified element of the
- symmetric array
-
symmetric_index_from_3d_array
(self, elm=(0, 0, 0))[source]¶ Given a 3D array index, retrieves a 1D symmetric storage index.
- Parameters
- elmtuple of int
Three element tuple containing the array index
Values must be in the range 1 to nc.
- Returns
- Index of 1D compact array corresponding to the specified element of the
- symmetric array
-
property
test_string
¶ List of strings that describe feasible limits on the mole numbers of phase components
Each string in the list constrains the bracketed component number using a mathematical relation, e.g. [‘[0] > 0.0’, ‘[1] > 0.0’, ‘[2] > 0.0’], which says that the first endmember component (Components are indexed starting with 0) must always have a value greater than 0, and similarly for the 2nd and 3rd components. The mathematical expressions may be complex, as ‘[0]+[1] > 0.0’, or ‘[0] - [1] < 1/2’, as required. The test strings are used to constrain feasible values of component mole numbers when the bulk composition of the solution is set.
- Returns
- List of strings, [str,…]
-
property
variables
¶ Array of Parameter class instances
This property returns or sets an array of variables, either T, P, T_r and P_r (if model_type is ’TP’) or T, V, T_r and V_r (if model type is ’TV’). Array elements are encapsulated as instances of the Parameter class object. This is done simply as a convenience wrapper. Note that SymPy symbols that are suitable for developing model expressions using these variables are probably more easily accessed using the methods:
get_symbol_for_t()
get_symbol_for_p()
and so on
- Returns
- Array of Parameter class instances, [Parameter,…]
-
class
coder.
Debye
[source]¶ SymPy Function package extension: Debye function integral
Defines symbolic derivatives using a recurrence relation.
-
classmethod
eval
(x, n=None)[source]¶ Returns a canonical form of cls applied to arguments args.
The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.
-
classmethod
-
class
coder.
B
[source]¶ SymPy Function package extension: Born function
Definition: \(B = - \frac{1}{\varepsilon }\), where \(\varepsilon\) is the dielectric constant of water
-
class
coder.
Y
[source]¶ SymPy Function package extension: Temperature derivative of the Born function
Definition: \(Y = \frac{1}{\varepsilon }{\left( {\frac{{\partial \ln \varepsilon }}{{\partial T}}} \right)_P}\)
Note that \(Y = \frac{{\partial B}}{{\partial T}}\).
-
class
coder.
Q
[source]¶ SymPy Function package extension: Pressure derivative of the Born function
Definition: \(Q = \frac{1}{\varepsilon }{\left( {\frac{{\partial \ln \varepsilon }}{{\partial P}}} \right)_T}\)
Note that \(Q = \frac{{\partial B}}{{\partial P}}\).
-
class
coder.
X
[source]¶ SymPy Function package extension: Second partial derivative of the Born function with respect to temperature
Definition: \(X = \frac{1}{\varepsilon }\left[ {{{\left( {\frac{{{\partial ^2}\ln \varepsilon }}{{\partial {T^2}}}} \right)}_P} - \left( {\frac{{\partial \ln \varepsilon }}{{\partial T}}} \right)_P^2} \right]\)
Note that \(X = \frac{{{\partial ^2}B}}{{\partial {T^2}}}\).
-
class
coder.
U
[source]¶ SymPy Function package extension: Second partial derivative of the Born function with respect to temperature and pressure
Definition: \(U = \frac{1}{\varepsilon }\left[ {\left( {\frac{{{\partial ^2}\ln \varepsilon }}{{\partial T\partial P}}} \right) - {{\left( {\frac{{\partial \ln \varepsilon }}{{\partial T}}} \right)}_P}{{\left( {\frac{{\partial \ln \varepsilon }}{{\partial P}}} \right)}_T}} \right]\)
Note that \(U = \frac{{{\partial ^2}B}}{{\partial T\partial P}}\).
-
class
coder.
N
[source]¶ SymPy Function package extension: Second partial derivative of the Born function with respect to pressure
Definition: \(N = \frac{1}{\varepsilon }\left[ {{{\left( {\frac{{{\partial ^2}\ln \varepsilon }}{{\partial {P^2}}}} \right)}_T} - \left( {\frac{{\partial \ln \varepsilon }}{{\partial P}}} \right)_T^2} \right]\)
Note that \(N = \frac{{{\partial ^2}B}}{{\partial {P^2}}}\).
-
class
coder.
dXdT
[source]¶ SymPy Function package extension: Third partial derivative of the Born function with respect to temperature
Note that \(X = \frac{{{\partial ^2}B}}{{\partial {T^2}}}\).
-
class
coder.
dUdT
[source]¶ SymPy Function package extension: Third partial derivative of the Born function with respect to pressure and twice with respect to temperature
Note that \(U = \frac{{{\partial ^2}B}}{{\partial T\partial P}}\).
-
class
coder.
dUdP
[source]¶ SymPy Function package extension: Third partial derivative of the Born function with respect to temperature and twice with respect to pressure
Note that \(U = \frac{{{\partial ^2}B}}{{\partial T\partial P}}\). Identical to dNdT.
-
class
coder.
dNdT
[source]¶ SymPy Function package extension: Third partial derivative of the Born function with respect to temperature and twice with respect to pressure
Note that \(N = \frac{{{\partial ^2}B}}{{\partial {P^2}}}\).
-
class
coder.
dNdP
[source]¶ SymPy Function package extension: Third partial derivative of the Born function with respect to pressure
Note that \(N = \frac{{{\partial ^2}B}}{{\partial {P^2}}}\).
-
class
coder.
Agamma
[source]¶ SymPy Function package extension: Debye-Hückel function Agamma
Temperature and pressure derivatives to third order are coded for this function.
-
class
coder.
Bgamma
[source]¶ SymPy Function package extension: Debye-Hückel function Bgamma
Temperature and pressure derivatives to third order are coded for this function.
-
class
coder.
AsubG
[source]¶ SymPy Function package extension: Gibbs free energy equivalent of the Debye-Hückel function Agamma
Definition: \({A_G} = - 2\left( {\ln 2} \right)RT{A_\gamma }\)
-
class
coder.
AsubH
[source]¶ SymPy Function package extension: Enthalpy equivalent of the Debye-Hückel function Agamma
Definition: \({A_H} = {A_G} - T{\left( {\frac{{\partial {A_G}}}{{\partial T}}} \right)_P}\)
Pressure derivative: \(\frac{{\partial {A_H}}}{{\partial P}} = \frac{{\partial {A_G}}}{{\partial P}} - T\frac{{{\partial ^2}{A_G}}}{{\partial T\partial P}}\)
or, \(\frac{{\partial {A_H}}}{{\partial P}} = {A_V} - T{A_{Ex}}\)
-
class
coder.
AsubJ
[source]¶ SymPy Function package extension: Temperature derivative of AsubH
Definition: \({A_J} = {\left( {\frac{{\partial {A_H}}}{{\partial T}}} \right)_P}\)
-
class
coder.
AsubV
[source]¶ SymPy Function package extension: Pressure derivative of AsubG
Definition: \({A_V} = {\left( {\frac{{\partial {A_G}}}{{\partial P}}} \right)_T}\)
-
class
coder.
AsubKappa
[source]¶ SymPy Function package extension: Pressure derivative of AsubV
Definition: \({A_\kappa } = {\left( {\frac{{\partial {A_V}}}{{\partial P}}} \right)_T}\)
-
class
coder.
AsubEx
[source]¶ SymPy Function package extension: Temperature derivative of AsubV
Definition: \({A_{Ex} } = {\left( {\frac{{\partial {A_V}}}{{\partial T}}} \right)_P}\)
-
class
coder.
BsubG
[source]¶ SymPy Function package extension: Gibbs free energy equivalent of the Debye-Hückel function Bgamma
Definition: \({B_G} = - 2\left( {\ln 2} \right)RT{B_\gamma }\)
-
class
coder.
BsubH
[source]¶ SymPy Function package extension: Enthalpy equivalent of the Debye-Hückel function Bgamma
Definition: \({B_H} = {B_G} - T{\left( {\frac{{\partial {B_G}}}{{\partial T}}} \right)_P}\)
Pressure derivative: \(\frac{{\partial {B_H}}}{{\partial P}} = \frac{{\partial {B_G}}}{{\partial P}} - T\frac{{{\partial ^2}{B_G}}}{{\partial T\partial P}}\)
or, \(\frac{{\partial {B_H}}}{{\partial P}} = {B_V} - T{B_{Ex}}\)
-
class
coder.
BsubJ
[source]¶ SymPy Function package extension: Temperature derivative of BsubH
Definition: \({B_J} = {\left( {\frac{{\partial {B_H}}}{{\partial T}}} \right)_P}\)
-
class
coder.
BsubV
[source]¶ SymPy Function package extension: Pressure derivative of BsubG
Definition: \({B_V} = {\left( {\frac{{\partial {B_G}}}{{\partial P}}} \right)_T}\)
-
class
coder.
BsubKappa
[source]¶ SymPy Function package extension: Pressure derivative of BsubV
Definition: \({B_\kappa } = {\left( {\frac{{\partial {B_V}}}{{\partial P}}} \right)_T}\)
-
class
coder.
BsubEx
[source]¶ SymPy Function package extension: Temperature derivative of BsubV
Definition: \({B_{Ex} } = {\left( {\frac{{\partial {B_V}}}{{\partial T}}} \right)_P}\)
-
class
coder.
Expression
(expression, params, exp_type='unrestricted', lower_limit_T=None, lower_limit_PorV=None, upper_limit_T=None, upper_limit_PorV=None)[source]¶ Class holds properties of a model expression.
- Parameters
- expressionsympy.core.symbol.Symbol
Instance of a SymPy symbol class that contains the model expression
- paramsarray of instances of the Parameter class
Parameter class instances provided are relevant to the expression
- exp_typestr
‘unrestricted’ if the expression applies to the whole of (T,P) or (T,V) space
‘restricted’ if the expression applies to a portion of (T,P) or (T,V) space, specified by lower_limits and upper_limits
- lower_limit_TNumber
Lower limit of applicability of expression in T units
- lower_limit_PorVNumber
Lower limit of applicability of expression in P or V units
- upper_limit_TNumber
Upper limit of applicability of expression in T units
- upper_limit_PorVNumber
Upper limit of applicability of expression in P or V units
Notes
A generic expression class for defining a thermodynamic model. Multiple expressions may be used to construct the model.
- Attributes
exp_type
Type of expression
expression
Instance of a SymPy symbol class that contains the model expression
lower_limit_PorV
Lower limit of applicability of expression in pressure (bars) or volume (J/bar)
lower_limit_T
Lower limit of applicability of expression in temperature (K)
params
Array of instances of the Parameter class
upper_limit_PorV
Upper limit of applicability of expression in pressure (bars) or volume (J/bar)
upper_limit_T
Upper limit of applicability of expression in temperature (K)
-
property
exp_type
¶ Type of expression
‘unrestricted’ if the expression applies to the whole of (T,P) or (T,V) space
‘restricted’ if the expression applies to a portion of (T,P) or (T,V) space, specified by lower_limits and upper_limits
- Returns
- String
-
property
expression
¶ Instance of a SymPy symbol class that contains the model expression
- Returns
- sympy.core.symbol.Symbol
-
property
lower_limit_PorV
¶ Lower limit of applicability of expression in pressure (bars) or volume (J/bar)
- Returns
- Float
-
property
lower_limit_T
¶ Lower limit of applicability of expression in temperature (K)
- Returns
- Float
-
property
params
¶ Array of instances of the Parameter class
- Returns
- Parameter class instances relevant to the expression
-
property
upper_limit_PorV
¶ Upper limit of applicability of expression in pressure (bars) or volume (J/bar)
- Returns
- Float
-
property
upper_limit_T
¶ Upper limit of applicability of expression in temperature (K)
- Returns
- Float
-
class
coder.
f_mu_e
[source]¶ A placeholder class that creates a SymPy function that accepts three arguments and returns a value of zero/
This class is used by the SpeciationSolnModel class to initial functions that return excess chemical potentials for an ideal solution.
- Extends:
sym.Function
- Variables:
nargs {number} – Number of arguments to the function
-
classmethod
eval
(x, y, z)[source]¶ Returns a canonical form of cls applied to arguments args.
The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.
-
class
coder.
gSolvent
[source]¶ SymPy Function package extension: g solvent function
Temperature and pressure derivatives to second order are coded for this function.
-
class
coder.
Implicit_Function
(implicit_function, dep_variable, initial_guess)[source]¶ Class holds properties of an Implicit Function
- Parameters
- implicit_functionsympy.core.symbol.Symbol
A SymPy expression for an implicit function in two independent (T,P or T,V) variables and one dependent variable (f). The function is equal to zero; e.g., \(log(f) - f = 0\). This expression must be defined in terms of known parameters and Tr, Pr, T, P.
- dep_variablesympy.core.symbol.Symbol
A SymPy symbol for the dependent variable f
- initial_guesssympy.core.symbol.Symbol
A SymPy expression that initializes f in the iterative routine. This expression must be defined in terms of known parameters and Tr, Pr, T, P.
Notes
Implicit functions are solved prior to evaluating model expressions for the Gibbs free energy or Helmholtz energy. They must be differentiable with respect to model parameters T and P, or T and V. Typically, implicit functions are used to support expressions for equations of state, e.g. the Birch Murnaghan expression, which is implicit in V and T, when coupled with a reference pressure expression for the Gibbs free energy, which is explicit in T and P, requires an implicit function that solves for V given an input value of P.
- Attributes
-
property
function
¶ A SymPy expression for an implicit function in two independent (T,P or T,V) variables and one dependent variable (f). The function is equal to zero; e.g., \(log(f) - f = 0\). This expression must be defined in terms of known parameters and Tr, Pr, T, P.
- Returns
- sympy.core.symbol.Symbol
-
property
guess
¶ A SymPy expression that initializes f in the iterative routine. This expression must be defined in terms of known parameters and Tr, Pr, T, P.
- Returns
- sympy.core.symbol.Symbol
-
property
variable
¶ A SymPy symbol for the dependent variable f.
- Returns
- sympy.core.symbol.Symbol
-
class
coder.
ComplexSolnModel
(nc=None, ns=None, nw=None, model_type='TP')[source]¶ Class creates a model of the thermodynamic properties of a complex solution.
Inherits all methods and functionality of the Simple Solution Model class.
- Parameters
- ncint
Number of thermodynamic components in the solution
- nsint
Number of ordering parameters in the solution
- nwint
Number of species in the solution
- model_typestr
Model type of ‘TP’ implies that expressions are of the form of the Gibbs free energy.
Model type of ‘TV’ implies that expressions are of the form of the Helmholtz energy. This option is infrequently used.
Notes
This class is for creating a representation of the thermodynamic properties of a complex solution phase. The principal use of the class is to construct a model symbolically and to generate code that implements the model for model parameter calibration and thermodynamic property calculation.
A complex solution is one that does not contain implicit variables that need be determined via solution of conditions of homogeneous equilibrium. Examples of complex solutions include aqueous or liquid solutions involving complex formation (speciation) or solid solutions that include cation-ordering or composition dependent symmetry-breaking phase transitions.
- Attributes
Methods
add_expression_to_model
(self, expression, params)Adds an expression and associated parameters to the model.
create_code_module
(self[, phase, params, …])Creates include and code file for a model instance.
create_ordering_code
(self, …)Generates ordering function code for a complex solution model.
create_soln_calc_h_file
(self[, language, …])Creates an include file implementing model calculations.
create_soln_calib_h_file
(self[, language])Creates an include file implementing model parameter derivatives.
eval_asymmetric_regular_param
(self, nA_val, …)Evaluates a Taylor expansion of the molar non-configurational Gibbs free energy equivalent to an asymmetric regular solution parameter.
eval_endmember
(self, n_val, s_val, taylor)Evaluates a Taylor expansion of the molar non-configurational Gibbs free energy at the specified composition.
eval_regular_param
(self, nA_val, sA_val, …)Evaluates a Taylor expansion of the molar non-configurational Gibbs free energy equivalent to a regular solution parameter for the A-B join.
eval_ternary_param
(self, nA_val, sA_val, …)Evaluates a Taylor expansion of the molar non-configurational Gibbs free energy equivalent to a strict ternary solution parameter.
exchange_indices
(self, i, j, k, var)Reassigns indices in a derivative tensor to generate dependent entries.
taylor_expansion
(self[, order, mod_type])Contructs a Taylor expansion of the non-configurational Gibbs free energy of specified order using the SymPy symbols in the list var.
-
add_expression_to_model
(self, expression, params, ordering_functions=None)[source]¶ Adds an expression and associated parameters to the model.
- Parameters
- expressionsympy.core.symbol.Symbol
A SymPy expression for the Gibbs free energy (if model_type is ‘TP’) or the Helmholtz energy (if model_type is ‘TV’).
The expression may contain an implicit variable, f, whose value is a function of T,P or T,V. The value of f is determined numerically by solving the implicit_function expression (defined below) at runtime using Newton’s method.
- paramsAn array of tuples
Structure (string, string, SymPy expression):
[0] str - Name of the parameter
[1] str - Units of parameter
[2] sympy.core.symbol.Symbol - SymPy symbol for the parameter
- ordering_functionstuple
A tuple element contains four parts:
[0] [sympy.core.symbol.Symbol] - List of SymPy expressions for a system of implicit functions in independent variables T,P,n, and one or more dependent variables (ordering parameters). Each of the functions in the system must evaluate to zero.
[1] [sympy.core.symbol.Symbol] - List of SymPy symbols for the dependent variables in the specified system.
[2] [sympy.core.symbol.Symbol] - List of SymPy expressions that initialize the ordering parameters in the iterative routine that solve the system of implicit functions.
[3] [sympy.logic.boolalg.And] - An instance of the And class, as output from reduce_inequalities(), that holds a logical expression that embodies bound constraints on the ordering parameters
-
create_code_module
(self, phase='Feldspar', params={}, endmembers=[], identifier=None, prefix='cy', module_type='fast', silent=False, language='C', add_code_to_access_order_paramater=False, minimal_deriv_set=False)[source]¶ Creates include and code file for a model instance.
See documentation for superclass.
- Parameters
- add_code_to_access_order_paramaterbool
Generates additional functions to output values of order parameters as a function of composition, temperature and pressure
-
create_ordering_code
(self, moles_assign_text, order_assign_text)[source]¶ Generates ordering function code for a complex solution model.
- Parameters
- moles_assign_textstr
Text string containing C code for assigning moles of each component (n1, n2, …, nc) from a vector of moles, n.
- order_assign_textstr
Text string containing C code for assigning values of each ordering variable (s1, s2, …, ss) from a vector, s
- Returns
- outputstr
String of code that implements ordering functions and derivatives.
Notes
The user does not normally call this function directly.
-
create_soln_calc_h_file
(self, language='C', module_type='fast', minimal_deriv_set=True)[source]¶ Creates an include file implementing model calculations.
Note that this include file contains code for functions that implement the model for the generic case. It is meant to be included into a file that implements a specific parameterized instance of the model. See create_code_module().
The user does not normally call this function directly.
- Parameters
- languagestring
Language syntax for generated code. (“C” is the C99 programming language.)
- module_typestring
Generate code that executes “fast” but does not expose hooks for model parameter calibration. Alternately, generate code suitable for “calib”ration of parameters in the model, which executes more slowly and exposes additional functions that allow setting of parameters and generation of derivatives of thermodynamic functions with respect to model parameters.
- minimal_deriv_setbool
Generate a minimal set of compositional derivatives: dgdn, d2gdndt, d2gdndp, d3gdndt2, d3gdndtdp, d3gdndp2, d4gdndt3, d4gdndt2dp, d4gdndtdp2, d4gdndp3, d2gdn2, d3gdn2dt, d3gdn2dp, d3gdn3. This is the subset of derivatives currently required for solution phases that are imported into the phases module. Remaining derivatives are returned with values of zero.
-
create_soln_calib_h_file
(self, language='C')[source]¶ Creates an include file implementing model parameter derivatives.
Note that this include file contains code for functions that implement the model for the generic case. It is meant to be included into a file that implements a specific parameterized instance of the model. See create_code_module().
The user does not normally call this function directly.
- Parameters
- languagestring
Language syntax for generated code. (“C” is the C99 programming language.)
-
eval_asymmetric_regular_param
(self, nA_val, sA_val, nB_val, sB_val, taylor)[source]¶ Evaluates a Taylor expansion of the molar non-configurational Gibbs free energy equivalent to an asymmetric regular solution parameter.
This method yields a quantity DW, related to the asymmetric regular solution parameters, W112 and W122, as W + DW and W - DW:
dW = (27/2)G(2A/3+B/3) - 12G(A/2+B/2) - 3G(A) + 3G(B)/2
See method eval_regular_param to obtain W.
- Parameters
- nA_val[]
List of SymPy constants providing composition in terms of solution components of endmember A
Must have length nc
- sA_val[]
List of SymPy constants providing values of ordering parameters for the specified composition of endmember A
Must have length ns
- nB_val[]
List of SymPy constants providing composition in terms of solution components of endmember B
Must have length nc
- sB_val[]
List of SymPy constants providing values of ordering parameters for the specified composition of endmember B
Must have length ns
- taylorstr
A SymPy expression for Taylor expansion of the non-configurational Gibbs free energy interms of the elements of n and s
- Returns
- outputstr
A SymPy expression for the evaluated Taylor series
Notes
join A-B ==> (1/3)(2/3)(W + dW(2/3-1/3)) = G(2A/3+B/3)-2G(A)/3-G(B)/3
-
eval_endmember
(self, n_val, s_val, taylor)[source]¶ Evaluates a Taylor expansion of the molar non-configurational Gibbs free energy at the specified composition.
- Parameters
- n_val[]
List of SymPy constants providing composition in terms of solution components
Must have length nc
- s_val[]
List of SymPy constants providing values of ordering parameters for the specified composition
Must have length ns
- taylorstr
A SymPy expression for Taylor expansion of the non-configurational Gibbs free energy interms of the elements of n and s
- Returns
- outputstr
A SymPy expression for the evaluated Taylor series
-
eval_regular_param
(self, nA_val, sA_val, nB_val, sB_val, taylor)[source]¶ Evaluates a Taylor expansion of the molar non-configurational Gibbs free energy equivalent to a regular solution parameter for the A-B join.
- Parameters
- nA_val[]
List of SymPy constants providing composition in terms of solution components of endmember A
Must have length nc
- sA_val[]
List of SymPy constants providing values of ordering parameters for the specified composition of endmember A
Must have length ns
- nB_val[]
List of SymPy constants providing composition in terms of solution components of endmember B
Must have length nc
- sB_val[]
List of SymPy constants providing values of ordering parameters for the specified composition of endmember B
Must have length ns
- taylorstr
A SymPy expression for Taylor expansion of the non-configurational Gibbs free energy interms of the elements of n and s
- Returns
- outputstr
A SymPy expression for the evaluated Taylor series
Notes
join A-B ==> 4 ( G(A/2+B/2) - G(A)/2 - G(B)/2 )
-
eval_ternary_param
(self, nA_val, sA_val, nB_val, sB_val, nC_val, sC_val, taylor)[source]¶ Evaluates a Taylor expansion of the molar non-configurational Gibbs free energy equivalent to a strict ternary solution parameter.
WT = 27G(A/3+B/3+C/3) - 12G(A/2+B/2) - 12G(A/2,C/2) - 12G(B/2,C/2) + 3G(A) + 3G(B) + 3G(C)
- Parameters
- nA_val[]
List of SymPy constants providing composition in terms of solution components of endmember A
Must have length nc
- sA_val[]
List of SymPy constants providing values of ordering parameters for the specified composition of endmember A
Must have length ns
- nB_val[]
List of SymPy constants providing composition in terms of solution components of endmember B
Must have length nc
- sB_val[]
List of SymPy constants providing values of ordering parameters for the specified composition of endmember B
Must have length ns
- nC_val[]
List of SymPy constants providing composition in terms of solution components of endmember C
Must have length nc
- sC_val[]
List of SymPy constants providing values of ordering parameters for the specified composition of endmember C
Must have length ns
- taylorstr
A SymPy expression for Taylor expansion of the non-configurational Gibbs free energy interms of the elements of n and s
- Returns
- outputstr
A SymPy expression for the evaluated Taylor series
Notes
- A-B-C ==> (1/27) W(A,B,C) + (1/9) W(A,B) + (1/9) W(A,C) + (1/9) W(B,C)
= G(A/3+B/3+C/3) - G(A)/3 - G(B)/3 - G(C)/3
-
exchange_indices
(self, i, j, k, var)[source]¶ Reassigns indices in a derivative tensor to generate dependent entries.
- Parameters
- i,j,kint
Indices, i <= j <= k, of a tensor derivative
- varstr
Name of tensor
- Returns
- outputstr
Code fragment (in C) that assigns name[i][j][k] to redundant elements of the tensor, e.g. name[k][j][i]
Notes
The user does not normally call this function directly.
-
property
ns
¶ Number of ordering parameters in the solution
- Returns
- Number of ordering parameters in the solution (int)
-
property
nw
¶ Number of species in the solution
- Returns
- Number of species in the solution (int)
-
property
order_sub
¶ Deprecated
-
property
s
¶ 1-d matrix of SymPy symbols for the ordering parameters in the model
- Returns
- SymPy Matrix object (sympy.Matrix)
-
taylor_expansion
(self, order=2, mod_type='non-convergent')[source]¶ Contructs a Taylor expansion of the non-configurational Gibbs free energy of specified order using the SymPy symbols in the list var.
- Parameters
- orderint
Order of the Taylor expansion. Second order is the default. The maximum order is 4.
- mod_typestr
‘convergent’: order parameter expansion only has symmetric terms
‘non-convergent’: order parameter expansion has all terms
- Returns
- outputtuple
Number of terms in the expansion
Taylor expansion as a SymPy expression
List of SymPy symbols for energetic terms in the expansion
List of SymPy expressions multiplying energetic terms in the expansion
-
class
coder.
Ordering_Functions
(ordering_functions, dep_variables, initial_guesses, dep_bounds)[source]¶ Class holds properties of implicit functions that describe homogeneous equilibria via cation ordering or speciation
- Parameters
- ordering_functionslist[sympy.core.symbol.Symbol]
A list of SymPy expressions defining a system of implicit multi-variable functions having 2+nc independent variables (T,P, and moles of endmember components) and one or more dependent variables (ordering parameters). The number of implicit equations in the system must equal the number of ordering parameters. The implicit function expressions must all be equal to zero; e.g., \(log(f) - f = 0\). The list of expressions must be defined in terms of known parameters and Tr, Pr, T, P, n.
- dep_variableslist[sympy.core.symbol.Symbol]
A list of SymPy symbols for the dependent variables, i.e., the ordering parameters or species mole fractions
- initial_guesseslist[sympy.core.symbol.Symbol]
SymPy expressions that initialize the ordering parameters in the iterative routines that solve the system. These expression must be defined in terms of known solution parameters and Tr, Pr, T, P, n.
- boundssympy.logic.boolalg.And
An instance of the And class, as output from reduce_inequalities(), which holds a logical expression that embodies bound constraints on the ordering parameters
Notes
This system of equations is solved for the ordering parameters prior to evaluating model expressions for the Gibbs free energy and its derivatives. The equations must be differentiable with respect to model parameters T and P.
- Attributes
-
property
bounds
¶ Storage for the bounds parameter
- Returns
- sympy.logic.boolalg.And
-
property
function
¶ Storage for the ordering_functions parameter
- Returns
- sympy.core.symbol.Symbol
-
property
guess
¶ Storage for the initial_guesses parameter
- Returns
- sympy.core.symbol.Symbol
-
property
variable
¶ Storage for the dep_variables parameter
- Returns
- sympy.core.symbol.Symbol
-
class
coder.
Parameter
(name, units, expression)[source]¶ Class holds properties of a model parameter.
- Parameters
- namestr
Name of the parameter
- unitsstr
Units of the parameter
- expressionsympy.core.symbol.Symbol
Instance of a SymPy symbol class equivalent to name
Notes
Class is utilized principally to store model parameters and model variables used by the Expression class to construct expressions for the Gibbs free energy or Helmholtz energy.
- Attributes
expression
Instance of a SymPy symbol class equivalent to property name
name
Name of the parameter
units
Units of the parameter
-
property
expression
¶ Instance of a SymPy symbol class equivalent to property name
- Returns
- sympy.core.symbol.Symbol
-
property
name
¶ Name of the parameter
- Returns
- String
-
property
units
¶ Units of the parameter
- Returns
- String
-
class
coder.
SpeciationSolnModel
(nc=None, nb=None, ns=None, Cb=None, Cs=None, R=None, model_type='ideal', debug_print=False, multiroot_method='gsl_multiroot_fdfsolver_gnewton')[source]¶ Class creates a model of the thermodynamic properties of a speciated solution.
Inherits all methods and functionality of the Complex Solution Model class.
- Parameters
- ncint
Number of thermodynamic components in the solution
- nbint
Number of basis species in the solution (usually, nb == nc)
- nsint
Number of non-basis species in the solution
- Cbnumpy 2-d array
An array of nb rows and ne columns that maps the composition of basis species to moles of endmember components. Often, this matrix is the identity matrix, but that condition is not required. Cb must be an invertible matrix.
- Csnumpy 2-d array
An array of ns rows and ne columns that maps the composition of non-basis species to moles of endmember components.
- RSymPy Matrix, (ns,nb)
A SymPy Matrix with ns rows and nb columns containing reaction coefficients that map basis to non-basis species. This matrix need be provided only if an expression added to the model utilizes a SymPy indexed symbol (e.g., the r property of this class). Otherwise, the quanity is unreferenced.
- model_type(str, opt …)
Type of speciation model. Default is (‘ideal’) implying ideal mixing between basis and non-basis species. Acceptable alternatives are:
(‘debye-huckel-limit’, []) - Non-ideal interactions are described by the Debye-Hückel limiting law and the mole fraction -> molality conversion term. The second element of the tuple is a list of charges associated with the basis plus non-basis species; anions have negative values, cations have positive values, neutral species have zero values.
(‘debye-huckel’, [], []) - Non-ideal interactions are described by the full version of Debye-Hückel theory (including the denominator term) and the mole fraction -> molality conversion term. The second element of the tuple is a list of charges associated with the basis plus non-basis species. The third term in the tuple is a list of constants associated with the azero contribution to the Debye-Hückel term for each basis and non-basis species.
(‘debye-huckel-ext’, [], [], []) - Non-ideal interactions are described by the full version of Debye-Hückel theory (including the denominator term) plus the mole fraction -> molality conversion term and an extended term. The second element of the tuple is a list of charges associated with the basis plus non-basis species. The third term in the tuple is a list of constants associated with the azero contribution to the Debye-Hückel term for each basis and non-basis species. The fourth term is a list of constant coefficients that pre- multiply the species molality and define an extended term contribution to the excess Gibbs energy.
- debug_printbool
Print debug messages from root solvers in generated C code
- multiroot_methodstr
Method to use in GNU Scientific Library (GSL) solver for homogeneous equilibrium speciation. Options are:
gsl_multiroot_fdfsolver_hybridsj
gsl_multiroot_fdfsolver_hybridj
gsl_multiroot_fdfsolver_newton
gsl_multiroot_fdfsolver_gnewton (default)
Notes
The property mu declared by the SimpleSolnModel subclass is modified by this class to return a 1-d SymPy Matrix of symbols for endmember chemical potentials of all solution species, nb+ns, numbered as 1 … nb+ns
This class is for creating a representation of the thermodynamic properties of a speciated solution phase. The principal use of the class is to construct a model symbolically, and to generate code that implements the model for model parameter calibration and thermodynamic property calculation.
A speciated solution is one that contains implicit concentration variables that need to be determined via solution of conditions of homogeneous equilibrium. Examples of speciated solutions include aqueous solutions with complexes or gas solutions with multiple species.
Model specification:
A model may be contructed in a manner similar to the SimpleSolnModel class by adding an expression for the total Gibbs free energy of solution using the add_expression_to_model() method. This methoid of construction is suitable if the specification is compact and does not involve iteration over a common expression. Alternatively,
A model may be formed by adding a basis species and non-basis species contribution, where the non-basis species contribution is specified as an implicit sum over a parameterized exprression of fixed mathematical form. A model of this kind is constructed by adding multiple terms using the add_expression_to_model() method. Typically, the terms are:
A SymPy expression for the ideal Gibbs free energy of solution contribution of the basis species. This expression should include standard state, and configurational contributions
A SymPy expression for the ideal Gibbs free energy of solution contribution of the non-basis species. This sympy expression represents a term that involves an implicit summation over non-basis species. This expression may be parameterized using SymPy IndexedBase-class symbols and a sympy function describing the standard state chemical potential of the non-basis species.
A SymPy expression for the non-ideal Gibbs free energy of solution. The expression may be parameterized using an arbitrary number of SymPy IndexedBase-class symbols.
- Attributes
- a_list (inherited from super class)
b_list
Symbolic definitions of basis species
Cb
Stoichiometric array mapping basis species to elements
Cs
Stoichiometric array mapping non-basis species to elements
debug_print
Print debug messages from root solvers in generated C code
- expression_parts (inherited from super class)
- g_list (inherited from super class)
i
Index variable for looping over basis species
- implicit_functions (inherited from super class)
j
Index variable for looping over non-basis species
k
Index variable for looping over all species
- module (inherited from super class)
- mu (overrides super class)
multiroot_method
Method to use in GNU Scientific Library (GSL) multiroot solver
mu_e
Generic excess chemical potential of a non-basis species
mu_ex
A SymPy matrix of SymPy functions that calculate the excess chemical
mu_s
Generic standard state chemical potenial of a non-basis species
- n (inherited from super class)
nb
Number of basis species
- nc (inherited from super class)
ns
Number of non-basis species
- nT (inherited from super class)
- params (inherited from super class)
- printer (inherited from super class)
r
Vector of SymPy symbols for indexed stoichiometric reaction coefficients
- s (inherited from super class)
R
SymPy Matrix of stoichiometric reaction coefficients
- Rg
- variables (inherited from super class)
-
property
Cb
¶ Stoichiometric array mapping basis species to elements
An array of nb rows and ne columns that maps the composition of basis species to moles of endmember components. Often, this matrix is the identity matrix, but that condition is not required. Cb must be an invertible matrix.
- Returns:
Numpy 2d array
-
property
Cs
¶ Stoichiometric array mapping non-basis species to elements
[description]
- Returns:
[type] – [description]
-
property
R
¶ SymPy Matrix of stoichiometric reaction coefficients
A SymPy Matrix of shape (ns, nb) whose elements are constants that map the stoichiometry of basis species to that of non-basis species. The constants are SymPy compatible rational numbers. The columns of R are assigned to the elements of r at code generation. See the description of the r property for further explanation as to how R is defined.
R need be specified only if one or more of the expressions added to the model contain a SymPy IndexedBase variable.
- Returns:
SymPy Matrix (ns,nb)
-
property
Rgas
¶ Sympy symbol for the Universal gas constant
The universal gas constant used as a parameter in constructing expresions for the Gibbs free energy. Must be given units and a parameter value.
- Returns:
SymPy Symbol
-
property
b_list
¶ Symbolic definitions of basis species
A list of SymPy expressions that define the mole fractions of basis species (the elements of b_list) in terms of moles of endmember components and mole fractions of non-basis species (elements of s)
- Returns:
list of SymPy expressions
-
create_code_module
(self, phase='IdealGas', params={}, endmembers=[], identifier=None, prefix='cy', module_type='fast', silent=False, language='C', minimal_deriv_set=False, debug=0)[source]¶ Creates include and code file for a model instance.
- Parameters
- phasestr
Model instance title (e.g., phase name). Used to name the generated function. Cannot contain blanks or special characters; underscore (“_”) is permitted. Convention capitalizes the first letter and letter following a “_” character.
- paramsdict
Parameter values for the model instance. The keys of this dictionary are validated against parameter symbols stored for the model.
- endmemberslist of str
A list of prefixes for standard state property functions for the endmember components of this solution. e.g., “Albite_berman” will be used to call functions with names like Albite_berman_g(…) If the standard state property routines are coded by the StdStateModel Class in this module, all required functions will be generated and they will automatically be compliant with this naming convention. There must be nc+ns entries in this list, i.e., list elements must include basis + non-basis species in an order that is internally consistent with specification of the G function.
- identifierstr
A unique identifier for the model instance. Defaults to date/time when module is created (rounded to the second).
- prefixstr
Prefix to function names for python bindings, e.g., {prefix}_{phase}_{module}_g(T,P)
- module_typestr
Generate code that executes “fast”, but does not expose hooks for model parameter calibration. Alternately, generate code suitable for “calib”ration of parameters in the model, which executes more slowly and exposes additional functions that allow setting of parameters and generation of derivatives of thermodynamic functions with respect to model parameters.
- silentbool
Do not print status messages.
- languagestr
Language syntax for generated code, (“C” is the C99 programming language.)
- minimal_deriv_setbool
Generate a minimal set of compositional derivatives: dgdn, d2gdndt, d2gdndp, d3gdndt2, d3gdndtdp, d3gdndp2, d4gdndt3, d4gdndt2dp, d4gdndtdp2, d4gdndp3, d2gdn2, d3gdn2dt, d3gdn2dp, d3gdn3. This is the subset of derivatives currently required for solution phases that are imported into the phases module. Remaining derivatives are returned with values of zero.
- debugint
Level of debugging output generated by module: 0 : None 1 : Informational messages 2 : Informational plus normal debugging messages 3 : Verbose informational and debugging messages
- Returns
- resultBoolean
True if module is succesfully generated, False if some error occurred
Notes
This method overrides that of the super class.
-
create_ordering_code
(self, moles_assign_text, order_assign_text)[source]¶ Generates ordering function code for a speciation solution model.
- Parameters
- moles_assign_textstr
Text string containing C code for assigning moles of each component (n1, n2, …, nc) from a vector of moles, n.
- order_assign_textstr
Text string containing C code for assigning values of each ordering variable (s1, s2, …, ss) from a vector, s
- Returns
- outputstr
String of code that implements ordering functions and derivatives.
Notes
The user does not normally call this function directly.
-
property
debug_print
¶ Print debug messages from root solvers in generated C code
Passed to code generation routines to flag generation of output related to the functioning of root finding and related numerical methods for speciation.
- Returns:
bool
-
property
i
¶ Index variable for looping over basis species
A SymPy instance of the class Idx that is used to loop over terms in the Gibbs free energy that describe properties of basis species. The range of the index is 1 to nb+1. Use this symbol as an index for summation or product terms in the potential.
- Returns:
SymPy.Idx
-
property
j
¶ Index variable for looping over non-basis species
A SymPy instance of the class Idx that is used to loop over terms in the Gibbs free energy that describe properties of non-basis species. The range of the index is 1 to ns+1. Use this symbol as an index for summation or product terms in the potential.
- Returns:
SymPy.Idx
-
property
k
¶ Index variable for looping over all species
A SymPy instance of the class Idx that is used to loop over terms in the Gibbs free energy that describe properties of species. The range of the index is 1 to nb+ns+1. Use this symbol as an index for summation or product terms in the potential.
- Returns:
SymPy.Idx
-
property
mu
¶ 1-d matrix of SymPy symbols for the chemical potentials of basis and non-basis species in the model
- Returns
- SymPy Matrix object (sympy.Matrix)
Notes
The property definition is changed from that of the underlying Simple Solution superclass
-
property
mu_e
¶ Generic excess chemical potential of a non-basis species
A SymPy instance of the class Function that is used to represent the value of the excess chemical potential of a non-basis species in an expression that loops species properties. In such a loop, values of mu_e are replaced with specific entries of mu_ex[…] when the code is printed. The instance is a function of T, P, and n.
By default, for an ideal solution this function returns a value of zero.
- Returns:
SymPy function
-
property
mu_ex
¶ A SymPy matrix of SymPy functions that calculate the excess chemical potential of each species in solution
The functions must have arguments T, P and n, where T is temperature, P is pressure and n is a vector of mole numbers of basis species in solution. The matrix has shape (nb+ns, 1)
By default, for an ideal solution each function returns a value of zero.
- Returns:
SymPy Matrix
-
property
mu_s
¶ Generic standard state chemical potenial of a non-basis species
A SymPy instance of the class Function that is used to represent the value of the standard state Gibbs free energy of a non-basis species in an expression that loops species properties. In such a loop, values of mu_s are replaced with specific entries of mu[…] when the code is printed. The instance is a function of T and P.
- Returns:
SymPy.Function
-
property
multiroot_method
¶ Method to use in GNU Scientific Library (GSL) multiroot solver
The gsl_multiroot_fdfsolver_type. Options are:
“gsl_multiroot_fdfsolver_hybridsj”
“gsl_multiroot_fdfsolver_hybridj”
“gsl_multiroot_fdfsolver_newton”
“gsl_multiroot_fdfsolver_gnewton” (default)
- Returns:
str
-
property
nb
¶ Number of basis species
The number of basis spcies is generally equal to the number of thermodynamic components (nc) required to describe the solution phase.
- Returns:
int
-
property
ns
¶ Number of non-basis species
The number of non-basis species is strictly positive but unbounded. Concentrations of non-basis species are determined by solution of mass action expressions corresponding to conditions of homogeneous equilibrium.
- Returns:
int
-
property
r
¶ Vector of SymPy symbols for indexed stoichiometric reaction coefficients
A SymPy Matrix of length nc whose elements are instances of the SymPy class IndexedBase. These symbols are used to parameterize model Gibbs free energy expressions that require coefficients that map the stoichiometry of basis species to that of non-basis species; i.e., (moles of non-basis species) = r[0]*(moles of 1st basis species) + … r[nc-1]*(moles of nc-1 basis species). Numerical values for these symbols will be assigned by letting r[…] denote rows of the numpy matrix R, where R is given by Cs (Cb)^-1. Cb is an array of nb rows and ne columns (ne is the number of elements; generally ne = nb) that maps the composition of basis species to moles of endmember components. Cs is an array of ns rows and ne columns that maps the composition of non-basis species to moles of endmember components. Numpy matrices Cb and Cs are provided to the class at the code generation step when calling the create_code_module() method.
- Returns:
SymPy.Matrix – length nb
-
class
coder.
SubCodePrinter
(settings=None, nBasis=0, forIndex='i', sum_result='result')[source]¶ Subclass of the C99 code printer class in SymPy
Extension expands \(x^2\), \(x^3\), and \(x^4\) as multiplication rather than pow(x, (double)n).
The second implements a version of user function derivative printing specified to endmember chemical potential derivatives called externally from a C structure. (See implementation below.)
- Attributes
forIndex
Index variable used in for loop generation for printing derivatives of
nBasis
Number of basis species used in printing derivatives of standard state
sum_result
Name of assignment variable used when printing summations
-
doprint
(self, expr, assign_to=None)[source]¶ Print the expression as code.
- Parameters
- exprExpression
The expression to be printed.
- assign_toSymbol, MatrixSymbol, or string (optional)
If provided, the printed code will set the expression to a variable with name
assign_to
.
-
property
forIndex
¶ Index variable used in for loop generation for printing derivatives of standard state chemical potentials
See _print_derivative method for the function mu_s to illustrate functionality. forIndex is the string equivalent of the index variable (SymPy class Idx) used in summation expressions that are fed to the SpeciationSolnModel class.
- Returns:
[type] – [description]
-
property
nBasis
¶ Number of basis species used in printing derivatives of standard state chemical potentials
See _print_derivative method for the function mu_s to illustrate functionality. nBasis is the number of basis species in an instance of the SpeciationSolnModel class.
- Returns:
str
-
property
print_subs
¶ A list of tuples of expression substitutions used in doprint()
Each tuple is of the form (sympy expression to be replaced, sympy expression to be substituted). Replacement is done in expressions passed to the doprint() method.
- Returns:
list of tuples
-
property
sum_result
¶ Name of assignment variable used when printing summations
See _print_Sum method to illustrate functionality. When an instance of the SymPy class Sum is printed, the result is assigned to a variable of this name.
- Returns:
str