#### Next topic

Coder Templates package

# 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_type : str 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) [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. berman_db (pandas dataframe) Berman (1988) database as a Pandas dataframe. elements (pandas dataframe) Table of elemental symbols, names, and molecular weights. entropies (pandas dataframe.) Table of third law entropies of the elements as adopted by Helgeson (1978). 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. g_list (array of tuples) [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. 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. module (str) Name of module params (array of Parameter class instances) Parameters are calibrated quantities that define the model, like T_r and P_r printer (C99CodePrinter) Instance of a Sympy code printer class used in code generation variables (array of Parameter class instances) Variables are quantities like T and P, used in the model. They are not calibrated.
add_expression_to_model(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: expression : sympy.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. params : an 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_type : str, 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_limits : tuple 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_limits : tuple 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_functions : array 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_functions : bool, 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. The default behavior may be disabled 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(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: language : str Language syntax for generated code, (“C” is the C99 programming language.) module_type : str 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(language='C')[source]

Creates a C-code include file implementing model calibration functions.

Parameters: language : string Language syntax for generated code, (“C” is the C99 programming language.)

Notes

Thw 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(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: phase : str 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. formula : str 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). params : dict Parameter values for the model instance. The keys of this dictionary are validated against parameter symbols stored for the model. identifier : str A unique identifier for the model instance. Defaults to local date and time when module is created (rounded to the second). prefix : str Prefix to function names for Python bindings, e.g., {prefix}_{phase}_{module}_g(T,P). module_type : str 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. silent : bool Print (True) or do not print (False) status messages. language : string Language syntax for generated code, (“C” is the C99 programming language; “C++” is the C++ programming language.) result : Boolean True if module is succesfully generated, False if some error occurred
get_berman_std_state_database(identifier=None, extend_defs=False)[source]

Retrieves priors from the thermodynamic database of Berman (1988).

Parameters: identifier : int Value may be None or an integer in the range (0, length of Berman database). extend_defs : bool 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. result : variable 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()[source]

Retrieves boolean flag specifying whether code implementing the Born functions will be linked to the generated module.

Returns: boolean : bool True or False (default)
get_include_debye_code()[source]

Retrieves a boolean flag specifying whether a block of code implementing the Debye integral function will be generated.

Returns: boolean : bool True or False (default)
get_model_param_names()[source]

Retrieves a list of strings of model parameter names.

Returns: result : list of str Names of model parameters
get_model_param_symbols()[source]

Retrieves a list of sympy symbols for model parameters.

Returns: result : list of sym.Symbol SymPy symbols for model parameters
get_model_param_units()[source]

Retrieves a list of strings of model parameter units.

Returns: result : list of str Units of model parameters
get_module_name()[source]

Retrieves module name.

The module name is used in creating file names for coded functions. Maintained for backward compatibility.

Returns: string : str The name of the module.
get_symbol_for_p()[source]

Retrieves sympy symbol for pressure.

Returns: P : sympy symbol SymPy symbol for pressure
get_symbol_for_pr()[source]

Retrieves sympy symbol for reference pressure.

Returns: Pr : sympy symbol SymPy symbol for reference pressure
get_symbol_for_t()[source]

Retrieves sympy symbol for temperature.

Returns: T : sympy.core.symbol.Symbol SymPy symbol for temperature
get_symbol_for_tr()[source]

Retrieves sympy symbol for reference temperature

Returns: Tr : sympy symbol SymPy symbol for reference temperature
get_symbol_for_v()[source]

Retrieves sympy symbol for volume.

Returns: V : sympy symbol SymPy symbol for volume
get_symbol_for_vr()[source]

Retrieves sympy symbol for reference volume.

Returns: Vr : sympy symbol SymPy symbol for reference volume
parse_formula(formula_string='Si(1)O(2)')[source]

Parse a chemical formula, and return a molecular weight and an array of elemental concentrations.

Parameters: formula_string : str Formula of compound specified in the standard form SiO2 -> Si(1)O(2). mw, elmvector : tuple [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.
set_include_born_code(include=False)[source]

Set a boolean flag controlling the inclusion of code implementing the Born functions.

Parameters: include : bool True or False
set_include_debye_code(include=False)[source]

Sets a boolean flag controlling the inclusion of a block of code implementing the Debye integral function.

Parameters: include : bool True or False
set_module_name(module_s)[source]

Retrieves module name.

The module name is used in creating file names for coded functions. Maintained for backward compatibility.

Parameters: module_s : str The name of the module.
set_reference_origin(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: Tr : float Reference temperature for the model (in Kelvins) Pr : float Reference pressure for the model (in bars) Vr : float Reference volume of the model (in J/bar)
class coder.SimpleSolnModel(nc=None, model_type='TP')[source]

Class creates a model of the thermodynamic properties of a simple solution.

Parameters: nc : int Number of thermodynamic components in the solution model_type : str 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) [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. 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. g_list (array of tuples) [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. 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. module (str) Name of module mu (sym.Matrix) 1-d matrix of SymPy symbols for the chemical potentials of thermodynamic components in the model n (sym.Matrix) 1-d matrix of SymPy symbols for the mole numbers of thermodynamic components in the model nc (int) Number of thermodynamic components in the solution nT (sym.Symbol) SymPy expression for the total number of moles of all thermodynamic components in the solution (expressed as elements of n) params (array of Parameter class instances) Parameters are calibrated quantities that define the model, like T_r and P_r printer (C99CodePrinter) Instance of a Sympy code printer class used in code generation variables (array of Parameter class instances) Variables are quantities like T and P, used in the model. They are not calibrated.
add_expression_to_model(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: expression : sympy.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. params : an 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_type : str, 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_limits : tuple, 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_limits : tuple, 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_functions : array 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.
create_code_module(phase='Feldspar', params={}, endmembers=[], identifier=None, prefix='cy', module_type='fast', silent=False, language='C')[source]

Creates include and code file for a model instance.

Parameters: phase : str 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. params : dict Parameter values for the model instance. The keys of this dictionary are validated against parameter symbols stored for the model. endmembers : list 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. identifier : str A unique identifier for the model instance. Defaults to local when module is created (rounded to the second). prefix : str Prefix to function names for python bindings, e.g., {prefix}_{phase}_{module}_g(T,P) module_type : str 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. silent : Bool Do not print status messages. language : str Language syntax for generated code, (“C” is the C99 programming language.) result : Boolean True if module is succesfully generated, False if some error occurred
create_conversion_code_block()[source]

Create 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 an numpy array containing mole numbers of elements

Returns: text : str 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()[source]

Create 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 an numpy array containing mole numbers of endmember components

Returns: text : str 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(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_code_module().

The user does not normally call this function directly.

Parameters: language : string Language syntax for generated code, (“C” is the C99 programming language.) module_type : string 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_soln_calib_h_file(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: language : string Language syntax for generated code, (“C” is the C99 programming language.)
create_test_code_block()[source]

Create 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: text : str 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.

get_include_dh_code()[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()[source]

Retrieves a list of strings of model parameter names.

Returns: result : list of str Names of model parameters
get_model_param_symbols()[source]

Retrieves a list of sympy symbols for model parameters.

Returns: result : list of sym.Symbol SymPy symbols for model parameters
get_model_param_units()[source]

Retrieves a list of strings of model parameter units.

Returns: result : list of str Units of model parameters
get_symbol_for_p()[source]

Retrieves sympy symbol for pressure.

Returns: P : sympy symbol SymPy symbol for pressure
get_symbol_for_pr()[source]

Retrieves sympy symbol for reference pressure.

Returns: Pr : sympy symbol SymPy symbol for reference pressure
get_symbol_for_t()[source]

Retrieves sympy symbol for temperature.

Returns: T : sympy.core.symbol.Symbol SymPy symbol for temperature
get_symbol_for_tr()[source]

Retrieves sympy symbol for reference temperature

Returns: Tr : sympy symbol SymPy symbol for reference temperature
get_symbol_for_v()[source]

Retrieves sympy symbol for volume.

Returns: V : sympy symbol SymPy symbol for volume
get_symbol_for_vr()[source]

Retrieves sympy symbol for reference volume.

Returns: Vr : sympy symbol SymPy symbol for reference volume
set_include_dh_code(include=False)[source]

Set a boolean flag controlling the inclusion code implementing the Debye-Hückel functions.

Parameters: include : boolean True or False
set_reference_origin(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: Tr : float Reference temperature for the model (in Kelvins) Pr : float Reference pressure for the model (in bars) Vr : float Reference volume of the model (in J/bar)
symmetric_index_from_2d_array(elm=(0, 0))[source]

Given a 2D array index, retrieves a 1D symmetric storage index.

Parameters: elm : tuple of int Two element tuple containing the array index Values must be in the range 1 to nc. Index of 1D compact array corresponding to the specified element of the symmetric array
symmetric_index_from_3d_array(elm=(0, 0, 0))[source]

Given a 3D array index, retrieves a 1D symmetric storage index.

Parameters: elm : tuple of int Three element tuple containing the array index Values must be in the range 1 to nc. Index of 1D compact array corresponding to the specified element of the symmetric array
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.

fdiff(argindex=1)[source]

Returns the first derivative of the function.

class coder.B[source]

SymPy Function package extension: Born function.

Definition: $$B = - \frac{1}{\varepsilon }$$, where $$\varepsilon$$ is the dielectric constant of water.

fdiff(argindex=1)[source]

Returns the first derivative of the function.

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}}$$

fdiff(argindex=1)[source]

Returns the first derivative of the function.

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}}$$

fdiff(argindex=1)[source]

Returns the first derivative of the function.

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}}}$$

fdiff(argindex=1)[source]

Returns the first derivative of the function.

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}}$$

fdiff(argindex=1)[source]

Returns the first derivative of the function.

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}}}$$

