def from_dict(cls, d): if "config" in d: d = d["config"] params = cls() params.lat = Lattice(read_coords(d["unitcell"])) params.supercell = d.get("supercell", [1, 1, 1]) params.base_structure = base_structure(params.lat, d["base_structure"]) params.defect_sublattices = [ defect_sublattice.from_dict(ds) for ds in d["defect_structure"] ] params.num_defects = [ {g["name"]: g["num"] for g in ds["groups"]} for ds in d["defect_structure"] ] return params
def test_structure_to_composition(self): coords = [[0, 0, 0], [0.75, 0.5, 0.75]] lattice = Lattice([[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]) struct = Structure(lattice, ["Si"] * 2, coords) df = DataFrame(data={'structure': [struct]}) df["composition"] = structure_to_composition(df["structure"]) self.assertEqual(df["composition"].tolist()[0], Composition("Si2")) df["composition_red"] = structure_to_composition(df["structure"], reduce=True) self.assertEqual(df["composition_red"].tolist()[0], Composition("Si"))
def test_to_istructure(self): cscl = Structure( Lattice([[4.209, 0, 0], [0, 4.209, 0], [0, 0, 4.209]]), ["Cl", "Cs"], [[0.45, 0.5, 0.5], [0, 0, 0]]) df = DataFrame({"structure": [cscl]}) # Run the conversion sti = StructureToIStructure() df = sti.featurize_dataframe(df, 'structure') # Make sure the new structure is an IStructure, and equal # to the original structure self.assertIsInstance(df["istructure"][0], IStructure) self.assertEqual(df["istructure"][0], df["structure"][0])
def test_apply_transformation(self): sub_dict = {1: ["Na", "K"]} t = MultipleSubstitutionTransformation("Li+", 0.5, sub_dict, None) coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.75, 0.75]) coords.append([0.5, 0.5, 0.5]) coords.append([0.25, 0.25, 0.25]) lattice = Lattice([[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]) struct = Structure(lattice, ["Li+", "Li+", "O2-", "O2-"], coords) self.assertEqual( len(t.apply_transformation(struct, return_ranked_list=True)), 2)
def setUpClass(self): if "VASP_PSP_DIR" not in os.environ: os.environ["VASP_PSP_DIR"] = test_dir filepath = os.path.join(test_dir, 'POSCAR') poscar = Poscar.from_file(filepath) self.structure = poscar.structure self.coords = [[0, 0, 0], [0.75, 0.5, 0.75]] self.lattice = Lattice([[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]) self.mitset = MITRelaxSet(self.structure) self.mitset_unsorted = MITRelaxSet(self.structure, sort_structure=False) self.mpset = MPRelaxSet(self.structure)
def test_get_poscar(self): coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.5, 0.75]) lattice = Lattice([[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]) struct = Structure(lattice, ["Fe", "Mn"], coords) s_unsorted = self.mitparamset_unsorted.get_poscar(struct).structure s_sorted = self.mitparamset.get_poscar(struct).structure self.assertEqual(s_unsorted[0].specie.symbol, 'Fe') self.assertEqual(s_sorted[0].specie.symbol, 'Mn')
def test_apply_transformation(self): t = SubstitutionPredictorTransformation(threshold=1e-3, alpha=-5, lambda_table=get_table()) coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.75, 0.75]) coords.append([0.5, 0.5, 0.5]) lattice = Lattice([[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]) struct = Structure(lattice, ['O2-', 'Li1+', 'Li1+'], coords) outputs = t.apply_transformation(struct, return_ranked_list=True) self.assertEqual(len(outputs), 4, 'incorrect number of structures')
def test_nn_shell(self): # First, make a SC lattice. Make my math easier s = Structure([[1, 0, 0], [0, 1, 0], [0, 0, 1]], ['Cu'], [[0, 0, 0]]) # Get the 1NN shell self.nn.targets = None nns = self.nn.get_nn_shell_info(s, 0, 1) self.assertEqual(6, len(nns)) # Test the 2nd NN shell nns = self.nn.get_nn_shell_info(s, 0, 2) self.assertEqual(18, len(nns)) self.assertArrayAlmostEqual( [1] * 6, [x['weight'] for x in nns if max(np.abs(x['image'])) == 2]) self.assertArrayAlmostEqual( [2] * 12, [x['weight'] for x in nns if max(np.abs(x['image'])) == 1]) # Test the 3rd NN shell nns = self.nn.get_nn_shell_info(s, 0, 3) for nn in nns: # Check that the coordinates were set correctly self.assertArrayAlmostEqual(nn['site'].frac_coords, nn['image']) # Test with a structure that has unequal faces cscl = Structure(Lattice([[4.209, 0, 0], [0, 4.209, 0], [0, 0, 4.209]]), ["Cl1-", "Cs1+"], [[2.1045, 2.1045, 2.1045], [0, 0, 0]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.nn.weight = 'area' nns = self.nn.get_nn_shell_info(cscl, 0, 1) self.assertEqual(14, len(nns)) self.assertEqual(6, np.isclose([x['weight'] for x in nns], 0.125 / 0.32476).sum()) # Square faces self.assertEqual(8, np.isclose([x['weight'] for x in nns], 1).sum()) nns = self.nn.get_nn_shell_info(cscl, 0, 2) # Weight of getting back on to own site # Square-square hop: 6*5 options times (0.125/0.32476)^2 weight each # Hex-hex hop: 8*7 options times 1 weight each self.assertAlmostEqual( 60.4444, np.sum([x['weight'] for x in nns if x['site_index'] == 0]), places=3)
def test_structure_to_oxidstructure(self): cscl = Structure( Lattice([[4.209, 0, 0], [0, 4.209, 0], [0, 0, 4.209]]), ["Cl", "Cs"], [[0.45, 0.5, 0.5], [0, 0, 0]]) d = {'structure': [cscl]} df = DataFrame(data=d) sto = StructureToOxidStructure() df = sto.featurize_dataframe(df, 'structure') self.assertEqual(df["structure_oxid"].tolist()[0][0].specie.oxi_state, -1) self.assertEqual(df["structure_oxid"].tolist()[0][1].specie.oxi_state, +1) sto = StructureToOxidStructure(target_col_id='structure_oxid2', oxi_states_override={ "Cl": [-2], "Cs": [+2] }) df = sto.featurize_dataframe(df, 'structure') self.assertEqual(df["structure_oxid2"].tolist()[0][0].specie.oxi_state, -2) self.assertEqual(df["structure_oxid2"].tolist()[0][1].specie.oxi_state, +2) # original is preserved self.assertEqual(df["structure"].tolist()[0][0].specie, Element("Cl")) # test in-place sto = StructureToOxidStructure(target_col_id=None, overwrite_data=True) df = sto.featurize_dataframe(df, 'structure') self.assertEqual( df["structure"].iloc[0]["structure"].iloc[0][0].specie, Element("Cl")) # test error handling test_struct = Structure([5, 0, 0, 0, 5, 0, 0, 0, 5], ['Sb', 'F', 'O'], [[0, 0, 0], [0.2, 0.2, 0.2], [0.5, 0.5, 0.5]]) df = DataFrame(data={'structure': [test_struct]}) sto = StructureToOxidStructure(return_original_on_error=False, max_sites=2) self.assertRaises(ValueError, sto.featurize_dataframe, df, 'structure') # check non oxi state structure returned correctly sto = StructureToOxidStructure(return_original_on_error=True, max_sites=2) df = sto.featurize_dataframe(df, 'structure') self.assertEqual(df["structure_oxid"].tolist()[0][0].specie, Element("Sb"))
def interpolate(s1, s2, nimages): ''' doesn't relax either end ''' fcoords1 = np.array(s1.frac_coords) fcoords2 = np.array(s2.frac_coords) lvect = s2.lattice.matrix - s1.lattice.matrix fcvect = fcoords2 - fcoords1 - np.round(fcoords2 - fcoords1) structures = [] for x in xrange(nimages): l = Lattice(s1.lattice.matrix + x * lvect / (nimages - 1)) fc = fcoords1 + x * fcvect / (nimages - 1) s = Structure(l, s1.species, fc) structures.append(s) return structures
def test_get_potcar_symbols(self): coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.5, 0.75]) coords.append([0.75, 0.25, 0.75]) lattice = Lattice([[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]) struct = Structure(lattice, ["P", "Fe", "O"], coords) syms = self.paramset.get_potcar_symbols(struct) self.assertEqual(syms, ['Fe_pv', 'P', 'O']) syms = MPVaspInputSet(sort_structure=False).get_potcar_symbols(struct) self.assertEqual(syms, ['P', 'Fe_pv', 'O'])
def test_potcar_symbols(self): coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.5, 0.75]) coords.append([0.75, 0.25, 0.75]) lattice = Lattice([[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]) structure = Structure(lattice, ["P", "Fe", "O"], coords) mitparamset = MITRelaxSet(structure) syms = mitparamset.potcar_symbols self.assertEqual(syms, ['Fe', 'P', 'O']) paramset = MPRelaxSet(structure, sort_structure=False) syms = paramset.potcar_symbols self.assertEqual(syms, ['P', 'Fe_pv', 'O'])
def add_vacuum(structure, vacuum): """ Adds padding to a slab or 2D material. Args: structure (Structure): Structure to add vacuum to vacuum (float): Vacuum thickness to add in Angstroms Returns: Structure object with vacuum added. """ structure = align_axis(structure) lattice = np.array(structure.lattice.matrix) lattice[2][2] += vacuum structure.lattice = Lattice(lattice) return center_slab(structure)
def test_apply_transformation(self): t = ConventionalCellTransformation() coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.75, 0.75]) coords.append([0.5, 0.5, 0.5]) coords.append([0.25, 0.25, 0.25]) lattice = Lattice([ [3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603], ]) struct = Structure(lattice, ["Li+", "Li+", "O2-", "O2-"], coords) conventional_struct = t.apply_transformation(struct) self.assertEqual(conventional_struct.lattice.alpha, 90)
def test_too_small_cell(self): t = OrderDisorderedStructureTransformation() coords = list() coords.append([0.5, 0.5, 0.5]) lattice = Lattice([ [3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603], ]) struct = Structure(lattice, [{ "X4+": 0.33, "O2-": 0.33, "P5+": 0.33 }], coords) self.assertRaises(ValueError, t.apply_transformation, struct)
def setUp(self): self.diamond = Structure( Lattice([[2.189, 0, 1.264], [0.73, 2.064, 1.264], [0, 0, 2.528]]), ["C0+", "C0+"], [[2.554, 1.806, 4.423], [0.365, 0.258, 0.632]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.nacl = Structure( Lattice([[3.485, 0, 2.012], [1.162, 3.286, 2.012], [0, 0, 4.025]]), ["Na1+", "Cl1-"], [[0, 0, 0], [2.324, 1.643, 4.025]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.cscl = Structure( Lattice([[4.209, 0, 0], [0, 4.209, 0], [0, 0, 4.209]]), ["Cl1-", "Cs1+"], [[2.105, 2.105, 2.105], [0, 0, 0]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.mos2 = Structure( Lattice([[3.19, 0, 0], [-1.595, 2.763, 0], [0, 0, 17.44]]), ['Mo', 'S', 'S'], [[-1e-06, 1.842, 3.72], [1.595, 0.92, 5.29], \ [1.595, 0.92, 2.155]], coords_are_cartesian=True)
def test_apply_transformation(self): t = SubstitutionTransformation({"Li+": "Na+", "O2-": "S2-"}) coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.75, 0.75]) coords.append([0.5, 0.5, 0.5]) coords.append([0.25, 0.25, 0.25]) lattice = Lattice([ [3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603], ]) struct = Structure(lattice, ["Li+", "Li+", "O2-", "O2-"], coords) s = t.apply_transformation(struct) self.assertEqual(s.composition.formula, "Na2 S2")
def test_get_volumes(self): # lattice = Lattice([1, 0, 0, 0, 1, 0, 0, 0, 1]) lattice = Lattice([ [-1.14892994, 1.14892994, 1.14892994], [1.14892994, -1.14892994, 1.14892994], [1.14892994, 1.14892994, -1.14892994], ]) mesh = np.array([3, 3, 3]) kpoints = get_dense_kpoint_mesh_spglib(mesh) # extra_points = get_dense_kpoint_mesh_spglib([2, 1, 1]) / mesh + [-0.4, -0.4, -0.4] # print(extra_points) # extra_points = kpoints_to_first_bz(extra_points) # extra_points = np.array([[-0.4, -0.4, -0.4], [-0.23333333, -0.4, -0.4]]) extra_points = np.array([[-0.4, -0.4, -0.4]]) all_points = np.concatenate((kpoints, extra_points)) # extra_points = np.array([[0.49, 0.49, 0.49]]) #, [-0.49, 0.49, 0.49]]) # extra_points = np.array([[0.49, 0.49, 0.49], [-0.49, -0.49, -0.49]]) # extra_points = np.array([[-0.4, -0.4, 0.], [0.4, 0.4, 0.0]]) # [-0.49, -0.49, -0.1], [-0.49, 0.49, 0], # [-0.49, 0.49, 0.1], [-0.49, 0.49, -0.1], # [0.49, -0.49, 0], [0.49, -0.49, 0.1], # [0.49, -0.49, -0.1], [0.49, 0.49, 0.], # [0.49, 0.49, 0.1], [0.49, 0.49, -0.1], # ]) # extra_points = np.array([[-0.49, -0.49, 0.], [-0.49, -0.49, 0.1], # [-0.49, -0.49, -0.1], [-0.49, 0.49, 0], # [-0.49, 0.49, 0.1], [-0.49, 0.49, -0.1], # [0.49, -0.49, 0], [0.49, -0.49, 0.1], # [0.49, -0.49, -0.1], [0.49, 0.49, 0.], # [0.49, 0.49, 0.1], [0.49, 0.49, -0.1], # ]) # extra_points = np.array([[0.49, 0.49, 0.49], [-0.49, 0.49, 0.49], # [0.49, -0.49, 0.49], [0.49, 0.49, -0.49], # [-0.49, -0.49, 0.49], [-0.49, 0.49, -0.49], # [0.49, -0.49, -0.49], [-0.49, -0.49, -0.49], # ]) # extra_points = np.array([[0., 0.0, 0.1], [0, 0, -0.1]]) # extra_points = np.array([[0., 0.0, 0.1], [0, 0, -0.1], # [0, 0.1, 0], [0, -0.1, 0], # [0.1, 0, 0], [-0.1, 0, 0]]) pv = PeriodicVoronoi(lattice, kpoints, mesh, extra_points) volumes = pv.compute_volumes() print(kpoints)
def test_apply_transformation(self): t = PartialRemoveSpecieTransformation("Li+", 1.0 / 3, 3) coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.75, 0.75]) coords.append([0.5, 0.5, 0.5]) coords.append([0.25, 0.25, 0.25]) lattice = Lattice([[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]) struct = Structure(lattice, ["Li+", "Li+", "Li+", "O2-"], coords) self.assertEqual(len(t.apply_transformation(struct, 100)), 2) d = t.as_dict() self.assertEqual(type(PartialRemoveSpecieTransformation.from_dict(d)), PartialRemoveSpecieTransformation)
def test_false_potcar_hash(self): coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.5, 0.75]) coords.append([0.75, 0.25, 0.75]) lattice = Lattice([[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]) struct = Structure(lattice, ["P", "Fe", "O"], coords) self.mitparamset.potcar_settings['Fe']['symbol'] = 'Fe_pv' self.assertRaises(ValueError, self.mitparamset.get_potcar, struct, check_hash=True) self.mitparamset.potcar_settings['Fe']['symbol'] = 'Fe'
def test_fractional_substitution(self): t = SubstitutionTransformation({"Li+": "Na+", "O2-": {"S2-": 0.5, "Se2-": 0.5}}) # test the to and from dict on the nested dictionary t = SubstitutionTransformation.from_dict(t.as_dict()) coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.75, 0.75]) coords.append([0.5, 0.5, 0.5]) coords.append([0.25, 0.25, 0.25]) lattice = Lattice([[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]) struct = Structure(lattice, ["Li+", "Li+", "O2-", "O2-"], coords) s = t.apply_transformation(struct) self.assertEqual(s.composition.formula, "Na2 Se1 S1")
def build_structure(c): # filter coordinates c = c[np.linalg.norm(c[:, :2], axis=1) <= radius, :] # build lattice min_c = c.min(axis=0) max_c = c.max(axis=0) lattice = np.diag((max_c - min_c) + np.array([vacuum_sep, vacuum_sep, vacuum_sep])) # center flake in the unit cell c += np.sum(lattice, axis=0) / 2 - np.average(c, axis=0) return Structure( lattice=Lattice(lattice), species=[Element.C] * c.shape[0], coords=c, coords_are_cartesian=True, )
def _lattice_crossover(self): # ---------- component --> self.w_lat matrix = ((self.w_lat[0] * self.parent_A.lattice.matrix + self.w_lat[1] * self.parent_B.lattice.matrix) / self.w_lat.sum()) mat_len = np.sqrt((matrix**2).sum(axis=1)) # ---------- absolute value of vector lat_len = ((np.array(self.parent_A.lattice.abc) * self.w_lat[0] + np.array(self.parent_B.lattice.abc) * self.w_lat[1]) / self.w_lat.sum()) # ---------- correction of vector length lat_array = np.empty([3, 3]) for i in range(3): lat_array[i] = matrix[i] * lat_len[i] / mat_len[i] # ---------- Lattice for pymatgen self.lattice = Lattice(lat_array)
def test_structure_to_composition(self): coords = [[0, 0, 0], [0.75, 0.5, 0.75]] lattice = Lattice([[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]) struct = Structure(lattice, ["Si"] * 2, coords) df = DataFrame(data={'structure': [struct]}) stc = StructureToComposition() df = stc.featurize_dataframe(df, 'structure') self.assertEqual(df["composition"].tolist()[0], Composition("Si2")) stc = StructureToComposition(reduce=True, target_col_id='composition_red') df = stc.featurize_dataframe(df, 'structure') self.assertEqual(df["composition_red"].tolist()[0], Composition("Si"))
def test_apply_transformation_fast(self): t = PartialRemoveSpecieTransformation("Li+", 0.5) coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.75, 0.75]) coords.append([0.5, 0.5, 0.5]) coords.append([0.25, 0.25, 0.25]) coords.append([0.1, 0.1, 0.1]) coords.append([0.3, 0.75, 0.3]) lattice = Lattice([[10, 0.00, 0.00], [0, 10, 0.00], [0.00, 0, 10]]) struct = Structure(lattice, ["Li+"] * 6, coords) fast_opt_s = t.apply_transformation(struct) t = PartialRemoveSpecieTransformation("Li+", 0.5, PartialRemoveSpecieTransformation.ALGO_COMPLETE) slow_opt_s = t.apply_transformation(struct) self.assertAlmostEqual(EwaldSummation(fast_opt_s).total_energy, EwaldSummation(slow_opt_s).total_energy, 4) self.assertEqual(fast_opt_s, slow_opt_s)
def test_disordered(self): si = Element("Si") n = Element("N") coords = list() coords.append(np.array([0, 0, 0])) coords.append(np.array([0.75, 0.5, 0.75])) 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, [si, {si: 0.5, n: 0.5}], coords) writer = CifWriter(struct) ans = """# generated using pymatgen data_Si1.5N0.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 Si1.5N0.5 _chemical_formula_sum 'Si1.5 N0.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_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 Si Si0 1 0.00000000 0.00000000 0.00000000 1 Si Si1 1 0.75000000 0.50000000 0.75000000 0.5 N N2 1 0.75000000 0.50000000 0.75000000 0.5""" for l1, l2 in zip(str(writer).split("\n"), ans.split("\n")): self.assertEqual(l1.strip(), l2.strip())
def setUp(self): coords = list() coords.append([0, 0, 0]) coords.append([0.375, 0.375, 0.375]) coords.append([.5, .5, .5]) coords.append([0.875, 0.875, 0.875]) coords.append([0.125, 0.125, 0.125]) coords.append([0.25, 0.25, 0.25]) coords.append([0.625, 0.625, 0.625]) coords.append([0.75, 0.75, 0.75]) lattice = Lattice([[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]) self.struct = Structure( lattice, ["Li+", "Li+", "Li+", "Li+", "O2-", "O2-", "O2-", "O2-"], coords)
def test_apply_transformation(self): t = RemoveSpeciesTransformation(["Li+"]) coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.75, 0.75]) coords.append([0.5, 0.5, 0.5]) coords.append([0.25, 0.25, 0.25]) lattice = Lattice([[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]) struct = Structure(lattice, ["Li+", "Li+", "O2-", "O2-"], coords) s = t.apply_transformation(struct) self.assertEqual(s.composition.formula, "O2") d = t.as_dict() self.assertEqual(type(RemoveSpeciesTransformation.from_dict(d)), RemoveSpeciesTransformation)
def structure_2_lmpdata(structure, ff_elements=None, atom_style="charge"): """ Converts a structure to a LammpsData object with no force field parameters and topologies. Args: structure (Structure): Input structure. ff_elements ([str]): List of strings of elements that must be present due to force field settings but not necessarily in the structure. Default to None. atom_style (str): Choose between "atomic" (neutral) and "charge" (charged). Default to "charge". Returns: LammpsData """ s = structure.get_sorted_structure() a, b, c = s.lattice.abc m = s.lattice.matrix xhi = a xy = np.dot(m[1], m[0] / xhi) yhi = np.sqrt(b**2 - xy**2) xz = np.dot(m[2], m[0] / xhi) yz = (np.dot(m[1], m[2]) - xy * xz) / yhi zhi = np.sqrt(c**2 - xz**2 - yz**2) box_bounds = [[0.0, xhi], [0.0, yhi], [0.0, zhi]] box_tilt = [xy, xz, yz] box_tilt = None if not any(box_tilt) else box_tilt new_latt = Lattice([[xhi, 0, 0], [xy, yhi, 0], [xz, yz, zhi]]) s.modify_lattice(new_latt) symbols = list(s.symbol_set) if ff_elements: symbols.extend(ff_elements) elements = sorted(Element(el) for el in set(symbols)) mass_info = [tuple([i.symbol] * 2) for i in elements] ff = ForceField(mass_info) topo = Topology(s) return LammpsData.from_ff_and_topologies(ff=ff, topologies=[topo], box_bounds=box_bounds, box_tilt=box_tilt, atom_style=atom_style)
def read_cfgs(self, filename='output.data'): """ Args: filename (str): The configuration file to be read. """ data_pool = [] with zopen(filename, 'rt') as f: lines = f.read() block_pattern = re.compile('begin\n(.*?)end', re.S) lattice_pattern = re.compile('lattice(.*?)\n') position_pattern = re.compile('atom(.*?)\n') energy_pattern = re.compile('energy(.*?)\n') for block in block_pattern.findall(lines): d = {'outputs': {}} lattice_str = lattice_pattern.findall(block) lattice = Lattice( np.array([latt.split() for latt in lattice_str], dtype=np.float) * self.bohr_to_angstrom) position_str = position_pattern.findall(block) positions = pd.DataFrame([pos.split() for pos in position_str]) positions.columns = \ ['x', 'y', 'z', 'specie', 'charge', 'atomic_energy', 'fx', 'fy', 'fz'] coords = np.array(positions.loc[:, ['x', 'y', 'z']], dtype=np.float) coords = coords * self.bohr_to_angstrom species = np.array(positions['specie']) forces = np.array(positions.loc[:, ['fx', 'fy', 'fz']], dtype=np.float) forces = forces / self.eV_to_Ha / self.bohr_to_angstrom energy_str = energy_pattern.findall(block)[0] energy = float(energy_str.lstrip()) / self.eV_to_Ha struct = Structure(lattice=lattice, species=species, coords=coords, coords_are_cartesian=True) d['structure'] = struct.as_dict() d['outputs']['energy'] = energy d['outputs']['forces'] = forces d['num_atoms'] = len(struct) data_pool.append(d) _, df = convert_docs(docs=data_pool) return data_pool, df