def test_discus(self): """check loading of discus file format """ f = datafile('Ni-discus.stru') stru = loadStructure(f) self.failUnless(type(stru) is PDFFitStructure) return
def loadStrufile(self, filename, stype='diffpy', periodic=None): ''' read and parse a structure file ''' self.filename = filename ext = os.path.splitext(filename)[1] if periodic != None: self.periodic = periodic else: # detect periodicity using file type if ext in ['.cif']: periodic = True else: periodic = False self.periodic = periodic # read the file if stype == 'diffpy': self.rawstru = loadStructure(filename) self.rawstype = stype self.parseDiffpyStru(self.rawstru) elif stype == 'objcryst': if ext == '.cif': self.rawstru = CreateCrystalFromCIF(file(filename)) self.rawstype = stype else: raise TypeError('Cannot read file!') else: raise TypeError('Cannot read file!') return
def test_goodkwarg(self): """check loading of CIF file and passing of parser keyword argument. """ f = datafile('graphite.cif') stru = loadStructure(f, eps=1e-10) self.assertEqual(8, len(stru)) return
def setAdStru(self, adele, stru, dPDFmode='ad'): ''' if dPDFmode == ad -> return the ad pdf if dPDFmode == non_ad -> return the non_ad pdf ''' self.adele = adele self.dPDFmode = dPDFmode self.periodic = stru.periodic s = loadStructure(stru.parent.filename) self.elements = list(set(s.element)) # init c c = {} for ele in self.elements: c[ele] = 0.0 tc = 0.0 for ele, occ in zip(s.element, s.occupancy): c[ele] = c[ele] + occ tc = tc + occ for ele in self.elements: c[ele] = c[ele] / tc self.c = c # init f self.f = {} ftotal = 0 for ele in self.elements: self.f[ele] = fxrayatq(ele, [0]) ftotal += fxrayatq(ele, [0]) * self.c[ele] self.f['total'] = ftotal self.adw = self.c[adele] * self.f[adele] / self.f['total'] return
def test_cif(self): """check loading of CIF file format """ f = datafile('PbTe.cif') stru = loadStructure(f) self.failUnless(isinstance(stru, Structure)) self.failIf(isinstance(stru, PDFFitStructure)) return
def test_cif(self): """check loading of CIF file format """ f = datafile('PbTe.cif') stru = loadStructure(f) self.assertTrue(isinstance(stru, Structure)) self.assertFalse(isinstance(stru, PDFFitStructure)) return
def test_xcfg(self): """check loading of atomeye xcfg format """ f = datafile('BubbleRaftShort.xcfg') stru = loadStructure(f) self.failUnless(type(stru) is Structure) self.assertRaises(StructureFormatError, loadStructure, f, 'xyz') return
def test(self): path = os.path.dirname(os.path.abspath(__file__)) struc=loadStructure(find('MnO_cubic.cif',path)) msp=diffpy.mpdf.MagSpecies(struc=struc) msp.magIdxs=[0,1,2,3] msp.basisvecs=np.array([[1,-1,0]]) msp.kvecs=np.array([[0.5,0.5,0.5]]) msp.ffparamkey='Mn2' mstr=diffpy.mpdf.MagStructure() mstr.loadSpecies(msp) mstr.makeAll() mc=diffpy.mpdf.MPDFcalculator(magstruc=mstr) r,fr,dr=mc.calc(both=True) testval=np.round(dr[100],decimals=4) self.assertEqual(testval,20.8841)
def dbc_iter(struc_f, iter_range): '''change different range''' import numpy as np import matplotlib.pyplot as plt from diffpy.srreal.pdfcalculator import DebyePDFCalculator from diffpy.Structure import loadStructure struc = loadStructure(struc_f) dbc = DebyePDFCalculator() dbc.setStructure(struc) dbc.qmax = 20 dbc.qmin = 0.5 dbc.rmax = 20 #par = eval(para) #print(dbc.par) for step in iter_range: (r,g) = dbc(delta2 = step) plt.plot(r,g)
def simple_pdf_cal(input_f, Debye = True, DW_factor = glbl.DW_factor, qmin = glbl.q_min, qmax = glbl.q_max, rmax = glbl.r_max): ''' simple pdf calculator. Take input .cif/.xyz file to calculate PDF (only use PDFCalculator now, can't calculate nano structrue at this stage) argument: input_f - str - strcuture file name Dw_factor - float - value of Debye-Waller factor, which accounts for thermal motions. Default=1 means zero temperature ''' ## calculate theoretical pdf from given structure file # create structure struc = loadStructure(input_f) struc.Bisoequiv = DW_factor # calculate PDF pdfc = PDFCalculator(qmax = qmax, rmax = rmax) dbc = DebyePDFCalculator(qmax = qmax, rmax = rmax) if Debye: (r, g) = dbc(struc, qmin = qmin) else: (r, g) = pdfc(struc, qmin=qmin) return (r, g)
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import matplotlib.pyplot as plt from diffpy.Structure import loadStructure from diffpy.srreal.pdfcalculator import PDFCalculator from rectangleprofile import RectangleProfile ni = loadStructure('ni.cif') # The CIF file had no displacement data so we supply them here: ni.Uisoequiv = 0.005 # Calculate PDF with default profile function pc1 = PDFCalculator() r1, g1 = pc1(ni) print("standard peakprofile:\n " + repr(pc1.peakprofile)) # Create new calculator that uses the custom profile function pc2 = PDFCalculator() pc2.peakprofile = RectangleProfile() # Note: pc2.peakprofile = 'rectangleprofile' # would do the same, because RectangleProfile class was registered # under its 'rectangleprofile' identifier. print("custom peakprofile:\n " + repr(pc1.peakprofile)) r2, g2 = pc2(ni) # compare both simulated curves plt.plot(r1, g1, r2, g2) plt.draw() plt.show()
dataFile = "cdse.gr" structureFile = "cdse.xyz" # The first thing to construct is a contribution. Since this is a simple # example, the contribution will simply contain our PDF data and an associated # structure file. We'll give it the name "cdse" cdsePDF = PDFContribution("CdSe") # Load the data and set the r-range over which we'll fit cdsePDF.loadData(dataFile) cdsePDF.setCalculationRange(xmin=1, xmax=20, dx=0.01) # Add the structure from our xyz file to the contribution, since the structure # model is non-periodic, we need to specify the periodic=False here to get the # right PDF cdseStructure = loadStructure(structureFile) cdsePDF.addStructure("CdSe", cdseStructure, periodic=False) # The FitRecipe does the work of managing one or more contributions # that are optimized together. In addition, FitRecipe configures # fit variables that are tied to the model parameters and thus # controls the calculated profiles. cdseFit = FitRecipe() # give the PDFContribution to the FitRecipe cdseFit.addContribution(cdsePDF) # Here we create variables for the overall scale of the PDF and a delta2 # parameter for correlated motion of neighboring atoms. cdseFit.addVar(cdsePDF.scale, 1) cdseFit.addVar(cdsePDF.CdSe.delta2, 5)
import pandas as pd from time import strftime from pprint import pprint import matplotlib.pyplot as plt from diffpy.Structure import loadStructure from diffpy.Structure import StructureFormatError from diffpy.srreal.structureadapter import nosymmetry from diffpy.srreal.pdfcalculator import DebyePDFCalculator from diffpy.srreal.pdfcalculator import PDFCalculator from pdf_lib.glbl import pdfCal_cfg, Uiso, delta2 cal = PDFCalculator() cal.delta2 = delta2 ni = loadStructure('ni.cif') ni.Uisoequiv = Uiso nacl = loadStructure('1000041.cif') nacl.Uisoequiv = Uiso print("Uiso = {}".format(Uiso)) def qdamp_test(struc, rmax_val, qdamp_array=None): pdfCal_cfg['rmax'] = rmax_val N = qdamp_array.size fig, ax = plt.subplots(N, figsize=(20, 6), sharex=True, sharey=True) for _ax, qdamp_val in zip(ax, qdamp_array): pdfCal_cfg['qdamp'] = qdamp_val r, g = cal(struc, **pdfCal_cfg) #cal.setStructure(struc)
import numpy as np import matplotlib.pyplot as plt from diffpy.Structure import loadStructure from diffpy.srreal.pdfcalculator import PDFCalculator, DebyePDFCalculator from diffpy.srfit.pdf import PDFContribution from scipy.integrate import simps nkl_crystal = loadStructure("BaTiO3.cif") nkl_crystal.Uisoequiv = 0.005 cfg_pc = {'rmin': 0, 'rmax': 20, 'rstep': 0.01} cfg_dpc1 = {'qmax': 100, 'qmin': 0, 'rmin': 0, 'rmax': 100, 'rstep': 0.01} #cfg_dpc2 = {'qmax' : 100, # 'qmin' : 0, # 'rmin' : 0, # 'rmax' : 70, # 'rstep': 0.01} # #cfg_dpc3 = {'qmax' : 100, # 'qmin' : 0, # 'rmin' : 0, # 'rmax' : 100, # 'rstep': 0.01} # calculate PDF by real-space summation pc0 = PDFCalculator(**cfg_pc) r0, g0 = pc0(nkl_crystal) # calcualte PDF by DPC
import numpy as np import matplotlib.pyplot as plt from diffpy.Structure import loadStructure from diffpy.srreal.pdfcalculator import PDFCalculator from diffpy.srfit.pdf import PDFContribution from scipy.integrate import simps ##load structure files including single molecule, supercell in xyz format mannitol_SM = loadStructure("Mannitol_Single_Molecule.xyz") mannitol_supercell = loadStructure("Mannitol_5_5_5.xyz") ##assign them thermal factors mannitol_SM.Uisoequiv = 0.005 mannitol_supercell.Uisoequiv = 0.005 cfg = { 'qmax' : 25, 'qmin' :0, 'rmin' : 0, 'rmax' : 20, 'rstep': 0.01, 'qdamp': 0.045, 'qbroad': 0.069} # calculate PDF by real-space summation pc0 = PDFCalculator(**cfg) r0, g0 = pc0(mannitol_SM) r1, g1 = pc0(mannitol_supercell) ###define a Gaussian function def Gauss(r, r0, Gamma, scale): return scale*(np.sqrt(np.log(2.)/np.pi))*(2./Gamma)*np.exp((-1)*(r-r0)**2*4.*np.log(2.)/Gamma**2)
import numpy as np import matplotlib.pyplot as plt from diffpy.Structure import loadStructure from diffpy.srreal.pdfcalculator import PDFCalculator from diffpy.srfit.pdf import PDFContribution from scipy.integrate import simps ##load structure files including single molecule, in xyz format and crystal cif mannitol_SM = loadStructure("Mannitol_Single_Molecule.xyz") mannitol_crystal = loadStructure("DMANTL01_alpha_RT.cif") ##assign them thermal factors mannitol_SM.Uisoequiv = 0.005 mannitol_crystal.Uisoequiv = 0.005 cfg = { 'qmax': 25, 'qmin': 0, 'rmin': 0, 'rmax': 20, 'rstep': 0.01, 'qdamp': 0.045, 'qbroad': 0.069 } # calculate PDF by real-space summation pc0 = PDFCalculator(**cfg) r0, g0 = pc0(mannitol_SM) r1, g1 = pc0(mannitol_crystal) plt.plot(r0, g0, "b-") plt.plot(r1, g1, "r-")
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import leastsq from mcalculator import * import diffpy as dp from diffpy.Structure import loadStructure # Create the structure from our cif file, update the lattice params MnOrhomb = loadStructure("mPDF_exampleFiles/MnO_R-3m.cif") MnOcubic = loadStructure("mPDF_exampleFiles/MnO_cubic.cif") latCub = MnOcubic.lattice latRhomb = MnOrhomb.lattice latRhomb.a, latRhomb.b, latRhomb.c = latCub.a / np.sqrt(2), latCub.a / np.sqrt( 2), np.sqrt(6) * latCub.a / np.sqrt(2) #MnOrhomb.lattice=latRhomb # Set up the mPDF calculators mcCub = mPDFcalculator(MnOcubic) mcCub.magIdxs = [0, 1, 2, 3] mcCub.makeAtoms() mcRhomb = mPDFcalculator(MnOrhomb) mcRhomb.magIdxs = [0, 1, 2] mcRhomb.makeAtoms() svec = 2.5 * np.array([1.0, -1.0, 0]) / np.sqrt(2) mcCub.svec = svec mcCub.kvec = np.array([0.5, 0.5, 0.5]) mcCub.spinOrigin = mcCub.atoms[0] mcCub.makeSpins()
#!/usr/bin/env python # -*- coding: utf-8 -*- from diffpy.Structure import loadStructure from diffpy.srreal.pdfcalculator import PDFCalculator from matplotlib.pyplot import plot, show cds = loadStructure('CdS_wurtzite.cif') pc1 = PDFCalculator() pc1.rmax = 20 pc1.scatteringfactortable.setCustomAs('S2-', 'S', 18) pc1.scatteringfactortable.lookup('S2-') r1, g1 = pc1(cds) plot(r1, g1) pc2 = pc1.copy() cds2 = loadStructure('CdS_wurtzite.cif') cds2.anisotropy = False r2, g2 = pc2(cds2) plot(r2, g2) plot(r1, g1 - g2) show()
# Files containing our experimental data and structure file dataFile = "ni-q27r100-neutron.gr" structureFile = "ni.cif" spaceGroup = "Fm-3m" # The first thing to construct is a contribution. Since this is a simple # example, the contribution will simply contain our PDF data and an associated # structure file. We'll give it the name "nickel" niPDF = PDFContribution("nickel") # Load the data and set the r-range over which we'll fit niPDF.loadData(dataFile) niPDF.setCalculationRange(xmin=1, xmax=20, dx=0.01) # Add the structure from our cif file to the contribution niStructure = loadStructure(structureFile) niPDF.addStructure("nickel", niStructure) # The FitRecipe does the work of calculating the PDF with the fit variable # that we give it. niFit = FitRecipe() # give the PDFContribution to the FitRecipe niFit.addContribution(niPDF) # Configure the fit variables and give them to the recipe. We can use the # srfit function constrainAsSpaceGroup to constrain the lattice and ADP # parameters according to the Fm-3m space group. from diffpy.srfit.structure import constrainAsSpaceGroup spaceGroupParams = constrainAsSpaceGroup(niPDF.nickel.phase, spaceGroup) print "Space group parameters are:",
#!/usr/bin/env python # -*- coding: utf-8 -*- from matplotlib.pyplot import * from diffpy.Structure import loadStructure from diffpy.srreal.pdfcalculator import PDFCalculator from rectangleprofile import RectangleProfile ni = loadStructure('ni.cif') # The CIF file had no displacement data so we supply them here: ni.Uisoequiv = 0.005 # Calculate PDF with default profile function pc1 = PDFCalculator() r1, g1 = pc1(ni) print "standard peakprofile:\n " + repr(pc1.peakprofile) # Create new calculator that uses the custom profile function pc2 = PDFCalculator() pc2.peakprofile = RectangleProfile() # Note: pc2.peakprofile = 'rectangleprofile' # would do the same, because RectangleProfile class was registered # under its 'rectangleprofile' identifier. print "custom peakprofile:\n " + repr(pc1.peakprofile) r2, g2 = pc2(ni) # compare both simulated curves plot(r1, g1, r2, g2) draw() show()
#!/usr/bin/env python # -*- coding: utf-8 -*- from diffpy.Structure import loadStructure from diffpy.srreal.pdfcalculator import PDFCalculator from matplotlib.pyplot import plot, show cds = loadStructure('CdS_wurtzite.cif') pc1 = PDFCalculator() pc1.rmax = 20 pc1.scatteringfactortable.setCustomAs('S2-', 'S', 18) pc1.scatteringfactortable.lookup('S2-') r1, g1 = pc1(cds) plot(r1, g1) pc2 = pc1.copy() cds2 = loadStructure('CdS_wurtzite.cif') cds2.anisotropy = False r2, g2 = pc2(cds2) plot(r2, g2) plot(r1, g1-g2) show()
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
#!/usr/bin/env python # -*- coding: utf-8 -*- from diffpy.Structure import loadStructure from diffpy.srreal.pdfcalculator import DebyePDFCalculator from matplotlib.pyplot import plot, show c60 = loadStructure('c60.stru') dpc = DebyePDFCalculator() dpc.qmax = 20 dpc.rmax = 20 r3, g3 = dpc(c60, qmin=0) r4, g4 = dpc(c60, qmin=1) plot(r3, g3, r4, g4) show()
import numpy as np import matplotlib.pyplot as plt from diffpy.Structure import loadStructure from diffpy.srreal.pdfcalculator import PDFCalculator from diffpy.srfit.pdf import PDFContribution from scipy.integrate import simps bto_cluster_1 = loadStructure("BaTiO3.xyz") bto_cluster_2 = loadStructure("BaTiO3_4_4_4.xyz") bto_cluster_3 = loadStructure("BaTiO3_8_8_8.xyz") bto_cluster_1.Uisoequiv = 0.005 bto_cluster_2.Uisoequiv = 0.005 bto_cluster_3.Uisoequiv = 0.005 cfg = { 'qmax': 25, 'qmin': 0, 'rmin': 0, 'rmax': 20, 'rstep': 0.01, 'qdamp': 0.045, 'qbroad': 0.069 } # calculate PDF by real-space summation pc0 = PDFCalculator(**cfg) r1, g1 = pc0(bto_cluster_1) r2, g2 = pc0(bto_cluster_2) r3, g3 = pc0(bto_cluster_3)
def gr_lib_build(self, cif_lib_path): ''' method to calculate G(r) based on path of cif library located at. Paramters of G(r) calculation are set via glbl.<attribute>, one can tune it based on purpose of building library. After entire method, text file contains all G(r), space_group_symbol and material name will be saved respectively Parameters ---------- cif_lib_path : str path to lib of cif files ''' el_list = [] # data column space_group_symbol_list = [] # reference for search have been done in the past # set up calculation environment #dbc = DebyePDFCalculator() pdf = PDFCalculator() pdf.rstep = glbl.rstep cfg = {'qmin': glbl.q_min, 'qmax':glbl.q_max, 'rmin':glbl.r_min, 'rmax': glbl.r_max} Bisoequiv = glbl.Bisoequiv #FIXME: current value = 0.5, need to figure out the most suitable value print('====Parameter used in this PDF calculator is: {}===='.format(cfg)) print('====Bisoequiv used in this PDF calculator is: {}===='.format(Bisoequiv)) # step 1: list cif dir output_dir = os.path.join(self.data_dir, 'lib_data') self._makedirs(output_dir) self.output_dir = output_dir cif_f_list = [ f for f in os.listdir(self.cif_dir)] # hidden step as numpy can't take an empty array and stack struc = loadStructure(os.path.join(self.cif_dir, cif_f_list[0])) struc.Bisoequiv = Bisoequiv (r,g) = pdf(nosymmetry(struc), **cfg) r_grid = np.array(r) # data x-axis gr_list = np.empty_like(np.array(g)) # data y-axis for cif in cif_f_list: # part 2: calculate PDF with diffpy struc = loadStructure(os.path.join(self.cif_dir, cif)) struc.Bisoequiv = Bisoequiv #(r,g) = pdf(nosymmetry(struc), **cfg) (r,g) = pdf(struc, **cfg) print('Finished calculation of G(r) on {}'.format(cif)) sep = cif.index('_') space_group_symbol = cif[:sep] m_name = cif[sep+1:] # part 3: save data #if not gr_list.any(): #gr_list = np.append(gr_list, g) gr_list = np.vstack((gr_list,g)) space_group_symbol_list.append(space_group_symbol) el_list.append(m_name) #print('size of gr_list = {}'.format(np.shape(gr_list))) #space_group_symbol_list = np.concatenate([space_group_symbol_list, space_group_symbol], axis=0) #el_list = np.concatenate([el_list, m_name], axis=0) time_info = time.strftime('%Y-%m-%d') gr_list_name = '{}_{}_Gr'.format(self.crystal_system, time_info) gr_list_w_name = os.path.join(output_dir, gr_list_name) print('Saving {}'.format(gr_list_w_name)) np.save(gr_list_w_name, gr_list) r_grid_name = '{}_{}_rgrid'.format(self.crystal_system, time_info) r_grid_w_name = os.path.join(output_dir, r_grid_name) np.save(r_grid_w_name, r) space_group_symbol_list_name = '{}_{}_SpaceGroupSymbol'.format(self.crystal_system, time_info) space_group_symbol_list_w_name= os.path.join(output_dir, space_group_symbol_list_name) np.save(space_group_symbol_list_w_name, space_group_symbol_list) #fmt="%s") el_list_name = '{}_{}_Element'.format(self.crystal_system, time_info) el_list_w_name = os.path.join(output_dir, el_list_name) np.save(el_list_w_name, el_list) #fmt="%s") print('''====SUMMARY====: for {} cystsal sytem, Number of cif pulled out and G(r) calculated is {}'''.format(self.crystal_system, np.shape(gr_list))) return gr_list
shuffle(urls) num_cifs0 = num_downloaded temp_filename = f"{save_loc}tmp.cif" for i, url in enumerate(urls): try: #Download file download = urlopen(url).read() #Create temporary copy to load structure from with open(temp_filename, "wb") as w: w.write(download) atom_list = loadStructure(temp_filename).tolist() #Make sure it doesn't contain hydrogen contains_H = False for atom in atom_list: elem_num = atom_enums[process_elem_string(atom.element)] if elem_num == 1: contains_H = True break if contains_H: continue num_downloaded += 1
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import leastsq from mcalculator import * import diffpy as dp from diffpy.Structure import loadStructure # Create the structure from our cif file, update the lattice params MnOrhomb = loadStructure("mPDF_exampleFiles/MnO_R-3m.cif") MnOcubic = loadStructure("mPDF_exampleFiles/MnO_cubic.cif") latCub=MnOcubic.lattice latRhomb=MnOrhomb.lattice latRhomb.a,latRhomb.b,latRhomb.c=latCub.a/np.sqrt(2),latCub.a/np.sqrt(2),np.sqrt(6)*latCub.a/np.sqrt(2) #MnOrhomb.lattice=latRhomb # Set up the mPDF calculators mcCub=mPDFcalculator(MnOcubic) mcCub.magIdxs=[0,1,2,3] mcCub.makeAtoms() mcRhomb=mPDFcalculator(MnOrhomb) mcRhomb.magIdxs=[0,1,2] mcRhomb.makeAtoms() svec=2.5*np.array([1.0,-1.0,0])/np.sqrt(2) mcCub.svec=svec mcCub.kvec=np.array([0.5,0.5,0.5]) mcCub.spinOrigin=mcCub.atoms[0] mcCub.makeSpins() mcRhomb.svec=svec
def learninglib_build(cif_list, xrd=False): """function designed for parallel computation Parameters ---------- cif_list : list List of cif filenames xrd : bool, optional Wether to calculate xrd pattern. Default to False """ gr_list = [] density_list = [] xrd_list = [] struc_df = pd.DataFrame() fail_list = [] composition_list_1 = [] composition_list_2 = [] # database fields flag = ['primitive', 'ordinary'] option = [True, False] compo_list = [composition_list_1, composition_list_2] struc_fields = ['a','b','c','alpha','beta','gamma', 'volume', 'sg_label', 'sg_order'] # looping for _cif in sorted(cif_list): try: # diffpy structure struc = loadStructure(_cif) struc.Uisoequiv = Uiso ## calculate PDF/RDF with diffpy ## r_grid, gr = cal(struc, **pdfCal_cfg) density = cal.slope # pymatgen 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 q = theta2q(q, wavelength) interp_q = assign_nearest(std_q, q, iq) xrd_list.append(interp_q) else: pass ## test if space group info can be parsed## dummy_struc = struc_meta.get_structures(False).pop() _sg = dummy_struc.get_space_group_info() #except RuntimeError: # allow exception to debug except: print("{} fail".format(_cif)) fail_list.append(_cif) else: # no error for both pymatgen and diffpy print('=== Finished evaluating PDF from structure {} ===' .format(_cif)) ## update features ## rv_dict = {} for f, op, compo in zip(flag, option, compo_list): struc = struc_meta.get_structures(op).pop() a, b, c = struc.lattice.abc aa, bb, cc = struc.lattice.angles volume = struc.volume sg, sg_order = struc.get_space_group_info() for k, v in zip(struc_fields, [a, b, c, aa, bb, cc, volume, sg, sg_order]): rv_dict.update({"{}_{}".format(f, k) : v}) compo.append(struc.composition.as_dict()) struc_df = struc_df.append(rv_dict, ignore_index=True) # storing results gr_list.append(gr) density_list.append(density) # end of loop, storing turn result into ndarray r_grid = cal.rgrid gr_array = np.asarray(gr_list) density_array = np.asarray(density_list) xrd_info = np.asarray(xrd_list) q_grid = std_q # talktive statement rv_name_list = ['gr_array', 'density_array', 'r_grid', 'xrd_info', 'q_grid', 'primitive_composition_list', 'ordinary_composition_list', 'struc_df', 'fail_list'] print('{:=^80}'.format(' Return ')) print('\n'.join(rv_name_list)) rv = gr_array, density_array, r_grid, xrd_info, q_grid,\ composition_list_1, composition_list_2, struc_df, fail_list return rv
def map_learninglib(cif_fp, mode='bond_dst'): """function designed to build atomic distance list with parallel computation Parameters ---------- cif_list : str full filepath to cif files. mode : str, optional String to specify quantities being calculated. Allowed strings are: ``pdf`` or ``bond_dst``. Default to ``pdf`` """ ## container for md ## rv_dict = {} struc_df = pd.DataFrame() composition_list_1 = [] composition_list_2 = [] ## fields for features ## flag = ['primitive', 'ordinary'] option = [True, False] compo_list = [composition_list_1, composition_list_2] struc_fields = ['a','b','c','alpha','beta','gamma', 'volume', 'sg_label', 'sg_order'] if mode not in ('pdf', 'bond_dst'): raise RuntimeError("Mode must be either 'pdf' or 'bond_dst'") try: # diffpy structure if mode == 'pdf': ## calculate PDF/RDF with diffpy ## struc = loadStructure(cif_fp) struc.Uisoequiv = Uiso r_grid, gr = cal(struc, **pdfCal_cfg) density = cal.slope elif mode == 'bond_dst': struc = loadStructure(cif_fp, eps=eps) dst = bc(struc) uniq_ind = (np.diff(np.r_[-1.0, bc.distances]) > 1e-8) uniq_dst = dst[uniq_ind] uniq_direction = bc.directions[uniq_ind] # pymatgen structure struc_meta = CifParser(cif_fp) ## test if space group info can be parsed## dummy_struc = struc_meta.get_structures(False).pop() _sg = dummy_struc.get_space_group_info() except: # parallelized so direct return return os.path.basename(cif_fp) else: # insert uid rv_dict.update({"COD_uid": strip_fn(cif_fp)}) for f, op, compo in zip(flag, option, compo_list): struc = struc_meta.get_structures(op).pop() a, b, c = struc.lattice.abc aa, bb, cc = struc.lattice.angles volume = struc.volume sg, sg_order = struc.get_space_group_info() for k, v in zip(struc_fields, [a, b, c, aa, bb, cc, volume, sg, sg_order]): rv_dict.update({"{}_{}".format(f, k) : v}) compo_info =dict(struc.composition.as_dict()) compo.append(compo_info) rv_dict.update({"{}_composition".format(f): compo}) struc_df = struc_df.append(rv_dict, ignore_index=True) if mode=='pdf': rv_name_list = ['gr', 'density', 'r_grid', 'struc_df'] print('{:=^80}'.format(' Return ')) print('\n'.join(rv_name_list)) return (gr, density, r_grid, struc_df) elif mode=='bond_dst': rv_name_list = ['uniq_dst', 'uniq_direction', 'struc_df'] print('{:=^80}'.format(' Return ')) print('\n'.join(rv_name_list)) return (uniq_dst, uniq_direction, struc_df)
import numpy as np import matplotlib.pyplot as plt from diffpy.Structure import loadStructure from diffpy.srreal.pdfcalculator import PDFCalculator, DebyePDFCalculator from diffpy.srfit.pdf import PDFContribution from scipy.integrate import simps nkl_crystal = loadStructure("Nickel.cif") nkl_crystal.Uisoequiv = 0.005 cfg_pc = {'rmin': 0, 'rmax': 20, 'rstep': 0.01} cfg_dpc1 = {'qmax': 100, 'qmin': 0, 'rmin': 0, 'rmax': 40, 'rstep': 0.01} #cfg_dpc2 = {'qmax' : 100, # 'qmin' : 0, # 'rmin' : 0, # 'rmax' : 70, # 'rstep': 0.01} # #cfg_dpc3 = {'qmax' : 100, # 'qmin' : 0, # 'rmin' : 0, # 'rmax' : 100, # 'rstep': 0.01} # calculate PDF by real-space summation pc0 = PDFCalculator(**cfg_pc) r0, g0 = pc0(nkl_crystal) # calcualte PDF by DPC
#!/usr/bin/env python # -*- coding: utf-8 -*- '''Calculation of bond valence sums using diffpy.srreal module included in DiffPy-CMI. ''' from __future__ import print_function from diffpy.Structure import loadStructure from diffpy.srreal.bvscalculator import BVSCalculator # load crystal structure data from a CIF file nacl = loadStructure('NaCl.cif') # create bond valence sum calculator object bvsc = BVSCalculator() # calculate BVS and print the expected and actual valences vsim = bvsc(nacl) print('Calculate bond valence sums for NaCl "bvsc(nacl)"') print('expected "bvsc.valences":\n ', bvsc.valences) print('calculated "bvsc.value":\n ' , vsim) print('difference "bvsc.bvdiff":\n ', bvsc.bvdiff) print('root mean square difference "bvsc.bvrmsdiff":', bvsc.bvrmsdiff) print() # create new BVS calculator with a custom bond valence parameters bvsc2 = BVSCalculator() # Use alternate value for the Na+ Cl- bond valence parameters from # http://www.iucr.org/__data/assets/file/0018/59004/bvparm2011.cif
# Import necessary functions from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from scipy.optimize import leastsq from diffpy.mpdf import * from diffpy.Structure import loadStructure from diffpy.srfit.pdf import PDFContribution from diffpy.srfit.fitbase import FitRecipe, FitResults # Files containing our experimental data and structure file dataFile = "npdf_07334.gr" structureFile = "MnO_R-3m.cif" spaceGroup = "H-3m" mnostructure = loadStructure(structureFile) # Create the Mn2+ magnetic species mn2p = MagSpecies(struc=mnostructure, label='Mn2+', magIdxs=[0, 1, 2], basisvecs=2.5 * np.array([[1, 0, 0]]), kvecs=np.array([[0, 0, 1.5]]), ffparamkey='Mn2') # Create and prep the magnetic structure mstr = MagStructure() mstr.loadSpecies(mn2p) mstr.makeAll() # Set up the mPDF calculator
Instituion:-----University of Colorado Boulder --------------------Raman Spectroscopy and Neutron Scattering Laboratory --------------------Professor Dmitry Reznik Description: You have to go down to where 'masses' is introduced and enter the masses of the atoms corresponding to the atoms in 'types' """ import numpy as np from diffpy.Structure import loadStructure from diffpy.Structure.expansion import supercell infile = 'C_mp-667273_conventional_standard.cif' outfile = 'c60' c60 = loadStructure(infile) c60_2x2x2 = supercell(c60, [12, 2, 2]) c60.write(outfile + '.xyz', 'xyz') c60_2x2x2.write(outfile + '_2x2x2.xyz', 'xyz') struct = c60_2x2x2 with open(outfile + '_2x2x2.xyz', 'r') as fid: nat = int(fid.readline()) # number of atoms fid.readline() # skip comment line pos = np.zeros((nat, 4)) types = [] for i in range(nat): tmp = fid.readline().strip().split() if tmp[0] not in types: types.append(tmp[0])