def refinePeaksT(peaks, difC, ibrav, A, Zero, ZeroRef): 'needs a doc string' dmin = getDmin(peaks) OK, smin, Aref, Z, result = FitHKLT(difC, ibrav, peaks, A, Zero, ZeroRef) Peaks = np.array(peaks).T H = Peaks[4:7] Peaks[8] = 1. / np.sqrt(G2lat.calc_rDsqT(H, Aref, Z, Peaks[0], difC)) peaks = Peaks.T HKL = G2lat.GenHBravais(dmin, ibrav, A) M20, X20 = calc_M20(peaks, HKL) return len(HKL), M20, X20, Aref, Z
def ranAbyV(Bravais,dmin,dmax,V): 'needs a doc string' cell = [0,0,0,0,0,0] bad = True while bad: bad = False cell = rancell(Bravais,dmin,dmax) G,g = G2lat.cell2Gmat(cell) A = G2lat.Gmat2A(G) if G2lat.calc_rVsq(A) < 1: scaleAbyV(A,V) cell = G2lat.A2cell(A) for i in range(3): bad |= cell[i] < dmin return A
def ranAbyV(Bravais,dmin,dmax,V): 'needs a doc string' cell = [0,0,0,0,0,0] bad = True while bad: bad = False cell = rancell(Bravais,dmin,dmax) G,g = G2lat.cell2Gmat(cell) A = G2lat.Gmat2A(G) if G2lat.calc_rVsq(A) < 1: scaleAbyV(A,V) cell = G2lat.A2cell(A) for i in range(3): bad |= cell[i] < dmin return A
def convert_lattice(self, paramList, params): ''' Convert between A and unit cell parameters. A is defined in GSAS-II as A = [G11, G22, G33, 2*G12, 2*G13, 2*G23] with G as the reciprocal metric tensor elements. ''' latparamList = [ '0::A0', '1::A0', '2::A0', '3::A0', '4::A0', '5::A0', '6::A0', '7::A0', '8::A0', '9::A0', '10::A0' ] check = any(item in paramList for item in latparamList) if check is True: return G2latt.A2cell(params) else: return G2latt.cell2A(params)
def refinePeaksTSS(peaks, difC, Inst, SGData, SSGData, maxH, ibrav, A, vec, vecRef, Zero, ZeroRef): 'needs a doc string' dmin = getDmin(peaks) OK, smin, Aref, Vref, Z, result = FitHKLTSS(difC, ibrav, peaks, A, vec, vecRef, Zero, ZeroRef) Peaks = np.array(peaks).T H = Peaks[4:8] Peaks[9] = 1. / np.sqrt( G2lat.calc_rDsqTSS(H, Aref, Vref, Z, Peaks[0], difC)) peaks = Peaks.T HKL = G2pwd.getHKLMpeak(dmin, Inst, SGData, SSGData, Vref, maxH, Aref) HKL = G2lat.GenHBravais(dmin, ibrav, A) M20, X20 = calc_M20SS(peaks, HKL) return len(HKL), M20, X20, Aref, Vref, Z
def Exporter(self,event=None): '''Export as a XYZ file ''' # the export process starts here self.InitExport(event) # load all of the tree into a set of dicts self.loadTree() # create a dict with refined values and their uncertainties self.loadParmDict() if self.ExportSelect(): # set export parameters; ask for file name return filename = self.filename for phasenam in self.phasenam: phasedict = self.Phases[phasenam] # pointer to current phase info General = phasedict['General'] i = self.Phases[phasenam]['pId'] Atoms = phasedict['Atoms'] if not len(Atoms): print('**** ERROR - Phase '+str(phasenam)+' has no atoms! ****') continue if len(self.phasenam) > 1: # if more than one filename is included, add a phase # self.filename = os.path.splitext(filename)[1] + "_" + str(i) + self.extension fp = self.OpenFile() cx,ct,cs,cia = General['AtomPtrs'] Cell = General['Cell'][1:7] A,B = G2lat.cell2AB(Cell) fmt = '{:4s}'+3*'{:12.4f}' self.Write('{:6d}'.format(len(Atoms))) self.Write(' ') for atom in Atoms: xyz = np.inner(A,np.array(atom[cx:cx+3])) self.Write(fmt.format(atom[ct],*xyz)) self.CloseFile() print('Phase '+str(phasenam)+' written to XYZ file '+str(self.fullpath))
def _run_rietveld_pawley_refinement(self, gsas_proj, do_pawley): """ Run a Rietveld or Pawley refinement :param gsas_proj: The project to work on :param do_pawley: True if doing a Pawley refinement (the default), False if doing a Rietveld refinement :return: (R weighted profile, goodness-of-fit coefficient, table containing refined lattice parameters) """ phase_paths = self.getPropertyValue(self.PROP_PATHS_TO_PHASE_FILES).split(",") pawley_tmin = None if self._refinement_method_is_pawley(): pawley_dmin = float(self.getPropertyValue(self.PROP_PAWLEY_DMIN)) pawley_tmin = GSASIIlattice.Dsp2pos(Inst=gsas_proj.histogram(0).data["Instrument Parameters"][0], dsp=pawley_dmin) refinements = self._create_refinement_params_dict(num_phases=len(phase_paths), pawley_tmin=pawley_tmin) prog = Progress(self, start=0, end=1, nreports=2) prog.report("Reading phase files") for phase_path in phase_paths: phase = gsas_proj.add_phase(phasefile=phase_path, histograms=[gsas_proj.histograms()[0]]) if do_pawley: self._set_pawley_phase_parameters(phase) pawley_reflections = self._generate_pawley_reflections(phase) phase.data["Pawley ref"] = pawley_reflections prog.report("Running {} refinement steps".format(len(refinements))) for refinement in refinements: gsas_proj.do_refinements([refinement]) gsas_proj.save() rwp = gsas_proj.histogram(0).get_wR() lattice_params = gsas_proj.phases()[0].get_cell() lattice_params_table = self._build_output_lattice_table(lattice_params) return rwp, lattice_params_table
def errFitT(values,ibrav,d,H,tof,difC,Z,Zref): Zero = Z if Zref: Zero = values[-1] A = Values2A(ibrav,values) Qo = 1./d**2 Qc = G2lat.calc_rDsqT(H,A,Zero,tof,difC) return (Qo-Qc)
def errFitZ(values,ibrav,d,H,tth,wave,Z,Zref): Zero = Z if Zref: Zero = values[-1] A = Values2A(ibrav,values) Qo = 1./d**2 Qc = G2lat.calc_rDsqZ(H,A,Zero,tth,wave) return (Qo-Qc)
def errFitZ(values, ibrav, d, H, tth, wave, Z, Zref): Zero = Z if Zref: Zero = values[-1] A = Values2A(ibrav, values) Qo = 1. / d**2 Qc = G2lat.calc_rDsqZ(H, A, Zero, tth, wave) return (Qo - Qc)
def errFitT(values, ibrav, d, H, tof, difC, Z, Zref): Zero = Z if Zref: Zero = values[-1] A = Values2A(ibrav, values) Qo = 1. / d**2 Qc = G2lat.calc_rDsqT(H, A, Zero, tof, difC) return (Qo - Qc)
def SetPOCoef(Order,hist): cofNames = G2lat.GenSHCoeff(SGData['SGLaue'],'0',Order,False) #cylindrical & no M newPOCoef = dict(zip(cofNames,np.zeros(len(cofNames)))) POCoeff = UseList[G2frame.hist]['Pref.Ori.'][5] for cofName in POCoeff: if cofName in cofNames: newPOCoef[cofName] = POCoeff[cofName] return newPOCoef
def errFitZSS(values,ibrav,d,H,tth,wave,vec,Vref,Z,Zref): Zero = Z if Zref: Zero = values[-1] A = Values2A(ibrav,values) Vec = Values2Vec(ibrav,vec,Vref,values) Qo = 1./d**2 Qc = G2lat.calc_rDsqZSS(H,A,Vec,Zero,tth,wave) return (Qo-Qc)
def errFitTSS(values, ibrav, d, H, tof, difC, vec, Vref, Z, Zref): Zero = Z if Zref: Zero = values[-1] A = Values2A(ibrav, values) Vec = Values2Vec(ibrav, vec, Vref, values) Qo = 1. / d**2 Qc = G2lat.calc_rDsqTSS(H, A, Vec, Zero, tof, difC) return (Qo - Qc)
def test1(): if NeedTestData: TestData() ibrav, A, Pwr, peaks = TestData2 print('bad cell:', G2lat.A2cell(A)) print('FitHKL') OK, smin, A, result = FitHKL(ibrav, peaks, A, Pwr) result = refinePeaks(peaks, ibrav, A) N, M20, X20, A = result print('refinePeaks:', N, M20, X20, A)
def refinePeaks(peaks, ibrav, A, ifX20=True): 'needs a doc string' dmin = getDmin(peaks) smin = 1.0e10 pwr = 8 maxTries = 10 OK = False tries = 0 HKL = G2lat.GenHBravais(dmin, ibrav, A) while len(HKL) > 2 and IndexPeaks(peaks, HKL)[0]: Pwr = pwr - (tries % 2) HKL = [] tries += 1 osmin = smin oldA = A[:] Vold = G2lat.calc_V(oldA) OK, smin, A, result = FitHKL(ibrav, peaks, A, Pwr) Vnew = G2lat.calc_V(A) if Vnew > 2.0 * Vold or Vnew < 2.: A = ranAbyR(ibrav, oldA, tries + 1, maxTries, ran2axis) OK = False continue try: HKL = G2lat.GenHBravais(dmin, ibrav, A) except FloatingPointError: A = oldA OK = False break if len(HKL) == 0: break #absurd cell obtained! rat = (osmin - smin) / smin if abs(rat) < 1.0e-5 or not OK: break if tries > maxTries: break if OK: OK, smin, A, result = FitHKL(ibrav, peaks, A, 2) Peaks = np.array(peaks).T H = Peaks[4:7] try: Peaks[8] = 1. / np.sqrt(G2lat.calc_rDsq(H, A)) peaks = Peaks.T except FloatingPointError: A = oldA M20, X20 = calc_M20(peaks, HKL, ifX20) return len(HKL), M20, X20, A
def refinePeaks(peaks,ibrav,A,ifX20=True): 'needs a doc string' dmin = getDmin(peaks) smin = 1.0e10 pwr = 8 maxTries = 10 OK = False tries = 0 HKL = G2lat.GenHBravais(dmin,ibrav,A) while len(HKL) > 2 and IndexPeaks(peaks,HKL)[0]: Pwr = pwr - (tries % 2) HKL = [] tries += 1 osmin = smin oldA = A[:] Vold = G2lat.calc_V(oldA) OK,smin,A,result = FitHKL(ibrav,peaks,A,Pwr) Vnew = G2lat.calc_V(A) if Vnew > 2.0*Vold or Vnew < 2.: A = ranAbyR(ibrav,oldA,tries+1,maxTries,ran2axis) OK = False continue try: HKL = G2lat.GenHBravais(dmin,ibrav,A) except FloatingPointError: A = oldA OK = False break if len(HKL) == 0: break #absurd cell obtained! rat = (osmin-smin)/smin if abs(rat) < 1.0e-5 or not OK: break if tries > maxTries: break if OK: OK,smin,A,result = FitHKL(ibrav,peaks,A,2) Peaks = np.array(peaks).T H = Peaks[4:7] try: Peaks[8] = 1./np.sqrt(G2lat.calc_rDsq(H,A)) peaks = Peaks.T except FloatingPointError: A = oldA M20,X20 = calc_M20(peaks,HKL,ifX20) return len(HKL),M20,X20,A
def ZSSfunc(values,peaks,dmin,Inst,SGData,SSGData,vec,Vref,maxH,A,wave,Z,dlg=None): Vec = Val2Vec(vec,Vref,values) HKL = G2pwd.getHKLMpeak(dmin,Inst,SGData,SSGData,Vec,maxH,A) Peaks = np.array(IndexSSPeaks(peaks,HKL)[1]).T Qo = 1./Peaks[-2]**2 Qc = G2lat.calc_rDsqZSS(Peaks[4:8],A,Vec,Z,Peaks[0],wave) chi = np.sum((Qo-Qc)**2) if dlg: dlg.Pulse() return chi
def refinePeaksZSS(peaks,wave,Inst,SGData,SSGData,maxH,ibrav,A,vec,vecRef,Zero,ZeroRef): 'needs a doc string' dmin = getDmin(peaks) OK,smin,Aref,Vref,Z,result = FitHKLZSS(wave,ibrav,peaks,A,vec,vecRef,Zero,ZeroRef) Peaks = np.array(peaks).T H = Peaks[4:8] Peaks[9] = 1./np.sqrt(G2lat.calc_rDsqZSS(H,Aref,Vref,Z,Peaks[0],wave)) #H,A,vec,Z,tth,lam peaks = Peaks.T HKL = G2pwd.getHKLMpeak(dmin,Inst,SGData,SSGData,Vref,maxH,Aref) M20,X20 = calc_M20SS(peaks,HKL) return len(HKL),M20,X20,Aref,Vref,Z
def refinePeaksT(peaks,difC,ibrav,A,Zero,ZeroRef): 'needs a doc string' dmin = getDmin(peaks) OK,smin,Aref,Z,result = FitHKLT(difC,ibrav,peaks,A,Zero,ZeroRef) Peaks = np.array(peaks).T H = Peaks[4:7] Peaks[8] = 1./np.sqrt(G2lat.calc_rDsqT(H,Aref,Z,Peaks[0],difC)) peaks = Peaks.T HKL = G2lat.GenHBravais(dmin,ibrav,A) M20,X20 = calc_M20(peaks,HKL) return len(HKL),M20,X20,Aref,Z
def monoCellReduce(ibrav,A): 'needs a doc string' a,b,c,alp,bet,gam = G2lat.A2cell(A) G,g = G2lat.A2Gmat(A) if ibrav in [11]: u = [0,0,-1] v = [1,0,2] anew = math.sqrt(np.dot(np.dot(v,g),v)) if anew < a: cang = np.dot(np.dot(u,g),v)/(anew*c) beta = acosd(-abs(cang)) A = G2lat.cell2A([anew,b,c,90,beta,90]) else: u = [-1,0,0] v = [1,0,1] cnew = math.sqrt(np.dot(np.dot(v,g),v)) if cnew < c: cang = np.dot(np.dot(u,g),v)/(a*cnew) beta = acosd(-abs(cang)) A = G2lat.cell2A([a,b,cnew,90,beta,90]) return A
def monoCellReduce(ibrav,A): 'needs a doc string' a,b,c,alp,bet,gam = G2lat.A2cell(A) G,g = G2lat.A2Gmat(A) if ibrav in [13]: u = [0,0,-1] v = [1,0,2] anew = math.sqrt(np.dot(np.dot(v,g),v)) if anew < a: cang = np.dot(np.dot(u,g),v)/(anew*c) beta = acosd(-abs(cang)) A = G2lat.cell2A([anew,b,c,90,beta,90]) else: u = [-1,0,0] v = [1,0,1] cnew = math.sqrt(np.dot(np.dot(v,g),v)) if cnew < c: cang = np.dot(np.dot(u,g),v)/(a*cnew) beta = acosd(-abs(cang)) A = G2lat.cell2A([a,b,cnew,90,beta,90]) return A
def Writer(self, TreeName, filename=None): #print filename self.OpenFile(filename) histblk = self.Histograms[TreeName] Parms = self.Histograms[TreeName]['Instrument Parameters'][0] for parm in Parms: if parm in [ 'Type', 'Source', ]: line = '"Instparm: %s","%s"' % (parm, Parms[parm][0]) elif parm in [ 'Lam', 'Zero', ]: line = '"Instparm: %s",%10.6f' % (parm, Parms[parm][1]) else: line = '"Instparm: %s",%10.2f' % (parm, Parms[parm][1]) self.Write(line) Samp = self.Histograms[TreeName]['Sample Parameters'] for samp in Samp: if samp in ['InstrName', 'Type']: line = '"Samparm: %s",%s' % (samp, Samp[samp]) elif samp in [ 'Azimuth', 'Chi', 'Gonio. radius', 'Omega', 'Phi', 'Pressure', 'Temperature', 'Time' ]: line = '"Samparm: %s",%10.2f' % (samp, Samp[samp]) elif samp in [ 'DisplaceX', 'DisplaceY', 'Scale', 'Shift', 'SurfRoughA', 'SurfRoughB', 'Transparency' ]: line = '"Samparm: %s",%10.2f' % (samp, Samp[samp][0]) else: continue self.Write(line) WriteList(self, ("x", "y_obs", "weight", "y_calc", "y_bkg", "Q")) digitList = 2 * ((13, 3), ) + ((13, 5), ) + 3 * ((13, 3), ) for vallist in zip( histblk['Data'][0], histblk['Data'][1], histblk['Data'][2], histblk['Data'][3], histblk['Data'][4], #histblk['Data'][5], 2 * np.pi / G2lat.Pos2dsp(Parms, histblk['Data'][0])): line = "" for val, digits in zip(vallist, digitList): if line: line += ',' line += G2py3.FormatValue(val, digits) self.Write(line) self.CloseFile()
def SHPenalty(POData): def OnHKLList(event): dlg = G2G.G2MultiChoiceDialog(G2frame, 'Select penalty hkls', 'Penalty hkls',hkls,filterBox=False) try: if dlg.ShowModal() == wx.ID_OK: POData[6] = [hkls[i] for i in dlg.GetSelections()] if not POData[6]: POData[6] = ['',] else: return finally: dlg.Destroy() wx.CallLater(100,RepaintHistogramInfo) def OnshToler(event): try: value = float(shToler.GetValue()) POData[7] = value except ValueError: pass shToler.SetValue('%.2f'%(POData[7])) A = G2lat.cell2A(generalData['Cell'][1:7]) hkls = G2lat.GenPfHKLs(10,SGData,A) shPenalty = wx.BoxSizer(wx.HORIZONTAL) shPenalty.Add(wx.StaticText(DData,wx.ID_ANY,' Negative MRD penalty list: '),0,WACV) shPenalty.Add(wx.ComboBox(DData,value=POData[6][0],choices=POData[6], style=wx.CB_DROPDOWN),0,WACV) hklList = wx.Button(DData,label='Select penalty hkls') hklList.Bind(wx.EVT_BUTTON,OnHKLList) shPenalty.Add(hklList,0,WACV) shPenalty.Add(wx.StaticText(DData,wx.ID_ANY,' Zero MRD tolerance: '),0,WACV) shToler = wx.TextCtrl(DData,wx.ID_ANY,'%.2f'%(POData[7]),style=wx.TE_PROCESS_ENTER) shToler.Bind(wx.EVT_TEXT_ENTER,OnshToler) shToler.Bind(wx.EVT_KILL_FOCUS,OnshToler) shPenalty.Add(shToler,0,WACV) return shPenalty
def test0(): if NeedTestData: TestData() ibrav, cell, bestcell, Pwr, peaks = TestData print('best cell:', bestcell) print('old cell:', cell) Peaks = np.array(peaks) HKL = Peaks[4:7] print(calc_M20(peaks, HKL)) A = G2lat.cell2A(cell) OK, smin, A, result = FitHKL(ibrav, peaks, A, Pwr) print('new cell:', G2lat.A2cell(A)) print('x:', result[0]) print('cov_x:', result[1]) print('infodict:') for item in result[2]: print(item, result[2][item]) print('msg:', result[3]) print('ier:', result[4]) result = refinePeaks(peaks, ibrav, A) N, M20, X20, A = result print('refinePeaks:', N, M20, X20, G2lat.A2cell(A)) print('compare bestcell:', bestcell)
def DisAglTor(DATData): 'Needs a doc string' SGData = DATData['SGData'] Cell = DATData['Cell'] Amat, Bmat = G2lat.cell2AB(Cell[:6]) covData = {} pfx = '' if 'covData' in DATData: covData = DATData['covData'] pfx = str(DATData['pId']) + '::' Datoms = [] Oatoms = [] for i, atom in enumerate(DATData['Datoms']): symop = atom[-1].split('+') if len(symop) == 1: symop.append('0,0,0') symop[0] = int(symop[0]) symop[1] = eval(symop[1]) atom.append(symop) Datoms.append(atom) oatom = DATData['Oatoms'][i] names = ['', '', ''] if pfx: names = [ pfx + 'dAx:' + str(oatom[0]), pfx + 'dAy:' + str(oatom[0]), pfx + 'dAz:' + str(oatom[0]) ] oatom += [ names, ] Oatoms.append(oatom) atmSeq = [atom[1] + '(' + atom[-2] + ')' for atom in Datoms] if DATData['Natoms'] == 4: #torsion Tors, sig = G2mth.GetDATSig(Oatoms, Datoms, Amat, SGData, covData) print(' Torsion angle for %s atom sequence: %s = %s' % (DATData['Name'], str(atmSeq).replace( "'", "")[1:-1], G2mth.ValEsd(Tors, sig))) print(' NB: Atom sequence determined by selection order') return # done with torsion elif DATData['Natoms'] == 3: #angle Ang, sig = G2mth.GetDATSig(Oatoms, Datoms, Amat, SGData, covData) print(' Angle in %s for atom sequence: %s = %s' % (DATData['Name'], str(atmSeq).replace( "'", "")[1:-1], G2mth.ValEsd(Ang, sig))) print(' NB: Atom sequence determined by selection order') else: #2 atoms - distance Dist, sig = G2mth.GetDATSig(Oatoms, Datoms, Amat, SGData, covData) print(' Distance in %s for atom sequence: %s = %s' % (DATData['Name'], str(atmSeq).replace( "'", "")[1:-1], G2mth.ValEsd(Dist, sig)))
def test0(): if NeedTestData: TestData() msg = 'test FitHKL' ibrav, cell, bestcell, Pwr, peaks = TestData print 'best cell:', bestcell print 'old cell:', cell Peaks = np.array(peaks) HKL = Peaks[4:7] print calc_M20(peaks, HKL) A = G2lat.cell2A(cell) OK, smin, A, result = FitHKL(ibrav, peaks, A, Pwr) print 'new cell:', G2lat.A2cell(A) print 'x:', result[0] print 'cov_x:', result[1] print 'infodict:' for item in result[2]: print item, result[2][item] print 'msg:', result[3] print 'ier:', result[4] result = refinePeaks(peaks, ibrav, A) N, M20, X20, A = result print 'refinePeaks:', N, M20, X20, G2lat.A2cell(A) print 'compare bestcell:', bestcell
def refinePeaksZSS(peaks, wave, Inst, SGData, SSGData, maxH, ibrav, A, vec, vecRef, Zero, ZeroRef): 'needs a doc string' dmin = getDmin(peaks) OK, smin, Aref, Vref, Z, result = FitHKLZSS(wave, ibrav, peaks, A, vec, vecRef, Zero, ZeroRef) Peaks = np.array(peaks).T H = Peaks[4:8] Peaks[9] = 1. / np.sqrt( G2lat.calc_rDsqZSS(H, Aref, Vref, Z, Peaks[0], wave)) #H,A,vec,Z,tth,lam peaks = Peaks.T HKL = G2pwd.getHKLMpeak(dmin, Inst, SGData, SSGData, Vref, maxH, Aref) M20, X20 = calc_M20SS(peaks, HKL) return len(HKL), M20, X20, Aref, Vref, Z
def findMV(peaks,controls,ssopt,Inst,dlg): def Val2Vec(vec,Vref,values): Vec = [] i = 0 for j,r in enumerate(Vref): if r: if values.size > 1: Vec.append(max(0.0,min(1.0,values[i]))) else: Vec.append(max(0.0,min(1.0,values))) i += 1 else: Vec.append(vec[j]) return np.array(Vec) def ZSSfunc(values,peaks,dmin,Inst,SGData,SSGData,vec,Vref,maxH,A,wave,Z,dlg=None): Vec = Val2Vec(vec,Vref,values) HKL = G2pwd.getHKLMpeak(dmin,Inst,SGData,SSGData,Vec,maxH,A) Peaks = np.array(IndexSSPeaks(peaks,HKL)[1]).T Qo = 1./Peaks[-2]**2 Qc = G2lat.calc_rDsqZSS(Peaks[4:8],A,Vec,Z,Peaks[0],wave) chi = np.sum((Qo-Qc)**2) if dlg: dlg.Pulse() return chi if 'C' in Inst['Type'][0]: wave = G2mth.getWave(Inst) else: difC = Inst['difC'][1] SGData = G2spc.SpcGroup(controls[13])[1] SSGData = G2spc.SSpcGroup(SGData,ssopt['ssSymb'])[1] A = G2lat.cell2A(controls[6:12]) Z = controls[1] Vref = [True if x in ssopt['ssSymb'] else False for x in ['a','b','g']] values = [] ranges = [] for v,r in zip(ssopt['ModVec'],Vref): if r: ranges += [slice(.02,.98,.05),] values += [v,] dmin = getDmin(peaks)-0.005 Peaks = np.copy(np.array(peaks).T) result = so.brute(ZSSfunc,ranges,finish=so.fmin_cg, args=(peaks,dmin,Inst,SGData,SSGData,ssopt['ModVec'],Vref,ssopt['maxH'],A,wave,Z,dlg)) return Val2Vec(ssopt['ModVec'],Vref,result)
def DisAglTor(DATData): 'Needs a doc string' SGData = DATData['SGData'] Cell = DATData['Cell'] Amat,Bmat = G2lat.cell2AB(Cell[:6]) covData = {} pfx = '' if 'covData' in DATData: covData = DATData['covData'] covMatrix = covData['covMatrix'] varyList = covData['varyList'] pfx = str(DATData['pId'])+'::' Datoms = [] Oatoms = [] for i,atom in enumerate(DATData['Datoms']): symop = atom[-1].split('+') if len(symop) == 1: symop.append('0,0,0') symop[0] = int(symop[0]) symop[1] = eval(symop[1]) atom.append(symop) Datoms.append(atom) oatom = DATData['Oatoms'][i] names = ['','',''] if pfx: names = [pfx+'dAx:'+str(oatom[0]),pfx+'dAy:'+str(oatom[0]),pfx+'dAz:'+str(oatom[0])] oatom += [names,] Oatoms.append(oatom) atmSeq = [atom[1]+'('+atom[-2]+')' for atom in Datoms] if DATData['Natoms'] == 4: #torsion Tors,sig = G2mth.GetDATSig(Oatoms,Datoms,Amat,SGData,covData) print ' Torsion angle for '+DATData['Name']+' atom sequence: ',atmSeq,'=',G2mth.ValEsd(Tors,sig) print ' NB: Atom sequence determined by selection order' return # done with torsion elif DATData['Natoms'] == 3: #angle Ang,sig = G2mth.GetDATSig(Oatoms,Datoms,Amat,SGData,covData) print ' Angle in '+DATData['Name']+' for atom sequence: ',atmSeq,'=',G2mth.ValEsd(Ang,sig) print ' NB: Atom sequence determined by selection order' else: #2 atoms - distance Dist,sig = G2mth.GetDATSig(Oatoms,Datoms,Amat,SGData,covData) print ' Distance in '+DATData['Name']+' for atom sequence: ',atmSeq,'=',G2mth.ValEsd(Dist,sig)
def Writer(self, TreeName, filename=None): import GSASIIlattice as G2lat self.OpenFile(filename) histblk = self.Histograms[TreeName] inst = histblk['Instrument Parameters'][0] self.Write(str(TreeName)[5:]) # drop 'PWDR ' if 'Lam1' in inst: print( 'Do you really want to write a multi-wavelength pattern in Q?') lam = 0. else: lam = inst['Lam'][1] self.Write("Q{:>20.6f}".format(lam)) self.Write("Intensity") self.Write(" " + str(len(histblk['Data'][0]))) for X, Y in zip(histblk['Data'][0], histblk['Data'][1]): line = " %5.7e" % (2. * np.pi / G2lat.Pos2dsp(inst, X)) line += " %5.7e" % Y self.Write(line) self.CloseFile()
def BestPlane(PlaneData): 'Needs a doc string' def ShowBanner(name): print(80 * '*') print(' Best plane result for phase ' + name) print(80 * '*', '\n') ShowBanner(PlaneData['Name']) Cell = PlaneData['Cell'] Amat, Bmat = G2lat.cell2AB(Cell[:6]) Atoms = PlaneData['Atoms'] sumXYZ = np.zeros(3) XYZ = [] Natoms = len(Atoms) for atom in Atoms: xyz = np.array(atom[3:6]) XYZ.append(xyz) sumXYZ += xyz sumXYZ /= Natoms XYZ = np.array(XYZ) - sumXYZ XYZ = np.inner(Amat, XYZ).T Zmat = np.zeros((3, 3)) for i, xyz in enumerate(XYZ): Zmat += np.outer(xyz.T, xyz) print(' Selected atoms centered at %10.5f %10.5f %10.5f' % (sumXYZ[0], sumXYZ[1], sumXYZ[2])) Evec, Emat = nl.eig(Zmat) Evec = np.sqrt(Evec) / (Natoms - 3) Order = np.argsort(Evec) XYZ = np.inner(XYZ, Emat.T).T XYZ = np.array([XYZ[Order[2]], XYZ[Order[1]], XYZ[Order[0]]]).T print(' Atoms in Cartesian best plane coordinates:') print(' Name X Y Z') for i, xyz in enumerate(XYZ): print(' %6s%10.3f%10.3f%10.3f' % (Atoms[i][1].ljust(6), xyz[0], xyz[1], xyz[2])) print('\n Best plane RMS X =%8.3f, Y =%8.3f, Z =%8.3f' % (Evec[Order[2]], Evec[Order[1]], Evec[Order[0]]))
def TSSfunc(values, peaks, dmin, Inst, SGData, SSGData, vec, Vref, maxH, A, difC, Z, dlg=None): Vec = Val2Vec(vec, Vref, values) HKL = G2pwd.getHKLMpeak(dmin, Inst, SGData, SSGData, Vec, maxH, A) Peaks = np.array(IndexSSPeaks(peaks, HKL)[1]).T Qo = 1. / Peaks[-2]**2 Qc = G2lat.calc_rDsqTSS(Peaks[4:8], A, Vec, Z, Peaks[0], difC) chi = np.sum((Qo - Qc)**2) if dlg: dlg.Pulse() return chi
def test0(): if NeedTestData: TestData() msg = 'test FitHKL' ibrav,cell,bestcell,Pwr,peaks = TestData print 'best cell:',bestcell print 'old cell:',cell Peaks = np.array(peaks) HKL = Peaks[4:7] print calc_M20(peaks,HKL) A = G2lat.cell2A(cell) OK,smin,A,result = FitHKL(ibrav,peaks,A,Pwr) print 'new cell:',G2lat.A2cell(A) print 'x:',result[0] print 'cov_x:',result[1] print 'infodict:' for item in result[2]: print item,result[2][item] print 'msg:',result[3] print 'ier:',result[4] result = refinePeaks(peaks,ibrav,A) N,M20,X20,A = result print 'refinePeaks:',N,M20,X20,G2lat.A2cell(A) print 'compare bestcell:',bestcell
def BestPlane(PlaneData): 'Needs a doc string' def ShowBanner(name): print 80*'*' print ' Best plane result for phase '+name print 80*'*','\n' ShowBanner(PlaneData['Name']) Cell = PlaneData['Cell'] Amat,Bmat = G2lat.cell2AB(Cell[:6]) Atoms = PlaneData['Atoms'] sumXYZ = np.zeros(3) XYZ = [] Natoms = len(Atoms) for atom in Atoms: xyz = np.array(atom[3:6]) XYZ.append(xyz) sumXYZ += xyz sumXYZ /= Natoms XYZ = np.array(XYZ)-sumXYZ XYZ = np.inner(Amat,XYZ).T Zmat = np.zeros((3,3)) for i,xyz in enumerate(XYZ): Zmat += np.outer(xyz.T,xyz) print ' Selected atoms centered at %10.5f %10.5f %10.5f'%(sumXYZ[0],sumXYZ[1],sumXYZ[2]) Evec,Emat = nl.eig(Zmat) Evec = np.sqrt(Evec)/(Natoms-3) Order = np.argsort(Evec) XYZ = np.inner(XYZ,Emat.T).T XYZ = np.array([XYZ[Order[2]],XYZ[Order[1]],XYZ[Order[0]]]).T print ' Atoms in Cartesian best plane coordinates:' print ' Name X Y Z' for i,xyz in enumerate(XYZ): print ' %6s%10.3f%10.3f%10.3f'%(Atoms[i][1].ljust(6),xyz[0],xyz[1],xyz[2]) print '\n Best plane RMS X =%8.3f, Y =%8.3f, Z =%8.3f'%(Evec[Order[2]],Evec[Order[1]],Evec[Order[0]])
def scaleAbyV(A,V): 'needs a doc string' v = G2lat.calc_V(A) scale = math.exp(math.log(v/V)/3.)**2 for i in range(6): A[i] *= scale
def RetDistAngle(DisAglCtls,DisAglData): '''Compute and return distances and angles :param dict DisAglCtls: contains distance/angle radii usually defined using :func:`GSASIIctrlGUI.DisAglDialog` :param dict DisAglData: contains phase data: Items 'OrigAtoms' and 'TargAtoms' contain the atoms to be used for distance/angle origins and atoms to be used as targets. Item 'SGData' has the space group information (see :ref:`Space Group object<SGData_table>`) :returns: AtomLabels,DistArray,AngArray where: **AtomLabels** is a dict of atom labels, keys are the atom number **DistArray** is a dict keyed by the origin atom number where the value is a list of distance entries. The value for each distance is a list containing: 0) the target atom number (int); 1) the unit cell offsets added to x,y & z (tuple of int values) 2) the symmetry operator number (which may be modified to indicate centering and center of symmetry) 3) an interatomic distance in A (float) 4) an uncertainty on the distance in A or 0.0 (float) **AngArray** is a dict keyed by the origin (central) atom number where the value is a list of angle entries. The value for each angle entry consists of three values: 0) a distance item reference for one neighbor (int) 1) a distance item reference for a second neighbor (int) 2) a angle, uncertainty pair; the s.u. may be zero (tuple of two floats) The AngArray distance reference items refer directly to the index of the items in the DistArray item for the list of distances for the central atom. ''' import numpy.ma as ma SGData = DisAglData['SGData'] Cell = DisAglData['Cell'] Amat,Bmat = G2lat.cell2AB(Cell[:6]) covData = {} if 'covData' in DisAglData: covData = DisAglData['covData'] covMatrix = covData['covMatrix'] varyList = covData['varyList'] pfx = str(DisAglData['pId'])+'::' Factor = DisAglCtls['Factors'] Radii = dict(zip(DisAglCtls['AtomTypes'],zip(DisAglCtls['BondRadii'],DisAglCtls['AngleRadii']))) indices = (-2,-1,0,1,2) Units = np.array([[h,k,l] for h in indices for k in indices for l in indices]) origAtoms = DisAglData['OrigAtoms'] targAtoms = DisAglData['TargAtoms'] AtomLabels = {} for Oatom in origAtoms: AtomLabels[Oatom[0]] = Oatom[1] for Oatom in targAtoms: AtomLabels[Oatom[0]] = Oatom[1] DistArray = {} AngArray = {} for Oatom in origAtoms: DistArray[Oatom[0]] = [] AngArray[Oatom[0]] = [] OxyzNames = '' IndBlist = [] Dist = [] Vect = [] VectA = [] angles = [] for Tatom in targAtoms: Xvcov = [] TxyzNames = '' if 'covData' in DisAglData: OxyzNames = [pfx+'dAx:%d'%(Oatom[0]),pfx+'dAy:%d'%(Oatom[0]),pfx+'dAz:%d'%(Oatom[0])] TxyzNames = [pfx+'dAx:%d'%(Tatom[0]),pfx+'dAy:%d'%(Tatom[0]),pfx+'dAz:%d'%(Tatom[0])] Xvcov = G2mth.getVCov(OxyzNames+TxyzNames,varyList,covMatrix) result = G2spc.GenAtom(Tatom[3:6],SGData,False,Move=False) BsumR = (Radii[Oatom[2]][0]+Radii[Tatom[2]][0])*Factor[0] AsumR = (Radii[Oatom[2]][1]+Radii[Tatom[2]][1])*Factor[1] for [Txyz,Top,Tunit,Spn] in result: Dx = (Txyz-np.array(Oatom[3:6]))+Units dx = np.inner(Amat,Dx) dist = ma.masked_less(np.sqrt(np.sum(dx**2,axis=0)),0.5) IndB = ma.nonzero(ma.masked_greater(dist-BsumR,0.)) if np.any(IndB): for indb in IndB: for i in range(len(indb)): if str(dx.T[indb][i]) not in IndBlist: IndBlist.append(str(dx.T[indb][i])) unit = Units[indb][i] tunit = (unit[0]+Tunit[0],unit[1]+Tunit[1],unit[2]+Tunit[2]) pdpx = G2mth.getDistDerv(Oatom[3:6],Tatom[3:6],Amat,unit,Top,SGData) sig = 0.0 if len(Xvcov): sig = np.sqrt(np.inner(pdpx,np.inner(pdpx,Xvcov))) Dist.append([Oatom[0],Tatom[0],tunit,Top,ma.getdata(dist[indb])[i],sig]) if (Dist[-1][-2]-AsumR) <= 0.: Vect.append(dx.T[indb][i]/Dist[-1][-2]) VectA.append([OxyzNames,np.array(Oatom[3:6]),TxyzNames,np.array(Tatom[3:6]),unit,Top]) else: Vect.append([0.,0.,0.]) VectA.append([]) for D in Dist: DistArray[Oatom[0]].append(D[1:]) Vect = np.array(Vect) angles = np.zeros((len(Vect),len(Vect))) angsig = np.zeros((len(Vect),len(Vect))) for i,veca in enumerate(Vect): if np.any(veca): for j,vecb in enumerate(Vect): if np.any(vecb): angles[i][j],angsig[i][j] = G2mth.getAngSig(VectA[i],VectA[j],Amat,SGData,covData) if i <= j: continue AngArray[Oatom[0]].append((i,j, G2mth.getAngSig(VectA[i],VectA[j],Amat,SGData,covData))) return AtomLabels,DistArray,AngArray
def ImageRecalibrate(self,data,masks): 'Needs a doc string' import ImageCalibrants as calFile print 'Image recalibration:' time0 = time.time() pixelSize = data['pixelSize'] scalex = 1000./pixelSize[0] scaley = 1000./pixelSize[1] pixLimit = data['pixLimit'] cutoff = data['cutoff'] data['rings'] = [] data['ellipses'] = [] if not data['calibrant']: print 'no calibration material selected' return True skip = data['calibskip'] dmin = data['calibdmin'] Bravais,SGs,Cells = calFile.Calibrants[data['calibrant']][:3] HKL = [] for bravais,sg,cell in zip(Bravais,SGs,Cells): A = G2lat.cell2A(cell) if sg: SGData = G2spc.SpcGroup(sg)[1] hkl = G2pwd.getHKLpeak(dmin,SGData,A) HKL += hkl else: hkl = G2lat.GenHBravais(dmin,bravais,A) HKL += hkl HKL = G2lat.sortHKLd(HKL,True,False) varyList = [item for item in data['varyList'] if data['varyList'][item]] parmDict = {'dist':data['distance'],'det-X':data['center'][0],'det-Y':data['center'][1], 'tilt':data['tilt'],'phi':data['rotation'],'wave':data['wavelength'],'dep':data['DetDepth']} Found = False wave = data['wavelength'] frame = masks['Frames'] tam = ma.make_mask_none(self.ImageZ.shape) if frame: tam = ma.mask_or(tam,MakeFrameMask(data,frame)) for iH,H in enumerate(HKL): if debug: print H dsp = H[3] tth = 2.0*asind(wave/(2.*dsp)) if tth+abs(data['tilt']) > 90.: print 'next line is a hyperbola - search stopped' break ellipse = GetEllipse(dsp,data) Ring = makeRing(dsp,ellipse,pixLimit,cutoff,scalex,scaley,ma.array(self.ImageZ,mask=tam)) if Ring: if iH >= skip: data['rings'].append(np.array(Ring)) data['ellipses'].append(copy.deepcopy(ellipse+('r',))) Found = True elif not Found: #skipping inner rings, keep looking until ring found continue else: #no more rings beyond edge of detector data['ellipses'].append([]) continue # break rings = np.concatenate((data['rings']),axis=0) chisq = FitDetector(rings,varyList,parmDict) data['wavelength'] = parmDict['wave'] data['distance'] = parmDict['dist'] data['center'] = [parmDict['det-X'],parmDict['det-Y']] data['rotation'] = np.mod(parmDict['phi'],360.0) data['tilt'] = parmDict['tilt'] data['DetDepth'] = parmDict['dep'] data['chisq'] = chisq N = len(data['ellipses']) data['ellipses'] = [] #clear away individual ellipse fits for H in HKL[:N]: ellipse = GetEllipse(H[3],data) data['ellipses'].append(copy.deepcopy(ellipse+('b',))) print 'calibration time = ',time.time()-time0 G2plt.PlotImage(self,newImage=True) return True
def ImageCalibrate(self,data): 'Needs a doc string' import copy import ImageCalibrants as calFile print 'Image calibration:' time0 = time.time() ring = data['ring'] pixelSize = data['pixelSize'] scalex = 1000./pixelSize[0] scaley = 1000./pixelSize[1] pixLimit = data['pixLimit'] cutoff = data['cutoff'] varyDict = data['varyList'] if varyDict['dist'] and varyDict['wave']: print 'ERROR - you can not simultaneously calibrate distance and wavelength' return False if len(ring) < 5: print 'ERROR - not enough inner ring points for ellipse' return False #fit start points on inner ring data['ellipses'] = [] data['rings'] = [] outE = FitEllipse(ring) fmt = '%s X: %.3f, Y: %.3f, phi: %.3f, R1: %.3f, R2: %.3f' fmt2 = '%s X: %.3f, Y: %.3f, phi: %.3f, R1: %.3f, R2: %.3f, chi**2: %.3f, Np: %d' if outE: print fmt%('start ellipse: ',outE[0][0],outE[0][1],outE[1],outE[2][0],outE[2][1]) ellipse = outE else: return False #setup 360 points on that ring for "good" fit data['ellipses'].append(ellipse[:]+('g',)) Ring = makeRing(1.0,ellipse,pixLimit,cutoff,scalex,scaley,self.ImageZ) if Ring: ellipse = FitEllipse(Ring) Ring = makeRing(1.0,ellipse,pixLimit,cutoff,scalex,scaley,self.ImageZ) #do again ellipse = FitEllipse(Ring) else: print '1st ring not sufficiently complete to proceed' return False if debug: print fmt2%('inner ring: ',ellipse[0][0],ellipse[0][1],ellipse[1], ellipse[2][0],ellipse[2][1],0.,len(Ring)) #cent,phi,radii data['ellipses'].append(ellipse[:]+('r',)) data['rings'].append(np.array(Ring)) G2plt.PlotImage(self,newImage=True) #setup for calibration data['rings'] = [] if not data['calibrant']: print 'no calibration material selected' return True skip = data['calibskip'] dmin = data['calibdmin'] #generate reflection set Bravais,SGs,Cells = calFile.Calibrants[data['calibrant']][:3] HKL = [] for bravais,sg,cell in zip(Bravais,SGs,Cells): A = G2lat.cell2A(cell) if sg: SGData = G2spc.SpcGroup(sg)[1] hkl = G2pwd.getHKLpeak(dmin,SGData,A) HKL += hkl else: hkl = G2lat.GenHBravais(dmin,bravais,A) HKL += hkl HKL = G2lat.sortHKLd(HKL,True,False)[skip:] #set up 1st ring elcent,phi,radii = ellipse #from fit of 1st ring dsp = HKL[0][3] print '1st ring: try %.4f'%(dsp) if varyDict['dist']: wave = data['wavelength'] tth = 2.0*asind(wave/(2.*dsp)) else: #varyDict['wave']! dist = data['distance'] tth = npatan2d(radii[0],dist) data['wavelength'] = wave = 2.0*dsp*sind(tth/2.0) Ring0 = makeRing(dsp,ellipse,3,cutoff,scalex,scaley,self.ImageZ) ttth = nptand(tth) stth = npsind(tth) ctth = npcosd(tth) #1st estimate of tilt; assume ellipse - don't know sign though if varyDict['tilt']: tilt = npasind(np.sqrt(max(0.,1.-(radii[0]/radii[1])**2))*ctth) if not tilt: print 'WARNING - selected ring was fitted as a circle' print ' - if detector was tilted we suggest you skip this ring - WARNING' else: tilt = data['tilt'] #1st estimate of dist: sample to detector normal to plane if varyDict['dist']: data['distance'] = dist = radii[0]**2/(ttth*radii[1]) else: dist = data['distance'] if varyDict['tilt']: #ellipse to cone axis (x-ray beam); 2 choices depending on sign of tilt zdisp = radii[1]*ttth*tand(tilt) zdism = radii[1]*ttth*tand(-tilt) #cone axis position; 2 choices. Which is right? #NB: zdisp is || to major axis & phi is rotation of minor axis #thus shift from beam to ellipse center is [Z*sin(phi),-Z*cos(phi)] centp = [elcent[0]+zdisp*sind(phi),elcent[1]-zdisp*cosd(phi)] centm = [elcent[0]+zdism*sind(phi),elcent[1]-zdism*cosd(phi)] #check get same ellipse parms either way #now do next ring; estimate either way & do a FitDetector each way; best fit is correct one fail = True i2 = 1 while fail: dsp = HKL[i2][3] print '2nd ring: try %.4f'%(dsp) tth = 2.0*asind(wave/(2.*dsp)) ellipsep = GetEllipse2(tth,0.,dist,centp,tilt,phi) print fmt%('plus ellipse :',ellipsep[0][0],ellipsep[0][1],ellipsep[1],ellipsep[2][0],ellipsep[2][1]) Ringp = makeRing(dsp,ellipsep,3,cutoff,scalex,scaley,self.ImageZ) parmDict = {'dist':dist,'det-X':centp[0],'det-Y':centp[1], 'tilt':tilt,'phi':phi,'wave':wave,'dep':0.0} varyList = [item for item in varyDict if varyDict[item]] if len(Ringp) > 10: chip = FitDetector(np.array(Ring0+Ringp),varyList,parmDict,True) tiltp = parmDict['tilt'] phip = parmDict['phi'] centp = [parmDict['det-X'],parmDict['det-Y']] fail = False else: chip = 1e6 ellipsem = GetEllipse2(tth,0.,dist,centm,-tilt,phi) print fmt%('minus ellipse:',ellipsem[0][0],ellipsem[0][1],ellipsem[1],ellipsem[2][0],ellipsem[2][1]) Ringm = makeRing(dsp,ellipsem,3,cutoff,scalex,scaley,self.ImageZ) if len(Ringm) > 10: parmDict['tilt'] *= -1 chim = FitDetector(np.array(Ring0+Ringm),varyList,parmDict,True) tiltm = parmDict['tilt'] phim = parmDict['phi'] centm = [parmDict['det-X'],parmDict['det-Y']] fail = False else: chim = 1e6 if fail: i2 += 1 if chip < chim: data['tilt'] = tiltp data['center'] = centp data['rotation'] = phip else: data['tilt'] = tiltm data['center'] = centm data['rotation'] = phim data['ellipses'].append(ellipsep[:]+('b',)) data['rings'].append(np.array(Ringp)) data['ellipses'].append(ellipsem[:]+('r',)) data['rings'].append(np.array(Ringm)) G2plt.PlotImage(self,newImage=True) parmDict = {'dist':data['distance'],'det-X':data['center'][0],'det-Y':data['center'][1], 'tilt':data['tilt'],'phi':data['rotation'],'wave':data['wavelength'],'dep':data['DetDepth']} varyList = [item for item in varyDict if varyDict[item]] data['rings'] = [] data['ellipses'] = [] for i,H in enumerate(HKL): dsp = H[3] tth = 2.0*asind(wave/(2.*dsp)) if tth+abs(data['tilt']) > 90.: print 'next line is a hyperbola - search stopped' break if debug: print 'HKLD:',H[:4],'2-theta: %.4f'%(tth) elcent,phi,radii = ellipse = GetEllipse(dsp,data) data['ellipses'].append(copy.deepcopy(ellipse+('g',))) if debug: print fmt%('predicted ellipse:',elcent[0],elcent[1],phi,radii[0],radii[1]) Ring = makeRing(dsp,ellipse,pixLimit,cutoff,scalex,scaley,self.ImageZ) if Ring: data['rings'].append(np.array(Ring)) rings = np.concatenate((data['rings']),axis=0) if i: chisq = FitDetector(rings,varyList,parmDict,False) data['distance'] = parmDict['dist'] data['center'] = [parmDict['det-X'],parmDict['det-Y']] data['rotation'] = parmDict['phi'] data['tilt'] = parmDict['tilt'] data['DetDepth'] = parmDict['dep'] data['chisq'] = chisq elcent,phi,radii = ellipse = GetEllipse(dsp,data) if debug: print fmt2%('fitted ellipse: ',elcent[0],elcent[1],phi,radii[0],radii[1],chisq,len(rings)) data['ellipses'].append(copy.deepcopy(ellipse+('r',))) # G2plt.PlotImage(self,newImage=True) else: if debug: print 'insufficient number of points in this ellipse to fit' # break G2plt.PlotImage(self,newImage=True) fullSize = len(self.ImageZ)/scalex if 2*radii[1] < .9*fullSize: print 'Are all usable rings (>25% visible) used? Try reducing Min ring I/Ib' N = len(data['ellipses']) if N > 2: FitDetector(rings,varyList,parmDict) data['wavelength'] = parmDict['wave'] data['distance'] = parmDict['dist'] data['center'] = [parmDict['det-X'],parmDict['det-Y']] data['rotation'] = parmDict['phi'] data['tilt'] = parmDict['tilt'] data['DetDepth'] = parmDict['dep'] for H in HKL[:N]: ellipse = GetEllipse(H[3],data) data['ellipses'].append(copy.deepcopy(ellipse+('b',))) print 'calibration time = ',time.time()-time0 G2plt.PlotImage(self,newImage=True) return True
def ImageRecalibrate(self, data, masks): 'Needs a doc string' import ImageCalibrants as calFile print 'Image recalibration:' time0 = time.time() pixelSize = data['pixelSize'] scalex = 1000. / pixelSize[0] scaley = 1000. / pixelSize[1] pixLimit = data['pixLimit'] cutoff = data['cutoff'] data['rings'] = [] data['ellipses'] = [] if not data['calibrant']: print 'no calibration material selected' return True skip = data['calibskip'] dmin = data['calibdmin'] Bravais, SGs, Cells = calFile.Calibrants[data['calibrant']][:3] HKL = [] for bravais, sg, cell in zip(Bravais, SGs, Cells): A = G2lat.cell2A(cell) if sg: SGData = G2spc.SpcGroup(sg)[1] hkl = G2pwd.getHKLpeak(dmin, SGData, A) HKL += hkl else: hkl = G2lat.GenHBravais(dmin, bravais, A) HKL += hkl HKL = G2lat.sortHKLd(HKL, True, False) varyList = [item for item in data['varyList'] if data['varyList'][item]] parmDict = { 'dist': data['distance'], 'det-X': data['center'][0], 'det-Y': data['center'][1], 'tilt': data['tilt'], 'phi': data['rotation'], 'wave': data['wavelength'], 'dep': data['DetDepth'] } Found = False wave = data['wavelength'] frame = masks['Frames'] tam = ma.make_mask_none(self.ImageZ.shape) if frame: tam = ma.mask_or(tam, MakeFrameMask(data, frame)) for iH, H in enumerate(HKL): if debug: print H dsp = H[3] tth = 2.0 * asind(wave / (2. * dsp)) if tth + abs(data['tilt']) > 90.: print 'next line is a hyperbola - search stopped' break ellipse = GetEllipse(dsp, data) Ring = makeRing(dsp, ellipse, pixLimit, cutoff, scalex, scaley, ma.array(self.ImageZ, mask=tam)) if Ring: if iH >= skip: data['rings'].append(np.array(Ring)) data['ellipses'].append(copy.deepcopy(ellipse + ('r', ))) Found = True elif not Found: #skipping inner rings, keep looking until ring found continue else: #no more rings beyond edge of detector data['ellipses'].append([]) continue # break rings = np.concatenate((data['rings']), axis=0) chisq = FitDetector(rings, varyList, parmDict) data['wavelength'] = parmDict['wave'] data['distance'] = parmDict['dist'] data['center'] = [parmDict['det-X'], parmDict['det-Y']] data['rotation'] = np.mod(parmDict['phi'], 360.0) data['tilt'] = parmDict['tilt'] data['DetDepth'] = parmDict['dep'] data['chisq'] = chisq N = len(data['ellipses']) data['ellipses'] = [] #clear away individual ellipse fits for H in HKL[:N]: ellipse = GetEllipse(H[3], data) data['ellipses'].append(copy.deepcopy(ellipse + ('b', ))) print 'calibration time = ', time.time() - time0 G2plt.PlotImage(self, newImage=True) return True
def DoIndexPeaks(peaks,controls,bravais,ifX20=True): 'needs a doc string' delt = 0.005 #lowest d-spacing cushion - can be fixed? amin = 2.5 amax = 5.0*getDmax(peaks) dmin = getDmin(peaks)-delt bravaisNames = ['Cubic-F','Cubic-I','Cubic-P','Trigonal-R','Trigonal/Hexagonal-P', 'Tetragonal-I','Tetragonal-P','Orthorhombic-F','Orthorhombic-I','Orthorhombic-C', 'Orthorhombic-P','Monoclinic-C','Monoclinic-P','Triclinic'] tries = ['1st','2nd','3rd','4th','5th','6th','7th','8th','9th','10th'] N1s = [1,1,1, 5,5, 5,5, 50,50,50,50, 50,50, 200] N2s = [1,1,1, 2,2, 2,2, 2,2,2,2, 2,2, 4] Nm = [1,1,1, 1,1, 1,1, 1,1,1,1, 2,2, 4] Nobs = len(peaks) zero,ncno = controls[1:3] ncMax = Nobs*ncno print "%s %8.3f %8.3f" % ('lattice parameter range = ',amin,amax) print "%s %.4f %s %d %s %d" % ('Zero =',zero,'Nc/No max =',ncno,' Max Nc =',ncno*Nobs) cells = [] for ibrav in range(14): begin = time.time() if bravais[ibrav]: print 'cell search for ',bravaisNames[ibrav] print ' M20 X20 Nc a b c alpha beta gamma volume V-test' V1 = controls[3] bestM20 = 0 topM20 = 0 cycle = 0 while cycle < 5: dlg = wx.ProgressDialog("Generated reflections",tries[cycle]+" cell search for "+bravaisNames[ibrav],ncMax, style = wx.PD_ELAPSED_TIME|wx.PD_AUTO_HIDE|wx.PD_REMAINING_TIME|wx.PD_CAN_ABORT) screenSize = wx.ClientDisplayRect() Size = dlg.GetSize() dlg.SetPosition(wx.Point(screenSize[2]-Size[0]-305,screenSize[1]+5)) try: GoOn = True while GoOn: #Loop over increment of volume N2 = 0 while N2 < N2s[ibrav]: #Table 2 step (iii) if ibrav > 2: if not N2: A = [] GoOn,Nc,M20,X20,A = findBestCell(dlg,ncMax,A,Nm[ibrav]*N1s[ibrav],ibrav,peaks,V1,ifX20) if A: GoOn,Nc,M20,X20,A = findBestCell(dlg,ncMax,A[:],N1s[ibrav],ibrav,peaks,0,ifX20) else: GoOn,Nc,M20,X20,A = findBestCell(dlg,ncMax,0,Nm[ibrav]*N1s[ibrav],ibrav,peaks,V1,ifX20) if Nc >= ncMax: GoOn = False break elif 3*Nc < Nobs: N2 = 10 break else: if not GoOn: break if M20 > 1.0: bestM20 = max(bestM20,M20) A = halfCell(ibrav,A[:],peaks) if ibrav in [12]: A = monoCellReduce(ibrav,A[:]) HKL = G2lat.GenHBravais(dmin,ibrav,A) peaks = IndexPeaks(peaks,HKL)[1] a,b,c,alp,bet,gam = G2lat.A2cell(A) V = G2lat.calc_V(A) if M20 >= 2.0: print "%10.3f %3d %3d %10.5f %10.5f %10.5f %10.3f %10.3f %10.3f %10.2f %10.2f" % (M20,X20,Nc,a,b,c,alp,bet,gam,V,V1) cells.append([M20,X20,ibrav,a,b,c,alp,bet,gam,V,False,False]) if not GoOn: break N2 += 1 if ibrav < 11: V1 *= 1.1 elif ibrav in range(11,14): V1 *= 1.05 if not GoOn: if bestM20 > topM20: topM20 = bestM20 if cells: V1 = cells[0][9] else: V1 = 25 ncMax += Nobs cycle += 1 print 'Restart search, new Max Nc = ',ncMax else: cycle = 10 finally: dlg.Destroy() print '%s%s%s%s'%('finished cell search for ',bravaisNames[ibrav], \ ', elapsed time = ',G2lat.sec2HMS(time.time()-begin)) if cells: return True,dmin,cells else: return False,0,[]
def UpdateLattice(self, parmVarDict, phase_index): ''' Update the lattice parameters in the current model for all phases ''' # Symmetry Options: # cubic, tetragonal, hexagonal, rhombohedral, trigonal, # orthorhombic, monoclinic, triclinic if self._symmetry[self._phase[phase_index]] == 'cubic': a = parmVarDict[str(phase_index) + '::a'] b = a c = a alpha = 90. beta = 90. gamma = 90. elif self._symmetry[self._phase[phase_index]] == 'tetragonal': a = parmVarDict[str(phase_index) + '::a'] b = a c = parmVarDict[str(phase_index) + '::c'] alpha = 90. beta = 90. gamma = 90. elif self._symmetry[self._phase[phase_index]] == 'hexagonal': a = parmVarDict[str(phase_index) + '::a'] b = a c = parmVarDict[str(phase_index) + '::c'] alpha = 90. beta = 90. gamma = 120. elif self._symmetry[self._phase[phase_index]] == 'trigonal': a = parmVarDict[str(phase_index) + '::a'] b = a c = parmVarDict[str(phase_index) + '::c'] alpha = 90. beta = 90. gamma = 120. elif self._symmetry[self._phase[phase_index]] == 'rhombohedral': a = parmVarDict[str(phase_index) + '::a'] b = a c = a alpha = parmVarDict[str(phase_index) + '::alpha'] beta = alpha gamma = alpha elif self._symmetry[self._phase[phase_index]] == 'orthorhombic': a = parmVarDict[str(phase_index) + '::a'] b = parmVarDict[str(phase_index) + '::b'] c = parmVarDict[str(phase_index) + '::c'] alpha = 90. beta = 90. gamma = 90. elif self._symmetry[self._phase[phase_index]] == 'monoclinic': a = parmVarDict[str(phase_index) + '::a'] b = parmVarDict[str(phase_index) + '::b'] c = parmVarDict[str(phase_index) + '::c'] beta = parmVarDict[str(phase_index) + '::beta'] alpha = 90. gamma = 90. elif self._symmetry[self._phase[phase_index]] == 'triclinic': a = parmVarDict[str(phase_index) + '::a'] b = parmVarDict[str(phase_index) + '::b'] c = parmVarDict[str(phase_index) + '::c'] alpha = parmVarDict[str(phase_index) + '::alpha'] beta = parmVarDict[str(phase_index) + '::beta'] gamma = parmVarDict[str(phase_index) + '::gamma'] A = G2latt.cell2A([a, b, c, alpha, beta, gamma]) LatticeUpdate = { str(phase_index) + '::A0': A[0], str(phase_index) + '::A1': A[1], str(phase_index) + '::A2': A[2], str(phase_index) + '::A3': A[3], str(phase_index) + '::A4': A[4], str(phase_index) + '::A5': A[5] } self._parmDict.update(LatticeUpdate) return parmVarDict
def ReadJANAPhase(self, filename, parent=None): '''Read a phase from a JANA2006 m50 & m40 files. ''' self.errors = 'Error opening file' file = open(filename, 'Ur') #contains only cell & spcgroup Phase = {} Title = os.path.basename(filename) Compnd = '' Type = 'nuclear' Atoms = [] Atypes = [] SuperVec = [[0, 0, .1], False, 4] S = file.readline() line = 1 SGData = None SuperSg = '' cell = None nqi = 0 while S: self.errors = 'Error reading at line ' + str(line) if 'title' in S and S != 'title\n': Title = S.split()[1] elif 'cell' in S[:4]: cell = S[5:].split() cell = [ float(cell[0]), float(cell[1]), float(cell[2]), float(cell[3]), float(cell[4]), float(cell[5]) ] Volume = G2lat.calc_V(G2lat.cell2A(cell)) elif 'spgroup' in S: if 'X' in S: raise self.ImportException( "Supersymmetry " + S + " too high; GSAS-II limited to (3+1) supersymmetry") SpGrp = S.split()[1] SuperSg = '' if '(' in SpGrp: #supercell symmetry - split in 2 SuperStr = SpGrp.split('(') SpGrp = SuperStr[0] SuperSg = '(' + SuperStr[1] SpGrpNorm = G2spc.StandardizeSpcName(SpGrp) E, SGData = G2spc.SpcGroup(SpGrpNorm) # space group processing failed, try to look up name in table while E: print G2spc.SGErrors(E) dlg = wx.TextEntryDialog( parent, SpGrp[:-1] + ' is invalid \nN.B.: make sure spaces separate axial fields in symbol', 'ERROR in space group symbol', '', style=wx.OK) if dlg.ShowModal() == wx.ID_OK: SpGrp = dlg.GetValue() E, SGData = G2spc.SpcGroup(SpGrp) else: SGData = G2IO.SGData # P 1 self.warnings += '\nThe space group was not interpreted and has been set to "P 1".' self.warnings += "Change this in phase's General tab." dlg.Destroy() SGlines = G2spc.SGPrint(SGData) elif 'qi' in S[:2]: if nqi: raise self.ImportException( "Supersymmetry too high; GSAS-II limited to (3+1) supersymmetry" ) Type = 'modulated' vec = S.split()[1:] SuperVec = [[float(vec[i]) for i in range(3)], False, 4] nqi += 1 elif 'atom' in S[:4]: Atypes.append(S.split()[1]) S = file.readline() line += 1 file.close() #read atoms from m40 file if not SGData: self.warnings += '\nThe space group was not read before atoms and has been set to "P 1". ' self.warnings += "Change this in phase's General tab." SGData = G2IO.SGData # P 1 waveTypes = [ 'Fourier', 'Sawtooth', 'ZigZag', ] filename2 = os.path.splitext(filename)[0] + '.m40' file2 = open(filename2, 'Ur') S = file2.readline() line = 1 self.errors = 'Error reading at line ' + str(line) nAtoms = int(S.split()[0]) for i in range(4): S = file2.readline() for i in range(nAtoms): S1 = file2.readline() S1N = S1.split()[-3:] # no. occ, no. pos waves, no. ADP waves S1N = [int(i) for i in S1N] S1T = list(S1[60:63]) waveType = waveTypes[int(S1T[1])] crenelType = '' Spos = [] Sadp = [] Sfrac = [] Smag = [] XYZ = [float(S1[27:36]), float(S1[36:45]), float(S1[45:54])] SytSym, Mult = G2spc.SytSym(XYZ, SGData) aType = Atypes[int(S1[9:11]) - 1] Name = S1[:8].strip() if S1[11:15].strip() == '1': S2 = file2.readline() Uiso = float(S2[:9]) Uij = [0, 0, 0, 0, 0, 0] IA = 'I' elif S1[11:15].strip() == '2': S2 = file2.readline() IA = 'A' Uiso = 0. Uij = [ float(S2[:9]), float(S2[9:18]), float(S2[18:27]), float(S2[27:36]), float(S2[36:45]), float(S2[45:54]) ] for i in range(S1N[0]): if not i: FS = file2.readline() Sfrac.append(FS[:9]) #'O' or 'delta' = 'length' for crenel if int( S1T[0] ): #"", "Legendre" or "Xharm" in 18:27 for "crenel"! waveType = 'Crenel/Fourier' #all waves 'Fourier' no other choice crenelType = FS[18:27] Sfrac.append( file2.readline()[:18]) #if not crenel = Osin & Ocos # else Osin & Ocos except last one is X40 = 'Center' for i in range(S1N[1]): Spos.append(file2.readline()[:54]) for i in range(S1N[2]): Sadp.append(file2.readline()[:54] + file2.readline()) if sum(S1N): #if any waves: skip mystery line? file2.readline() for i, it in enumerate(Sfrac): print i, it if not i: if 'Crenel' in waveType: vals = [float(it), float(Sfrac[-1][:9])] else: vals = [ float(it), ] else: vals = [float(it[:9]), float(it[9:18])] if 'Crenel' in waveType and i == len(Sfrac) - 1: del Sfrac[-1] break Sfrac[i] = [vals, False] print Sfrac[i] for i, it in enumerate(Spos): if waveType in ['ZigZag', 'Sawtooth'] and not i: vals = [ float(it[:9]), float(it[9:18]), float(it[18:27]), float(it[27:36]) ] else: vals = [ float(it[:9]), float(it[9:18]), float(it[18:27]), float(it[27:36]), float(it[36:45]), float(it[45:54]) ] Spos[i] = [vals, False] for i, it in enumerate(Sadp): vals = [ float(it[:9]), float(it[9:18]), float(it[18:27]), float(it[27:36]), float(it[36:45]), float(it[45:54]), float(it[54:63]), float(it[63:72]), float(it[72:81]), float(it[81:90]), float(it[90:99]), float(it[99:108]) ] Sadp[i] = [vals, False] Atom = [ Name, aType, '', XYZ[0], XYZ[1], XYZ[2], 1.0, SytSym, Mult, IA, Uiso ] Atom += Uij Atom.append(ran.randint(0, sys.maxint)) Atom.append([]) Atom.append([]) Atom.append({ 'SS1': { 'waveType': waveType, 'crenelType': crenelType, 'Sfrac': Sfrac, 'Spos': Spos, 'Sadp': Sadp, 'Smag': Smag } }) #SS2 is for (3+2), etc. Atoms.append(Atom) file2.close() self.errors = 'Error after read complete' if not SGData: raise self.ImportException("No space group (spcgroup entry) found") if not cell: raise self.ImportException("No cell found") Phase = G2IO.SetNewPhase(Name=Title, SGData=SGData, cell=cell + [ Volume, ]) Phase['General']['Type'] = Type Phase['General']['Super'] = nqi Phase['General']['SuperVec'] = SuperVec Phase['General']['SuperSg'] = SuperSg if SuperSg: Phase['General']['SSGData'] = G2spc.SSpcGroup(SGData, SuperSg)[1] Phase['General']['AtomPtrs'] = [3, 1, 7, 9] Phase['Atoms'] = Atoms return Phase
def PrintDistAngle(DisAglCtls,DisAglData,out=sys.stdout): '''Print distances and angles :param dict DisAglCtls: contains distance/angle radii usually defined using :func:`GSASIIctrlGUI.DisAglDialog` :param dict DisAglData: contains phase data: Items 'OrigAtoms' and 'TargAtoms' contain the atoms to be used for distance/angle origins and atoms to be used as targets. Item 'SGData' has the space group information (see :ref:`Space Group object<SGData_table>`) :param file out: file object for output. Defaults to sys.stdout. ''' def MyPrint(s): out.write(s+'\n') # print(s,file=out) # use in Python 3 def ShowBanner(name): MyPrint(80*'*') MyPrint(' Interatomic Distances and Angles for phase '+name) MyPrint((80*'*')+'\n') ShowBanner(DisAglCtls['Name']) SGData = DisAglData['SGData'] SGtext,SGtable = G2spc.SGPrint(SGData) for line in SGtext: MyPrint(line) if len(SGtable) > 1: for i,item in enumerate(SGtable[::2]): if 2*i+1 == len(SGtable): line = ' %s'%(item.ljust(30)) else: line = ' %s %s'%(item.ljust(30),SGtable[2*i+1].ljust(30)) MyPrint(line) else: MyPrint(' ( 1) %s'%(SGtable[0])) #triclinic case Cell = DisAglData['Cell'] Amat,Bmat = G2lat.cell2AB(Cell[:6]) covData = {} if 'covData' in DisAglData: covData = DisAglData['covData'] pfx = str(DisAglData['pId'])+'::' A = G2lat.cell2A(Cell[:6]) cellSig = G2stIO.getCellEsd(pfx,SGData,A,covData) names = [' a = ',' b = ',' c = ',' alpha = ',' beta = ',' gamma = ',' Volume = '] valEsd = [G2mth.ValEsd(Cell[i],cellSig[i],True) for i in range(7)] line = '\n Unit cell:' for name,vals in zip(names,valEsd): line += name+vals MyPrint(line) else: MyPrint('\n Unit cell: a = '+('%.5f'%Cell[0])+' b = '+('%.5f'%Cell[1])+' c = '+('%.5f'%Cell[2])+ ' alpha = '+('%.3f'%Cell[3])+' beta = '+('%.3f'%Cell[4])+' gamma = '+ ('%.3f'%Cell[5])+' Volume = '+('%.3f'%Cell[6])) AtomLabels,DistArray,AngArray = RetDistAngle(DisAglCtls,DisAglData) origAtoms = DisAglData['OrigAtoms'] for Oatom in origAtoms: i = Oatom[0] Dist = DistArray[i] nDist = len(Dist) angles = np.zeros((nDist,nDist)) angsig = np.zeros((nDist,nDist)) for k,j,tup in AngArray[i]: angles[k][j],angsig[k][j] = angles[j][k],angsig[j][k] = tup line = '' for i,x in enumerate(Oatom[3:6]): line += ('%12.5f'%x).rstrip('0') MyPrint('\n Distances & angles for '+Oatom[1]+' at '+line.rstrip()) MyPrint(80*'*') line = '' for dist in Dist[:-1]: line += '%12s'%(AtomLabels[dist[0]].center(12)) MyPrint(' To cell +(sym. op.) dist. '+line.rstrip()) for i,dist in enumerate(Dist): line = '' for j,angle in enumerate(angles[i][0:i]): sig = angsig[i][j] if angle: if sig: line += '%12s'%(G2mth.ValEsd(angle,sig,True).center(12)) else: val = '%.3f'%(angle) line += '%12s'%(val.center(12)) else: line += 12*' ' if dist[4]: #sig exists! val = G2mth.ValEsd(dist[3],dist[4]) else: val = '%8.4f'%(dist[3]) tunit = '[%2d%2d%2d]'% dist[1] MyPrint((' %8s%10s+(%4d) %12s'%(AtomLabels[dist[0]].ljust(8),tunit.ljust(10),dist[2],val.center(12)))+line.rstrip())
def PrintDistAngle(DisAglCtls,DisAglData,out=sys.stdout): '''Print distances and angles :param dict DisAglCtls: contains distance/angle radii usually defined using :func:`GSASIIgrid.DisAglDialog` :param dict DisAglData: contains phase data: Items 'OrigAtoms' and 'TargAtoms' contain the atoms to be used for distance/angle origins and atoms to be used as targets. Item 'SGData' has the space group information (see :ref:`Space Group object<SGData_table>`) :param file out: file object for output. Defaults to sys.stdout. ''' import numpy.ma as ma def MyPrint(s): out.write(s+'\n') # print(s,file=out) # use in Python 3 def ShowBanner(name): MyPrint(80*'*') MyPrint(' Interatomic Distances and Angles for phase '+name) MyPrint((80*'*')+'\n') ShowBanner(DisAglCtls['Name']) SGData = DisAglData['SGData'] SGtext,SGtable = G2spc.SGPrint(SGData) for line in SGtext: MyPrint(line) if len(SGtable): for i,item in enumerate(SGtable[::2]): line = ' %s %s'%(item.ljust(30),SGtable[2*i+1].ljust(30)) MyPrint(line) else: MyPrint(' ( 1) %s'%(SGtable[0])) Cell = DisAglData['Cell'] Amat,Bmat = G2lat.cell2AB(Cell[:6]) covData = {} if 'covData' in DisAglData: covData = DisAglData['covData'] covMatrix = covData['covMatrix'] varyList = covData['varyList'] pfx = str(DisAglData['pId'])+'::' A = G2lat.cell2A(Cell[:6]) cellSig = G2stIO.getCellEsd(pfx,SGData,A,covData) names = [' a = ',' b = ',' c = ',' alpha = ',' beta = ',' gamma = ',' Volume = '] valEsd = [G2mth.ValEsd(Cell[i],cellSig[i],True) for i in range(7)] line = '\n Unit cell:' for name,vals in zip(names,valEsd): line += name+vals MyPrint(line) else: MyPrint('\n Unit cell: a = '+('%.5f'%Cell[0])+' b = '+('%.5f'%Cell[1])+' c = '+('%.5f'%Cell[2])+ ' alpha = '+('%.3f'%Cell[3])+' beta = '+('%.3f'%Cell[4])+' gamma = '+ ('%.3f'%Cell[5])+' volume = '+('%.3f'%Cell[6])) AtomLabels,DistArray,AngArray = RetDistAngle(DisAglCtls,DisAglData) origAtoms = DisAglData['OrigAtoms'] targAtoms = DisAglData['TargAtoms'] for Oatom in origAtoms: i = Oatom[0] Dist = DistArray[i] nDist = len(Dist) angles = np.zeros((nDist,nDist)) angsig = np.zeros((nDist,nDist)) for k,j,tup in AngArray[i]: angles[k][j],angsig[k][j] = angles[j][k],angsig[j][k] = tup line = '' for i,x in enumerate(Oatom[3:6]): line += ('%12.5f'%x).rstrip('0') MyPrint('\n Distances & angles for '+Oatom[1]+' at '+line.rstrip()) MyPrint(80*'*') line = '' for dist in Dist[:-1]: line += '%12s'%(AtomLabels[dist[0]].center(12)) MyPrint(' To cell +(sym. op.) dist. '+line.rstrip()) for i,dist in enumerate(Dist): line = '' for j,angle in enumerate(angles[i][0:i]): sig = angsig[i][j] if angle: if sig: line += '%12s'%(G2mth.ValEsd(angle,sig,True).center(12)) else: val = '%.3f'%(angle) line += '%12s'%(val.center(12)) else: line += 12*' ' if dist[4]: #sig exists! val = G2mth.ValEsd(dist[3],dist[4]) else: val = '%8.4f'%(dist[3]) tunit = '[%2d%2d%2d]'% dist[1] MyPrint((' %8s%10s+(%4d) %12s'%(AtomLabels[dist[0]].ljust(8),tunit.ljust(10),dist[2],val.center(12)))+line.rstrip())
def RetDistAngle(DisAglCtls,DisAglData): '''Compute and return distances and angles :param dict DisAglCtls: contains distance/angle radii usually defined using :func:`GSASIIgrid.DisAglDialog` :param dict DisAglData: contains phase data: Items 'OrigAtoms' and 'TargAtoms' contain the atoms to be used for distance/angle origins and atoms to be used as targets. Item 'SGData' has the space group information (see :ref:`Space Group object<SGData_table>`) :returns: AtomLabels,DistArray,AngArray where: **AtomLabels** is a dict of atom labels, keys are the atom number **DistArray** is a dict keyed by the origin atom number where the value is a list of distance entries. The value for each distance is a list containing: 0) the target atom number (int); 1) the unit cell offsets added to x,y & z (tuple of int values) 2) the symmetry operator number (which may be modified to indicate centering and center of symmetry) 3) an interatomic distance in A (float) 4) an uncertainty on the distance in A or 0.0 (float) **AngArray** is a dict keyed by the origin (central) atom number where the value is a list of angle entries. The value for each angle entry consists of three values: 0) a distance item reference for one neighbor (int) 1) a distance item reference for a second neighbor (int) 2) a angle, uncertainty pair; the s.u. may be zero (tuple of two floats) The AngArray distance reference items refer directly to the index of the items in the DistArray item for the list of distances for the central atom. ''' import numpy.ma as ma SGData = DisAglData['SGData'] Cell = DisAglData['Cell'] Amat,Bmat = G2lat.cell2AB(Cell[:6]) covData = {} if 'covData' in DisAglData: covData = DisAglData['covData'] covMatrix = covData['covMatrix'] varyList = covData['varyList'] pfx = str(DisAglData['pId'])+'::' A = G2lat.cell2A(Cell[:6]) cellSig = G2stIO.getCellEsd(pfx,SGData,A,covData) names = [' a = ',' b = ',' c = ',' alpha = ',' beta = ',' gamma = ',' Volume = '] valEsd = [G2mth.ValEsd(Cell[i],cellSig[i],True) for i in range(7)] Factor = DisAglCtls['Factors'] Radii = dict(zip(DisAglCtls['AtomTypes'],zip(DisAglCtls['BondRadii'],DisAglCtls['AngleRadii']))) indices = (-1,0,1) Units = np.array([[h,k,l] for h in indices for k in indices for l in indices]) origAtoms = DisAglData['OrigAtoms'] targAtoms = DisAglData['TargAtoms'] AtomLabels = {} for Oatom in origAtoms: AtomLabels[Oatom[0]] = Oatom[1] for Oatom in targAtoms: AtomLabels[Oatom[0]] = Oatom[1] DistArray = {} AngArray = {} for Oatom in origAtoms: DistArray[Oatom[0]] = [] AngArray[Oatom[0]] = [] OxyzNames = '' IndBlist = [] Dist = [] Vect = [] VectA = [] angles = [] for Tatom in targAtoms: Xvcov = [] TxyzNames = '' if 'covData' in DisAglData: OxyzNames = [pfx+'dAx:%d'%(Oatom[0]),pfx+'dAy:%d'%(Oatom[0]),pfx+'dAz:%d'%(Oatom[0])] TxyzNames = [pfx+'dAx:%d'%(Tatom[0]),pfx+'dAy:%d'%(Tatom[0]),pfx+'dAz:%d'%(Tatom[0])] Xvcov = G2mth.getVCov(OxyzNames+TxyzNames,varyList,covMatrix) result = G2spc.GenAtom(Tatom[3:6],SGData,False,Move=False) BsumR = (Radii[Oatom[2]][0]+Radii[Tatom[2]][0])*Factor[0] AsumR = (Radii[Oatom[2]][1]+Radii[Tatom[2]][1])*Factor[1] for Txyz,Top,Tunit in result: Dx = (Txyz-np.array(Oatom[3:6]))+Units dx = np.inner(Amat,Dx) dist = ma.masked_less(np.sqrt(np.sum(dx**2,axis=0)),0.5) IndB = ma.nonzero(ma.masked_greater(dist-BsumR,0.)) if np.any(IndB): for indb in IndB: for i in range(len(indb)): if str(dx.T[indb][i]) not in IndBlist: IndBlist.append(str(dx.T[indb][i])) unit = Units[indb][i] tunit = (unit[0]+Tunit[0],unit[1]+Tunit[1],unit[2]+Tunit[2]) pdpx = G2mth.getDistDerv(Oatom[3:6],Tatom[3:6],Amat,unit,Top,SGData) sig = 0.0 if len(Xvcov): sig = np.sqrt(np.inner(pdpx,np.inner(Xvcov,pdpx))) Dist.append([Oatom[0],Tatom[0],tunit,Top,ma.getdata(dist[indb])[i],sig]) if (Dist[-1][-2]-AsumR) <= 0.: Vect.append(dx.T[indb][i]/Dist[-1][-2]) VectA.append([OxyzNames,np.array(Oatom[3:6]),TxyzNames,np.array(Tatom[3:6]),unit,Top]) else: Vect.append([0.,0.,0.]) VectA.append([]) for D in Dist: DistArray[Oatom[0]].append(D[1:]) Vect = np.array(Vect) angles = np.zeros((len(Vect),len(Vect))) angsig = np.zeros((len(Vect),len(Vect))) for i,veca in enumerate(Vect): if np.any(veca): for j,vecb in enumerate(Vect): if np.any(vecb): angles[i][j],angsig[i][j] = G2mth.getAngSig(VectA[i],VectA[j],Amat,SGData,covData) if i <= j: continue AngArray[Oatom[0]].append((i,j, G2mth.getAngSig(VectA[i],VectA[j],Amat,SGData,covData))) return AtomLabels,DistArray,AngArray
def ReadEXPPhase(self, G2frame, filepointer): '''Read a phase from a GSAS .EXP file. ''' shModels = ['cylindrical', 'none', 'shear - 2/m', 'rolling - mmm'] textureData = { 'Order': 0, 'Model': 'cylindrical', 'Sample omega': [False, 0.0], 'Sample chi': [False, 0.0], 'Sample phi': [False, 0.0], 'SH Coeff': [False, {}], 'SHShow': False, 'PFhkl': [0, 0, 1], 'PFxyz': [0, 0, 1], 'PlotType': 'Pole figure' } shNcof = 0 S = 1 NPhas = [] Expr = [{}, {}, {}, {}, {}, {}, {}, {}, {}] # GSAS can have at most 9 phases for line, S in enumerate(filepointer): self.errors = 'Error reading at line ' + str(line + 1) if 'EXPR NPHAS' in S[:12]: Num = S[12:-1].count('0') NPhas = S[12:-1].split() if 'CRS' in S[:3]: N = int(S[3:4]) - 1 Expr[N][S[:12]] = S[12:-1] PNames = [] if not NPhas: raise self.ImportException("No EXPR NPHAS record found") self.errors = 'Error interpreting file' for n, N in enumerate(NPhas): if N != '0': result = n key = 'CRS' + str(n + 1) + ' PNAM' PNames.append(Expr[n][key]) if len(PNames) == 0: raise self.ImportException("No phases found") elif len(PNames) > 1: dlg = wx.SingleChoiceDialog(G2frame, 'Which phase to read?', 'Read phase data', PNames, wx.CHOICEDLG_STYLE) try: if dlg.ShowModal() == wx.ID_OK: result = dlg.GetSelection( ) # I think this breaks is there are skipped phases. Cant this happen? finally: dlg.Destroy() EXPphase = Expr[result] keyList = EXPphase.keys() keyList.sort() SGData = {} if NPhas[result] == '1': Ptype = 'nuclear' elif NPhas[result] in ['2', '3']: Ptype = 'magnetic' elif NPhas[result] == '4': Ptype = 'macromolecular' elif NPhas[result] == '10': Ptype = 'Pawley' else: raise self.ImportException("Phase type not recognized") for key in keyList: if 'PNAM' in key: PhaseName = EXPphase[key].strip() elif 'ABC ' in key: abc = [ float(EXPphase[key][:10]), float(EXPphase[key][10:20]), float(EXPphase[key][20:30]) ] elif 'ANGLES' in key: angles = [ float(EXPphase[key][:10]), float(EXPphase[key][10:20]), float(EXPphase[key][20:30]) ] elif 'SG SYM' in key: SpGrp = EXPphase[key][:15].strip() E, SGData = G2spc.SpcGroup(SpGrp) if E: SGData = G2IO.SGData # P 1 -- unlikely to need this! self.warnings += '\nThe GSAS space group was not interpreted(!) and has been set to "P 1".' self.warnings += "Change this in phase's General tab." elif 'OD ' in key: SHdata = EXPphase[key].split() # may not have all 9 values SHvals = 9 * [0] for i in range(9): try: float(SHdata[i]) SHvals[i] = SHdata[i] except: pass textureData['Order'] = int(SHvals[0]) textureData['Model'] = shModels[int(SHvals[2])] textureData['Sample omega'] = [False, float(SHvals[6])] textureData['Sample chi'] = [False, float(SHvals[7])] textureData['Sample phi'] = [False, float(SHvals[8])] shNcof = int(SHvals[1]) Atoms = [] if Ptype == 'nuclear': for key in keyList: if 'AT' in key: if key[11:] == 'A': S = EXPphase[key] elif key[11:] == 'B': S += EXPphase[key] Atom = [ S[50:58].strip(), S[:10].strip().capitalize(), '', float(S[10:20]), float(S[20:30]), float(S[30:40]), float(S[40:50]), '', int(S[60:62]), S[130:131] ] if Atom[9] == 'I': Atom += [float(S[68:78]), 0., 0., 0., 0., 0., 0.] elif Atom[9] == 'A': Atom += [ 0.0, float(S[68:78]), float(S[78:88]), float(S[88:98]), float(S[98:108]), float(S[108:118]), float(S[118:128]) ] XYZ = Atom[3:6] Atom[7], Atom[8] = G2spc.SytSym(XYZ, SGData) Atom.append(ran.randint(0, sys.maxint)) Atoms.append(Atom) elif Ptype == 'macromolecular': for key in keyList: if 'AT' in key[6:8]: S = EXPphase[key] Atom = [ S[56:60], S[50:54].strip().upper(), S[54:56], S[46:51].strip(), S[:8].strip().capitalize(), '', float(S[16:24]), float(S[24:32]), float(S[32:40]), float(S[8:16]), '1', 1, 'I', float(S[40:46]), 0, 0, 0, 0, 0, 0 ] XYZ = Atom[6:9] Atom[10], Atom[11] = G2spc.SytSym(XYZ, SGData) Atom.append(ran.randint(0, sys.maxint)) Atoms.append(Atom) Volume = G2lat.calc_V(G2lat.cell2A(abc + angles)) if shNcof: shCoef = {} nRec = [i + 1 for i in range((shNcof - 1) / 6 + 1)] for irec in nRec: ODkey = keyList[0][:6] + 'OD' + '%3dA' % (irec) indx = EXPphase[ODkey].split() ODkey = ODkey[:-1] + 'B' vals = EXPphase[ODkey].split() for i, val in enumerate(vals): key = 'C(%s,%s,%s)' % (indx[3 * i], indx[3 * i + 1], indx[3 * i + 2]) shCoef[key] = float(val) textureData['SH Coeff'] = [False, shCoef] if not SGData: raise self.ImportException("No space group found in phase") if not abc: raise self.ImportException("No cell lengths found in phase") if not angles: raise self.ImportException("No cell angles found in phase") if not Atoms: raise self.ImportException("No atoms found in phase") Phase = G2IO.SetNewPhase(Name=PhaseName, SGData=SGData, cell=abc + angles + [ Volume, ]) general = Phase['General'] general['Type'] = Ptype if general['Type'] == 'macromolecular': general['AtomPtrs'] = [6, 4, 10, 12] else: general['AtomPtrs'] = [3, 1, 7, 9] general['SH Texture'] = textureData Phase['Atoms'] = Atoms return Phase
def ReadEXPPhase(self, G2frame,filepointer): '''Read a phase from a GSAS .EXP file. ''' shModels = ['cylindrical','none','shear - 2/m','rolling - mmm'] textureData = {'Order':0,'Model':'cylindrical','Sample omega':[False,0.0], 'Sample chi':[False,0.0],'Sample phi':[False,0.0],'SH Coeff':[False,{}], 'SHShow':False,'PFhkl':[0,0,1],'PFxyz':[0,0,1],'PlotType':'Pole figure'} shNcof = 0 S = 1 NPhas = [] Expr = [{},{},{},{},{},{},{},{},{}] # GSAS can have at most 9 phases for line,S in enumerate(filepointer): self.errors = 'Error reading at line '+str(line+1) if 'EXPR NPHAS' in S[:12]: Num = S[12:-1].count('0') NPhas = S[12:-1].split() if 'CRS' in S[:3]: N = int(S[3:4])-1 Expr[N][S[:12]] = S[12:-1] PNames = [] if not NPhas: raise self.ImportException("No EXPR NPHAS record found") self.errors = 'Error interpreting file' for n,N in enumerate(NPhas): if N != '0': result = n key = 'CRS'+str(n+1)+' PNAM' PNames.append(Expr[n][key]) if len(PNames) == 0: raise self.ImportException("No phases found") elif len(PNames) > 1: dlg = wx.SingleChoiceDialog(G2frame, 'Which phase to read?', 'Read phase data', PNames, wx.CHOICEDLG_STYLE) try: if dlg.ShowModal() == wx.ID_OK: result = dlg.GetSelection() # I think this breaks is there are skipped phases. Cant this happen? finally: dlg.Destroy() EXPphase = Expr[result] keyList = EXPphase.keys() keyList.sort() SGData = {} if NPhas[result] == '1': Ptype = 'nuclear' elif NPhas[result] in ['2','3']: Ptype = 'magnetic' elif NPhas[result] == '4': Ptype = 'macromolecular' elif NPhas[result] == '10': Ptype = 'Pawley' else: raise self.ImportException("Phase type not recognized") for key in keyList: if 'PNAM' in key: PhaseName = EXPphase[key].strip() elif 'ABC ' in key: abc = [float(EXPphase[key][:10]),float(EXPphase[key][10:20]),float(EXPphase[key][20:30])] elif 'ANGLES' in key: angles = [float(EXPphase[key][:10]),float(EXPphase[key][10:20]),float(EXPphase[key][20:30])] elif 'SG SYM' in key: SpGrp = EXPphase[key][:15].strip() E,SGData = G2spc.SpcGroup(SpGrp) if E: SGData = G2IO.SGData # P 1 -- unlikely to need this! self.warnings += '\nThe GSAS space group was not interpreted(!) and has been set to "P 1".' self.warnings += "Change this in phase's General tab." elif 'OD ' in key: SHdata = EXPphase[key].split() # may not have all 9 values SHvals = 9*[0] for i in range(9): try: float(SHdata[i]) SHvals[i] = SHdata[i] except: pass textureData['Order'] = int(SHvals[0]) textureData['Model'] = shModels[int(SHvals[2])] textureData['Sample omega'] = [False,float(SHvals[6])] textureData['Sample chi'] = [False,float(SHvals[7])] textureData['Sample phi'] = [False,float(SHvals[8])] shNcof = int(SHvals[1]) Atoms = [] if Ptype == 'nuclear': for key in keyList: if 'AT' in key: if key[11:] == 'A': S = EXPphase[key] elif key[11:] == 'B': S += EXPphase[key] Atom = [S[50:58].strip(),S[:10].strip().capitalize(),'', float(S[10:20]),float(S[20:30]),float(S[30:40]), float(S[40:50]),'',int(S[60:62]),S[130:131]] if Atom[9] == 'I': Atom += [float(S[68:78]),0.,0.,0.,0.,0.,0.] elif Atom[9] == 'A': Atom += [0.0,float(S[68:78]),float(S[78:88]), float(S[88:98]),float(S[98:108]), float(S[108:118]),float(S[118:128])] XYZ = Atom[3:6] Atom[7],Atom[8] = G2spc.SytSym(XYZ,SGData) Atom.append(ran.randint(0,sys.maxint)) Atoms.append(Atom) elif Ptype == 'macromolecular': for key in keyList: if 'AT' in key[6:8]: S = EXPphase[key] Atom = [S[56:60],S[50:54].strip().upper(),S[54:56], S[46:51].strip(),S[:8].strip().capitalize(),'', float(S[16:24]),float(S[24:32]),float(S[32:40]), float(S[8:16]),'1',1,'I',float(S[40:46]),0,0,0,0,0,0] XYZ = Atom[6:9] Atom[10],Atom[11] = G2spc.SytSym(XYZ,SGData) Atom.append(ran.randint(0,sys.maxint)) Atoms.append(Atom) Volume = G2lat.calc_V(G2lat.cell2A(abc+angles)) if shNcof: shCoef = {} nRec = [i+1 for i in range((shNcof-1)/6+1)] for irec in nRec: ODkey = keyList[0][:6]+'OD'+'%3dA'%(irec) indx = EXPphase[ODkey].split() ODkey = ODkey[:-1]+'B' vals = EXPphase[ODkey].split() for i,val in enumerate(vals): key = 'C(%s,%s,%s)'%(indx[3*i],indx[3*i+1],indx[3*i+2]) shCoef[key] = float(val) textureData['SH Coeff'] = [False,shCoef] if not SGData: raise self.ImportException("No space group found in phase") if not abc: raise self.ImportException("No cell lengths found in phase") if not angles: raise self.ImportException("No cell angles found in phase") if not Atoms: raise self.ImportException("No atoms found in phase") Phase = G2IO.SetNewPhase(Name=PhaseName,SGData=SGData,cell=abc+angles+[Volume,]) general = Phase['General'] general['Type'] = Ptype if general['Type'] =='macromolecular': general['AtomPtrs'] = [6,4,10,12] else: general['AtomPtrs'] = [3,1,7,9] general['SH Texture'] = textureData Phase['Atoms'] = Atoms return Phase
def ReadPDBPhase(self, filename, parent=None): '''Read a phase from a PDB file. ''' EightPiSq = 8. * math.pi**2 self.errors = 'Error opening file' file = open(filename, 'Ur') Phase = {} Title = '' Compnd = '' Atoms = [] A = np.zeros(shape=(3, 3)) S = file.readline() line = 1 SGData = None cell = None while S: self.errors = 'Error reading at line ' + str(line) Atom = [] if 'TITLE' in S[:5]: Title = S[10:72].strip() elif 'COMPND ' in S[:10]: Compnd = S[10:72].strip() elif 'CRYST' in S[:5]: abc = S[7:34].split() angles = S[34:55].split() cell = [ float(abc[0]), float(abc[1]), float(abc[2]), float(angles[0]), float(angles[1]), float(angles[2]) ] Volume = G2lat.calc_V(G2lat.cell2A(cell)) AA, AB = G2lat.cell2AB(cell) SpGrp = S[55:65] E, SGData = G2spc.SpcGroup(SpGrp) # space group processing failed, try to look up name in table if E: SpGrpNorm = G2spc.StandardizeSpcName(SpGrp) if SpGrpNorm: E, SGData = G2spc.SpcGroup(SpGrpNorm) while E: print G2spc.SGErrors(E) dlg = wx.TextEntryDialog( parent, SpGrp[:-1] + ' is invalid \nN.B.: make sure spaces separate axial fields in symbol', 'ERROR in space group symbol', '', style=wx.OK) if dlg.ShowModal() == wx.ID_OK: SpGrp = dlg.GetValue() E, SGData = G2spc.SpcGroup(SpGrp) else: SGData = G2IO.SGData # P 1 self.warnings += '\nThe space group was not interpreted and has been set to "P 1".' self.warnings += "Change this in phase's General tab." dlg.Destroy() SGlines = G2spc.SGPrint(SGData) for l in SGlines: print l elif 'SCALE' in S[:5]: V = S[10:41].split() A[int(S[5]) - 1] = [float(V[0]), float(V[1]), float(V[2])] elif 'ATOM' in S[:4] or 'HETATM' in S[:6]: if not SGData: self.warnings += '\nThe space group was not read before atoms and has been set to "P 1". ' self.warnings += "Change this in phase's General tab." SGData = G2IO.SGData # P 1 XYZ = [float(S[31:39]), float(S[39:47]), float(S[47:55])] XYZ = np.inner(AB, XYZ) XYZ = np.where(abs(XYZ) < 0.00001, 0, XYZ) SytSym, Mult = G2spc.SytSym(XYZ, SGData) Uiso = float(S[61:67]) / EightPiSq Type = S[12:14].lower() if Type[0] in '123456789': Type = Type[1:] Atom = [ S[22:27].strip(), S[17:20].upper(), S[20:22], S[12:17].strip(), Type.strip().capitalize(), '', XYZ[0], XYZ[1], XYZ[2], float(S[55:61]), SytSym, Mult, 'I', Uiso, 0, 0, 0, 0, 0, 0 ] S = file.readline() line += 1 if 'ANISOU' in S[:6]: Uij = S[30:72].split() Uij = [ float(Uij[0]) / 10000., float(Uij[1]) / 10000., float(Uij[2]) / 10000., float(Uij[3]) / 10000., float(Uij[4]) / 10000., float(Uij[5]) / 10000. ] Atom = Atom[:14] + Uij Atom[12] = 'A' Atom.append(ran.randint(0, sys.maxint)) Atoms.append(Atom) S = file.readline() line += 1 file.close() self.errors = 'Error after read complete' if Title: PhaseName = Title elif Compnd: PhaseName = Compnd else: PhaseName = 'None' if not SGData: raise self.ImportException("No space group (CRYST entry) found") if not cell: raise self.ImportException("No cell (CRYST entry) found") Phase = G2IO.SetNewPhase(Name=PhaseName, SGData=SGData, cell=cell + [ Volume, ]) Phase['General']['Type'] = 'macromolecular' Phase['General']['AtomPtrs'] = [6, 4, 10, 12] Phase['Atoms'] = Atoms return Phase
def ReadJANAPhase(self,filename,parent=None): '''Read a phase from a JANA2006 m50 & m40 files. ''' self.errors = 'Error opening file' file = open(filename, 'Ur') #contains only cell & spcgroup Phase = {} Title = os.path.basename(filename) Compnd = '' Type = 'nuclear' Atoms = [] Atypes = [] SuperVec = [[0,0,.1],False,4] S = file.readline() line = 1 SGData = None SuperSg = '' cell = None nqi = 0 while S: self.errors = 'Error reading at line '+str(line) if 'title' in S and S != 'title\n': Title = S.split()[1] elif 'cell' in S[:4]: cell = S[5:].split() cell=[float(cell[0]),float(cell[1]),float(cell[2]), float(cell[3]),float(cell[4]),float(cell[5])] Volume = G2lat.calc_V(G2lat.cell2A(cell)) elif 'spgroup' in S: if 'X' in S: raise self.ImportException("Supersymmetry "+S+" too high; GSAS-II limited to (3+1) supersymmetry") SpGrp = S.split()[1] SuperSg = '' if '(' in SpGrp: #supercell symmetry - split in 2 SuperStr = SpGrp.split('(') SpGrp = SuperStr[0] SuperSg = '('+SuperStr[1] SpGrpNorm = G2spc.StandardizeSpcName(SpGrp) E,SGData = G2spc.SpcGroup(SpGrpNorm) # space group processing failed, try to look up name in table while E: print G2spc.SGErrors(E) dlg = wx.TextEntryDialog(parent, SpGrp[:-1]+' is invalid \nN.B.: make sure spaces separate axial fields in symbol', 'ERROR in space group symbol','',style=wx.OK) if dlg.ShowModal() == wx.ID_OK: SpGrp = dlg.GetValue() E,SGData = G2spc.SpcGroup(SpGrp) else: SGData = G2IO.SGData # P 1 self.warnings += '\nThe space group was not interpreted and has been set to "P 1".' self.warnings += "Change this in phase's General tab." dlg.Destroy() SGlines = G2spc.SGPrint(SGData) elif 'qi' in S[:2]: if nqi: raise self.ImportException("Supersymmetry too high; GSAS-II limited to (3+1) supersymmetry") Type = 'modulated' vec = S.split()[1:] SuperVec = [[float(vec[i]) for i in range(3)],False,4] nqi += 1 elif 'atom' in S[:4]: Atypes.append(S.split()[1]) S = file.readline() line += 1 file.close() #read atoms from m40 file if not SGData: self.warnings += '\nThe space group was not read before atoms and has been set to "P 1". ' self.warnings += "Change this in phase's General tab." SGData = G2IO.SGData # P 1 waveTypes = ['Fourier','Sawtooth','ZigZag',] filename2 = os.path.splitext(filename)[0]+'.m40' file2 = open(filename2,'Ur') S = file2.readline() line = 1 self.errors = 'Error reading at line '+str(line) nAtoms = int(S.split()[0]) for i in range(4): S = file2.readline() for i in range(nAtoms): S1 = file2.readline() S1N = S1.split()[-3:] # no. occ, no. pos waves, no. ADP waves S1N = [int(i) for i in S1N] S1T = list(S1[60:63]) waveType = waveTypes[int(S1T[1])] crenelType = '' Spos = [] Sadp = [] Sfrac = [] Smag = [] XYZ = [float(S1[27:36]),float(S1[36:45]),float(S1[45:54])] SytSym,Mult = G2spc.SytSym(XYZ,SGData) aType = Atypes[int(S1[9:11])-1] Name = S1[:8].strip() if S1[11:15].strip() == '1': S2 = file2.readline() Uiso = float(S2[:9]) Uij = [0,0,0,0,0,0] IA = 'I' elif S1[11:15].strip() == '2': S2 = file2.readline() IA = 'A' Uiso = 0. Uij = [float(S2[:9]),float(S2[9:18]),float(S2[18:27]), float(S2[27:36]),float(S2[36:45]),float(S2[45:54])] for i in range(S1N[0]): if not i: FS = file2.readline() Sfrac.append(FS[:9]) #'O' or 'delta' = 'length' for crenel if int(S1T[0]): #"", "Legendre" or "Xharm" in 18:27 for "crenel"! waveType = 'Crenel/Fourier' #all waves 'Fourier' no other choice crenelType = FS[18:27] Sfrac.append(file2.readline()[:18]) #if not crenel = Osin & Ocos # else Osin & Ocos except last one is X40 = 'Center' for i in range(S1N[1]): Spos.append(file2.readline()[:54]) for i in range(S1N[2]): Sadp.append(file2.readline()[:54]+file2.readline()) if sum(S1N): #if any waves: skip mystery line? file2.readline() for i,it in enumerate(Sfrac): print i,it if not i: if 'Crenel' in waveType: vals = [float(it),float(Sfrac[-1][:9])] else: vals = [float(it),] else: vals = [float(it[:9]),float(it[9:18])] if 'Crenel' in waveType and i == len(Sfrac)-1: del Sfrac[-1] break Sfrac[i] = [vals,False] print Sfrac[i] for i,it in enumerate(Spos): if waveType in ['ZigZag','Sawtooth'] and not i: vals = [float(it[:9]),float(it[9:18]),float(it[18:27]),float(it[27:36])] else: vals = [float(it[:9]),float(it[9:18]),float(it[18:27]),float(it[27:36]),float(it[36:45]),float(it[45:54])] Spos[i] = [vals,False] for i,it in enumerate(Sadp): vals = [float(it[:9]),float(it[9:18]),float(it[18:27]),float(it[27:36]),float(it[36:45]),float(it[45:54]), float(it[54:63]),float(it[63:72]),float(it[72:81]),float(it[81:90]),float(it[90:99]),float(it[99:108])] Sadp[i] = [vals,False] Atom = [Name,aType,'',XYZ[0],XYZ[1],XYZ[2],1.0,SytSym,Mult,IA,Uiso] Atom += Uij Atom.append(ran.randint(0,sys.maxint)) Atom.append([]) Atom.append([]) Atom.append({'SS1':{'waveType':waveType,'crenelType':crenelType,'Sfrac':Sfrac,'Spos':Spos,'Sadp':Sadp,'Smag':Smag}}) #SS2 is for (3+2), etc. Atoms.append(Atom) file2.close() self.errors = 'Error after read complete' if not SGData: raise self.ImportException("No space group (spcgroup entry) found") if not cell: raise self.ImportException("No cell found") Phase = G2IO.SetNewPhase(Name=Title,SGData=SGData,cell=cell+[Volume,]) Phase['General']['Type'] = Type Phase['General']['Super'] = nqi Phase['General']['SuperVec'] = SuperVec Phase['General']['SuperSg'] = SuperSg if SuperSg: Phase['General']['SSGData'] = G2spc.SSpcGroup(SGData,SuperSg)[1] Phase['General']['AtomPtrs'] = [3,1,7,9] Phase['Atoms'] = Atoms return Phase
def errFit(values,ibrav,d,H,Pwr): A = Values2A(ibrav,values) Qo = 1./d**2 Qc = G2lat.calc_rDsq(H,A) return (Qo-Qc)*d**Pwr
def ReadPDBPhase(self,filename,parent=None): '''Read a phase from a PDB file. ''' EightPiSq = 8.*math.pi**2 self.errors = 'Error opening file' file = open(filename, 'Ur') Phase = {} Title = '' Compnd = '' Atoms = [] A = np.zeros(shape=(3,3)) S = file.readline() line = 1 SGData = None cell = None while S: self.errors = 'Error reading at line '+str(line) Atom = [] if 'TITLE' in S[:5]: Title = S[10:72].strip() elif 'COMPND ' in S[:10]: Compnd = S[10:72].strip() elif 'CRYST' in S[:5]: abc = S[7:34].split() angles = S[34:55].split() cell=[float(abc[0]),float(abc[1]),float(abc[2]), float(angles[0]),float(angles[1]),float(angles[2])] Volume = G2lat.calc_V(G2lat.cell2A(cell)) AA,AB = G2lat.cell2AB(cell) SpGrp = S[55:65] E,SGData = G2spc.SpcGroup(SpGrp) # space group processing failed, try to look up name in table if E: SpGrpNorm = G2spc.StandardizeSpcName(SpGrp) if SpGrpNorm: E,SGData = G2spc.SpcGroup(SpGrpNorm) while E: print G2spc.SGErrors(E) dlg = wx.TextEntryDialog(parent, SpGrp[:-1]+' is invalid \nN.B.: make sure spaces separate axial fields in symbol', 'ERROR in space group symbol','',style=wx.OK) if dlg.ShowModal() == wx.ID_OK: SpGrp = dlg.GetValue() E,SGData = G2spc.SpcGroup(SpGrp) else: SGData = G2IO.SGData # P 1 self.warnings += '\nThe space group was not interpreted and has been set to "P 1".' self.warnings += "Change this in phase's General tab." dlg.Destroy() SGlines = G2spc.SGPrint(SGData) for l in SGlines: print l elif 'SCALE' in S[:5]: V = S[10:41].split() A[int(S[5])-1] = [float(V[0]),float(V[1]),float(V[2])] elif 'ATOM' in S[:4] or 'HETATM' in S[:6]: if not SGData: self.warnings += '\nThe space group was not read before atoms and has been set to "P 1". ' self.warnings += "Change this in phase's General tab." SGData = G2IO.SGData # P 1 XYZ = [float(S[31:39]),float(S[39:47]),float(S[47:55])] XYZ = np.inner(AB,XYZ) XYZ = np.where(abs(XYZ)<0.00001,0,XYZ) SytSym,Mult = G2spc.SytSym(XYZ,SGData) Uiso = float(S[61:67])/EightPiSq Type = S[12:14].lower() if Type[0] in '123456789': Type = Type[1:] Atom = [S[22:27].strip(),S[17:20].upper(),S[20:22], S[12:17].strip(),Type.strip().capitalize(),'',XYZ[0],XYZ[1],XYZ[2], float(S[55:61]),SytSym,Mult,'I',Uiso,0,0,0,0,0,0] S = file.readline() line += 1 if 'ANISOU' in S[:6]: Uij = S[30:72].split() Uij = [float(Uij[0])/10000.,float(Uij[1])/10000.,float(Uij[2])/10000., float(Uij[3])/10000.,float(Uij[4])/10000.,float(Uij[5])/10000.] Atom = Atom[:14]+Uij Atom[12] = 'A' Atom.append(ran.randint(0,sys.maxint)) Atoms.append(Atom) S = file.readline() line += 1 file.close() self.errors = 'Error after read complete' if Title: PhaseName = Title elif Compnd: PhaseName = Compnd else: PhaseName = 'None' if not SGData: raise self.ImportException("No space group (CRYST entry) found") if not cell: raise self.ImportException("No cell (CRYST entry) found") Phase = G2IO.SetNewPhase(Name=PhaseName,SGData=SGData,cell=cell+[Volume,]) Phase['General']['Type'] = 'macromolecular' Phase['General']['AtomPtrs'] = [6,4,10,12] Phase['Atoms'] = Atoms return Phase
def ImageCalibrate(self, data): 'Needs a doc string' import copy import ImageCalibrants as calFile print 'Image calibration:' time0 = time.time() ring = data['ring'] pixelSize = data['pixelSize'] scalex = 1000. / pixelSize[0] scaley = 1000. / pixelSize[1] pixLimit = data['pixLimit'] cutoff = data['cutoff'] varyDict = data['varyList'] if varyDict['dist'] and varyDict['wave']: print 'ERROR - you can not simultaneously calibrate distance and wavelength' return False if len(ring) < 5: print 'ERROR - not enough inner ring points for ellipse' return False #fit start points on inner ring data['ellipses'] = [] data['rings'] = [] outE = FitEllipse(ring) fmt = '%s X: %.3f, Y: %.3f, phi: %.3f, R1: %.3f, R2: %.3f' fmt2 = '%s X: %.3f, Y: %.3f, phi: %.3f, R1: %.3f, R2: %.3f, chi**2: %.3f, Np: %d' if outE: print fmt % ('start ellipse: ', outE[0][0], outE[0][1], outE[1], outE[2][0], outE[2][1]) ellipse = outE else: return False #setup 360 points on that ring for "good" fit data['ellipses'].append(ellipse[:] + ('g', )) Ring = makeRing(1.0, ellipse, pixLimit, cutoff, scalex, scaley, self.ImageZ) if Ring: ellipse = FitEllipse(Ring) Ring = makeRing(1.0, ellipse, pixLimit, cutoff, scalex, scaley, self.ImageZ) #do again ellipse = FitEllipse(Ring) else: print '1st ring not sufficiently complete to proceed' return False if debug: print fmt2 % ('inner ring: ', ellipse[0][0], ellipse[0][1], ellipse[1], ellipse[2][0], ellipse[2][1], 0., len(Ring) ) #cent,phi,radii data['ellipses'].append(ellipse[:] + ('r', )) data['rings'].append(np.array(Ring)) G2plt.PlotImage(self, newImage=True) #setup for calibration data['rings'] = [] if not data['calibrant']: print 'no calibration material selected' return True skip = data['calibskip'] dmin = data['calibdmin'] #generate reflection set Bravais, SGs, Cells = calFile.Calibrants[data['calibrant']][:3] HKL = [] for bravais, sg, cell in zip(Bravais, SGs, Cells): A = G2lat.cell2A(cell) if sg: SGData = G2spc.SpcGroup(sg)[1] hkl = G2pwd.getHKLpeak(dmin, SGData, A) HKL += hkl else: hkl = G2lat.GenHBravais(dmin, bravais, A) HKL += hkl HKL = G2lat.sortHKLd(HKL, True, False)[skip:] #set up 1st ring elcent, phi, radii = ellipse #from fit of 1st ring dsp = HKL[0][3] print '1st ring: try %.4f' % (dsp) if varyDict['dist']: wave = data['wavelength'] tth = 2.0 * asind(wave / (2. * dsp)) else: #varyDict['wave']! dist = data['distance'] tth = npatan2d(radii[0], dist) data['wavelength'] = wave = 2.0 * dsp * sind(tth / 2.0) Ring0 = makeRing(dsp, ellipse, 3, cutoff, scalex, scaley, self.ImageZ) ttth = nptand(tth) stth = npsind(tth) ctth = npcosd(tth) #1st estimate of tilt; assume ellipse - don't know sign though if varyDict['tilt']: tilt = npasind(np.sqrt(max(0., 1. - (radii[0] / radii[1])**2)) * ctth) if not tilt: print 'WARNING - selected ring was fitted as a circle' print ' - if detector was tilted we suggest you skip this ring - WARNING' else: tilt = data['tilt'] #1st estimate of dist: sample to detector normal to plane if varyDict['dist']: data['distance'] = dist = radii[0]**2 / (ttth * radii[1]) else: dist = data['distance'] if varyDict['tilt']: #ellipse to cone axis (x-ray beam); 2 choices depending on sign of tilt zdisp = radii[1] * ttth * tand(tilt) zdism = radii[1] * ttth * tand(-tilt) #cone axis position; 2 choices. Which is right? #NB: zdisp is || to major axis & phi is rotation of minor axis #thus shift from beam to ellipse center is [Z*sin(phi),-Z*cos(phi)] centp = [elcent[0] + zdisp * sind(phi), elcent[1] - zdisp * cosd(phi)] centm = [elcent[0] + zdism * sind(phi), elcent[1] - zdism * cosd(phi)] #check get same ellipse parms either way #now do next ring; estimate either way & do a FitDetector each way; best fit is correct one fail = True i2 = 1 while fail: dsp = HKL[i2][3] print '2nd ring: try %.4f' % (dsp) tth = 2.0 * asind(wave / (2. * dsp)) ellipsep = GetEllipse2(tth, 0., dist, centp, tilt, phi) print fmt % ('plus ellipse :', ellipsep[0][0], ellipsep[0][1], ellipsep[1], ellipsep[2][0], ellipsep[2][1]) Ringp = makeRing(dsp, ellipsep, 3, cutoff, scalex, scaley, self.ImageZ) parmDict = { 'dist': dist, 'det-X': centp[0], 'det-Y': centp[1], 'tilt': tilt, 'phi': phi, 'wave': wave, 'dep': 0.0 } varyList = [item for item in varyDict if varyDict[item]] if len(Ringp) > 10: chip = FitDetector(np.array(Ring0 + Ringp), varyList, parmDict, True) tiltp = parmDict['tilt'] phip = parmDict['phi'] centp = [parmDict['det-X'], parmDict['det-Y']] fail = False else: chip = 1e6 ellipsem = GetEllipse2(tth, 0., dist, centm, -tilt, phi) print fmt % ('minus ellipse:', ellipsem[0][0], ellipsem[0][1], ellipsem[1], ellipsem[2][0], ellipsem[2][1]) Ringm = makeRing(dsp, ellipsem, 3, cutoff, scalex, scaley, self.ImageZ) if len(Ringm) > 10: parmDict['tilt'] *= -1 chim = FitDetector(np.array(Ring0 + Ringm), varyList, parmDict, True) tiltm = parmDict['tilt'] phim = parmDict['phi'] centm = [parmDict['det-X'], parmDict['det-Y']] fail = False else: chim = 1e6 if fail: i2 += 1 if chip < chim: data['tilt'] = tiltp data['center'] = centp data['rotation'] = phip else: data['tilt'] = tiltm data['center'] = centm data['rotation'] = phim data['ellipses'].append(ellipsep[:] + ('b', )) data['rings'].append(np.array(Ringp)) data['ellipses'].append(ellipsem[:] + ('r', )) data['rings'].append(np.array(Ringm)) G2plt.PlotImage(self, newImage=True) parmDict = { 'dist': data['distance'], 'det-X': data['center'][0], 'det-Y': data['center'][1], 'tilt': data['tilt'], 'phi': data['rotation'], 'wave': data['wavelength'], 'dep': data['DetDepth'] } varyList = [item for item in varyDict if varyDict[item]] data['rings'] = [] data['ellipses'] = [] for i, H in enumerate(HKL): dsp = H[3] tth = 2.0 * asind(wave / (2. * dsp)) if tth + abs(data['tilt']) > 90.: print 'next line is a hyperbola - search stopped' break if debug: print 'HKLD:', H[:4], '2-theta: %.4f' % (tth) elcent, phi, radii = ellipse = GetEllipse(dsp, data) data['ellipses'].append(copy.deepcopy(ellipse + ('g', ))) if debug: print fmt % ('predicted ellipse:', elcent[0], elcent[1], phi, radii[0], radii[1]) Ring = makeRing(dsp, ellipse, pixLimit, cutoff, scalex, scaley, self.ImageZ) if Ring: data['rings'].append(np.array(Ring)) rings = np.concatenate((data['rings']), axis=0) if i: chisq = FitDetector(rings, varyList, parmDict, False) data['distance'] = parmDict['dist'] data['center'] = [parmDict['det-X'], parmDict['det-Y']] data['rotation'] = parmDict['phi'] data['tilt'] = parmDict['tilt'] data['DetDepth'] = parmDict['dep'] data['chisq'] = chisq elcent, phi, radii = ellipse = GetEllipse(dsp, data) if debug: print fmt2 % ('fitted ellipse: ', elcent[0], elcent[1], phi, radii[0], radii[1], chisq, len(rings)) data['ellipses'].append(copy.deepcopy(ellipse + ('r', ))) # G2plt.PlotImage(self,newImage=True) else: if debug: print 'insufficient number of points in this ellipse to fit' # break G2plt.PlotImage(self, newImage=True) fullSize = len(self.ImageZ) / scalex if 2 * radii[1] < .9 * fullSize: print 'Are all usable rings (>25% visible) used? Try reducing Min ring I/Ib' N = len(data['ellipses']) if N > 2: FitDetector(rings, varyList, parmDict) data['wavelength'] = parmDict['wave'] data['distance'] = parmDict['dist'] data['center'] = [parmDict['det-X'], parmDict['det-Y']] data['rotation'] = parmDict['phi'] data['tilt'] = parmDict['tilt'] data['DetDepth'] = parmDict['dep'] for H in HKL[:N]: ellipse = GetEllipse(H[3], data) data['ellipses'].append(copy.deepcopy(ellipse + ('b', ))) print 'calibration time = ', time.time() - time0 G2plt.PlotImage(self, newImage=True) return True
def ShowHistogramInfo(): try: histData = UseList[G2frame.hist] except KeyError: G2frame.ErrorDialog('Missing data error', G2frame.hist+' not in GSAS-II data tree') return if 'Use' not in UseList[G2frame.hist]: #patch UseList[G2frame.hist]['Use'] = True if 'Babinet' not in UseList[G2frame.hist]: UseList[G2frame.hist]['Babinet'] = {'BabA':[0.0,False],'BabU':[0.0,False]} bottomSizer = wx.BoxSizer(wx.VERTICAL) showSizer = wx.BoxSizer(wx.HORIZONTAL) useData = wx.CheckBox(DData,wx.ID_ANY,label='Use Histogram: '+G2frame.hist+' ?') showSizer.Add(useData,0,WACV|wx.TOP|wx.BOTTOM,5) useData.Bind(wx.EVT_CHECKBOX, OnUseData) useData.SetValue(UseList[G2frame.hist]['Use']) bottomSizer.Add(showSizer,0,WACV|wx.TOP|wx.BOTTOM|wx.LEFT,5) bottomSizer.Add(ScaleSizer(),0,WACV|wx.BOTTOM,5) if G2frame.hist[:4] == 'PWDR': if UseList[G2frame.hist]['Size'][0] == 'isotropic': isoSizer = wx.BoxSizer(wx.HORIZONTAL) isoSizer.Add(TopSizer(' Domain size model: ',['isotropic','uniaxial','ellipsoidal'], 'Size',OnSizeType),0,WACV) isoSizer.Add(LGmixSizer('Size',OnLGmixVal,OnLGmixRef)) isoSizer.Add(ResetSizer('isotropic',OnResetSize),0,WACV) bottomSizer.Add(isoSizer) bottomSizer.Add(IsoSizer(u'size(\xb5m): ','Size','%.5f', OnSizeVal,OnSizeRef),0,WACV|wx.BOTTOM,5) elif UseList[G2frame.hist]['Size'][0] == 'uniaxial': uniSizer = wx.BoxSizer(wx.HORIZONTAL) uniSizer.Add(TopSizer(' Domain size model: ',['isotropic','uniaxial','ellipsoidal'], 'Size',OnSizeType),0,WACV) uniSizer.Add(LGmixSizer('Size',OnLGmixVal,OnLGmixRef)) uniSizer.Add(ResetSizer('uniaxial',OnResetSize),0,WACV) bottomSizer.Add(UniSizer('Size',OnSizeAxis),0,WACV) bottomSizer.Add(uniSizer) bottomSizer.Add(UniDataSizer(u'size(\xb5m): ','Size','%.5f',OnSizeVal,OnSizeRef) ,0,WACV|wx.BOTTOM,5) elif UseList[G2frame.hist]['Size'][0] == 'ellipsoidal': ellSizer = wx.BoxSizer(wx.HORIZONTAL) ellSizer.Add(TopSizer(' Domain size model: ',['isotropic','uniaxial','ellipsoidal'], 'Size',OnSizeType),0,WACV) ellSizer.Add(LGmixSizer('Size',OnLGmixVal,OnLGmixRef)) ellSizer.Add(ResetSizer('ellipsoidal',OnResetSize),0,WACV) bottomSizer.Add(ellSizer) bottomSizer.Add(EllSizeDataSizer(),0,WACV|wx.BOTTOM,5) if UseList[G2frame.hist]['Mustrain'][0] == 'isotropic': isoSizer = wx.BoxSizer(wx.HORIZONTAL) isoSizer.Add(TopSizer(' Mustrain model: ',['isotropic','uniaxial','generalized',], 'Mustrain',OnStrainType),0,WACV) isoSizer.Add(LGmixSizer('Mustrain',OnLGmixVal,OnLGmixRef)) isoSizer.Add(ResetSizer('isotropic',OnResetStrain),0,WACV) bottomSizer.Add(isoSizer) bottomSizer.Add(IsoSizer(' microstrain: ','Mustrain','%.1f', OnStrainVal,OnStrainRef),0,WACV|wx.BOTTOM,5) elif UseList[G2frame.hist]['Mustrain'][0] == 'uniaxial': uniSizer = wx.BoxSizer(wx.HORIZONTAL) uniSizer.Add(TopSizer(' Mustrain model: ',['isotropic','uniaxial','generalized',], 'Mustrain',OnStrainType),0,WACV) uniSizer.Add(LGmixSizer('Mustrain',OnLGmixVal,OnLGmixRef)) uniSizer.Add(ResetSizer('uniaxial',OnResetStrain),0,WACV) bottomSizer.Add(uniSizer) bottomSizer.Add(UniSizer('Mustrain',OnStrainAxis),0,WACV) bottomSizer.Add(UniDataSizer('mustrain: ','Mustrain','%.1f',OnStrainVal,OnStrainRef) ,0,WACV|wx.BOTTOM,5) elif UseList[G2frame.hist]['Mustrain'][0] == 'generalized': genSizer = wx.BoxSizer(wx.HORIZONTAL) genSizer.Add(TopSizer(' Mustrain model: ',['isotropic','uniaxial','generalized',], 'Mustrain',OnStrainType),0,WACV) genSizer.Add(LGmixSizer('Mustrain',OnLGmixVal,OnLGmixRef)) genSizer.Add(ResetSizer('generalized',OnResetStrain),0,WACV) bottomSizer.Add(genSizer) bottomSizer.Add(GenStrainDataSizer(),0,WACV|wx.BOTTOM,5) bottomSizer.Add(wx.StaticText(DData,wx.ID_ANY,' Hydrostatic/elastic strain:')) bottomSizer.Add(HstrainSizer()) poSizer = wx.BoxSizer(wx.VERTICAL) POData = UseList[G2frame.hist]['Pref.Ori.'] # patch - add penalty items if len(POData) < 7: POData.append(['',]) POData.append(0.1) if not POData[6]: POData[6] = ['',] # end patch poSizer.Add(PoTopSizer(POData)) if POData[0] == 'MD': poSizer.Add(MDDataSizer(POData)) else: #'SH' if POData[4]: #SH order > 0 textJ = G2lat.textureIndex(POData[5]) poSizer.Add(wx.StaticText(DData,wx.ID_ANY,' Spherical harmonic coefficients: '+'Texture index: %.3f'%(textJ)) ,0,WACV|wx.TOP|wx.BOTTOM,5) poSizer.Add(SHDataSizer(POData),0,WACV|wx.TOP|wx.BOTTOM,5) poSizer.Add(SHPenalty(POData),0,WACV|wx.TOP|wx.BOTTOM,5) bottomSizer.Add(poSizer,0,WACV|wx.TOP|wx.BOTTOM,5) bottomSizer.Add(ExtSizer(),0,WACV|wx.TOP|wx.BOTTOM,5) bottomSizer.Add(BabSizer(),0,WACV|wx.BOTTOM,5) elif G2frame.hist[:4] == 'HKLF': bottomSizer.Add(SCExtSizer(),0,WACV|wx.TOP|wx.BOTTOM,5) bottomSizer.Add(BabSizer(),0,WACV|wx.BOTTOM,5) return bottomSizer