def get_kpts(screener, cif_file, level): """ Obtain the number of kpoints Args: screener (class): pymofscreen.screener class cif_file (string): name of CIF file level (string): accuracy level Returns: kpts (list of ints): kpoint grid gamma (bool): True for gamma-centered """ niggli = screener.niggli mofpath = screener.mofpath kpts_path = screener.kpts_path kppas = screener.kppas kpts = None if not mofpath: mofpath = '' if kpts_path == 'Auto': if level == 'low': kppa = kppas[0] elif level == 'high': kppa = kppas[1] else: raise ValueError('kpoints accuracy level not defined') filepath = os.path.join(mofpath, cif_file) if '.cif' in cif_file: parser = CifParser(filepath) pm_mof = parser.get_structures(primitive=niggli)[0] else: pm_mof = pm.Structure.from_file(filepath, primitive=niggli) pm_kpts = Kpoints.automatic_density(pm_mof, kppa) kpts = pm_kpts.kpts[0] if pm_kpts.style.name == 'Gamma': gamma = True else: gamma = None else: old_cif_name = cif_file.split('.cif')[0].split('_')[0] infile = open(kpts_path, 'r') lines = infile.read().splitlines() infile.close() for i in range(len(lines)): if old_cif_name in lines[i]: if level == 'low': kpts = lines[i + 1] gamma = lines[i + 2] elif level == 'high': kpts = lines[i + 3] gamma = lines[i + 4] else: raise ValueError('Incompatible KPPA with prior runs') break kpts = np.squeeze(np.asarray(np.matrix(kpts))).tolist() if not kpts or len(kpts) != 3: raise ValueError('Error parsing k-points for ' + cif_file) if gamma == 'True': gamma = True elif gamma == 'False': gamma = False else: raise ValueError('Error parsing gamma for ' + cif_file) return kpts, gamma
def cif_structure(file_name): parser = CifParser(file_name) structure = parser.get_structures()[0] return structure
def test_get_primitive_standard_structure(self): parser = CifParser( os.path.join(PymatgenTest.TEST_FILES_DIR, "bcc_1927.cif")) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) prim = s.get_primitive_standard_structure() self.assertAlmostEqual(prim.lattice.alpha, 109.47122063400001) self.assertAlmostEqual(prim.lattice.beta, 109.47122063400001) self.assertAlmostEqual(prim.lattice.gamma, 109.47122063400001) self.assertAlmostEqual(prim.lattice.a, 7.9657251015812145) self.assertAlmostEqual(prim.lattice.b, 7.9657251015812145) self.assertAlmostEqual(prim.lattice.c, 7.9657251015812145) parser = CifParser( os.path.join(PymatgenTest.TEST_FILES_DIR, "btet_1915.cif")) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) prim = s.get_primitive_standard_structure() self.assertAlmostEqual(prim.lattice.alpha, 105.015053349) self.assertAlmostEqual(prim.lattice.beta, 105.015053349) self.assertAlmostEqual(prim.lattice.gamma, 118.80658411899999) self.assertAlmostEqual(prim.lattice.a, 4.1579321075608791) self.assertAlmostEqual(prim.lattice.b, 4.1579321075608791) self.assertAlmostEqual(prim.lattice.c, 4.1579321075608791) parser = CifParser( os.path.join(PymatgenTest.TEST_FILES_DIR, "orci_1010.cif")) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) prim = s.get_primitive_standard_structure() self.assertAlmostEqual(prim.lattice.alpha, 134.78923546600001) self.assertAlmostEqual(prim.lattice.beta, 105.856239333) self.assertAlmostEqual(prim.lattice.gamma, 91.276341676000001) self.assertAlmostEqual(prim.lattice.a, 3.8428217771014852) self.assertAlmostEqual(prim.lattice.b, 3.8428217771014852) self.assertAlmostEqual(prim.lattice.c, 3.8428217771014852) parser = CifParser( os.path.join(PymatgenTest.TEST_FILES_DIR, "orcc_1003.cif")) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) prim = s.get_primitive_standard_structure() self.assertAlmostEqual(prim.lattice.alpha, 90) self.assertAlmostEqual(prim.lattice.beta, 90) self.assertAlmostEqual(prim.lattice.gamma, 164.985257335) self.assertAlmostEqual(prim.lattice.a, 15.854897098324196) self.assertAlmostEqual(prim.lattice.b, 15.854897098324196) self.assertAlmostEqual(prim.lattice.c, 3.99648651) parser = CifParser( os.path.join(PymatgenTest.TEST_FILES_DIR, "orac_632475.cif")) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) prim = s.get_primitive_standard_structure() self.assertAlmostEqual(prim.lattice.alpha, 90) self.assertAlmostEqual(prim.lattice.beta, 90) self.assertAlmostEqual(prim.lattice.gamma, 144.40557588533386) self.assertAlmostEqual(prim.lattice.a, 5.2005185662155391) self.assertAlmostEqual(prim.lattice.b, 5.2005185662155391) self.assertAlmostEqual(prim.lattice.c, 3.5372412099999999) parser = CifParser( os.path.join(PymatgenTest.TEST_FILES_DIR, "monoc_1028.cif")) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) prim = s.get_primitive_standard_structure() self.assertAlmostEqual(prim.lattice.alpha, 63.579155761999999) self.assertAlmostEqual(prim.lattice.beta, 116.42084423747779) self.assertAlmostEqual(prim.lattice.gamma, 148.47965136208569) self.assertAlmostEqual(prim.lattice.a, 7.2908007159612325) self.assertAlmostEqual(prim.lattice.b, 7.2908007159612325) self.assertAlmostEqual(prim.lattice.c, 6.8743926325200002) parser = CifParser( os.path.join(PymatgenTest.TEST_FILES_DIR, "hex_1170.cif")) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) prim = s.get_primitive_standard_structure() self.assertAlmostEqual(prim.lattice.alpha, 90) self.assertAlmostEqual(prim.lattice.beta, 90) self.assertAlmostEqual(prim.lattice.gamma, 120) self.assertAlmostEqual(prim.lattice.a, 3.699919902005897) self.assertAlmostEqual(prim.lattice.b, 3.699919902005897) self.assertAlmostEqual(prim.lattice.c, 6.9779585500000003) parser = CifParser( os.path.join(PymatgenTest.TEST_FILES_DIR, "rhomb_3478_conv.cif")) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) prim = s.get_primitive_standard_structure() self.assertAlmostEqual(prim.lattice.alpha, 28.049186140546812) self.assertAlmostEqual(prim.lattice.beta, 28.049186140546812) self.assertAlmostEqual(prim.lattice.gamma, 28.049186140546812) self.assertAlmostEqual(prim.lattice.a, 5.9352627428399982) self.assertAlmostEqual(prim.lattice.b, 5.9352627428399982) self.assertAlmostEqual(prim.lattice.c, 5.9352627428399982) parser = CifParser( os.path.join(PymatgenTest.TEST_FILES_DIR, "rhomb_3478_conv.cif")) structure = parser.get_structures(False)[0] structure.add_site_property("magmom", [1.0] * len(structure)) s = SpacegroupAnalyzer(structure, symprec=1e-2) prim = s.get_primitive_standard_structure(keep_site_properties=True) self.assertEqual(prim.site_properties["magmom"], [1.0] * len(prim)) parser = CifParser( os.path.join(PymatgenTest.TEST_FILES_DIR, "rhomb_3478_conv.cif")) structure = parser.get_structures(False)[0] structure.add_site_property("magmom", [1.0] * len(structure)) s = SpacegroupAnalyzer(structure, symprec=1e-2) prim = s.get_primitive_standard_structure(keep_site_properties=False) self.assertEqual(prim.site_properties.get("magmom", None), None)
def setUpClass(cls): r = CifParser(os.path.join(test_dir, "CoO19128.cif")) cls.structure = r.get_structures()[0] cls.atoms = Atoms(cls.structure, "O", 10.0)
def cif_structure(self, file_name): parser = CifParser(file_name) structure = parser.get_structures()[0] # parse.close() return structure
def test_CifParserSpringerPauling(self): with warnings.catch_warnings(): warnings.simplefilter("ignore") # Below are 10 tests for CIFs from the Springer Materials/Pauling file DBs. # Partial occupancy on sites, incorrect label, previously unparsable parser = CifParser(self.TEST_FILES_DIR / 'PF_sd_1928405.cif') for s in parser.get_structures(True): self.assertEqual(s.formula, "Er1 Mn3.888 Fe2.112 Sn6") self.assertTrue(parser.has_errors) # Partial occupancy on sites, previously parsed as an ordered structure parser = CifParser(self.TEST_FILES_DIR / 'PF_sd_1011081.cif') for s in parser.get_structures(True): self.assertEqual(s.formula, "Zr0.2 Nb0.8") self.assertTrue(parser.has_errors) # Partial occupancy on sites, incorrect label, previously unparsable parser = CifParser(self.TEST_FILES_DIR / 'PF_sd_1615854.cif') for s in parser.get_structures(True): self.assertEqual(s.formula, "Na2 Al2 Si6 O16") self.assertTrue(parser.has_errors) # Partial occupancy on sites, incorrect label, previously unparsable parser = CifParser(self.TEST_FILES_DIR / 'PF_sd_1622133.cif') for s in parser.get_structures(True): self.assertEqual(s.formula, "Ca0.184 Mg13.016 Fe2.8 Si16 O48") self.assertTrue(parser.has_errors) # Partial occupancy on sites, previously parsed as an ordered structure parser = CifParser(self.TEST_FILES_DIR / 'PF_sd_1908491.cif') for s in parser.get_structures(True): self.assertEqual(s.formula, "Mn0.48 Zn0.52 Ga2 Se4") self.assertTrue(parser.has_errors) # Partial occupancy on sites, incorrect label, previously unparsable parser = CifParser(self.TEST_FILES_DIR / 'PF_sd_1811457.cif') for s in parser.get_structures(True): self.assertEqual(s.formula, "Ba2 Mg0.6 Zr0.2 Ta1.2 O6") self.assertTrue(parser.has_errors) # Incomplete powder diffraction data, previously unparsable # This CIF file contains the molecular species "NH3" which is # parsed as "N" because the label is "N{x}" (x = 1,2,..) and the # corresponding symbol is "NH3". Since, the label and symbol are switched # in CIFs from Springer Materials/Pauling file DBs, CifParser parses the # element as "N". parser = CifParser(self.TEST_FILES_DIR / 'PF_sd_1002871.cif') self.assertEqual(parser.get_structures(True)[0].formula, "Cu1 Br2 N6") self.assertEqual(parser.get_structures(True)[1].formula, "Cu1 Br4 N6") self.assertTrue(parser.has_errors) # Incomplete powder diffraction data, previously unparsable parser = CifParser(self.TEST_FILES_DIR / 'PF_sd_1704003.cif') for s in parser.get_structures(): self.assertEqual(s.formula, "Rb4 Mn2 F12") self.assertTrue(parser.has_errors) # Unparsable species 'OH/OH2', previously parsed as "O" parser = CifParser(self.TEST_FILES_DIR / 'PF_sd_1500382.cif') for s in parser.get_structures(): self.assertEqual(s.formula, "Mg6 B2 O6 F1.764") self.assertTrue(parser.has_errors) # Unparsable species 'OH/OH2', previously parsed as "O" parser = CifParser(self.TEST_FILES_DIR / 'PF_sd_1601634.cif') for s in parser.get_structures(): self.assertEqual(s.formula, "Zn1.29 Fe0.69 As2 Pb1.02 O8")
def test_primes(self): with warnings.catch_warnings(): warnings.simplefilter("ignore") parser = CifParser(self.TEST_FILES_DIR / 'C26H16BeN2O2S2.cif') for s in parser.get_structures(False): self.assertEqual(s.composition, 8 * Composition('C26H16BeN2O2S2'))
def test_no_symmops(self): f = os.path.join(test_dir, "nosymm.cif") p = CifParser(f) s = p.get_structures()[0] self.assertEqual(s.formula, "H96 C60 O8")
def process_precomputed_core( name, loggerobject=None, ): """ The main function that generates the data to be sent back to the view. :param name: The structure name (CSD reference code) (string) :param loggerobject: if not None, should be a valid logger, that is used to output useful log messages. :return: this function calls directly flask methods and returns flask objects :raise: FlaskRedirectException if there is an error that requires to redirect the the main selection page. The Exception message is the message to be flashed via Flask (or in general shown to the user). """ loggerobject.debug("dealing with {}".format(name)) start_time = time.time() try: loggerobject.debug("building path") structurefilepath = os.path.join( THIS_DIR, "compute", "precomputed", "structures", name + ".cif" ) loggerobject.debug("structurefilepath is {}".format(structurefilepath)) s = CifParser(structurefilepath, occupancy_tolerance=100).get_structures()[0] loggerobject.debug("read pymatgen structure") structure_tuple = tuple_from_pymatgen(s) loggerobject.debug("generated structure tuple") except Exception as excep: # pylint:disable=broad-except # There was an exception... logger.debug("Exception {} when parsing the input".format(excep)) raise FlaskRedirectException( "I tried my best, but I wasn't able to load your " "file in format because of {}".format(excep) ) from excep parsing_time = start_time - time.time() logger.debug("Successfully read structure in {}".format(parsing_time)) # Now, read the precomputed results try: logger.debug("reading pickle") precomputed_dict = load_pickle( os.path.join( THIS_DIR, "compute", "precomputed", "precomputed", name + ".pkl" ) ) # feature_array = precomputed_dict["feature_array"] feature_value_dict = precomputed_dict["feature_value_dict"] metal_indices = precomputed_dict["metal_indices"] # feature_names = precomputed_dict["feature_names"] # metal_sites = precomputed_dict["metal_sites"] predictions_output = precomputed_dict["predictions_output"] prediction_labels = precomputed_dict["prediction_labels"] featurization_output = precomputed_dict["featurization_output"] except Exception as excep: # pylint:disable=broad-except, invalid-name logger.debug("Exception {} when parsing the input".format(excep)) raise FlaskRedirectException( "I tried my best, but I wasn't able to load your " "result for '{}'... because of {}".format(name, excep) ) from excep logger.debug("Successfully read pickle with precomputed results") try: in_json_data = { "cell": structure_tuple[0], "scaled_coords": structure_tuple[1], "atomic_numbers": structure_tuple[2], } path_results = get_json_for_visualizer(s) raw_code_dict = copy.copy(path_results) raw_code_dict["primitive_lattice"] = path_results["primitive_lattice"].tolist() raw_code_dict["primitive_positions"] = path_results[ "primitive_positions" ].tolist() inputstructure_positions_cartesian = np.dot( np.array(in_json_data["scaled_coords"]), np.array(in_json_data["cell"]) ).tolist() primitive_positions_cartesian = np.dot( np.array(path_results["primitive_positions"]), np.array(path_results["primitive_lattice"]), ).tolist() primitive_positions_cartesian_refolded = np.dot( np.array(path_results["primitive_positions"]) % 1.0, np.array(path_results["primitive_lattice"]), ).tolist() raw_code_dict["primitive_positions_cartesian"] = primitive_positions_cartesian raw_code_dict["primitive_types"] = path_results["primitive_types"].tolist() primitive_symbols = [ chemical_symbols[num] for num in path_results["primitive_types"] ] raw_code_dict["primitive_symbols"] = primitive_symbols raw_code = json.dumps(raw_code_dict, indent=2) raw_code = ( str(jinja2.escape(raw_code)).replace("\n", "<br>").replace(" ", " ") ) inputstructure_cell_vectors = [ [idx, coords[0], coords[1], coords[2]] for idx, coords in enumerate(in_json_data["cell"], start=1) ] inputstructure_symbols = [ chemical_symbols[num] for num in in_json_data["atomic_numbers"] ] inputstructure_atoms_scaled = [ [label, coords[0], coords[1], coords[2]] for label, coords in zip( inputstructure_symbols, in_json_data["scaled_coords"] ) ] inputstructure_atoms_cartesian = [ [label, coords[0], coords[1], coords[2]] for label, coords in zip( inputstructure_symbols, inputstructure_positions_cartesian ) ] atoms_scaled = [ [label, coords[0], coords[1], coords[2]] for label, coords in zip( primitive_symbols, path_results["primitive_positions"] ) ] atoms_cartesian = [ [label, coords[0], coords[1], coords[2]] for label, coords in zip(primitive_symbols, primitive_positions_cartesian) ] direct_vectors = [ [idx, coords[0], coords[1], coords[2]] for idx, coords in enumerate(path_results["primitive_lattice"], start=1) ] primitive_lattice = path_results["primitive_lattice"] xsfstructure = [] xsfstructure.append("CRYSTAL") xsfstructure.append("PRIMVEC") for vector in primitive_lattice: xsfstructure.append("{} {} {}".format(vector[0], vector[1], vector[2])) xsfstructure.append("PRIMCOORD") xsfstructure.append("{} 1".format(len(primitive_positions_cartesian_refolded))) for atom_num, pos in zip( path_results["primitive_types"], primitive_positions_cartesian_refolded ): xsfstructure.append("{} {} {} {}".format(atom_num, pos[0], pos[1], pos[2])) xsfstructure = "\n".join(xsfstructure) compute_time = time.time() - start_time except Exception as excep: # pylint:disable=broad-except logger.debug("Exception {} when parsing the input".format(excep)) return dict( raw_code=raw_code, prediction_labels=prediction_labels, metal_indices=metal_indices, predictions_output=predictions_output, featurization_output=featurization_output, inputstructure_cell_vectors=inputstructure_cell_vectors, inputstructure_atoms_scaled=inputstructure_atoms_scaled, inputstructure_atoms_cartesian=inputstructure_atoms_cartesian, atoms_scaled=atoms_scaled, direct_vectors=direct_vectors, atoms_cartesian=atoms_cartesian, compute_time=compute_time, model_version=MODEL_VERSION, xsfstructure=xsfstructure, feature_values=feature_value_dict, warning="", )
def test_missing_atom_site_type_with_oxistates(self): parser = CifParser(os.path.join(test_dir, 'P24Ru4H252C296S24N16.cif')) c = Composition({'S0+': 24, 'Ru0+': 4, 'H0+': 252, 'C0+': 296, 'N0+': 16, 'P0+': 24}) for s in parser.get_structures(False): self.assertEqual(s.composition, c)
def test_one_line_symm(self): f = os.path.join(test_dir, "OneLineSymmP1.cif") p = CifParser(f) s = p.get_structures()[0] self.assertEqual(s.formula, "Ga4 Pb2 O8")
def test_primes(self): parser = CifParser(os.path.join(test_dir, 'C26H16BeN2O2S2.cif')) for s in parser.get_structures(False): self.assertEqual(s.composition, 8 * Composition('C26H16BeN2O2S2'))
def test_CifParser(self): parser = CifParser(os.path.join(test_dir, 'LiFePO4.cif')) for s in parser.get_structures(True): self.assertEqual(s.formula, "Li4 Fe4 P4 O16", "Incorrectly parsed cif.") parser = CifParser(os.path.join(test_dir, 'V2O3.cif')) for s in parser.get_structures(True): self.assertEqual(s.formula, "V4 O6") parser = CifParser(os.path.join(test_dir, 'Li2O.cif')) prim = parser.get_structures(True)[0] self.assertEqual(prim.formula, "Li2 O1") conv = parser.get_structures(False)[0] self.assertEqual(conv.formula, "Li8 O4") #test for disordered structures parser = CifParser(os.path.join(test_dir, 'Li10GeP2S12.cif')) for s in parser.get_structures(True): self.assertEqual(s.formula, "Li20.2 Ge2.06 P3.94 S24", "Incorrectly parsed cif.") cif_str = """#\#CIF1.1 ########################################################################## # Crystallographic Information Format file # Produced by PyCifRW module # # This is a CIF file. CIF has been adopted by the International # Union of Crystallography as the standard for data archiving and # transmission. # # For information on this file format, follow the CIF links at # http://www.iucr.org ########################################################################## data_FePO4 _symmetry_space_group_name_H-M 'P 1' _cell_length_a 10.4117668699 _cell_length_b 6.06717187997 _cell_length_c 4.75948953998 loop_ # sometimes this is in a loop (incorrectly) _cell_angle_alpha 91.0 _cell_angle_beta 92.0 _cell_angle_gamma 93.0 _chemical_name_systematic 'Generated by pymatgen' _symmetry_Int_Tables_number 1 _chemical_formula_structural FePO4 _chemical_formula_sum 'Fe4 P4 O16' _cell_volume 300.65685512 _cell_formula_units_Z 4 loop_ _symmetry_equiv_pos_site_id _symmetry_equiv_pos_as_xyz 1 'x, y, z' loop_ _atom_site_type_symbol _atom_site_label _atom_site_symmetry_multiplicity _atom_site_fract_x _atom_site_fract_y _atom_site_fract_z _atom_site_attached_hydrogens _atom_site_B_iso_or_equiv _atom_site_occupancy Fe Fe1 1 0.218728 0.750000 0.474867 0 . 1 Fe JJ2 1 0.281272 0.250000 0.974867 0 . 1 # there's a typo here, parser should read the symbol from the # _atom_site_type_symbol Fe Fe3 1 0.718728 0.750000 0.025133 0 . 1 Fe Fe4 1 0.781272 0.250000 0.525133 0 . 1 P P5 1 0.094613 0.250000 0.418243 0 . 1 P P6 1 0.405387 0.750000 0.918243 0 . 1 P P7 1 0.594613 0.250000 0.081757 0 . 1 P P8 1 0.905387 0.750000 0.581757 0 . 1 O O9 1 0.043372 0.750000 0.707138 0 . 1 O O10 1 0.096642 0.250000 0.741320 0 . 1 O O11 1 0.165710 0.046072 0.285384 0 . 1 O O12 1 0.165710 0.453928 0.285384 0 . 1 O O13 1 0.334290 0.546072 0.785384 0 . 1 O O14 1 0.334290 0.953928 0.785384 0 . 1 O O15 1 0.403358 0.750000 0.241320 0 . 1 O O16 1 0.456628 0.250000 0.207138 0 . 1 O O17 1 0.543372 0.750000 0.792862 0 . 1 O O18 1 0.596642 0.250000 0.758680 0 . 1 O O19 1 0.665710 0.046072 0.214616 0 . 1 O O20 1 0.665710 0.453928 0.214616 0 . 1 O O21 1 0.834290 0.546072 0.714616 0 . 1 O O22 1 0.834290 0.953928 0.714616 0 . 1 O O23 1 0.903358 0.750000 0.258680 0 . 1 O O24 1 0.956628 0.250000 0.292862 0 . 1 """ parser = CifParser.from_string(cif_str) struct = parser.get_structures(primitive=False)[0] self.assertEqual(struct.formula, "Fe4 P4 O16", "Incorrectly parsed cif.") self.assertAlmostEqual(struct.lattice.a, 10.4117668699) self.assertAlmostEqual(struct.lattice.b, 6.06717187997) self.assertAlmostEqual(struct.lattice.c, 4.75948953998) self.assertAlmostEqual(struct.lattice.alpha, 91) self.assertAlmostEqual(struct.lattice.beta, 92) self.assertAlmostEqual(struct.lattice.gamma, 93) with warnings.catch_warnings(): warnings.simplefilter("ignore") parser = CifParser(os.path.join(test_dir, 'srycoo.cif')) self.assertEqual(parser.get_structures()[0].formula, "Sr5.6 Y2.4 Co8 O21") # Test with a decimal Xyz. This should parse as two atoms in # conventional cell if it is correct, one if not. parser = CifParser(os.path.join(test_dir, "Fe.cif")) self.assertEqual(len(parser.get_structures(primitive=False)[0]), 2) # Below are 10 tests for CIFs from the Springer Materials/Pauling file DBs. # Partial occupancy on sites, incorrect label, previously unparsable parser = CifParser(os.path.join(test_dir, 'PF_sd_1928405.cif')) for s in parser.get_structures(True): self.assertEqual(s.formula, "Er1 Mn3.888 Fe2.112 Sn6") # Partial occupancy on sites, previously parsed as an ordered structure parser = CifParser(os.path.join(test_dir, 'PF_sd_1011081.cif')) for s in parser.get_structures(True): self.assertEqual(s.formula, "Zr0.2 Nb0.8") # Partial occupancy on sites, incorrect label, previously unparsable parser = CifParser(os.path.join(test_dir, 'PF_sd_1615854.cif')) for s in parser.get_structures(True): self.assertEqual(s.formula, "Na2 Al2 Si6 O16") # Partial occupancy on sites, incorrect label, previously unparsable parser = CifParser(os.path.join(test_dir, 'PF_sd_1622133.cif')) for s in parser.get_structures(True): self.assertEqual(s.formula, "Ca0.184 Mg13.016 Fe2.8 Si16 O48") # Partial occupancy on sites, previously parsed as an ordered structure parser = CifParser(os.path.join(test_dir, 'PF_sd_1908491.cif')) for s in parser.get_structures(True): self.assertEqual(s.formula, "Mn0.48 Zn0.52 Ga2 Se4") # Partial occupancy on sites, incorrect label, previously unparsable parser = CifParser(os.path.join(test_dir, 'PF_sd_1811457.cif')) for s in parser.get_structures(True): self.assertEqual(s.formula, "Ba2 Mg0.6 Zr0.2 Ta1.2 O6") # Incomplete powder diffraction data, previously unparsable # This CIF file contains the molecular species "NH3" which is # parsed as "N" because the label is "N{x}" (x = 1,2,..) and the # corresponding symbol is "NH3". Since, the label and symbol are switched # in CIFs from Springer Materials/Pauling file DBs, CifParser parses the # element as "N". parser = CifParser(os.path.join(test_dir, 'PF_sd_1002871.cif')) self.assertEqual(parser.get_structures(True)[0].formula, "Cu1 Br2 N6") self.assertEqual(parser.get_structures(True)[1].formula, "Cu1 Br4 N6") # Incomplete powder diffraction data, previously unparsable parser = CifParser(os.path.join(test_dir, 'PF_sd_1704003.cif')) for s in parser.get_structures(): self.assertEqual(s.formula, "Rb4 Mn2 F12") # Unparsable species 'OH/OH2', previously parsed as "O" parser = CifParser(os.path.join(test_dir, 'PF_sd_1500382.cif')) for s in parser.get_structures(): self.assertEqual(s.formula, "Mg6 B2 O6 F1.764") # Unparsable species 'OH/OH2', previously parsed as "O" parser = CifParser(os.path.join(test_dir, 'PF_sd_1601634.cif')) for s in parser.get_structures(): self.assertEqual(s.formula, "Zn1.29 Fe0.69 As2 Pb1.02 O8")
utm_medium=organic&utm_source=google_rich_qa&utm_campai gn=google_rich_qa ''' return [atoi(c) for c in re.split('(\d+)', text)] # #################################################### filelist.sort(key=natural_keys) print(filelist) i = 0 for file in filelist: i = i + 1 file_cif = file + '.cif' structure_parser = CifParser(file_cif) # print(structure_parser) structure = structure_parser.get_structures( primitive=False) # use False without using primitive cell # print(structure) structure[0].to(filename='POSCAR') for filename in os.listdir("."): if filename == 'POSCAR': os.rename(filename, filename + '_' + str(i - 1)) # filename = input('input the cif file: ') # structure_parser = CifParser(filename) # print(structure_parser) # structure = structure_parser.get_structures() # print(structure) # structure[0].to(filename='POSCAR')
def test_CifParser(self): parser = CifParser(self.TEST_FILES_DIR / 'LiFePO4.cif') for s in parser.get_structures(True): self.assertEqual(s.formula, "Li4 Fe4 P4 O16", "Incorrectly parsed cif.") parser = CifParser(self.TEST_FILES_DIR / 'V2O3.cif') for s in parser.get_structures(True): self.assertEqual(s.formula, "V4 O6") bibtex_str = """ @article{cifref0, author = "Andersson, G.", title = "Studies on vanadium oxides. I. Phase analysis", journal = "Acta Chemica Scandinavica (1-27,1973-42,1988)", volume = "8", year = "1954", pages = "1599--1606" } """ self.assertEqual(parser.get_bibtex_string().strip(), bibtex_str.strip()) parser = CifParser(self.TEST_FILES_DIR / 'Li2O.cif') prim = parser.get_structures(True)[0] self.assertEqual(prim.formula, "Li2 O1") conv = parser.get_structures(False)[0] self.assertEqual(conv.formula, "Li8 O4") # test for disordered structures parser = CifParser(self.TEST_FILES_DIR / 'Li10GeP2S12.cif') for s in parser.get_structures(True): self.assertEqual(s.formula, "Li20.2 Ge2.06 P3.94 S24", "Incorrectly parsed cif.") cif_str = """#\#CIF1.1 ########################################################################## # Crystallographic Information Format file # Produced by PyCifRW module # # This is a CIF file. CIF has been adopted by the International # Union of Crystallography as the standard for data archiving and # transmission. # # For information on this file format, follow the CIF links at # http://www.iucr.org ########################################################################## data_FePO4 _symmetry_space_group_name_H-M 'P 1' _cell_length_a 10.4117668699 _cell_length_b 6.06717187997 _cell_length_c 4.75948953998 loop_ # sometimes this is in a loop (incorrectly) _cell_angle_alpha 91.0 _cell_angle_beta 92.0 _cell_angle_gamma 93.0 _chemical_name_systematic 'Generated by pymatgen' _symmetry_Int_Tables_number 1 _chemical_formula_structural FePO4 _chemical_formula_sum 'Fe4 P4 O16' _cell_volume 300.65685512 _cell_formula_units_Z 4 loop_ _symmetry_equiv_pos_site_id _symmetry_equiv_pos_as_xyz 1 'x, y, z' loop_ _atom_site_type_symbol _atom_site_label _atom_site_symmetry_multiplicity _atom_site_fract_x _atom_site_fract_y _atom_site_fract_z _atom_site_attached_hydrogens _atom_site_B_iso_or_equiv _atom_site_occupancy Fe Fe1 1 0.218728 0.750000 0.474867 0 . 1 Fe JJ2 1 0.281272 0.250000 0.974867 0 . 1 # there's a typo here, parser should read the symbol from the # _atom_site_type_symbol Fe Fe3 1 0.718728 0.750000 0.025133 0 . 1 Fe Fe4 1 0.781272 0.250000 0.525133 0 . 1 P P5 1 0.094613 0.250000 0.418243 0 . 1 P P6 1 0.405387 0.750000 0.918243 0 . 1 P P7 1 0.594613 0.250000 0.081757 0 . 1 P P8 1 0.905387 0.750000 0.581757 0 . 1 O O9 1 0.043372 0.750000 0.707138 0 . 1 O O10 1 0.096642 0.250000 0.741320 0 . 1 O O11 1 0.165710 0.046072 0.285384 0 . 1 O O12 1 0.165710 0.453928 0.285384 0 . 1 O O13 1 0.334290 0.546072 0.785384 0 . 1 O O14 1 0.334290 0.953928 0.785384 0 . 1 O O15 1 0.403358 0.750000 0.241320 0 . 1 O O16 1 0.456628 0.250000 0.207138 0 . 1 O O17 1 0.543372 0.750000 0.792862 0 . 1 O O18 1 0.596642 0.250000 0.758680 0 . 1 O O19 1 0.665710 0.046072 0.214616 0 . 1 O O20 1 0.665710 0.453928 0.214616 0 . 1 O O21 1 0.834290 0.546072 0.714616 0 . 1 O O22 1 0.834290 0.953928 0.714616 0 . 1 O O23 1 0.903358 0.750000 0.258680 0 . 1 O O24 1 0.956628 0.250000 0.292862 0 . 1 """ parser = CifParser.from_string(cif_str) struct = parser.get_structures(primitive=False)[0] self.assertEqual(struct.formula, "Fe4 P4 O16") self.assertAlmostEqual(struct.lattice.a, 10.4117668699) self.assertAlmostEqual(struct.lattice.b, 6.06717187997) self.assertAlmostEqual(struct.lattice.c, 4.75948953998) self.assertAlmostEqual(struct.lattice.alpha, 91) self.assertAlmostEqual(struct.lattice.beta, 92) self.assertAlmostEqual(struct.lattice.gamma, 93) with warnings.catch_warnings(): warnings.simplefilter("ignore") parser = CifParser(self.TEST_FILES_DIR / 'srycoo.cif') self.assertEqual(parser.get_structures()[0].formula, "Sr5.6 Y2.4 Co8 O21") # Test with a decimal Xyz. This should parse as two atoms in # conventional cell if it is correct, one if not. parser = CifParser(self.TEST_FILES_DIR / "Fe.cif") self.assertEqual(len(parser.get_structures(primitive=False)[0]), 2) self.assertFalse(parser.has_errors)
def test_get_primitive_standard_structure(self): parser = CifParser(os.path.join(test_dir, 'bcc_1927.cif')) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) prim = s.get_primitive_standard_structure() self.assertAlmostEqual(prim.lattice.alpha, 109.47122063400001) self.assertAlmostEqual(prim.lattice.beta, 109.47122063400001) self.assertAlmostEqual(prim.lattice.gamma, 109.47122063400001) self.assertAlmostEqual(prim.lattice.a, 7.9657251015812145) self.assertAlmostEqual(prim.lattice.b, 7.9657251015812145) self.assertAlmostEqual(prim.lattice.c, 7.9657251015812145) parser = CifParser(os.path.join(test_dir, 'btet_1915.cif')) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) prim = s.get_primitive_standard_structure() self.assertAlmostEqual(prim.lattice.alpha, 105.015053349) self.assertAlmostEqual(prim.lattice.beta, 105.015053349) self.assertAlmostEqual(prim.lattice.gamma, 118.80658411899999) self.assertAlmostEqual(prim.lattice.a, 4.1579321075608791) self.assertAlmostEqual(prim.lattice.b, 4.1579321075608791) self.assertAlmostEqual(prim.lattice.c, 4.1579321075608791) parser = CifParser(os.path.join(test_dir, 'orci_1010.cif')) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) prim = s.get_primitive_standard_structure() self.assertAlmostEqual(prim.lattice.alpha, 134.78923546600001) self.assertAlmostEqual(prim.lattice.beta, 105.856239333) self.assertAlmostEqual(prim.lattice.gamma, 91.276341676000001) self.assertAlmostEqual(prim.lattice.a, 3.8428217771014852) self.assertAlmostEqual(prim.lattice.b, 3.8428217771014852) self.assertAlmostEqual(prim.lattice.c, 3.8428217771014852) parser = CifParser(os.path.join(test_dir, 'orcc_1003.cif')) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) prim = s.get_primitive_standard_structure() self.assertAlmostEqual(prim.lattice.alpha, 90) self.assertAlmostEqual(prim.lattice.beta, 90) self.assertAlmostEqual(prim.lattice.gamma, 164.985257335) self.assertAlmostEqual(prim.lattice.a, 15.854897098324196) self.assertAlmostEqual(prim.lattice.b, 15.854897098324196) self.assertAlmostEqual(prim.lattice.c, 3.99648651) parser = CifParser(os.path.join(test_dir, 'monoc_1028.cif')) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) prim = s.get_primitive_standard_structure() self.assertAlmostEqual(prim.lattice.alpha, 63.579155761999999) self.assertAlmostEqual(prim.lattice.beta, 116.42084423747779) self.assertAlmostEqual(prim.lattice.gamma, 148.47965136208569) self.assertAlmostEqual(prim.lattice.a, 7.2908007159612325) self.assertAlmostEqual(prim.lattice.b, 7.2908007159612325) self.assertAlmostEqual(prim.lattice.c, 6.8743926325200002) parser = CifParser(os.path.join(test_dir, 'hex_1170.cif')) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) prim = s.get_primitive_standard_structure() self.assertAlmostEqual(prim.lattice.alpha, 90) self.assertAlmostEqual(prim.lattice.beta, 90) self.assertAlmostEqual(prim.lattice.gamma, 120) self.assertAlmostEqual(prim.lattice.a, 3.699919902005897) self.assertAlmostEqual(prim.lattice.b, 3.699919902005897) self.assertAlmostEqual(prim.lattice.c, 6.9779585500000003) parser = CifParser(os.path.join(test_dir, 'rhomb_3478_conv.cif')) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) prim = s.get_primitive_standard_structure() self.assertAlmostEqual(prim.lattice.alpha, 28.049186140546812) self.assertAlmostEqual(prim.lattice.beta, 28.049186140546812) self.assertAlmostEqual(prim.lattice.gamma, 28.049186140546812) self.assertAlmostEqual(prim.lattice.a, 5.9352627428399982) self.assertAlmostEqual(prim.lattice.b, 5.9352627428399982) self.assertAlmostEqual(prim.lattice.c, 5.9352627428399982)
def test_site_symbol_preference(self): parser = CifParser(self.TEST_FILES_DIR / 'site_type_symbol_test.cif') self.assertEqual(parser.get_structures()[0].formula, "Ge0.4 Sb0.4 Te1")
# Initiate the surface screening algorithm SS = ScreenSurf(bulkstruct) index = SS.ScreenSurfaces(natomsinsphere=20, keep=1, samespeconly=True, ignore=[]) # ScreenSurfaces uses the following parameters: # natomsinsphere = Increases radius of sphere until there are #natomsinsphere in the sphere. For simple structures this can be as low as 20. # keep = What percentage of the histogram to keep up to. Using keep=0.8 means we only keep the most common 80% of planes. # samespeconly = This is whether or not to search for only atoms of the same element in the sphere. # ignore = these are atoms to ignore. These often include small atoms on complex anions (e.g., O on CO_3^2-), or other moieties, like hydrogen. #Structures can also be read from CIF files in pymatgen parser = CifParser("AnataseTiO2.cif") Anatase = parser.get_structures()[0] SS = ScreenSurf(Anatase) index = SS.ScreenSurfaces(natomsinsphere=20, keep=1, samespeconly=True, ignore=[]) #Structures can also be read from VASP POSCAR files in pymatgen LiFePO4 = Poscar.from_file("Poscar_LiFePO4").structure SS = ScreenSurf(LiFePO4) index = SS.ScreenSurfaces(natomsinsphere=100, keep=1, samespeconly=True, ignore=['O'])
def test_parse_symbol(self): """ Test the _parse_symbol function with several potentially problematic examples of symbols and labels. """ test_cases = { "MgT": "Mg", "MgT1": "Mg", "H(46A)": "H", "O(M)": "O", "N(Am)": "N", "H1N2a": "H", "CO(1)": "Co", "Wat1": "O", "MgM2A": "Mg", "CaX": "Ca", "X1": "X", "X": "X", "OA1": "O", "NaA2": "Na", "O-H2": "O", "OD2": "O", "OW": "O", "SiT": "Si", "SiTet": "Si", "Na-Int": "Na", "CaD1": "Ca", "KAm": "K", "D+1": "D", "D": "D", "D1-": "D", "D4": "D", "D0": "D", "NH": "N", "NH2": "N", "NH3": "N", "SH": "S" } for e in Element: name = e.name test_cases[name] = name if len(name) == 2: test_cases[name.upper()] = name test_cases[name.upper() + str(1)] = name test_cases[name.upper() + "A"] = name test_cases[name + str(1)] = name test_cases[name + str(2)] = name test_cases[name + str(3)] = name test_cases[name + str(1) + "A"] = name special = {"Hw": "H", "Ow": "O", "Wat": "O", "wat": "O", "OH": "", "OH2": ""} test_cases.update(special) with warnings.catch_warnings(): warnings.simplefilter("ignore") parser = CifParser(self.TEST_FILES_DIR / 'LiFePO4.cif') for sym, expected_symbol in test_cases.items(): self.assertEqual(parser._parse_symbol(sym), expected_symbol)
def read_cif(path, primitive=True): parser = CifParser(path) return parser.get_structures(primitive)[0]
def test_dot_positions(self): f = self.TEST_FILES_DIR / "ICSD59959.cif" p = CifParser(f) s = p.get_structures()[0] self.assertEqual(s.formula, "K1 Mn1 F3")
def test_dot_positions(self): f = os.path.join(test_dir, "ICSD59959.cif") p = CifParser(f) s = p.get_structures()[0] self.assertEqual(s.formula, "K1 Mn1 F3")
from __future__ import unicode_literals import unittest import os from pymatgen.io.feff.sets import FeffInputSet from pymatgen.io.feff import FeffPot from pymatgen.io.cif import CifParser test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", 'test_files') cif_file = 'CoO19128.cif' central_atom = 'O' cif_path = os.path.join(test_dir, cif_file) r = CifParser(cif_path) structure = r.get_structures()[0] x = FeffInputSet("MaterialsProject") class FeffInputSetTest(unittest.TestCase): header_string = """* This FEFF.inp file generated by pymatgen TITLE comment: From cif file TITLE Source: CoO19128.cif TITLE Structure Summary: Co2 O2 TITLE Reduced formula: CoO TITLE space group: (P6_3mc), space number: (186) TITLE abc: 3.297078 3.297078 5.254213 TITLE angles: 90.000000 90.000000 120.000000 TITLE sites: 4
def test_site_symbol_preference(self): parser = CifParser(os.path.join(test_dir, 'site_type_symbol_test.cif')) self.assertEqual(parser.get_structures()[0].formula, "Ge0.4 Sb0.4 Te1")
start_time = time.time() if args.generate: # Generate new structures. (Multiple structures at one time, still random, peichen will implement Domain selection). if os.path.isfile(args.gensetting): print("Using exisiting generator setup in {}".format( args.gensetting)) with open(args.gensetting) as fin: generator = StructureGenerator.from_dict(json.load(fin)) else: print( "No existing generator setup detected. Constructing a new one." ) prim = CifParser(args.prim).get_structures()[0] compaxis = json.loads(args.compaxis) if args.compaxis else None enforceoccu = json.loads( args.enforceoccu) if args.compaxis else None transmat = json.loads(args.transmat) if args.transmat else None generator = StructureGenerator(prim, args.vasprun, enforceoccu, args.samplestep, args.scs,args.numsc,\ compaxis,transmat,args.cefile,args.vaspsetting) generator.generate_structures() generator.write_structures() generator.write_settings() #else: # print("Generator aborted. Check the reason carefully.") elif args.fit:
def compute_environments(chemenv_configuration): string_sources = { 'cif': { 'string': 'a Cif file', 'regexp': '.*\.cif$' }, 'mp': { 'string': 'the Materials Project database', 'regexp': 'mp-[0-9]+$' } } questions = {'c': 'cif'} if chemenv_configuration.has_materials_project_access: questions['m'] = 'mp' lgf = LocalGeometryFinder() lgf.setup_parameters() allcg = AllCoordinationGeometries() strategy_class = strategies_class_lookup[ chemenv_configuration.package_options['default_strategy']['strategy']] #TODO: Add the possibility to change the parameters and save them in the chemenv_configuration default_strategy = strategy_class() default_strategy.setup_options( chemenv_configuration.package_options['default_strategy'] ['strategy_options']) max_dist_factor = chemenv_configuration.package_options[ 'default_max_distance_factor'] firsttime = True while True: if len(questions) > 1: found = False print( 'Enter the source from which the structure is coming or <q> to quit :' ) for key_character, qq in questions.items(): print(' - <{}> for a structure from {}'.format( key_character, string_sources[qq]['string'])) test = input(' ... ') if test == 'q': break if test not in list(questions.keys()): for key_character, qq in questions.items(): if re.match(string_sources[qq]['regexp'], str(test)) is not None: found = True source_type = qq if not found: print('Wrong key, try again ...') continue else: source_type = questions[test] else: found = False source_type = list(questions.values())[0] if found and len(questions) > 1: input_source = test if source_type == 'cif': if not found: input_source = input('Enter path to cif file : ') cp = CifParser(input_source) structure = cp.get_structures()[0] elif source_type == 'mp': if not found: input_source = input( 'Enter materials project id (e.g. "mp-1902") : ') a = MPRester(chemenv_configuration.materials_project_api_key) structure = a.get_structure_by_material_id(input_source) lgf.setup_structure(structure) print('Computing environments for {} ... '.format( structure.composition.reduced_formula)) se = lgf.compute_structure_environments( maximum_distance_factor=max_dist_factor) print('Computing environments finished') while True: test = input( 'See list of environments determined for each (unequivalent) site ? ' '("y" or "n", "d" with details, "g" to see the grid) : ') strategy = default_strategy if test in ['y', 'd', 'g']: strategy.set_structure_environments(se) for eqslist in se.equivalent_sites: site = eqslist[0] isite = se.structure.index(site) try: if strategy.uniquely_determines_coordination_environments: ces = strategy.get_site_coordination_environments( site) else: ces = strategy.get_site_coordination_environments_fractions( site) except NeighborsNotComputedChemenvError: continue if ces is None: continue if len(ces) == 0: continue comp = site.species_and_occu #ce = strategy.get_site_coordination_environment(site) if strategy.uniquely_determines_coordination_environments: ce = ces[0] if ce is None: continue thecg = allcg.get_geometry_from_mp_symbol(ce[0]) mystring = 'Environment for site #{} {} ({}) : {} ({})\n'.format( str(isite), comp.get_reduced_formula_and_factor()[0], str(comp), thecg.name, ce[0]) else: mystring = 'Environments for site #{} {} ({}) : \n'.format( str(isite), comp.get_reduced_formula_and_factor()[0], str(comp)) for ce in ces: cg = allcg.get_geometry_from_mp_symbol(ce[0]) csm = ce[1]['other_symmetry_measures'][ 'csm_wcs_ctwcc'] mystring += ' - {} ({}): {:.2f} % (csm : {:2f})\n'.format( cg.name, cg.mp_symbol, 100.0 * ce[2], csm) if test in [ 'd', 'g' ] and strategy.uniquely_determines_coordination_environments: if thecg.mp_symbol != UNCLEAR_ENVIRONMENT_SYMBOL: mystring += ' <Continuous symmetry measures> ' mingeoms = se.ce_list[isite][ thecg. coordination_number][0].minimum_geometries() for mingeom in mingeoms: csm = mingeom[1]['other_symmetry_measures'][ 'csm_wcs_ctwcc'] mystring += '{} : {:.2f} '.format( mingeom[0], csm) print(mystring) if test == 'g': test = input( 'Enter index of site(s) for which you want to see the grid of parameters : ' ) indices = list(map(int, test.split())) print(indices) for isite in indices: se.plot_environments(isite, additional_condition=se.AC.ONLY_ACB) if no_vis: test = input('Go to next structure ? ("y" to do so)') if test == 'y': break continue test = input( 'View structure with environments ? ("y" for the unit cell or "m" for a supercell or "n") : ' ) if test in ['y', 'm']: if test == 'm': mydeltas = [] test = input('Enter multiplicity (e.g. 3 2 2) : ') nns = test.split() for i0 in range(int(nns[0])): for i1 in range(int(nns[1])): for i2 in range(int(nns[2])): mydeltas.append( np.array([1.0 * i0, 1.0 * i1, 1.0 * i2], np.float)) else: mydeltas = [np.zeros(3, np.float)] if firsttime: vis = StructureVis(show_polyhedron=False, show_unit_cell=True) vis.show_help = False firsttime = False vis.set_structure(se.structure) strategy.set_structure_environments(se) for isite, site in enumerate(se.structure): try: ces = strategy.get_site_coordination_environments(site) except NeighborsNotComputedChemenvError: continue if len(ces) == 0: continue ce = strategy.get_site_coordination_environment(site) if ce is not None and ce[0] != UNCLEAR_ENVIRONMENT_SYMBOL: for mydelta in mydeltas: psite = PeriodicSite(site._species, site._fcoords + mydelta, site._lattice, properties=site._properties) vis.add_site(psite) neighbors = strategy.get_site_neighbors(psite) draw_cg(vis, psite, neighbors, cg=lgf.allcg.get_geometry_from_mp_symbol( ce[0]), perm=ce[1]['permutation']) vis.show() test = input('Go to next structure ? ("y" to do so) : ') if test == 'y': break print('')
def test_get_conventional_standard_structure(self): parser = CifParser( os.path.join(PymatgenTest.TEST_FILES_DIR, "bcc_1927.cif")) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) conv = s.get_conventional_standard_structure() self.assertAlmostEqual(conv.lattice.alpha, 90) self.assertAlmostEqual(conv.lattice.beta, 90) self.assertAlmostEqual(conv.lattice.gamma, 90) self.assertAlmostEqual(conv.lattice.a, 9.1980270633769461) self.assertAlmostEqual(conv.lattice.b, 9.1980270633769461) self.assertAlmostEqual(conv.lattice.c, 9.1980270633769461) parser = CifParser( os.path.join(PymatgenTest.TEST_FILES_DIR, "btet_1915.cif")) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) conv = s.get_conventional_standard_structure() self.assertAlmostEqual(conv.lattice.alpha, 90) self.assertAlmostEqual(conv.lattice.beta, 90) self.assertAlmostEqual(conv.lattice.gamma, 90) self.assertAlmostEqual(conv.lattice.a, 5.0615106678044235) self.assertAlmostEqual(conv.lattice.b, 5.0615106678044235) self.assertAlmostEqual(conv.lattice.c, 4.2327080177761687) parser = CifParser( os.path.join(PymatgenTest.TEST_FILES_DIR, "orci_1010.cif")) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) conv = s.get_conventional_standard_structure() self.assertAlmostEqual(conv.lattice.alpha, 90) self.assertAlmostEqual(conv.lattice.beta, 90) self.assertAlmostEqual(conv.lattice.gamma, 90) self.assertAlmostEqual(conv.lattice.a, 2.9542233922299999) self.assertAlmostEqual(conv.lattice.b, 4.6330325651443296) self.assertAlmostEqual(conv.lattice.c, 5.373703587040775) parser = CifParser( os.path.join(PymatgenTest.TEST_FILES_DIR, "orcc_1003.cif")) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) conv = s.get_conventional_standard_structure() self.assertAlmostEqual(conv.lattice.alpha, 90) self.assertAlmostEqual(conv.lattice.beta, 90) self.assertAlmostEqual(conv.lattice.gamma, 90) self.assertAlmostEqual(conv.lattice.a, 4.1430033493799998) self.assertAlmostEqual(conv.lattice.b, 31.437979757624728) self.assertAlmostEqual(conv.lattice.c, 3.99648651) parser = CifParser( os.path.join(PymatgenTest.TEST_FILES_DIR, "orac_632475.cif")) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) conv = s.get_conventional_standard_structure() self.assertAlmostEqual(conv.lattice.alpha, 90) self.assertAlmostEqual(conv.lattice.beta, 90) self.assertAlmostEqual(conv.lattice.gamma, 90) self.assertAlmostEqual(conv.lattice.a, 3.1790663399999999) self.assertAlmostEqual(conv.lattice.b, 9.9032878699999998) self.assertAlmostEqual(conv.lattice.c, 3.5372412099999999) parser = CifParser( os.path.join(PymatgenTest.TEST_FILES_DIR, "monoc_1028.cif")) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) conv = s.get_conventional_standard_structure() self.assertAlmostEqual(conv.lattice.alpha, 90) self.assertAlmostEqual(conv.lattice.beta, 117.53832420192903) self.assertAlmostEqual(conv.lattice.gamma, 90) self.assertAlmostEqual(conv.lattice.a, 14.033435583000625) self.assertAlmostEqual(conv.lattice.b, 3.96052850731) self.assertAlmostEqual(conv.lattice.c, 6.8743926325200002) parser = CifParser( os.path.join(PymatgenTest.TEST_FILES_DIR, "hex_1170.cif")) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) conv = s.get_conventional_standard_structure() self.assertAlmostEqual(conv.lattice.alpha, 90) self.assertAlmostEqual(conv.lattice.beta, 90) self.assertAlmostEqual(conv.lattice.gamma, 120) self.assertAlmostEqual(conv.lattice.a, 3.699919902005897) self.assertAlmostEqual(conv.lattice.b, 3.699919902005897) self.assertAlmostEqual(conv.lattice.c, 6.9779585500000003) structure = Structure.from_file( os.path.join(PymatgenTest.TEST_FILES_DIR, "tric_684654.json")) s = SpacegroupAnalyzer(structure, symprec=1e-2) conv = s.get_conventional_standard_structure() self.assertAlmostEqual(conv.lattice.alpha, 74.09581916308757) self.assertAlmostEqual(conv.lattice.beta, 75.72817279281173) self.assertAlmostEqual(conv.lattice.gamma, 63.63234318667333) self.assertAlmostEqual(conv.lattice.a, 3.741372924048738) self.assertAlmostEqual(conv.lattice.b, 3.9883228679270686) self.assertAlmostEqual(conv.lattice.c, 7.288495840048958) structure = Structure.from_file( os.path.join(PymatgenTest.TEST_FILES_DIR, "tric_684654.json")) structure.add_site_property("magmom", [1.0] * len(structure)) s = SpacegroupAnalyzer(structure, symprec=1e-2) conv = s.get_conventional_standard_structure(keep_site_properties=True) self.assertEqual(conv.site_properties["magmom"], [1.0] * len(conv)) structure = Structure.from_file( os.path.join(PymatgenTest.TEST_FILES_DIR, "tric_684654.json")) structure.add_site_property("magmom", [1.0] * len(structure)) s = SpacegroupAnalyzer(structure, symprec=1e-2) conv = s.get_conventional_standard_structure( keep_site_properties=False) self.assertEqual(conv.site_properties.get("magmom", None), None)
'Greigite_127', 'Pyrite_12728', 'Pyrrhotite_288', 'Mackinawite_14518', 'Marcasite_12726', 'Smythite_80', 'Tochilinite_15564', 'Troilite_4160' ] d = '/home/kenneth/proj/proMin/minerals/database/reformat' bv_elem = [] bv_sum = [] bv_type = [] bvs = [] for m in mins: print(m) mn, num = m.split('_') fi = os.path.join(d, mn, mn + '_' + str(num) + '.cif') # print(fi) # exit() parser = CifParser(fi) structure = parser.get_structures(primitive=True)[0] els = [Element(el.symbol) for el in structure.composition.elements] if not set(els).issubset(set(BV_PARAMS.keys())): raise ValueError( "Structure contains elements not in set of BV parameters!") bv = pma.BVAnalyzer() # Perform symmetry determination and get sites grouped by symmetry. if bv.symm_tol: finder = SpacegroupAnalyzer(structure, bv.symm_tol) symm_structure = finder.get_symmetrized_structure() equi_sites = symm_structure.equivalent_sites else:
def test_get_conventional_standard_structure(self): parser = CifParser(os.path.join(test_dir, 'bcc_1927.cif')) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) conv = s.get_conventional_standard_structure() self.assertAlmostEqual(conv.lattice.alpha, 90) self.assertAlmostEqual(conv.lattice.beta, 90) self.assertAlmostEqual(conv.lattice.gamma, 90) self.assertAlmostEqual(conv.lattice.a, 9.1980270633769461) self.assertAlmostEqual(conv.lattice.b, 9.1980270633769461) self.assertAlmostEqual(conv.lattice.c, 9.1980270633769461) parser = CifParser(os.path.join(test_dir, 'btet_1915.cif')) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) conv = s.get_conventional_standard_structure() self.assertAlmostEqual(conv.lattice.alpha, 90) self.assertAlmostEqual(conv.lattice.beta, 90) self.assertAlmostEqual(conv.lattice.gamma, 90) self.assertAlmostEqual(conv.lattice.a, 5.0615106678044235) self.assertAlmostEqual(conv.lattice.b, 5.0615106678044235) self.assertAlmostEqual(conv.lattice.c, 4.2327080177761687) parser = CifParser(os.path.join(test_dir, 'orci_1010.cif')) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) conv = s.get_conventional_standard_structure() self.assertAlmostEqual(conv.lattice.alpha, 90) self.assertAlmostEqual(conv.lattice.beta, 90) self.assertAlmostEqual(conv.lattice.gamma, 90) self.assertAlmostEqual(conv.lattice.a, 2.9542233922299999) self.assertAlmostEqual(conv.lattice.b, 4.6330325651443296) self.assertAlmostEqual(conv.lattice.c, 5.373703587040775) parser = CifParser(os.path.join(test_dir, 'orcc_1003.cif')) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) conv = s.get_conventional_standard_structure() self.assertAlmostEqual(conv.lattice.alpha, 90) self.assertAlmostEqual(conv.lattice.beta, 90) self.assertAlmostEqual(conv.lattice.gamma, 90) self.assertAlmostEqual(conv.lattice.a, 4.1430033493799998) self.assertAlmostEqual(conv.lattice.b, 31.437979757624728) self.assertAlmostEqual(conv.lattice.c, 3.99648651) parser = CifParser(os.path.join(test_dir, 'orac_632475.cif')) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) conv = s.get_conventional_standard_structure() self.assertAlmostEqual(conv.lattice.alpha, 90) self.assertAlmostEqual(conv.lattice.beta, 90) self.assertAlmostEqual(conv.lattice.gamma, 90) self.assertAlmostEqual(conv.lattice.a, 3.1790663399999999) self.assertAlmostEqual(conv.lattice.b, 9.9032878699999998) self.assertAlmostEqual(conv.lattice.c, 3.5372412099999999) parser = CifParser(os.path.join(test_dir, 'monoc_1028.cif')) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) conv = s.get_conventional_standard_structure() self.assertAlmostEqual(conv.lattice.alpha, 90) self.assertAlmostEqual(conv.lattice.beta, 117.53832420192903) self.assertAlmostEqual(conv.lattice.gamma, 90) self.assertAlmostEqual(conv.lattice.a, 14.033435583000625) self.assertAlmostEqual(conv.lattice.b, 3.96052850731) self.assertAlmostEqual(conv.lattice.c, 6.8743926325200002) parser = CifParser(os.path.join(test_dir, 'hex_1170.cif')) structure = parser.get_structures(False)[0] s = SpacegroupAnalyzer(structure, symprec=1e-2) conv = s.get_conventional_standard_structure() self.assertAlmostEqual(conv.lattice.alpha, 90) self.assertAlmostEqual(conv.lattice.beta, 90) self.assertAlmostEqual(conv.lattice.gamma, 120) self.assertAlmostEqual(conv.lattice.a, 3.699919902005897) self.assertAlmostEqual(conv.lattice.b, 3.699919902005897) self.assertAlmostEqual(conv.lattice.c, 6.9779585500000003)
db = client[DB] group = Group.get_from_string('%s_cif_raw' % COLLECTION) logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.DEBUG, filename='%s.log' % COLLECTION) logging.info('Creating collection %s', COLLECTION) collection = db[COLLECTION] documents = [] for cif in group.nodes: path, structures, source, structure, document = [None] * 5 path = cif.get_file_abs_path() try: structures = CifParser(path).get_structures(primitive=False) except Exception as exception: logging.error('%s', str(exception)) else: source = cif.get_attr('source') for structure in structures: document = {'source': source, 'structure': structure.as_dict()} documents.append(document) if not (len(documents) % (N / 10)): logging.info('%d documents collected', len(documents)) if len(documents) == N: logging.info('Inserting %d documents into %s', len(documents), COLLECTION) try: result = collection.insert_many(documents) except Exception as exception: