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, conditions=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.
conditions (OrderedDict) – Mapping of StateVariables to conditions. Must contain state variables and phase-local conditions only.
- Return type:
Dataset of the sampled attribute as a function of state variables
Examples
None yet.
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¶
- num_phase_local_conditions¶
- phase_record¶
- set_local_conditions(phase_local_conditions)¶
- update(site_fracs, phase_amt, state_variables)¶
pycalphad.core.conditions module¶
- class pycalphad.core.conditions.Conditions(wks: Workspace | None)[source]¶
Bases:
object
- classmethod cast_from(key) Conditions [source]¶
- minimum_composition: float = 1e-10¶
- class pycalphad.core.conditions.ConditionsEntry(prop, value)[source]¶
Bases:
NamedTuple
- prop: ComputableProperty¶
Alias for field number 0
- value: Q_¶
Alias for field number 1
- pycalphad.core.conditions.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.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(composition_sets, phase_records, grid, current_idx, chemical_potentials, state_variables, minimum_df, verbose)¶
- pycalphad.core.eqsolver.add_new_phases(composition_sets, removed_compsets, phase_records, grid, current_idx, chemical_potentials, state_variables, minimum_df, verbose)¶
Attempt to add a new phase with the largest driving force (based on chemical potentials). Candidate phases are taken from current_grid and modify the composition_sets object. The function returns a boolean indicating whether it modified composition_sets.
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, calc_opts=None, to_xarray=True, parameters=None, solver=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.
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.
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.
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
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:
CalculateError
,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(compositions, energies, chemical_potentials, fixed_chempot_indices, fixed_lincomb_molefrac_coefs, fixed_lincomb_molefrac_rhs, result_fractions, result_simplex)¶
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,)
chemical_potentials (ndarray) – Shape of (N,) Will be overwritten
fixed_chempot_indices (ndarray) – Variable shape from (0,) to (N-1,)
fixed_lincomb_molefrac_coefs (ndarray) – Variable shape from (0,P) to (N-1, P)
fixed_lincomb_molefrac_rhs (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.hyperplane.hyperplane_coefficients(compositions, fixed_chempot_indices, trial_simplex, out_plane_coefs)¶
- pycalphad.core.hyperplane.intersecting_point(compositions, fixed_chempot_indices, trial_simplex, fixed_lincomb_molefrac_coefs, fixed_lincomb_molefrac_rhs, out_intersecting_point)¶
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, conds_keys, phase_record_factory, 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.
conds_keys (List) – A list of the keys of the conditions used in this calculation.
phase_record_factory (PhaseRecordFactory) – PhaseRecordFactory object corresponding to 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(state)¶
- get_new_state(compsets)¶
- post_solve_hook(state)¶
- pre_solve_hook(state)¶
- run_loop(state, max_iterations)¶
- class pycalphad.core.minimizer.SystemState¶
Bases:
object
- chemical_potentials¶
- compsets¶
- cs_states¶
- iteration¶
- recompute(spec)¶
- pycalphad.core.minimizer.advance_state(spec, state, equilibrium_soln, step_size)¶
- pycalphad.core.minimizer.chemical_potential_differential(spec, state, target_component_index)¶
- pycalphad.core.minimizer.construct_equilibrium_system(spec, state, num_reserved_rows)¶
- pycalphad.core.minimizer.fixed_component_differential(spec, state, target_component_index)¶
- pycalphad.core.minimizer.lstsq_check_infeasible(A, b, out_x)¶
- pycalphad.core.minimizer.site_fraction_differential(csst, delta_chempots, delta_statevars)¶
- pycalphad.core.minimizer.solve_state(spec, state)¶
- pycalphad.core.minimizer.state_variable_differential(spec, state, target_statevar_index)¶
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.FastFunctionFactory¶
Bases:
object
- get_cons_func()¶
- get_cons_hess()¶
- get_cons_jac()¶
- get_cons_len()¶
- get_mole_formula_func(element_name)¶
- get_mole_formula_grad(element_name)¶
- get_mole_formula_hess(element_name)¶
- get_mole_fraction_func(element_name)¶
- get_mole_fraction_grad(element_name)¶
- get_mole_fraction_hess(element_name)¶
- 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¶
- formulagrad(out, dof)¶
- formulahess(out, dof)¶
- formulamole_grad(out, dof, comp_idx)¶
- formulamole_hess(out, dof, comp_idx)¶
- formulamole_obj(out, dof, comp_idx)¶
- formulaobj(outp, dof)¶
- function_factory¶
- internal_cons_func(out, dof)¶
- internal_cons_hess(out, dof)¶
- internal_cons_jac(out, dof)¶
- mass_obj(out, dof, comp_idx)¶
- mass_obj_2d(out, dof, comp_idx)¶
- molar_masses¶
- nonvacant_elements¶
- num_internal_cons¶
- num_statevars¶
- obj(outp, dof)¶
- obj_2d(outp, dof)¶
- obj_parameters_2d(outp, dof, parameters)¶
- parameters¶
- phase_dof¶
- phase_local_cons_func(out, dof, func)¶
- phase_local_cons_jac(out, dof, jac_func)¶
- phase_name¶
- phase_record_factory¶
- prop(outp, dof, property_name)¶
- prop_2d(outp, dof, property_name)¶
- prop_grad(out, dof, property_name)¶
- prop_parameters_2d(outp, dof, parameters, property_name)¶
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)
- pure_elements¶
- state_variables¶
- variables¶
pycalphad.core.polytope module¶
This module provides functions to uniformly sample points subject to a system of linear inequality constraints, \(Ax <= b\) (convex polytope), and linear equality constraints, \(Ax = b\) (affine projection).
A comparison of MCMC algorithms to generate uniform samples over a convex polytope is given in [Chen2018]. Here, we use the Hit & Run algorithm described in [Smith1984]. The R-package hitandrun provides similar functionality to this module.
Based on https://github.com/DavidWalz/polytope-sampling Used under the terms of the MIT license. License information can be found in the pycalphad LICENSE.txt.
References
Chen Y., Dwivedi, R., Wainwright, M., Yu B. (2018) Fast MCMC Sampling Algorithms on Polytopes. JMLR, 19(55):1−86 https://arxiv.org/abs/1710.08165
Smith, R. (1984). Efficient Monte Carlo Procedures for Generating Points Uniformly Distributed Over Bounded Regions. Operations Research, 32(6), 1296-1308. www.jstor.org/stable/170949
- pycalphad.core.polytope.affine_subspace(A, b)[source]¶
Compute a basis of the nullspace of A, and a particular solution to Ax = b. This allows to to construct arbitrary solutions as the sum of any vector in the nullspace, plus the particular solution.
- Parameters:
A (2d-array of shape (n_constraints, dimension)) – Left-hand-side of Ax <= b.
b (1d-array of shape (n_constraints)) – Right-hand-side of Ax <= b.
- Returns:
N (2d-array of shape (dimension, dimension)) – Orthonormal basis of the nullspace of A.
xp (1d-array of shape (dimension)) – Particular solution to Ax = b.
- pycalphad.core.polytope.chebyshev_center(A, b)[source]¶
Find the center of the polytope Ax <= b.
- Parameters:
A (2d-array of shape (n_constraints, dimension)) – Left-hand-side of Ax <= b.
b (1d-array of shape (n_constraints)) – Right-hand-side of Ax <= b.
- Returns:
Chebyshev center of the polytope
- Return type:
1d-array of shape (dimension)
- pycalphad.core.polytope.check_Ab(A, b)[source]¶
Check if matrix equation Ax=b is well defined.
- Parameters:
A (2d-array of shape (n_constraints, dimension)) – Left-hand-side of Ax <= b.
b (1d-array of shape (n_constraints)) – Right-hand-side of Ax <= b.
- pycalphad.core.polytope.constraints_from_bounds(lower, upper)[source]¶
Construct the inequality constraints Ax <= b that correspond to the given lower and upper bounds.
- Parameters:
lower (array-like) – lower bound in each dimension
upper (array-like) – upper bound in each dimension
- Returns:
A (2d-array of shape (2 * dimension, dimension)) – Left-hand-side of Ax <= b.
b (1d-array of shape (2 * dimension)) – Right-hand-side of Ax <= b.
- pycalphad.core.polytope.sample(n_points, lower, upper, A1=None, b1=None, A2=None, b2=None)[source]¶
Sample a number of points from a convex polytope A1 x <= b1 using the Hit & Run algorithm.
Lower and upper bounds need to be provided to ensure that the polytope is bounded. Equality constraints A2 x = b2 may be optionally provided.
- Parameters:
n_points (int) – Number of samples to generate.
lower (1d-array of shape (dimension)) – Lower bound in each dimension. If not wanted set to -np.inf.
upper (1d-array of shape (dimension)) – Upper bound in each dimension. If not wanted set to np.inf.
A1 (2d-array of shape (n_constraints, dimension)) – Left-hand-side of A1 x <= b1.
b1 (1d-array of shape (n_constraints)) – Right-hand-side of A1 x <= b1.
A2 (2d-array of shape (n_constraints, dimensions), optional) – Left-hand-side of A2 x = b2.
b2 (1d-array of shape (n_constraints), optional) – Right-hand-side of A2 x = b2.
- Returns:
Points sampled from the polytope.
- Return type:
2d-array of shape (n_points)
pycalphad.core.solver module¶
- class pycalphad.core.solver.Solver(verbose=False, remove_metastable=True, **options)[source]¶
Bases:
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[StateVariable, 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_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()
pycalphad.core.workspace module¶
- class pycalphad.core.workspace.ComponentList[source]¶
Bases:
object
- classmethod cast_from(s: Sequence[(<class 'str'>+<class 'pycalphad.variables.Component'>)]) ComponentList [source]¶
- class pycalphad.core.workspace.ComponentsField(depends_on=None)[source]¶
Bases:
TypedField
- class pycalphad.core.workspace.ConditionKey[source]¶
Bases:
object
- classmethod cast_from(key: (<class 'str'>+<class 'pycalphad.variables.StateVariable'>)) ConditionKey [source]¶
- class pycalphad.core.workspace.ConditionValue[source]¶
Bases:
object
- classmethod cast_from(value: (Sequence[<class 'float'>]+<class 'float'>)) ConditionValue [source]¶
- class pycalphad.core.workspace.ConditionsField(default_factory=None, depends_on=None)[source]¶
Bases:
DictField
- class pycalphad.core.workspace.ConstituentsField(depends_on=None)[source]¶
Bases:
TypedField
- class pycalphad.core.workspace.ConstituentsList[source]¶
Bases:
object
- classmethod cast_from(s: Sequence[Any]) ConstituentsList [source]¶
- class pycalphad.core.workspace.DictField(default_factory=None, depends_on=None)[source]¶
Bases:
TypedField
- class pycalphad.core.workspace.EquilibriumCalculationField(default_factory=None, depends_on=None)[source]¶
Bases:
TypedField
- class pycalphad.core.workspace.PRFField(depends_on=None)[source]¶
Bases:
TypedField
- class pycalphad.core.workspace.PhasesField(depends_on=None)[source]¶
Bases:
TypedField
- class pycalphad.core.workspace.SolverField(default_factory=None, depends_on=None)[source]¶
Bases:
TypedField
- class pycalphad.core.workspace.TypedField(default_factory=None, depends_on=None)[source]¶
Bases:
object
A descriptor for managing attributes with specific types in a class, supporting automatic type coercion and default values. This class is designed to be used in scenarios (like Workspace) where one needs to implement an observer pattern. It enables the tracking of changes in attribute values and notifies dependent attributes of any updates.
- class pycalphad.core.workspace.Workspace(*args, **kwargs)[source]¶
Bases:
object
- calc_opts: (dict[(Any*Any)]+Literal[None])¶
- components: ComponentList¶
- property condition_axis_order¶
- conditions: Conditions¶
- constituents: ConstituentsList¶
- database: Database¶
A descriptor for managing attributes with specific types in a class, supporting automatic type coercion and default values. This class is designed to be used in scenarios (like Workspace) where one needs to implement an observer pattern. It enables the tracking of changes in attribute values and notifies dependent attributes of any updates.
- eq: LightDataset | None¶
- get(*args: Tuple[ComputableProperty])[source]¶
- get_dict(*args: Tuple[ComputableProperty])[source]¶
- models: Mapping[(PhaseName*Any)]¶
- property ndim: int¶
- parameters: (dict[(Any*Any)]+Literal[None])¶
- phase_record_factory: PhaseRecordFactory | None¶
- solver: SolverBase¶
- verbose: bool¶
A descriptor for managing attributes with specific types in a class, supporting automatic type coercion and default values. This class is designed to be used in scenarios (like Workspace) where one needs to implement an observer pattern. It enables the tracking of changes in attribute values and notifies dependent attributes of any updates.