Example #1
0
 def test_from_dict(self):
     d = self.propertied_structure.to_dict
     s = Structure.from_dict(d)
     self.assertEqual(s[0].magmom, 5)
     d = {'lattice': {'a': 3.8401979337, 'volume': 40.044794644251596,
                      'c': 3.8401979337177736, 'b': 3.840198994344244,
                      'matrix': [[3.8401979337, 0.0, 0.0],
                                 [1.9200989668, 3.3257101909, 0.0],
                                 [0.0, -2.2171384943, 3.1355090603]],
                      'alpha': 119.9999908639842, 'beta': 90.0,
                      'gamma': 60.000009137322195},
          'sites': [{'properties': {'magmom': 5}, 'abc': [0.0, 0.0, 0.0],
                     'occu': 1.0, 'species': [{'occu': 1.0,
                                               'oxidation_state':-2,
                                               'properties': {'spin': 3},
                                               'element': 'O'}],
                     'label': 'O2-', 'xyz': [0.0, 0.0, 0.0]},
                    {'properties': {'magmom':-5}, 'abc': [0.75, 0.5, 0.75],
                     'occu': 0.8, 'species': [{'occu': 0.8,
                                               'oxidation_state': 2,
                                               'properties': {'spin': 2},
                                               'element': 'Mg'}],
                     'label': 'Mg2+:0.800',
                     'xyz': [3.8401979336749994, 1.2247250003039056e-06,
                             2.351631795225]}]}
     s = Structure.from_dict(d)
     self.assertEqual(s[0].magmom, 5)
     self.assertEqual(s[0].specie.spin, 3)
Example #2
0
def get_basic_analysis_and_error_checks(d, max_force_threshold=0.5,
                                        volume_change_threshold=0.2):

    initial_vol = d["input"]["crystal"]["lattice"]["volume"]
    final_vol = d["output"]["crystal"]["lattice"]["volume"]
    delta_vol = final_vol - initial_vol
    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"]])

        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()}
Example #3
0
    def from_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 = {
                Spin(int(spin)): [
                    [{Orbital[orb]: [
                        d['projections'][spin][i][j][orb][k]
                        for k in range(len(d['projections'][spin][i][j][orb]))]
                      for orb in d['projections'][spin][i][j]}
                     for j in range(len(d['projections'][spin][i]))]
                    for i in range(len(d['projections'][spin]))]
                for spin in d['projections']}

        return BandStructureSymmLine(
            d['kpoints'], {Spin(int(k)): d['bands'][k]
                           for k in d['bands']},
            Lattice(d['lattice_rec']['matrix']), d['efermi'],
            labels_dict, structure=structure, projections=projections)
Example #4
0
def get_basic_analysis_and_error_checks(d):
    initial_vol = d["input"]["crystal"]["lattice"]["volume"]
    final_vol = d["output"]["crystal"]["lattice"]["volume"]
    delta_vol = final_vol - initial_vol
    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"]

    if abs(percent_delta_vol) > 0.20:
        warning_msgs = ["Volume change > 20%"]
    else:
        warning_msgs = []

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

    return {"delta_volume": delta_vol,
            "percent_delta_volume": percent_delta_vol,
            "warnings": warning_msgs, "coordination_numbers": coord_num,
            "bandgap": gap, "cbm": cbm, "vbm": vbm,
            "is_gap_direct": is_direct,
            "bv_structure": bv_struct.to_dict}
Example #5
0
 def from_dict(cls, d):
     structure = Structure.from_dict(d["structure"])
     return MPINTLammps(structure, parameters=d["parameters"],
                        label=d["label"],
                        specorder=d["specorder"],
                        always_triclinic=d["always_triclinic"],
                        no_data_file=d["no_data_file"])
Example #6
0
    def from_dict(cls, d):
        """
        Args:
            d (dict): A dict with all data for a band structure symm line
                object.

        Returns:
            A BandStructureSymmLine object
        """
        try:
            # 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 d.get('projections'):
                if isinstance(d["projections"]['1'][0][0], dict):
                    raise ValueError("Old band structure dict format detected!")
                structure = Structure.from_dict(d['structure'])
                projections = {Spin(int(spin)): np.array(v)
                               for spin, v in d["projections"].items()}

            return BandStructureSymmLine(
                d['kpoints'], {Spin(int(k)): d['bands'][k]
                               for k in d['bands']},
                Lattice(d['lattice_rec']['matrix']), d['efermi'],
                labels_dict, structure=structure, projections=projections)
        except:
            warnings.warn("Trying from_dict failed. Now we are trying the old "
                          "format. Please convert your BS dicts to the new "
                          "format. The old format will be retired in pymatgen "
                          "5.0.")
            return BandStructureSymmLine.from_old_dict(d)
 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))
