def test_molecular_trans(self): c1 = pyxtal(molecular=True) c1.from_seed(seed=cif_path + "aspirin.cif", molecules=["aspirin"]) pmg1 = c1.to_pymatgen() c1.transform(trans=[[1, 0, 0], [0, 1, 0], [-1, 0, 1]]) pmg2 = c1.to_pymatgen() c1.optimize_lattice() pmg3 = c1.to_pymatgen() self.assertTrue(sm.StructureMatcher().fit(pmg1, pmg2)) self.assertTrue(sm.StructureMatcher().fit(pmg2, pmg3))
def test_molecules(self): for name in ["aspirin", "resorcinol", "coumarin", "HAHCOI", "xxvi",\ "WEXBOS", "MERQIM", "LAGNAL", "YICMOP", "LUFHAW", "JAPWIH"]: cif = cif_path + name + ".cif" struc = pyxtal(molecular=True) struc.from_seed(seed=cif, molecules=[name]) pmg_struc = struc.to_pymatgen() pmg_s1 = Structure.from_file(cif) self.assertTrue(sm.StructureMatcher().fit(pmg_struc, pmg_s1)) if name not in ["resorcinol", "coumarin"]: Cs = struc.subgroup(eps=0, max_cell=1) for C in Cs: pmg_s2 = C.to_pymatgen() self.assertTrue(sm.StructureMatcher().fit( pmg_struc, pmg_s2))
def test_hydrate(self): # glycine dihydrate cif = cif_path + "gdh.cif" struc = pyxtal(molecular=True) struc.from_seed(seed=cif, molecules=['Glycine-z', 'H2O']) pmg_struc = struc.to_pymatgen() pmg_s1 = Structure.from_file(cif) self.assertTrue(sm.StructureMatcher().fit(pmg_struc, pmg_s1))
def test_atomic(self): s1 = pyxtal() s1.from_random(3, 36, ['C', 'Si'], [4, 8]) s2 = pyxtal() s2.load_dict(s1.save_dict()) pmg_s1 = s1.to_pymatgen() pmg_s2 = s2.to_pymatgen() self.assertTrue(sm.StructureMatcher().fit(pmg_s1, pmg_s2))
def test_molecular(self): s1 = pyxtal(molecular=True) s1.from_random(3, 36, ['H2O'], [4]) s2 = pyxtal() s2.load_dict(s1.save_dict()) pmg_s1 = s1.to_pymatgen() pmg_s2 = s2.to_pymatgen() self.assertTrue(sm.StructureMatcher().fit(pmg_s1, pmg_s2))
def test_molecular(self): c1 = pyxtal(molecular=True) c1.from_seed(seed=cif_path + "aspirin-c.cif", molecules=["aspirin"]) pmg1 = c1.to_pymatgen() c2 = c1.copy() c2.optimize_lattice(1) pmg2 = c2.to_pymatgen() self.assertTrue(sm.StructureMatcher().fit(pmg1, pmg2))
def test_atomic(self): c1 = pyxtal() c1.from_seed(cif_path + "LiCs.cif", backend='pyxtal') pmg1 = c1.to_pymatgen() c2 = c1.copy() c2.optimize_lattice(1) pmg2 = c2.to_pymatgen() self.assertTrue(sm.StructureMatcher().fit(pmg1, pmg2)) c2.optimize_lattice(1) pmg2 = c2.to_pymatgen() self.assertTrue(sm.StructureMatcher().fit(pmg1, pmg2)) c3 = pyxtal() c3.from_seed(cif_path + "LiCs.cif") pmg3 = c3.to_pymatgen() self.assertTrue(sm.StructureMatcher().fit(pmg1, pmg3))
def test_read(self): # test reading xtal from cif for name in ["FAU", "NaSb3F10", "PVO", "lt_quartz"]: cif_file = cif_path + name + ".cif" pmg1 = Structure.from_file(cif_file) struc = pyxtal() struc.from_seed(seed=cif_file) pmg_struc = struc.to_pymatgen() self.assertTrue(sm.StructureMatcher().fit(pmg_struc, pmg1))
def new_struc(db, s, eng): s_pmg = AseAtomsAdaptor().get_structure(s) for row in db.select(): ref = db.get_atoms(id=row.id) if abs(eng-row.ff_energy) < 1e-2: ref_pmg = AseAtomsAdaptor().get_structure(ref) if sm.StructureMatcher().fit(s_pmg, ref_pmg): return False return True
def test_read(self): # test reading structure from external struc = pyxtal(molecular=True) struc.from_seed(seed=cif_path + "aspirin.cif", molecule="aspirin") pmg_struc = struc.to_pymatgen() sga = SpacegroupAnalyzer(pmg_struc) self.assertTrue(sga.get_space_group_symbol() == "P2_1/c") C = struc.subgroup_once(eps=0, H=4) pmg_s2 = C.to_pymatgen() self.assertTrue(sm.StructureMatcher().fit(pmg_struc, pmg_s2))
def test_molecular_nodiag(self): sgs, diag = [5, 7, 8, 12, 13, 14], False for i in range(40): sg = choice(sgs) num = len(Group(sg)[0]) c1 = pyxtal(molecular=True) c1.from_random(3, sg, ["aspirin"], [num], diag=diag) pmg1 = c1.to_pymatgen() c2 = c1.copy() c2.optimize_lattice(1) pmg2 = c2.to_pymatgen() self.assertTrue(sm.StructureMatcher().fit(pmg1, pmg2))
def new_structure(struc, refs): """ check if struc is already in the reference solutions """ g1 = struc.group.number pmg1 = struc.to_pymatgen() for ref in refs: g2 = ref.group.number if g1 == g2: pmg2 = ref.to_pymatgen() if sm.StructureMatcher().fit(pmg1, pmg2): return False return True
def test_cubic_cubic(self): sites = ['8a', '32e'] numIons = int(sum([int(i[:-1]) for i in sites])) C1 = pyxtal() C1.from_random(3, 227, ['C'], [numIons], sites=[sites]) pmg_s1 = C1.to_pymatgen() sga1 = SpacegroupAnalyzer(pmg_s1).get_space_group_symbol() C2s = C1.subgroup(eps=1e-4) for C2 in C2s: pmg_s2 = C2.to_pymatgen() sga2 = SpacegroupAnalyzer(pmg_s2).get_space_group_symbol() self.assertTrue(sm.StructureMatcher().fit(pmg_s1, pmg_s2))
def test_molecules(self): for name in [ "HAHCOI", "WEXBOS", "MERQIM", "LAGNAL", "YICMOP", "LUFHAW", "JAPWIH" ]: cif = cif_path + name + ".cif" struc = pyxtal(molecular=True) struc.from_seed(seed=cif, molecule=name) pmg_struc = struc.to_pymatgen() Cs = struc.subgroup(eps=0, max_cell=1) for C in Cs: pmg_s2 = C.to_pymatgen() self.assertTrue(sm.StructureMatcher().fit(pmg_struc, pmg_s2))
def test_alternative(self): for name in [ "BTO-Amm2", "lt_quartz", "GeF2", "lt_cristobalite", "PVO" ]: s = pyxtal() s.from_seed(cif_path + name + '.cif') pmg_s1 = s.to_pymatgen() strucs = s.get_alternatives() for struc in strucs: pmg_s2 = struc.to_pymatgen() #if not sm.StructureMatcher().fit(pmg_s1, pmg_s2): # print(struc) # print(s) self.assertTrue(sm.StructureMatcher().fit(pmg_s1, pmg_s2))
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_from_seed(self): coords = [[0, 0, 0], [0.75, 0.5, 0.75]] lattice = pmg_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))
def test_cubic_cubic(self): sites = ['8a', '32e'] G, fac = 227, 4 numIons = int(sum([int(i[:-1]) for i in sites]) / fac) while True: C1 = random_crystal(G, ['C'], [numIons], sites=[sites]) if C1.valid: break pmg_s1 = C1.to_pymatgen() sga1 = SpacegroupAnalyzer(pmg_s1).get_space_group_symbol() C2s = C1.subgroup() for C2 in C2s: pmg_s2 = C2.to_pymatgen() sga2 = SpacegroupAnalyzer(pmg_s2).get_space_group_symbol() self.assertTrue(sm.StructureMatcher().fit(pmg_s1, pmg_s2))
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 = random_crystal(seed=struct) s2 = s1.subgroup(once=True) pmg_s1 = s1.to_pymatgen() pmg_s2 = s2.to_pymatgen() #sga1 = SpacegroupAnalyzer(pmg_s1).get_space_group_symbol() #sga2 = SpacegroupAnalyzer(pmg_s2).get_space_group_symbol() self.assertTrue(sm.StructureMatcher().fit(pmg_s1, pmg_s2))
C1 = pyxtal() C1.from_random(3, G, ['C'], [g[0].multiplicity], sites=[[letter]]) #print(C1) pmg_s1 = C1.to_pymatgen() sga1 = SpacegroupAnalyzer(pmg_s1).get_space_group_symbol() # each subgroup #C2s = C1.subgroup(eps=0, group_type='t') try: C2s = C1.subgroup(eps=0, group_type='k', max_cell=4) for C2 in C2s: #print(C2) pmg_s2 = C2.to_pymatgen() try: sga2 = SpacegroupAnalyzer( pmg_s2, symprec=1e-4).get_space_group_symbol() except: #print("unable to find the space group") sga2 = None print(G, C2.group.number, g.symbol, C2.group.symbol, sga1, sga2) if not sm.StructureMatcher().fit(pmg_s1, pmg_s2): print('WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW') print(C1) print(C2) except RuntimeError: pass #print(pmg_s1) #print(pmg_s2) #print(tran[i]) #import sys; sys.exit()
for para in paras: name, H, gtype = para name = "pyxtal/miscellaneous/cifs/" + name + ".cif" print(name) s = pyxtal() s.from_seed(name) pmg_s1 = s.to_pymatgen() G = s.group.number for i in range(10): struc_h = s.subgroup_once(eps=0.15, H=H, group_type=gtype, mut_lat=False, max_cell=4) #print(struc_h) #print(s) sup = supergroups(struc_h, G=G, d_tol=0.2, show=True, max_per_G=500) if sup.strucs is not None: match = False for struc in sup.strucs: pmg_g = struc.to_pymatgen() if sm.StructureMatcher().fit(pmg_g, pmg_s1): match = True break if not match: print("==Wrong: cannot recover the original structure") else: print(sup) print("==Error: cannot generate structure") break
return None, None, 0, True elif adjust and abs(energy) < 1e-8: matrix = struc.lattice.matrix struc.lattice.set_matrix(matrix * 0.8) return struc, energy, time_total, False if __name__ == "__main__": while True: struc = pyxtal() struc.from_random(3, 19, ["C"], [4]) if struc.valid: break pmg1 = struc.to_pymatgen() calc = GULP(struc, opt="single", ff="tersoff.lib") calc.run() print(calc.energy) print(calc.stress) print(calc.forces) pmg2 = calc.to_pymatgen() import pymatgen.analysis.structure_matcher as sm print(sm.StructureMatcher().fit(pmg1, pmg2)) struc, eng, time, _ = optimize(struc, ff="tersoff.lib") print(struc) print(eng) print(time)
from pymatgen import Structure from pyxtal import pyxtal from pyxtal.supergroup import supergroups for i, name in enumerate(glob("pyxtal/miscellaneous/cifs/*.cif")): # 1, read from cif s = pyxtal() s.from_seed(name) pmg_s1 = s.to_pymatgen() pmg0 = Structure.from_file(name) G = s.group.number print(i, name, len(s.atom_sites)) if len(s.atom_sites) <= 10: if not sm.StructureMatcher().fit(pmg_s1, pmg0): print("Error in reading cif") # 2, alternative setting strucs = s.get_alternatives() for i, struc in enumerate(strucs): pmg_s2 = struc.to_pymatgen() if not sm.StructureMatcher().fit(pmg_s1, pmg_s2): print("Error in alternative setting") print(s) print(struc) break # 3, subgroup for gtype in ['t', 'k']: valid = True
# C1 = random_crystal(G, ['C'], [numIons], sites=[sites]) # C2 = C1.subgroup(H=H) # #print(C1) # #print(C2) # pmg_s1 = C1.to_pymatgen() # pmg_s2 = C2.to_pymatgen() # sga1 = SpacegroupAnalyzer(pmg_s1).get_space_group_symbol() # sga2 = SpacegroupAnalyzer(pmg_s2).get_space_group_symbol() # print(i, sga1, sga2, sm.StructureMatcher().fit(pmg_s1, pmg_s2)) # if not sm.StructureMatcher().fit(pmg_s1, pmg_s2): # import sys # sys.exit() G, fac = 227, 4 sites = ['8a', '32e'] #for H in [166, 141, 203, 210, 216]: for H in [203, 210, 216]: for i in range(10): numIons = int(sum([int(i[:-1]) for i in sites]) / fac) C1 = random_crystal(G, ['C'], [numIons], sites=[sites]) C2 = C1.subgroup(H=H) #print(C1) #print(C2) pmg_s1 = C1.to_pymatgen() pmg_s2 = C2.to_pymatgen() sga1 = SpacegroupAnalyzer(pmg_s1).get_space_group_symbol() sga2 = SpacegroupAnalyzer(pmg_s2).get_space_group_symbol() print(i, sga1, sga2, sm.StructureMatcher().fit(pmg_s1, pmg_s2)) if not sm.StructureMatcher().fit(pmg_s1, pmg_s2): import sys sys.exit()
howcome = POPULATION[0][0]['howCome'][0][i][0] energy = POPULATION[0][0]['Enthalpies'][0][i][0][-1] fitness = POPULATION[0][0]['Fitness'][0][i][0][-1] s = []; for el,num in zip(Element,numIons[0]): s = s + ([el]*num) Struc.append(mg.Structure(lattice, s, coord)) Origin.append(howcome) Energy.append(energy/sum(numIons[0])) Fitness.append(fitness) if options.compare: # check s1 = mg.Structure.from_file(options.compare) for i, s0 in enumerate(Struc): dist = sm.StructureMatcher().fit(s1, s0) p1 = ['{:6.3f}'.format(j) for j in s0.lattice.abc] p2 = ['{:6.2f}'.format(j) for j in s0.lattice.angles] s = ' '.join(map(str,p1+p2)) spg = SpacegroupAnalyzer(s0, symprec=options.tol).get_space_group_symbol() print('{0:4d} {1:40s} {2:12s} {3:9.3f} {4:10s} {5:4b}'.format(i+1, s, spg, Energy[i], Origin[i], dist)) if dist: break else: Fitness = np.array(Fitness) Ranking = np.argsort(Fitness) ids = [Ranking[0] + 1] struc_out = [Struc[Ranking[0]]] energy_out = [Energy[Ranking[0]]] fitness_out = [Fitness[Ranking[0]]] for i in Ranking[1:]:
G, H, fac = 227, 166, 4 numIons = int(sum([int(i[:-1]) for i in sites]) / fac) C = random_crystal(G, ['C'], [numIons], sites=[sites]) spg1 = get_symmetry_dataset(C.to_ase(), symprec=1e-4)['international'] splitter = wyckoff_split(G=G, H=H, wp1=sites) print(splitter) lat1 = np.dot(C.lattice.matrix, splitter.R[:3, :3].T) pos1 = None for i, site in enumerate(C.atom_sites): pos = site.position for ops1, ops2 in zip(splitter.G2_orbits[i], splitter.H_orbits[i]): pos0 = pos + 0.05 * (np.random.sample(3) - 0.5) #print(pos0) pos_tmp = apply_ops(pos0, ops1) pos_tmp = apply_ops(pos_tmp[0], ops2) if pos1 is None: pos1 = pos_tmp else: pos1 = np.vstack((pos1, pos_tmp)) C1 = Atoms(["C"] * len(pos1), scaled_positions=pos1, cell=lat1, pbc=[1, 1, 1]) C1.write("1.vasp", format='vasp', vasp5=True, direct=True) C.to_ase().write("0.vasp", format='vasp', vasp5=True, direct=True) pmg_s1 = AseAtomsAdaptor.get_structure(C1) spg2 = get_symmetry_dataset(C1, symprec=1e-4)['international'] print(spg1, spg2, sm.StructureMatcher().fit(pmg_s1, C.to_pymatgen()))
def struc_matcher_cmd(argv=None): # IGNORE:C0111 '''Command line options.''' if argv is None: argv = sys.argv else: sys.argv.extend(argv) program_name = os.path.basename(sys.argv[0]) program_version = "v%s" % __version__ program_build_date = str(__updated__) program_version_message = '%%(prog)s %s (%s)' % (program_version, program_build_date) program_shortdesc = __import__('__main__').__doc__.split("\n")[1] program_license = '''%s Created by hebing on %s. Copyright 2017 School of Computer Engineering and Science, ShangHai University. All rights reserved. USAGE ''' % (program_shortdesc, str(__date__)) try: # Setup argument parser parser = ArgumentParser(description=program_license, formatter_class=RawDescriptionHelpFormatter) parser.add_argument("-e", "--elements", nargs=1, dest="elements", action="store", help=" 堆积原子的元素种类") parser.add_argument("-l", "--ltol", dest="ltol", action="store", type=float, default=0.2, help=" 分数长度容差[缺省: %(default)s]") parser.add_argument("-s", "--stol", dest="stol", action="store", type=float, default=1, help=" rms长度容差[缺省: %(default)s]") parser.add_argument("-a", "--angle_tol", dest="angle_tol", action="store", type=float, default=5, help=" 角度容差(单位:度)[缺省: %(default)s]") parser.add_argument("-infile", action="store", help=" 结构文件名") parser.add_argument("-batch", action="store", type=bool, default=False, help=" 批量读入cifs文件夹下的结构文件") # Process arguments args = parser.parse_args() lentol = args.ltol atol = args.angle_tol stol = args.stol elements = args.elements batch = args.batch if not batch: infile = args.infile print(args.infile) stru = cstructure.from_file(infile) stru.save_species(elements) V = stru.volume n = stru.num_sites stol = 0.3 * (V / n)**(1 / 3) bccstruct = CreateTemplateStructure('bcc', 3.0, stru.species[0]) fccstruct = CreateTemplateStructure('fcc', 3.0, stru.species[0]) hcpstruct = CreateTemplateStructure('hcp', 3.0, stru.species[0]) pcomp = pmgmach.StructureMatcher(ltol=lentol, stol=stol, angle_tol=atol, primitive_cell=False, attempt_supercell=True) print( 'Structure like bcc is {}.'.format(pcomp.fit(stru, bccstruct)), 'RMS displacement between two structures and max maximum distance between paired sites is {}' .format(pcomp.get_rms_dist(stru, bccstruct))) print( 'Structure like fcc is {}.'.format(pcomp.fit(stru, fccstruct)), 'RMS displacement between two structures and max maximum distance between paired sites is {}' .format(pcomp.get_rms_dist(stru, fccstruct))) print( 'Structure like hcp is {}.'.format(pcomp.fit(stru, hcpstruct)), 'RMS displacement between two structures and max maximum distance between paired sites is {}' .format(pcomp.get_rms_dist(stru, hcpstruct))) else: path = "./cifs/" filetype = ".cif" results = [] filenames = batch_read_filename(path, filetype) print(filenames) for file in filenames: infile = path + file stru = cstructure.from_file(infile) stru.save_species(elements) V = stru.volume n = stru.num_sites stol = 0.3 * (V / n)**(1 / 3) bccstruct = CreateTemplateStructure('bcc', 3.0, stru.species[0]) fccstruct = CreateTemplateStructure('fcc', 3.0, stru.species[0]) hcpstruct = CreateTemplateStructure('hcp', 3.0, stru.species[0]) pcomp = pmgmach.StructureMatcher(ltol=lentol, stol=stol, angle_tol=atol, primitive_cell=False, attempt_supercell=True) results.append(infile+'\t' \ +str(pcomp.fit(stru,bccstruct))+'\t'+str(pcomp.get_rms_dist(stru,bccstruct))+'\t' \ +str(pcomp.fit(stru,fccstruct))+'\t'+str(pcomp.get_rms_dist(stru,fccstruct))+'\t' \ +str(pcomp.fit(stru,hcpstruct))+'\t'+str(pcomp.get_rms_dist(stru,hcpstruct))) #print(results) write_to_excel(results) print("Matcher completed!") except KeyboardInterrupt: ### handle keyboard interrupt ### return 0
def struc_matcher(element, infile, batch=False, ltol=0.2, stol=1, atol=5): # IGNORE:C0111 try: if not batch: stru = cstructure.from_file(infile) stru.save_species(element) V = stru.volume n = stru.num_sites stol = 0.3 * (V / n)**(1 / 3) bccstruct = CreateTemplateStructure('bcc', 3.0, stru.species[0]) fccstruct = CreateTemplateStructure('fcc', 3.0, stru.species[0]) hcpstruct = CreateTemplateStructure('hcp', 3.0, stru.species[0]) pcomp = pmgmach.StructureMatcher(ltol=ltol, stol=stol, angle_tol=atol, primitive_cell=False, attempt_supercell=True) print( 'Structure like bcc is {}.'.format(pcomp.fit(stru, bccstruct)), 'RMS displacement between two structures and max maximum distance between paired sites is {}' .format(pcomp.get_rms_dist(stru, bccstruct))) print( 'Structure like fcc is {}.'.format(pcomp.fit(stru, fccstruct)), 'RMS displacement between two structures and max maximum distance between paired sites is {}' .format(pcomp.get_rms_dist(stru, fccstruct))) print( 'Structure like hcp is {}.'.format(pcomp.fit(stru, hcpstruct)), 'RMS displacement between two structures and max maximum distance between paired sites is {}' .format(pcomp.get_rms_dist(stru, hcpstruct))) else: path = infile filetype = ".cif" results = [] filenames = batch_read_filename(path, filetype) print(filenames) for file in filenames: infile = path + file stru = cstructure.from_file(infile) stru.save_species(element) V = stru.volume n = stru.num_sites stol = 0.3 * (V / n)**(1 / 3) bccstruct = CreateTemplateStructure('bcc', 3.0, stru.species[0]) fccstruct = CreateTemplateStructure('fcc', 3.0, stru.species[0]) hcpstruct = CreateTemplateStructure('hcp', 3.0, stru.species[0]) pcomp = pmgmach.StructureMatcher(ltol=ltol, stol=stol, angle_tol=atol, primitive_cell=False, attempt_supercell=True) results.append(infile+'\t' \ +str(pcomp.fit(stru,bccstruct))+'\t'+str(pcomp.get_rms_dist(stru,bccstruct))+'\t' \ +str(pcomp.fit(stru,fccstruct))+'\t'+str(pcomp.get_rms_dist(stru,fccstruct))+'\t' \ +str(pcomp.fit(stru,hcpstruct))+'\t'+str(pcomp.get_rms_dist(stru,hcpstruct))) #print(results) write_to_excel(results) print("Matcher completed!") except KeyboardInterrupt: ### handle keyboard interrupt ### return 0