source: trunk/GSASIIplot.py @ 108

Last change on this file since 108 was 108, checked in by vondreel, 13 years ago

fix to GenHlaue?; add Hx2Rh & Rh2Hx
mod to ReadPDBPhase to use np.inner instead of np.sum
mod to ImRelease?
mods to ImageIntegrate?

File size: 45.2 KB
Line 
1import math
2import time
3import copy
4import numpy as np
5import wx
6import wx.aui
7import matplotlib as mpl
8import GSASIIpath
9import GSASIIgrid as G2gd
10import GSASIIimage as G2img
11import GSASIIIO as G2IO
12import GSASIIpwdGUI as G2pdG
13import GSASIIimgGUI as G2imG
14from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as Canvas
15from matplotlib.backends.backend_wxagg import NavigationToolbar2Wx as Toolbar
16
17# useful degree trig functions
18sind = lambda x: math.sin(x*math.pi/180.)
19cosd = lambda x: math.cos(x*math.pi/180.)
20tand = lambda x: math.tan(x*math.pi/180.)
21asind = lambda x: 180.*math.asin(x)/math.pi
22acosd = lambda x: 180.*math.acos(x)/math.pi
23atan2d = lambda x,y: 180.*math.atan2(y,x)/math.pi
24atand = lambda x: 180.*math.atan(x)/math.pi
25   
26class G2Plot(wx.Panel):
27   
28    def __init__(self,parent,id=-1,dpi=None,**kwargs):
29        wx.Panel.__init__(self,parent,id=id,**kwargs)
30        self.figure = mpl.figure.Figure(dpi=dpi,figsize=(5,7))
31        self.canvas = Canvas(self,-1,self.figure)
32        self.toolbar = Toolbar(self.canvas)
33
34        self.toolbar.Realize()
35       
36        sizer=wx.BoxSizer(wx.VERTICAL)
37        sizer.Add(self.canvas,1,wx.EXPAND)
38        sizer.Add(self.toolbar,0,wx.LEFT|wx.EXPAND)
39        self.SetSizer(sizer)
40               
41class G2PlotNoteBook(wx.Panel):
42    def __init__(self,parent,id=-1):
43        wx.Panel.__init__(self,parent,id=id)
44        #so one can't delete a plot page!!
45        self.nb = wx.aui.AuiNotebook(self, \
46            style=wx.aui.AUI_NB_DEFAULT_STYLE ^ wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB)
47        sizer = wx.BoxSizer()
48        sizer.Add(self.nb,1,wx.EXPAND)
49        self.SetSizer(sizer)
50        self.status = parent.CreateStatusBar()
51        self.status.SetFieldsCount(2)
52        self.status.SetStatusWidths([125,-1])
53        self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
54       
55        self.plotList = []
56           
57    def add(self,name=""):
58        page = G2Plot(self.nb)
59        self.nb.AddPage(page,name)
60       
61        self.plotList.append(name)
62       
63        return page.figure
64       
65    def OnPageChanged(self,event):
66        self.status.DestroyChildren()                           #get rid of special stuff on status bar
67       
68def PlotSngl(self,newPlot=False):
69    from matplotlib.patches import Circle
70
71    def OnSCMotion(event):
72        xpos = event.xdata
73        if xpos:
74            xpos = round(xpos)                                        #avoid out of frame mouse position
75            ypos = round(event.ydata)
76            zpos = Data['Layer']
77            if '100' in Data['Zone']:
78                HKLtxt = '(%3d,%3d,%3d)'%(zpos,xpos,ypos)
79            elif '010' in Data['Zone']:
80                HKLtxt = '(%3d,%3d,%3d)'%(xpos,zpos,ypos)
81            elif '001' in Data['Zone']:
82                HKLtxt = '(%3d,%3d,%3d)'%(xpos,ypos,zpos)
83            Page.canvas.SetToolTipString(HKLtxt)
84            self.G2plotNB.status.SetFields(['HKL = '+HKLtxt,''])
85               
86    def OnSCPick(event):
87        zpos = Data['Layer']
88        pos = event.artist.center
89        if '100' in Data['Zone']:
90            Page.canvas.SetToolTipString('(picked:(%3d,%3d,%3d))'%(zpos,pos[0],pos[1]))
91            hkl = [zpos,pos[0],pos[1]]
92        elif '010' in Data['Zone']:
93            Page.canvas.SetToolTipString('(picked:(%3d,%3d,%3d))'%(pos[0],zpos,pos[1]))
94            hkl = [pos[0],zpos,pos[1]]
95        elif '001' in Data['Zone']:
96            Page.canvas.SetToolTipString('(picked:(%3d,%3d,%3d))'%(pos[0],pos[1],zpos))
97            hkl = [pos[0],pos[1],zpos]
98        h,k,l = hkl
99        i = HKL.all(hkl)
100        print i
101        HKLtxt = '(%3d,%3d,%3d %10.2f %6.3f %10.2f)'%(h,k,l,Fosq,sig,Fcsq)
102        self.G2plotNB.status.SetFields(['','HKL, Fosq, sig, Fcsq = '+HKLtxt])
103                         
104       
105    def OnSCKeyPress(event):
106        print event.key
107
108    try:
109        plotNum = self.G2plotNB.plotList.index('Structure Factors')
110        Page = self.G2plotNB.nb.GetPage(plotNum)
111        if not newPlot:
112            Plot = Page.figure.gca()          #get previous powder plot & get limits
113            xylim = Plot.get_xlim(),Plot.get_ylim()
114        Page.figure.clf()
115        Plot = Page.figure.gca()          #get a fresh plot after clf()
116    except ValueError,error:
117        Plot = self.G2plotNB.add('Structure Factors').gca()
118        plotNum = self.G2plotNB.plotList.index('Structure Factors')
119        Page = self.G2plotNB.nb.GetPage(plotNum)
120        Page.canvas.mpl_connect('key_press_event', OnSCKeyPress)
121        Page.canvas.mpl_connect('pick_event', OnSCPick)
122        Page.canvas.mpl_connect('motion_notify_event', OnSCMotion)
123    Page.SetFocus()
124   
125    Plot.set_aspect(aspect='equal')
126    HKLref = self.PatternTree.GetItemPyData(self.Sngl)
127    Data = self.PatternTree.GetItemPyData( \
128        G2gd.GetPatternTreeItemId(self,self.Sngl, 'HKL Plot Controls'))
129    Type = Data['Type']           
130    scale = Data['Scale']
131    HKLmax = Data['HKLmax']
132    HKLmin = Data['HKLmin']
133    FosqMax = Data['FoMax']
134    FoMax = math.sqrt(FosqMax)
135    ifFc = Data['ifFc']
136    xlabel = ['k, h=','h, k=','h, l=']
137    ylabel = ['l','l','k']
138    zones = ['100','010','001']
139    pzone = [[1,2],[0,2],[0,1]]
140    izone = zones.index(Data['Zone'])
141    Plot.set_title(self.PatternTree.GetItemText(self.Sngl)[5:])
142    HKL = []
143    for H,Fosq,sig,Fcsq,x,x,x in HKLref:
144        HKL.append(H)
145        if H[izone] == Data['Layer']:
146            B = 0
147            if Type == 'Fosq':
148                A = scale*Fosq/FosqMax
149                B = scale*Fcsq/FosqMax
150                C = abs(A-B)
151            elif Type == 'Fo':
152                A = scale*math.sqrt(max(0,Fosq))/FoMax
153                B = scale*math.sqrt(max(0,Fcsq))/FoMax
154                C = abs(A-B)
155            elif Type == '|DFsq|/sig':
156                A = abs(Fosq-Fcsq)/(scale*sig)
157            elif Type == '|DFsq|>sig':
158                A = abs(Fosq-Fcsq)/(scale*sig)
159                if A < 1.0: A = 0                   
160            elif Type == '|DFsq|>3sig':
161                A = abs(Fosq-Fcsq)/(scale*sig)
162                if A < 3.0: A = 0                   
163            xy = (H[pzone[izone][0]],H[pzone[izone][1]])
164            if A > 0.0:
165                Plot.add_artist(Circle(xy,radius=A,ec='g',fc='w',picker=3))
166            if B:
167                Plot.add_artist(Circle(xy,radius=B,ec='b',fc='w'))
168                radius = C
169                if radius > 0:
170                    if A > B:
171                        Plot.add_artist(Circle(xy,radius=radius,ec='r',fc='r'))
172                    else:                   
173                        Plot.add_artist(Circle(xy,radius=radius,ec='g',fc='g'))
174    HKL = np.array(HKL)
175    Plot.set_xlabel(xlabel[izone]+str(Data['Layer']),fontsize=12)
176    Plot.set_ylabel(ylabel[izone],fontsize=12)
177    Plot.set_xlim((HKLmin[pzone[izone][0]],HKLmax[pzone[izone][0]]))
178    Plot.set_ylim((HKLmin[pzone[izone][1]],HKLmax[pzone[izone][1]]))
179    if not newPlot:
180        Page.toolbar.push_current()
181        Plot.set_xlim(xylim[0])
182        Plot.set_ylim(xylim[1])
183        xylim = []
184        Page.toolbar.push_current()
185        Page.toolbar.draw()
186    else:
187        Page.canvas.draw()
188       
189def PlotPatterns(self,newPlot=False):
190   
191    def OnPick(event):
192        if self.itemPicked is not None: return
193        PatternId = self.PatternId
194        PickId = self.PickId
195        pick = event.artist
196        mouse = event.mouseevent
197        xpos = pick.get_xdata()
198        ypos = pick.get_ydata()
199        ind = event.ind
200        view = Page.toolbar._views.forward()
201        if view and 'line2' in str(pick):           #apply offset only for picked powder pattern points
202            ind += np.searchsorted(xye[0],view[0][0])
203        xy = zip(xpos[ind],ypos[ind])[0]
204        if self.PatternTree.GetItemText(PickId) == 'Peak List':
205            if ind.all() != [0]:                                    #picked a data point
206                inst = self.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(self,PatternId, 'Instrument Parameters'))
207                if len(inst[1]) == 11:
208                    ins = inst[1][4:10]
209                else:
210                    ins = inst[1][6:12]   
211                sig = ins[0]*tand(xy[0]/2.0)**2+ins[1]*tand(xy[0]/2.0)+ins[2]
212                gam = ins[3]/cosd(xy[0]/2.0)+ins[4]*tand(xy[0]/2.0)           
213                data = self.PatternTree.GetItemPyData(self.PickId)
214                XY = [xy[0],0, xy[1],1, sig,0, gam,0]       #default refine intensity 1st   
215                data.append(XY)
216                G2pdG.UpdatePeakGrid(self,data)
217                PlotPatterns(self)
218            else:                                                   #picked a peak list line
219                self.itemPicked = pick
220        elif self.PatternTree.GetItemText(PickId) == 'Limits':
221            if ind.all() != [0]:                                    #picked a data point
222                LimitId = G2gd.GetPatternTreeItemId(self,PatternId, 'Limits')
223                data = self.PatternTree.GetItemPyData(LimitId)
224                if mouse.button==1:
225                    data[1][0] = min(xy[0],data[1][1])
226                if mouse.button==3:
227                    data[1][1] = max(xy[0],data[1][0])
228                self.PatternTree.SetItemPyData(LimitId,data)
229                G2pdG.UpdateLimitsGrid(self,data)
230                PlotPatterns(self)
231            else:                                                   #picked a limit line
232                self.itemPicked = pick               
233       
234    def OnPlotKeyPress(event):
235        if event.key == 'w':
236            if self.Weight:
237                self.Weight = False
238            else:
239                self.Weight = True
240            print 'plot weighting:',self.Weight
241        elif event.key == 'u' and self.Offset < 100.:
242            self.Offset += 1.
243        elif event.key == 'd' and self.Offset > 0.:
244            self.Offset -= 1.
245        elif event.key == 'c':
246            if self.Contour:
247                self.Contour = False
248            else:
249                self.Contour = True
250        elif event.key == 's':
251            if self.SinglePlot:
252                self.SinglePlot = False
253            else:
254                self.SinglePlot = True
255           
256        PlotPatterns(self)
257       
258    def OnKeyBox(event):
259        if self.G2plotNB.nb.GetSelection() == self.G2plotNB.plotList.index('Powder Patterns'):
260            event.key = cb.GetValue()[0]
261            cb.SetValue(' key press')
262            OnPlotKeyPress(event)
263                       
264    def OnMotion(event):
265        xpos = event.xdata
266        if xpos:                                        #avoid out of frame mouse position
267            ypos = event.ydata
268            Page.canvas.SetCursor(wx.CROSS_CURSOR)
269            try:
270                wave = self.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(self, \
271                    self.PatternId, 'Instrument Parameters'))[0][1]
272                dsp = 0.0
273                if abs(xpos) > 0.:                  #avoid possible singularity at beam center
274                    dsp = wave/(2.*sind(abs(xpos)/2.0))
275                self.G2plotNB.status.SetStatusText('2-theta =%9.3f d =%9.5f Intensity =%9.1f'%(xpos,dsp,ypos),1)
276                if self.itemPicked:
277                    Page.canvas.SetToolTipString('%9.3f'%(xpos))
278            except TypeError:
279                self.G2plotNB.status.SetStatusText('Select PWDR powder pattern first',1)
280                                   
281    def OnRelease(event):
282        if self.itemPicked is None: return
283        xpos = event.xdata
284        if xpos:                                        #avoid out of frame mouse position
285            lines = []
286            for line in self.Lines: lines.append(line.get_xdata()[0])
287            lineNo = lines.index(self.itemPicked.get_xdata()[0])
288            if  lineNo in [0,1]:
289                LimitId = G2gd.GetPatternTreeItemId(self,self.PatternId, 'Limits')
290                data = self.PatternTree.GetItemPyData(LimitId)
291#                print 'limits',xpos
292                data[1][lineNo] = xpos
293                self.PatternTree.SetItemPyData(LimitId,data)
294                if self.PatternTree.GetItemText(self.PickId) == 'Limits':
295                    G2pdG.UpdateLimitsGrid(self,data)
296            else:
297                PeakId = G2gd.GetPatternTreeItemId(self,self.PatternId, 'Peak List')
298                data = self.PatternTree.GetItemPyData(PeakId)
299#                print 'peaks',xpos
300                data[lineNo-2][0] = xpos
301                self.PatternTree.SetItemPyData(PeakId,data)
302                G2pdG.UpdatePeakGrid(self,data)
303        PlotPatterns(self)
304        self.itemPicked = None   
305
306    xylim = []
307    try:
308        plotNum = self.G2plotNB.plotList.index('Powder Patterns')
309        Page = self.G2plotNB.nb.GetPage(plotNum)
310        if not newPlot:
311            Plot = Page.figure.gca()          #get previous powder plot & get limits
312            xylim = Plot.get_xlim(),Plot.get_ylim()
313        Page.figure.clf()
314        Plot = Page.figure.gca()          #get a fresh plot after clf()
315    except ValueError,error:
316        newPlot = True
317        Plot = self.G2plotNB.add('Powder Patterns').gca()
318        plotNum = self.G2plotNB.plotList.index('Powder Patterns')
319        Page = self.G2plotNB.nb.GetPage(plotNum)
320        Page.canvas.mpl_connect('key_press_event', OnPlotKeyPress)
321        Page.canvas.mpl_connect('motion_notify_event', OnMotion)
322        Page.canvas.mpl_connect('pick_event', OnPick)
323        Page.canvas.mpl_connect('button_release_event', OnRelease)
324    Page.SetFocus()
325    cb = wx.ComboBox(self.G2plotNB.status,style=wx.CB_DROPDOWN|wx.CB_READONLY,
326        choices=(' key press','d: offset down','u: offset up','c: toggle contour','s: toggle single plot'))
327    cb.Bind(wx.EVT_COMBOBOX, OnKeyBox)
328    cb.SetValue(' key press')
329   
330    PickId = self.PickId
331    PatternId = self.PatternId
332    colors=['b','g','r','c','m','k']
333    Lines = []
334    if self.SinglePlot:
335        Pattern = self.PatternTree.GetItemPyData(self.PatternId)
336        Pattern.append(self.PatternTree.GetItemText(self.PatternId))
337        PlotList = [Pattern,]
338    else:       
339        PlotList = []
340        item, cookie = self.PatternTree.GetFirstChild(self.root)
341        while item:
342            if 'PWDR' in self.PatternTree.GetItemText(item):
343                Pattern = self.PatternTree.GetItemPyData(item)
344                Pattern.append(self.PatternTree.GetItemText(item))
345                PlotList.append(Pattern)
346            item, cookie = self.PatternTree.GetNextChild(self.root, cookie)               
347    Ymax = 1.0
348    for Pattern in PlotList:
349        xye = Pattern[1]
350        Ymax = max(Ymax,max(xye[1]))
351    offset = self.Offset*Ymax/100.0
352    Plot.set_title('Powder Patterns')
353    Plot.set_xlabel(r'$\mathsf{2\theta}$',fontsize=14)
354    Plot.set_ylabel('Intensity',fontsize=12)
355    if self.Contour:
356        ContourZ = []
357        ContourY = []
358        Nseq = 0
359    for N,Pattern in enumerate(PlotList):
360        ifpicked = False
361        LimitId = 0
362        xye = Pattern[1]
363        if PickId:
364            ifpicked = Pattern[2] == self.PatternTree.GetItemText(PatternId)
365            LimitId = G2gd.GetPatternTreeItemId(self,PatternId, 'Limits')
366        X = xye[0]
367        Y = xye[1]+offset*N
368        if LimitId:
369            limits = self.PatternTree.GetItemPyData(LimitId)
370            Lines.append(Plot.axvline(limits[1][0],color='g',dashes=(5,5),picker=3.))   
371            Lines.append(Plot.axvline(limits[1][1],color='r',dashes=(5,5),picker=3.))                   
372        if self.Contour:
373            ContourY.append(N)
374            ContourZ.append(Y)
375            ContourX = X
376            Nseq += 1
377            Plot.set_ylabel('Data sequence',fontsize=12)
378        else:
379            if ifpicked:
380                Z = xye[3]+offset*N
381                W = xye[4]+offset*N
382                D = xye[5]+offset*N-Ymax*.02
383                if self.Weight:
384                    W2 = np.sqrt(xye[2])
385                    D *= W2-Ymax*.02
386                Plot.plot(X,Y,colors[N%6]+'+',picker=3.,clip_on=False)
387                Plot.plot(X,Z,colors[(N+1)%6],picker=False)
388                Plot.plot(X,W,colors[(N+2)%6],picker=False)
389                Plot.plot(X,D,colors[(N+3)%6],picker=False)
390                Plot.axhline(0.,color=wx.BLACK)
391                Page.canvas.SetToolTipString('')
392                if self.PatternTree.GetItemText(PickId) == 'Peak List':
393                    tip = 'On data point: Pick peak - L or R MB.On line: MB down to move'
394                    Page.canvas.SetToolTipString(tip)
395                    data = self.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(self,PatternId, 'Peak List'))
396                    for item in data:
397                        Lines.append(Plot.axvline(item[0],color=colors[N%6],picker=2.))
398                if self.PatternTree.GetItemText(PickId) == 'Limits':
399                    tip = 'On data point: Lower limit - L MB; Upper limit - R MB. On limit: MB down to move'
400                    Page.canvas.SetToolTipString(tip)
401                    data = self.LimitsTable.GetData()
402            else:
403                Plot.plot(X,Y,colors[N%6],picker=False)
404    if PickId and self.PatternTree.GetItemText(PickId) in ['Index Peak List','Unit Cells List']:
405        peaks = self.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(self,PatternId, 'Index Peak List'))
406        for peak in peaks:
407            Plot.axvline(peak[0],color='b')
408        for hkl in self.HKL:
409            Plot.axvline(hkl[5],color='r',dashes=(5,5))
410    if self.Contour:
411        acolor = mpl.cm.get_cmap('Paired')
412        Plot.imshow(ContourZ,cmap=acolor,vmin=0,vmax=Ymax,interpolation='nearest', 
413            extent=[ContourX[0],ContourX[-1],ContourY[0],ContourY[-1]],aspect='auto')
414        newPlot = True
415    else:
416        self.Lines = Lines
417    if not newPlot:
418        Page.toolbar.push_current()
419        Plot.set_xlim(xylim[0])
420        Plot.set_ylim(xylim[1])
421        xylim = []
422        Page.toolbar.push_current()
423        Page.toolbar.draw()
424    else:
425        Page.canvas.draw()
426    self.Pwdr = True
427
428def PlotPowderLines(self):
429
430    def OnMotion(event):
431        xpos = event.xdata
432        if xpos:                                        #avoid out of frame mouse position
433            Page.canvas.SetCursor(wx.CROSS_CURSOR)
434            self.G2plotNB.status.SetFields(['','2-theta =%9.3f '%(xpos,)])
435
436    try:
437        plotNum = self.G2plotNB.plotList.index('Powder Lines')
438        Page = self.G2plotNB.nb.GetPage(plotNum)
439        Page.figure.clf()
440        Plot = Page.figure.gca()
441    except ValueError,error:
442        Plot = self.G2plotNB.add('Powder Lines').gca()
443        plotNum = self.G2plotNB.plotList.index('Powder Lines')
444        Page = self.G2plotNB.nb.GetPage(plotNum)
445        Page.canvas.mpl_connect('motion_notify_event', OnMotion)
446       
447    Page.SetFocus()
448    Plot.set_title('Powder Pattern Lines')
449    Plot.set_xlabel(r'$\mathsf{2\theta}$',fontsize=14)
450    PickId = self.PickId
451    PatternId = self.PatternId
452    peaks = self.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(self,PatternId, 'Index Peak List'))
453    for peak in peaks:
454        Plot.axvline(peak[0],color='b')
455    for hkl in self.HKL:
456        Plot.axvline(hkl[5],color='r',dashes=(5,5))
457    xmin = peaks[0][0]
458    xmax = peaks[-1][0]
459    delt = xmax-xmin
460    xlim = [max(0,xmin-delt/20.),min(180.,xmax+delt/20.)]
461    Plot.set_xlim(xlim)
462    Page.canvas.draw()
463
464def PlotPeakWidths(self):
465    PatternId = self.PatternId
466    limitID = G2gd.GetPatternTreeItemId(self,PatternId, 'Limits')
467    if limitID:
468        limits = self.PatternTree.GetItemPyData(limitID)
469    else:
470        return
471    instParms = self.PatternTree.GetItemPyData( \
472        G2gd.GetPatternTreeItemId(self,PatternId, 'Instrument Parameters'))
473    if instParms[0][0] == 'PXC':
474        lam = instParms[1][1]
475        if len(instParms[1]) == 13:
476            GU,GV,GW,LX,LY = instParms[0][6:11]
477        else:
478            GU,GV,GW,LX,LY = instParms[0][4:9]
479    peakID = G2gd.GetPatternTreeItemId(self,PatternId, 'Peak List')
480    if peakID:
481        peaks = self.PatternTree.GetItemPyData(peakID)
482    else:
483        peaks = []
484   
485    try:
486        plotNum = self.G2plotNB.plotList.index('Peak Widths')
487        Page = self.G2plotNB.nb.GetPage(plotNum)
488        Page.figure.clf()
489        Plot = Page.figure.gca()
490    except ValueError,error:
491        Plot = self.G2plotNB.add('Peak Widths').gca()
492        plotNum = self.G2plotNB.plotList.index('Peak Widths')
493        Page = self.G2plotNB.nb.GetPage(plotNum)
494    Page.SetFocus()
495   
496    Page.canvas.SetToolTipString('')
497    colors=['b','g','r','c','m','k']
498    Xmin,Xmax = limits[1]
499    Xmin = min(0.5,max(Xmin,1))
500    Xmin /= 2
501    Xmax /= 2
502    nPts = 100
503    delt = (Xmax-Xmin)/nPts
504    thetas = []
505    for i in range(nPts):
506        thetas.append(Xmin+i*delt)
507    X = []
508    Y = []
509    Z = []
510    W = []
511    V = []
512    sig = lambda Th,U,V,W: 1.17741*math.sqrt(U*tand(Th)**2+V*tand(Th)+W)*math.pi/18000.
513    gam = lambda Th,X,Y: (X/cosd(Th)+Y*tand(Th))*math.pi/18000.
514    gamFW = lambda s,g: math.exp(math.log(s**5+2.69269*s**4*g+2.42843*s**3*g**2+4.47163*s**2*g**3+0.07842*s*g**4+g**5)/5.)
515    gamFW2 = lambda s,g: math.sqrt(s**2+(0.4654996*g)**2)+.5345004*#Ubaldo Bafile - private communication
516    for theta in thetas:
517        X.append(4.0*math.pi*sind(theta)/lam)              #q
518        s = sig(theta,GU,GV,GW)
519        g = gam(theta,LX,LY)
520        G = gamFW(g,s)
521        H = gamFW2(g,s)
522        Y.append(s/tand(theta))
523        Z.append(g/tand(theta))
524        W.append(G/tand(theta))
525        V.append(H/tand(theta))
526    Plot.set_title('Instrument and sample peak widths')
527    Plot.set_ylabel(r'$\Delta q/q, \Delta d/d$',fontsize=14)
528    Plot.set_xlabel(r'$q, \AA^{-1}$',fontsize=14)
529    Plot.plot(X,Y,color='r',label='Gaussian')
530    Plot.plot(X,Z,color='g',label='Lorentzian')
531    Plot.plot(X,W,color='b',label='G+L')
532    Plot.plot(X,V,color='k',label='G+L2')
533    X = []
534    Y = []
535    Z = []
536    W = []
537    V = []
538    for peak in peaks:
539        X.append(4.0*math.pi*sind(peak[0]/2.0)/lam)
540        s = 1.17741*math.sqrt(peak[4])*math.pi/18000.
541        g = peak[6]*math.pi/18000.
542        G = gamFW(g,s)
543        H = gamFW2(g,s)
544        Y.append(s/tand(peak[0]/2.))
545        Z.append(g/tand(peak[0]/2.))
546        W.append(G/tand(peak[0]/2.))
547        V.append(H/tand(peak[0]/2.))
548    Plot.plot(X,Y,'+',color='r',label='G peak')
549    Plot.plot(X,Z,'+',color='g',label='L peak')
550    Plot.plot(X,W,'+',color='b',label='G+L peak')
551    Plot.plot(X,V,'+',color='k',label='G+L2 peak')
552    Plot.legend(loc='best')
553    Page.canvas.draw()
554           
555def PlotExposedImage(self,newPlot=False):
556    plotNo = self.G2plotNB.nb.GetSelection()
557    if self.G2plotNB.nb.GetPageText(plotNo) == '2D Powder Image':
558        PlotImage(self,newPlot)
559    elif self.G2plotNB.nb.GetPageText(plotNo) == '2D Integration':
560        PlotIntegration(self,newPlot)
561
562def PlotImage(self,newPlot=False):
563    from matplotlib.patches import Ellipse,Arc,Circle,Polygon
564    import numpy.ma as ma
565    Dsp = lambda tth,wave: wave/(2.*sind(tth/2.))
566
567    def OnImMotion(event):
568        Data = self.PatternTree.GetItemPyData(
569            G2gd.GetPatternTreeItemId(self,self.Image, 'Image Controls'))
570        Page.canvas.SetToolTipString('')
571        size = len(self.ImageZ)
572        if event.xdata and event.ydata:                 #avoid out of frame errors
573            Page.canvas.SetCursor(wx.CROSS_CURSOR)
574            item = self.itemPicked
575            pixelSize = Data['pixelSize']
576            scalex = 1000./pixelSize[0]
577            scaley = 1000./pixelSize[1]                   
578            if item and self.PatternTree.GetItemText(self.PickId) == 'Image Controls':
579                if 'Text' in str(item):
580                    Page.canvas.SetToolTipString('%8.3f %8.3fmm'%(event.xdata,event.ydata))
581                else:
582                    xcent,ycent = Data['center']
583                    xpos = event.xdata-xcent
584                    ypos = event.ydata-ycent
585                    if 'line3' in  str(item) or 'line4' in str(item) and not Data['fullIntegrate']:
586                        ang = int(atan2d(xpos,ypos))
587                        Page.canvas.SetToolTipString('%6d deg'%(ang))
588                    elif 'line1' in  str(item) or 'line2' in str(item):
589                        tth = G2img.GetTth(event.xdata,event.ydata,Data)
590                        Page.canvas.SetToolTipString('%8.3fdeg'%(tth))                           
591            else:
592                xpos = event.xdata
593                ypos = event.ydata
594                xpix = xpos*scalex
595                ypix = ypos*scaley
596                Int = 0
597                if (0 <= xpix <= size) and (0 <= ypix <= size):
598                    Int = self.ImageZ[ypix][xpix]
599                tth,azm,dsp = G2img.GetTthAzmDsp(xpos,ypos,Data)
600                Q = 2.*math.pi/dsp
601                self.G2plotNB.status.SetFields(\
602                    ['','Detector 2-th =%9.2fdeg, dsp =%9.3fA, Q = %6.3fA-1, azm = %7.2fdeg, I = %6d'%(tth,dsp,Q,azm,Int)])
603
604    def OnImPlotKeyPress(event):
605        if self.PatternTree.GetItemText(self.PickId) == 'Masks':
606            Data = self.PatternTree.GetItemPyData(
607                G2gd.GetPatternTreeItemId(self,self.Image, 'Image Controls'))
608            Masks = self.PatternTree.GetItemPyData(
609                G2gd.GetPatternTreeItemId(self,self.Image, 'Masks'))
610            Xpos = event.xdata
611            if not Xpos:            #got point out of frame
612                return
613            Ypos = event.ydata
614            if event.key == 's':
615                print 'spot mask @ ',Xpos,Ypos
616                Masks['Points'].append([Xpos,Ypos,1.])
617            elif event.key == 'r':
618                tth = G2img.GetTth(Xpos,Ypos,Data)
619                print 'ring mask @ ',Xpos,Ypos,tth
620                Masks['Rings'].append([tth,0.1])
621            elif event.key == 'a':
622                tth,azm = G2img.GetTthAzm(Xpos,Ypos,Data)
623                azm = int(azm)               
624                print 'arc mask @ ', Xpos,Ypos
625                Masks['Arcs'].append([tth,[azm-5,azm+5],0.1])
626            elif event.key == 'p':
627                self.setPoly = True
628                Masks['Polygons'].append([])
629                print 'Polygon mask active - pick points with mouse LB'
630                print '   use RB to close when > 2 points chosen'
631                print 'Vertices can be dragged with LB down after polygon closed'
632            G2imG.UpdateMasks(self,Masks)
633        PlotImage(self)
634           
635    def OnImPick(event):
636        if self.PatternTree.GetItemText(self.PickId) not in ['Image Controls','Masks']:
637            return
638        if self.setPoly:
639            Masks = self.PatternTree.GetItemPyData(
640                G2gd.GetPatternTreeItemId(self,self.Image, 'Masks'))
641            polygon = Masks['Polygons'][-1]
642            xpos,ypos = event.mouseevent.xdata,event.mouseevent.ydata
643            if xpos and ypos:                       #point inside image
644                if len(polygon) > 2 and event.mouseevent.button == 3:
645                    x0,y0 = polygon[0]
646                    polygon.append([x0,y0])
647                    self.setPoly = False
648                else:           
649                    polygon.append([xpos,ypos])
650                G2imG.UpdateMasks(self,Masks)
651        else:
652            if self.itemPicked is not None: return
653            self.itemPicked = event.artist
654            self.mousePicked = event.mouseevent
655       
656    def OnImRelease(event):
657        PickName = self.PatternTree.GetItemText(self.PickId)
658        if PickName not in ['Image Controls','Masks']:
659            return
660        Data = self.PatternTree.GetItemPyData(
661            G2gd.GetPatternTreeItemId(self,self.Image, 'Image Controls'))
662        Masks = self.PatternTree.GetItemPyData(
663            G2gd.GetPatternTreeItemId(self,self.Image, 'Masks'))
664        pixelSize = Data['pixelSize']
665        scalex = 1000./pixelSize[0]
666        scaley = 1000./pixelSize[1]
667        print self.itemPicked
668        if self.itemPicked is None and PickName == 'Image Controls':
669            size = len(self.ImageZ)
670            Xpos = event.xdata
671            if not (Xpos and self.ifGetRing):                   #got point out of frame
672                return
673            Ypos = event.ydata
674            if Ypos and not Page.toolbar._active:         #make sure zoom/pan not selected
675                if event.button == 1:
676                    Xpix = Xpos*scalex
677                    Ypix = Ypos*scaley
678                    xpos,ypos,I,J = G2img.ImageLocalMax(self.ImageZ,20,Xpix,Ypix)
679                    if I and J:
680                        xpos += .5                              #shift to pixel center
681                        ypos += .5
682                        xpos /= scalex                          #convert to mm
683                        ypos /= scaley
684                        Data['ring'].append([xpos,ypos])
685                PlotImage(self)
686            return
687        else:
688            xpos = event.xdata
689            if xpos:                                        #avoid out of frame mouse position
690                ypos = event.ydata
691                if self.ifGetRing:
692                    xypos = [xpos,ypos]
693                    rings = Data['ring']
694                    for ring in rings:
695                        if np.allclose(ring,xypos,.01,0):
696                            rings.remove(ring)                                                                       
697                else:
698                    tth,azm,dsp = G2img.GetTthAzmDsp(xpos,ypos,Data)
699                    itemPicked = str(self.itemPicked)
700                    if 'Line2D' in itemPicked and PickName == 'Image Controls':
701                        print int(itemPicked.split('_line')[1].strip(')'))
702                        if 'line1' in itemPicked:
703                            Data['IOtth'][0] = tth
704                        elif 'line2' in itemPicked:
705                            Data['IOtth'][1] = tth
706                        elif 'line3' in itemPicked and not Data['fullIntegrate']:
707                            Data['LRazimuth'][0] = int(azm)
708                        elif 'line4' in itemPicked and not Data['fullIntegrate']:
709                            Data['LRazimuth'][1] = int(azm)
710                           
711                        if Data['LRazimuth'][1] < Data['LRazimuth'][0]:
712                            Data['LRazimuth'][1] += 360
713                        if  Data['IOtth'][0] > Data['IOtth'][1]:
714                            Data['IOtth'][0],Data['IOtth'][1] = Data['IOtth'][1],Data['IOtth'][0]
715                           
716                        self.InnerTth.SetValue("%8.2f" % (Data['IOtth'][0]))
717                        self.OuterTth.SetValue("%8.2f" % (Data['IOtth'][1]))
718                        self.Lazim.SetValue("%6d" % (Data['LRazimuth'][0]))
719                        self.Razim.SetValue("%6d" % (Data['LRazimuth'][1]))
720                    elif 'Circle' in itemPicked and PickName == 'Masks':
721                        spots = Masks['Points']
722                        newPos = itemPicked.split(')')[0].split('(')[2].split(',')
723                        newPos = np.array([float(newPos[0]),float(newPos[1])])
724                        for spot in spots:
725                            if np.allclose(np.array([spot[:2]]),newPos):
726                                spot[:2] = xpos,ypos
727                        G2imG.UpdateMasks(self,Masks)
728                    elif 'Line2D' in itemPicked and PickName == 'Masks':
729                        Obj = self.itemPicked.findobj()
730                        rings = Masks['Rings']
731                        arcs = Masks['Arcs']
732                        polygons = Masks['Polygons']
733                        for ring in self.ringList:
734                            if Obj == ring[0]:
735                                rN = ring[1]
736                                if ring[2] == 'o':
737                                    rings[rN][0] = G2img.GetTth(xpos,ypos,Data)-rings[rN][1]/2.
738                                else:
739                                    rings[rN][0] = G2img.GetTth(xpos,ypos,Data)+rings[rN][1]/2.
740                        for arc in self.arcList:
741                            if Obj == arc[0]:
742                                aN = arc[1]
743                                if arc[2] == 'o':
744                                    arcs[aN][0] = G2img.GetTth(xpos,ypos,Data)-arcs[aN][2]/2
745                                elif arc[2] == 'i':
746                                    arcs[aN][0] = G2img.GetTth(xpos,ypos,Data)+arcs[aN][2]/2
747                                elif arc[2] == 'l':
748                                    arcs[aN][1][0] = int(G2img.GetAzm(xpos,ypos,Data))
749                                else:
750                                    arcs[aN][1][1] = int(G2img.GetAzm(xpos,ypos,Data))
751                        for poly in self.polyList:
752                            if Obj == poly[0]:
753                                ind = self.itemPicked.contains(self.mousePicked)[1]['ind'][0]
754                                oldPos = np.array([self.mousePicked.xdata,self.mousePicked.ydata])
755                                pN = poly[1]
756                                for i,xy in enumerate(polygons[pN]):
757                                    if np.allclose(np.array([xy]),oldPos,atol=1.0):
758                                        polygons[pN][i] = xpos,ypos
759                        G2imG.UpdateMasks(self,Masks)
760#                    else:                  #keep for future debugging
761#                        print str(self.itemPicked),event.xdata,event.ydata,event.button
762                PlotImage(self)
763            self.itemPicked = None
764           
765    try:
766        plotNum = self.G2plotNB.plotList.index('2D Powder Image')
767        Page = self.G2plotNB.nb.GetPage(plotNum)
768        if not newPlot:
769            Plot = Page.figure.gca()          #get previous powder plot & get limits
770            xylim = Plot.get_xlim(),Plot.get_ylim()
771        Page.figure.clf()
772        Plot = Page.figure.gca()          #get a fresh plot after clf()
773       
774    except ValueError,error:
775        Plot = self.G2plotNB.add('2D Powder Image').gca()
776        plotNum = self.G2plotNB.plotList.index('2D Powder Image')
777        Page = self.G2plotNB.nb.GetPage(plotNum)
778        Page.canvas.mpl_connect('key_press_event', OnImPlotKeyPress)
779        Page.canvas.mpl_connect('motion_notify_event', OnImMotion)
780        Page.canvas.mpl_connect('pick_event', OnImPick)
781        Page.canvas.mpl_connect('button_release_event', OnImRelease)
782    Page.SetFocus()
783    Plot.set_title(self.PatternTree.GetItemText(self.Image)[4:])
784    size,imagefile = self.PatternTree.GetItemPyData(self.Image)
785    if imagefile != self.oldImagefile:
786        self.ImageZ = G2IO.GetImageData(imagefile,imageOnly=True)
787        self.oldImagefile = imagefile
788    Data = self.PatternTree.GetItemPyData(
789        G2gd.GetPatternTreeItemId(self,self.Image, 'Image Controls'))
790    Masks = self.PatternTree.GetItemPyData(
791        G2gd.GetPatternTreeItemId(self,self.Image, 'Masks'))
792
793    imScale = 1
794    if len(self.ImageZ) > 1024:
795        imScale = len(self.ImageZ)/1024
796    pixelSize = Data['pixelSize']
797    scalex = 1000./pixelSize[0]
798    scaley = 1000./pixelSize[1]
799    xmax = len(self.ImageZ)
800    Xmax = len(self.ImageZ)*pixelSize[0]/1000.
801    xlim = (-0.5,Xmax-.5)
802    ylim = (Xmax-.5,-0.5,)
803    Imin,Imax = Data['range'][1]
804    acolor = mpl.cm.get_cmap(Data['color'])
805    xcent,ycent = Data['center']
806    Plot.set_xlabel('Image x-axis, mm',fontsize=12)
807    Plot.set_ylabel('Image y-axis, mm',fontsize=12)
808    #do threshold mask - "real" mask - others are just bondaries
809    Zlim = Masks['Thresholds'][1]
810    MA = ma.masked_greater(ma.masked_less(self.ImageZ,Zlim[0]),Zlim[1])
811    MaskA = ma.getmaskarray(MA)
812    A = G2img.ImageCompress(MA,imScale)
813    AM = G2img.ImageCompress(MaskA,imScale)
814   
815    ImgM = Plot.imshow(AM,aspect='equal',cmap='Reds',
816        interpolation='nearest',vmin=0,vmax=2,extent=[0,Xmax,Xmax,0])
817    Img = Plot.imshow(A,aspect='equal',cmap=acolor,
818        interpolation='nearest',vmin=Imin,vmax=Imax,extent=[0,Xmax,Xmax,0])
819
820    Plot.plot(xcent,ycent,'x')
821    if Data['showLines']:
822        LRAzim = Data['LRazimuth']                  #NB: integers
823        IOtth = Data['IOtth']
824        wave = Data['wavelength']
825        dspI = wave/(2.0*sind(IOtth[0]/2.0))
826        ellI = G2img.GetEllipse(dspI,Data)           #=False if dsp didn't yield an ellipse (ugh! a parabola or a hyperbola)
827        dspO = wave/(2.0*sind(IOtth[1]/2.0))
828        ellO = G2img.GetEllipse(dspO,Data)           #Ditto & more likely for outer ellipse
829        if Data['fullIntegrate']:
830            Azm = np.array(range(0,361))
831        else:
832            Azm = np.array(range(LRAzim[0],LRAzim[1]+1))
833        if ellI:
834            xyI = []
835            for azm in Azm:
836                xyI.append(G2img.GetDetectorXY(dspI,azm,Data))
837            xyI = np.array(xyI)
838            arcxI,arcyI = xyI.T
839            Plot.plot(arcxI,arcyI,picker=3)
840        if ellO:
841            xyO = []
842            for azm in Azm:
843                xyO.append(G2img.GetDetectorXY(dspO,azm,Data))
844            xyO = np.array(xyO)
845            arcxO,arcyO = xyO.T
846            Plot.plot(arcxO,arcyO,picker=3)
847        if ellO and ellI and not Data['fullIntegrate']:
848            Plot.plot([arcxI[0],arcxO[0]],[arcyI[0],arcyO[0]],picker=3)
849            Plot.plot([arcxI[-1],arcxO[-1]],[arcyI[-1],arcyO[-1]],picker=3)
850    for xring,yring in Data['ring']:
851        Plot.plot(xring,yring,'r+',picker=3)
852    if Data['setRings']:
853        rings = np.concatenate((Data['rings']),axis=0)
854        for xring,yring,dsp in rings:
855            Plot.plot(xring,yring,'r+')           
856    for ellipse in Data['ellipses']:
857        cent,phi,[width,height],col = ellipse
858        Plot.add_artist(Ellipse([cent[0],cent[1]],2*width,2*height,phi,ec=col,fc='none'))
859        Plot.text(cent[0],cent[1],'+',color=col,ha='center',va='center')
860    #masks - mask lines numbered after integration limit lines
861    spots = Masks['Points']
862    rings = Masks['Rings']
863    arcs = Masks['Arcs']
864    polygons = Masks['Polygons']
865    for x,y,d in spots:
866        Plot.add_artist(Circle((x,y),radius=d/2,fc='none',ec='r',picker=3))
867    self.ringList = []
868    for iring,(tth,thick) in enumerate(rings):
869        wave = Data['wavelength']
870        x1,y1 = np.hsplit(np.array(G2img.makeIdealRing(G2img.GetEllipse(Dsp(tth+thick/2.,wave),Data))),2)
871        x2,y2 = np.hsplit(np.array(G2img.makeIdealRing(G2img.GetEllipse(Dsp(tth-thick/2.,wave),Data))),2)
872        self.ringList.append([Plot.plot(x1,y1,'r',picker=3),iring,'o'])           
873        self.ringList.append([Plot.plot(x2,y2,'r',picker=3),iring,'i'])
874    self.arcList = []
875    for iarc,(tth,azm,thick) in enumerate(arcs):           
876        wave = Data['wavelength']
877        x1,y1 = np.hsplit(np.array(G2img.makeIdealRing(G2img.GetEllipse(Dsp(tth+thick/2.,wave),Data),azm)),2)
878        x2,y2 = np.hsplit(np.array(G2img.makeIdealRing(G2img.GetEllipse(Dsp(max(0.01,tth-thick/2.),wave),Data),azm)),2)
879        self.arcList.append([Plot.plot(x1,y1,'r',picker=3),iarc,'o'])           
880        self.arcList.append([Plot.plot(x2,y2,'r',picker=3),iarc,'i'])
881        self.arcList.append([Plot.plot([x1[0],x2[0]],[y1[0],y2[0]],'r',picker=3),iarc,'l'])
882        self.arcList.append([Plot.plot([x1[-1],x2[-1]],[y1[-1],y2[-1]],'r',picker=3),iarc,'u'])
883    self.polyList = []
884    for ipoly,polygon in enumerate(polygons):
885        x,y = np.hsplit(np.array(polygon),2)
886        self.polyList.append([Plot.plot(x,y,'r',picker=3),ipoly])           
887    colorBar = Page.figure.colorbar(Img)
888    Plot.set_xlim(xlim)
889    Plot.set_ylim(ylim)
890    if not newPlot:
891        Page.toolbar.push_current()
892        Plot.set_xlim(xylim[0])
893        Plot.set_ylim(xylim[1])
894        xylim = []
895        Page.toolbar.push_current()
896        Page.toolbar.draw()
897    else:
898        Page.canvas.draw()
899       
900def PlotIntegration(self,newPlot=False):
901           
902    def OnMotion(event):
903        Page.canvas.SetToolTipString('')
904        Page.canvas.SetCursor(wx.CROSS_CURSOR)
905        azm = event.ydata
906        tth = event.xdata
907        if azm and tth:
908            self.G2plotNB.status.SetFields(\
909                ['','Detector 2-th =%9.3fdeg, azm = %7.2fdeg'%(tth,azm)])
910                               
911    try:
912        plotNum = self.G2plotNB.plotList.index('2D Integration')
913        Page = self.G2plotNB.nb.GetPage(plotNum)
914        if not newPlot:
915            Plot = Page.figure.gca()          #get previous plot & get limits
916            xylim = Plot.get_xlim(),Plot.get_ylim()
917        Page.figure.clf()
918        Plot = Page.figure.gca()          #get a fresh plot after clf()
919       
920    except ValueError,error:
921        Plot = self.G2plotNB.add('2D Integration').gca()
922        plotNum = self.G2plotNB.plotList.index('2D Integration')
923        Page = self.G2plotNB.nb.GetPage(plotNum)
924        Page.canvas.mpl_connect('motion_notify_event', OnMotion)
925        Page.views = False
926        view = False
927    Page.SetFocus()
928       
929    Data = self.PatternTree.GetItemPyData(
930        G2gd.GetPatternTreeItemId(self,self.Image, 'Image Controls'))
931    image = self.Integrate[0]
932    xsc = self.Integrate[1]
933    ysc = self.Integrate[2]
934    Imin,Imax = Data['range'][1]
935    acolor = mpl.cm.get_cmap(Data['color'])
936    Plot.set_title(self.PatternTree.GetItemText(self.Image)[4:])
937    Plot.set_ylabel('azimuth',fontsize=12)
938    Plot.set_xlabel('2-theta',fontsize=12)
939    Img = Plot.imshow(image,cmap=acolor,vmin=Imin,vmax=Imax,interpolation='nearest', \
940        extent=[ysc[0],ysc[-1],xsc[-1],xsc[0]],aspect='auto')
941    colorBar = Page.figure.colorbar(Img)
942    if Data['setRings']:
943        rings = np.concatenate((Data['rings']),axis=0)
944        for xring,yring,dsp in rings:
945            x,y = G2img.GetTthAzm(xring,yring,Data)
946            Plot.plot(x,y,'r+')
947    if Data['ellipses']:           
948        for ellipse in Data['ellipses']:
949            ring = np.array(G2img.makeIdealRing(ellipse[:3])) #skip color
950            x,y = np.hsplit(ring,2)
951            tth,azm = G2img.GetTthAzm(x,y,Data)
952            Plot.plot(tth,azm,'b,')
953    if not newPlot:
954        Page.toolbar.push_current()
955        Plot.set_xlim(xylim[0])
956        Plot.set_ylim(xylim[1])
957        xylim = []
958        Page.toolbar.push_current()
959        Page.toolbar.draw()
960    else:
961        Page.canvas.draw()
962       
963       
964def PlotTRImage(self,tax,tay,taz,newPlot=False):
965    #a test plot routine - not normally used
966           
967    def OnMotion(event):
968        Page.canvas.SetToolTipString('')
969        Page.canvas.SetCursor(wx.CROSS_CURSOR)
970        azm = event.xdata
971        tth = event.ydata
972        if azm and tth:
973            self.G2plotNB.status.SetFields(\
974                ['','Detector 2-th =%9.3fdeg, azm = %7.2fdeg'%(tth,azm)])
975                               
976    try:
977        plotNum = self.G2plotNB.plotList.index('2D Transformed Powder Image')
978        Page = self.G2plotNB.nb.GetPage(plotNum)
979        if not newPlot:
980            Plot = Page.figure.gca()          #get previous plot & get limits
981            xylim = Plot.get_xlim(),Plot.get_ylim()
982        Page.figure.clf()
983        Plot = Page.figure.gca()          #get a fresh plot after clf()
984       
985    except ValueError,error:
986        Plot = self.G2plotNB.add('2D Transformed Powder Image').gca()
987        plotNum = self.G2plotNB.plotList.index('2D Transformed Powder Image')
988        Page = self.G2plotNB.nb.GetPage(plotNum)
989        Page.canvas.mpl_connect('motion_notify_event', OnMotion)
990        Page.views = False
991        view = False
992    Page.SetFocus()
993       
994    Data = self.PatternTree.GetItemPyData(
995        G2gd.GetPatternTreeItemId(self,self.Image, 'Image Controls'))
996    Imin,Imax = Data['range'][1]
997    step = (Imax-Imin)/5.
998    V = np.arange(Imin,Imax,step)
999    acolor = mpl.cm.get_cmap(Data['color'])
1000    Plot.set_title(self.PatternTree.GetItemText(self.Image)[4:])
1001    Plot.set_xlabel('azimuth',fontsize=12)
1002    Plot.set_ylabel('2-theta',fontsize=12)
1003    Plot.contour(tax,tay,taz,V,cmap=acolor)
1004    if Data['showLines']:
1005        IOtth = Data['IOtth']
1006        if Data['fullIntegrate']:
1007            LRAzim = [-180,180]
1008        else:
1009            LRAzim = Data['LRazimuth']                  #NB: integers
1010        Plot.plot([LRAzim[0],LRAzim[1]],[IOtth[0],IOtth[0]],picker=True)
1011        Plot.plot([LRAzim[0],LRAzim[1]],[IOtth[1],IOtth[1]],picker=True)
1012        if not Data['fullIntegrate']:
1013            Plot.plot([LRAzim[0],LRAzim[0]],[IOtth[0],IOtth[1]],picker=True)
1014            Plot.plot([LRAzim[1],LRAzim[1]],[IOtth[0],IOtth[1]],picker=True)
1015    if Data['setRings']:
1016        rings = np.concatenate((Data['rings']),axis=0)
1017        for xring,yring,dsp in rings:
1018            x,y = G2img.GetTthAzm(xring,yring,Data)
1019            Plot.plot(y,x,'r+')           
1020    if Data['ellipses']:           
1021        for ellipse in Data['ellipses']:
1022            ring = np.array(G2img.makeIdealRing(ellipse[:3])) #skip color
1023            x,y = np.hsplit(ring,2)
1024            tth,azm = G2img.GetTthAzm(x,y,Data)
1025            Plot.plot(azm,tth,'b,')
1026    if not newPlot:
1027        Page.toolbar.push_current()
1028        Plot.set_xlim(xylim[0])
1029        Plot.set_ylim(xylim[1])
1030        xylim = []
1031        Page.toolbar.push_current()
1032        Page.toolbar.draw()
1033    else:
1034        Page.canvas.draw()
1035       
1036       
Note: See TracBrowser for help on using the repository browser.