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/578078py26andpy30backportofpython33slrucache/

pycalphad.core.cache.
cacheit
(user_function)¶

pycalphad.core.cache.
lru_cache
(maxsize=100, typed=False)[source]¶ Leastrecentlyused 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, **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 equallength 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 endmembers. 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/usingnumpytobuildanarrayofallcombinationsoftwoarrays
Parameters:  arrays (list of arraylike) – 1D arrays to form the cartesian product of.
 out (ndarray) – Array to place the cartesian product in.
Returns: out – 2D 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
¶

grad
¶

phase_record
¶

zero_seen
¶

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.eqsolver module¶
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, 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 equallength list (or singlevalued). 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.
 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.InteriorPointSolver.
 callables (dict, optional) – Precomputed 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.
pycalphad.core.halton module¶
The halton module allows the construction of multidimensional scrambled Halton sequences.

pycalphad.core.halton.
halton
(dim, nbpts, primes=None, scramble=True)[source]¶ Generate a multidimensional 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
 result_fractions (ndarray) – Relative amounts of the points making up the hyperplane simplex. Shape of (P,). Will be overwritten. Output sums to 1.
 best_guess_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.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, 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.
 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.patched_piecewise module¶
Copied from Piecewise SymPy. The only modification is in piecewise_eval where
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.phase_rec module¶

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 and CompiledModel. Each PhaseRecord holds a reference to its own Model or CompiledModel; these objects are pickleable. PhaseRecords are immutable after initialization.

composition_matrices
¶

grad
()¶

mass_grad
()¶

mass_obj
()¶

num_sites
¶

obj
()¶

parameters
¶

phase_dof
¶

phase_name
¶

sublattice_dof
¶

vacancy_index
¶

variables
¶


pycalphad.core.phase_rec.
PhaseRecord_from_cython
()¶

pycalphad.core.phase_rec.
PhaseRecord_from_cython_pickle
()¶
pycalphad.core.problem module¶
pycalphad.core.solver module¶

class
pycalphad.core.solver.
InteriorPointSolver
(verbose=False, infeasibility_threshold=0.0001, **ipopt_options)[source]¶ Bases:
pycalphad.core.solver.SolverBase
Standard solver class that uses IPOPT.

verbose
¶ If True, will print solver diagonstics. Defaults to False.
Type: bool

infeasibility_threshold
¶ Dual infeasibility threshold used to tighten constraints and attempt a second solve, if necessary. Defaults to 1e4.
Type: float

ipopt_options
¶ Dictionary of options to pass to IPOPT.
Type: dict

apply_options
(problem)[source] Apply global options to the solver
Parameters: problem (ipopt.problem) – A problem object that will be solved Notes
Strings are encoded to byte strings.

solve
(prob)[source] Solve a nonlinear problem
Parameters: prob (pycalphad.core.problem.Problem) – Returns: Return type: SolverResult


class
pycalphad.core.solver.
SolverBase
[source]¶ Bases:
object
“Base class for solvers.

ignore_convergence
= False¶

solve
(prob)[source]¶ Implement this method. Solve a nonlinear problem
Parameters: prob (pycalphad.core.problem.Problem) – Returns: Return type: pycalphad.core.solver.SolverResult

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.
 list of list of int, optional (vacancy_indices,) – 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.
filter_phases
(dbf, comps)[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 orderdisorder model
Parameters:  dbf (Database) – Thermodynamic database containing the relevant parameters.
 comps (list) – Names of components to consider in the calculation.
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.
make_callable
(model, variables, mode=None)[source]¶ Take a SymPy object and create a callable function.
Parameters:  SymPy object (model,) – Abstract representation of function
 list (variables,) – Input variables, ordered in the way the return function will expect
 ['numpy', 'numba', 'sympy'], optional (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 speedups when calling the energy function many times on multicore 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 quasirandomly 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]¶ Humanreadable string for a number of bytes. http://stackoverflow.com/questions/1094841/reusablelibrarytogethumanreadableversionoffilesize

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 nontuple 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()