Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def from_dict(cls, d):
"""
Returns Dos object from dict representation of Dos.
"""
dos = Dos(d["efermi"], d["energies"],
{Spin(int(k)): v for k, v in d["densities"].items()})
return FermiDos(dos, structure=Structure.from_dict(d["structure"]),
nelecs=d["nelecs"])
optional parameters to store along with the
TransformedStructure. This can include tags (a list) or author
which will be parsed.
"""
history = [] if history is None else history
self._source = {}
self._structures = []
self._changes = []
self._change_parameters = []
self._redo_trans = []
self._other_parameters = {} if other_parameters is None \
else deepcopy(other_parameters)
if len(history) > 0:
self._source = history[0]
for i in xrange(1, len(history)):
struct = Structure.from_dict(history[i]["input_structure"])
trans = AbstractTransformation.from_dict(history[i])
param = history[i].get("output_parameters", {})
self._structures.append(struct)
self._changes.append(trans)
self._change_parameters.append(param)
self._structures.append(structure)
for t in transformations:
self.append_transformation(t)
logger.error("BVAnalyzer error {e}.".format(e=str(ex)))
max_force = None
if d["state"] == "successful" and \
d["calculations"][0]["input"]["parameters"].get("NSW", 0) > 0:
# handle the max force and max force error
max_force = max([np.linalg.norm(a)
for a in d["calculations"][-1]["output"]
["ionic_steps"][-1]["forces"]])
if max_force > max_force_threshold:
error_msgs.append("Final max force exceeds {} eV"
.format(max_force_threshold))
d["state"] = "error"
s = Structure.from_dict(d["output"]["crystal"])
if not s.is_valid():
error_msgs.append("Bad structure (atoms are too close!)")
d["state"] = "error"
return {"delta_volume": delta_vol,
"max_force": max_force,
"percent_delta_volume": percent_delta_vol,
"warnings": warning_msgs,
"errors": error_msgs,
"coordination_numbers": coord_num,
"bandgap": gap, "cbm": cbm, "vbm": vbm,
"is_gap_direct": is_direct,
"bv_structure": bv_struct.as_dict()}
def from_old_dict(cls, d):
"""
Args:
d (dict): A dict with all data for a band structure symm line
object.
Returns:
A BandStructureSymmLine object
"""
# Strip the label to recover initial string (see trick used in as_dict to handle $ chars)
labels_dict = {k.strip(): v for k, v in d['labels_dict'].items()}
projections = {}
structure = None
if 'projections' in d and len(d['projections']) != 0:
structure = Structure.from_dict(d['structure'])
projections = {}
for spin in d['projections']:
dd = []
for i in range(len(d['projections'][spin])):
ddd = []
for j in range(len(d['projections'][spin][i])):
dddd = []
for k in range(len(d['projections'][spin][i][j])):
ddddd = []
orb = Orbital(k).name
for l in range(len(d['projections'][spin][i][j][
orb])):
ddddd.append(d['projections'][spin][i][j][
orb][l])
dddd.append(np.array(ddddd))
ddd.append(np.array(dddd))
def from_dict(d):
"""
Returns CompleteDos object from dict representation.
"""
tdos = Dos.from_dict(d)
struct = Structure.from_dict(d["structure"])
pdoss = {}
for i in xrange(len(d["pdos"])):
at = struct[i]
orb_dos = {}
for orb_str, odos in d["pdos"][i].items():
orb = Orbital.from_string(orb_str)
orb_dos[orb] = {Spin.from_int(int(k)): v
for k, v in odos["densities"].items()}
pdoss[at] = orb_dos
return CompleteDos(struct, tdos, pdoss)
elif 'mps' in old_task and old_task['mps']:
snl = mps_dict_to_snl(old_task['mps'])
mpsnl, snlgroup_id = sma.add_snl(snl)
d['snl'] = mpsnl.to_dict
d['snlgroup_id'] = snlgroup_id
else:
s = Structure.from_dict(old_task['input']['crystal'])
snl = StructureNL(s, 'Anubhav Jain ', remarks=['origin unknown'])
mpsnl, snlgroup_id = sma.add_snl(snl)
d['snl'] = mpsnl.to_dict
d['snlgroup_id'] = snlgroup_id
if 'optimize structure' in d['task_type'] and 'output' in d:
# create a new SNL based on optimized structure
new_s = Structure.from_dict(d['output']['crystal'])
old_snl = StructureNL.from_dict(d['snl'])
history = old_snl.history
history.append(
{'name': 'Materials Project structure optimization',
'url': 'http://www.materialsproject.org',
'description': {'task_type': d['task_type'],
'fw_id': d['fw_id'],
'task_id': d['task_id']}})
new_snl = StructureNL(new_s, old_snl.authors, old_snl.projects,
old_snl.references, old_snl.remarks,
old_snl.data, history)
# add snl
mpsnl, snlgroup_id = sma.add_snl(new_snl, snlgroup_guess=d['snlgroup_id'])
d['snl_final'] = mpsnl.to_dict
def from_dict(cls, d):
"""
Creates a TransformedStructure from a dict.
"""
s = Structure.from_dict(d)
return cls(s, history=d["history"],
other_parameters=d.get("other_parameters", None))
d["input_mp_id"] = tag["input_id"]
d["snl_final"] = o["snl_final"]
d["pretty_formula"] = o["pretty_formula"]
# Old input mp-id style
if o["snl"]["about"].get("_mp_id"):
d["material_id"] = o["snl"]["about"]["_mp_id"]
# New style
elif "input_mp_id" in d:
d["material_id"] = d["input_mp_id"]
else:
d["material_id"] = None
d["relaxation_task_id"] = i
calc_struct = Structure.from_dict(o["snl_final"])
# TODO:
# JHM: This test is unnecessary at the moment, but should be redone
"""
conventional = is_conventional(calc_struct)
if conventional:
d["analysis"]["is_conventional"] = True
else:
d["analysis"]["is_conventional"] = False
"""
d["spacegroup"]=o.get("spacegroup", "Unknown")
if ndocs >= 20:
# Perform Elastic tensor fitting and analysis
result = ElasticTensor.from_stress_dict(ss_dict)
d["elastic_tensor"] = result.tolist()
kg_average = result.kg_average
percent_delta_vol = delta_vol / initial_vol
coord_num = get_coordination_numbers(d)
calc = d["calculations"][-1]
gap = calc["output"]["bandgap"]
cbm = calc["output"]["cbm"]
vbm = calc["output"]["vbm"]
is_direct = calc["output"]["is_gap_direct"]
warning_msgs = []
error_msgs = []
if abs(percent_delta_vol) > volume_change_threshold:
warning_msgs.append("Volume change > {}%"
.format(volume_change_threshold * 100))
bv_struct = Structure.from_dict(d["output"]["crystal"])
try:
bva = BVAnalyzer()
bv_struct = bva.get_oxi_state_decorated_structure(bv_struct)
except ValueError as e:
logger.error("Valence cannot be determined due to {e}."
.format(e=e))
except Exception as ex:
logger.error("BVAnalyzer error {e}.".format(e=str(ex)))
max_force = None
if d["state"] == "successful" and \
d["calculations"][0]["input"]["parameters"].get("NSW", 0) > 0:
# handle the max force and max force error
max_force = max([np.linalg.norm(a)
for a in d["calculations"][-1]["output"]
["ionic_steps"][-1]["forces"]])