Changeset 949
 Timestamp:
 Jun 12, 2013 3:08:54 PM (8 years ago)
 Location:
 trunk
 Files:

 3 edited
Legend:
 Unmodified
 Added
 Removed

trunk/GSASIIlattice.py
r939 r949 93 93 94 94 :param A: reciprocal metric tensor elements as [G11,G22,G33,2*G12,2*G13,2*G23] 95 :param bool inverse: if True return bot G and g; else just G95 :param bool inverse: if True return both G and g; else just G 96 96 :return: reciprocal (G) & real (g) metric tensors (list of two numpy 3x3 arrays) 97 97 … … 271 271 272 272 def CosSinAngle(U,V,G): 273 """ calculate sin & cos of angle betwee U & V in generalized coordinates273 """ calculate sin & cos of angle between U & V in generalized coordinates 274 274 defined by metric tensor G 275 275 
trunk/GSASIImath.py
r948 r949 1465 1465 return Ind 1466 1466 1467 ################################################################################ 1468 ##### single peak fitting profile fxn stuff 1469 ################################################################################ 1470 1467 1471 def getCWsig(ins,pos): 1468 1472 tp = tand(pos/2.0) … … 1628 1632 1629 1633 def update_guess(self, x0): 1630 pass1634 return np.squeeze(np.random.uniform(0.,1.,size=self.dims))*(self.upperself.lower)+self.lower 1631 1635 1632 1636 def update_temp(self, x0): … … 1644 1648 self.c = self.m * exp(self.n * self.quench) 1645 1649 1646 def update_guess(self, x0):1647 x0 = asarray(x0)1648 u = squeeze(random.uniform(0.0, 1.0, size=self.dims))1649 T = self.T1650 y = sign(u0.5)*T*((1+1.0/T)**abs(2*u1)1.0)1651 xc = y*(self.upper  self.lower)1652 xnew = x0 + xc1653 return xnew1650 # def update_guess(self, x0): 1651 # x0 = asarray(x0) 1652 # u = squeeze(random.uniform(0.0, 1.0, size=self.dims)) 1653 # T = self.T 1654 # y = sign(u0.5)*T*((1+1.0/T)**abs(2*u1)1.0) 1655 # xc = y*(self.upper  self.lower) 1656 # xnew = x0 + xc 1657 # return xnew 1654 1658 1655 1659 def update_temp(self): … … 1659 1663 1660 1664 class cauchy_sa(base_schedule): 1661 def update_guess(self, x0):1662 x0 = asarray(x0)1663 numbers = squeeze(random.uniform(pi/2, pi/2, size=self.dims))1664 xc = self.learn_rate * self.T * tan(numbers)1665 xnew = x0 + xc1666 return xnew1665 # def update_guess(self, x0): 1666 # x0 = asarray(x0) 1667 # numbers = squeeze(random.uniform(pi/2, pi/2, size=self.dims)) 1668 # xc = self.learn_rate * self.T * tan(numbers) 1669 # xnew = x0 + xc 1670 # return xnew 1667 1671 1668 1672 def update_temp(self): … … 1672 1676 1673 1677 class boltzmann_sa(base_schedule): 1674 def update_guess(self, x0):1675 std = minimum(sqrt(self.T)*ones(self.dims), (self.upperself.lower)/3.0/self.learn_rate)1676 x0 = asarray(x0)1677 xc = squeeze(random.normal(0, 1.0, size=self.dims))1678 1679 xnew = x0 + xc*std*self.learn_rate1680 return xnew1678 # def update_guess(self, x0): 1679 # std = minimum(sqrt(self.T)*ones(self.dims), (self.upperself.lower)/3.0/self.learn_rate) 1680 # x0 = asarray(x0) 1681 # xc = squeeze(random.normal(0, 1.0, size=self.dims)) 1682 # 1683 # xnew = x0 + xc*std*self.learn_rate 1684 # return xnew 1681 1685 1682 1686 def update_temp(self): … … 1690 1694 self.__dict__.update(options) 1691 1695 1692 def update_guess(self,x0): 1693 x0 = np.asarray(x0) 1694 u = np.squeeze(np.random.uniform(0.,1.,size=self.dims)) 1695 xnew = x0+u 1696 return xnew 1696 # def update_guess(self,x0): 1697 # return np.squeeze(np.random.uniform(0.,1.,size=self.dims))*(self.upperself.lower)+self.lower 1697 1698 1698 1699 def update_temp(self): 1699 1700 self.k += 1 1700 self.T = self.T0*self.slope** k1701 self.T = self.T0*self.slope**self.k 1701 1702 1702 1703 class Tremayne_sa(base_schedule): #needs fixing for two steps … … 1705 1706 self.__dict__.update(options) 1706 1707 1707 def update_guess(self,x0):1708 x0 = np.asarray(x0)1709 u = np.squeeze(np.random.uniform(0.,1.,size=self.dims))1710 xnew = x0+u1711 return xnew1708 # def update_guess(self,x0): 1709 # x0 = np.asarray(x0) 1710 # u = np.squeeze(np.random.uniform(0.,1.,size=self.dims)) 1711 # xnew = x0+u 1712 # return xnew 1712 1713 1713 1714 def update_temp(self): … … 1730 1731 T0=None, Tf=1e12, maxeval=None, maxaccept=None, maxiter=400, 1731 1732 boltzmann=1.0, learn_rate=0.5, feps=1e6, quench=1.0, m=1.0, n=1.0, 1732 lower=100, upper=100, dwell=50, slope=0.9 ):1733 lower=100, upper=100, dwell=50, slope=0.9,dlg=None): 1733 1734 """Minimize a function using simulated annealing. 1734 1735 … … 1809 1810 generate new points and vary their temperature. Temperatures are 1810 1811 only updated with iterations in the outer loop. The inner loop is 1811 over loop overxrange(dwell), and new points are generated for1812 over xrange(dwell), and new points are generated for 1812 1813 every iteration in the inner loop. (Though whether the proposed 1813 1814 new points are accepted is probabilistic.) … … 1854 1855 schedule.init(dims=shape(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, 1855 1856 learn_rate=learn_rate, lower=lower, upper=upper, 1856 m=m, n=n, quench=quench, dwell=dwell )1857 m=m, n=n, quench=quench, dwell=dwell, slope=slope) 1857 1858 1858 1859 current_state, last_state, best_state = _state(), _state(), _state() … … 1886 1887 best_state.x = last_state.x.copy() 1887 1888 best_state.cost = last_state.cost 1889 if dlg: 1890 GoOn = dlg.Update(best_state.cost*100, 1891 newmsg='%s%8.3f\n%s%8.3f%s'%('Temperature =',schedule.T,'MC/SA Residual =',best_state.cost*100,'%'))[0] 1892 if not GoOn: 1893 break 1888 1894 schedule.update_temp() 1889 1895 iters += 1 … … 1939 1945 lower.append(limits[0]) 1940 1946 upper.append(limits[1]) 1941 1947 1942 1948 def getAtomparms(item,pfx,aTypes,SGData,parmDict,varyList): 1943 1949 parmDict[pfx+'Atype'] = item['atType'] … … 1956 1962 parmDict[pfx+'Amul'] = len(G2spc.GenAtom(XYZ,SGData)) 1957 1963 1958 def getRBparms(item,mfx,aTypes,RBdata, atNo,parmDict,varyList):1964 def getRBparms(item,mfx,aTypes,RBdata,SGData,atNo,parmDict,varyList): 1959 1965 parmDict[mfx+'MolCent'] = item['MolCent'] 1960 1966 parmDict[mfx+'RBId'] = item['RBId'] … … 1995 2001 atNo += len(atypes) 1996 2002 return atNo 1997 1998 def GetAtomTMX(pfx,RBdata,parmDict): 2003 2004 def GetAtomM(Xdata,SGData): 2005 Mdata = [] 2006 for xyz in Xdata.T: 2007 Mdata.append(len(G2spc.GenAtom(xyz,SGData))) 2008 return np.array(Mdata) 2009 2010 def GetAtomTX(RBdata,parmDict): 1999 2011 'Needs a doc string' 2000 atNo = parmDIct['atNo'] 2012 Bmat = parmDict['Bmat'] 2013 atNo = parmDict['atNo'] 2001 2014 nfixAt = parmDict['nfixAt'] 2002 2015 Tdata = atNo*[' ',] 2003 Mdata = np.zeros(atNo)2004 Fdata = np.zeros(atNo)2005 2016 Xdata = np.zeros((3,atNo)) 2006 keys = {'Atype:':Tdata,'Amul:':Mdata, 2007 'Ax:':Xdata[0],'Ay:':Xdata[1],'Az:':Xdata[2]} 2008 nObjs = parmDict['nObjs'] 2017 keys = {':Atype':Tdata,':Ax':Xdata[0],':Ay':Xdata[1],':Az':Xdata[2]} 2009 2018 for iatm in range(nfixAt): 2010 2019 for key in keys: 2011 parm = pfx+key+str(iatm)2020 parm = ':'+str(iatm)+key 2012 2021 if parm in parmDict: 2013 2022 keys[key][iatm] = parmDict[parm] 2014 return Tdata,Mdata,Xdata 2015 2016 # def mcsaSfCalc(refList,RBdata,G,SGData,parmDict): 2023 iatm = nfixAt 2024 for iObj in range(parmDict['nObj']): 2025 pfx = str(iObj)+':' 2026 if parmDict[pfx+'Type'] in ['Vector','Residue']: 2027 if parmDict[pfx+'Type'] == 'Vector': 2028 RBId = parmDict[pfx+':RBId'] 2029 RBRes = RBdata['Vector'][RBId] 2030 aTypes = RBRes['rbTypes'] 2031 vecs = RBRes['rbVect'] 2032 mags = RBRes['VectMag'] 2033 Cart = np.zeros_like(vecs[0]) 2034 for vec,mag in zip(vecs,mags): 2035 Cart += vec*mag 2036 elif parmDict[pfx+'Type'] == 'Residue': 2037 RBId = parmDict[pfx+':RBId'] 2038 RBRes = RBdata['Residue'][RBId] 2039 aTypes = RBRes['rbTypes'] 2040 Cart = np.array(RBRes['rbXYZ']) 2041 for itor,seq in enumerate(RBRes['rbSeq']): 2042 tName = pfx+':Tor'+str(itor) 2043 QuatA = AVdeg2Q(parmDict[tName],Cart[seq[0]]Cart[seq[1]]) 2044 for ride in seq[3]: 2045 Cart[ride] = prodQVQ(QuatA,Cart[ride]Cart[seq[1]])+Cart[seq[1]] 2046 if parmDict[pfx+':MolCent'][1]: 2047 Cart = parmDict[pfx+':MolCent'][0] 2048 Qori = np.array([parmDict[pfx+':Qa'],parmDict[pfx+':Qi'],parmDict[pfx+':Qj'],parmDict[pfx+':Qk']]) 2049 Pos = np.array([parmDict[pfx+':Px'],parmDict[pfx+':Py'],parmDict[pfx+':Pz']]) 2050 for i,x in enumerate(Cart): 2051 X = np.inner(Bmat,prodQVQ(Qori,x))+Pos 2052 for j in range(3): 2053 Xdata[j][iatm] = X[j] 2054 Tdata[iatm] = aTypes[i] 2055 iatm += 1 2056 elif parmDict[pfx+'Type'] == 'Atom': 2057 atNo = parmDict[pfx+'atNo'] 2058 afx = pfx+str(atNo) 2059 for key in keys: 2060 parm = afx+key 2061 if parm in parmDict: 2062 keys[key][atNo] = parmDict[parm] 2063 else: 2064 continue #skips March Dollase 2065 return Tdata,Xdata 2066 2067 def calcMDcorr(MDval,MDaxis,Uniq,G): 2068 sumMD = 0 2069 for H in Uniq: 2070 cosP,sinP = G2lat.CosSinAngle(H,MDaxis,G) 2071 A = 1.0/np.sqrt((MDval*cosP)**2+sinP**2/MDval) 2072 sumMD += A**3 2073 return sumMD 2074 2075 def mcsaCalc(values,refList,rcov,ifInv,RBdata,varyList,parmDict): 2017 2076 # ''' Compute structure factors for all h,k,l for phase 2018 2077 # input: 2019 2078 # refList: [ref] where each ref = h,k,l,m,d,...,[equiv h,k,l],phase[equiv] 2020 # G: reciprocal metric tensor2021 # SGData: space group info. dictionary output from SpcGroup2022 2079 # ParmDict: 2023 2080 # puts result F^2 in each ref[8] in refList 2024 2081 # ''' 2025 # twopi = 2.0*np.pi 2026 # twopisq = 2.0*np.pi**2 2027 # ast = np.sqrt(np.diag(G)) 2028 # Mast = twopisq*np.multiply.outer(ast,ast) 2029 # Tdata,Mdata,Fdata,Xdata = GetAtomFX(pfx,calcControls,parmDict) 2030 # FF = np.zeros(len(Tdata)) 2031 # if 'N' in parmDict[hfx+'Type']: 2032 # FP,FPP = G2el.BlenRes(Tdata,BLtables,parmDict[hfx+'Lam']) 2033 # else: 2034 # FP = np.array([FFtables[El][hfx+'FP'] for El in Tdata]) 2035 # FPP = np.array([FFtables[El][hfx+'FPP'] for El in Tdata]) 2036 # Uij = np.array(G2lat.U6toUij(Uijdata)) 2037 # bij = Mast*Uij.T 2038 # for refl in refList: 2039 # fbs = np.array([0,0]) 2040 # H = refl[:3] 2041 # SQ = 1./(2.*refl[4])**2 2042 # SQfactor = 4.0*SQ*twopisq 2043 # Bab = parmDict[phfx+'BabA']*np.exp(parmDict[phfx+'BabU']*SQfactor) 2044 # if not len(refl[1]): #no form factors 2045 # if 'N' in parmDict[hfx+'Type']: 2046 # refl[1] = getBLvalues(BLtables) 2047 # else: #'X' 2048 # refl[1] = getFFvalues(FFtables,SQ) 2049 # for i,El in enumerate(Tdata): 2050 # FF[i] = refl[1][El] 2051 # Uniq = refl[11] 2052 # phi = refl[12] 2053 # phase = twopi*(np.inner(Uniq,(Xdata.T))+phi[:,np.newaxis]) 2054 # sinp = np.sin(phase) 2055 # cosp = np.cos(phase) 2056 # occ = Mdata*Fdata/len(Uniq) 2057 # fa = np.array([(FF+FPBab)*occ*cosp,FPP*occ*sinp]) 2058 # fas = np.sum(np.sum(fa,axis=1),axis=1) #real 2059 # if not SGData['SGInv']: 2060 # fb = np.array([(FF+FPBab)*occ*sinp*Tcorr,FPP*occ*cosp*Tcorr]) 2061 # fbs = np.sum(np.sum(fb,axis=1),axis=1) 2062 # fasq = fas**2 2063 # fbsq = fbs**2 #imaginary 2064 # refl[9] = np.sum(fasq)+np.sum(fbsq) 2065 # refl[10] = atan2d(fbs[0],fas[0]) 2082 twopi = 2.0*np.pi 2083 parmDict.update(dict(zip(varyList,values))) 2084 Tdata,Xdata = GetAtomTX(RBdata,parmDict) 2085 Mdata = parmDict['Mdata'] 2086 FF = np.zeros(len(Tdata)) 2087 MDval = parmDict['0:MDval'] 2088 MDaxis = parmDict['0:MDaxis'] 2089 Gmat = parmDict['Gmat'] 2090 Srefs = np.zeros(len(refList)) 2091 sumFcsq = 0 2092 for refl in refList: 2093 fbs = 0 2094 H = refl[:3] 2095 for i,El in enumerate(Tdata): 2096 FF[i] = refl[7][El] 2097 Uniq = refl[8] 2098 phi = refl[9] 2099 phase = twopi*(np.inner(Uniq,(Xdata.T))+phi[:,np.newaxis]) 2100 sinp = np.sin(phase) 2101 cosp = np.cos(phase) 2102 occ = Mdata/len(Uniq) 2103 fa = np.asarray(FF*occ*cosp) 2104 fas = np.sum(fa) 2105 if not ifInv: 2106 fb = np.asarray(FF*occ*sinp) 2107 fbs = np.sum(fb) 2108 fcsq = (fas**2+fbs**2)*refl[3]*calcMDcorr(MDval,MDaxis,Uniq,Gmat) 2109 sumFcsq += fcsq 2110 refl[5] = fcsq 2111 scale = (parmDict['sumFosq']/sumFcsq) 2112 for iref,refl in enumerate(refList): 2113 refl[5] *= scale 2114 Srefs[iref] = refl[4]refl[5] 2115 M = np.inner(Srefs,np.inner(rcov,Srefs)) 2116 return M/parmDict['sumFosq']**2 2066 2117 2067 2118 sq8ln2 = np.sqrt(8*np.log(2)) … … 2069 2120 sq4pi = np.sqrt(4*np.pi) 2070 2121 generalData = data['General'] 2122 Amat,Bmat = G2lat.cell2AB(generalData['Cell'][1:7]) 2123 Gmat = G2lat.cell2Gmat(generalData['Cell'][1:7])[0] 2071 2124 SGData = generalData['SGData'] 2072 2125 fixAtoms = data['Atoms'] #if any 2073 2126 cx,ct,cs = generalData['AtomPtrs'][:3] 2074 2127 aTypes = set([]) 2075 parmDict = { }2128 parmDict = {'Bmat':Bmat,'Gmat':Gmat} 2076 2129 varyList = [] 2077 2130 atNo = 0 … … 2087 2140 atNo += 1 2088 2141 parmDict['nfixAt'] = len(fixAtoms) 2089 mcsaControls= generalData['MCSA controls']2090 reflName = mcsaControls['Data source']2142 MCSA = generalData['MCSA controls'] 2143 reflName = MCSA['Data source'] 2091 2144 phaseName = generalData['Name'] 2092 2145 MCSAObjs = data['MCSA']['Models'] #list of MCSA models … … 2101 2154 pfx = mfx+str(atNo)+':' 2102 2155 getAtomparms(item,pfx,aTypes,SGData,parmDict,varyList) 2156 parmDict[mfx+'atNo'] = atNo 2103 2157 atNo += 1 2104 2158 elif item['Type'] in ['Residue','Vector']: 2105 2159 pfx = mfx+':' 2106 atNo = getRBparms(item,pfx,aTypes,RBdata, atNo,parmDict,varyList)2160 atNo = getRBparms(item,pfx,aTypes,RBdata,SGData,atNo,parmDict,varyList) 2107 2161 parmDict['atNo'] = atNo #total no. of atoms 2108 2162 parmDict['nObj'] = len(MCSAObjs) 2163 Tdata,Xdata = GetAtomTX(RBdata,parmDict) 2164 parmDict['Mdata'] = GetAtomM(Xdata,SGData) 2109 2165 FFtables = G2el.GetFFtable(aTypes) 2110 2166 refs = [] 2167 sumFosq = 0 2111 2168 if 'PWDR' in reflName: 2112 2169 for ref in reflData: 2113 2170 h,k,l,m,d,pos,sig,gam,f = ref[:9] 2114 if d >= mcsaControls['dmin']:2171 if d >= MCSA['dmin']: 2115 2172 sig = gamFW(sig,gam)/sq8ln2 #> sig from FWHM 2116 2173 SQ = 0.25/d**2 … … 2118 2175 FFs = G2el.getFFvalues(FFtables,SQ) 2119 2176 refs.append([h,k,l,m,f*m,pos,sig,FFs,Uniq,phi]) 2177 sumFosq += f*m 2120 2178 nRef = len(refs) 2121 2179 rcov = np.zeros((nRef,nRef)) … … 2138 2196 for iref,refI in enumerate(reflData): 2139 2197 h,k,l,m,d,v,f,s = refI 2140 if d >= mcsaControls['dmin'] and v: #skip unrefined ones2198 if d >= MCSA['dmin'] and v: #skip unrefined ones 2141 2199 SQ = 0.25/d**2 2142 2200 Uniq,phi = G2spc.GenHKLf([h,k,l],SGData)[2:] 2143 2201 FFs = G2el.getFFvalues(FFtables,SQ) 2144 2202 refs.append([h,k,l,m,f*m,iref,0.,FFs,Uniq,phi]) 2203 sumFosq += f*m 2145 2204 nRef = len(refs) 2146 2205 pfx = str(data['pId'])+'::PWLref:' … … 2169 2228 for ref in reflData: 2170 2229 [h,k,l,m,d],f = ref[:5],ref[6] 2171 if d >= mcsaControls['dmin']:2230 if d >= MCSA['dmin']: 2172 2231 SQ = 0.25/d**2 2173 2232 Uniq,phi = G2spc.GenHKLf([h,k,l],SGData)[2:] 2174 2233 FFs = G2el.getFFvalues(FFtables,SQ) 2175 2234 refs.append([h,k,l,m,f*m,0.,0.,FFs,Uniq,phi]) 2235 sumFosq += f*m 2176 2236 rcov = np.identity(len(refs)) 2177 2178 for parm in parmDict: 2179 print parm,parmDict[parm] 2237 parmDict['sumFosq'] = sumFosq 2238 x0 = [parmDict[val] for val in varyList] 2239 ifInv = SGData['SGInv'] 2240 results = anneal(mcsaCalc,x0,args=(refs,rcov,ifInv,RBdata,varyList,parmDict), 2241 schedule=MCSA['Algorithm'], full_output=True,maxiter=MCSA['nRuns'], 2242 T0=MCSA['Annealing'][0], Tf=MCSA['Annealing'][1],dwell=MCSA['Annealing'][2], 2243 boltzmann=MCSA['boltzmann'], learn_rate=0.5, feps=MCSA['Annealing'][3], 2244 quench=MCSA['fast parms'][0], m=MCSA['fast parms'][1], n=MCSA['fast parms'][2], 2245 lower=lower, upper=upper, slope=MCSA['log slope'],dlg=pgbar) 2246 print results 2247 2248 # parmDict.update(zip(varylist,results[0])) 2180 2249 2181 # XYZ,aTypes = UpdateMCSAxyz(Bmat,MCSA)2182 2183 # generalData['MCSA controls'] = {'Data source':'','Annealing':[50.,0.001,50,1.e6],2184 # 'dmin':2.0,'Algorithm':'fast','Jump coeff':[0.95,0.5],'nRuns':1,'boltzmann':1.0,2185 # 'fast parms':[1.0,1.0,1.0],'log slope':0.9}2186 2187 2250 return {} 2188 2251 
trunk/GSASIIphsGUI.py
r946 r949 127 127 'MCSA controls' not in generalData: 128 128 generalData['MCSA controls'] = {'Data source':'','Annealing':[50.,0.001,50,1.e6], 129 'dmin':2.0,'Algorithm':'fast','Jump coeff':[0.95,0.5],'nRuns': 1,'boltzmann':1.0,129 'dmin':2.0,'Algorithm':'fast','Jump coeff':[0.95,0.5],'nRuns':50,'boltzmann':1.0, 130 130 'fast parms':[1.0,1.0,1.0],'log slope':0.9} 131 131 # end of patches … … 726 726 mcsaSizer.Add((5,5),) 727 727 line2Sizer = wx.BoxSizer(wx.HORIZONTAL) 728 Rchoice = ['1 ','2','3','5','10','15','20','50','100','200','500']729 line2Sizer.Add(wx.StaticText(General,label=' No. MC/SA runs: '),0,wx.ALIGN_CENTER_VERTICAL)728 Rchoice = ['10','15','20','50','100','200','500'] 729 line2Sizer.Add(wx.StaticText(General,label=' No. temp. steps: '),0,wx.ALIGN_CENTER_VERTICAL) 730 730 noRuns = wx.ComboBox(General,1,value=str(MCSA.get('nRuns',1)),choices=Rchoice, 731 731 style=wx.CB_READONLYwx.CB_DROPDOWN)
Note: See TracChangeset
for help on using the changeset viewer.