fdiff(argindex=1)[source]

Returns the first derivative of the function.

class coder.dXdT[source]

SymPy Function package extension: Third partial derivative of the Born function with respect to temperature.

See notes regarding X.

fdiff(argindex=1)[source]

Returns the first derivative of the function.

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.

See notes regarding U.

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.

See notes regarding U. 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.

See notes regarding N.

class coder.dNdP[source]

SymPy Function package extension: Third partial derivative of the Born function with respect to pressure.

See notes regarding N.

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: :math: {A_G} = - 2left( {ln 2} right)RT{A_gamma }

fdiff(argindex=1)[source]

Returns the first derivative of the function.

class coder.AsubH[source]

SymPy Function package extension: Enthalpy equivalent of the Debye-Hückel function Agamma

Definition: :math: {A_H} = {A_G} - T{left( {frac{{partial {A_G}}}{{partial T}}} right)_P} Pressure derivative: :math: frac{{partial {A_H}}}{{partial P}} = frac{{partial {A_G}}}{{partial P}} - Tfrac{{{partial ^2}{A_G}}}{{partial Tpartial P}} or, :math: frac{{partial {A_H}}}{{partial P}} = {A_V} - T{A_{Ex}}

fdiff(argindex=1)[source]

Returns the first derivative of the function.

