def test_get_xrd_data(self): a = 4.209 latt = Lattice.cubic(a) structure = Structure(latt, ["Cs", "Cl"], [[0, 0, 0], [0.5, 0.5, 0.5]]) c = XRDCalculator() data = c.get_xrd_data(structure, two_theta_range=(0, 90)) #Check the first two peaks self.assertAlmostEqual(data[0][0], 21.107738329639844) self.assertAlmostEqual(data[0][1], 36.483184003748946) self.assertEqual(data[0][2], {(1, 0, 0): 6}) self.assertAlmostEqual(data[0][3], 4.2089999999999996) self.assertAlmostEqual(data[1][0], 30.024695921112777) self.assertAlmostEqual(data[1][1], 100) self.assertEqual(data[1][2], {(1, 1, 0): 12}) self.assertAlmostEqual(data[1][3], 2.976212442014178) s = read_structure(os.path.join(test_dir, "LiFePO4.cif")) data = c.get_xrd_data(s, two_theta_range=(0, 90)) self.assertAlmostEqual(data[1][0], 17.03504233621785) self.assertAlmostEqual(data[1][1], 50.400928948337075) s = read_structure(os.path.join(test_dir, "Li10GeP2S12.cif")) data = c.get_xrd_data(s, two_theta_range=(0, 90)) self.assertAlmostEqual(data[1][0], 14.058274883353876) self.assertAlmostEqual(data[1][1], 4.4111123641667671) # Test a hexagonal structure. s = read_structure(os.path.join(test_dir, "Graphite.cif"), primitive=False) data = c.get_xrd_data(s, two_theta_range=(0, 90)) self.assertAlmostEqual(data[0][0], 7.929279053132362) self.assertAlmostEqual(data[0][1], 100) self.assertAlmostEqual(len(list(data[0][2].keys())[0]), 4) #Add test case with different lengths of coefficients. #Also test d_hkl. coords = [[0.25, 0.25, 0.173], [0.75, 0.75, 0.827], [0.75, 0.25, 0], [0.25, 0.75, 0], [0.25, 0.25, 0.676], [0.75, 0.75, 0.324]] sp = ["Si", "Si", "Ru", "Ru", "Pr", "Pr"] s = Structure(Lattice.tetragonal(4.192, 6.88), sp, coords) data = c.get_xrd_data(s) self.assertAlmostEqual(data[0][0], 12.86727341476735) self.assertAlmostEqual(data[0][1], 31.448239816769796) self.assertAlmostEqual(data[0][3], 6.88) self.assertEqual(len(data), 42) data = c.get_xrd_data(s, two_theta_range=[0, 60]) self.assertEqual(len(data), 18) #Test with and without Debye-Waller factor tungsten = Structure(Lattice.cubic(3.1653), ["W"] * 2, [[0, 0, 0], [0.5, 0.5, 0.5]]) data = c.get_xrd_data(tungsten, scaled=False) self.assertAlmostEqual(data[0][0], 40.294828554672264) self.assertAlmostEqual(data[0][1], 2414237.5633093244) self.assertAlmostEqual(data[0][3], 2.2382050944897789) c = XRDCalculator(debye_waller_factors={"W": 0.1526}) data = c.get_xrd_data(tungsten, scaled=False) self.assertAlmostEqual(data[0][0], 40.294828554672264) self.assertAlmostEqual(data[0][1], 2377745.2296686019) self.assertAlmostEqual(data[0][3], 2.2382050944897789)
def test_get_xrd_data(self): a = 4.209 latt = Lattice.cubic(a) structure = Structure(latt, ["Cs", "Cl"], [[0, 0, 0], [0.5, 0.5, 0.5]]) c = XRDCalculator() data = c.get_xrd_data(structure, two_theta_range=(0, 90)) #Check the first two peaks self.assertAlmostEqual(data[0][0], 21.107738329639844) self.assertAlmostEqual(data[0][1], 36.483184003748946) self.assertEqual(data[0][2], {(1, 0, 0): 6}) self.assertAlmostEqual(data[0][3], 4.2089999999999996) self.assertAlmostEqual(data[1][0], 30.024695921112777) self.assertAlmostEqual(data[1][1], 100) self.assertEqual(data[1][2], {(1, 1, 0): 12}) self.assertAlmostEqual(data[1][3], 2.976212442014178) s = read_structure(os.path.join(test_dir, "LiFePO4.cif")) data = c.get_xrd_data(s, two_theta_range=(0, 90)) self.assertAlmostEqual(data[1][0], 17.03504233621785) self.assertAlmostEqual(data[1][1], 50.400928948337075) s = read_structure(os.path.join(test_dir, "Li10GeP2S12.cif")) data = c.get_xrd_data(s, two_theta_range=(0, 90)) self.assertAlmostEqual(data[1][0], 14.058274883353876) self.assertAlmostEqual(data[1][1], 4.4111123641667671) # Test a hexagonal structure. s = read_structure(os.path.join(test_dir, "Graphite.cif"), primitive=False) data = c.get_xrd_data(s, two_theta_range=(0, 90)) self.assertAlmostEqual(data[0][0], 7.929279053132362) self.assertAlmostEqual(data[0][1], 100) self.assertAlmostEqual(len(list(data[0][2].keys())[0]), 4) #Add test case with different lengths of coefficients. #Also test d_hkl. coords = [[0.25, 0.25, 0.173], [0.75, 0.75, 0.827], [0.75, 0.25, 0], [0.25, 0.75, 0], [0.25, 0.25, 0.676], [0.75, 0.75, 0.324]] sp = ["Si", "Si", "Ru", "Ru", "Pr", "Pr"] s = Structure(Lattice.tetragonal(4.192, 6.88), sp, coords) data = c.get_xrd_data(s) self.assertAlmostEqual(data[0][0], 12.86727341476735) self.assertAlmostEqual(data[0][1], 31.448239816769796) self.assertAlmostEqual(data[0][3], 6.88) self.assertEqual(len(data), 42) data = c.get_xrd_data(s, two_theta_range=[0, 60]) self.assertEqual(len(data), 18) #Test with and without Debye-Waller factor tungsten = Structure(Lattice.cubic(3.1653), ["W"] * 2, [[0, 0, 0], [0.5, 0.5, 0.5]]) data = c.get_xrd_data(tungsten, scaled=False) self.assertAlmostEqual(data[0][0], 40.294828554672264) self.assertAlmostEqual(data[0][1], 2414237.5633093244) self.assertAlmostEqual(data[0][3], 2.2382050944897789) c = XRDCalculator(debye_waller_factors={"W": 0.1526}) data = c.get_xrd_data(tungsten, scaled=False) self.assertAlmostEqual(data[0][0], 40.294828554672264) self.assertAlmostEqual(data[0][1], 2377745.2296686019) self.assertAlmostEqual(data[0][3], 2.2382050944897789)
def set_from_pymatgen(self, structure, k0, k0p, file=None, name='', version=4, comments='', thermal_expansion=0., two_theta_range=(0., 40.)): """ set parameters from pymatgen outputs Parameters ---------- structure = pymatgen structure object k0 = bulk modulus k0p = pressure derivative of bulk modulus file = file name (optional) name = name (optional) version = version (optional) comments = comments (optional) thermal_expansion = 0 (optional) Returns ------- """ lattice = structure.lattice self.k0 = k0 self.k0p = k0p self.a0 = lattice.a self.b0 = lattice.b self.c0 = lattice.c self.alpha0 = lattice.alpha self.beta0 = lattice.beta self.gamma0 = lattice.gamma self.symmetry = SpacegroupAnalyzer(structure).get_crystal_system() self.file = file self.name = name self.version = version self.comments = comments self.thermal_expansion = thermal_expansion self.v0 = cal_UnitCellVolume(self.symmetry, self.a0, self.b0, self.c0, self.alpha0, self.beta0, self.gamma0) c = XRDCalculator(wavelength=0.3344) pattern = c.get_xrd_data(structure, two_theta_range=two_theta_range) DiffLines = [] for line in pattern: hkl_key = line[2].keys() hkl_txt = str(hkl_key)[12:-3].split(",") d_line = DiffractionLine() d_line.dsp0 = line[3] d_line.dsp = line[3] d_line.intensity = line[1] d_line.h = int(hkl_txt[0]) d_line.k = int(hkl_txt[1]) d_line.l = int(hkl_txt[-1]) DiffLines.append(d_line) self.DiffLines = DiffLines
def get_interplanar_spacing(self, structure, surface): xc = XRDCalculator() xrd_data = xc.get_xrd_data(structure) logging.info("xrd_data: {}".format(xrd_data)) sort_data = pd.DataFrame( xrd_data, columns=["two_theta", "intensity", "miller_index_dict", "d_hkl"]) matcher = (1, 1, 1) logging.info("sort_data: {}".format(sort_data)) flag = 0 for mid in sort_data.miller_index_dict: logging.info("mid: {}".format(mid)) for key, value in mid.items(): key = reduce_vector(key) if (surface == key): matcher = mid flag = 1 break else: logging.info("*" * 50) logging.info("key: {}".format(key)) logging.info("value {}".format(value)) logging.info("*" * 50) if flag == 1: break spacing = sort_data[sort_data.miller_index_dict == matcher].d_hkl.values[0] return spacing
def get_xrd_from_struct(self, structure): doc = {} for xs in self.__xrd_settings: xrdcalc = XRDCalculator(wavelength="".join([xs['target'], xs['edge']]), symprec=xs.get('symprec', 0)) pattern = [[float(p[1]), [int(x) for x in list(p[2])[0]], p[0], float(p[3])] for p in xrdcalc.get_xrd_data(structure, two_theta_range=xs['two_theta'])] # TODO: Make sure this is what the website actually needs d = {'wavelength': {'element': xs['target'], 'in_angstroms': WAVELENGTHS["".join([xs['target'], xs['edge']])]}, 'meta': ['amplitude', 'hkl', 'two_theta', 'd_spacing'], 'pattern': pattern} doc[xs['target']] = d return doc
# # 4. Get lattice parameters # In[9]: lattice = material.lattice print('Lattice parameters = ', lattice.a, lattice.b, lattice.c, lattice.alpha, lattice.beta, lattice.gamma) crystal_system = SpacegroupAnalyzer(material).get_crystal_system() print(crystal_system) # # 5. Get diffraction pattern # In[10]: c = XRDCalculator(wavelength=wl_xray) pattern = c.get_xrd_data(material, two_theta_range=xrange) # ## 5.1. Extract twotheta, d-sp, int, hkl # In[11]: d_lines = [] for values in pattern: hkl_key = values[2].keys() hkl_txt = str(hkl_key)[12:-3].split(",") # print(hkl_txt[0], hkl_txt[1], hkl_txt[-1]) d_lines.append([ values[0], values[3], values[1], int(hkl_txt[0]), int(hkl_txt[1]), int(hkl_txt[-1])
def learninglib_build(self, output_dir=None, pdfcal_cfg=None, rdf=True, xrd=False, Bisoequiv=0.1, rstep=None, DebyeCal=False, nosymmetry=False, tth_range=None, wavelength=0.5): """ method to build learning lib with diffpy based on path of cif library. Paramters of G(r) calculation are set via glbl.<attribute>. "PDFCal_config.txt" file with PDFCalculator configuration will also be output Parameters ---------- pdfcal_cfg : dict, optional configuration of PDF calculator, default is the one defined inside glbl class. rdf : bool, optional option to compute RDF or not. default to True, if not, compute pdf xrd : bool, optional option to compute XRD (which is slow). default to False. Bisoequiv : float, optional value of isotropic thermal parameter. default is 0.1. scientific equation: Biso = 8 (pi**2) Uiso rstep : float, optioanl space of PDF. default is pi/qmax. DebyeCal : bool, optional option to use Debye calculator. default is False. nosymmetry : bool, optional DEPRECATED for now. option to apply no symmetry. default is False. tth_range : ndarray, optional range of 2theta. default is [0:0.1:90] wavelength : float, optional wavelength in angstroms, default to 0.5 A which corresponds to Qmax ~= 17 """ # setup output dir timestr = _timestampstr(time.time()) if output_dir is None: tail = "LearningLib_{}".format(timestr) output_dir = os.path.join(os.getcwd(), tail) print('=== output dir would be {} ==='.format(output_dir)) self.output_dir = output_dir if tth_range is None: self.tth_range = np.arange(0, 90, 0.1) self.wavelength = wavelength self.std_q = theta2q(self.tth_range, self.wavelength) ####### configure pymatgen XRD calculator ##### # instantiate calculators xrd_cal = XRDCalculator() xrd_cal.wavelength = self.wavelength xrd_cal.TWO_THETA_TOL = 10**-2 self.calculate_params.update({'xrd_wavelength': xrd_cal.wavelength}) xrd_list = [] sg_list = [] # (a,b,c, alpha, beta, gamma, volume) structure_list_1 = [] # primative cell structure_list_2 = [] # ordinary cell # chemical element composition_list_1 = [] # primative cell composition_list_2 = [] # ordinary cell fail_list = [] ####### configure diffpy PDF calculator ###### if DebyeCal: cal = DebyePDFCalculator() self.calculator_type = 'Debye' cal = PDFCalculator() self.calculator = cal self.calculator_type = 'PDF' self.calculate_params.update({'calculator_type': self.calculator_type}) # setup calculator parameters if rstep is None: rstep = glbl.rstep self.rstep = rstep self.calculator.rstep = rstep # annoying fact self.calculate_params.update({'rstep':rstep}) if pdfcal_cfg is None: self.pdfcal_cfg = glbl.cfg self.calculate_params.update(self.pdfcal_cfg) # configure calculator for k,v in self.pdfcal_cfg.items(): setattr(self.calculator, k, v) # empty list to store results gr_list = [] rdf_list = [] print("====== INFO: calculation parameters:====\n{}" .format(self.calculate_params)) struc_df = pd.DataFrame() ############# loop through cifs ################# for cif in sorted(self.cif_list): _cif = os.path.join(self.input_dir, cif) try: # diffpy structure struc = loadStructure(_cif) struc.Bisoequiv = Bisoequiv ## calculate PDF/RDF with diffpy ## if nosymmetry: struc = nosymmetry(struc) cal.setStructure(struc) cal.eval() # pymatge structure struc_meta = CifParser(_cif) ## calculate XRD with pymatgen ## if xrd: xrd = xrd_cal.get_xrd_data(struc_meta\ .get_structures(False).pop()) _xrd = np.asarray(xrd)[:,:2] q, iq = _xrd.T interp_q = assign_nearest(self.std_q, q, iq) xrd_list.append(interp_q) else: pass ## test space group info ## _sg = struc_meta.get_structures(False).pop()\ .get_space_group_info() except: print("{} fail".format(_cif)) fail_list.append(cif) else: # no error for both pymatgen and diffpy gr_list.append(cal.pdf) rdf_list.append(cal.rdf) self.density_list.append(cal.slope) print('=== Finished evaluating PDF from structure {} ===' .format(cif)) ## update features ## flag = ['primitive', 'ordinary'] option = [True, False] compo_list = [composition_list_1, composition_list_2] struc_fields = ['a','b','c','alpha','beta','gamma', 'volume'] for f, op, compo in zip(flag, option, compo_list): rv_dict = {} struc = struc_meta.get_structures(op).pop() a, b, c = struc.lattice.abc aa, bb, cc = struc.lattice.angles volume = struc.volume for k, v in zip(struc_fields, [a, b, c, aa, bb, cc, volume]): rv_dict.update({"{}_{}".format(f, k) : v}) compo.append(struc.composition.as_dict()) struc_df = struc_df.append(rv_dict, ignore_index=True) # sg info, use the ordinary setup sg_list.append(struc.get_space_group_info()) print('=== Finished evaluating XRD from structure {} ===' .format(cif)) # finally, store crucial calculation results as attributes self.r_grid = cal.rgrid #4*pi * r^2 * rho(r) = R(r) -> RDF to density self.gr_array = np.asarray(gr_list)/4/np.pi/self.r_grid**2 self.rdf_array = np.asarray(gr_list) self.density_list = np.asarray(self.density_list) self.xrd_info = np.asarray(xrd_list) self.sg_list = sg_list # 1 -> primitive , 2 -> ordinary self.composition_list_1 = composition_list_1 self.composition_list_2 = composition_list_2 self.struc_df = struc_df self.fail_list = fail_list
return(structure_files) #################################################################### def find_line(file,searchExp): f=open(file,'r') index=0 for line in f: if searchExp in line: break index += 1 f.close() return(index) #################################################################### # filename = 'TMDMOF.vasp' read_structures() for each in structure_files: print(each) filename = str(each + ".vasp") structure_pos = Poscar.from_file(filename) c = XRDCalculator() structure = structure_pos.structure XRD = c.get_xrd_data(structure, scaled = True, two_theta_range = (5,20)) fil = filename.split(".", 1) f = open(str(fil[0] + ".xye"), 'w') print(*XRD, sep='\n', file=f)