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.fhash(thing)[source]

Compute a hash of an object. Works on dicts and lists.

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, **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 SymPy Symbol to numbers, for overriding the values of parameters in the Database.

Returns

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.constraints.build_constraints(mod, variables, parameters=None)[source]

pycalphad.core.eqsolver module

pycalphad.core.eqsolver.solve_and_update()

solve_and_update(composition_sets, conditions, solver, remove_metastable=True)

Use the solver to find a solution satisfying the conditions from the starting point given by the composition sets.

Parameters
  • composition_sets (List[CompositionSet]) –

  • conditions (OrderedDict[str, float]) –

  • solver (pycalphad.core.solver.SolverBase) –

  • remove_metastable (Optional[bool]) – If True (the default), remove metastable compsets from the compositions_sets.

pycalphad.core.eqsolver.update_composition_sets()

update_composition_sets(composition_sets, solver_result, remove_metastable=True)

Parameters

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, **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 SymPy 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.

Returns

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.

exception pycalphad.core.errors.DofError[source]

Bases: Exception

Error due to missing degrees of freedom.

exception pycalphad.core.errors.EquilibriumError[source]

Bases: Exception

Exception related to calculation of equilibrium.

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)) –

Returns

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. :param compositions: A sample of the energy surface of the system.

Aligns with ‘energies’. Shape of (M, N)

Parameters
  • 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.

add_variable(var, coord, value)[source]
get_dataset()[source]

Build an xarray Dataset

merge(other, inplace=False, compat='no_conflicts')[source]
remove(item)[source]

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.

Returns

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

class pycalphad.core.minimizer.SystemState

Bases: object

pycalphad.core.minimizer.check_convergence_and_change_phases()
pycalphad.core.minimizer.find_solution()
pycalphad.core.minimizer.take_step()

pycalphad.core.patched_piecewise module

Copied from Piecewise SymPy. The only modification is in piecewise_eval where

```
for e, c in _args:
if not c.is_Atom and not isinstance(c, Relational):

free = c.free_symbols

```

is changed to

```
for e, c in _args:
if not c.is_Atom and not isinstance(c, Relational):

free = c.expr_free_symbols

```

See the following links: https://github.com/sympy/sympy/issues/14933 https://github.com/pycalphad/pycalphad/pull/180

pycalphad.core.patched_piecewise.exprcondpair_new(cls, expr, cond)[source]
pycalphad.core.patched_piecewise.piecewise_eval(cls, *_args)[source]

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, **options)[source]

Bases: pycalphad.core.solver.SolverBase

solve(composition_sets, conditions)[source]

Minimize the energy under the specified conditions using the given candidate composition sets.

Parameters
Returns

Return type

SolverResult

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
Returns

Return type

pycalphad.core.solver.SolverResult

class pycalphad.core.solver.SolverResult(converged, x, chemical_potentials)

Bases: tuple

chemical_potentials

Alias for field number 2

converged

Alias for field number 0

x

Alias for field number 1

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) –

Returns

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.

Returns

Return type

Dataset

pycalphad.core.utils module

The utils module handles helper routines for equilibrium calculation.

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.

  • of list of int (list) – 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.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 (dict, optional) – 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 SymPy 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.make_callable(model, variables, mode=None)[source]

Take a SymPy object and create a callable function.

Parameters
  • model – Abstract representation of function

  • object (SymPy) – Abstract representation of function

  • variables – Input variables, ordered in the way the return function will expect

  • list – Input variables, ordered in the way the return function will expect

  • mode – Method to use when ‘compiling’ the function. SymPy mode is slow and should only be used for debugging. If Numba is installed, it can offer speed-ups when calling the energy function many times on multi-core CPUs.

  • ['numpy' – Method to use when ‘compiling’ the function. SymPy mode is slow and should only be used for debugging. If Numba is installed, it can offer speed-ups when calling the energy function many times on multi-core CPUs.

  • 'numba' – Method to use when ‘compiling’ the function. SymPy mode is slow and should only be used for debugging. If Numba is installed, it can offer speed-ups when calling the energy function many times on multi-core CPUs.

  • 'sympy'] – Method to use when ‘compiling’ the function. SymPy mode is slow and should only be used for debugging. If Numba is installed, it can offer speed-ups when calling the energy function many times on multi-core CPUs.

  • optional – Method to use when ‘compiling’ the function. SymPy mode is slow and should only be used for debugging. If Numba is installed, it can offer speed-ups when calling the energy function many times on multi-core CPUs.

Returns

  • Function that takes arguments in the same order as ‘variables’

  • and returns the energy according to ‘model’.

Examples

None yet.

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.

Returns

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

Returns

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()
pycalphad.core.utils.unpack_phases(phases)[source]

Convert a phases list/dict into a sorted list.

pycalphad.core.utils.wrap_symbol(obj)[source]
pycalphad.core.utils.wrap_symbol_symengine(obj)[source]

Module contents