def get_structure_by_formula(self, formula, **kwargs): """ Queries the COD for structures by formula. Requires mysql executable to be in the path. Args: cod_id (int): COD id. kwargs: All kwargs supported by :func:`pymatgen.core.structure.Structure.from_str`. Returns: A list of dict of the format [{"structure": Structure, "cod_id": cod_id, "sg": "P n m a"}] """ structures = [] sql = f'select file, sg from data where formula="- {Composition(formula).hill_formula} -"' text = self.query(sql).split("\n") text.pop(0) for l in text: if l.strip(): cod_id, sg = l.split("\t") r = requests.get(f"http://www.crystallography.net/cod/{cod_id.strip()}.cif") try: s = Structure.from_str(r.text, fmt="cif", **kwargs) structures.append({"structure": s, "cod_id": int(cod_id), "sg": sg}) except Exception: import warnings warnings.warn(f"\nStructure.from_str failed while parsing CIF file:\n{r.text}") raise return structures
def test_sites_for_bio2(): bio2_structure = Structure.from_str("""Bi4 O8 1.0 4.880207 0.000000 -2.019673 -0.667412 5.402283 -1.612690 -0.040184 -0.016599 6.808846 Bi O 4 8 direct 0.729106 0.250000 1.000000 Bi 0.270894 0.750000 0.000000 Bi 0.000000 0.000000 0.500000 Bi 0.500000 0.500000 0.500000 Bi 0.321325 0.021684 0.814642 O 0.114894 0.650123 0.351314 O 0.885106 0.349877 0.648686 O 0.763580 0.849877 0.648686 O 0.236420 0.150123 0.351314 O 0.493318 0.521684 0.814642 O 0.506682 0.478316 0.185358 O 0.678675 0.978316 0.185358 O""", fmt="POSCAR") symmetrizer = StructureSymmetrizer(bio2_structure) actual = symmetrizer.sites expected = \ {'Bi1': Site(element='Bi', wyckoff_letter='e', site_symmetry='2', equivalent_atoms=[0, 1]), 'Bi2': Site(element='Bi', wyckoff_letter='c', site_symmetry='-1', equivalent_atoms=[2, 3]), 'O1': Site(element='O', wyckoff_letter='f', site_symmetry='1', equivalent_atoms=[4, 9, 10, 11]), 'O2': Site(element='O', wyckoff_letter='f', site_symmetry='1', equivalent_atoms=[5, 6, 7, 8])} assert actual == expected
def __getitem__(self, idx): """ Computes graph featurs from CIF string """ indexes = np.arange(0, len(self.df))[idx * self.batch_size:(idx + 1) * self.batch_size] atomic_features = [] bond_features = [] atom_neighbour_idxs = [] masks = [] targets = [] for i in indexes: crystal = Structure.from_str(self.df['cif'].iloc[i], fmt='cif') atom_fea = np.vstack([ self.atom_init.get_atom_fea(crystal[i].specie.number) for i in range(len(crystal)) ]) all_nbrs = crystal.get_all_neighbors(self.radius, include_index=True) all_nbrs = [sorted(nbrs, key=lambda x: x[1]) for nbrs in all_nbrs] nbr_fea_idx, nbr_fea = [], [] for nbr in all_nbrs: if len(nbr) < self.max_num_nbr: warnings.warn( '{} not find enough neighbors to build graph. ' 'If it happens frequently, consider increase ' 'radius.'.format(self.df['mp_id'].iloc[i])) nbr_fea_idx.append( list(map(lambda x: x[2], nbr)) + [0] * (self.max_num_nbr - len(nbr))) nbr_fea.append( list(map(lambda x: x[1], nbr)) + [self.radius + 1.] * (self.max_num_nbr - len(nbr))) else: nbr_fea_idx.append( list(map(lambda x: x[2], nbr[:self.max_num_nbr]))) nbr_fea.append( list(map(lambda x: x[1], nbr[:self.max_num_nbr]))) nbr_fea_idx, nbr_fea = np.array(nbr_fea_idx), np.array(nbr_fea) nbr_fea = self.gdf.expand(nbr_fea) atom_fea_new, nbr_fea_new, nbr_fea_idx_new, mask_new = self.pad_features_with_n( atom_fea, nbr_fea, nbr_fea_idx, n=128) atomic_features.append(atom_fea_new) bond_features.append(nbr_fea_new) atom_neighbour_idxs.append(nbr_fea_idx_new) masks.append(mask_new) targets.append(self.df[self.target].iloc[i]) atomic_features = np.array(atomic_features, dtype=np.float32) bond_features = np.array(bond_features, dtype=np.float32) atom_neighbour_idxs = np.array(atom_neighbour_idxs, dtype=int) masks = np.array(masks, dtype=int) targets = np.array(targets, dtype=np.float32) return [atomic_features, bond_features, atom_neighbour_idxs, masks], targets
def test_spglib_cyclic_behavior(): input_structure = Structure.from_str("""Ca4 Sc2 Sb2 O12 1.0 5.469740 0.000000 0.000000 0.000000 5.632621 0.000000 -5.467914 0.000000 7.830251 O 12 direct 0.344251 0.197893 0.550856 O 0.344251 0.302107 0.050856 O 0.655749 0.802107 0.449144 O 0.655749 0.697893 0.949144 O 0.752694 0.208674 0.946720 O 0.752694 0.291326 0.446720 O 0.247306 0.791326 0.053280 O 0.247306 0.708674 0.553280 O 0.144882 0.034671 0.743977 O 0.144882 0.465329 0.243977 O 0.855118 0.965329 0.256023 O 0.855118 0.534671 0.756023 O """, fmt="POSCAR") ss = StructureSymmetrizer(input_structure) sss = StructureSymmetrizer(ss.primitive) assert ss.primitive == sss.primitive
def parallel_computing(root_dir, fnames, wavelength, sym_thresh): # initialize XRD simulator xrd_simulator = xrd.XRDSimulator(wavelength=wavelength) for idx, filename in enumerate(fnames): if (idx + 1) % 100 == 0: print('this worker finished processing {} materials..'.format(idx + 1), flush=True) with open(os.path.join(root_dir, filename + ".cif")) as f: cif_struct = Structure.from_str(f.read(), fmt="cif") sga = SpacegroupAnalyzer(cif_struct, symprec=sym_thresh) # conventional cell conventional_struct = sga.get_conventional_standard_structure() _, conventional_recip_latt, conventional_features = \ xrd_simulator.get_pattern(structure=conventional_struct) # save conventional reciprocal lattice vector np.save(os.path.join(root_dir, filename+"_conventional_basis.npy"), \ conventional_recip_latt) # save conventional diffraction pattern np.save(os.path.join(root_dir, filename+"_conventional.npy"), \ np.array(conventional_features)) # primitive cell primitive_struct = sga.get_primitive_standard_structure() _, primitive_recip_latt, primitive_features = \ xrd_simulator.get_pattern(structure=primitive_struct) # save primitive reciprocal lattice vector np.save(os.path.join(root_dir, filename+"_primitive_basis.npy"), \ primitive_recip_latt) # save primitive diffraction pattern np.save(os.path.join(root_dir, filename+"_primitive.npy"), \ np.array(primitive_features))
def get_structure_by_formula(self, formula, **kwargs): """ Queries the COD for structures by formula. Requires mysql executable to be in the path. Args: cod_id (int): COD id. kwargs: All kwargs supported by :func:`pymatgen.core.structure.Structure.from_str`. Returns: A list of dict of the format [{"structure": Structure, "cod_id": cod_id, "sg": "P n m a"}] """ structures = [] sql = 'select file, sg from data where formula="- %s -"' % \ Composition(formula).hill_formula text = self.query(sql).split("\n") text.pop(0) for l in text: if l.strip(): cod_id, sg = l.split("\t") r = requests.get("http://www.crystallography.net/cod/%s.cif" % cod_id.strip()) s = Structure.from_str(r.text, fmt="cif", **kwargs) structures.append({ "structure": s, "cod_id": int(cod_id), "sg": sg }) return structures
def get_structure_by_formula(self, formula, **kwargs): """ Queries the COD for structures by formula. Requires mysql executable to be in the path. Args: cod_id (int): COD id. kwargs: All kwargs supported by :func:`pymatgen.core.structure.Structure.from_str`. Returns: A list of dict of the format [{"structure": Structure, "cod_id": cod_id, "sg": "P n m a"}] """ structures = [] sql = 'select file, sg from data where formula="- %s -"' % \ Composition(formula).hill_formula text = self.query(sql).split("\n") text.pop(0) for l in text: if l.strip(): cod_id, sg = l.split("\t") r = requests.get("http://www.crystallography.net/cod/%s.cif" % cod_id.strip()) s = Structure.from_str(r.text, fmt="cif", **kwargs) structures.append({"structure": s, "cod_id": int(cod_id), "sg": sg}) return structures
def make_crystal_img(cif_str, resolution=0.5): struct = Structure.from_str(input_string=cif_str,fmt='cif') sg = SpacegroupAnalyzer(struct) conv_struct = sg.get_conventional_standard_structure() sites = conv_struct.sites nfeats = [3] lattice_lengths = np.asarray(conv_struct.lattice.abc) dimensions = list(np.ceil(lattice_lengths / resolution).astype(int)) img = np.zeros(dimensions+nfeats, dtype=np.float32) for i in range(img.shape[0]): for j in range(img.shape[1]): for k in range(img.shape[2]): x = (float(i)+0.5)/img.shape[0]*lattice_lengths[0] y = (float(j)+0.5)/img.shape[1]*lattice_lengths[1] z = (float(k)+0.5)/img.shape[2]*lattice_lengths[2] pt = np.array([x,y,z]) neighbors = conv_struct.get_sites_in_sphere(pt=pt,r=10) nearest_neighbor = [n[0] for n in sorted(neighbors, key=lambda s: s[1])][0] features = element_features(nearest_neighbor.specie) if all([f != 'failed' for f in features]): img[i,j,k,:] = features else: return 'failed' return img
def test_decimal(self): struct = Structure.from_str("""Mg2 Al4 O8 1.0 5.003532 0.000000 2.888790 1.667844 4.717375 2.888790 0.000000 0.000000 5.777581 O Mg Al 8 2 4 direct 0.736371 0.736371 0.736371 O 0.263629 0.263629 0.709114 O 0.263629 0.709114 0.263629 O 0.709114 0.263629 0.263629 O 0.736371 0.290886 0.736371 O 0.290886 0.736371 0.736371 O 0.263629 0.263629 0.263629 O 0.736371 0.736371 0.290886 O 0.125000 0.125000 0.125000 Mg 0.875000 0.875000 0.875000 Mg 0.500000 0.500000 0.000000 Al 0.500000 0.500000 0.500000 Al 0.000000 0.500000 0.500000 Al 0.500000 0.000000 0.500000 Al""", fmt='poscar') bp = BuckinghamPotential(bush_lewis_flag="bush") gio = GulpIO() input = gio.buckingham_input(struct, ['relax conp']) caller = GulpCaller() gout = caller.run(input)
def test_decimal(self): struct = Structure.from_str( """Mg2 Al4 O8 1.0 5.003532 0.000000 2.888790 1.667844 4.717375 2.888790 0.000000 0.000000 5.777581 O Mg Al 8 2 4 direct 0.736371 0.736371 0.736371 O 0.263629 0.263629 0.709114 O 0.263629 0.709114 0.263629 O 0.709114 0.263629 0.263629 O 0.736371 0.290886 0.736371 O 0.290886 0.736371 0.736371 O 0.263629 0.263629 0.263629 O 0.736371 0.736371 0.290886 O 0.125000 0.125000 0.125000 Mg 0.875000 0.875000 0.875000 Mg 0.500000 0.500000 0.000000 Al 0.500000 0.500000 0.500000 Al 0.000000 0.500000 0.500000 Al 0.500000 0.000000 0.500000 Al""", fmt="poscar", ) bp = BuckinghamPotential(bush_lewis_flag="bush") gio = GulpIO() input = gio.buckingham_input(struct, ["relax conp"]) caller = GulpCaller() gout = caller.run(input)
def test_specie_cifwriter(self): si4 = Species("Si", 4) si3 = Species("Si", 3) n = DummySpecies("X", -3) coords = list() coords.append(np.array([0.5, 0.5, 0.5])) coords.append(np.array([0.75, 0.5, 0.75])) coords.append(np.array([0, 0, 0])) lattice = Lattice( np.array([ [3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603], ])) struct = Structure(lattice, [n, {si3: 0.5, n: 0.5}, si4], coords) writer = CifWriter(struct) ans = """# generated using pymatgen data_X1.5Si1.5 _symmetry_space_group_name_H-M 'P 1' _cell_length_a 3.84019793 _cell_length_b 3.84019899 _cell_length_c 3.84019793 _cell_angle_alpha 119.99999086 _cell_angle_beta 90.00000000 _cell_angle_gamma 60.00000914 _symmetry_Int_Tables_number 1 _chemical_formula_structural X1.5Si1.5 _chemical_formula_sum 'X1.5 Si1.5' _cell_volume 40.04479464 _cell_formula_units_Z 1 loop_ _symmetry_equiv_pos_site_id _symmetry_equiv_pos_as_xyz 1 'x, y, z' loop_ _atom_type_symbol _atom_type_oxidation_number X3- -3.0 Si3+ 3.0 Si4+ 4.0 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_occupancy X3- X0 1 0.50000000 0.50000000 0.50000000 1 X3- X1 1 0.75000000 0.50000000 0.75000000 0.5 Si3+ Si2 1 0.75000000 0.50000000 0.75000000 0.5 Si4+ Si3 1 0.00000000 0.00000000 0.00000000 1 """ for l1, l2 in zip(str(writer).split("\n"), ans.split("\n")): self.assertEqual(l1.strip(), l2.strip()) # test that mixed valence works properly s2 = Structure.from_str(ans, "cif") self.assertEqual(struct.composition, s2.composition)
def read(self, fileName='POSCAR'): file1 = open(fileName, 'r') Lines = file1.readlines() poscar = '' for Line in Lines: poscar += Line s = Structure.from_str(poscar, fmt='poscar').as_dict() self.structure = s
def read_data(name, data): if name == "structure": data_str = np.string_(data[()]).decode() return Structure.from_str(data_str, fmt="json") if name == "scattering_labels": return data[()].astype("U13") # decode string if name == "vb_idx": d = data[()] return d if d is not False else None return data[()]
def main(): # get args args = parse_arguments() # make output directory out_dir = args.out_dir out_dir_path = path.normpath(path.join(getcwd(), out_dir)) makedirs(out_dir_path, exist_ok=True) # load raw dataset csv_path = path.normpath(path.join(getcwd(), args.csv_path)) table_data = pd.read_csv(csv_path, index_col=False) structure_path = path.normpath(path.join(getcwd(), args.structure_path)) structure_data = h5py.File(structure_path, "r") # loop mp_ids = [] for mp_id, formula in tqdm( zip(table_data['material_id'], table_data['pretty_formula'])): crystal = Structure.from_str(structure_data[mp_id].value, args.fmt) n_sites = len(crystal.sites) max_lattice_length = max(crystal.lattice.lengths) if isinstance(formula, str): crystal = Structure.from_str(structure_data[mp_id].value, args.fmt) n_sites = len(crystal.sites) max_lattice_length = max(crystal.lattice.lengths) n_elements = len(Composition(formula).elements) # https://github.com/kaist-amsg/imatgen/issues/2 + up to 5 elements if n_sites <= 20 and max_lattice_length <= 10 and n_elements <= 5: mp_ids += [mp_id] # save print('All MP ids : ', len(mp_ids)) mp_ids = np.array(mp_ids) if len(mp_ids) > args.size: seed_everything(seed=1234) index = random.sample([i for i in range(len(mp_ids))], args.size) mp_ids = mp_ids[index] save_path = path.join(out_dir, 'mp_ids.npy') np.save(save_path, mp_ids) print('Total MP ids : ', len(mp_ids)) return True
def test_sum_frac_coords(): structure = Structure.from_str(""" 1.0 1 0 0 0 1 0 0 0 1 H 2 direct 0.1 0.2 0.3 H 0.4 0.5 0.6 H""", fmt="POSCAR") assert sum_frac_coords(structure) == 2.1
def load_deformation_potentials(filename): deformation_potentials = {} with h5py.File(filename, "r") as f: deform_keys = [k for k in list(f.keys()) if "deformation_potentials" in k] for key in deform_keys: spin = str_to_spin[key.split("_")[-1]] deformation_potentials[spin] = np.array(f[key]) structure_str = np.string_(np.array(f["structure"])).decode() structure = Structure.from_str(structure_str, fmt="json") kpoints = np.array(f["kpoints"]) return deformation_potentials, kpoints, structure
def get_relaxed_structure(aurl): """Collects the relaxed structure as a pymatgen.Structure. Args: aurl: (str) The url for the material entry in AFLOW. Returns: (pymatgen.Structure) The relaxed structure. """ # downloads the file as a string file = AflowFile(aurl, 'CONTCAR.relax.vasp')() # calling induces dwnld # returns the python object return Structure.from_str(file, fmt='poscar')
def get_structure_by_material_id(self, material_id, final=True): """ Get a Structure corresponding to a material_id. Args: material_id (str): MaterialsWeb material_id (a string, e.g., mp-1234). final (bool): Whether to get the final structure, or the initial (pre-relaxation) structure. Defaults to True. Returns: Structure object. """ prop = "final_structure" if final else "initial_structure" data = self.get_data(material_id) return Structure.from_str(data[0][prop], fmt="json")
def get_structure_by_id(self, cod_id, **kwargs): """ Queries the COD for a structure by id. Args: cod_id (int): COD id. kwargs: All kwargs supported by :func:`pymatgen.core.structure.Structure.from_str`. Returns: A Structure. """ r = requests.get("http://www.crystallography.net/cod/%s.cif" % cod_id) return Structure.from_str(r.text, fmt="cif", **kwargs)
def main(): # get args args = parse_arguments() # make output directory out_dir = args.out_dir out_dir_path = path.normpath(path.join(getcwd(), out_dir)) makedirs(out_dir_path, exist_ok=True) cell_dir_path = path.join(out_dir_path, 'cell_image') makedirs(cell_dir_path, exist_ok=True) # load raw dataset structure_path = path.normpath(path.join(getcwd(), args.structure_path)) csv_path = path.normpath(path.join(getcwd(), args.csv_path)) mp_ids_path = path.normpath(path.join(getcwd(), args.mp_ids)) structure_data = h5py.File(structure_path, "r") table_data = pd.read_csv(csv_path, index_col=False) mp_ids = np.load(mp_ids_path) table_data = table_data[table_data['material_id'].isin(mp_ids)] assert len(mp_ids) == len(table_data) cell_nbins = 32 length = len(table_data['material_id'].values) cell_csv = pd.DataFrame( [], columns=['mp_id', 'crystal_system', 'space_group', 'image_name'], index=range(length)) for i, mp_id in tqdm(enumerate(table_data['material_id'].values)): crystal = Structure.from_str(structure_data[mp_id].value, args.fmt) ase_atoms = AseAtomsAdaptor.get_atoms(crystal) cell_atoms = cell_translate(ase_atoms) cell_image, _ = ase_atoms_to_image(cell_atoms, cell_nbins, args.atom_list, args.jobs) # save cell image image_name = mp_id.replace('-', '_') cell_save_path = path.join(cell_dir_path, image_name) np.save('{}.npy'.format(cell_save_path), cell_image) # save basis image finder = SpacegroupAnalyzer(crystal) crystal_system = finder.get_crystal_system() space_group_num = finder.get_space_group_number() cell_csv.iloc[i] = [mp_id, crystal_system, space_group_num, image_name] # save cell_csv_save_path = path.join(out_dir_path, 'cell_image.csv') cell_csv.to_csv(cell_csv_save_path) return True
def get_structure_by_id(self, cod_id, **kwargs): """ Queries the COD for a structure by id. Args: cod_id (int): COD id. kwargs: All kwargs supported by :func:`pymatgen.core.structure.Structure.from_str`. Returns: A Structure. """ r = requests.get(f"http://{self.url}/cod/{cod_id}.cif") return Structure.from_str(r.text, fmt="cif", **kwargs)
def test_is_first_primitive(): structure = Structure.from_str("""Hg6 1.0 4.4679886286 2.5795944374 4.4083109087 -4.4679886286 2.5795944374 4.4083109087 0.0000000000 -5.1591888749 4.4083109087 H Hg 1 6 direct 0.0 0.0 0.0 H 0.2500000000 0.6035253347 0.8964746653 Hg 0.8964746653 0.2500000000 0.6035253347 Hg 0.6035253347 0.8964746653 0.2500000000 Hg 0.7500000000 0.3964746653 0.1035253347 Hg 0.1035253347 0.7500000000 0.3964746653 Hg 0.3964746653 0.1035253347 0.7500000000 Hg""", fmt="poscar") structure2 = Structure.from_str("""Hg6 1.0 4.4679886286 2.5795944374 4.4083109087 -4.4679886286 2.5795944374 4.4083109087 0.0000000000 -5.1591888749 4.4083109087 H Hg 1 6 direct 0.0 0.0 0.0 H 0.750000 0.103525 0.396475 Hg 0.396475 0.750000 0.103525 Hg 0.103525 0.396475 0.750000 Hg 0.250000 0.896475 0.603525 Hg 0.603525 0.250000 0.896475 Hg 0.896475 0.603525 0.250000 Hg """, fmt="poscar") assert first_structure_is_primitive(structure, structure2) is True assert first_structure_is_primitive(structure2, structure) is False
def get_all_structures(self, final=True): """ Download all MaterialsWeb structures as pymatgen Structure objects. Args: final (bool): Whether to get the final structures, or the initial (pre-relaxation) structures. Defaults to True. Returns: List of Structure objects. """ prop = "final_structure" if final else "initial_structure" data = self.get_data("all") structures = [Structure.from_str(data[i][prop], fmt="json") for i in range(len(data))] return structures
def _get_structure(entry, use_web_api=True): """ Extracts structure data from AFLOW CONTCAR file. If the file is unavailable, the structure can be reconstituted from different fields in the AFLOW database. Can perform web queries to retrieve those fields. Args: entry (aflow.entries.Entry): entry containing the CONTCAR data as a string in the "AEL_elastic_tensor_json" field, or containing the fields 'geometry', 'species', 'composition', and 'positions_fractional'. use_web_api (bool): True allows missing data to be retrieved from the AFLOW API. False will raise an exception if the data is missing. Default: True Returns: pymatgen.core.structure.Structure: a pymatgen structure object """ data_in = entry.raw.get('CONTCAR_relax_vasp') contcar = True if data_in is None: contcar = False if contcar: try: structure = Structure.from_str(data_in, fmt="poscar") return structure except Exception: logger.warning("Parsing structure file for {} failed.".format(entry.auid) + " Generating from material entry") if not use_web_api: if not all(kw in entry.attributes for kw in ('geometry', 'species', 'composition', 'positions_fractional')): return None from pymatgen.core.lattice import Lattice # This lazy-loads the data by making an HTTP request for each property it needs # if the fields don't exist in the entry geometry = entry.geometry lattice = Lattice.from_parameters(*geometry) elements = list(map(str.strip, entry.species)) composition = list(entry.composition) species = list(chain.from_iterable([elem] * comp for elem, comp in zip(elements, composition))) xyz = entry.positions_fractional.tolist() return Structure(lattice, species, xyz)
def get_all_structures(self, final=True): """ Download all MaterialsWeb structures as pymatgen Structure objects. Args: final (bool): Whether to get the final structures, or the initial (pre-relaxation) structures. Defaults to True. Returns: List of Structure objects. """ prop = "final_structure" if final else "initial_structure" data = self.get_data("all") structures = [ Structure.from_str(data[i][prop], fmt="json") for i in range(len(data)) ] return structures
def load_coefficients(filename): coeffs = {} with h5py.File(filename, "r") as f: coeff_keys = [k for k in list(f.keys()) if "coefficients" in k] for key in coeff_keys: spin = str_to_spin[key.split("_")[1]] coeffs[spin] = np.array(f[key]) structure_str = np.string_(np.array(f["structure"])).decode() structure = Structure.from_str(structure_str, fmt="json") kpoints = np.array(f["kpoints"]) if "gpoints" in f: gpoints = np.array(f["gpoints"]) else: gpoints = None return coeffs, gpoints, kpoints, structure
def as_pymatgen_struc(self): ''' Method that converts results to list of pymatgen strucutures Returns: struc: List of pymatgen structures ''' struc = [] for c in self.results: urlp = ('http://2d' + c['path'][9:21] + '.org/' + c['path'][22:] + '/POSCAR') file = urllib.request.urlopen(urlp) poscar = '' for line in file: poscar += line.decode("utf-8") s = Structure.from_str(poscar, fmt='poscar') struc.append(s) return struc
def _load_struct_data(fname: PathLike) -> pd.DataFrame: """Load data containing ``Structure``s from a file. Deserializes the "structure" column to a string. The converse of :func:`save_struct_data`. Args: fname: Whence to load the file. Returns: The deserialized ``DataFrame``. """ serial_df = pd.read_parquet(fname) serial_df["structure"] = serial_df["structure"].map( lambda string: Structure.from_str(string, "json") ) return serial_df
def setUp(self): struct = Structure.from_str( """FCC Al 1.0 2.473329 0.000000 1.427977 0.824443 2.331877 1.427977 0.000000 0.000000 2.855955 Al 1 direct 0.000000 0.000000 0.000000 Al""", fmt="POSCAR", ) self.energies = [ -3.69150886, -3.70788383, -3.71997361, -3.72522301, -3.73569569, -3.73649743, -3.74054982, ] self.volumes = [ 14.824542034870653, 18.118887714656875, 15.373596786943025, 17.569833126580278, 15.92265868064787, 17.02077912220064, 16.471717630914863, ] self.eos = "vinet" self.T = 500 self.qhda = QuasiharmonicDebyeApprox( self.energies, self.volumes, struct, t_min=self.T, t_max=self.T, eos=self.eos, anharmonic_contribution=True, ) self.opt_vol = 17.216094889116807
def as_pymatgen_struc(self): """ Method that converts results to list of pymatgen strucutures Returns ------- struc : list List of pymatgen structures """ struc = [] for c in self.results: urlp = "http://" + c["path"][9:21] + ".org/" + c["path"][22:] + "/POSCAR" file = urllib.request.urlopen(urlp) poscar = "" for line in file: poscar += line.decode("utf-8") s = Structure.from_str(poscar, fmt="poscar") struc.append(s) return struc
def test_to_from_file_string(self): for fmt in ["cif", "json", "poscar", "cssr", "yaml", "xsf"]: s = self.structure.to(fmt=fmt) self.assertIsNotNone(s) ss = Structure.from_str(s, fmt=fmt) self.assertArrayAlmostEqual( ss.lattice.lengths_and_angles, self.structure.lattice.lengths_and_angles, decimal=5) self.assertArrayAlmostEqual(ss.frac_coords, self.structure.frac_coords) self.assertIsInstance(ss, Structure) self.structure.to(filename="POSCAR.testing") self.assertTrue(os.path.exists("POSCAR.testing")) os.remove("POSCAR.testing") self.structure.to(filename="structure_testing.json") self.assertTrue(os.path.exists("structure_testing.json")) s = Structure.from_file("structure_testing.json") self.assertEqual(s, self.structure) os.remove("structure_testing.json")
def test_(): structure = Structure.from_str(""" Na2 Cu2 O4 1.0 1.8088488050 -5.4059198794 0.0000000000 1.8088488050 5.4059198794 0.0000000000 0.0000000000 0.0000000000 5.3190514901 Na Cu O 2 2 4 direct 0.7123738820 0.2876261180 0.2500000000 Na 0.2876261180 0.7123738820 0.7500000000 Na 0.9970663194 0.0029336806 0.2500000000 Cu 0.0029336806 0.9970663194 0.7500000000 Cu 0.1138815169 0.8861184831 0.4939795157 O 0.8861184831 0.1138815169 0.5060204843 O 0.1138815169 0.8861184831 0.0060204843 O 0.8861184831 0.1138815169 0.9939795157 O """, fmt="POSCAR") symmetrizer = StructureSymmetrizer(structure) print(symmetrizer.primitive) sstructure = Structure.from_str(""" Na24 Cu24 O48 1.0 10.853093 0.000000 0.000000 0.000000 10.811840 0.000000 0.000000 0.000000 10.638103 Na Cu O 24 24 48 direct 0.166667 -0.212374 0.125000 Na 0.166667 -0.212374 0.625000 Na 0.500000 -0.212374 0.125000 Na 0.500000 -0.212374 0.625000 Na 0.833333 -0.212374 0.125000 Na 0.833333 -0.212374 0.625000 Na 0.333333 0.287626 0.125000 Na 0.333333 0.287626 0.625000 Na 0.666667 0.287626 0.125000 Na 0.666667 0.287626 0.625000 Na 1.000000 0.287626 0.125000 Na 1.000000 0.287626 0.625000 Na 0.166667 0.212374 0.375000 Na 0.166667 0.212374 0.875000 Na 0.500000 0.212374 0.375000 Na 0.500000 0.212374 0.875000 Na 0.833333 0.212374 0.375000 Na 0.833333 0.212374 0.875000 Na 0.333333 0.712374 0.375000 Na 0.333333 0.712374 0.875000 Na 0.666667 0.712374 0.375000 Na 0.666667 0.712374 0.875000 Na 1.000000 0.712374 0.375000 Na 1.000000 0.712374 0.875000 Na 0.166667 -0.497066 0.125000 Cu 0.166667 -0.497066 0.625000 Cu 0.500000 -0.497066 0.125000 Cu 0.500000 -0.497066 0.625000 Cu 0.833333 -0.497066 0.125000 Cu 0.833333 -0.497066 0.625000 Cu 0.333333 0.002934 0.125000 Cu 0.333333 0.002934 0.625000 Cu 0.666667 0.002934 0.125000 Cu 0.666667 0.002934 0.625000 Cu 1.000000 0.002934 0.125000 Cu 1.000000 0.002934 0.625000 Cu 0.166667 0.497066 0.375000 Cu 0.166667 0.497066 0.875000 Cu 0.500000 0.497066 0.375000 Cu 0.500000 0.497066 0.875000 Cu 0.833333 0.497066 0.375000 Cu 0.833333 0.497066 0.875000 Cu 0.333333 0.997066 0.375000 Cu 0.333333 0.997066 0.875000 Cu 0.666667 0.997066 0.375000 Cu 0.666667 0.997066 0.875000 Cu 1.000000 0.997066 0.375000 Cu 1.000000 0.997066 0.875000 Cu 0.166667 0.386118 0.246990 O 0.166667 0.386118 0.746990 O 0.500000 0.386118 0.246990 O 0.500000 0.386118 0.746990 O 0.833333 0.386118 0.246990 O 0.833333 0.386118 0.746990 O 0.333333 0.886118 0.246990 O 0.333333 0.886118 0.746990 O 0.666667 0.886118 0.246990 O 0.666667 0.886118 0.746990 O 1.000000 0.886118 0.246990 O 1.000000 0.886118 0.746990 O 0.166667 -0.386118 0.253010 O 0.166667 -0.386118 0.753010 O 0.500000 -0.386118 0.253010 O 0.500000 -0.386118 0.753010 O 0.833333 -0.386118 0.253010 O 0.833333 -0.386118 0.753010 O 0.333333 0.113882 0.253010 O 0.333333 0.113882 0.753010 O 0.666667 0.113882 0.253010 O 0.666667 0.113882 0.753010 O 1.000000 0.113882 0.253010 O 1.000000 0.113882 0.753010 O 0.166667 0.386118 0.003010 O 0.166667 0.386118 0.503010 O 0.500000 0.386118 0.003010 O 0.500000 0.386118 0.503010 O 0.833333 0.386118 0.003010 O 0.833333 0.386118 0.503010 O 0.333333 0.886118 0.003010 O 0.333333 0.886118 0.503010 O 0.666667 0.886118 0.003010 O 0.666667 0.886118 0.503010 O 1.000000 0.886118 0.003010 O 1.000000 0.886118 0.503010 O 0.166667 -0.386118 0.496990 O 0.166667 -0.386118 0.996990 O 0.500000 -0.386118 0.496990 O 0.500000 -0.386118 0.996990 O 0.833333 -0.386118 0.496990 O 0.833333 -0.386118 0.996990 O 0.333333 0.113882 0.496990 O 0.333333 0.113882 0.996990 O 0.666667 0.113882 0.496990 O 0.666667 0.113882 0.996990 O 1.000000 0.113882 0.496990 O 1.000000 0.113882 0.996990 O""", fmt="POSCAR") symmetrizer = StructureSymmetrizer(sstructure) print(symmetrizer.primitive)
def get_property_lattice(filename): s = read_and_trim(filename) s = clear_cif_from_crystalmaker(s) structure = Structure.from_str(s, 'cif') return structure.lattice