Changeset 265


Ignore:
Timestamp:
Apr 19, 2011 3:12:37 PM (12 years ago)
Author:
vondreele
Message:

further progress on implementing pdf calculations
optionally put legends on the pdf plots
attempt implementation of a rotation of the azimuth ranges for multiazimuth integrations -not fully successful

Location:
trunk
Files:
9 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASII.py

    r264 r265  
    1616import copy
    1717import numpy as np
     18import scipy as sp
    1819import wx
    1920import matplotlib as mpl
     
    3637print "matplotlib: ",mpl.__version__
    3738print "numpy:      ",np.__version__
     39print "scipy:      ",sp.__version__
    3840print "OpenGL:     ",ogl.__version__
    3941
     
    267269        self.qPlot = False
    268270        self.Contour = False
     271        self.Legend = False
    269272        self.SinglePlot = False
    270273        self.plotView = 0
     
    471474                            Data['outChannels'] = 2500
    472475                            Data['outAzimuths'] = 1
     476                            Data['azmthRotate'] = 0.0
    473477                            Data['fullIntegrate'] = False
    474478                            Data['setRings'] = False
     
    12401244
    12411245    def OnMakePDFs(self,event):
    1242         TextList = []
     1246        tth2q = lambda t,w:4.0*math.pi*sind(t/2.0)/w
     1247        TextList = ['All PWDR']
     1248        PDFlist = []
    12431249        Names = []
    12441250        if self.PatternTree.GetCount():
     
    12481254                Names.append(name)
    12491255                if 'PWDR' in name:
    1250                     TextList.append([False,name,id])
     1256                    TextList.append(name)
    12511257                id, cookie = self.PatternTree.GetNextChild(self.root, cookie)
    1252             if not len(TextList):
     1258            if len(TextList) == 1:
    12531259                self.ErrorDialog('Nothing to make PDFs for','There must be at least one "PWDR" pattern')
    12541260                return
    1255             dlg = self.CopyDialog(self,'Make PDF controls','Make PDF controls for:',TextList)
     1261            dlg = wx.MultiChoiceDialog(self,'Make PDF controls','Make PDF controls for:',TextList, wx.CHOICEDLG_STYLE)
    12561262            try:
    12571263                if dlg.ShowModal() == wx.ID_OK:
    1258                     result = dlg.GetData()
    1259                     for i,item in enumerate(result):
    1260                         ifmake,name,id = item
    1261                         if ifmake:
    1262                             PWDRname = name[4:]
    1263                             Id = self.PatternTree.AppendItem(parent=self.root,text='PDF '+PWDRname)
    1264                             Data = {
    1265                                 'Sample':{'Name':name,'Mult':1.0,'Add':0.0},
    1266                                 'Sample Bkg.':{'Name':'','Mult':-1.0,'Add':0.0},
    1267                                 'Container':{'Name':'','Mult':-1.0,'Add':0.0},
    1268                                 'Container Bkg.':{'Name':'','Mult':-1.0,'Add':0.0},'ElList':{},
    1269                                 'Geometry':'Cylinder','Diam':1.0,'Pack':0.50,'Form Vol':10.0}
    1270                             self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(Id,text='PDF Controls'),Data)
    1271                             self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(Id,text='S(Q)'+PWDRname),[])       
    1272                             self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(Id,text='G(R)'+PWDRname),[])       
     1264                    result = dlg.GetSelections()
     1265                    for i in result: PDFlist.append(TextList[i])
     1266                    if 0 in result:
     1267                        PDFlist = [item for item in TextList if item[:4] == 'PWDR']                       
     1268                    for item in PDFlist:
     1269                        PWDRname = item[4:]
     1270                        Id = self.PatternTree.AppendItem(parent=self.root,text='PDF '+PWDRname)
     1271                        Data = {
     1272                            'Sample':{'Name':item,'Mult':1.0,'Add':0.0},
     1273                            'Sample Bkg.':{'Name':'','Mult':-1.0,'Add':0.0},
     1274                            'Container':{'Name':'','Mult':-1.0,'Add':0.0},
     1275                            'Container Bkg.':{'Name':'','Mult':-1.0,'Add':0.0},'ElList':{},
     1276                            'Geometry':'Cylinder','Diam':1.0,'Pack':0.50,'Form Vol':10.0,
     1277                            'DetType':'Image plate','ObliqCoeff':0.2,'Ruland':0.003,'QScaleLim':[0,100],
     1278                            'Lorch':True,}
     1279                        self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(Id,text='PDF Controls'),Data)
     1280                        self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(Id,text='I(Q)'+PWDRname),[])       
     1281                        self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(Id,text='S(Q)'+PWDRname),[])       
     1282                        self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(Id,text='F(Q)'+PWDRname),[])       
     1283                        self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(Id,text='G(R)'+PWDRname),[])       
    12731284            finally:
    12741285                dlg.Destroy()
  • trunk/GSASIIElem.py

    r264 r265  
    5353    FFdata.close()
    5454    return FormFactors
     55   
     56def GetFFC5(ElSym):
     57    '''Get 5 term form factor and Compton scattering data
     58    @param ElSym: str(1-2 character element symbol with proper case);
     59    @return El: dictionary with 5 term form factor & compton coefficients
     60    '''
     61    import FormFactors as FF
     62    El = {}
     63    FF5 = FF.FFac5term[ElSym]
     64    El['fa'] = FF5[:5]
     65    El['fc'] = FF5[5]
     66    El['fb'] = FF5[6:]
     67    Cmp5 = FF.Compton[ElSym]
     68    El['cmpz'] = Cmp5[0]
     69    El['cmpa'] = Cmp5[1:6]
     70    El['cmpb'] = Cmp5[6:]
     71    return El
    5572   
    5673def GetAtomInfo(El):
     
    214231    return MagFormFactors
    215232
    216 def ScatFac(FormFac, SQ):
     233def ScatFac(El, SQ):
    217234    """compute value of form factor
    218     @param FormFac: dictionary  defined in GetFormFactorCoeff
     235    @param El: element dictionary  defined in GetFormFactorCoeff
    219236    @param SQ: (sin-theta/lambda)**2
    220     @return: f: real part of form factor
     237    @return: real part of form factor
    221238    """
    222     fa = np.array(FormFac['fa'])
    223     fb = np.array(FormFac['fb'])
    224     t = -fb*SQ
    225     return np.sum(fa*np.exp(t))+FormFac['fc']
    226    
    227 def ComptonFac(ComptonCoeff,SQ):
     239    fa = np.array(El['fa'])
     240    fb = np.array(El['fb'])
     241    t = -fb[:,np.newaxis]*SQ
     242    return np.sum(fa[:,np.newaxis]*np.exp(t)[:],axis=0)+El['fc']
     243   
     244def ComptonFac(El,SQ):
    228245    """compute Compton scattering factor
    229     @param ComptonCoeff: list [Z, a1:a5, b1:b5]
     246    @param El: element dictionary
    230247    @param SQ: (sin-theta/lambda)**2
    231     @return: comp: compton scattering factor
     248    @return: compton scattering factor
    232249    """   
    233     ca = np.array(ComptonCoeff[1:6])
    234     cb = np.array(ComptonCoeff[6:11])
    235     t = -cb*SQ
    236     return ComptonCoeff[0]-np.sum(ca*np.exp(t))
     250    ca = np.array(El['cmpa'])
     251    cb = np.array(El['cmpb'])
     252    t = -cb[:,np.newaxis]*SQ       
     253    return El['cmpz']-np.sum(ca[:,np.newaxis]*np.exp(t),axis=0)
    237254           
    238255def FPcalc(Orbs, KEv):
     
    367384class DeleteElement(wx.Dialog):
    368385    "Delete element from selected set widget"
    369     def _init_ctrls(self, parent):
    370         l = len(DeleteElement.Elems)-1
    371         wx.Dialog.__init__(self, id=-1, name='Delete', parent=parent,
     386    def _init_ctrls(self, parent,choice):
     387        l = len(choice)-1
     388        wx.Dialog.__init__(self, id=-1, name='Delete', parent=parent, 
    372389              pos=wx.DefaultPosition, size=wx.Size(max(128,64+l*24), 87),
    373390              style=wx.DEFAULT_DIALOG_STYLE, title='Delete Element')
     
    379396        i = 0
    380397        Elem = []
    381         for Elem in DeleteElement.Elems:
    382             name = Elem[0].lower().capitalize()
    383             self.ElButton(id=-1,name=name,pos=wx.Point(16+i*24, 16))
     398        for Elem in choice:
     399            self.ElButton(id=-1,name=Elem,pos=wx.Point(16+i*24, 16))
    384400            i+=1
    385401             
    386     def __init__(self, parent):
    387         DeleteElement.Elems = parent.Elems
     402    def __init__(self, parent,choice):
    388403        DeleteElement.El = ' '
    389         self._init_ctrls(parent)
     404        self._init_ctrls(parent,choice)
    390405
    391406    def ElButton(self, id, name, pos):
  • trunk/GSASIIIO.py

    r251 r265  
    438438    ext = ospath.splitext(imagefile)[1]
    439439    Comments = []
    440     if ext == '.tif':
     440    if ext == '.tif' or ext == '.tiff':
    441441        Comments,Data,Npix,Image = GetTifData(imagefile)
    442442    elif ext == '.img':
     
    648648            Value = st.unpack(byteOrd+'i',File.read(4))
    649649        elif Type == 3:
    650             Value = st.unpack(byteOrd+nVal*'i',File.read(nVal*4))
     650            Value = st.unpack(byteOrd+nVal*'h',File.read(nVal*2))
     651            x = st.unpack(byteOrd+nVal*'h',File.read(nVal*2))
    651652        elif Type == 4:
    652653            Value = st.unpack(byteOrd+nVal*'i',File.read(nVal*4))
     
    656657            Value = st.unpack(byteOrd+nVal*'f',File.read(nVal*4))
    657658        IFD[Tag] = [Type,nVal,Value]
     659#    for key in IFD:
     660#        print key,IFD[key]
    658661    sizexy = [IFD[256][2][0],IFD[257][2][0]]
    659662    [nx,ny] = sizexy
     
    790793    names = ['Type','Lam','Zero','Polariz.','U','V','W','X','Y','SH/L','Azimuth']
    791794    codes = [0 for i in range(11)]
    792     parms = ['PXC',data['wavelength'],0.0,0.0,1.0,-1.0,0.3,0.0,1.0,0.0,0.0]
    793795    Azms = [(azms[i+1]+azms[i])/2. for i in range(len(azms)-1)]
     796    if data['fullIntegrate'] and data['outAzimuths'] == 1:
     797        Azms = [0.0,]
    794798    for i,azm in enumerate(Azms):
    795799        item, cookie = self.PatternTree.GetFirstChild(self.root)
     
    800804                Id = item
    801805            item, cookie = self.PatternTree.GetNextChild(self.root, cookie)
    802         parms[10] = azm
     806        parms = ['PXC',data['wavelength'],0.0,0.95,1.0,-1.0,0.3,0.0,1.0,0.0,azm]    #set polarization for synchrotron radiation!
    803807        Y = self.Integrate[0][i]
    804808        W = 1./Y                    #probably not true
     
    809813            self.PatternTree.SetItemPyData(G2gd.GetPatternTreeItemId(self,Id,'Limits'),[tuple(Xminmax),Xminmax])
    810814            self.PatternTree.SetItemPyData(G2gd.GetPatternTreeItemId(self,Id,'Background'),[['chebyschev',1,3,1.0,0.0,0.0]])
    811             self.PatternTree.SetItemPyData(G2gd.GetPatternTreeItemId(self,Id,'Instrument Parameters'),[tuple(parms),parms,codes,names])
     815            self.PatternTree.SetItemPyData(G2gd.GetPatternTreeItemId(self,Id,'Instrument Parameters'),[tuple(parms),parms[:],codes,names])
    812816            self.PatternTree.SetItemPyData(G2gd.GetPatternTreeItemId(self,Id,'Peak List'),[])
    813817            self.PatternTree.SetItemPyData(G2gd.GetPatternTreeItemId(self,Id,'Index Peak List'),[])
     
    818822            self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(Id,text='Limits'),[tuple(Xminmax),Xminmax])
    819823            self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(Id,text='Background'),[['chebyschev',1,3,1.0,0.0,0.0]])
    820             self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(Id,text='Instrument Parameters'),[tuple(parms),parms,codes,names])
     824            self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(Id,text='Instrument Parameters'),[tuple(parms),parms[:],codes,names])
    821825            self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(Id,text='Sample Parameters'),Sample)
    822826            self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(Id,text='Peak List'),[])
    823827            self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(Id,text='Index Peak List'),[])
    824             self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(Id,text='Unit Cells List'),[])             
     828            self.PatternTree.SetItemPyData(self.PatternTree.AppendItem(Id,text='Unit Cells List'),[])
    825829        self.PatternTree.SetItemPyData(Id,[[''],[np.array(X),np.array(Y),np.array(W),np.zeros(N),np.zeros(N),np.zeros(N)]])
    826830    self.PatternTree.SelectItem(Id)
  • trunk/GSASIIgrid.py

    r264 r265  
    199199           
    200200    def _init_coll_PDF_Items(self,parent):
    201         parent.Append(help='Copy PDF controls', id=wxID_PDFCOPYCONTROLS, kind=wx.ITEM_NORMAL,
    202             text='Copy controls')
    203         parent.Append(help='Save PDF controls to file', id=wxID_PDFSAVECONTROLS, kind=wx.ITEM_NORMAL,
    204             text='Save controls')
    205         parent.Append(help='Load PDF controls from file',id=wxID_PDFLOADCONTROLS, kind=wx.ITEM_NORMAL,
    206             text='Load Controls')
    207201        parent.Append(help='Add element to sample composition',id=wxID_PDFADDELEMENT, kind=wx.ITEM_NORMAL,
    208202            text='Add element')
    209203        parent.Append(help='Delete element from sample composition',id=wxID_PDFDELELEMENT, kind=wx.ITEM_NORMAL,
    210204            text='Delete element')
     205        parent.Append(help='Copy PDF controls', id=wxID_PDFCOPYCONTROLS, kind=wx.ITEM_NORMAL,
     206            text='Copy controls')
     207        parent.Append(help='Load PDF controls from file',id=wxID_PDFLOADCONTROLS, kind=wx.ITEM_NORMAL,
     208            text='Load Controls')
     209        parent.Append(help='Save PDF controls to file', id=wxID_PDFSAVECONTROLS, kind=wx.ITEM_NORMAL,
     210            text='Save controls')
    211211        self.PDFCompute = parent.Append(help='Compute PDF', id=wxID_PDFCOMPUTE, kind=wx.ITEM_NORMAL,
    212212            text='Compute PDF')
     
    750750        elif 'PDF' in self.PatternTree.GetItemText(item):
    751751            self.PatternId = item
    752             G2plt.PlotSofQ(self)
    753             G2plt.PlotGofR(self)
    754            
     752            G2plt.PlotISFG(self,type='S(Q)')
     753           
     754    elif 'I(Q)' in self.PatternTree.GetItemText(item):
     755        self.PickId = item
     756        self.PatternId = self.PatternTree.GetItemParent(item)
     757        G2plt.PlotISFG(self,type='I(Q)',newPlot=True)
    755758    elif 'S(Q)' in self.PatternTree.GetItemText(item):
    756759        self.PickId = item
    757760        self.PatternId = self.PatternTree.GetItemParent(item)
    758         G2plt.PlotSofQ(self)
     761        G2plt.PlotISFG(self,type='S(Q)',newPlot=True)
     762    elif 'F(Q)' in self.PatternTree.GetItemText(item):
     763        self.PickId = item
     764        self.PatternId = self.PatternTree.GetItemParent(item)
     765        G2plt.PlotISFG(self,type='F(Q)',newPlot=True)
    759766    elif 'G(R)' in self.PatternTree.GetItemText(item):
    760767        self.PickId = item
    761768        self.PatternId = self.PatternTree.GetItemParent(item)
    762         G2plt.PlotGofR(self)           
     769        G2plt.PlotISFG(self,type='G(R)',newPlot=True)           
    763770    elif self.PatternTree.GetItemText(parentID) == 'Phases':
    764771        self.PickId = item
     
    798805        data = self.PatternTree.GetItemPyData(item)
    799806        G2pdG.UpdatePDFGrid(self,data)
    800         G2plt.PlotSofQ(self)
    801         G2plt.PlotGofR(self)
     807        G2plt.PlotISFG(self,type='S(Q)')
    802808    elif self.PatternTree.GetItemText(item) == 'Peak List':
    803809        self.PatternId = self.PatternTree.GetItemParent(item)
  • trunk/GSASIIimage.py

    r264 r265  
    291291    tilt = data['tilt']
    292292    phi = data['rotation']
     293    LRazim = data['LRazimuth']
    293294    azmthoff = data['azmthOff']
     295    azmRot = data['azmthRotate']
     296    Full = data['fullIntegrate']
    294297    dx = np.array(x-cent[0],dtype=np.float32)
    295298    dy = np.array(y-cent[1],dtype=np.float32)
     
    299302    tth = npatand(np.sqrt(dx**2+dy**2-Z**2)/(dist-Z))
    300303    dsp = wave/(2.*npsind(tth/2.))
    301     azm = npatan2d(dx,-dy)+azmthoff
     304    azm = (npatan2d(dx,-dy)+azmthoff+720.)%360.
     305    if Full:
     306        azm = (azm+azmRot+720.)%360.
     307    else:
     308        azm = np.where(azm<LRazim[0],azm+360.,azm)
    302309    return tth,azm,dsp
    303310   
     
    325332    return abs(avg-curr)/avg < .02
    326333
    327        
    328334def ImageCalibrate(self,data):
    329335    import copy
     
    554560    LUtth = data['IOtth']
    555561    if data['fullIntegrate']:
    556         LRazm = [-180,180]
     562        LRazm = [0,360]
    557563    else:
    558564        LRazm = data['LRazimuth']
    559565    numAzms = data['outAzimuths']
    560566    numChans = data['outChannels']
     567    azmRot = data['azmthRotate']
     568    Full = data['fullIntegrate']
    561569    Dtth = (LUtth[1]-LUtth[0])/numChans
    562570    Dazm = (LRazm[1]-LRazm[0])/numAzms
     
    602610            H2 = LUtth
    603611        if Dazm:       
    604             H1 = [azm for azm in np.linspace(LRazm[0],LRazm[1],numAzms+1)]
     612            H1 = np.array([azm for azm in np.linspace(LRazm[0],LRazm[1],numAzms+1)])
     613            if Full:
     614                H1 = H1+azmRot
    605615        else:
    606616            H1 = LRazm
  • trunk/GSASIIimgGUI.py

    r264 r265  
    152152            pass
    153153        outAzim.SetValue(str(data['outAzimuths']))          #reset in case of error       
     154        G2plt.PlotExposedImage(self,event=event)
    154155       
    155156    def OnWavelength(event):
     
    181182        G2plt.PlotExposedImage(self,event=event)
    182183       
     184    def OnAzmRot(event):
     185        try:
     186            azmrot = float(azmRot.GetValue())
     187            data['azmthRotate'] = azmrot
     188        except ValueError:
     189            pass
     190        azmRot.SetValue("%.2f" % (data['azmthRotate']))          #reset in case of error         
     191        G2plt.PlotExposedImage(self,event=event)
     192               
    183193    def OnSetDefault(event):
    184194        import copy
     
    362372    #fix for old files:
    363373    if 'azmthOff' not in data:
    364         data['azmthOff'] = 0.0       
     374        data['azmthOff'] = 0.0
     375    if 'azmthRotate' not in data:
     376        data['azmthRotate'] = 0.0       
    365377    #end fix
    366378   
     
    523535    dataSizer.Add(tiltSel,0,wx.ALIGN_CENTER_VERTICAL)
    524536    showLines = wx.CheckBox(parent=self.dataDisplay,label='Show integration limits?')
    525     dataSizer.Add(showLines,0)
     537    dataSizer.Add(showLines,0,wx.ALIGN_CENTER_VERTICAL)
    526538    showLines.Bind(wx.EVT_CHECKBOX, OnShowLines)
    527539    showLines.SetValue(data['showLines'])
    528540    fullIntegrate = wx.CheckBox(parent=self.dataDisplay,label='Do full integration?')
    529     dataSizer.Add(fullIntegrate,0)
     541    dataSizer.Add(fullIntegrate,0,wx.ALIGN_CENTER_VERTICAL)
    530542    fullIntegrate.Bind(wx.EVT_CHECKBOX, OnFullIntegrate)
    531543    fullIntegrate.SetValue(data['fullIntegrate'])
     
    536548    rotSel.SetBackgroundColour(VERY_LIGHT_GREY)
    537549    dataSizer.Add(rotSel,0,wx.ALIGN_CENTER_VERTICAL)
     550    dataSizer.Add(wx.StaticText(parent=self.dataDisplay,label=' Bin offset'),0,
     551        wx.ALIGN_CENTER_VERTICAL)
     552    azmRot = wx.TextCtrl(parent=self.dataDisplay,value=("%.2f" % (data['azmthRotate'])),style=wx.TE_PROCESS_ENTER)
     553    azmRot.Bind(wx.EVT_TEXT_ENTER,OnAzmRot)
     554    azmRot.Bind(wx.EVT_KILL_FOCUS,OnAzmRot)
     555    dataSizer.Add(azmRot,0,wx.ALIGN_CENTER_VERTICAL)
    538556    setDefault = wx.CheckBox(parent=self.dataDisplay,label='Use as default for all images?')
    539     dataSizer.Add(setDefault,0)
     557    dataSizer.Add(setDefault,0,wx.ALIGN_CENTER_VERTICAL)
    540558    setDefault.Bind(wx.EVT_CHECKBOX, OnSetDefault)
    541559    setDefault.SetValue(data['setDefault'])
  • trunk/GSASIIpeak.py

    r264 r265  
    1212import time
    1313import numpy as np
     14import scipy as sp
    1415import numpy.linalg as nl
     16import scipy.interpolate as si
    1517import GSASIIpath
    1618import pypowder as pyp              #assumes path has been amended to include correctr bin directory
    1719import GSASIIplot as G2plt
     20import GSASIIlattice as G2lat
     21import GSASIIElem as G2elem
     22import GSASIIgrid as G2gd
    1823
    1924# trig functions in degrees
     
    3338npatand = lambda x: 180.*np.arctan(x)/np.pi
    3439npatan2d = lambda y,x: 180.*np.arctan2(y,x)/np.pi
     40npT2stl = lambda tth, wave: 2.0*npsind(tth/2.0)/wave
     41npT2q = lambda tth,wave: 2.0*np.pi*npT2stl(tth,wave)
    3542
    3643def factorize(num):
     
    7885def Transmission(Geometry,Abs,Diam):
    7986#Calculate sample transmission
    80 #   Geometry: one of 'Cylinder','Bragg-Brentano','Tilting Flat Plate in transmission','Fixed flat plate'
     87#   Geometry: one of 'Cylinder','Bragg-Brentano','Tilting flat plate in transmission','Fixed flat plate'
    8188#   Abs: absorption coeff in cm-1
    8289#   Diam: sample thickness/diameter in mm
    8390    if 'Cylinder' in Geometry:      #Lobanov & Alte da Veiga for 2-theta = 0; beam fully illuminates sample
    84         MuR = Abs*Diam/5.0
     91        MuR = Abs*Diam/20.0
    8592        if MuR <= 3.0:
    8693            T0 = 16/(3.*math.pi)
     
    100107            T = (T1-T4)/(1.0+T2*(MuR-3.0))**T3+T4
    101108            return T/100.
     109    elif 'plate' in Geometry:
     110        MuR = Abs*Diam/10.
     111        return math.exp(-MuR)
     112    elif 'Bragg' in Geometry:
     113        return 0.0
    102114
    103115def Absorb(Geometry,Abs,Diam,Tth,Phi=0,Psi=0):
     
    109121#   Phi: flat plate tilt angle - future
    110122#   Psi: flat plate tilt axis - future
    111     MuR = Abs*Diam/5.0
    112123    Sth2 = npsind(Tth/2.0)**2
    113124    Cth2 = 1.-Sth2
    114125    if 'Cylinder' in Geometry:      #Lobanov & Alte da Veiga for 2-theta = 0; beam fully illuminates sample
     126        MuR = Abs*Diam/20.0
    115127        if MuR < 3.0:
    116128            T0 = 16.0/(3*np.pi)
     
    136148    elif 'Fixed' in Geometry: #assumes sample plane is perpendicular to incident beam
    137149        # and only defined for 2theta < 90
     150        MuR = Abs*Diam/10.0
    138151        T1 = np.exp(-MuR)
    139         T2 = np.exp(-MuR/(1.-2.*Sth2))
    140         Tb = -2.*Abs*Sth2
    141         return (T1-T2)/Tb
     152        T2 = np.exp(-MuR/npcosd(Tth))
     153        Tb = MuR-MuR/npcosd(Tth)
     154        return (T2-T1)/Tb
    142155    elif 'Tilting' in Geometry: #assumes symmetric tilt so sample plane is parallel to diffraction vector
     156        MuR = Abs*Diam/10.0
    143157        cth = npcosd(Tth/2.0)
    144         return (Diam/cth)*np.exp(-MuR/cth)
     158        return np.exp(-MuR/cth)/cth
    145159       
    146 def Polarization(Pola,Azm,Tth):
    147 #   Calculate x-ray polarization correction
     160def Polarization(Pola,Tth,Azm=0.0):
     161#   Calculate angle dependent x-ray polarization correction (not scaled correctly!)
    148162#   Pola: polarization coefficient e.g 1.0 fully polarized, 0.5 unpolarized
    149 #   Azm: azimuthal angle e.g. 0.0 in plane of polarization(?)
     163#   Azm: azimuthal angle e.g. 0.0 in plane of polarization
    150164#   Tth: 2-theta scattering angle - can be numpy array
    151     pass
    152    
     165#       which (if either) of these is "right"?
     166#    return (Pola*npcosd(Azm)**2+(1.-Pola)*npsind(Azm)**2)*npcosd(Tth)**2+ \
     167#        Pola*npsind(Azm)**2+(1.-Pola)*npcosd(Azm)**2
     168#    return (Pola*npcosd(Azm)**2+npsind(Azm)**2)*npcosd(Tth)**2+   \
     169#        Pola*npsind(Azm)**2+npcosd(Azm)**2
     170    return Pola*npcosd(Tth)**2+1.0
     171   
     172def Oblique(ObCoeff,Tth):
     173    if ObCoeff:
     174        return (1.-ObCoeff)/(1.0-np.exp(np.log(ObCoeff)/npcosd(Tth)))
     175    else:
     176        return 1.0
     177       
     178def Ruland(RulCoff,wave,Q,Compton):
     179    C = 2.9978e8
     180    D = 1.5e-3
     181    hmc = 0.024262734687
     182    sinth2 = (Q*wave/(4.0*np.pi))**2
     183    dlam = (wave**2)*Compton*Q/C
     184    dlam_c = 2.0*hmc*sinth2-D*wave**2
     185    return 1.0/((1.0+dlam/RulCoff)*(1.0+(np.pi*dlam_c/(dlam+RulCoff))**2))
     186   
     187def lambdaCompton(DetType,wave,Q):
     188    hmc = 0.024262734687
     189    if 'Image' in DetType:       
     190        return wave*(1.0+2.0*hmc*wave*(Q/(4.0*np.pi))**2)**3
     191    else: 
     192        return wave*(1.0+2.0*hmc*wave*(Q/(4.0*np.pi))**2)**2
     193       
     194def GetAsfMean(ElList,Sthl2):
     195#   Calculate various scattering factor terms for PDF calcs
     196#   ElList: element dictionary contains scattering factor coefficients, etc.
     197#   Sthl2: numpy array of sin theta/lambda squared values
     198#   returns: mean(f^2), mean(f)^2, mean(compton)
     199    sumNoAtoms = 0.0
     200    FF = np.zeros_like(Sthl2)
     201    FF2 = np.zeros_like(Sthl2)
     202    CF = np.zeros_like(Sthl2)
     203    for El in ElList:
     204        sumNoAtoms += ElList[El]['FormulaNo']
     205    for El in ElList:
     206        el = ElList[El]
     207        ff2 = (G2elem.ScatFac(el,Sthl2)+el['fp'])**2+el['fpp']**2
     208        cf = G2elem.ComptonFac(el,Sthl2)
     209        FF += np.sqrt(ff2)*el['FormulaNo']/sumNoAtoms
     210        FF2 += ff2*el['FormulaNo']/sumNoAtoms
     211        CF += cf*el['FormulaNo']/sumNoAtoms
     212    return FF2,FF**2,CF
     213           
     214def MultGetQ(Tth,MuT,Geometry,b=88.0,a=0.01):
     215    NS = 500
     216    Gama = np.linspace(0.,np.pi/2.,NS,False)[1:]
     217    Cgama = np.cos(Gama)[:,np.newaxis]
     218    Sgama = np.sin(Gama)[:,np.newaxis]
     219    CSgama = 1.0/Sgama
     220    Delt = Gama[1]-Gama[0]
     221    emc = 7.94e-26
     222    Navo = 6.023e23
     223    Cth = npcosd(Tth/2.0)
     224    CTth = npcosd(Tth)
     225    Sth = npcosd(Tth/2.0)
     226    STth = npsind(Tth)
     227    CSth = 1.0/Sth
     228    CSTth = 1.0/STth
     229    SCth = 1.0/Cth
     230    SCTth = 1.0/CTth
     231    if 'Bragg' in Geometry:
     232        G = 8.0*Delt*Navo*emc*Sth/((1.0-CTth**2)*(1.0-np.exp(-2.0*MuT*CSth)))
     233        Y1 = np.pi
     234        Y2 = np.pi/2.0
     235        Y3 = 3.*np.pi/8. #3pi/4?
     236        W = 1.0/(Sth+np.fabs(Sgama))
     237        W += np.exp(-MuT*CSth)*(2.0*np.fabs(Sgama)*np.exp(-MuT*np.fabs(CSgama))-
     238            (Sth+np.fabs(Sgama))*np.exp(-MuT*CSth))/(Sth**2-Sgama**2)
     239        Fac0 = Sth**2*Sgama**2
     240        X = Fac0+(Fac0+CTth)**2/2
     241        Y = Cgama**2*Cth**2*(1.0-Fac0-CTth)
     242        Z = Cgama**4*Cth**4/2.0
     243        E = 2.0*(1.0-a)/(b*Cgama/Cth)
     244        F1 = (2.0+b*(1.0+Sth*Sgama))/(b*Cth*Cgama) #trouble if < 1
     245        F2 = (2.0+b*(1.0-Sth*Sgama))/(b*Cth*Cgama)
     246        T1 = np.pi/np.sqrt(F1**2-1.0)
     247        T2 = np.pi/np.sqrt(F2**2-1.0)
     248        Y4 = T1+T2
     249        Y5 = F1**2*T1+F2**2*T2-np.pi*(F1+F2)
     250        Y6 = F1**4*T1+F2**4*T2-np.pi*(F1+F2)/2.0-np.pi*(F1**3+F2**3)
     251        Y7 = (T2-T1)/(F1-F2)
     252        YT = F2**2*T2-F1**2*T1
     253        Y8 = Y1+YT/(F1-F2)
     254        Y9 = Y2+(F2**4*T2-F1**4*T1)/(F1-F2)+Y1*((F1+F2)**2-F1*F2)
     255        M = (a**2*(X*Y1+Y*Y2+Z*Y3)+a*E*(X*Y4+Y*Y5+Z*Y6)+E**2*(X*Y7+Y*Y8+Z*Y9))*Cgama
     256       
     257        Q = np.sum(W*M,axis=0)
     258        return Q*G*NS/(NS-1.)
     259#
     260#      cos2th=2.0d*costh^2 - 1.0d
     261#      G= delta * 8.0d * Na * emc * sinth/(1.0d + cos2th^2)/(1.0d - exp(-2.0d*mut*cscth))
     262#      Y1=3.1415926d
     263#      Y2=Y1*0.5d
     264#      Y3=Y2*0.75d
     265#      for i=1,num_steps-1 do begin
     266#         cosgama=double(cos(gama[i]))
     267#         singama=double(sin(gama[i]))
     268#         cscgama=1.0d / singama
     269#
     270#         W=1.0d/(sinth+abs(singama))
     271#         W=W+exp(-1.0*mut*cscth)*(2.0d*abs(singama)*exp(-1.0d*mut*abs(cscgama))- $
     272#                 (sinth+abs(singama))*exp(-1.0d*mut*cscth))/(sinth^2-singama^2)
     273#
     274#         factor0=sinth^2*singama^2
     275#         X=factor0+(factor0+cos2th)^2/2.0d
     276#         Y=cosgama^2*(1.0d - factor0-cos2th)*costh^2
     277#         Z=cosgama^4/2.0d*costh^4
     278#         E=2.0d*(1.0-a)/b/cosgama/costh
     279#
     280#         F1=1.0d/b/cosgama*(2.0d + b*(1.0+sinth*singama))/costh
     281#         F2=1.0d/b/cosgama*(2.0d + b*(1.0-sinth*singama))/costh
     282#
     283#         T1=3.14159/sqrt(F1^2-1.0d)
     284#         T2=3.14159/sqrt(F2^2-1.0d)
     285#         Y4=T1+T2
     286#         Y5=F1^2*T1+F2^2*T2-3.14159*(F1+F2)
     287#         Y6=F1^4*T1+F2^4*T2-3.14159*(F1+F2)/2.0-3.14159*(F1^3+F2^3)
     288#         Y7=(T2-T1)/(F1-F2)
     289#         Y8=Y1+(F2^2*T2-F1^2*T1)/(F1-F2)
     290#         Y9=Y2+(F2^4*T2-F1^4*T1)/(F1-F2)+Y1*((F1+F2)^2-F1*F2)
     291#         M=(a^2*(X*Y1+Y*Y2+Z*Y3)+a*E*(X*Y4+Y*Y5+Z*Y6)+E^2* $
     292#                      (X*Y7+Y*Y8+Z*Y9))*cosgama
     293#
     294#         Q=Q+W*M
     295#
     296#      endfor
     297#      Q=double(num_steps)/Double(num_steps-1)*Q*G
     298#      end
     299    elif 'Cylinder' in Geometry:
     300        Q = 0.
     301    elif 'Fixed' in Geometry:   #Dwiggens & Park, Acta Cryst. A27, 264 (1971) with corrections
     302        EMA = np.exp(-MuT*(1.0-SCTth))
     303        Fac1 = (1.-EMA)/(1.0-SCTth)
     304        G = 2.0*Delt*Navo*emc/((1.0+CTth**2)*Fac1)
     305        Fac0 = Cgama/(1-Sgama*SCTth)
     306        Wp = Fac0*(Fac1-(EMA-np.exp(-MuT*(CSgama-SCTth)))/(CSgama-1.0))
     307        Fac0 = Cgama/(1.0+Sgama*SCTth)
     308        Wm = Fac0*(Fac1+(np.exp(-MuT*(1.0+CSgama))-1.0)/(CSgama+1.0))
     309        X = (Sgama**2+CTth**2*(1.0-Sgama**2+Sgama**4))/2.0
     310        Y = Sgama**3*Cgama*STth*CTth
     311        Z = Cgama**2*(1.0+Sgama**2)*STth**2/2.0
     312        Fac2 = 1.0/(b*Cgama*STth)
     313        U = 2.0*(1.0-a)*Fac2
     314        V = (2.0+b*(1.0-CTth*Sgama))*Fac2
     315        Mp = 2.0*np.pi*(a+2.0*(1.0-a)/(2.0+b*(1.0-Sgama)))*(a*X+a*Z/2.0-U*Y+U*(X+Y*V+Z*V**2)/np.sqrt(V**2-1.0)-U*Z*V)
     316        V = (2.0+b*(1.0+CTth*Sgama))*Fac2
     317        Y = -Y
     318        Mm = 2.0*np.pi*(a+2.0*(1.0-a)/(2.0+b*(1.0+Sgama)))*(a*X+a*Z/2.0-U*Y+U*(X+Y*V+Z*V**2)/np.sqrt(V**2-1.0)-U*Z*V)
     319        Q = np.sum(Wp*Mp+Wm*Mm,axis=0)
     320        return Q*G*NS/(NS-1.)
     321    elif 'Tilting' in Geometry:
     322        EMA = np.exp(-MuT*SCth)
     323        G = 2.0*Delt*Navo*emc/((1.0+CTth**2)*EMA)
     324#          Wplus = expmutsecth/(1.0d - singama*secth) + singama/mut/(1.0 -singama*secth)/(1.0-singama*secth)* $
     325#                                                       (Exp(-1.0*mut*cscgama) - expmutsecth)
     326#          Wminus = expmutsecth/(1.0d + singama*secth) - singama/mut/(1.0 +singama*secth)/(1.0+singama*secth)* $
     327#                                                        expmutsecth*(1.0d - expmutsecth*Exp(-1.0*mut*cscgama))
     328        Wp = EMA/(1.0-Sgama*SCth)+Sgama/MuT/(1.0-Sgama*SCth)/(1.0-Sgama*SCth)*(np.exp(-MuT*CSgama)-EMA)
     329#        Wp = EMA/(1.0-Sgama*SCth)+Sgama/MuT/(1.0-Sgama*SCth)**2*(np.exp(-MuT*CSgama)-EMA)
     330        Wm = EMA/(1.0+Sgama*SCth)-Sgama/MuT/(1.0+Sgama*SCth)/(1.0+Sgama*SCth)*EMA*(1.0-EMA*np.exp(-MuT*CSgama))
     331#        Wm = EMA/(1.0+Sgama*SCth)-Sgama/MuT/(1.0+Sgama*SCth)**2*EMA*(1.0-EMA*np.exp(-MuT*CSgama))
     332        X = 0.5*(Cth**2*(Cth**2*Sgama**4-4.0*Sth**2*Cgama**2)+1.0)
     333        Y = Cgama**2*(1.0+Cgama**2)*Cth**2*Sth**2
     334        Z = 0.5*Cgama**4*Sth**4
     335#          X = 0.5*(costh*costh*(costh*costh*singama*singama*singama*singama - $
     336#                           4.0*sinth*sinth*cosgama*cosgama) +1.0d)
     337#
     338#          Y = cosgama*cosgama*(1.0 + cosgama*cosgama)*costh*costh*sinth*sinth
     339#
     340#          Z= 0.5 *cosgama*cosgama*cosgama*cosgama* (sinth^4)
     341#
     342        AlP = 2.0+b*(1.0-Cth*Sgama)
     343        AlM = 2.0+b*(1.0+Cth*Sgama)
     344#          alphaplus = 2.0 + b*(1.0 - costh*singama)
     345#          alphaminus = 2.0 + b*(1.0 + costh*singama)
     346        BeP = np.sqrt(np.fabs(AlP**2-(b*Cgama*Sth)**2))
     347        BeM = np.sqrt(np.fabs(AlM**2-(b*Cgama*Sth)**2))
     348#          betaplus = Sqrt(Abs(alphaplus*alphaplus - b*b*cosgama*cosgama*sinth*sinth))
     349#          betaminus = Sqrt(Abs(alphaminus*alphaminus - b*b*cosgama*cosgama*sinth*sinth))
     350        Mp = Cgama*(np.pi*a**2*(2.0*X+Y+0.75*Z)+(2.0*np.pi*(1.0-a))*(1.0-a+a*AlP)* \
     351            (4.0*X/AlP/BeP+(4.0*(1.0+Cgama**2)/b/b*Cth**2)*(AlP/BeP-1.0)+
     352            2.0/b**4*AlP/BeP*AlP**2-2.0/b**4*AlP**2-Cgama**2/b/b*Sth*2))
     353#          Mplus = cosgama*(!DPI * a * a * (2.0*x + y + 0.75*z) + $
     354#                   (2.0*!DPI*(1.0 - a)) *(1.0 - a + a*alphaplus)* $
     355#                   (4.0*x/alphaplus/betaplus + (4.0*(1.0+cosgama*cosgama)/b/b*costh*costh)*(alphaplus/betaplus -1.0) + $
     356#                   2.0/(b^4)*alphaplus/betaplus*alphaplus*alphaplus - 2.0/(b^4)*alphaplus*alphaplus - $
     357#                   cosgama*cosgama/b/b*sinth*sinth))
     358        Mm =Cgama*(np.pi*a**2*(2.0*X+Y+0.75*Z)+(2.0*np.pi*(1.0-a))*(1.0-a+a*AlM)* \
     359            (4.0*X/AlM/BeM+(4.0*(1.0+Cgama**2)/b/b*Cth**2)*(AlM/BeM-1.0)+
     360            2.0/b**4*AlM/BeM*AlM**2-2.0/b**4*AlM**2-Cgama**2/b/b*Sth*2))
     361#          Mminus = cosgama*(!DPI * a * a * (2.0*x + y + 0.75*z) + $
     362#                   (2.0*!DPI*(1.0 - a)) *(1.0 - a + a*alphaminus)* $
     363#                   (4.0*x/alphaminus/betaminus + (4.0*(1.0+cosgama*cosgama)/b/b*costh*costh)*(alphaminus/betaminus -1.0) + $
     364#                   2.0/(b^4)*alphaminus/betaminus*alphaminus*alphaminus - 2.0/(b^4)*alphaminus*alphaminus - $
     365#                   cosgama*cosgama/b/b*sinth*sinth))
     366        Q = np.sum(Wp*Mp+Wm*Mm,axis=0)
     367        return Q*G*NS/(NS-1.)
     368#       expmutsecth = Exp(-1.0*mut*secth)
     369#       G= delta * 2.0 * Na * emc /(1.0+costth^2)/expmutsecth
     370#       for i=1, num_steps-1 do begin
     371#          cosgama=double(cos(gama[i]))
     372#          singama=double(sin(gama[i]))
     373#          cscgama=1.0d/singama
     374#
     375#
     376#     ; print, "W", min(wplus), max(wplus), min(wminus), max(wminus)
     377#
     378#
     379#
     380#
     381#    ;               print, a,b
     382#  ; print, "M", min(mplus), max(mplus), min(mminus), max(mminus)
     383#          Q=Q+ Wplus*Mplus + Wminus*Mminus
     384#      endfor
     385#      Q=double(num_steps)/double(num_steps-1)*Q*G
     386#   ;   print, min(q), max(q)
     387#      end
     388
     389def MultiScattering(Geometry,ElList,Tth):
     390    BN = BD = 0.0
     391    Amu = 0.0
     392    for El in ElList:
     393        el = ElList[El]
     394        BN += el['Z']*el['FormulaNo']
     395        BD += el['FormulaNo']
     396        Amu += el['FormulaNo']*el['mu']
    153397       
    154398
     
    406650    return True,smin,Rwp,runtime,GoOn
    407651
    408 def ComputePDF(data,xydata):
    409     for key in data:
    410         print key,data[key]
     652def CalcPDF(data,inst,xydata):
     653    auxPlot = []
     654    import copy
     655    import scipy.fftpack as ft
    411656    #subtract backgrounds - if any
    412     xydata['Sample corrected'] = xydata['Sample']
    413     if 'Sample Bkg.' in xydata:
    414         xydata['Sample corrected'][1][1] -= (xydata['Sample Bkg.'][1][1]+
     657    xydata['IofQ'] = copy.deepcopy(xydata['Sample'])
     658    if data['Sample Bkg.']['Name']:
     659        xydata['IofQ'][1][1] += (xydata['Sample Bkg.'][1][1]+
    415660            data['Sample Bkg.']['Add'])*data['Sample Bkg.']['Mult']
    416     if 'Container' in xydata:   
    417         xydata['Sample corrected'][1][1] -= (xydata['Container'][1][1]+
    418             data['Container']['Add'])*data['Container']['Mult']
    419     if 'Container Bkg.' in xydata:
    420         xydata['Sample corrected'][1][1] += (xydata['Container Bkg.'][1][1]+
    421             data['Container Bkg.']['Add'])*data['Container Bkg.']['Mult']
    422    
    423            
     661    if data['Container']['Name']:
     662        xycontainer = (xydata['Container'][1][1]+data['Container']['Add'])*data['Container']['Mult']
     663        if data['Container Bkg.']['Name']:
     664            xycontainer += (xydata['Container Bkg.'][1][1]+
     665                data['Container Bkg.']['Add'])*data['Container Bkg.']['Mult']
     666        xydata['IofQ'][1][1] += xycontainer
     667    #get element data & absorption coeff.
     668    ElList = data['ElList']
     669    Abs = G2lat.CellAbsorption(ElList,data['Form Vol'])
     670    #Apply angle dependent corrections
     671    Tth = xydata['Sample'][1][0]
     672    dt = (Tth[1]-Tth[0])
     673    xydata['IofQ'][1][1] /= Absorb(data['Geometry'],Abs,data['Diam'],Tth)
     674    pola = Polarization(inst['Polariz.'],Tth,Azm=inst['Azimuth'])
     675    auxPlot.append([Tth,pola,'Pola'])     
     676    xydata['IofQ'][1][1] /= pola
     677    xydata['IofQ'][1][1] *= Oblique(data['ObliqCoeff'],Tth)
     678    XY = xydata['IofQ'][1]   
     679    #convert to Q
     680    hc = 12.397639
     681    if 'Lam' in inst:
     682        wave = inst['Lam']
     683    else:
     684        wave = inst['Lam1']
     685    keV = hc/wave
     686    minQ = npT2q(Tth[0],wave)
     687    maxQ = npT2q(Tth[-1],wave)   
     688    Qpoints = np.linspace(0.,maxQ,len(XY[0]),endpoint=True)
     689    dq = Qpoints[1]-Qpoints[0]
     690    XY[0] = npT2q(XY[0],wave)
     691    Qdata = np.nan_to_num(si.griddata(XY[0],XY[1],Qpoints,method='linear'))
     692   
     693    qLimits = data['QScaleLim']
     694    minQ = np.searchsorted(Qpoints,qLimits[0])
     695    maxQ = np.searchsorted(Qpoints,qLimits[1])
     696    newdata = []
     697    xydata['IofQ'][1][0] = Qpoints
     698    xydata['IofQ'][1][1] = Qdata
     699    for item in xydata['IofQ'][1]:
     700        newdata.append(item[:maxQ])
     701    xydata['IofQ'][1] = newdata
     702   
     703
     704    xydata['SofQ'] = copy.deepcopy(xydata['IofQ'])
     705    FFSq,SqFF,CF = GetAsfMean(ElList,(xydata['SofQ'][1][0]/(4.0*np.pi))**2)  #these are <f^2>,<f>^2,Cf
     706    Q = xydata['SofQ'][1][0]
     707    ruland = Ruland(data['Ruland'],wave,Q,CF)
     708    auxPlot.append([Q,ruland,'Ruland'])     
     709    CF *= ruland
     710    auxPlot.append([Q,CF,'Compton*Ruland'])
     711    scale =       np.sum((FFSq+CF)[minQ:maxQ])/np.sum(xydata['SofQ'][1][1][minQ:maxQ])
     712    xydata['SofQ'][1][1] *= scale
     713    xydata['SofQ'][1][1] -= CF
     714    xydata['SofQ'][1][1] = xydata['SofQ'][1][1]/SqFF
     715
     716    xydata['FofQ'] = copy.deepcopy(xydata['SofQ'])
     717    xydata['FofQ'][1][1] = xydata['FofQ'][1][0]*(xydata['SofQ'][1][1]-1.0)
     718    xydata['FofQ'][1][1] *= np.sin(np.pi*(qLimits[1]-Q)/(2.0*qLimits[1]))
     719   
     720    xydata['GofR'] = copy.deepcopy(xydata['FofQ'])
     721    nR = len(xydata['GofR'][1][1])
     722    xydata['GofR'][1][1] = -dq*np.imag(ft.fft(xydata['FofQ'][1][1],4*nR)[:nR])
     723    xydata['GofR'][1][0] = 0.5*np.pi*np.linspace(0,nR,nR)/qLimits[1]
     724   
    424725       
    425     return xydata['Sample corrected'],[]
     726    return auxPlot
    426727       
  • trunk/GSASIIplot.py

    r264 r265  
    5050    def __init__(self,parent,id=-1,dpi=None,**kwargs):
    5151        wx.Panel.__init__(self,parent,id=id,**kwargs)
     52        mpl.rcParams['legend.fontsize'] = 8
    5253        self.figure = mpl.figure.Figure(dpi=dpi,figsize=(5,7))
    5354        self.canvas = Canvas(self,-1,self.figure)
     
    599600                Plot.set_ylabel('Data sequence',fontsize=12)
    600601        else:
     602            X += self.Offset*.01*N
    601603            if ifpicked:
    602604                Z = xye[3]+offset*N
     
    671673    self.Pwdr = True
    672674   
    673 def PlotSofQ(self,newPlot=False):
     675def PlotISFG(self,newPlot=False,type=''):
     676    if not type:
     677        type = self.G2plotNB.plotList[self.G2plotNB.nb.GetSelection()]
     678    if type not in ['I(Q)','S(Q)','F(Q)','G(R)']:
     679        return
    674680    superMinusOne = unichr(0xaf)+unichr(0xb9)
    675681   
     
    720726                self.Interpolate = 'nearest'
    721727            dlg.Destroy()
     728        elif event.key == 't' and not self.Contour:
     729            if self.Legend:
     730                self.Legend = False
     731            else:
     732                self.Legend = True
    722733           
    723         PlotSofQ(self,newPlot=newPlot)
     734           
     735        PlotISFG(self,newPlot=newPlot,type=type)
    724736       
    725737    def OnKeyBox(event):
    726         if self.G2plotNB.nb.GetSelection() == self.G2plotNB.plotList.index('S(Q)'):
     738        if self.G2plotNB.nb.GetSelection() == self.G2plotNB.plotList.index(type):
    727739            event.key = cb.GetValue()[0]
    728740            cb.SetValue(' key press')
     
    736748            try:
    737749                if self.Contour:
    738                     self.G2plotNB.status.SetStatusText('Q =%9.3fA pattern ID =%5d'%(xpos,int(ypos)),1)
     750                    self.G2plotNB.status.SetStatusText('R =%.3fA pattern ID =%5d'%(xpos,int(ypos)),1)
    739751                else:
    740                     self.G2plotNB.status.SetStatusText('Q =%9.3fA S(q) =%9.1f'%(xpos,ypos),1)
    741 
     752                    self.G2plotNB.status.SetStatusText('R =%.3fA %s =%.2f'%(xpos,type,ypos),1)                   
    742753            except TypeError:
    743                 self.G2plotNB.status.SetStatusText('Select S(Q) pattern first',1)
     754                self.G2plotNB.status.SetStatusText('Select '+type+' pattern first',1)
    744755   
    745756    xylim = []
    746757    try:
    747         plotNum = self.G2plotNB.plotList.index('S(Q)')
     758        plotNum = self.G2plotNB.plotList.index(type)
    748759        Page = self.G2plotNB.nb.GetPage(plotNum)
    749760        if not newPlot:
     
    755766        newPlot = True
    756767        self.Cmax = 1.0
    757         Plot = self.G2plotNB.addMpl('S(Q)').gca()
    758         plotNum = self.G2plotNB.plotList.index('S(Q)')
     768        Plot = self.G2plotNB.addMpl(type).gca()
     769        plotNum = self.G2plotNB.plotList.index(type)
    759770        Page = self.G2plotNB.nb.GetPage(plotNum)
    760771        Page.canvas.mpl_connect('key_press_event', OnPlotKeyPress)
     
    767778            'i: interpolation method','s: color scheme','c: contour off')
    768779    else:
    769         Choice = (' key press','d: offset down','u: offset up',
    770             'c: contour on','s: toggle single plot','+: no selection')
     780        Choice = (' key press','d: offset down','u: offset up','t: toggle legend',
     781            'c: contour on','s: toggle single plot')
    771782    cb = wx.ComboBox(self.G2plotNB.status,style=wx.CB_DROPDOWN|wx.CB_READONLY,
    772783        choices=Choice)
     
    775786    PatternId = self.PatternId
    776787    PickId = self.PickId
    777     Plot.set_title('S(Q)')
    778     Plot.set_xlabel(r'$Q,\AA$'+superMinusOne,fontsize=14)
    779     Plot.set_ylabel(r'S(Q)',fontsize=14)
     788    Plot.set_title(type)
     789    if type == 'G(R)':
     790        Plot.set_xlabel(r'$R,\AA$',fontsize=14)
     791    else:
     792        Plot.set_xlabel(r'$Q,\AA$'+superMinusOne,fontsize=14)
     793    Plot.set_ylabel(r''+type,fontsize=14)
    780794    colors=['b','g','r','c','m','k']
    781795    name = self.PatternTree.GetItemText(PatternId)[4:]
     
    783797    Pattern = []   
    784798    if self.SinglePlot:
    785         name = 'S(Q)'+self.PatternTree.GetItemText(PatternId)[4:]
     799        name = self.PatternTree.GetItemText(PatternId)
     800        name = type+name[4:]
    786801        Id = G2gd.GetPatternTreeItemId(self,PatternId,name)
     802        Pattern = self.PatternTree.GetItemPyData(Id)
    787803        if Pattern:
    788             Pattern = self.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(self,Id,name))
    789804            Pattern.append(name)
    790805        PlotList = [Pattern,]
    791     else:       
     806    else:
    792807        PlotList = []
    793808        item, cookie = self.PatternTree.GetFirstChild(self.root)
    794809        while item:
    795810            if 'PDF' in self.PatternTree.GetItemText(item):
    796                 name = 'S(Q)'+self.PatternTree.GetItemText(item)[4:]
    797                 print name
     811                name = type+self.PatternTree.GetItemText(item)[4:]
    798812                Id = G2gd.GetPatternTreeItemId(self,item,name)
    799813                Pattern = self.PatternTree.GetItemPyData(Id)
     
    813827        Nseq = 0
    814828    for N,Pattern in enumerate(PlotList):
    815         xye = np.array(Pattern[1])
     829        xye = Pattern[1]
    816830        if PickId:
    817831            ifpicked = Pattern[2] == self.PatternTree.GetItemText(PatternId)
     
    828842                Plot.set_ylabel('Data sequence',fontsize=12)
    829843        else:
     844            X = xye[0]+self.Offset*.1*N
    830845            if ifpicked:
    831846                Plot.plot(X,Y,colors[N%6]+'+',picker=3.,clip_on=False)
    832847                Page.canvas.SetToolTipString('')
    833848            else:
    834                 Plot.plot(X,Y,colors[N%6],picker=False)
     849                if self.Legend:
     850                    Plot.plot(X,Y,colors[N%6],picker=False,label='Azm:'+Pattern[2].split('=')[1])
     851                else:
     852                    Plot.plot(X,Y,colors[N%6],picker=False)
     853            if type == 'G(R)':
     854                Plot.axhline(0.,color=wx.BLACK)
     855            elif type == 'F(Q)':
     856                Plot.axhline(0.,color=wx.BLACK)
     857            elif type == 'S(Q)':
     858                Plot.axhline(1.,color=wx.BLACK)
    835859    if self.Contour:
    836860        acolor = mpl.cm.get_cmap(self.ContourColor)
     
    838862            extent=[ContourX[0],ContourX[-1],ContourY[0],ContourY[-1]],aspect='auto',origin='lower')
    839863        Page.figure.colorbar(Img)
     864    elif self.Legend:
     865        Plot.legend(loc='best')
    840866    if not newPlot:
    841867        Page.toolbar.push_current()
     
    847873    else:
    848874        Page.canvas.draw()
     875       
     876def PlotXY(self,XY,newPlot=False,type=''):
     877    #simple plot of xy data
    849878
    850 def PlotGofR(self,newPlot=False):
    851    
    852     def OnPlotKeyPress(event):
    853         newPlot = False
    854         if event.key == 'u':
    855             if self.Contour:
    856                 self.Cmax = min(1.0,self.Cmax*1.2)
    857             elif self.Offset < 100.:
    858                 self.Offset += 1.
    859         elif event.key == 'd':
    860             if self.Contour:
    861                 self.Cmax = max(0.0,self.Cmax*0.8)
    862             elif self.Offset > 0.:
    863                 self.Offset -= 1.
    864         elif event.key == 'c':
    865             newPlot = True
    866             if self.Contour:
    867                 self.Contour = False
    868             else:
    869                 self.Contour = True
    870                 self.SinglePlot = False
    871                 self.Offset = 0
    872         elif event.key == 's':
    873             if self.Contour:
    874                 choice = [m for m in mpl.cm.datad.keys() if not m.endswith("_r")]
    875                 dlg = wx.SingleChoiceDialog(self,'Select','Color scheme',choice)
    876                 if dlg.ShowModal() == wx.ID_OK:
    877                     sel = dlg.GetSelection()
    878                     self.ContourColor = choice[sel]
    879                 else:
    880                     self.ContourColor = 'Paired'
    881                 dlg.Destroy()
    882             else:               
    883                 if self.SinglePlot:
    884                     self.SinglePlot = False
    885                 else:
    886                     self.SinglePlot = True
    887         elif event.key == 'i':                  #for smoothing contour plot
    888             choice = ['nearest','bilinear','bicubic','spline16','spline36','hanning',
    889                'hamming','hermite','kaiser','quadric','catrom','gaussian','bessel',
    890                'mitchell','sinc','lanczos']
    891             dlg = wx.SingleChoiceDialog(self,'Select','Interpolation',choice)
    892             if dlg.ShowModal() == wx.ID_OK:
    893                 sel = dlg.GetSelection()
    894                 self.Interpolate = choice[sel]
    895             else:
    896                 self.Interpolate = 'nearest'
    897             dlg.Destroy()
    898            
    899         PlotGofR(self,newPlot=newPlot)
    900        
    901     def OnKeyBox(event):
    902         if self.G2plotNB.nb.GetSelection() == self.G2plotNB.plotList.index('G(R)'):
    903             event.key = cb.GetValue()[0]
    904             cb.SetValue(' key press')
    905             OnPlotKeyPress(event)
    906                        
    907879    def OnMotion(event):
    908880        xpos = event.xdata
     
    911883            Page.canvas.SetCursor(wx.CROSS_CURSOR)
    912884            try:
    913                 if self.Contour:
    914                     self.G2plotNB.status.SetStatusText('r =%9.3fA pattern ID =%5d'%(xpos,int(ypos)),1)
    915                 else:
    916                     self.G2plotNB.status.SetStatusText('r =%9.3fA G(r) =%9.1f'%(xpos,ypos),1)
     885                self.G2plotNB.status.SetStatusText('X =%9.3f %s =%9.3f'%(xpos,type,ypos),1)                   
     886            except TypeError:
     887                self.G2plotNB.status.SetStatusText('Select '+type+' pattern first',1)
    917888
    918             except TypeError:
    919                 self.G2plotNB.status.SetStatusText('Select G(R) pattern first',1)
    920    
    921     xylim = []
    922889    try:
    923         plotNum = self.G2plotNB.plotList.index('G(r)')
     890        plotNum = self.G2plotNB.plotList.index(type)
    924891        Page = self.G2plotNB.nb.GetPage(plotNum)
    925892        if not newPlot:
    926             Plot = Page.figure.gca()          #get previous G(R) plot & get limits
     893            Plot = Page.figure.gca()
    927894            xylim = Plot.get_xlim(),Plot.get_ylim()
    928895        Page.figure.clf()
     
    930897    except ValueError,error:
    931898        newPlot = True
    932         self.Cmax = 1.0
    933         Plot = self.G2plotNB.addMpl('G(r)').gca()
    934         plotNum = self.G2plotNB.plotList.index('G(r)')
     899        Plot = self.G2plotNB.addMpl(type).gca()
     900        plotNum = self.G2plotNB.plotList.index(type)
    935901        Page = self.G2plotNB.nb.GetPage(plotNum)
    936         Page.canvas.mpl_connect('key_press_event', OnPlotKeyPress)
    937902        Page.canvas.mpl_connect('motion_notify_event', OnMotion)
    938        
     903   
    939904    Page.SetFocus()
    940905    self.G2plotNB.status.DestroyChildren()
    941     if self.Contour:
    942         Choice = (' key press','d: lower contour max','u: raise contour max',
    943             'i: interpolation method','s: color scheme','c: contour off')
     906    Plot.set_title(type)
     907    Plot.set_xlabel(r'X',fontsize=14)
     908    Plot.set_ylabel(r''+type,fontsize=14)
     909    colors=['b','g','r','c','m','k']
     910    Ymax = 1.0
     911    lenX = 0
     912    X,Y = XY[:2]
     913    Ymax = max(Ymax,max(Y))
     914    Plot.plot(X,Y,'k',picker=False)
     915    if not newPlot:
     916        Page.toolbar.push_current()
     917        Plot.set_xlim(xylim[0])
     918        Plot.set_ylim(xylim[1])
     919        xylim = []
     920        Page.toolbar.push_current()
     921        Page.toolbar.draw()
    944922    else:
    945         Choice = (' key press','d: offset down','u: offset up',
    946             'c: contour on','s: toggle single plot','+: no selection')
    947     cb = wx.ComboBox(self.G2plotNB.status,style=wx.CB_DROPDOWN|wx.CB_READONLY,
    948         choices=Choice)
    949     cb.Bind(wx.EVT_COMBOBOX, OnKeyBox)
    950     cb.SetValue(' key press')
    951     PatternId = self.PatternId
    952     Pattern = []   
    953     if self.SinglePlot:
    954         Pattern = self.PatternTree.GetItemPyData(PatternId)
    955         Pattern.append(self.PatternTree.GetItemText(PatternId))
    956         PlotList = [Pattern,]
    957     else:       
    958         PlotList = []
    959         item, cookie = self.PatternTree.GetFirstChild(self.root)
    960         while item:
    961             if 'PDF' in self.PatternTree.GetItemText(item):
    962                 Pattern = self.PatternTree.GetItemPyData(item)
    963                 PlotList.append(Pattern)
    964             item, cookie = self.PatternTree.GetNextChild(self.root, cookie)               
    965     Plot.set_title('G(r)')
    966     Plot.set_xlabel(r'$r,\AA$',fontsize=14)
    967     Plot.set_ylabel(r'G(r)',fontsize=14)
    968     PatternId = self.PatternId
    969     Page.canvas.draw()
     923        Page.canvas.draw()
    970924
    971925def PlotPowderLines(self):
     
    11421096            Z = np.outer(np.ones(np.size(PHI)),npcosd(PSI))
    11431097            if muStrain[0] == 'isotropic':
    1144                 muiso = muStrain[1][0]*math.pi/0.018
     1098                muiso = muStrain[1][0]*math.pi/0.018      #centidegrees to radians!
    11451099                X *= muiso
    11461100                Y *= muiso
     
    11511105                    cp = abs(np.dot(xyz,axes))
    11521106                    S = muiso+muaniso*cp
    1153                     return S*xyz*math.pi/0.018
     1107                    return S*xyz*math.pi/0.018      #centidegrees to radians!
    11541108                muiso,muaniso = muStrain[1][:2]
    11551109                axes = np.inner(A,np.array(muStrain[3]))
     
    11681122                    uvw = np.inner(A.T,xyz)
    11691123                    Strm = np.array(G2spc.MustrainCoeff(uvw,SGData))
    1170                     sum = np.sqrt(np.sum(np.multiply(Shkl,Strm)))*math.pi/0.018
     1124                    sum = np.sqrt(np.sum(np.multiply(Shkl,Strm)))*math.pi/0.018      #centidegrees to radians!
    11711125                    return sum*xyz
    11721126                Shkl = np.array(muStrain[4])
     
    12091163        Page.canvas.SetToolTipString('')
    12101164        sizexy = Data['size']
     1165        azmRot = 0.
     1166        if Data['fullIntegrate']:
     1167            azmRot = Data['azmthRotate']
    12111168        if event.xdata and event.ydata:                 #avoid out of frame errors
    12121169            Page.canvas.SetCursor(wx.CROSS_CURSOR)
     
    12241181                    tth,azm = G2img.GetTthAzm(event.xdata,event.ydata,Data)
    12251182                    if 'line3' in  str(item) or 'line4' in str(item) and not Data['fullIntegrate']:
    1226                         Page.canvas.SetToolTipString('%6d deg'%(azm))
     1183                        Page.canvas.SetToolTipString('%6d deg'%(azm-azmRot))
    12271184                    elif 'line1' in  str(item) or 'line2' in str(item):
    12281185                        Page.canvas.SetToolTipString('%8.3fdeg'%(tth))                           
     
    12411198                else:
    12421199                    self.G2plotNB.status.SetFields(\
    1243                         ['','Detector 2-th =%9.3fdeg, dsp =%9.3fA, Q = %6.5fA-1, azm = %7.2fdeg, I = %6d'%(tth,dsp,Q,azm,Int)])
     1200                        ['','Detector 2-th =%9.3fdeg, dsp =%9.3fA, Q = %6.5fA-1, azm = %7.2fdeg, I = %6d'%(tth,dsp,Q,azm-azmRot,Int)])
    12441201
    12451202    def OnImPlotKeyPress(event):
     
    15251482        if Data['showLines']:
    15261483            LRAzim = Data['LRazimuth']                  #NB: integers
     1484            if Data['fullIntegrate']: LRAzim = [0,360]
     1485            Nazm = Data['outAzimuths']
     1486            delAzm = float(LRAzim[1]-LRAzim[0])/Nazm
    15271487            AzmthOff = Data['azmthOff']
    15281488            IOtth = Data['IOtth']
     
    15341494            if Data['fullIntegrate']:
    15351495                Azm = np.array(range(0,361))
     1496                AzmRot = Data['azmthRotate']
    15361497            else:
    15371498                Azm = np.array(range(LRAzim[0],LRAzim[1]+1))-AzmthOff
     1499                AzmRot = 0.0
    15381500            if ellI:
    15391501                xyI = []
     
    15531515                Plot.plot([arcxI[0],arcxO[0]],[arcyI[0],arcyO[0]],picker=3)
    15541516                Plot.plot([arcxI[-1],arcxO[-1]],[arcyI[-1],arcyO[-1]],picker=3)
     1517            if Nazm > 1:
     1518                for i in range(Nazm):
     1519                    cake = (LRAzim[0]+i*delAzm+AzmRot+720)%360
     1520                    ind = np.searchsorted(Azm,cake)
     1521                    Plot.plot([arcxI[ind],arcxO[ind]],[arcyI[ind],arcyO[ind]],color='k',dashes=(5,5))
     1522                   
    15551523        for xring,yring in Data['ring']:
    15561524            Plot.plot(xring,yring,'r+',picker=3)
     
    16531621        extent=[ysc[0],ysc[-1],xsc[-1],xsc[0]],aspect='auto')
    16541622    colorBar = Page.figure.colorbar(Img)
    1655     if Data['setRings']:
     1623    if Data['setRings'] and Data['rings']:
    16561624        rings = np.concatenate((Data['rings']),axis=0)
    16571625        for xring,yring,dsp in rings:
  • trunk/GSASIIpwdGUI.py

    r264 r265  
    10771077
    10781078def UpdatePDFGrid(self,data):
     1079    tth2q = lambda t,w:4.0*math.pi*sind(t/2.0)/w
    10791080    dataFile = self.PatternTree.GetItemText(self.PatternId)
    10801081    powName = 'PWDR'+dataFile[4:]
    10811082    powId = G2gd.GetPatternTreeItemId(self,self.root, powName)
    1082     limits = self.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(self,powId, 'Limits'))[1]
     1083    fullLimits,limits = self.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(self,powId, 'Limits'))
    10831084    inst = self.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(self,powId, 'Instrument Parameters'))
    10841085    inst = dict(zip(inst[3],inst[1]))
     
    10881089        keV = 12.397639/inst['Lam1']
    10891090    wave = 12.397639/keV
     1091    qLimits = [tth2q(fullLimits[0],wave),tth2q(fullLimits[1],wave)]
     1092    data['QScaleLim'][0] = max(qLimits[0],data['QScaleLim'][0])
     1093    data['QScaleLim'][1] = min(qLimits[1],data['QScaleLim'][1])
    10901094    polariz = inst['Polariz.']
     1095    azimuth = inst['Azimuth']
    10911096    itemDict = {}
    10921097   
     
    11011106            Obj.SetValue(fmt%(value))
    11021107            data[fileKey][itemKey] = value
     1108            UpdatePDFGrid(self,data)
    11031109       
    11041110        def OnValueChange(event):
     
    11111117            Obj.SetValue(fmt%(value))
    11121118            data[fileKey][itemKey] = value
    1113             UpdatePDFGrid(self,data)
    1114            
     1119            auxPlot = ComputePDF(data)
     1120            G2plt.PlotISFG(self,newPlot=True)
     1121                       
    11151122        item = data[key]
    11161123        fileList = np.array(GetFileList('PWDR')).T[1]
     
    11691176        UpdatePDFGrid(self,data)
    11701177       
     1178    def OnDetType(event):
     1179        data['DetType'] = detType.GetValue()
     1180        UpdatePDFGrid(self,data)
     1181       
    11711182    def OnFormVol(event):
    11721183        try:
     
    11781189        data['Form Vol'] = value
    11791190        UpdatePDFGrid(self,data)
     1191        auxPlot = ComputePDF(data)
     1192        G2plt.PlotISFG(self,newPlot=True)       
    11801193       
    11811194    def OnDiameter(event):
     
    11881201        data['Diam'] = value
    11891202        UpdatePDFGrid(self,data)
     1203        auxPlot = ComputePDF(data)
     1204        G2plt.PlotISFG(self,newPlot=True)       
     1205       
     1206    def OnObliqCoeff(event):
     1207        try:
     1208            value = float(obliqCoeff.GetValue())
     1209            if value < 0.0:
     1210                raise ValueError
     1211            elif value > 1.0:
     1212                value = 1.0
     1213        except ValueError:
     1214            value = data['ObliqCoeff']
     1215        data['ObliqCoeff'] = value
     1216        obliqCoeff.SetValue('%.3f'%(value))
     1217        auxPlot = ComputePDF(data)
     1218        G2plt.PlotISFG(self,newPlot=True)
     1219       
     1220    def OnRulandWdt(event):
     1221        try:
     1222            value = float(rulandWdt.GetValue())
     1223            if value <= 0.001:
     1224                raise ValueError
     1225            elif value > 1.0:
     1226                value = 1.0
     1227        except ValueError:
     1228            value = data['Ruland']
     1229        data['Ruland'] = value
     1230        rulandWdt.SetValue('%.3f'%(value))
     1231        auxPlot = ComputePDF(data)
     1232        G2plt.PlotISFG(self,newPlot=True)
     1233       
     1234    def OnLorch(event):
     1235        data['Lorch'] = lorch.GetValue()
     1236        auxPlot = ComputePDF(data)
     1237        G2plt.PlotISFG(self,newPlot=True)       
     1238               
    11901239       
    11911240    def OnPacking(event):
     
    11981247        data['Pack'] = value
    11991248        UpdatePDFGrid(self,data)
     1249        G2plt.PlotISFG(self,newPlot=True)       
    12001250               
     1251    def OnSQmin(event):
     1252        try:
     1253            value = float(SQmin.GetValue())
     1254            if value < qLimits[0]:
     1255                raise ValueError
     1256        except ValueError:
     1257            value = max(qLimits[0],data['QScaleLim'][0])
     1258        data['QScaleLim'][0] = value
     1259        SQmin.SetValue('%.1f'%(value))
     1260        auxPlot = ComputePDF(data)
     1261       
     1262    def OnSQmax(event):
     1263        try:
     1264            value = float(SQmax.GetValue())
     1265            if value > qLimits[1]:
     1266                raise ValueError
     1267        except ValueError:
     1268            value = min(qLimits[1],data['QScaleLim'][1])
     1269        data['QScaleLim'][1] = value
     1270        SQmax.SetValue('%.1f'%(value))
     1271        auxPlot = ComputePDF(data)
     1272        G2plt.PlotISFG(self,newPlot=True)
     1273       
     1274    def OnResetQ(event):
     1275        data['QScaleLim'][1] = qLimits[1]
     1276        SQmax.SetValue('%.1f'%(data['QScaleLim'][1]))
     1277        data['QScaleLim'][0] = 0.9*qLimits[1]
     1278        SQmin.SetValue('%.1f'%(data['QScaleLim'][0]))
     1279        auxPlot = ComputePDF(data)
     1280        G2plt.PlotISFG(self,newPlot=True)       
    12011281
    12021282    def GetFileList(fileType,skip=None):
    1203         fileList = [] #[[False,'',0]]
     1283        fileList = [[False,'',0]]
    12041284        Source = ''
    12051285        id, cookie = self.PatternTree.GetFirstChild(self.root)
     
    12201300        import copy
    12211301        TextList,Source = GetFileList('PDF',skip=self.PatternId)
    1222         if not len(TextList):
     1302        if len(TextList) == 1:
    12231303            self.ErrorDialog('Nothing to copy controls to','There must be more than one "PDF" pattern')
    12241304            return
    1225         dlg = self.CopyDialog(self,'Copy PDF controls','Copy controls from '+Source+' to:',TextList)
     1305        dlg = self.CopyDialog(self,'Copy PDF controls','Copy controls from '+Source+' to:',TextList[1:])
    12261306        try:
    12271307            if dlg.ShowModal() == wx.ID_OK:
     
    12561336                ElData.update(G2elem.GetAtomInfo(ElemSym))
    12571337                ElData.update(dict(zip(['fp','fpp','mu'],FpMu)))
     1338                ElData.update(G2elem.GetFFC5(El))
    12581339                data['ElList'][El] = ElData
    12591340            data['Form Vol'] = max(10.0,SumElementVolumes())
     
    12621343       
    12631344    def OnDeleteElement(event):
    1264         print 'Delete element'
    1265        
    1266     def OnComputePDF(event):
     1345        ElList = data['ElList']
     1346        choice = ElList.keys()
     1347        dlg = G2elem.DeleteElement(self,choice=choice)
     1348        if dlg.ShowModal() == wx.ID_OK:
     1349            del ElList[dlg.GetDeleteElement()]
     1350        dlg.Destroy()
     1351        UpdatePDFGrid(self,data)
     1352               
     1353    def ComputePDF(Data):
    12671354        xydata = {}
    12681355        for key in ['Sample','Sample Bkg.','Container','Container Bkg.']:
    1269             name = data[key]['Name']
     1356            name = Data[key]['Name']
    12701357            if name:
    12711358                xydata[key] = self.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(self,self.root,name))
    1272         SofQ,GofR = G2pk.ComputePDF(data,xydata)
    1273         if SofQ:
    1274             self.PatternTree.SetItemPyData(G2gd.GetPatternTreeItemId(self,self.PatternId,'S(Q)'+dataFile[4:]),SofQ)
    1275             G2plt.PlotSofQ(self,newPlot=True)
    1276         if GofR:
    1277             self.PatternTree.SetItemPyData(G2gd.GetPatternTreeItemId(self,self.PatternId,'G(R)'+dataFile[4:]),GofR)
    1278             G2plt.PlotGofR(self,newPlot=True)
     1359                PDFname = name
     1360        powName = xydata['Sample'][2]
     1361        powId = G2gd.GetPatternTreeItemId(self,self.root,powName)
     1362        inst = self.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(self,powId,'Instrument Parameters'))
     1363        inst = dict(zip(inst[3],inst[1]))
     1364        auxPlot = G2pk.CalcPDF(data,inst,xydata)
     1365        PDFId = G2gd.GetPatternTreeItemId(self,self.root,'PDF '+powName[4:])
     1366        self.PatternTree.SetItemPyData(G2gd.GetPatternTreeItemId(self,PDFId,'I(Q)'+powName[4:]),xydata['IofQ'])
     1367        self.PatternTree.SetItemPyData(G2gd.GetPatternTreeItemId(self,PDFId,'S(Q)'+powName[4:]),xydata['SofQ'])
     1368        self.PatternTree.SetItemPyData(G2gd.GetPatternTreeItemId(self,PDFId,'F(Q)'+powName[4:]),xydata['FofQ'])
     1369        self.PatternTree.SetItemPyData(G2gd.GetPatternTreeItemId(self,PDFId,'G(R)'+powName[4:]),xydata['GofR'])
     1370        return auxPlot
     1371       
     1372    def OnComputePDF(event):
     1373        print 'Calculating PDF:'
     1374        auxPlot = ComputePDF(data)
     1375        for plot in auxPlot:
     1376            G2plt.PlotXY(self,plot[:2],type=plot[2])
     1377       
     1378        G2plt.PlotISFG(self,newPlot=True,type='I(Q)')
     1379        G2plt.PlotISFG(self,newPlot=True,type='S(Q)')
     1380        G2plt.PlotISFG(self,newPlot=True,type='F(Q)')
     1381        G2plt.PlotISFG(self,newPlot=True,type='G(R)')
    12791382       
    12801383    def OnComputeAllPDF(event):
    1281         print 'doing all PDFs here'
     1384        print 'Calculating PDFs:'
     1385        if self.PatternTree.GetCount():
     1386            id, cookie = self.PatternTree.GetFirstChild(self.root)
     1387            while id:
     1388                Name = self.PatternTree.GetItemText(id)
     1389                if 'PDF' in Name:
     1390                    Data = self.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(self,id,'PDF Controls'))
     1391                    auxPlot = ComputePDF(Data)                   
     1392                id, cookie = self.PatternTree.GetNextChild(self.root, cookie)
     1393            G2plt.PlotISFG(self,newPlot=True,type='G(R)')
    12821394       
    12831395    def OnShowTip(self,tip):
     
    13051417    mainSizer.Add((5,5),0)
    13061418    fileSizer = wx.FlexGridSizer(3,6,5,1)
    1307     for key in ['Sample Bkg.','Container','Container Bkg.']:
     1419    select = ['Sample Bkg.','Container']
     1420    if data['Container']['Name']:
     1421        select.append('Container Bkg.')
     1422    for key in select:
    13081423        FillFileSizer(fileSizer,key)
    13091424    mainSizer.Add(fileSizer,0)
     
    13341449    geoBox = wx.BoxSizer(wx.HORIZONTAL)
    13351450    geoBox.Add(wx.StaticText(self.dataDisplay,label=' Sample geometry: '),0,wx.ALIGN_CENTER_VERTICAL)
    1336     choice = ['Cylinder','Bragg-Brentano','Tilting Flat Plate in transmission','Fixed flat plate']
     1451    choice = ['Cylinder','Bragg-Brentano','Tilting flat plate in transmission','Fixed flat plate']
    13371452    geometry = wx.ComboBox(self.dataDisplay,value=data['Geometry'],choices=choice,
    13381453            style=wx.CB_READONLY|wx.CB_DROPDOWN)
     
    13401455    geoBox.Add(geometry,0)
    13411456    geoBox.Add(wx.StaticText(self.dataDisplay,label=' Sample diameter/thickness, mm: '),0,wx.ALIGN_CENTER_VERTICAL)
    1342     diam = wx.TextCtrl(self.dataDisplay,value='%.2f'%(data['Diam']))
     1457    diam = wx.TextCtrl(self.dataDisplay,value='%.3f'%(data['Diam']))
    13431458    diam.Bind(wx.EVT_TEXT_ENTER,OnDiameter)       
    13441459    diam.Bind(wx.EVT_KILL_FOCUS,OnDiameter)
     
    13571472    mainSizer.Add((5,5),0)   
    13581473       
    1359     mainSizer.Add(wx.StaticText(parent=self.dataDisplay,label=' S(Q) corrections: '),0,wx.ALIGN_CENTER_VERTICAL)
     1474    mainSizer.Add(wx.StaticText(parent=self.dataDisplay,label=' S(Q)->F(Q)->G(R) controls: '),0,wx.ALIGN_CENTER_VERTICAL)
    13601475    mainSizer.Add((5,5),0)
    1361    
    1362    
    1363    
     1476    sqBox = wx.BoxSizer(wx.HORIZONTAL)
     1477    sqBox.Add(wx.StaticText(self.dataDisplay,label=' Detector type: '),0,wx.ALIGN_CENTER_VERTICAL)
     1478    choice = ['Image plate','Point detector']
     1479    detType = wx.ComboBox(self.dataDisplay,value=data['DetType'],choices=choice,
     1480            style=wx.CB_READONLY|wx.CB_DROPDOWN)
     1481    detType.Bind(wx.EVT_COMBOBOX, OnDetType)
     1482    sqBox.Add(detType,0)
     1483    if data['DetType'] == 'Image plate':
     1484        sqBox.Add(wx.StaticText(self.dataDisplay,label=' IP transmission coeff.: '),0,wx.ALIGN_CENTER_VERTICAL)
     1485        obliqCoeff = wx.TextCtrl(self.dataDisplay,value='%.3f'%(data['ObliqCoeff']))
     1486        obliqCoeff.Bind(wx.EVT_TEXT_ENTER,OnObliqCoeff)       
     1487        obliqCoeff.Bind(wx.EVT_KILL_FOCUS,OnObliqCoeff)
     1488        sqBox.Add(obliqCoeff,0)
     1489    sqBox.Add(wx.StaticText(self.dataDisplay,label=' Ruland width: '),0,wx.ALIGN_CENTER_VERTICAL)
     1490    rulandWdt = wx.TextCtrl(self.dataDisplay,value='%.3f'%(data['Ruland']))
     1491    rulandWdt.Bind(wx.EVT_TEXT_ENTER,OnRulandWdt)       
     1492    rulandWdt.Bind(wx.EVT_KILL_FOCUS,OnRulandWdt)
     1493    sqBox.Add(rulandWdt,0)   
     1494    mainSizer.Add(sqBox,0)
     1495   
     1496    sqBox = wx.BoxSizer(wx.HORIZONTAL)
     1497    lorch = wx.CheckBox(parent=self.dataDisplay,label='Lorch damping?')
     1498    lorch.SetValue(data['Lorch'])
     1499    lorch.Bind(wx.EVT_CHECKBOX, OnLorch)
     1500    sqBox.Add(lorch,0,wx.ALIGN_CENTER_VERTICAL)
     1501    sqBox.Add(wx.StaticText(self.dataDisplay,label=' Scaling q-range: '),0,wx.ALIGN_CENTER_VERTICAL)
     1502    SQmin = wx.TextCtrl(self.dataDisplay,value='%.1f'%(data['QScaleLim'][0]))
     1503    SQmin.Bind(wx.EVT_TEXT_ENTER,OnSQmin)       
     1504    SQmin.Bind(wx.EVT_KILL_FOCUS,OnSQmin)   
     1505    sqBox.Add(SQmin,0)
     1506    sqBox.Add(wx.StaticText(self.dataDisplay,label=' to '),0,wx.ALIGN_CENTER_VERTICAL)
     1507    SQmax = wx.TextCtrl(self.dataDisplay,value='%.1f'%(data['QScaleLim'][1]))
     1508    SQmax.Bind(wx.EVT_TEXT_ENTER,OnSQmax)       
     1509    SQmax.Bind(wx.EVT_KILL_FOCUS,OnSQmax)
     1510    sqBox.Add(SQmax,0)
     1511    resetQ = wx.CheckBox(parent=self.dataDisplay,label='Reset?')
     1512    sqBox.Add(resetQ,0)
     1513    resetQ.Bind(wx.EVT_CHECKBOX, OnResetQ)
     1514   
     1515    mainSizer.Add(sqBox,0)
     1516
    13641517    mainSizer.Layout()   
    13651518    self.dataDisplay.SetSizer(mainSizer)
Note: See TracChangeset for help on using the changeset viewer.