Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
desired_sitefracs[dof_idx:dof_idx + len(dof)] = sitefracs_to_add
dof_idx += len(dof)
single_eqdata = calculate_(dbf, species, [current_phase], str_statevar_dict, models, phase_records, pdens=500)
driving_force = np.multiply(target_hyperplane_chempots, single_eqdata.X).sum(axis=-1) - single_eqdata.GM
driving_force = float(np.squeeze(driving_force))
else:
# Extract energies from single-phase calculations
grid = calculate_(dbf, species, [current_phase], str_statevar_dict, models, phase_records, pdens=500, fake_points=True)
single_eqdata = _equilibrium(species, phase_records, cond_dict, grid)
if np.all(np.isnan(single_eqdata.NP)):
logging.debug('Calculation failure: all NaN phases with phases: {}, conditions: {}, parameters {}'.format(current_phase, cond_dict, parameters))
return np.inf
select_energy = float(single_eqdata.GM)
region_comps = []
for comp in [c for c in sorted(comps) if c != 'VA']:
region_comps.append(cond_dict.get(v.X(comp), np.nan))
region_comps[region_comps.index(np.nan)] = 1 - np.nansum(region_comps)
driving_force = np.multiply(target_hyperplane_chempots, region_comps).sum() - select_energy
driving_force = float(driving_force)
return driving_force
conds = data_group[0].json['conditions']
conds['T'] = np.array(conds['T'])
conds['T'] = conds['T'][conds['T'] >= 300.]
for key in conds.keys():
if key not in ['T', 'P']:
raise ValueError('Invalid conditions in JSON file')
# To work around differences in sublattice models, relax the internal dof
global_comps = sorted(set(data_group[0].json['components']) - set(['VA']))
compositions = \
_map_internal_dof(input_database,
sorted(data_group[0].json['components']),
data_group[0].json['phases'][0],
np.atleast_2d(
data_group[0].json['solver']['sublattice_configuration']).astype(np.float))
# Tiny perturbation to work around a bug in lower_convex_hull (gh-28)
compare_conds = {v.X(comp): np.add(compositions[:, idx], 1e-4).flatten().tolist()
for idx, comp in enumerate(global_comps[:-1])}
compare_conds.update({v.__dict__[key]: value for key, value in conds.items()})
# We only want to relax the internal dof at the lowest temperature
# This will help us capture the most related sublattice config since solver mode=manual
# probably means this is first-principles data
compare_conds[v.T] = 300.
eqres = equilibrium(dbf, data_group[0].json['components'],
str(data_group[0].json['phases'][0]), compare_conds, verbose=False)
internal_dof = sum(map(len, dbf.phases[data_group[0].json['phases'][0]].constituents))
largest_phase_fraction = eqres['NP'].values.argmax()
eqpoints = eqres['Y'].values[..., largest_phase_fraction, :internal_dof]
result = calculate(dbf, data_group[0].json['components'],
str(data_group[0].json['phases'][0]), output=y,
points=eqpoints, **conds)
# Don't show CALPHAD results below 300 K because they're meaningless right now
result = result.sel(T=slice(300, None))
iter_callables = {name: functools.partial(func, *parvalues)
for name, func in callables.items()}
iter_grad_callables = {name: functools.partial(func, *parvalues)
for name, func in grad_callables.items()}
res = np.zeros(len(input_data))
# TODO: This should definitely be vectorized
# It will probably require an update to equilibrium()
for idx, row in input_data.iterrows():
conditions = dict()
if 'T' in row:
conditions[v.T] = row['T']
if 'P' in row:
conditions[v.P] = row['P']
for comp in global_comps[:-1]:
conditions[v.X(comp)] = row['X('+comp+')']
statevars = dict((str(key), value) for key, value in conditions.items() if key in [v.T, v.P])
eq = equilibrium(dbf, comps, row['Phase'], conditions,
model=mods, callables=iter_callables,
grad_callables=iter_grad_callables, verbose=False)
# TODO: Support for miscibility gaps, i.e., FCC_A1#1 specification
eq_values = eq['Y'].sel(vertex=0).values
#print(eq_values)
# TODO: All the needed 'Types' should be precalculated and looked up
variables = sorted(mods[row['Phase']].energy.atoms(v.StateVariable).union({v.T, v.P}), key=str)
output_callables = {row['Phase']: functools.partial(make_callable(getattr(mods[row['Phase']],
row['Type']),
itertools.chain(param_names, variables)),
*parvalues)}
calculated_value = calculate(dbf, comps, row['Phase'], output=row['Type'],
model=mods, callables=output_callables,
points=eq_values, **statevars)
df = np.multiply(target_hyperplane_chempots, single_eqdata.X).sum(axis=-1) - single_eqdata.GM
driving_force = float(df.max())
elif phase_flag == 'disordered':
# Construct disordered sublattice configuration from composition dict
# Compute energy
# Compute residual driving force
# TODO: Check that it actually makes sense to declare this phase 'disordered'
num_dof = sum([len(set(c).intersection(species)) for c in dbf.phases[current_phase].constituents])
desired_sitefracs = np.ones(num_dof, dtype=np.float)
dof_idx = 0
for c in dbf.phases[current_phase].constituents:
dof = sorted(set(c).intersection(comps))
if (len(dof) == 1) and (dof[0] == 'VA'):
return 0
# If it's disordered config of BCC_B2 with VA, disordered config is tiny vacancy count
sitefracs_to_add = np.array([cond_dict.get(v.X(d)) for d in dof], dtype=np.float)
# Fix composition of dependent component
sitefracs_to_add[np.isnan(sitefracs_to_add)] = 1 - np.nansum(sitefracs_to_add)
desired_sitefracs[dof_idx:dof_idx + len(dof)] = sitefracs_to_add
dof_idx += len(dof)
single_eqdata = calculate_(dbf, species, [current_phase], str_statevar_dict, models, phase_records, pdens=500)
driving_force = np.multiply(target_hyperplane_chempots, single_eqdata.X).sum(axis=-1) - single_eqdata.GM
driving_force = float(np.squeeze(driving_force))
else:
# Extract energies from single-phase calculations
grid = calculate_(dbf, species, [current_phase], str_statevar_dict, models, phase_records, pdens=500, fake_points=True)
single_eqdata = _equilibrium(species, phase_records, cond_dict, grid)
if np.all(np.isnan(single_eqdata.NP)):
logging.debug('Calculation failure: all NaN phases with phases: {}, conditions: {}, parameters {}'.format(current_phase, cond_dict, parameters))
return np.inf
select_energy = float(single_eqdata.GM)
region_comps = []
def _map_coord_to_variable(coord):
"""
Map a coordinate to a StateVariable object.
Parameters
----------
coord : str
Name of coordinate in equilibrium object.
Returns
-------
pycalphad StateVariable
"""
vals = {'T': v.T, 'P': v.P}
if coord.startswith('X_'):
return v.X(coord[2:])
elif coord in vals:
return vals[coord]
else:
return coord