def test_potcar_doenst_match_structure(self): compat = MITCompatibility() el_li = Element("Li") el_o = Element("O") el_h = Element("H") latt = Lattice.from_parameters(3.565276, 3.565276, 4.384277, 90.000000, 90.000000, 90.000000) elts = [el_h, el_h, el_li, el_li, el_o, el_o] coords = [[0.000000, 0.500000, 0.413969], [0.500000, 0.000000, 0.586031], [0.000000, 0.000000, 0.000000], [0.500000, 0.500000, 0.000000], [0.000000, 0.500000, 0.192672], [0.500000, 0.000000, 0.807328]] struct = Structure(latt, elts, coords) lioh_entry = ComputedStructureEntry(struct, -3, parameters={'is_hubbard': False, 'hubbards': None, 'run_type': 'GGA', 'potcar_symbols': ['PAW_PBE Fe 17Jan2003', 'PAW_PBE O 08Apr2002', 'PAW_PBE H 15Jun2001']}) self.assertIsNone(compat.process_entry(lioh_entry))
def cubic_supercell_info_wo_int(mocker, cubic_supercell): mock = mocker.patch("pydefect.util.structure_tools.defaults") mock.same_distance_criterion = defaults.same_distance_criterion mock.cutoff_distance_factor = 1.7 sites = { "H1": Site(element="H", wyckoff_letter="a", site_symmetry="m-3m", equivalent_atoms=[0, 1, 2, 3]), "He1": Site(element="He", wyckoff_letter="b", site_symmetry="m-3m", equivalent_atoms=[4, 5, 6, 7]) } unitcell = Structure(Lattice.rhombohedral(7.071068, 60), species=["H", "He"], coords=[[0.0] * 3, [0.5] * 3]) return SupercellInfo(cubic_supercell, "Fm-3m", [[-2, 2, 2], [2, -2, 2], [2, 2, -2]], sites, unitcell_structure=unitcell)
def test_process_entry_superoxide(self): el_li = Element("Li") el_o = Element("O") latt = Lattice([[3.985034, 0.0, 0.0], [0.0, 4.881506, 0.0], [0.0, 0.0, 2.959824]]) elts = [el_li, el_li, el_o, el_o, el_o, el_o] coords = list() coords.append([0.500000, 0.500000, 0.500000]) coords.append([0.0, 0.0, 0.0]) coords.append([0.632568, 0.085090, 0.500000]) coords.append([0.367432, 0.914910, 0.500000]) coords.append([0.132568, 0.414910, 0.000000]) coords.append([0.867432, 0.585090, 0.000000]) struct = Structure(latt, elts, coords) lio2_entry = ComputedStructureEntry(struct, -3, parameters={'is_hubbard': False, 'hubbards': None, 'run_type': 'GGA', 'potcar_symbols': ['PAW_PBE Fe 06Sep2000', 'PAW_PBE O 08Apr2002']}) lio2_entry_corrected = self.compat.process_entry(lio2_entry) self.assertAlmostEqual(lio2_entry_corrected.energy, -3 -0.13893*4, 4)
def from_lines(lines_cell, lines_atom): # ---------- lattice unit = lines_cell[0].split()[1] if unit[0] == '(' and unit[-1] == ')': unit = unit[1:-1] if unit.startswith('alat'): scale = float(unit[unit.index('=') + 1:]) # in Bohr scale = float(Length(scale, 'bohr').to('ang')) # in Ang elif unit == 'bohr': scale = float(Length(1.0, 'bohr').to('ang')) # in Ang elif unit == 'angstrom': scale = 1.0 # in Ang else: ValueError( 'unit "{0:s}" for CELL_PARAMETERS is not supported'.format(unit)) lattice = [[scale * float(x) for x in line.split()] for line in lines_cell[1:4]] # ---------- species & coordinates unit = lines_atom[0].split()[1] if unit[0] == '(' and unit[-1] == ')': unit = unit[1:-1] species = [] coords = [] for line in lines_atom[1:]: fields = line.split() species.append(fields[0]) coords.append([float(x) for x in fields[1:4]]) if unit == 'crystal': pass # 'coords' are already internal coordinates else: ValueError( 'unit "{0:s}" for ATOMIC_POSITIONS is not supported yet'. format(unit)) structure = Structure(lattice, species, coords) return structure
def extract(entry): struct = entry.structure spacegroup = entry.spacegroup pmg_s = Structure(struct.cell, struct.site_compositions, struct.site_coords) return OrderedDict([ ('id', entry.id), ('label', entry.label), ('proto_label', entry.proto_label), ('formula', entry.name), ('composition', entry.spec_comp), ('reduced_comp', entry.red_comp), ('unit_comp', entry.unit_comp), ('total_energy_pa', entry.total_energy), ('formation_energy_pa', entry.energy), ('experiment', entry.composition.experiment), ('mass', entry.mass), ('stable', entry.stable), ('e_above_hull', entry.formationenergy_set.first().stability), ('is_ordered', pmg_s.is_ordered), ('band_gap', entry.band_gap), ('spacegroup', spacegroup.hm), ('spacegroup_hall', spacegroup.hall), ('spacegroup_id', spacegroup.number), ('spacegroup_schoenflies', spacegroup.schoenflies), ('is_centro_symmetric', spacegroup.centrosymmetric), ('natoms', struct.natoms), ('ntypes', struct.ntypes), ('nsites', struct.nsites), # ('stresses', struct.stresses), # ('forces', struct.forces), ('volume', struct.volume), ('volume_pa', struct.volume_pa), # ('magmon', struct.magmom), # ('magmon_pa', struct.magmom_pa), ]), OrderedDict([('id', entry.id), ('structure', pmg_s.as_dict())])
def run_displacement(file_primitive, prefix, scaling_matrix, disp_magnitude_angstrom): qeobj = QEParser() qeobj.load_initial_structure(file_primitive) structure = Structure(qeobj.lattice_vector.transpose(), qeobj.kd_in_str, qeobj.x_fractional) Structure.make_supercell(structure, scaling_matrix) print("Supercell generated. # Atoms: %i" % structure.num_sites) print("") prefix0 = 'supercell' disp = np.zeros((structure.num_sites, 3)) # update structural information of qeobj qeobj_mod = update_qeobj(qeobj, structure) # create the supercell structure qeobj_mod.generate_structures(prefix0, ['original'], [disp]) # rename the file command = ("mv %s1.pw.in %s0.scf.in" % (prefix0, prefix0)) os.system(command) # Generate displacement files gen_alm_input('ALM0.in', prefix0, 'suggest', structure, 1, "*-* None") command = ("%s/alm/alm ALM0.in > ALM0.log" % ALAMODE_root) os.system(command) dispobj = AlamodeDisplace("fd", qeobj_mod, verbosity=0) header_list, disp_list \ = dispobj.generate(file_pattern=["%s.pattern_HARMONIC" % prefix0], magnitude=disp_magnitude_angstrom) qeobj_mod.generate_structures(prefix, header_list, disp_list)
def from_file(name): # ---------- last structure with open(name, 'r') as f: lines = f.readlines() for i, line in enumerate(lines): if 'ITEM: TIMESTEP' in line: tmp_lines = lines[i:i+rin.natot+9] lines = tmp_lines # ---------- lattice xlo_bound, xhi_bound, xy = [float(x) for x in lines[5].split()] ylo_bound, yhi_bound, xz = [float(x) for x in lines[6].split()] zlo_bound, zhi_bound, yz = [float(x) for x in lines[7].split()] xlo = xlo_bound - min(0.0, xy, xz, xy+xz) xhi = xhi_bound - max(0.0, xy, xz, xy+xz) ylo = ylo_bound - min(0.0, yz) yhi = yhi_bound - max(0.0, yz) zlo = zlo_bound zhi = zhi_bound a = [xhi-xlo, 0, 0] b = [xy, yhi-ylo, 0] c = [xz, yz, zhi-zlo] lattice = np.array([a, b, c]) # in Ang, each row is a lattice vector # ---------- non replica coordinates coords = [[float(x) for x in line.split()][2:] for line in lines[9:]] # ---------- species species = [itertools.repeat(typ, times=num) for typ, num in zip(rin.atype, rin.nat)] species = list(itertools.chain.from_iterable(species)) structure = Structure(lattice, species, coords) return structure
def test_interstice_distribution_of_glass(self): cuzr_glass = Structure(Lattice([[25, 0, 0], [0, 25, 0], [0, 0, 25]]), ["Cu", "Cu", "Cu", "Cu", "Cu", "Zr", "Cu", "Zr", "Cu", "Zr", "Cu", "Zr", "Cu", "Cu"], [[11.81159679, 16.49480537, 21.69139442], [11.16777208, 17.87850033, 18.57877144], [12.22394796, 15.83218325, 19.37763412], [13.07053548, 14.34025424, 21.77557646], [10.78147725, 19.61647494, 20.77595531], [10.87541011, 14.65986432, 23.61517624], [12.76631002, 18.41479521, 20.46717947], [14.63911675, 16.47487037, 20.52671362], [14.2470256, 18.44215167, 22.56257566], [9.38050168, 16.87974592, 20.51885879], [10.66332986, 14.43900833, 20.545186], [11.57096832, 18.79848982, 23.26073408], [13.27048138, 16.38613795, 23.59697472], [9.55774984, 17.09220537, 23.1856528]], coords_are_cartesian=True) df_glass= pd.DataFrame({'struct': [cuzr_glass], 'site': [0]}) interstice_distribution = IntersticeDistribution() intersticefp = interstice_distribution.featurize_dataframe( df_glass, ['struct', 'site']) self.assertAlmostEqual(intersticefp['Interstice_vol_mean'][0], 0.28905, 5) self.assertAlmostEqual(intersticefp['Interstice_vol_std_dev'][0], 0.04037, 5) self.assertAlmostEqual(intersticefp['Interstice_vol_minimum'][0], 0.21672, 5) self.assertAlmostEqual(intersticefp['Interstice_vol_maximum'][0], 0.39084, 5) self.assertAlmostEqual(intersticefp['Interstice_area_mean'][0], 0.16070, 5) self.assertAlmostEqual(intersticefp['Interstice_area_std_dev'][0], 0.05245, 5) self.assertAlmostEqual(intersticefp['Interstice_area_minimum'][0], 0.07132, 5) self.assertAlmostEqual(intersticefp['Interstice_area_maximum'][0], 0.26953, 5) self.assertAlmostEqual(intersticefp['Interstice_dist_mean'][0], 0.08154, 5) self.assertAlmostEqual(intersticefp['Interstice_dist_std_dev'][0], 0.14778, 5) self.assertAlmostEqual(intersticefp['Interstice_dist_minimum'][0], -0.04668, 5) self.assertAlmostEqual(intersticefp['Interstice_dist_maximum'][0], 0.37565, 5)
def __init__(self, structure: PymatgenStructure, aos: List[str], pbc: List[bool], ns: int = 1, na: int = 1, cutoff: float = 6.00): """ Parameters ---------- structure: : PymatgenStructure Pymatgen Structure object of the primitive cell used for calculating neighbors from lattice transformations.It also requires site_properties attribute with "Sitetypes"(Active or spectator site). aos: List[str] A list of all the active site species. For the Pt, N, NO configuration set it as ['0', '1', '2'] pbc: List[bool] Periodic Boundary Condition ns: int (default 1) The number of spectator types elements. For "S1" its 1. na: int (default 1) the number of active types elements. For "A1" its 1. cutoff: float (default 6.00) Cutoff of radius for getting local environment.Only used down to 2 digits. """ try: from pymatgen import Structure except: raise ImportError("This class requires pymatgen to be installed.") if type(structure) is not Structure: structure = Structure(**structure) self.aos = aos self.cutoff = np.around(cutoff, 2) self.setup_env = _load_primitive_cell(structure, aos, pbc, ns, na, cutoff)
def test_velocities(self): si = 14 coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.5, 0.75]) # Silicon structure for testing. latt = [ [3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603], ] struct = Structure(latt, [si, si], coords) poscar = Poscar(struct) poscar.set_temperature(900) v = np.array(poscar.velocities) for x in np.sum(v, axis=0): self.assertAlmostEqual(x, 0, 7) temperature = (struct[0].specie.atomic_mass.to("kg") * np.sum(v**2) / (3 * const.k) * 1e10) self.assertAlmostEqual(temperature, 900, 4, "Temperature instantiated incorrectly") poscar.set_temperature(700) v = np.array(poscar.velocities) for x in np.sum(v, axis=0): self.assertAlmostEqual( x, 0, 7, "Velocities initialized with a net momentum") temperature = (struct[0].specie.atomic_mass.to("kg") * np.sum(v**2) / (3 * const.k) * 1e10) self.assertAlmostEqual(temperature, 700, 4, "Temperature instantiated incorrectly")
def run_optimize(file_primitive, file_dfset, scaling_matrix): qeobj = QEParser() qeobj.load_initial_structure(file_primitive) structure = Structure(qeobj.lattice_vector.transpose(), qeobj.kd_in_str, qeobj.x_fractional) Structure.make_supercell(structure, scaling_matrix) print("Supercell generated. # Atoms: %i" % structure.num_sites) print("") prefix0 = 'supercell' # Generate displacement files gen_alm_input('ALM1.in', prefix0, 'optimize', structure, 1, "*-* None", dfset=file_dfset) command = ("%s/alm/alm ALM1.in > ALM1.log" % ALAMODE_root) os.system(command)
def test_from_seed(self): from pymatgen import Lattice, Structure coords = [[0, 0, 0], [0.75, 0.5, 0.75]] lattice = Lattice.from_parameters(a=3.84, b=3.84, c=3.84, alpha=120, beta=90, gamma=60) struct = Structure(lattice, ["Si", "C"], coords) s1 = pyxtal() s1.from_seed(struct) s2 = s1.subgroup_once(eps=0) pmg_s1 = s1.to_pymatgen() pmg_s2 = s2.to_pymatgen() self.assertTrue(sm.StructureMatcher().fit(pmg_s1, pmg_s2)) pmg_s1 = Structure.from_file(cif_path + "B28.vasp") struc = pyxtal() struc.from_seed(seed=cif_path + "B28.vasp") pmg_s2 = struc.to_pymatgen() self.assertTrue(sm.StructureMatcher().fit(pmg_s1, pmg_s2)) permutation = {"B": "C"} struc.subgroup_once(0.01, None, permutation, max_cell=2)
def test_aqueous_compat(self): el_li = Element("Li") el_o = Element("O") el_h = Element("H") latt = Lattice.from_parameters(3.565276, 3.565276, 4.384277, 90.000000, 90.000000, 90.000000) elts = [el_h, el_h, el_li, el_li, el_o, el_o] coords = [[0.000000, 0.500000, 0.413969], [0.500000, 0.000000, 0.586031], [0.000000, 0.000000, 0.000000], [0.500000, 0.500000, 0.000000], [0.000000, 0.500000, 0.192672], [0.500000, 0.000000, 0.807328]] struct = Structure(latt, elts, coords) lioh_entry = ComputedStructureEntry(struct, -3, parameters={'is_hubbard': False, 'hubbards': None, 'run_type': 'GGA', 'potcar_symbols': ['PAW_PBE Fe 17Jan2003', 'PAW_PBE O 08Apr2002', 'PAW_PBE H 15Jun2001']}) lioh_entry_compat = self.compat.process_entry(lioh_entry) lioh_entry_compat_aqcorr = self.aqcorr.correct_entry(lioh_entry_compat) lioh_entry_aqcompat = self.aqcompat.process_entry(lioh_entry) self.assertAlmostEqual(lioh_entry_compat_aqcorr.energy, lioh_entry_aqcompat.energy, 4)
def from_structure(cls, structure, ff_elements=None, atom_style="charge"): """ Simple constructor building LammpsData from a structure without 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". """ s = structure.get_sorted_structure() box, symmop = lattice_2_lmpbox(s.lattice) coords = symmop.operate_multi(s.cart_coords) site_properties = s.site_properties if "velocities" in site_properties: velos = np.array(s.site_properties["velocities"]) rot = SymmOp.from_rotation_and_translation(symmop.rotation_matrix) rot_velos = rot.operate_multi(velos) site_properties.update({"velocities": rot_velos}) boxed_s = Structure(box.to_lattice(), s.species, coords, site_properties=site_properties, coords_are_cartesian=True) 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(boxed_s) return cls.from_ff_and_topologies(box=box, ff=ff, topologies=[topo], atom_style=atom_style)
def get_recp_symmetry_operation( self, symprec: float = 0.01) -> List: """ Find the symmetric operations of the reciprocal lattice, to be used for hkl transformations Args: symprec: default is 0.001 """ recp_lattice = self.reciprocal_lattice_crystallographic # get symmetry operations from input conventional unit cell # Need to make sure recp lattice is big enough, otherwise symmetry # determination will fail. We set the overall volume to 1. recp_lattice = recp_lattice.scale(1) # need a localized import of structure to build a # pseudo empty lattice for SpacegroupAnalyzer from pymatgen import Structure from pymatgen.symmetry.analyzer import SpacegroupAnalyzer recp = Structure(recp_lattice, ["H"], [[0, 0, 0]]) # Creates a function that uses the symmetry operations in the # structure to find Miller indices that might give repetitive slabs analyzer = SpacegroupAnalyzer(recp, symprec=symprec) recp_symmops = analyzer.get_symmetry_operations() return recp_symmops
def test_peroxide_energy_corr(self): latt = Lattice.from_parameters(3.159597, 3.159572, 7.685205, 89.999884, 89.999674, 60.000510) el_li = Element("Li") el_o = Element("O") elts = [el_li, el_li, el_li, el_li, el_o, el_o, el_o, el_o] coords = [[0.666656, 0.666705, 0.750001], [0.333342, 0.333378, 0.250001], [0.000001, 0.000041, 0.500001], [0.000001, 0.000021, 0.000001], [0.333347, 0.333332, 0.649191], [0.333322, 0.333353, 0.850803], [0.666666, 0.666686, 0.350813], [0.666665, 0.666684, 0.149189]] struct = Structure(latt, elts, coords) li2o2_entry = ComputedStructureEntry(struct, -3, parameters={'is_hubbard': False, 'hubbards': None, 'run_type': 'GGA', 'potcar_symbols': ['PAW_PBE Fe 06Sep2000', 'PAW_PBE O 08Apr2002']}) li2o2_entry_corrected = self.compat.process_entry(li2o2_entry) self.assertRaises(AssertionError, self.assertAlmostEqual, *(li2o2_entry_corrected.energy, -3 - 0.44317 * 4, 4)) self.assertAlmostEqual(li2o2_entry_corrected.energy, -3 - 0.66975 * 4, 4)
def test_subset(self): sm = StructureMatcher(ltol=0.2, stol=0.3, angle_tol=5, primitive_cell=False, scale=True, attempt_supercell=False, allow_subset=True) l = Lattice.orthorhombic(10, 20, 30) s1 = Structure(l, ['Si', 'Si', 'Ag'], [[0, 0, 0.1], [0, 0, 0.2], [.7, .4, .5]]) s2 = Structure(l, ['Si', 'Ag'], [[0, 0.1, 0], [-.7, .5, .4]]) result = sm.get_s2_like_s1(s1, s2) self.assertEqual( len(find_in_coord_list_pbc(result.frac_coords, [0, 0, 0.1])), 1) self.assertEqual( len(find_in_coord_list_pbc(result.frac_coords, [0.7, 0.4, 0.5])), 1) #test with fewer species in s2 s1 = Structure(l, ['Si', 'Ag', 'Si'], [[0, 0, 0.1], [0, 0, 0.2], [.7, .4, .5]]) s2 = Structure(l, ['Si', 'Si'], [[0, 0.1, 0], [-.7, .5, .4]]) result = sm.get_s2_like_s1(s1, s2) mindists = np.min(s1.lattice.get_all_distances(s1.frac_coords, result.frac_coords), axis=0) self.assertLess(np.max(mindists), 1e-6) self.assertEqual( len(find_in_coord_list_pbc(result.frac_coords, [0, 0, 0.1])), 1) self.assertEqual( len(find_in_coord_list_pbc(result.frac_coords, [0.7, 0.4, 0.5])), 1) #test with not enough sites in s1 #test with fewer species in s2 s1 = Structure(l, ['Si', 'Ag', 'Cl'], [[0, 0, 0.1], [0, 0, 0.2], [.7, .4, .5]]) s2 = Structure(l, ['Si', 'Si'], [[0, 0.1, 0], [-.7, .5, .4]]) self.assertEqual(sm.get_s2_like_s1(s1, s2), None)
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.diamond_no_oxi = Structure( Lattice([[2.189, 0, 1.264], [0.73, 2.064, 1.264], [0, 0, 2.528]]), ["C", "C"], [[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.1045, 2.1045], [0, 0, 0]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.ni3al = Structure( Lattice([[3.52, 0, 0], [0, 3.52, 0], [0, 0, 3.52]]), ["Al", ] + ["Ni"] * 3, [[0, 0, 0], [0.5, 0.5, 0], [0.5, 0, 0.5], [0, 0.5, 0.5]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=False, site_properties=None) self.sc = Structure(Lattice([[3.52, 0, 0], [0, 3.52, 0], [0, 0, 3.52]]), ["Al"], [[0, 0, 0]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=False) self.bond_angles = range(5, 180, 5)
def get_spg(data): atomNames = data["name_array"] latt = data["finalpos"]["basis"] pos = data["finalpos"]["positions"] crystal = Structure(latt, atomNames, pos) return SpacegroupAnalyzer(crystal,symprec=0.02).get_space_group_symbol()
from pymatgen import Lattice, Structure from pymatgen.analysis.diffraction.xrd import XRDCalculator from IPython.display import Image, display from matplotlib import pyplot # Create CsCl structure a = 4.209 #Angstrom(埃:一个长度单位,用来表示原子尺寸、键长和电磁波波长。) latt = Lattice.cubic(a) #latt:点阵一个长度为a的立方体 #species:物质,这里是["Cs", "Cl"] #坐标:三位数组的列表,表示物质的坐标 structure = Structure(latt, ["Cs", "Cl"], [[0, 0, 0], [0.5, 0.5, 0.5]]) c = XRDCalculator() #get_plot返回的结果就是一个pyplot类型的图片 image = c.get_plot(structure, two_theta_range=(0, 90), annotate_peaks=True, ax=None, with_labels=True, fontsize=16) #image.show() image.savefig("alpha CsCl.jpg") #display(Image(filename=('./PDF - alpha CsCl.png'))) a = 6.923 #Angstrom latt = Lattice.cubic(a) structure = Structure(latt, ["Cs", "Cs", "Cs", "Cs", "Cl", "Cl", "Cl", "Cl"], [[0, 0, 0], [0.5, 0.5, 0], [0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0.5], [0, 0, 0.5], [0, 0.5, 0], [0.5, 0, 0]]) image = c.get_plot(structure, two_theta_range=(0, 90), annotate_peaks=True, ax=None, with_labels=True, fontsize=16) #display(Image(filename=('./PDF - beta CsCl.png')))这段代码display我还没有弄明白,帮我看看哪里出问题了
def test_write(self): cw_ref_string = """# generated using pymatgen data_GdB4 _symmetry_space_group_name_H-M 'P 1' _cell_length_a 7.13160000 _cell_length_b 7.13160000 _cell_length_c 4.05050000 _cell_angle_alpha 90.00000000 _cell_angle_beta 90.00000000 _cell_angle_gamma 90.00000000 _symmetry_Int_Tables_number 1 _chemical_formula_structural GdB4 _chemical_formula_sum 'Gd4 B16' _cell_volume 206.00729003 _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_occupancy Gd Gd0 1 0.31746000 0.81746000 0.00000000 1.0 Gd Gd1 1 0.18254000 0.31746000 0.00000000 1.0 Gd Gd2 1 0.81746000 0.68254000 0.00000000 1.0 Gd Gd3 1 0.68254000 0.18254000 0.00000000 1.0 B B4 1 0.00000000 0.00000000 0.20290000 1.0 B B5 1 0.50000000 0.50000000 0.79710000 1.0 B B6 1 0.00000000 0.00000000 0.79710000 1.0 B B7 1 0.50000000 0.50000000 0.20290000 1.0 B B8 1 0.17590000 0.03800000 0.50000000 1.0 B B9 1 0.96200000 0.17590000 0.50000000 1.0 B B10 1 0.03800000 0.82410000 0.50000000 1.0 B B11 1 0.67590000 0.46200000 0.50000000 1.0 B B12 1 0.32410000 0.53800000 0.50000000 1.0 B B13 1 0.82410000 0.96200000 0.50000000 1.0 B B14 1 0.53800000 0.67590000 0.50000000 1.0 B B15 1 0.46200000 0.32410000 0.50000000 1.0 B B16 1 0.08670000 0.58670000 0.50000000 1.0 B B17 1 0.41330000 0.08670000 0.50000000 1.0 B B18 1 0.58670000 0.91330000 0.50000000 1.0 B B19 1 0.91330000 0.41330000 0.50000000 1.0 loop_ _atom_site_moment_label _atom_site_moment_crystalaxis_x _atom_site_moment_crystalaxis_y _atom_site_moment_crystalaxis_z Gd0 5.05000000 5.05000000 0.00000000 Gd1 -5.05000000 5.05000000 0.00000000 Gd2 5.05000000 -5.05000000 0.00000000 Gd3 -5.05000000 -5.05000000 0.00000000 """ s_ncl = self.mcif_ncl.get_structures(primitive=False)[0] cw = CifWriter(s_ncl, write_magmoms=True) self.assertEqual(cw.__str__(), cw_ref_string) # from list-type magmoms list_magmoms = [list(m) for m in s_ncl.site_properties['magmom']] # float magmoms (magnitude only) float_magmoms = [float(m) for m in s_ncl.site_properties['magmom']] s_ncl.add_site_property('magmom', list_magmoms) cw = CifWriter(s_ncl, write_magmoms=True) self.assertEqual(cw.__str__(), cw_ref_string) s_ncl.add_site_property('magmom', float_magmoms) cw = CifWriter(s_ncl, write_magmoms=True) cw_ref_string_magnitudes = """# generated using pymatgen data_GdB4 _symmetry_space_group_name_H-M 'P 1' _cell_length_a 7.13160000 _cell_length_b 7.13160000 _cell_length_c 4.05050000 _cell_angle_alpha 90.00000000 _cell_angle_beta 90.00000000 _cell_angle_gamma 90.00000000 _symmetry_Int_Tables_number 1 _chemical_formula_structural GdB4 _chemical_formula_sum 'Gd4 B16' _cell_volume 206.00729003 _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_occupancy Gd Gd0 1 0.31746000 0.81746000 0.00000000 1.0 Gd Gd1 1 0.18254000 0.31746000 0.00000000 1.0 Gd Gd2 1 0.81746000 0.68254000 0.00000000 1.0 Gd Gd3 1 0.68254000 0.18254000 0.00000000 1.0 B B4 1 0.00000000 0.00000000 0.20290000 1.0 B B5 1 0.50000000 0.50000000 0.79710000 1.0 B B6 1 0.00000000 0.00000000 0.79710000 1.0 B B7 1 0.50000000 0.50000000 0.20290000 1.0 B B8 1 0.17590000 0.03800000 0.50000000 1.0 B B9 1 0.96200000 0.17590000 0.50000000 1.0 B B10 1 0.03800000 0.82410000 0.50000000 1.0 B B11 1 0.67590000 0.46200000 0.50000000 1.0 B B12 1 0.32410000 0.53800000 0.50000000 1.0 B B13 1 0.82410000 0.96200000 0.50000000 1.0 B B14 1 0.53800000 0.67590000 0.50000000 1.0 B B15 1 0.46200000 0.32410000 0.50000000 1.0 B B16 1 0.08670000 0.58670000 0.50000000 1.0 B B17 1 0.41330000 0.08670000 0.50000000 1.0 B B18 1 0.58670000 0.91330000 0.50000000 1.0 B B19 1 0.91330000 0.41330000 0.50000000 1.0 loop_ _atom_site_moment_label _atom_site_moment_crystalaxis_x _atom_site_moment_crystalaxis_y _atom_site_moment_crystalaxis_z Gd0 0.00000000 0.00000000 7.14177849 Gd1 0.00000000 0.00000000 7.14177849 Gd2 0.00000000 0.00000000 -7.14177849 Gd3 0.00000000 0.00000000 -7.14177849 """ self.assertEqual(cw.__str__().strip(), cw_ref_string_magnitudes.strip()) # test we're getting correct magmoms in ncl case s_ncl2 = self.mcif_ncl2.get_structures()[0] list_magmoms = [list(m) for m in s_ncl2.site_properties['magmom']] self.assertEqual(list_magmoms[0][0], 0.0) self.assertAlmostEqual(list_magmoms[0][1], 5.9160793408726366) self.assertAlmostEqual(list_magmoms[1][0], -5.1234749999999991) self.assertAlmostEqual(list_magmoms[1][1], 2.9580396704363183) # test creating an structure without oxidation state doesn't raise errors s_manual = Structure(Lattice.cubic(4.2), ["Cs", "Cl"], [[0, 0, 0], [0.5, 0.5, 0.5]]) s_manual.add_spin_by_site([1, -1]) cw = CifWriter(s_manual, write_magmoms=True) # check oxidation state cw_manual_oxi_string = """# generated using pymatgen data_CsCl _symmetry_space_group_name_H-M 'P 1' _cell_length_a 4.20000000 _cell_length_b 4.20000000 _cell_length_c 4.20000000 _cell_angle_alpha 90.00000000 _cell_angle_beta 90.00000000 _cell_angle_gamma 90.00000000 _symmetry_Int_Tables_number 1 _chemical_formula_structural CsCl _chemical_formula_sum 'Cs1 Cl1' _cell_volume 74.08800000 _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 Cs+ 1.0 Cl+ 1.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 Cs+ Cs0 1 0.00000000 0.00000000 0.00000000 1 Cl+ Cl1 1 0.50000000 0.50000000 0.50000000 1 loop_ _atom_site_moment_label _atom_site_moment_crystalaxis_x _atom_site_moment_crystalaxis_y _atom_site_moment_crystalaxis_z """ s_manual.add_oxidation_state_by_site([1, 1]) cw = CifWriter(s_manual, write_magmoms=True) self.assertEqual(cw.__str__(), cw_manual_oxi_string)
def setUp(self): self.single_bond = Structure(Lattice.from_lengths_and_angles( [10, 10, 10], [90, 90, 90]), ["H", "H", "H"], [[1, 0, 0], [0, 0, 0], [6, 0, 0]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.linear = Structure(Lattice.from_lengths_and_angles([10, 10, 10], [90, 90, 90]), ["H", "H", "H"], [[1, 0, 0], [0, 0, 0], [2, 0, 0]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.bent45 = Structure(Lattice.from_lengths_and_angles([10, 10, 10], [90, 90, 90]), ["H", "H", "H"], [[0, 0, 0], [0.707, 0.707, 0], [0.707, 0, 0]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.cubic = Structure(Lattice.from_lengths_and_angles([1, 1, 1], [90, 90, 90]), ["H"], [[0, 0, 0]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=False, site_properties=None) self.bcc = Structure(Lattice.from_lengths_and_angles([1, 1, 1], [90, 90, 90]), ["H", "H"], [[0, 0, 0], [0.5, 0.5, 0.5]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=False, site_properties=None) self.fcc = Structure( Lattice.from_lengths_and_angles([1, 1, 1], [90, 90, 90]), ["H", "H", "H", "H"], [[0, 0, 0], [0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=False, site_properties=None) self.hcp = Structure(Lattice.from_lengths_and_angles([1, 1, 1.633], [90, 90, 120]), ["H", "H"], [[0.3333, 0.6667, 0.25], [0.6667, 0.3333, 0.75]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=False, site_properties=None) self.diamond = Structure( Lattice.from_lengths_and_angles([1, 1, 1], [90, 90, 90]), ["H", "H", "H", "H", "H", "H", "H", "H"], [[0, 0, 0.5], [0.75, 0.75, 0.75], [0, 0.5, 0], [0.75, 0.25, 0.25], [0.5, 0, 0], [0.25, 0.75, 0.25], [0.5, 0.5, 0.5], [0.25, 0.25, 0.75]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=False, site_properties=None) self.trigonal_off_plane = Structure( Lattice.from_lengths_and_angles( [100, 100, 100], [90, 90, 90]), ["H", "H", "H", "H"], [[0.50, 0.50, 0.50], [0.25, 0.75, 0.25], \ [0.25, 0.25, 0.75], [0.75, 0.25, 0.25]], \ validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.regular_triangle = Structure( Lattice.from_lengths_and_angles( [30, 30, 30], [90, 90, 90]), ["H", "H", "H", "H"], [[15, 15.28867, 15.65], [14.5, 15, 15], [15.5, 15, 15], \ [15, 15.866, 15]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.trigonal_planar = Structure( Lattice.from_lengths_and_angles( [30, 30, 30], [90, 90, 90]), ["H", "H", "H", "H"], [[15, 15.28867, 15], [14.5, 15, 15], [15.5, 15, 15], \ [15, 15.866, 15]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.square_planar = Structure( Lattice.from_lengths_and_angles( [30, 30, 30], [90, 90, 90]), ["H", "H", "H", "H", "H"], [[15, 15, 15], [14.75, 14.75, 15], [14.75, 15.25, 15], \ [15.25, 14.75, 15], [15.25, 15.25, 15]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.square = Structure( Lattice.from_lengths_and_angles( [30, 30, 30], [90, 90, 90]), ["H", "H", "H", "H", "H"], [[15, 15, 15.707], [14.75, 14.75, 15], [14.75, 15.25, 15], \ [15.25, 14.75, 15], [15.25, 15.25, 15]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.T_shape = Structure( Lattice.from_lengths_and_angles([30, 30, 30], [90, 90, 90]), ["H", "H", "H", "H"], [[15, 15, 15], [15, 15, 15.5], [15, 15.5, 15], [15, 14.5, 15]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.square_pyramid = Structure( Lattice.from_lengths_and_angles([30, 30, 30], [90, 90, 90]), ["H", "H", "H", "H", "H", "H"], [[15, 15, 15], [15, 15, 15.3535], [14.75, 14.75, 15], [14.75, 15.25, 15], [15.25, 14.75, 15], [15.25, 15.25, 15]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.pentagonal_planar = Structure( Lattice.from_lengths_and_angles( [30, 30, 30], [90, 90, 90]), ["Xe", "F", "F", "F", "F", "F"], [[0, -1.6237, 0], [1.17969, 0, 0], [-1.17969, 0, 0], \ [1.90877, -2.24389, 0], [-1.90877, -2.24389, 0], [0, -3.6307, 0]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.pentagonal_pyramid = Structure( Lattice.from_lengths_and_angles( [30, 30, 30], [90, 90, 90]), ["Xe", "F", "F", "F", "F", "F", "F"], [[0, -1.6237, 0], [0, -1.6237, 1.17969], [1.17969, 0, 0], \ [-1.17969, 0, 0], [1.90877, -2.24389, 0], \ [-1.90877, -2.24389, 0], [0, -3.6307, 0]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.pentagonal_bipyramid = Structure( Lattice.from_lengths_and_angles( [30, 30, 30], [90, 90, 90]), ["Xe", "F", "F", "F", "F", "F", "F", "F"], [[0, -1.6237, 0], [0, -1.6237, -1.17969], \ [0, -1.6237, 1.17969], [1.17969, 0, 0], \ [-1.17969, 0, 0], [1.90877, -2.24389, 0], \ [-1.90877, -2.24389, 0], [0, -3.6307, 0]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.hexagonal_planar = Structure( Lattice.from_lengths_and_angles([30, 30, 30], [90, 90, 90]), ["H", "C", "C", "C", "C", "C", "C"], [[0, 0, 0], [0.71, 1.2298, 0], [-0.71, 1.2298, 0], [0.71, -1.2298, 0], [-0.71, -1.2298, 0], [1.4199, 0, 0], [-1.4199, 0, 0]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.hexagonal_pyramid = Structure( Lattice.from_lengths_and_angles( [30, 30, 30], [90, 90, 90]), \ ["H", "Li", "C", "C", "C", "C", "C", "C"], [[0, 0, 0], [0, 0, 1.675], [0.71, 1.2298, 0], \ [-0.71, 1.2298, 0], [0.71, -1.2298, 0], [-0.71, -1.2298, 0], \ [1.4199, 0, 0], [-1.4199, 0, 0]], \ validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.hexagonal_bipyramid = Structure( Lattice.from_lengths_and_angles( [30, 30, 30], [90, 90, 90]), \ ["H", "Li", "Li", "C", "C", "C", "C", "C", "C"], [[0, 0, 0], [0, 0, 1.675], [0, 0, -1.675], \ [0.71, 1.2298, 0], [-0.71, 1.2298, 0], \ [0.71, -1.2298, 0], [-0.71, -1.2298, 0], \ [1.4199, 0, 0], [-1.4199, 0, 0]], \ validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.trigonal_pyramid = Structure( Lattice.from_lengths_and_angles([30, 30, 30], [90, 90, 90]), ["P", "Cl", "Cl", "Cl", "Cl"], [[0, 0, 0], [0, 0, 2.14], [0, 2.02, 0], [1.74937, -1.01, 0], [-1.74937, -1.01, 0]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.trigonal_bipyramidal = Structure( Lattice.from_lengths_and_angles([30, 30, 30], [90, 90, 90]), ["P", "Cl", "Cl", "Cl", "Cl", "Cl"], [[0, 0, 0], [0, 0, 2.14], [0, 2.02, 0], [1.74937, -1.01, 0], [-1.74937, -1.01, 0], [0, 0, -2.14]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.cuboctahedron = Structure( Lattice.from_lengths_and_angles([30, 30, 30], [90, 90, 90]), ["H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H"], [[15, 15, 15], [15, 14.5, 14.5], [15, 14.5, 15.5], [ 15, 15.5, 14.5 ], [15, 15.5, 15.5], [14.5, 15, 14.5], [14.5, 15, 15.5], [15.5, 15, 14.5], [15.5, 15, 15.5], [14.5, 14.5, 15], [14.5, 15.5, 15], [15.5, 14.5, 15], [15.5, 15.5, 15]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None) self.see_saw_rect = Structure( Lattice.from_lengths_and_angles([30, 30, 30], [90, 90, 90]), ["H", "H", "H", "H", "H"], [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, -1.0], [-1.0, 0.0, 0.0]], validate_proximity=False, to_unit_cell=False, coords_are_cartesian=True, site_properties=None)
def test_supercell_subsets(self): sm = StructureMatcher(ltol=0.2, stol=0.3, angle_tol=5, primitive_cell=False, scale=True, attempt_supercell=True, allow_subset=True, supercell_size='volume') sm_no_s = StructureMatcher(ltol=0.2, stol=0.3, angle_tol=5, primitive_cell=False, scale=True, attempt_supercell=True, allow_subset=False, supercell_size='volume') l = Lattice.orthorhombic(1, 2, 3) s1 = Structure(l, ['Ag', 'Si', 'Si'], [[.7, .4, .5], [0, 0, 0.1], [0, 0, 0.2]]) s1.make_supercell([2, 1, 1]) s2 = Structure(l, ['Si', 'Si', 'Ag'], [[0, 0.1, -0.95], [0, 0.1, 0], [-.7, .5, .375]]) shuffle = [0, 2, 1, 3, 4, 5] s1 = Structure.from_sites([s1[i] for i in shuffle]) #test when s1 is exact supercell of s2 result = sm.get_s2_like_s1(s1, s2) for a, b in zip(s1, result): self.assertTrue(a.distance(b) < 0.08) self.assertEqual(a.species_and_occu, b.species_and_occu) self.assertTrue(sm.fit(s1, s2)) self.assertTrue(sm.fit(s2, s1)) self.assertTrue(sm_no_s.fit(s1, s2)) self.assertTrue(sm_no_s.fit(s2, s1)) rms = (0.048604032430991401, 0.059527539448807391) self.assertTrue(np.allclose(sm.get_rms_dist(s1, s2), rms)) self.assertTrue(np.allclose(sm.get_rms_dist(s2, s1), rms)) #test when the supercell is a subset of s2 subset_supercell = s1.copy() del subset_supercell[0] result = sm.get_s2_like_s1(subset_supercell, s2) self.assertEqual(len(result), 6) for a, b in zip(subset_supercell, result): self.assertTrue(a.distance(b) < 0.08) self.assertEqual(a.species_and_occu, b.species_and_occu) self.assertTrue(sm.fit(subset_supercell, s2)) self.assertTrue(sm.fit(s2, subset_supercell)) self.assertFalse(sm_no_s.fit(subset_supercell, s2)) self.assertFalse(sm_no_s.fit(s2, subset_supercell)) rms = (0.053243049896333279, 0.059527539448807336) self.assertTrue(np.allclose(sm.get_rms_dist(subset_supercell, s2), rms)) self.assertTrue(np.allclose(sm.get_rms_dist(s2, subset_supercell), rms)) #test when s2 (once made a supercell) is a subset of s1 s2_missing_site = s2.copy() del s2_missing_site[1] result = sm.get_s2_like_s1(s1, s2_missing_site) for a, b in zip((s1[i] for i in (0, 2, 4, 5)), result): self.assertTrue(a.distance(b) < 0.08) self.assertEqual(a.species_and_occu, b.species_and_occu) self.assertTrue(sm.fit(s1, s2_missing_site)) self.assertTrue(sm.fit(s2_missing_site, s1)) self.assertFalse(sm_no_s.fit(s1, s2_missing_site)) self.assertFalse(sm_no_s.fit(s2_missing_site, s1)) rms = (0.029763769724403633, 0.029763769724403987) self.assertTrue(np.allclose(sm.get_rms_dist(s1, s2_missing_site), rms)) self.assertTrue(np.allclose(sm.get_rms_dist(s2_missing_site, s1), rms))
def test_fit(self): """ Take two known matched structures 1) Ensure match 2) Ensure match after translation and rotations 3) Ensure no-match after large site translation 4) Ensure match after site shuffling """ sm = StructureMatcher() self.assertTrue(sm.fit(self.struct_list[0], self.struct_list[1])) # Test rotational/translational invariance op = SymmOp.from_axis_angle_and_translation([0, 0, 1], 30, False, np.array([0.4, 0.7, 0.9])) self.struct_list[1].apply_operation(op) self.assertTrue(sm.fit(self.struct_list[0], self.struct_list[1])) #Test failure under large atomic translation self.struct_list[1].translate_sites([0], [.4, .4, .2], frac_coords=True) self.assertFalse(sm.fit(self.struct_list[0], self.struct_list[1])) self.struct_list[1].translate_sites([0], [-.4, -.4, -.2], frac_coords=True) # random.shuffle(editor._sites) self.assertTrue(sm.fit(self.struct_list[0], self.struct_list[1])) #Test FrameworkComporator sm2 = StructureMatcher(comparator=FrameworkComparator()) lfp = self.get_structure("LiFePO4") nfp = self.get_structure("NaFePO4") self.assertTrue(sm2.fit(lfp, nfp)) self.assertFalse(sm.fit(lfp, nfp)) #Test anonymous fit. self.assertEqual(sm.fit_anonymous(lfp, nfp), True) self.assertAlmostEqual( sm.get_rms_anonymous(lfp, nfp)[0], 0.060895871160262717) #Test partial occupancies. s1 = Structure(Lattice.cubic(3), [{ "Fe": 0.5 }, { "Fe": 0.5 }, { "Fe": 0.5 }, { "Fe": 0.5 }], [[0, 0, 0], [0.25, 0.25, 0.25], [0.5, 0.5, 0.5], [0.75, 0.75, 0.75]]) s2 = Structure(Lattice.cubic(3), [{ "Fe": 0.25 }, { "Fe": 0.5 }, { "Fe": 0.5 }, { "Fe": 0.75 }], [[0, 0, 0], [0.25, 0.25, 0.25], [0.5, 0.5, 0.5], [0.75, 0.75, 0.75]]) self.assertFalse(sm.fit(s1, s2)) self.assertFalse(sm.fit(s2, s1)) s2 = Structure(Lattice.cubic(3), [{ "Mn": 0.5 }, { "Mn": 0.5 }, { "Mn": 0.5 }, { "Mn": 0.5 }], [[0, 0, 0], [0.25, 0.25, 0.25], [0.5, 0.5, 0.5], [0.75, 0.75, 0.75]]) self.assertEqual(sm.fit_anonymous(s1, s2), True) self.assertAlmostEqual(sm.get_rms_anonymous(s1, s2)[0], 0)
import dash_core_components as dcc from dash.dependencies import Input, Output, State from dash.exceptions import PreventUpdate # standard Crystal Toolkit import import crystal_toolkit.components as ctc from dash_mp_components import JsonView # import for this example from pymatgen import Structure, Lattice # create Dash app as normal app = dash.Dash() # create the Structure object structure = Structure(Lattice.cubic(4.2), ["Na", "K"], [[0, 0, 0], [0.5, 0.5, 0.5]]) from pymatgen import MPRester # create an input structure as an example structure_component = ctc.StructureMoleculeComponent( MPRester().get_structure_by_material_id("mp-804"), id="structure_in") # and a way to view the transformed structure structure_component_transformed = ctc.StructureMoleculeComponent( MPRester().get_structure_by_material_id("mp-804"), id="structure_out") # and the transformation component itself transformation_component = ctc.AllTransformationsComponent( input_structure_component=structure_component, ) # example layout to demonstrate capabilities of component
def test_oxide_type(self): el_li = Element("Li") el_o = Element("O") latt = Lattice([[3.985034, 0.0, 0.0], [0.0, 4.881506, 0.0], [0.0, 0.0, 2.959824]]) elts = [el_li, el_li, el_o, el_o, el_o, el_o] coords = list() coords.append([0.500000, 0.500000, 0.500000]) coords.append([0.0, 0.0, 0.0]) coords.append([0.632568, 0.085090, 0.500000]) coords.append([0.367432, 0.914910, 0.500000]) coords.append([0.132568, 0.414910, 0.000000]) coords.append([0.867432, 0.585090, 0.000000]) struct = Structure(latt, elts, coords) self.assertEqual(oxide_type(struct, 1.1), "superoxide") el_li = Element("Li") el_o = Element("O") elts = [el_li, el_o, el_o, el_o] latt = Lattice.from_parameters(3.999911, 3.999911, 3.999911, 133.847504, 102.228244, 95.477342) coords = [[0.513004, 0.513004, 1.000000], [0.017616, 0.017616, 0.000000], [0.649993, 0.874790, 0.775203], [0.099587, 0.874790, 0.224797]] struct = Structure(latt, elts, coords) self.assertEqual(oxide_type(struct, 1.1), "ozonide") latt = Lattice.from_parameters(3.159597, 3.159572, 7.685205, 89.999884, 89.999674, 60.000510) el_li = Element("Li") el_o = Element("O") elts = [el_li, el_li, el_li, el_li, el_o, el_o, el_o, el_o] coords = [[0.666656, 0.666705, 0.750001], [0.333342, 0.333378, 0.250001], [0.000001, 0.000041, 0.500001], [0.000001, 0.000021, 0.000001], [0.333347, 0.333332, 0.649191], [0.333322, 0.333353, 0.850803], [0.666666, 0.666686, 0.350813], [0.666665, 0.666684, 0.149189]] struct = Structure(latt, elts, coords) self.assertEqual(oxide_type(struct, 1.1), "peroxide") el_li = Element("Li") el_o = Element("O") el_h = Element("H") latt = Lattice.from_parameters(3.565276, 3.565276, 4.384277, 90.000000, 90.000000, 90.000000) elts = [el_h, el_h, el_li, el_li, el_o, el_o] coords = [[0.000000, 0.500000, 0.413969], [0.500000, 0.000000, 0.586031], [0.000000, 0.000000, 0.000000], [0.500000, 0.500000, 0.000000], [0.000000, 0.500000, 0.192672], [0.500000, 0.000000, 0.807328]] struct = Structure(latt, elts, coords) self.assertEqual(oxide_type(struct, 1.1), "hydroxide") el_li = Element("Li") el_n = Element("N") el_h = Element("H") latt = Lattice.from_parameters(3.565276, 3.565276, 4.384277, 90.000000, 90.000000, 90.000000) elts = [el_h, el_h, el_li, el_li, el_n, el_n] coords = [[0.000000, 0.500000, 0.413969], [0.500000, 0.000000, 0.586031], [0.000000, 0.000000, 0.000000], [0.500000, 0.500000, 0.000000], [0.000000, 0.500000, 0.192672], [0.500000, 0.000000, 0.807328]] struct = Structure(latt, elts, coords) self.assertEqual(oxide_type(struct, 1.1), "None") el_o = Element("O") latt = Lattice.from_parameters(4.389828, 5.369789, 5.369789, 70.786622, 69.244828, 69.244828) elts = [el_o, el_o, el_o, el_o, el_o, el_o, el_o, el_o] coords = [[0.844609, 0.273459, 0.786089], [0.155391, 0.213911, 0.726541], [0.155391, 0.726541, 0.213911], [0.844609, 0.786089, 0.273459], [0.821680, 0.207748, 0.207748], [0.178320, 0.792252, 0.792252], [0.132641, 0.148222, 0.148222], [0.867359, 0.851778, 0.851778]] struct = Structure(latt, elts, coords) self.assertEqual(oxide_type(struct, 1.1), "None")
def structure_from_string(data): """ Parses a rndstr.in or lat.in file into pymatgen's Structure format. :param data: contents of a rndstr.in or lat.in file :return: Structure object """ data = data.splitlines() data = [x.split() for x in data if x] # remove empty lines # following specification/terminology given in manual if len(data[0]) == 6: # lattice parameters a, b, c, alpha, beta, gamma = map(float, data[0]) coord_system = Lattice.from_parameters(a, b, c, alpha, beta, gamma).matrix lattice_vecs = np.array([ [data[1][0], data[1][1], data[1][2]], [data[2][0], data[2][1], data[2][2]], [data[3][0], data[3][1], data[3][2]] ], dtype=float) first_species_line = 4 else: coord_system = np.array([ [data[0][0], data[0][1], data[0][2]], [data[1][0], data[1][1], data[1][2]], [data[2][0], data[2][1], data[2][2]] ], dtype=float) lattice_vecs = np.array([ [data[3][0], data[3][1], data[3][2]], [data[4][0], data[4][1], data[4][2]], [data[5][0], data[5][1], data[5][2]] ], dtype=float) first_species_line = 6 scaled_matrix = np.matmul(coord_system, lattice_vecs) lattice = Lattice(scaled_matrix) all_coords = [] all_species = [] for l in data[first_species_line:]: all_coords.append(np.array([l[0], l[1], l[2]], dtype=float)) species_strs = "".join(l[3:]) # join multiple strings back together species_strs = species_strs.replace(" ", "") # trim any white space species_strs = species_strs.split(",") # comma-delimited species = {} for species_str in species_strs: species_str = species_str.split('=') if len(species_str) == 1: # assume occupancy is 1.0 species_str = [species_str[0], 1.0] try: species[Specie(species_str[0])] = float(species_str[1]) except Exception: species[DummySpecie(species_str[0])] = float(species_str[1]) all_species.append(species) return Structure(lattice, all_species, all_coords)
def setUp(self): self.diamond = Structure( Lattice([[2.189, 0, 1.264], [0.73, 2.064, 1.264], [0, 0, 2.528]]), ["C", "C"], [[2.554, 1.806, 4.423], [0.365, 0.258, 0.632]], coords_are_cartesian=True)
def read_cfgs(self, filename, predict=False): """ Args: filename (str): The configuration file to be read. """ type_convert = {'R': np.float32, 'I': np.int, 'S': np.str} data_pool = [] with zopen(filename, 'rt') as f: lines = f.read() repl = re.compile('AT ') lines = repl.sub('', string=lines) block_pattern = re.compile( '(\n[0-9]+\n|^[0-9]+\n)(.+?)(?=\n[0-9]+\n|$)', re.S) lattice_pattern = re.compile('Lattice="(.+)"') # energy_pattern = re.compile('dft_energy=(-?[0-9]+.[0-9]+)', re.I) energy_pattern = re.compile( r'(?<=\S{3}\s|dft_)energy=(-?[0-9]+.[0-9]+)') # stress_pattern = re.compile('dft_virial={(.+)}') stress_pattern = re.compile('dft_virial=({|)(.+?)(}|) \S.*') properties_pattern = re.compile('properties=(\S+)', re.I) # position_pattern = re.compile('\n(.+)', re.S) position_pattern = re.compile('\n(.+?)(?=\nE.*|\n\n.*|$)', re.S) # formatify = lambda string: [float(s) for s in string.split()] for (size, block) in block_pattern.findall(lines): d = {'outputs': {}} size = int(size) lattice_str = lattice_pattern.findall(block)[0] lattice = Lattice( list(map(lambda s: float(s), lattice_str.split()))) # energy_str = energy_pattern.findall(block)[0] energy_str = energy_pattern.findall(block)[-1] energy = float(energy_str) # stress_str = stress_pattern.findall(block)[0] stress_str = stress_pattern.findall(block)[0][1] virial_stress = np.array( list(map(lambda s: float(s), stress_str.split()))) virial_stress = [virial_stress[i] for i in [0, 4, 8, 1, 5, 6]] properties = properties_pattern.findall(block)[0].split(":") labels_columns = OrderedDict() labels = defaultdict() for i in range(0, len(properties), 3): labels_columns[properties[i]] = [ int(properties[i + 2]), properties[i + 1] ] position_str = position_pattern.findall(block)[0].split('\n') position = np.array([p.split() for p in position_str]) column_index = 0 for key in labels_columns: num_columns, dtype = labels_columns[key] labels[key] = position[:, column_index:column_index + num_columns].astype(type_convert[dtype]) column_index += num_columns struct = Structure(lattice=lattice, species=labels['species'].ravel(), coords=labels['pos'], coords_are_cartesian=True) if predict: forces = labels['force'] else: forces = labels['dft_force'] d['structure'] = struct.as_dict() d['outputs']['energy'] = energy assert size == struct.num_sites d['num_atoms'] = size d['outputs']['forces'] = forces d['outputs']['virial_stress'] = virial_stress data_pool.append(d) _, df = convert_docs(docs=data_pool) return data_pool, df
def test_two_targets(self): s = Structure(Lattice.cubic(3), ['Si'], [[0, 0, 0]]) # initialize the model self.model2.train([s, s], [[0.1, 0.2], [0.1, 0.2]], epochs=1) pred = self.model2.predict_structure(s) self.assertEqual(len(pred.ravel()), 2)