Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
property_output = output.split('_')[0] # property without _FORM, _MIX, etc.
samples = np.array(data['values']).flatten()
reference = data.get('reference', '')
# Models are now modified in response to the data from this data
if 'reference_states' in data:
property_output = output[:-1] if output.endswith('R') else output # unreferenced model property so we can tell shift_reference_state what to build.
reference_states = []
for el, vals in data['reference_states'].items():
reference_states.append(ReferenceState(v.Species(el), vals['phase'], fixed_statevars=vals.get('fixed_state_variables')))
for mod in models.values():
mod.shift_reference_state(reference_states, dbf, output=(property_output,))
data['conditions'].setdefault('N', 1.0) # Add default for N. Nothing else is supported in pycalphad anyway.
pot_conds = OrderedDict([(getattr(v, key), unpack_condition(data['conditions'][key])) for key in sorted(data['conditions'].keys()) if not key.startswith('X_')])
comp_conds = OrderedDict([(v.X(key[2:]), unpack_condition(data['conditions'][key])) for key in sorted(data['conditions'].keys()) if key.startswith('X_')])
phase_records = build_phase_records(dbf, species, data_phases, {**pot_conds, **comp_conds}, models, parameters=parameters, build_gradients=True, build_hessians=True)
# Now we need to unravel the composition conditions
# (from Dict[v.X, Sequence[float]] to Sequence[Dict[v.X, float]]), since the
# composition conditions are only broadcast against the potentials, not
# each other. Each individual composition needs to be computed
# independently, since broadcasting over composition cannot be turned off
# in pycalphad.
rav_comp_conds = [OrderedDict(zip(comp_conds.keys(), pt_comps)) for pt_comps in zip(*comp_conds.values())]
# Build weights, should be the same size as the values
total_num_calculations = len(rav_comp_conds)*np.prod([len(vals) for vals in pot_conds.values()])
dataset_weights = np.array(data.get('weight', 1.0)) * np.ones(total_num_calculations)
weights = (property_std_deviation.get(property_output, 1.0)/data_weight_dict.get(property_output, 1.0)/dataset_weights).flatten()
def _adjust_conditions(conds):
"Adjust conditions values to be within the numerical limit of the solver."
new_conds = OrderedDict()
for key, value in sorted(conds.items(), key=str):
if isinstance(key, v.Composition):
new_conds[key] = [max(val, MIN_SITE_FRACTION*1000) for val in unpack_condition(value)]
else:
new_conds[key] = unpack_condition(value)
return new_conds
def _adjust_conditions(conds):
"Adjust conditions values to be within the numerical limit of the solver."
new_conds = OrderedDict()
for key, value in sorted(conds.items(), key=str):
if key == str(key):
key = getattr(v, key, key)
if isinstance(key, v.Composition):
new_conds[key] = [max(val, MIN_SITE_FRACTION*1000) for val in unpack_condition(value)]
else:
new_conds[key] = unpack_condition(value)
return new_conds
comp_cond = [k for k in conds.keys() if isinstance(k, v.X)][0]
indep_comp = comp_cond.name[2:]
indep_comp_idx = sorted(get_pure_elements(dbf, comps)).index(indep_comp)
composition_grid = unpack_condition(conds[comp_cond])
dX = composition_grid[1] - composition_grid[0]
Xmax = composition_grid.max()
temperature_grid = unpack_condition(conds[v.T])
dT = temperature_grid[1] - temperature_grid[0]
boundary_sets = boundary_sets or ZPFBoundarySets(comps, comp_cond)
equilibria_calculated = 0
equilibrium_time = 0
convex_hulls_calculated = 0
convex_hull_time = 0
curr_conds = {key: unpack_condition(val) for key, val in conds.items()}
str_conds = sorted([str(k) for k in curr_conds.keys()])
grid_conds = _adjust_conditions(curr_conds)
for T_idx in range(temperature_grid.size):
T = temperature_grid[T_idx]
iter_equilibria = 0
if verbose:
print("=== T = {} ===".format(float(T)))
curr_conds[v.T] = [float(T)]
eq_conds = deepcopy(curr_conds)
Xmax_visited = 0.0
hull_time = time.time()
grid = calculate(dbf, comps, phases, fake_points=True, output='GM',
T=T, P=grid_conds[v.P], N=1,
model=models, parameters=parameters, to_xarray=False, **calc_kwargs)
hull = starting_point(eq_conds, statevars, prxs, grid)
convex_hull_time += time.time() - hull_time
parameters=parameters, symbols_only=True)
prxs = build_phase_records(dbf, species, phases, conds, models, output='GM',
parameters=parameters, build_gradients=True, build_hessians=True)
indep_comp = [key for key, value in conds.items() if isinstance(key, v.Composition) and len(np.atleast_1d(value)) > 1]
indep_pot = [key for key, value in conds.items() if (type(key) is v.StateVariable) and len(np.atleast_1d(value)) > 1]
if (len(indep_comp) != 1) or (len(indep_pot) != 1):
raise ValueError('Binary map requires exactly one composition and one potential coordinate')
if indep_pot[0] != v.T:
raise ValueError('Binary map requires that a temperature grid must be defined')
# binary assumption, only one composition specified.
comp_cond = [k for k in conds.keys() if isinstance(k, v.X)][0]
indep_comp = comp_cond.name[2:]
indep_comp_idx = sorted(get_pure_elements(dbf, comps)).index(indep_comp)
composition_grid = unpack_condition(conds[comp_cond])
dX = composition_grid[1] - composition_grid[0]
Xmax = composition_grid.max()
temperature_grid = unpack_condition(conds[v.T])
dT = temperature_grid[1] - temperature_grid[0]
boundary_sets = boundary_sets or ZPFBoundarySets(comps, comp_cond)
equilibria_calculated = 0
equilibrium_time = 0
convex_hulls_calculated = 0
convex_hull_time = 0
curr_conds = {key: unpack_condition(val) for key, val in conds.items()}
str_conds = sorted([str(k) for k in curr_conds.keys()])
grid_conds = _adjust_conditions(curr_conds)
for T_idx in range(temperature_grid.size):
T = temperature_grid[T_idx]
def _adjust_conditions(conds):
"Adjust conditions values to be within the numerical limit of the solver."
new_conds = OrderedDict()
for key, value in sorted(conds.items(), key=str):
if key == str(key):
key = getattr(v, key, key)
if isinstance(key, v.Composition):
new_conds[key] = [max(val, MIN_SITE_FRACTION*1000) for val in unpack_condition(value)]
else:
new_conds[key] = unpack_condition(value)
return new_conds
Result of equilibrium calculation.
ax : matplotlib.Axes
Default axes used if not specified.
x : StateVariable, optional
y : StateVariable, optional
z : StateVariable, optional
tielines : bool
If True, will plot tielines
kwargs : kwargs
Passed to `matplotlib.pyplot.scatter`.
Returns
-------
matplotlib AxesSubplot
"""
conds = OrderedDict([(_map_coord_to_variable(key), unpack_condition(np.asarray(value)))
for key, value in sorted(eq.coords.items(), key=str)
if (key in ('T', 'P', 'N')) or (key.startswith('X_'))])
indep_comps = sorted([key for key, value in conds.items() if isinstance(key, v.Composition) and len(value) > 1], key=str)
indep_pots = [key for key, value in conds.items() if (type(key) is v.StateVariable) and len(value) > 1]
# determine what the type of plot will be
if len(indep_comps) == 1 and len(indep_pots) == 1:
projection = None
elif len(indep_comps) == 2 and len(indep_pots) == 0:
projection = 'triangular'
else:
raise ValueError('The eqplot projection is not defined and cannot be autodetected. There are {} independent compositions and {} indepedent potentials.'.format(len(indep_comps), len(indep_pots)))
if z is not None:
raise NotImplementedError('3D plotting is not yet implemented')
if ax is None:
fig = plt.figure()
def _adjust_conditions(conds):
"Adjust conditions values to be within the numerical limit of the solver."
new_conds = OrderedDict()
for key, value in sorted(conds.items(), key=str):
if isinstance(key, v.Composition):
new_conds[key] = [max(val, MIN_SITE_FRACTION*1000) for val in unpack_condition(value)]
else:
new_conds[key] = unpack_condition(value)
return new_conds