Example #8
0
 def setUp(self):
     structure_dict = {
         "lattice": {"a": 4.754150115,
                     "volume": 302.935463898643,
                     "c": 10.462573348,
                     "b": 6.090300362,
                     "matrix": [[4.754150115, 0.0, 0.0],
                                [0.0, 6.090300362, 0.0],
                                [0.0, 0.0, 10.462573348]],
                     "alpha": 90.0,
                     "beta": 90.0,
                     "gamma": 90.0},
         "sites": [{"occu": 1, "abc": [0.0, 0.0, 0.0],
                    "xyz": [0.0, 0.0, 0.0],
                    "species": [{"occu": 1, "element": "Li"}],
                    "label": "Li"}, {"occu": 1,
                                     "abc": [0.5000010396179928, 0.0,
                                             0.5000003178950235],
                                     "xyz": [2.37708, 0.0, 5.23129],
                                     "species": [{"occu": 1,
                                                  "element": "Li"}],
                                     "label": "Li"},
                                 {"occu": 1, "abc": [0.0,
                                                     0.49999997028061194,
                                                     0.0],
                                  "xyz": [0.0, 3.04515, 0.0],
                                  "species": [{"occu": 1, "element": "Li"}], "label": "Li"}, {"occu": 1, "abc": [0.5000010396179928, 0.49999997028061194, 0.5000003178950235], "xyz": [2.37708, 3.04515, 5.23129], "species": [{"occu": 1, "element": "Li"}], "label": "Li"}, {"occu": 1, "abc": [0.7885825876997996, 0.5473161916279229, 0.3339168944194627], "xyz": [3.74904, 3.33332, 3.4936300000000005], "species": [{"occu": 1, "element": "O"}], "label": "O"}, {"occu": 1, "abc": [0.2114173881108085, 0.452683748933301, 0.6660827855827808], "xyz": [1.00511, 2.75698, 6.968940000000001], "species": [{"occu": 1, "element": "O"}], "label": "O"}, {"occu": 1, "abc": [0.7114184277288014, 0.5473161916279229, 0.8339172123144861], "xyz": [3.38219, 3.33332, 8.72492], "species": [{"occu": 1, "element": "O"}], "label": "O"}, {"occu": 1, "abc": [0.7885825876997996, 0.9526820772587701, 0.3339168944194627], "xyz": [3.74904, 5.8021199999999995, 3.4936300000000005], "species": [{"occu": 1, "element": "O"}], "label": "O"}, {"occu": 1, "abc": [0.28858365150718424, 0.047317863302453654, 0.16608342347556082], "xyz": [1.37197, 0.28818, 1.73766], "species": [{"occu": 1, "element": "O"}], "label": "O"}, {"occu": 1, "abc": [0.7440972443925447, 0.25000080611787734, 0.09613791622232937], "xyz": [3.537549999999999, 1.52258, 1.00585], "species": [{"occu": 1, "element": "O"}], "label": "O"}, {"occu": 1, "abc": [0.28858365150718424, 0.452683748933301, 0.16608342347556082], "xyz": [1.37197, 2.75698, 1.73766], "species": [{"occu": 1, "element": "O"}], "label": "O"}, {"occu": 1, "abc": [0.2114173881108085, 0.047317863302453654, 0.6660827855827808], "xyz": [1.00511, 0.28818, 6.968940000000001], "species": [{"occu": 1, "element": "O"}], "label": "O"}, {"occu": 1, "abc": [0.2559006279926859, 0.7499991344433464, 0.9038627195677177], "xyz": [1.21659, 4.56772, 9.45673], "species": [{"occu": 1, "element": "O"}], "label": "O"}, {"occu": 1, "abc": [0.7559016676106785, 0.25000080611787734, 0.5961372783295493], "xyz": [3.5936699999999986, 1.52258, 6.2371300000000005], "species": [{"occu": 1, "element": "O"}], "label": "O"}, {"occu": 1, "abc": [0.7939989080466804, 0.7499991344433464, 0.5421304884886912], "xyz": [3.77479, 4.56772, 5.67208], "species": [{"occu": 1, "element": "O"}], "label": "O"}, {"occu": 1, "abc": [0.24409830819992942, 0.7499991344433464, 0.40386240167269416], "xyz": [1.16048, 4.56772, 4.22544], "species": [{"occu": 1, "element": "O"}], "label": "O"}, {"occu": 1, "abc": [0.7060021073819206, 0.7499991344433464, 0.04213017059366761], "xyz": [3.35644, 4.56772, 0.44079000000000007], "species": [{"occu": 1, "element": "O"}], "label": "O"}, {"occu": 1, "abc": [0.2939978684286875, 0.25000080611787734, 0.9578695094085758], "xyz": [1.3977099999999996, 1.52258, 10.02178], "species": [{"occu": 1, "element": "O"}], "label": "O"}, {"occu": 1, "abc": [0.20600106776392774, 0.25000080611787734, 0.4578701473013559], "xyz": [0.9793599999999998, 1.52258, 4.7905], "species": [{"occu": 1, "element": "O"}], "label": "O"}, {"occu": 1, "abc": [0.7114184277288014, 0.9526820772587701, 0.8339172123144861], "xyz": [3.38219, 5.8021199999999995, 8.72492], "species": [{"occu": 1, "element": "O"}], "label": "O"}, {"occu": 1, "abc": [0.5793611756830275, 0.7499991344433464, 0.9051119342269868], "xyz": [2.75437, 4.56772, 9.4698], "species": [{"occu": 1, "element": "P"}], "label": "P"}, {"occu": 1, "abc": [0.9206377363201961, 0.7499991344433464, 0.40511161633196324], "xyz": [4.37685, 4.56772, 4.23851], "species": [{"occu": 1, "element": "P"}], "label": "P"}, {"occu": 1, "abc": [0.42063880012758065, 0.25000080611787734, 0.09488774577525667], "xyz": [1.9997799999999994, 1.52258, 0.99277], "species": [{"occu": 1, "element": "P"}], "label": "P"}, {"occu": 1, "abc": [0.07936223949041206, 0.25000080611787734, 0.5948880636702801], "xyz": [0.3773, 1.52258, 6.22406], "species": [{"occu": 1, "element": "P"}], "label": "P"}, {"occu": 1, "abc": [0.021860899947623972, 0.7499991344433464, 0.7185507570598875], "xyz": [0.10393, 4.56772, 7.517890000000001], "species": [{"occu": 1, "element": "Fe"}], "label": "Fe"}, {"occu": 1, "abc": [0.478135932819614, 0.7499991344433464, 0.21855043916486389], "xyz": [2.27313, 4.56772, 2.2866], "species": [{"occu": 1, "element": "Fe"}], "label": "Fe"}, {"occu": 1, "abc": [0.9781369724376069, 0.25000080611787734, 0.2814489229423561], "xyz": [4.65021, 1.52258, 2.9446800000000004], "species": [{"occu": 1, "element": "Fe"}], "label": "Fe"}, {"occu": 1, "abc": [0.5218619395656168, 0.25000080611787734, 0.7814492408373795], "xyz": [2.48101, 1.52258, 8.17597], "species": [{"occu": 1, "element": "Fe"}], "label": "Fe"}]}
     structure = Structure.from_dict(structure_dict)
     self.structure = structure
     trans = [SubstitutionTransformation({"Li": "Na"})]
     self.trans = TransformedStructure(structure, trans)
