pycalphad.core package¶
Submodules¶
pycalphad.core.cache module¶
The cache module handles caching of expensive function calls.
Based on Raymond Hettinger’s backport of lru_cache The difference is _HashedSeq has been modified to use a custom hash function. http://code.activestate.com/recipes/578078-py26-and-py30-backport-of-python-33s-lru-cache/
- pycalphad.core.cache.cacheit(user_function)¶
- pycalphad.core.cache.lru_cache(maxsize=100, typed=False)[source]¶
Least-recently-used cache decorator.
If maxsize is set to None, the LRU features are disabled and the cache can grow without bound.
If typed is True, arguments of different types will be cached separately. For example, f(3.0) and f(3) will be treated as distinct calls with distinct results.
Arguments to the cached function must be hashable.
View the cache statistics named tuple (hits, misses, maxsize, currsize) with f.cache_info(). Clear the cache and statistics with f.cache_clear(). Access the underlying function with f.__wrapped__.
See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
pycalphad.core.calculate module¶
The calculate module contains a routine for calculating the property surface of a system.
- pycalphad.core.calculate.calculate(dbf, comps, phases, mode=None, output='GM', fake_points=False, broadcast=True, parameters=None, to_xarray=True, phase_records=None, **kwargs)[source]¶
Sample the property surface of ‘output’ containing the specified components and phases. Model parameters are taken from ‘dbf’ and any state variables (T, P, etc.) can be specified as keyword arguments.
- Parameters
dbf (Database) – Thermodynamic database containing the relevant parameters.
comps (str or sequence) – Names of components to consider in the calculation.
phases (str or sequence) – Names of phases to consider in the calculation.
mode (string, optional) – See ‘make_callable’ docstring for details.
output (string, optional) – Model attribute to sample.
fake_points (bool, optional (Default: False)) – If True, the first few points of the output surface will be fictitious points used to define an equilibrium hyperplane guaranteed to be above all the other points. This is used for convex hull computations.
broadcast (bool, optional) – If True, broadcast given state variable lists against each other to create a grid. If False, assume state variables are given as equal-length lists.
points (ndarray or a dict of phase names to ndarray, optional) – Columns of ndarrays must be internal degrees of freedom (site fractions), sorted. If this is not specified, points will be generated automatically.
pdens (int, a dict of phase names to int, or a seq of both, optional) – Number of points to sample per degree of freedom. Default: 2000; Default when called from equilibrium(): 500
model (Model, a dict of phase names to Model, or a seq of both, optional) – Model class to use for each phase.
sampler (callable, a dict of phase names to callable, or a seq of both, optional) – Function to sample phase constitution space. Must have same signature as ‘pycalphad.core.utils.point_sample’
grid_points (bool, a dict of phase names to bool, or a seq of both, optional (Default: True)) – Whether to add evenly spaced points between end-members. The density of points is determined by ‘pdens’
parameters (dict, optional) – Maps SymEngine Symbol to numbers, for overriding the values of parameters in the Database.
phase_records (Optional[Mapping[str, PhaseRecord]]) – Mapping of phase names to PhaseRecord objects. Must include all active phases. The model argument must be a mapping of phase names to instances of Model objects. Callers must take care that the PhaseRecord objects were created with the same output as passed to calculate.
- Return type
Dataset of the sampled attribute as a function of state variables
Examples
None yet.
pycalphad.core.cartesian module¶
The cartesian module contains a routine for computing the Cartesian product of N arrays.
- pycalphad.core.cartesian.cartesian(arrays, out=None)[source]¶
Generate a cartesian product of input arrays. Source: http://stackoverflow.com/questions/1208118/using-numpy-to-build-an-array-of-all-combinations-of-two-arrays
- Parameters
arrays (list of array-like) – 1-D arrays to form the cartesian product of.
out (ndarray) – Array to place the cartesian product in.
- Returns
out – 2-D array of shape (M, len(arrays)) containing cartesian products formed of input arrays.
- Return type
ndarray
Examples
>>> cartesian(([1, 2, 3], [4, 5], [6, 7])) array([[1, 4, 6], [1, 4, 7], [1, 5, 6], [1, 5, 7], [2, 4, 6], [2, 4, 7], [2, 5, 6], [2, 5, 7], [3, 4, 6], [3, 4, 7], [3, 5, 6], [3, 5, 7]])
pycalphad.core.composition_set module¶
- class pycalphad.core.composition_set.CompositionSet¶
Bases:
object
This is the primary object the solver interacts with. It keeps the state of a phase (P, T, y…) at a particular solver iteration and can be updated using the update() member function. Every CompositionSet has a reference to a particular PhaseRecord which describes the prototype of the phase. These objects can be created and destroyed by the solver as needed to describe the stable set of phases. Multiple CompositionSets can point to the same PhaseRecord for the case of miscibility gaps. CompositionSets are not pickleable. They are used in miscibility gap deteciton.
- NP¶
- X¶
- dof¶
- energy¶
- fixed¶
- phase_record¶
- update()¶
pycalphad.core.constants module¶
The constants module contains some numerical constants for use in the module. Note that modifying these may yield unpredictable results.
pycalphad.core.constraints module¶
- class pycalphad.core.constraints.ConstraintTuple(internal_cons_func, internal_cons_jac, internal_cons_hess, num_internal_cons)¶
Bases:
tuple
- internal_cons_func¶
Alias for field number 0
- internal_cons_hess¶
Alias for field number 2
- internal_cons_jac¶
Alias for field number 1
- num_internal_cons¶
Alias for field number 3
pycalphad.core.eqsolver module¶
- pycalphad.core.eqsolver.add_nearly_stable()¶
pycalphad.core.equilibrium module¶
The equilibrium module defines routines for interacting with calculated phase equilibria.
- pycalphad.core.equilibrium.equilibrium(dbf, comps, phases, conditions, output=None, model=None, verbose=False, broadcast=True, calc_opts=None, to_xarray=True, scheduler='sync', parameters=None, solver=None, callables=None, phase_records=None, **kwargs)[source]¶
Calculate the equilibrium state of a system containing the specified components and phases, under the specified conditions.
- Parameters
dbf (Database) – Thermodynamic database containing the relevant parameters.
comps (list) – Names of components to consider in the calculation.
phases (list or dict) – Names of phases to consider in the calculation.
conditions (dict or (list of dict)) – StateVariables and their corresponding value.
output (str or list of str, optional) – Additional equilibrium model properties (e.g., CPM, HM, etc.) to compute. These must be defined as attributes in the Model class of each phase.
model (Model, a dict of phase names to Model, or a seq of both, optional) – Model class to use for each phase.
verbose (bool, optional) – Print details of calculations. Useful for debugging.
broadcast (bool) – If True, broadcast conditions against each other. This will compute all combinations. If False, each condition should be an equal-length list (or single-valued). Disabling broadcasting is useful for calculating equilibrium at selected conditions, when those conditions don’t comprise a grid.
calc_opts (dict, optional) – Keyword arguments to pass to calculate, the energy/property calculation routine.
to_xarray (bool) – Whether to return an xarray Dataset (True, default) or an EquilibriumResult.
scheduler (Dask scheduler, optional) – Job scheduler for performing the computation. If None, return a Dask graph of the computation instead of actually doing it.
parameters (dict, optional) – Maps SymEngine Symbol to numbers, for overriding the values of parameters in the Database.
solver (pycalphad.core.solver.SolverBase) – Instance of a solver that is used to calculate local equilibria. Defaults to a pycalphad.core.solver.Solver.
callables (dict, optional) – Pre-computed callable functions for equilibrium calculation.
phase_records (Optional[Mapping[str, PhaseRecord]]) – Mapping of phase names to PhaseRecord objects with ‘GM’ output. Must include all active phases. The model argument must be a mapping of phase names to instances of Model objects.
- Return type
Structured equilibrium calculation, or Dask graph if scheduler=None.
Examples
None yet.
pycalphad.core.errors module¶
- exception pycalphad.core.errors.CalculateError[source]¶
Bases:
Exception
Exception related to use of calculate() function.
- exception pycalphad.core.errors.ConditionError[source]¶
Bases:
pycalphad.core.errors.CalculateError
,pycalphad.core.errors.EquilibriumError
Exception related to calculation conditions.
pycalphad.core.halton module¶
The halton module allows the construction of multi-dimensional scrambled Halton sequences.
- pycalphad.core.halton.halton(dim, nbpts, primes=None, scramble=True)[source]¶
Generate a multi-dimensional Halton sequence.
- Parameters
dim (int) – Number of dimensions in the sequence.
nbpts (int) – Number of points along each dimension.
primes (sequence, optional) – A sequence of at least ‘dim’ prime numbers.
scramble (boolean, optional (default: True)) –
- Return type
ndarray of shape (nbpts, dim)
pycalphad.core.hyperplane module¶
- pycalphad.core.hyperplane.hyperplane()¶
Find chemical potentials which approximate the tangent hyperplane at the given composition.
- Parameters
compositions (ndarray) – A sample of the energy surface of the system. Aligns with ‘energies’. Shape of (M, N)
energies (ndarray) – A sample of the energy surface of the system. Aligns with ‘compositions’. Shape of (M,)
composition (ndarray) – Target composition for the hyperplane. Shape of (N,)
chemical_potentials (ndarray) – Shape of (N,) Will be overwritten
total_moles (double) – Total number of moles in the system.
fixed_chempot_indices (ndarray) – Variable shape from (0,) to (N-1,)
fixed_comp_indices (ndarray) – Variable shape from (0,) to (N-1,)
result_fractions (ndarray) – Relative amounts of the points making up the hyperplane simplex. Shape of (P,). Will be overwritten. Output sums to 1.
result_simplex (ndarray) – Energies of the points making up the hyperplane simplex. Shape of (P,). Will be overwritten. Output*result_fractions sums to out_energy (return value).
- Returns
out_energy – Energy of the output configuration.
- Return type
double
Examples
None yet.
Notes
M: number of energy points that have been sampled N: number of components P: N+1, max phases by gibbs phase rule that we can find in a point calculations
pycalphad.core.light_dataset module¶
Defines a class for internally representing arrays used in equilibrium calculations
- class pycalphad.core.light_dataset.LightDataset(data_vars=None, coords=None, attrs=None)[source]¶
Bases:
object
Lightweight wrapper around an xarray Dataset.
- data_vars¶
- Type
dict
- coords¶
- Type
dict
- attrs¶
- Type
dict
Notes
The idea of LightDataset is to provide the same constructor API as Dataset objects, but doesn’t provide any sel or other functionality. Calls to getitem or getattr to get a DataArray from xarray Datasets can take ~1ms or more, which is problematic when the equilibrium solver operates on the order of a few tens of ms and xarray Datasets are in the core loop.
This class provides a similar getattr API to accessing data variables and “wraps” xarray Datasets in the sense that any LightDataset can be converted to an xarray Dataset by the getdataset method.
pycalphad.core.lower_convex_hull module¶
The lower_convex_hull module handles geometric calculations associated with equilibrium calculation.
- pycalphad.core.lower_convex_hull.lower_convex_hull(global_grid, state_variables, result_array)[source]¶
Find the simplices on the lower convex hull satisfying the specified conditions in the result array.
- Parameters
global_grid (Dataset) – A sample of the energy surface of the system.
state_variables (List[v.StateVariable]) – A list of the state variables (e.g., P, T) used in this calculation.
result_array (Dataset) – This object will be modified! Coordinates correspond to conditions axes.
- Return type
None. Results are written to result_array.
Notes
This routine will not check if any simplex is degenerate. Degenerate simplices will manifest with duplicate or NaN indices.
Examples
None yet.
pycalphad.core.minimizer module¶
- class pycalphad.core.minimizer.CompsetState¶
Bases:
object
- class pycalphad.core.minimizer.SystemSpecification¶
Bases:
object
- check_convergence()¶
- get_new_state()¶
- post_solve_hook()¶
- pre_solve_hook()¶
- run_loop()¶
- pycalphad.core.minimizer.advance_state()¶
- pycalphad.core.minimizer.construct_equilibrium_system()¶
- pycalphad.core.minimizer.solve_state()¶
pycalphad.core.phase_rec module¶
- class pycalphad.core.phase_rec.FastFunction¶
Bases:
object
FastFunction
provides a stable(-ish) interface that encapsulates SymEngine function pointers.
- class pycalphad.core.phase_rec.PhaseRecord¶
Bases:
object
This object exposes a common API to the solver so it doesn’t need to know about the differences between Model implementations. PhaseRecords are immutable after initialization.
- components¶
- formulagfunc_¶
- formulagrad()¶
- formulahess()¶
- formulahfunc_¶
- formulamole_grad()¶
- formulamole_hess()¶
- formulamole_obj()¶
- formulamolefuncs_¶
- formulamolegradfuncs_¶
- formulamolehessianfuncs_¶
- formulaobj()¶
- formulaofunc_¶
- internal_cons_func()¶
- internal_cons_func_¶
- internal_cons_hess()¶
- internal_cons_hess_¶
- internal_cons_jac()¶
- internal_cons_jac_¶
- mass_obj()¶
- mass_obj_2d()¶
- massfuncs_¶
- nonvacant_elements¶
- num_internal_cons¶
- num_statevars¶
- obj()¶
- obj_2d()¶
- obj_parameters_2d()¶
Calculate objective function using custom parameters. Note dof and parameters are vectorized separately, i.e., broadcast against each other. Let dof.shape[0] = M and parameters.shape[0] = N Then outp.shape = (M,N)
- ofunc_¶
- parameters¶
- phase_dof¶
- phase_name¶
- pure_elements¶
- state_variables¶
- variables¶
pycalphad.core.solver module¶
- class pycalphad.core.solver.Solver(verbose=False, remove_metastable=True, **options)[source]¶
Bases:
pycalphad.core.solver.SolverBase
- get_system_spec(composition_sets, conditions)[source]¶
Create a SystemSpecification object for the specified conditions.
- Parameters
composition_sets (List[pycalphad.core.composition_set.CompositionSet]) – List of CompositionSet objects in the starting point. Modified in place.
conditions (OrderedDict[str, float]) – Conditions to satisfy.
- Return type
- solve(composition_sets, conditions)[source]¶
Minimize the energy under the specified conditions using the given candidate composition sets.
- Parameters
composition_sets (List[pycalphad.core.composition_set.CompositionSet]) – List of CompositionSet objects in the starting point. Modified in place.
conditions (OrderedDict[str, float]) – Conditions to satisfy.
- Return type
- class pycalphad.core.solver.SolverBase[source]¶
Bases:
object
“Base class for solvers.
- ignore_convergence = False¶
- solve(composition_sets, conditions)[source]¶
Implement this method. Minimize the energy under the specified conditions using the given candidate composition sets.
- Parameters
composition_sets (List[pycalphad.core.composition_set.CompositionSet]) – List of CompositionSet objects in the starting point. Modified in place.
conditions (OrderedDict[str, float]) – Conditions to satisfy.
- Return type
pycalphad.core.starting_point module¶
- pycalphad.core.starting_point.global_min_is_possible(conditions, state_variables)[source]¶
Determine whether global minimization is possible to perform under the given set of conditions. Global minimization is possible when only T, P, N, compositions and/or chemical potentials are specified, but may not be possible with other conditions because there may be multiple (or zero) solutions.
- Parameters
conditions (dict) –
state_variables (iterable of StateVariables) –
- Return type
bool
- pycalphad.core.starting_point.starting_point(conditions, state_variables, phase_records, grid)[source]¶
Find a starting point for the solution using a sample of the system energy surface.
- Parameters
conditions (OrderedDict) – Mapping of StateVariable to array of condition values.
state_variables (list) – A list of the state variables (e.g., N, P, T) used in this calculation.
phase_records (dict) – Mapping of phase names (strings) to PhaseRecords.
grid (Dataset) – A sample of the energy surface of the system. The sample should at least cover the same state variable space as specified in the conditions.
- Return type
Dataset
pycalphad.core.utils module¶
The utils module handles helper routines for equilibrium calculation.
- pycalphad.core.utils.canonical_sort_key(x)[source]¶
Wrap strings in tuples so they’ll sort.
- Parameters
x (list) – List of strings to sort
- Returns
tuple of strings that can be sorted
- Return type
tuple
- pycalphad.core.utils.endmember_matrix(dof, vacancy_indices=None)[source]¶
Accept the number of components in each sublattice. Return a matrix corresponding to the compositions of all endmembers.
- Parameters
dof (list of int) – Number of components in each sublattice.
vacancy_indices – If vacancies are present in every sublattice, specify their indices in each sublattice to ensure the “pure vacancy” endmembers are excluded.
int (list of list of) – If vacancies are present in every sublattice, specify their indices in each sublattice to ensure the “pure vacancy” endmembers are excluded.
optional – If vacancies are present in every sublattice, specify their indices in each sublattice to ensure the “pure vacancy” endmembers are excluded.
Examples
Sublattice configuration like: (AL, NI, VA):(AL, NI, VA):(VA) >>> endmember_matrix([3,3,1], vacancy_indices=[[2], [2], [0]])
- pycalphad.core.utils.extract_parameters(parameters)[source]¶
Extract symbols and values from parameters.
- Parameters
parameters (dict) – Dictionary of parameters
- Returns
Tuple of parameter symbols (list) and parameter values (parameter_array_length, # parameters)
- Return type
tuple
- pycalphad.core.utils.filter_phases(dbf, comps, candidate_phases=None)[source]¶
Return phases that are valid for equilibrium calculations for the given database and components
Filters out phases that * Have no active components in any sublattice of a phase * Are disordered phases in an order-disorder model
- Parameters
dbf (Database) – Thermodynamic database containing the relevant parameters.
comps (list of v.Species) – Species to consider in the calculation.
candidate_phases (list) – Names of phases to consider in the calculation, if not passed all phases from DBF will be considered
- Returns
Sorted list of phases that are valid for the Database and components
- Return type
list
- pycalphad.core.utils.generate_dof(phase, active_comps)[source]¶
Accept a Phase object and a set() of the active components. Return a tuple of variable names and the sublattice degrees of freedom.
- pycalphad.core.utils.generate_symmetric_group(configuration, symmetry)[source]¶
For a particular configuration and list of sublattices that are symmetric, generate all the symmetrically equivalent configurations.
- Parameters
configuration (Sequence[Any]) – Typically a constituent array. The length should correspond to the number of sublattices in the phase.
symmetry (Union[None, Sequence[Sequence[int]]]) – A list of lists giving the indices of symmetrically equivalent sublattices. For example: a symmetry of [[0, 1, 2, 3]] means that the first four sublattices are symmetric to each other. If multiple sublattices are given, the sublattices are internally equivalent and the sublattices themselves are assumed interchangeble. That is, for a symmetry of [[0, 1], [2, 3]], sublattices 0 and 1 are equivalent to each other (i.e. [0, 1] == [1, 0]) and similarly for sublattices 2 and 3. It also implies that the sublattices are interchangeable, (i.e. [[0, 1], [2, 3]] == [[2, 3], [0, 1]]), but note that constituents cannot change sublattices (i.e. [[0, 1], [2, 3]] != [[0, 3], [2, 1]]). If symmetry=None is given, no new configurations are generated.
- Returns
Tuple of configuration tuples that are all symmetrically equivalent.
- Return type
tuple
Notes
In the general case, equivalency between sublattices, for example ([[0, 1], [2, 3]] == [[2, 3], [0, 1]]), is not necessarily required. It could be that sublattices 0 and 1 represent equivalent substitutional sublattices, while 2 and 3 represent equivalent interstitial sites. Interchanging sublattices between substitutional sublattices is allowed, but the substitutional sites would not be interchangeable with the interstitial sites. To achieve this kind of effect with this function, you would need to call it once with the equivalent substitutional sublattices, then for each generated configuration, call this function again, giving the unique configurations for symmetric interstitial sublattices.
- pycalphad.core.utils.get_pure_elements(dbf, comps)[source]¶
Return a list of pure elements in the system.
- Parameters
dbf (Database) – A Database object
comps (list) – A list of component names (species and pure elements)
- Returns
A list of pure elements in the Database
- Return type
list
- pycalphad.core.utils.get_state_variables(models=None, conds=None)[source]¶
Return a set of StateVariables defined Model instances and/or conditions.
- Parameters
models (dict, optional) – Dictionary mapping phase names to instances of Model objects
conds (Iterable[v.StateVariable]) – An iterable of StateVariables or a dictionary mapping pycalphad StateVariables to values
- Returns
State variables that are defined in the models and or conditions.
- Return type
set
Examples
>>> from pycalphad import variables as v >>> from pycalphad.core.utils import get_state_variables >>> get_state_variables(conds={v.P: 101325, v.N: 1, v.X('AL'): 0.2}) == {v.P, v.N, v.T} True
- pycalphad.core.utils.instantiate_models(dbf, comps, phases, model=None, parameters=None, symbols_only=True)[source]¶
- Parameters
dbf (Database) – Database used to construct the Model instances.
comps (Iterable) – Names of components to consider in the calculation.
phases (Iterable) – Names of phases to consider in the calculation.
model (Model class, a dict of phase names to Model, or a Iterable of both) – Model class to use for each phase.
parameters (dict, optional) – Maps SymEngine Symbol to numbers, for overriding the values of parameters in the Database.
symbols_only (bool) – If True, symbols will be extracted from the parameters dict and used to construct the Model instances.
- Returns
Dictionary of Model instances corresponding to the passed phases.
- Return type
dict
- pycalphad.core.utils.point_sample(comp_count, pdof=10)[source]¶
Sample ‘pdof * (sum(comp_count) - len(comp_count))’ points in composition space for the sublattice configuration specified by ‘comp_count’. Points are sampled quasi-randomly from a Halton sequence. A Halton sequence is like a uniform random distribution, but the result will always be the same for a given ‘comp_count’ and ‘pdof’. Note: For systems with only one component, only one point will be returned, regardless of ‘pdof’. This is because the degrees of freedom are zero for that case.
- Parameters
comp_count (list) – Number of components in each sublattice.
pdof (int) – Number of points to sample per degree of freedom.
- Return type
ndarray of generated points satisfying the mass balance.
Examples
>>> comps = [8,1] # 8 components in sublattice 1; only 1 in sublattice 2 >>> pts = point_sample(comps, pdof=20) # 7 d.o.f, returns a 140x7 ndarray
- pycalphad.core.utils.sizeof_fmt(num, suffix='B')[source]¶
Human-readable string for a number of bytes. http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
- pycalphad.core.utils.unpack_components(dbf, comps)[source]¶
- Parameters
dbf (Database) – Thermodynamic database containing elements and species.
comps (list) – Names of components to consider in the calculation.
- Returns
Set of Species objects
- Return type
set
- pycalphad.core.utils.unpack_condition(tup)[source]¶
Convert a condition to a list of values.
Notes
Rules for keys of conditions dicts: (1) If it’s numeric, treat as a point value (2) If it’s a tuple with one element, treat as a point value (3) If it’s a tuple with two elements, treat as lower/upper limits and guess a step size. (4) If it’s a tuple with three elements, treat as lower/upper/step (5) If it’s a list, ndarray or other non-tuple ordered iterable, use those values directly.
- pycalphad.core.utils.unpack_kwarg(kwarg_obj, default_arg=None)[source]¶
Keyword arguments in pycalphad can be passed as a constant value, a dict of phase names and values, or a list containing both of these. If the latter, then the dict is checked first; if the phase of interest is not there, then the constant value is used.
This function is a way to construct defaultdicts out of keyword arguments.
- Parameters
kwarg_obj (dict, iterable, or None) – Argument to unpack into a defaultdict
default_arg (object) – Default value to use if iterable isn’t specified
- Return type
defaultdict for the keyword argument of interest
Examples
>>> test_func = lambda **kwargs: print(unpack_kwarg('opt')) >>> test_func(opt=100) >>> test_func(opt={'FCC_A1': 50, 'BCC_B2': 10}) >>> test_func(opt=[{'FCC_A1': 30}, 200]) >>> test_func() >>> test_func2 = lambda **kwargs: print(unpack_kwarg('opt', default_arg=1)) >>> test_func2()