class coder.AsubJ[source]

SymPy Function package extension: Temperature derivative of AsubH

Definition: :math: {A_J} = {left( {frac{{partial {A_H}}}{{partial T}}} right)_P}

class coder.AsubV[source]

SymPy Function package extension: Pressure derivative of AsubG

Definition: :math: {A_V} = {left( {frac{{partial {A_G}}}{{partial P}}} right)_T}

fdiff(argindex=1)[source]

Returns the first derivative of the function.

class coder.AsubKappa[source]

SymPy Function package extension: Pressure derivative of AsubV

Definition: :math: {A_kappa } = {left( {frac{{partial {A_V}}}{{partial P}}} right)_T}

class coder.AsubEx[source]

SymPy Function package extension: Temperature derivative of AsubV

Definition: :math: {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: :math: {B_G} = - 2left( {ln 2} right)RT{B_gamma }

fdiff(argindex=1)[source]

Returns the first derivative of the function.

class coder.BsubH[source]

SymPy Function package extension: Enthalpy equivalent of the Debye-Hückel function Bgamma

Definition: :math: {B_H} = {B_G} - T{left( {frac{{partial {B_G}}}{{partial T}}} right)_P} Pressure derivative: :math: frac{{partial {B_H}}}{{partial P}} = frac{{partial {B_G}}}{{partial P}} - Tfrac{{{partial ^2}{B_G}}}{{partial Tpartial P}} or, :math: frac{{partial {B_H}}}{{partial P}} = {B_V} - T{B_{Ex}}

fdiff(argindex=1)[source]

Returns the first derivative of the function.

class coder.BsubJ[source]

SymPy Function package extension: Temperature derivative of BsubH

Definition: :math: {B_J} = {left( {frac{{partial {B_H}}}{{partial T}}} right)_P}

class coder.BsubV[source]

SymPy Function package extension: Pressure derivative of BsubG

Definition: :math: {B_V} = {left( {frac{{partial {B_G}}}{{partial P}}} right)_T}

fdiff(argindex=1)[source]

Returns the first derivative of the function.

class coder.BsubKappa[source]

SymPy Function package extension: Pressure derivative of BsubV

Definition: :math: {B_kappa } = {left( {frac{{partial {B_V}}}{{partial P}}} right)_T}

class coder.BsubEx[source]

SymPy Function package extension: Temperature derivative of BsubV

Definition: :math: {B_{Ex} } = {left( {frac{{partial {B_V}}}{{partial T}}} right)_P}

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.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: nc : int Number of thermodynamic components in the solution ns : int Number of ordering parameters in the solution nw : int Number of species in the solution model_type : str 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

 ns (int) Number of ordering parameters in the solution s (sym.Matrix) 1-d matrix of SymPy symbols for the ordering parameters in the model nw (int) Number of species in the solution

Adds an expression and associated parameters to the model.

Parameters: expression : sympy.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. params : an 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_functions : tuple 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 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(phase='Feldspar', params={}, endmembers=[], identifier=None, prefix='cy', module_type='fast', silent=False, language='C', add_code_to_access_order_paramater=False)[source]

Creates include and code file for a model instance.

See documentation for superclass.

Parameters: add_code_to_access_order_paramater : bool Generates additional functions to output values of order parameters as a function of composition, temperature and pressure
create_ordering_code(moles_assign_text, order_assign_text)[source]

Generates ordering function code for a complex solution model.

Parameters: moles_assign_text : str Text string containing C code for assigning moles of each component (n1, n2, …, nc) from a vector of moles, n. order_assign_text : str Text string containing C code for assigning values of each ordering variable (s1, s2, …, ss) from a vactor, s output : str String of code that implements ordering functions and derivatives.

Notes

The user does not normally call this function directly.

create_soln_calc_h_file(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_code_module().

The user does not normally call this function directly.

Parameters: language : string Language syntax for generated code, (“C” is the C99 programming language.) module_type : string 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_soln_calib_h_file(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: language : string Language syntax for generated code, (“C” is the C99 programming language.)
eval_asymmetric_regular_param(nA_val, sA_val, nB_val, sB_val, taylor)[source]

Evaluate 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 parametes 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 parametes for the specified composition of endmember B Must have length ns taylor : str A sympy expression for Taylor expansion of the non-configurational Gibbs free energy interms of the elements of n and s output : str 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(n_val, s_val, taylor)[source]

Evaluate 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 parametes for the specified composition Must have length ns taylor : str A sympy expression for Taylor expansion of the non-configurational Gibbs free energy interms of the elements of n and s output : str A sympy expression for the evaluated Taylor series
eval_regular_param(nA_val, sA_val, nB_val, sB_val, taylor)[source]

Evaluate 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 parametes 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 parametes for the specified composition of endmember B Must have length ns taylor : str A sympy expression for Taylor expansion of the non-configurational Gibbs free energy interms of the elements of n and s output : str 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(nA_val, sA_val, nB_val, sB_val, nC_val, sC_val, taylor)[source]

Evaluate 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 parametes 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 parametes 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 parametes for the specified composition of endmember C Must have length ns taylor : str A sympy expression for Taylor expansion of the non-configurational Gibbs free energy interms of the elements of n and s output : str A sympy expression for the evaluated Taylor series

= G(A/3+B/3+C/3) - G(A)/3 - G(B)/3 - G(C)/3

exchange_indices(i, j, k, var)[source]

Reassigns indices in a derivative tensor to generate dependent entries.

Parameters: i,j,k : int Indices, i <= j <= k, of a tensor derivative var : str Name of tensor output : str 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.

taylor_expansion(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: order : int Order of the Taylor expansion. Second order is the default. The maximum order is 4. mod_type : str ‘convergent’: order parameter expansion only has symmetric terms ‘non-convergent’: order parameter expansion has all terms output : tuple 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_functions : list[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_variables : list[sympy.core.symbol.Symbol] A list of SymPy symbols for the dependent variables, i.e. the ordering parameters or species mole fractions initial_guesses : list[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. bounds : sympy.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

 functions ([sympy.core.symbol.Symbol]) Storage for ordering_functions, described above variables ([sympy.core.symbol.Symbol]) Storage for dep_variables, described above guess ([sympy.core.symbol.Symbol]) Storage for initial_guesses, described above bound (sympy.logic.boolalg.And) Storage for bounds, described above