Example #9
0
    def set_analysis(self, d, max_force_threshold=0.5, volume_change_threshold=0.2):
        """
        Adapted from matgendb.creator

        set the 'analysis' key
        """
        initial_vol = d["input"]["structure"]["lattice"]["volume"]
        final_vol = d["output"]["structure"]["lattice"]["volume"]
        delta_vol = final_vol - initial_vol
        percent_delta_vol = delta_vol / initial_vol
        warning_msgs = []
        error_msgs = []
        if abs(percent_delta_vol) > volume_change_threshold:
            warning_msgs.append("Volume change > {}%".format(volume_change_threshold * 100))
        max_force = None
        calc = d["calcs_reversed"][0]
        if d["state"] == "successful" and calc["input"]["parameters"].get("NSW", 0) > 0:
            # handle the max force and max force error
            max_force = max([np.linalg.norm(a) for a in calc["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"]["structure"])
            if not s.is_valid():
                error_msgs.append("Bad structure (atoms are too close!)")
                d["state"] = "error"
        d["analysis"] = {"delta_volume": delta_vol,
                         "delta_volume_percent": percent_delta_vol,
                         "max_force": max_force,
                         "warnings": warning_msgs,
                         "errors": error_msgs}
Example #10
0
    def from_dict(cls, d):
        """
        Create from dict.

        Args:
            A dict with all data for a band structure object.

        Returns:
            A BandStructure object
        """
        labels_dict = d['labels_dict']
        projections = {}
        structure = None
        if isinstance(list(d['bands'].values())[0], dict):
            eigenvals = {Spin(int(k)): np.array(d['bands'][k]['data'])
                         for k in d['bands']}
        else:
            eigenvals = {Spin(int(k)): d['bands'][k] for k in d['bands']}
        if 'structure' in d:
            structure = Structure.from_dict(d['structure'])
        if d.get('projections'):
            projections = {Spin(int(spin)): np.array(v)
                           for spin, v in d["projections"].items()}

        return BandStructure(
            d['kpoints'], eigenvals,
            Lattice(d['lattice_rec']['matrix']), d['efermi'],
            labels_dict, structure=structure, projections=projections)
Example #11
0
 def from_dict(cls, d):
     structure = Structure.from_dict(d["structure"])
     return cls(structure, np.array(d["displacements"]), specie=d["specie"],
                temperature=d["temperature"], time_step=d["time_step"],
                step_skip=d["step_skip"], min_obs=d["min_obs"],
                smoothed=d.get("smoothed", "max"),
                avg_nsteps=d.get("avg_nsteps", 1000))
Example #12
0
 def from_dict(d):
     """
     Creates a TransformedStructure from a dict.
     """
     s = Structure.from_dict(d)
     return TransformedStructure(s, [], d["history"],
                                 d.get("other_parameters", None))
Example #13
0
 def from_dict(d):
     """
     Returns feffAtoms object from dictionary
     """
     return FeffAtoms(Structure.from_dict(d['structure']),
                      d['central_atom'],
                      d['comment'])
Example #14
0
 def from_dict(d):
     return Poscar(Structure.from_dict(d["structure"]),
                   comment=d["comment"],
                   selective_dynamics=d["selective_dynamics"],
                   true_names=d["true_names"],
                   velocities=d.get("velocities", None),
                   predictor_corrector=d.get("predictor_corrector", None))
Example #15
0
    def __call__(self, params, query_engine):
        # Assign prototypes to all the structures at this parameter point that do not have a prototype
        total_prototypes = 0
        new_prototypes = 0

        structures_coll = query_engine.collection
        stoichs = structures_coll.find({"potential.params_id": params["_id"]}, {"pretty_formula": 1}).\
            distinct("pretty_formula")

        for stoich in stoichs:
            cur = structures_coll.find({"potential.params_id": params["_id"], "prototype_id": {"$exists": False},
                                        "pretty_formula": stoich}, fields={"structure": 1, "energy_per_site": 1})
            if self.limit:
                cur.sort('energy_per_site', pymongo.ASCENDING).limit(self.limit)

            for doc in cur:
                # Either get the prototype or insert this structure as a new one
                structure = Structure.from_dict(doc["structure"])
                if not splpy.util.is_structure_bad(structure):
                    proto_id, is_new = prototype.insert_prototype(structure, query_engine.db)
                    if proto_id is None:
                        logger.warn("Failed to create find or create prototype for structure {}".format(doc["_id"]))
                        continue

                    query_engine.collection.update({'_id': doc['_id']}, {"$set": {'prototype_id': proto_id}})
                    total_prototypes += 1
                    if is_new:
                        new_prototypes += 1
                else:
                    logger.info("Skipping structure {} because there is something wrong with it.".format(doc["_id"]))

        logger.info("Assigned {} prototypes, {} new.".format(total_prototypes, new_prototypes))
Example #16
0
    def from_dict(d):
        """
        Args:
            A dict with all data for a band structure symm line object.

        Returns:
            A BandStructureSymmLine object
        """
        labels_dict = d['labels_dict']
        projections = {}
        structure = None
        if 'projections' in d and len(d['projections']) != 0:
            structure = Structure.from_dict(d['structure'])
            projections = {
                Spin.from_int(int(spin)): [
                    [{Orbital.from_string(orb): [
                        d['projections'][spin][i][j][orb][k]
                        for k in range(len(d['projections'][spin][i][j][orb]))]
                      for orb in d['projections'][spin][i][j]}
                     for j in range(len(d['projections'][spin][i]))]
                    for i in range(len(d['projections'][spin]))]
                for spin in d['projections']}

        return BandStructureSymmLine(
            d['kpoints'], {Spin.from_int(int(k)): d['bands'][k]
                           for k in d['bands']},
            Lattice(d['lattice_rec']['matrix']), d['efermi'],
            labels_dict, structure=structure, projections=projections)
Example #17
0
 def test_as_dict(self):
     self.trans.set_parameter('author', 'will')
     d = self.trans.as_dict()
     self.assertIn('last_modified', d)
     self.assertIn('history', d)
     self.assertIn('version', d)
     self.assertIn('author', d['other_parameters'])
     self.assertEqual(Structure.from_dict(d).formula, 'Na4 Fe4 P4 O16')
Example #18
0
 def test_as_dict(self):
     self.trans.set_parameter("author", "will")
     d = self.trans.as_dict()
     self.assertIn("last_modified", d)
     self.assertIn("history", d)
     self.assertIn("version", d)
     self.assertIn("author", d["other_parameters"])
     self.assertEqual(Structure.from_dict(d).formula, "Na4 Fe4 P4 O16")
Example #19
0
 def from_dict(hdict):
     """
     Returns header object from a dictionary representation
     """
     comment = hdict['comment']
     source = hdict['source']
     structure = Structure.from_dict(hdict['structure'])
     return Header(structure, source, comment)
 def structures(self):
     """
     Copy of all structures in the TransformedStructure. A
     structure is stored after every single transformation.
     """
     hstructs = [Structure.from_dict(s['input_structure'])
                 for s in self.history if 'input_structure' in s]
     return hstructs + [self.final_structure]
Example #21
0
    def from_dict(d):
        """
        Returns FeffPot object from dictionary

        Args:
            d:
                dictionary of FeffPot input parameters
        """
        return FeffPot(Structure.from_dict(d['structure']), d['central_atom'])
Example #22
0
def render_graph(batt_id):
    query_path = {'battid': batt_id}
    result = list(mongo_coll_path.find(query_path))
    if result and result[0]['intercalating_paths']:
        intercalating_paths = result[0]['intercalating_paths']
        hops = result[0]['hops']
        fss = Structure.from_dict(result[0]['full_sites_struct'])
        bs = Structure.from_dict(result[0]['base_structure'])
        graph_result = migration_graph(intercalating_paths, hops, fss, bs)
    else:
        print('No intercalating path available')
        id_discharge = int(
            list(mongo_coll.find(query_path))[0]['id_discharge'])
        struct_dict = list(mongo_coll_mat.find({'task_id':
                                                id_discharge}))[0]['structure']
        graph_result = ctc.StructureMoleculeComponent(
            Structure.from_dict(struct_dict), static=True)
    return graph_result.struct_layout
Example #23
0
 def from_dict(cls, d):
     lattice_rec = Lattice(d['lattice_rec']['matrix'])
     eigendisplacements = np.array(d['eigendisplacements']['real']) + np.array(d['eigendisplacements']['imag'])*1j
     nac_eigendisplacements = [(direction, np.array(e['real']) + np.array(e['imag'])*1j)
                               for direction, e in d['nac_eigendisplacements']]
     nac_frequencies = [(direction, np.array(f)) for direction, f in d['nac_frequencies']]
     structure = Structure.from_dict(d['structure']) if 'structure' in d else None
     return cls(d['qpoints'], np.array(d['bands']), lattice_rec, nac_frequencies, eigendisplacements,
                nac_eigendisplacements, d['labels_dict'], structure=structure)
Example #24
0
    def from_dict(d):
        """
        Returns FeffPot object from dictionary

        Args:
            d: dictionary of FeffPot input parameters
        """
        return FeffPot(Structure.from_dict(d['structure']),
                       d['central_atom'])
Example #25
0
 def from_dict(cls, d):
     """
     Returns IRDielectricTensor from dict representation
     """
     structure = Structure.from_dict(d["structure"])
     oscillator_strength = d["oscillator_strength"]
     ph_freqs_gamma = d["ph_freqs_gamma"]
     epsilon_infinity = d["epsilon_infinity"]
     return cls(oscillator_strength, ph_freqs_gamma, epsilon_infinity, structure)
 def from_dict(cls, d):
     structure = Structure.from_dict(d["structure"])
     return cls(structure, np.array(d["displacements"]), specie=d["specie"],
                temperature=d["temperature"], time_step=d["time_step"],
                step_skip=d["step_skip"], min_obs=d["min_obs"],
                smoothed=d.get("smoothed", "max"),
                avg_nsteps=d.get("avg_nsteps", 1000),
                lattices=np.array(d.get("lattices",
                                        [d["structure"]["lattice"][
                                             "matrix"]])))
Example #27
0
 def structures(self):
     """
     Copy of all structures in the TransformedStructure. A
     structure is stored after every single transformation.
     """
     hstructs = [
         Structure.from_dict(s["input_structure"]) for s in self.history
         if "input_structure" in s
     ]
     return hstructs + [self.final_structure]
Example #28
0
 def from_dict(cls, d):
     structure = Structure.from_dict(d["structure"])
     return cls(structure,
                np.array(d["displacements"]),
                specie=d["specie"],
                temperature=d["temperature"],
                time_step=d["time_step"],
                step_skip=d["step_skip"],
                time_intervals_number=d["time_intervals_number"],
                spec_dict=d['spec_dict'])
Example #29
0
File: dos.py Project: tllu/pymatgen
 def from_dict(cls, d) -> "FermiDos":
     """
     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"])
Example #30
0
    def set_analysis(d, max_force_threshold=0.5, volume_change_threshold=0.2):
        """
        Adapted from matgendb.creator

        set the 'analysis' key
        """
        initial_vol = d["input"]["structure"]["lattice"]["volume"]
        final_vol = d["output"]["structure"]["lattice"]["volume"]
        delta_vol = final_vol - initial_vol
        percent_delta_vol = 100 * delta_vol / initial_vol
        warning_msgs = []
        error_msgs = []

        # delta volume checks
        if abs(percent_delta_vol) > volume_change_threshold:
            warning_msgs.append("Volume change > {}%".format(volume_change_threshold * 100))

        # max force and valid structure checks
        max_force = None
        calc = d["calcs_reversed"][0]
        if d["state"] == "successful" and calc["input"]["parameters"].get("NSW", 0) > 0:
            # handle the max force and max force error
            forces = np.array(calc['output']['ionic_steps'][-1]['forces'])
            # account for selective dynamics
            final_structure = Structure.from_dict(calc['output']['structure'])
            sdyn = final_structure.site_properties.get('selective_dynamics')
            if sdyn:
                forces[np.logical_not(sdyn)] = 0
            max_force = max(np.linalg.norm(forces, axis=1))
            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"]["structure"])
            if not s.is_valid():
                error_msgs.append("Bad structure (atoms are too close!)")
                d["state"] = "error"

        d["analysis"] = {"delta_volume": delta_vol,
                         "delta_volume_as_percent": percent_delta_vol,
                         "max_force": max_force,
                         "warnings": warning_msgs,
                         "errors": error_msgs}
Example #31
0
 def from_dict(cls, d):
     """
     Returns IRDielectricTensor from dict representation
     """
     structure = Structure.from_dict(d['structure'])
     oscillator_strength = d['oscillator_strength']
     ph_freqs_gamma = d['ph_freqs_gamma']
     epsilon_infinity = d['epsilon_infinity']
     return cls(oscillator_strength, ph_freqs_gamma, epsilon_infinity,
                structure)
Example #32
0
    def from_dict(cls, d):
        """
        Returns CompleteDos object from dict representation.
        """
        tdos = PhononDos.from_dict(d)
        struct = Structure.from_dict(d["structure"])
        pdoss = {}
        for at, pdos in zip(struct, d["pdos"]):
            pdoss[at] = pdos

        return cls(struct, tdos, pdoss)
Example #33
0
 def __init__(self, parameters):
     self.update(parameters)
     structure = Structure.from_dict(parameters['structure'])
     structure.vbm_l = parameters['band_structure']['vbm_l']
     structure.cbm_l = parameters['band_structure']['cbm_l']
     structure.vbm = (parameters['band_structure']['vbm_a'], parameters['band_structure']['vbm_b'], parameters['band_structure']['vbm_c'])
     structure.cbm = (parameters['band_structure']['cbm_a'], parameters['band_structure']['cbm_b'], parameters['band_structure']['cbm_c'])
     self.structure = structure
     self.job = parameters['job']
     self.spec = parameters['spec']
     self.option = parameters['option']
Example #34
0
    def from_dict(cls, d: dict) -> "ComplexDefects":
        # orderedDict disables MSONable.
        structure = d["structure"]
        if isinstance(structure, dict):
            structure = Structure.from_dict(structure)

        complex_defects = OrderedDict()
        for k, v in d["complex_defects"].items():
            complex_defects[k] = ComplexDefect.from_dict(v)

        return cls(structure=structure, complex_defects=complex_defects)
Example #35
0
    def from_dict(cls, d):
        """
        Returns CompleteCohp object from dict representation.
        """
        cohp_dict = {}
        efermi = d["efermi"]
        energies = d["energies"]
        structure = Structure.from_dict(d["structure"])
        if "bonds" in d.keys():
            bonds = {
                bond: {
                    "length":
                    d["bonds"][bond]["length"],
                    "sites":
                    tuple(
                        PeriodicSite.from_dict(site)
                        for site in d["bonds"][bond]["sites"])
                }
                for bond in d["bonds"]
            }
        else:
            bonds = None
        for label in d["COHP"]:
            cohp = {
                Spin(int(spin)): np.array(d["COHP"][label][spin])
                for spin in d["COHP"][label]
            }
            try:
                icohp = {
                    Spin(int(spin)): np.array(d["ICOHP"][label][spin])
                    for spin in d["ICOHP"][label]
                }
            except KeyError:
                icohp = None
            if label == "average":
                avg_cohp = Cohp(efermi, energies, cohp, icohp=icohp)
            else:
                cohp_dict[label] = Cohp(efermi, energies, cohp, icohp=icohp)
        if "average" not in d["COHP"].keys():
            # calculate average
            cohp = np.array([np.array(c)
                             for c in d["COHP"].values()]).mean(axis=0)
            try:
                icohp = np.array([np.array(c)
                                  for c in d["ICOHP"].values()]).mean(axis=0)
            except KeyError:
                icohp = None
            avg_cohp = Cohp(efermi, energies, cohp, icohp=icohp)

        return CompleteCohp(structure,
                            avg_cohp,
                            cohp_dict,
                            bonds=bonds,
                            are_coops=d["are_coops"])
Example #36
0
    def from_dict(cls, d):
        """
        Returns CompleteDos object from dict representation.
        """
        tdos = PhononDos.from_dict(d)
        struct = Structure.from_dict(d["structure"])
        pdoss = {}
        for at, pdos in zip(struct, d["pdos"]):
            pdoss[at] = pdos

        return cls(struct, tdos, pdoss)
Example #37
0
 def from_dict(cls, d):
     """
     :param d: Dict representation
     :return: SymmetrizedStructure
     """
     return SymmetrizedStructure(
         Structure.from_dict(d["structure"]),
         spacegroup=d["spacegroup"],
         equivalent_positions=d["equivalent_positions"],
         wyckoff_letters=d["wyckoff_letters"],
     )
Example #38
0
def example_maker():
        struct=Structure.from_dict(json.loads(open("PbTiO3.json",'r').read()))
        make_vasp_dielectric_files(struct, user_settings=loadfn('vasp_settings.yaml'))
        make_vasp_defect_files(ChargedDefectsStructures(struct,
            max_min_oxi={'Pb':(0,2),'Ti':(0,4),'O':(-2,0),'Al':(3,4),'V':(3,4),
                "Cr":(3,4),'Ga':(3,4),'Fe':(3,4),'Co':(3,4),'Ni':(3,4),
                'K':(1,2),'Na':(1,2),"N":(-3,-2)},
            substitutions={'Pb':['Na','K'],
                'Ti':['Al','V','Cr','Ga','Fe','Co','Ni'],'O':['N']}, 
            oxi_states={'Pb':2,'Ti':4,'O':-2}).defects, 
            struct.composition.reduced_formula,
            user_settings=loadfn('vasp_settings.yaml'))
Example #39
0
 def from_dict(cls, d):
     struct = d['entry_bulk']['structure']
     struct = struct if isinstance(struct, Structure) \
         else Structure.from_dict(struct)
     entry_bulk = ComputedStructureEntry(struct, d['entry_bulk']['energy'])
     analyzer = DefectsAnalyzer(
         entry_bulk, d['e_vbm'],
         {Element(el): d['mu_elts'][el]
          for el in d['mu_elts']}, d['band_gap'])
     for ddict in d['defects']:
         analyzer.add_computed_defect(ComputedDefect.from_dict(ddict))
     return analyzer
Example #40
0
    def from_dict(cls, d):
        """
        keys are

        pymatgen_structure
        """
        pstructure = Structure.from_dict(d['clean_unwrap_structure'])
        try:
            occu = d['occu']
        except KeyError:
            occu = 1.0
        return cls.from_pstructure(pstructure, occu)
Example #41
0
    def from_dict(cls, d):
        """
        Create from dict.

        Args:
            A dict with all data for a band structure object.

        Returns:
            A BandStructure 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 isinstance(list(d["bands"].values())[0], dict):
            eigenvals = {
                Spin(int(k)): np.array(d["bands"][k]["data"])
                for k in d["bands"]
            }
        else:
            eigenvals = {Spin(int(k)): d["bands"][k] for k in d["bands"]}

        if "structure" in d:
            structure = Structure.from_dict(d["structure"])

        try:
            if d.get("projections"):
                if isinstance(d["projections"]["1"][0][0], dict):
                    raise ValueError(
                        "Old band structure dict format detected!")
                projections = {
                    Spin(int(spin)): np.array(v)
                    for spin, v in d["projections"].items()
                }

            return cls(
                d["kpoints"],
                eigenvals,
                Lattice(d["lattice_rec"]["matrix"]),
                d["efermi"],
                labels_dict,
                structure=structure,
                projections=projections,
            )

        except Exception:
            warnings.warn("Trying from_dict failed. Now we are trying the old "
                          "format. Please convert your BS dicts to the new "
                          "format. The old format will be retired in pymatgen "
                          "5.0.")
            return cls.from_old_dict(d)
Example #42
0
    def from_dict(cls, d):
        lattice = Lattice.from_dict(d["lattice"])
        sites = [PeriodicSite.from_dict(sd, lattice) for sd in d["sites"]]
        s = Structure.from_sites(sites)

        return Slab(
            lattice=lattice,
            species=s.species_and_occu, coords=s.frac_coords,
            miller_index=d["miller_index"],
            oriented_unit_cell=Structure.from_dict(d["oriented_unit_cell"]),
            shift=d["shift"], scale_factor=d["scale_factor"],
            site_properties=s.site_properties, energy=d["energy"]
        )
Example #43
0
    def setUpClass(cls):
        cls.Mn3Al = pd.read_json(os.path.join(test_dir, "Mn3Al.json"))
        cls.db_file = ""
        cls.uuid = 1
        cls.structures = [Structure.from_dict(s) for s in cls.Mn3Al.structure]
        cls.parent_structure = cls.structures[0]
        cls.energies = [
            e * len(cls.parent_structure) for e in cls.Mn3Al.energy_per_atom
        ]
        cls.heisenberg_settings = {"cutoff": 3.0, "tol": 0.04}
        cls.db_file = os.path.join(db_dir, "db.json")

        new_fw_spec = {"_fw_env": {"db_file": os.path.join(db_dir, "db.json")}}
Example #44
0
    def from_dict(cls, d):
        lattice = Lattice.from_dict(d["lattice"])
        sites = [PeriodicSite.from_dict(sd, lattice) for sd in d["sites"]]
        s = Structure.from_sites(sites)

        return Slab(
            lattice=lattice,
            species=s.species_and_occu, coords=s.frac_coords,
            miller_index=d["miller_index"],
            oriented_unit_cell=Structure.from_dict(d["oriented_unit_cell"]),
            shift=d["shift"], scale_factor=d["scale_factor"],
            site_properties=s.site_properties, energy=d["energy"]
        )
Example #45
0
    def setUp(self):

        with open(
                os.path.join(PymatgenTest.TEST_FILES_DIR,
                             "LobsterCompleteDos_spin.json")) as f:
            data_spin = json.load(f)
        self.LobsterCompleteDOS_spin = LobsterCompleteDos.from_dict(data_spin)

        with open(
                os.path.join(PymatgenTest.TEST_FILES_DIR,
                             "LobsterCompleteDos_nonspin.json")) as f:
            data_nonspin = json.load(f)
        self.LobsterCompleteDOS_nonspin = LobsterCompleteDos.from_dict(
            data_nonspin)

        with open(
                os.path.join(PymatgenTest.TEST_FILES_DIR,
                             "structure_KF.json")) as f:
            data_structure = json.load(f)
        self.structure = Structure.from_dict(data_structure)

        with open(
                os.path.join(PymatgenTest.TEST_FILES_DIR,
                             "LobsterCompleteDos_MnO.json")) as f:
            data_MnO = json.load(f)
        self.LobsterCompleteDOS_MnO = LobsterCompleteDos.from_dict(data_MnO)

        with open(
                os.path.join(PymatgenTest.TEST_FILES_DIR,
                             "LobsterCompleteDos_MnO_nonspin.json")) as f:
            data_MnO_nonspin = json.load(f)
        self.LobsterCompleteDOS_MnO_nonspin = LobsterCompleteDos.from_dict(
            data_MnO_nonspin)

        with open(
                os.path.join(PymatgenTest.TEST_FILES_DIR,
                             "structure_MnO.json")) as f:
            data_MnO = json.load(f)
        self.structure_MnO = Structure.from_dict(data_MnO)
Example #46
0
    def post_process(self, docs):

        s1 = Structure.from_dict(self.structure)

        m = StructureMatcher(
            ltol=self.ltol,
            stol=self.stol,
            angle_tol=self.angle_tol,
            primitive_cell=True,
            scale=True,
            attempt_supercell=False,
            comparator=ElementComparator(),
        )

        matches = []

        for doc in docs:

            s2 = Structure.from_dict(doc["structure"])
            matched = m.fit(s1, s2)

            if matched:
                rms = m.get_rms_dist(s1, s2)

                matches.append({
                    "material_id": doc["material_id"],
                    "normalized_rms_displacement": rms[0],
                    "max_distance_paired_sites": rms[1],
                })

        response = sorted(
            matches[:self.limit],
            key=lambda x: (
                x["normalized_rms_displacement"],
                x["max_distance_paired_sites"],
            ),
        )

        return response
Example #47
0
 def from_dict(cls, d):
     lattice_rec = Lattice(d['lattice_rec']['matrix'])
     eigendisplacements = np.array(
         d['eigendisplacements']['real']) + np.array(
             d['eigendisplacements']['imag']) * 1j
     structure = Structure.from_dict(
         d['structure']) if 'structure' in d else None
     return cls(d['qpoints'],
                np.array(d['bands']),
                lattice_rec,
                d['has_nac'],
                eigendisplacements,
                d['labels_dict'],
                structure=structure)
Example #48
0
 def test_propertied_structure_mod(self):
     prop_structure = Structure(
         self.structure.lattice, ["Si"] * 2, self.structure.frac_coords, site_properties={"magmom": [5, -5]}
     )
     prop_structure.append("C", [0.25, 0.25, 0.25])
     d = prop_structure.to_dict
     with warnings.catch_warnings(record=True) as w:
         # Cause all warnings to always be triggered.
         warnings.simplefilter("always")
         s2 = Structure.from_dict(d)
         self.assertEqual(len(w), 1)
         self.assertEqual(
             str(w[0].message), "Not all sites have property magmom. Missing values are set " "to None."
         )
    def from_dict(cls, d):
        # Programmatic access to enumeration members in Enum class.
        structure = d["structure"]
        if isinstance(structure, dict):
            structure = Structure.from_dict(structure)

        return cls(structure=structure,
                   xc=Xc.from_string(d["xc"]),
                   task=Task.from_string(d["task"]),
                   kpoints=d["kpoints"],
                   potcar=Potcar.from_dict(d["potcar"]),
                   incar_settings=d["incar_settings"],
                   files_to_transfer=d["files_to_transfer"],
                   **d["kwargs"])
Example #50
0
    def from_dict(cls, d):
        """
        Args:
            d (dict): Dict representation

        Returns: DiffusionAnalyzer
        """
        structure = Structure.from_dict(d["structure"])
        return cls(structure, np.array(d["displacements"]), specie=d["specie"],
                   temperature=d["temperature"], time_step=d["time_step"],
                   step_skip=d["step_skip"], min_obs=d["min_obs"],
                   smoothed=d.get("smoothed", "max"),
                   avg_nsteps=d.get("avg_nsteps", 1000),
                   lattices=np.array(d.get("lattices", [d["structure"]["lattice"]["matrix"]])))
Example #51
0
 def set_output_data(self, d_calc, d):
     """
     set the 'output' key
     """
     d["output"] = {
         "structure": d_calc["output"]["structure"],
         "density": d_calc.pop("density"),
         "energy": d_calc["output"]["energy"],
         "energy_per_atom": d_calc["output"]["energy_per_atom"]}
     d["output"].update(self.get_basic_processed_data(d))
     sg = SpacegroupAnalyzer(Structure.from_dict(d_calc["output"]["structure"]), 0.1)
     if not sg.get_symmetry_dataset():
         sg = SpacegroupAnalyzer(Structure.from_dict(d_calc["output"]["structure"]), 1e-3, 1)
     d["output"]["spacegroup"] = {
         "source": "spglib",
         "symbol": sg.get_space_group_symbol(),
         "number": sg.get_space_group_number(),
         "point_group": sg.get_point_group_symbol(),
         "crystal_system": sg.get_crystal_system(),
         "hall": sg.get_hall()}
     if d["input"]["parameters"].get("LEPSILON"):
         for k in ['epsilon_static', 'epsilon_static_wolfe', 'epsilon_ionic']:
             d["output"][k] = d_calc["output"][k]
Example #52
0
    def from_dict(cls, d):
        a = d["about"]
        dec = PMGJSONDecoder()

        created_at = dec.process_decoded(a.get("created_at"))
        data = {k: v for k, v in d["about"].items()
                if k.startswith("_")}
        data = dec.process_decoded(data)

        structure = Structure.from_dict(d) if "lattice" in d \
            else Molecule.from_dict(d)
        return cls(structure, a["authors"], projects=a.get("projects", None),
                   references=a.get("references", ""),
                   remarks=a.get("remarks", None), data=data,
                   history=a.get("history", None), created_at=created_at)
Example #53
0
def load_flla():
    # ref: F. Faber, A. Lindmaa, O.A. von Lilienfeld, R. Armiento,
    # Crystal structure representations for machine learning models
    # of formation energies, Int. J. Quantum Chem. 115 (2015) 1094–1101.
    # doi:10.1002/qua.24917.
    df = pandas.read_csv(os.path.join(module_dir, "flla_2015.csv"),
                         comment="#")
    column_headers = [
        'material_id', 'e_above_hull', 'formula', 'nsites', 'structure',
        'formation_energy', 'formation_energy_per_atom'
    ]
    df['structure'] = pandas.Series(
        [Structure.from_dict(ast.literal_eval(s)) for s in df['structure']],
        df.index)
    return df[column_headers]
Example #54
0
File: dos.py Project: tllu/pymatgen
 def from_dict(cls, d) -> "LobsterCompleteDos":
     """
     Returns: CompleteDos object from dict representation.
     """
     tdos = Dos.from_dict(d)
     struct = Structure.from_dict(d["structure"])
     pdoss = {}
     for i in range(len(d["pdos"])):
         at = struct[i]
         orb_dos = {}
         for orb_str, odos in d["pdos"][i].items():
             orb = orb_str
             orb_dos[orb] = {Spin(int(k)): v for k, v in odos["densities"].items()}
         pdoss[at] = orb_dos
     return LobsterCompleteDos(struct, tdos, pdoss)
Example #55
0
    def from_dict(cls, d):
        a = d["about"]
        dec = MontyDecoder()

        created_at = dec.process_decoded(a.get("created_at"))
        data = {k: v for k, v in d["about"].items()
                if k.startswith("_")}
        data = dec.process_decoded(data)

        structure = Structure.from_dict(d) if "lattice" in d \
            else Molecule.from_dict(d)
        return cls(structure, a["authors"], projects=a.get("projects", None),
                   references=a.get("references", ""),
                   remarks=a.get("remarks", None), data=data,
                   history=a.get("history", None), created_at=created_at)
Example #56
0
    def calc(self, item):
        """
        Calculates diffraction patterns for the structures

        Args:
            item (dict): a dict with a material_id and a structure

        Returns:
            dict: a diffraction dict
        """
        self.logger.debug("Calculating diffraction for {}".format(item[self.materials.key]))

        struct = Structure.from_dict(item['structure'])
        xrd_doc = {"xrd": self.get_xrd_from_struct(struct)}
        return xrd_doc
Example #57
0
 def test_propertied_structure_mod(self):
     prop_structure = Structure(self.structure.lattice, ["Si"] * 2,
                                self.structure.frac_coords,
                                site_properties={'magmom': [5, -5]})
     prop_structure.append("C", [0.25, 0.25, 0.25])
     d = prop_structure.to_dict
     with warnings.catch_warnings(record=True) as w:
         # Cause all warnings to always be triggered.
         warnings.simplefilter("always")
         s2 = Structure.from_dict(d)
         self.assertEqual(len(w), 1)
         self.assertEqual(
             str(w[0].message),
             'Not all sites have property magmom. Missing values are set '
             'to None.')
Example #58
0
 def from_dict(cls, d):
     """
     Returns CompleteDos object from dict representation.
     """
     tdos = Dos.from_dict(d)
     struct = Structure.from_dict(d["structure"])
     pdoss = {}
     for i in range(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)
Example #59
0
    def undo_last_change(self):
        """
        Undo the last change in the TransformedStructure.

        Raises:
            IndexError if already at the oldest change.
        """
        if len(self.history) == 0:
            raise IndexError("Can't undo. Already at oldest change.")
        if 'input_structure' not in self.history[-1]:
            raise IndexError("Can't undo. Latest history has no input_structure")
        h = self.history.pop()
        self._undone.append((h, self.final_structure))
        s = h["input_structure"]
        if isinstance(s, dict):
            s = Structure.from_dict(s)
        self.final_structure = s