source: trunk/GSASIIplot.py @ 120

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

cleanup

File size: 45.8 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    print len(PlotList)
349    for Pattern in PlotList:
350        xye = Pattern[1]
351        Ymax = max(Ymax,max(xye[1]))
352    offset = self.Offset*Ymax/100.0
353    Plot.set_title('Powder Patterns')
354    Plot.set_xlabel(r'$\mathsf{2\theta}$',fontsize=14)
355    Plot.set_ylabel('Intensity',fontsize=12)
356    if self.Contour:
357        ContourZ = []
358        ContourY = []
359        Nseq = 0
360    for N,Pattern in enumerate(PlotList):
361        ifpicked = False
362        LimitId = 0
363        xye = Pattern[1]
364        if PickId:
365            ifpicked = Pattern[2] == self.PatternTree.GetItemText(PatternId)
366            LimitId = G2gd.GetPatternTreeItemId(self,PatternId, 'Limits')
367        X = xye[0]
368        Y = xye[1]+offset*N
369        if LimitId:
370            limits = self.PatternTree.GetItemPyData(LimitId)
371            Lines.append(Plot.axvline(limits[1][0],color='g',dashes=(5,5),picker=3.))   
372            Lines.append(Plot.axvline(limits[1][1],color='r',dashes=(5,5),picker=3.))                   
373        if self.Contour:
374            ContourY.append(N)
375            ContourZ.append(Y)
376            ContourX = X
377            Nseq += 1
378            Plot.set_ylabel('Data sequence',fontsize=12)
379        else:
380            if ifpicked:
381                Z = xye[3]+offset*N
382                W = xye[4]+offset*N
383                D = xye[5]+offset*N-Ymax*.02
384                if self.Weight:
385                    W2 = np.sqrt(xye[2])
386                    D *= W2-Ymax*.02
387                Plot.plot(X,Y,colors[N%6]+'+',picker=3.,clip_on=False)
388                Plot.plot(X,Z,colors[(N+1)%6],picker=False)
389                Plot.plot(X,W,colors[(N+2)%6],picker=False)
390                Plot.plot(X,D,colors[(N+3)%6],picker=False)
391                Plot.axhline(0.,color=wx.BLACK)
392                Page.canvas.SetToolTipString('')
393                if self.PatternTree.GetItemText(PickId) == 'Peak List':
394                    tip = 'On data point: Pick peak - L or R MB.On line: MB down to move'
395                    Page.canvas.SetToolTipString(tip)
396                    data = self.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(self,PatternId, 'Peak List'))
397                    for item in data:
398                        Lines.append(Plot.axvline(item[0],color=colors[N%6],picker=2.))
399                if self.PatternTree.GetItemText(PickId) == 'Limits':
400                    tip = 'On data point: Lower limit - L MB; Upper limit - R MB. On limit: MB down to move'
401                    Page.canvas.SetToolTipString(tip)
402                    data = self.LimitsTable.GetData()
403            else:
404                Plot.plot(X,Y,colors[N%6],picker=False)
405    if PickId and self.PatternTree.GetItemText(PickId) in ['Index Peak List','Unit Cells List']:
406        peaks = self.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(self,PatternId, 'Index Peak List'))
407        for peak in peaks:
408            Plot.axvline(peak[0],color='b')
409        for hkl in self.HKL:
410            Plot.axvline(hkl[5],color='r',dashes=(5,5))
411    if self.Contour:
412        acolor = mpl.cm.get_cmap('Paired')
413        Plot.imshow(ContourZ,cmap=acolor,vmin=0,vmax=Ymax,interpolation='nearest', 
414            extent=[ContourX[0],ContourX[-1],ContourY[0],ContourY[-1]],aspect='auto')
415        newPlot = True
416    else:
417        self.Lines = Lines
418    if not newPlot:
419        Page.toolbar.push_current()
420        Plot.set_xlim(xylim[0])
421        Plot.set_ylim(xylim[1])
422        xylim = []
423        Page.toolbar.push_current()
424        Page.toolbar.draw()
425    else:
426        Page.canvas.draw()
427    self.Pwdr = True
428
429def PlotPowderLines(self):
430
431    def OnMotion(event):
432        xpos = event.xdata
433        if xpos:                                        #avoid out of frame mouse position
434            Page.canvas.SetCursor(wx.CROSS_CURSOR)
435            self.G2plotNB.status.SetFields(['','2-theta =%9.3f '%(xpos,)])
436
437    try:
438        plotNum = self.G2plotNB.plotList.index('Powder Lines')
439        Page = self.G2plotNB.nb.GetPage(plotNum)
440        Page.figure.clf()
441        Plot = Page.figure.gca()
442    except ValueError,error:
443        Plot = self.G2plotNB.add('Powder Lines').gca()
444        plotNum = self.G2plotNB.plotList.index('Powder Lines')
445        Page = self.G2plotNB.nb.GetPage(plotNum)
446        Page.canvas.mpl_connect('motion_notify_event', OnMotion)
447       
448    Page.SetFocus()
449    Plot.set_title('Powder Pattern Lines')
450    Plot.set_xlabel(r'$\mathsf{2\theta}$',fontsize=14)
451    PickId = self.PickId
452    PatternId = self.PatternId
453    peaks = self.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(self,PatternId, 'Index Peak List'))
454    for peak in peaks:
455        Plot.axvline(peak[0],color='b')
456    for hkl in self.HKL:
457        Plot.axvline(hkl[5],color='r',dashes=(5,5))
458    xmin = peaks[0][0]
459    xmax = peaks[-1][0]
460    delt = xmax-xmin
461    xlim = [max(0,xmin-delt/20.),min(180.,xmax+delt/20.)]
462    Plot.set_xlim(xlim)
463    Page.canvas.draw()
464
465def PlotPeakWidths(self):
466    PatternId = self.PatternId
467    limitID = G2gd.GetPatternTreeItemId(self,PatternId, 'Limits')
468    if limitID:
469        limits = self.PatternTree.GetItemPyData(limitID)
470    else:
471        return
472    instParms = self.PatternTree.GetItemPyData( \
473        G2gd.GetPatternTreeItemId(self,PatternId, 'Instrument Parameters'))
474    if instParms[0][0] == 'PXC':
475        lam = instParms[1][1]
476        if len(instParms[1]) == 13:
477            GU,GV,GW,LX,LY = instParms[0][6:11]
478        else:
479            GU,GV,GW,LX,LY = instParms[0][4:9]
480    peakID = G2gd.GetPatternTreeItemId(self,PatternId, 'Peak List')
481    if peakID:
482        peaks = self.PatternTree.GetItemPyData(peakID)
483    else:
484        peaks = []
485   
486    try:
487        plotNum = self.G2plotNB.plotList.index('Peak Widths')
488        Page = self.G2plotNB.nb.GetPage(plotNum)
489        Page.figure.clf()
490        Plot = Page.figure.gca()
491    except ValueError,error:
492        Plot = self.G2plotNB.add('Peak Widths').gca()
493        plotNum = self.G2plotNB.plotList.index('Peak Widths')
494        Page = self.G2plotNB.nb.GetPage(plotNum)
495    Page.SetFocus()
496   
497    Page.canvas.SetToolTipString('')
498    colors=['b','g','r','c','m','k']
499    Xmin,Xmax = limits[1]
500    Xmin = min(0.5,max(Xmin,1))
501    Xmin /= 2
502    Xmax /= 2
503    nPts = 100
504    delt = (Xmax-Xmin)/nPts
505    thetas = []
506    for i in range(nPts):
507        thetas.append(Xmin+i*delt)
508    X = []
509    Y = []
510    Z = []
511    W = []
512    V = []
513    sig = lambda Th,U,V,W: 1.17741*math.sqrt(U*tand(Th)**2+V*tand(Th)+W)*math.pi/18000.
514    gam = lambda Th,X,Y: (X/cosd(Th)+Y*tand(Th))*math.pi/18000.
515    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.)
516    gamFW2 = lambda s,g: math.sqrt(s**2+(0.4654996*g)**2)+.5345004*#Ubaldo Bafile - private communication
517    for theta in thetas:
518        X.append(4.0*math.pi*sind(theta)/lam)              #q
519        s = sig(theta,GU,GV,GW)
520        g = gam(theta,LX,LY)
521        G = gamFW(g,s)
522        H = gamFW2(g,s)
523        Y.append(s/tand(theta))
524        Z.append(g/tand(theta))
525        W.append(G/tand(theta))
526        V.append(H/tand(theta))
527    Plot.set_title('Instrument and sample peak widths')
528    Plot.set_ylabel(r'$\Delta q/q, \Delta d/d$',fontsize=14)
529    Plot.set_xlabel(r'$q, \AA^{-1}$',fontsize=14)
530    Plot.plot(X,Y,color='r',label='Gaussian')
531    Plot.plot(X,Z,color='g',label='Lorentzian')
532    Plot.plot(X,W,color='b',label='G+L')
533    Plot.plot(X,V,color='k',label='G+L2')
534    X = []
535    Y = []
536    Z = []
537    W = []
538    V = []
539    for peak in peaks:
540        X.append(4.0*math.pi*sind(peak[0]/2.0)/lam)
541        s = 1.17741*math.sqrt(peak[4])*math.pi/18000.
542        g = peak[6]*math.pi/18000.
543        G = gamFW(g,s)
544        H = gamFW2(g,s)
545        Y.append(s/tand(peak[0]/2.))
546        Z.append(g/tand(peak[0]/2.))
547        W.append(G/tand(peak[0]/2.))
548        V.append(H/tand(peak[0]/2.))
549    Plot.plot(X,Y,'+',color='r',label='G peak')
550    Plot.plot(X,Z,'+',color='g',label='L peak')
551    Plot.plot(X,W,'+',color='b',label='G+L peak')
552    Plot.plot(X,V,'+',color='k',label='G+L2 peak')
553    Plot.legend(loc='best')
554    Page.canvas.draw()
555           
556def PlotExposedImage(self,newPlot=False,event=None):
557    plotNo = self.G2plotNB.nb.GetSelection()
558    if self.G2plotNB.nb.GetPageText(plotNo) == '2D Powder Image':
559        PlotImage(self,newPlot,event)
560    elif self.G2plotNB.nb.GetPageText(plotNo) == '2D Integration':
561        PlotIntegration(self,newPlot,event)
562
563def PlotImage(self,newPlot=False,event=None):
564    from matplotlib.patches import Ellipse,Arc,Circle,Polygon
565    import numpy.ma as ma
566    Dsp = lambda tth,wave: wave/(2.*sind(tth/2.))
567
568    def OnImMotion(event):
569        Data = self.PatternTree.GetItemPyData(
570            G2gd.GetPatternTreeItemId(self,self.Image, 'Image Controls'))
571        Page.canvas.SetToolTipString('')
572        size = len(self.ImageZ)
573        if event.xdata and event.ydata:                 #avoid out of frame errors
574            Page.canvas.SetCursor(wx.CROSS_CURSOR)
575            item = self.itemPicked
576            pixelSize = Data['pixelSize']
577            scalex = 1000./pixelSize[0]
578            scaley = 1000./pixelSize[1]                   
579            if item and self.PatternTree.GetItemText(self.PickId) == 'Image Controls':
580                if 'Text' in str(item):
581                    Page.canvas.SetToolTipString('%8.3f %8.3fmm'%(event.xdata,event.ydata))
582                else:
583                    xcent,ycent = Data['center']
584                    xpos = event.xdata-xcent
585                    ypos = event.ydata-ycent
586                    if 'line3' in  str(item) or 'line4' in str(item) and not Data['fullIntegrate']:
587                        ang = int(atan2d(xpos,ypos))
588                        Page.canvas.SetToolTipString('%6d deg'%(ang))
589                    elif 'line1' in  str(item) or 'line2' in str(item):
590                        tth = G2img.GetTth(event.xdata,event.ydata,Data)
591                        Page.canvas.SetToolTipString('%8.3fdeg'%(tth))                           
592            else:
593                xpos = event.xdata
594                ypos = event.ydata
595                xpix = xpos*scalex
596                ypix = ypos*scaley
597                Int = 0
598                if (0 <= xpix <= size) and (0 <= ypix <= size):
599                    Int = self.ImageZ[ypix][xpix]
600                tth,azm,dsp = G2img.GetTthAzmDsp(xpos,ypos,Data)
601                Q = 2.*math.pi/dsp
602                self.G2plotNB.status.SetFields(\
603                    ['','Detector 2-th =%9.2fdeg, dsp =%9.3fA, Q = %6.3fA-1, azm = %7.2fdeg, I = %6d'%(tth,dsp,Q,azm,Int)])
604
605    def OnImPlotKeyPress(event):
606        if self.PatternTree.GetItemText(self.PickId) == 'Masks':
607            Data = self.PatternTree.GetItemPyData(
608                G2gd.GetPatternTreeItemId(self,self.Image, 'Image Controls'))
609            Masks = self.PatternTree.GetItemPyData(
610                G2gd.GetPatternTreeItemId(self,self.Image, 'Masks'))
611            Xpos = event.xdata
612            if not Xpos:            #got point out of frame
613                return
614            Ypos = event.ydata
615            if event.key == 's':
616                print 'spot mask @ ',Xpos,Ypos
617                Masks['Points'].append([Xpos,Ypos,1.])
618            elif event.key == 'r':
619                tth = G2img.GetTth(Xpos,Ypos,Data)
620                print 'ring mask @ ',Xpos,Ypos,tth
621                Masks['Rings'].append([tth,0.1])
622            elif event.key == 'a':
623                tth,azm = G2img.GetTthAzm(Xpos,Ypos,Data)
624                azm = int(azm)               
625                print 'arc mask @ ', Xpos,Ypos
626                Masks['Arcs'].append([tth,[azm-5,azm+5],0.1])
627            elif event.key == 'p':
628                self.setPoly = True
629                Masks['Polygons'].append([])
630                print 'Polygon mask active - pick points with mouse LB'
631                print '   use RB to close when > 2 points chosen'
632                print 'Vertices can be dragged with LB down after polygon closed'
633            G2imG.UpdateMasks(self,Masks)
634        PlotImage(self)
635           
636    def OnImPick(event):
637        if self.PatternTree.GetItemText(self.PickId) not in ['Image Controls','Masks']:
638            return
639        if self.setPoly:
640            Masks = self.PatternTree.GetItemPyData(
641                G2gd.GetPatternTreeItemId(self,self.Image, 'Masks'))
642            polygon = Masks['Polygons'][-1]
643            xpos,ypos = event.mouseevent.xdata,event.mouseevent.ydata
644            if xpos and ypos:                       #point inside image
645                if len(polygon) > 2 and event.mouseevent.button == 3:
646                    x0,y0 = polygon[0]
647                    polygon.append([x0,y0])
648                    self.setPoly = False
649                else:           
650                    polygon.append([xpos,ypos])
651                G2imG.UpdateMasks(self,Masks)
652        else:
653            if self.itemPicked is not None: return
654            self.itemPicked = event.artist
655            self.mousePicked = event.mouseevent
656       
657    def OnImRelease(event):
658        PickName = self.PatternTree.GetItemText(self.PickId)
659        if PickName not in ['Image Controls','Masks']:
660            return
661        Data = self.PatternTree.GetItemPyData(
662            G2gd.GetPatternTreeItemId(self,self.Image, 'Image Controls'))
663        Masks = self.PatternTree.GetItemPyData(
664            G2gd.GetPatternTreeItemId(self,self.Image, 'Masks'))
665        pixelSize = Data['pixelSize']
666        scalex = 1000./pixelSize[0]
667        scaley = 1000./pixelSize[1]
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    if not event:                       #event from GUI TextCtrl - don't want focus to change to plot!!!
783        Page.SetFocus()
784    Plot.set_title(self.PatternTree.GetItemText(self.Image)[4:])
785    size,imagefile = self.PatternTree.GetItemPyData(self.Image)
786    if imagefile != self.oldImagefile:
787        self.ImageZ = G2IO.GetImageData(imagefile,imageOnly=True)
788        self.oldImagefile = imagefile
789    Data = self.PatternTree.GetItemPyData(
790        G2gd.GetPatternTreeItemId(self,self.Image, 'Image Controls'))
791    Masks = self.PatternTree.GetItemPyData(
792        G2gd.GetPatternTreeItemId(self,self.Image, 'Masks'))
793
794    imScale = 1
795    if len(self.ImageZ) > 1024:
796        imScale = len(self.ImageZ)/1024
797    pixelSize = Data['pixelSize']
798    scalex = 1000./pixelSize[0]
799    scaley = 1000./pixelSize[1]
800    xmax = len(self.ImageZ)
801    Xmax = len(self.ImageZ)*pixelSize[0]/1000.
802    xlim = (-0.5,Xmax-.5)
803    ylim = (Xmax-.5,-0.5,)
804    Imin,Imax = Data['range'][1]
805    acolor = mpl.cm.get_cmap(Data['color'])
806    xcent,ycent = Data['center']
807    Plot.set_xlabel('Image x-axis, mm',fontsize=12)
808    Plot.set_ylabel('Image y-axis, mm',fontsize=12)
809    #do threshold mask - "real" mask - others are just bondaries
810    Zlim = Masks['Thresholds'][1]
811    wx.BeginBusyCursor()
812    try:
813        MA = ma.masked_greater(ma.masked_less(self.ImageZ,Zlim[0]),Zlim[1])
814        MaskA = ma.getmaskarray(MA)
815        A = G2img.ImageCompress(MA,imScale)
816        AM = G2img.ImageCompress(MaskA,imScale)
817       
818        ImgM = Plot.imshow(AM,aspect='equal',cmap='Reds',
819            interpolation='nearest',vmin=0,vmax=2,extent=[0,Xmax,Xmax,0])
820        Img = Plot.imshow(A,aspect='equal',cmap=acolor,
821            interpolation='nearest',vmin=Imin,vmax=Imax,extent=[0,Xmax,Xmax,0])
822   
823        Plot.plot(xcent,ycent,'x')
824        if Data['showLines']:
825            LRAzim = Data['LRazimuth']                  #NB: integers
826            IOtth = Data['IOtth']
827            wave = Data['wavelength']
828            dspI = wave/(2.0*sind(IOtth[0]/2.0))
829            ellI = G2img.GetEllipse(dspI,Data)           #=False if dsp didn't yield an ellipse (ugh! a parabola or a hyperbola)
830            dspO = wave/(2.0*sind(IOtth[1]/2.0))
831            ellO = G2img.GetEllipse(dspO,Data)           #Ditto & more likely for outer ellipse
832            if Data['fullIntegrate']:
833                Azm = np.array(range(0,361))
834            else:
835                Azm = np.array(range(LRAzim[0],LRAzim[1]+1))
836            if ellI:
837                xyI = []
838                for azm in Azm:
839                    xyI.append(G2img.GetDetectorXY(dspI,azm,Data))
840                xyI = np.array(xyI)
841                arcxI,arcyI = xyI.T
842                Plot.plot(arcxI,arcyI,picker=3)
843            if ellO:
844                xyO = []
845                for azm in Azm:
846                    xyO.append(G2img.GetDetectorXY(dspO,azm,Data))
847                xyO = np.array(xyO)
848                arcxO,arcyO = xyO.T
849                Plot.plot(arcxO,arcyO,picker=3)
850            if ellO and ellI and not Data['fullIntegrate']:
851                Plot.plot([arcxI[0],arcxO[0]],[arcyI[0],arcyO[0]],picker=3)
852                Plot.plot([arcxI[-1],arcxO[-1]],[arcyI[-1],arcyO[-1]],picker=3)
853        for xring,yring in Data['ring']:
854            Plot.plot(xring,yring,'r+',picker=3)
855        if Data['setRings']:
856            rings = np.concatenate((Data['rings']),axis=0)
857            for xring,yring,dsp in rings:
858                Plot.plot(xring,yring,'r+')           
859        for ellipse in Data['ellipses']:
860            cent,phi,[width,height],col = ellipse
861            Plot.add_artist(Ellipse([cent[0],cent[1]],2*width,2*height,phi,ec=col,fc='none'))
862            Plot.text(cent[0],cent[1],'+',color=col,ha='center',va='center')
863        #masks - mask lines numbered after integration limit lines
864        spots = Masks['Points']
865        rings = Masks['Rings']
866        arcs = Masks['Arcs']
867        polygons = Masks['Polygons']
868        for x,y,d in spots:
869            Plot.add_artist(Circle((x,y),radius=d/2,fc='none',ec='r',picker=3))
870        self.ringList = []
871        for iring,(tth,thick) in enumerate(rings):
872            wave = Data['wavelength']
873            x1,y1 = np.hsplit(np.array(G2img.makeIdealRing(G2img.GetEllipse(Dsp(tth+thick/2.,wave),Data))),2)
874            x2,y2 = np.hsplit(np.array(G2img.makeIdealRing(G2img.GetEllipse(Dsp(tth-thick/2.,wave),Data))),2)
875            self.ringList.append([Plot.plot(x1,y1,'r',picker=3),iring,'o'])           
876            self.ringList.append([Plot.plot(x2,y2,'r',picker=3),iring,'i'])
877        self.arcList = []
878        for iarc,(tth,azm,thick) in enumerate(arcs):           
879            wave = Data['wavelength']
880            x1,y1 = np.hsplit(np.array(G2img.makeIdealRing(G2img.GetEllipse(Dsp(tth+thick/2.,wave),Data),azm)),2)
881            x2,y2 = np.hsplit(np.array(G2img.makeIdealRing(G2img.GetEllipse(Dsp(max(0.01,tth-thick/2.),wave),Data),azm)),2)
882            self.arcList.append([Plot.plot(x1,y1,'r',picker=3),iarc,'o'])           
883            self.arcList.append([Plot.plot(x2,y2,'r',picker=3),iarc,'i'])
884            self.arcList.append([Plot.plot([x1[0],x2[0]],[y1[0],y2[0]],'r',picker=3),iarc,'l'])
885            self.arcList.append([Plot.plot([x1[-1],x2[-1]],[y1[-1],y2[-1]],'r',picker=3),iarc,'u'])
886        self.polyList = []
887        for ipoly,polygon in enumerate(polygons):
888            x,y = np.hsplit(np.array(polygon),2)
889            self.polyList.append([Plot.plot(x,y,'r',picker=3),ipoly])           
890        colorBar = Page.figure.colorbar(Img)
891        Plot.set_xlim(xlim)
892        Plot.set_ylim(ylim)
893        if not newPlot:
894            Page.toolbar.push_current()
895            Plot.set_xlim(xylim[0])
896            Plot.set_ylim(xylim[1])
897            xylim = []
898            Page.toolbar.push_current()
899            Page.toolbar.draw()
900        else:
901            Page.canvas.draw()
902    finally:
903        wx.EndBusyCursor()
904       
905def PlotIntegration(self,newPlot=False,event=None):
906           
907    def OnMotion(event):
908        Page.canvas.SetToolTipString('')
909        Page.canvas.SetCursor(wx.CROSS_CURSOR)
910        azm = event.ydata
911        tth = event.xdata
912        if azm and tth:
913            self.G2plotNB.status.SetFields(\
914                ['','Detector 2-th =%9.3fdeg, azm = %7.2fdeg'%(tth,azm)])
915                               
916    try:
917        plotNum = self.G2plotNB.plotList.index('2D Integration')
918        Page = self.G2plotNB.nb.GetPage(plotNum)
919        if not newPlot:
920            Plot = Page.figure.gca()          #get previous plot & get limits
921            xylim = Plot.get_xlim(),Plot.get_ylim()
922        Page.figure.clf()
923        Plot = Page.figure.gca()          #get a fresh plot after clf()
924       
925    except ValueError,error:
926        Plot = self.G2plotNB.add('2D Integration').gca()
927        plotNum = self.G2plotNB.plotList.index('2D Integration')
928        Page = self.G2plotNB.nb.GetPage(plotNum)
929        Page.canvas.mpl_connect('motion_notify_event', OnMotion)
930        Page.views = False
931        view = False
932    if not event:
933        Page.SetFocus()
934       
935    Data = self.PatternTree.GetItemPyData(
936        G2gd.GetPatternTreeItemId(self,self.Image, 'Image Controls'))
937    image = self.Integrate[0]
938    xsc = self.Integrate[1]
939    ysc = self.Integrate[2]
940    Imin,Imax = Data['range'][1]
941    acolor = mpl.cm.get_cmap(Data['color'])
942    Plot.set_title(self.PatternTree.GetItemText(self.Image)[4:])
943    Plot.set_ylabel('azimuth',fontsize=12)
944    Plot.set_xlabel('2-theta',fontsize=12)
945    Img = Plot.imshow(image,cmap=acolor,vmin=Imin,vmax=Imax,interpolation='nearest', \
946        extent=[ysc[0],ysc[-1],xsc[-1],xsc[0]],aspect='auto')
947    colorBar = Page.figure.colorbar(Img)
948    if Data['setRings']:
949        rings = np.concatenate((Data['rings']),axis=0)
950        for xring,yring,dsp in rings:
951            x,y = G2img.GetTthAzm(xring,yring,Data)
952            Plot.plot(x,y,'r+')
953    if Data['ellipses']:           
954        for ellipse in Data['ellipses']:
955            ring = np.array(G2img.makeIdealRing(ellipse[:3])) #skip color
956            x,y = np.hsplit(ring,2)
957            tth,azm = G2img.GetTthAzm(x,y,Data)
958            Plot.plot(tth,azm,'b,')
959    if not newPlot:
960        Page.toolbar.push_current()
961        Plot.set_xlim(xylim[0])
962        Plot.set_ylim(xylim[1])
963        xylim = []
964        Page.toolbar.push_current()
965        Page.toolbar.draw()
966    else:
967        Page.canvas.draw()
968       
969       
970def PlotTRImage(self,tax,tay,taz,newPlot=False):
971    #a test plot routine - not normally used
972           
973    def OnMotion(event):
974        Page.canvas.SetToolTipString('')
975        Page.canvas.SetCursor(wx.CROSS_CURSOR)
976        azm = event.xdata
977        tth = event.ydata
978        if azm and tth:
979            self.G2plotNB.status.SetFields(\
980                ['','Detector 2-th =%9.3fdeg, azm = %7.2fdeg'%(tth,azm)])
981                               
982    try:
983        plotNum = self.G2plotNB.plotList.index('2D Transformed Powder Image')
984        Page = self.G2plotNB.nb.GetPage(plotNum)
985        if not newPlot:
986            Plot = Page.figure.gca()          #get previous plot & get limits
987            xylim = Plot.get_xlim(),Plot.get_ylim()
988        Page.figure.clf()
989        Plot = Page.figure.gca()          #get a fresh plot after clf()
990       
991    except ValueError,error:
992        Plot = self.G2plotNB.add('2D Transformed Powder Image').gca()
993        plotNum = self.G2plotNB.plotList.index('2D Transformed Powder Image')
994        Page = self.G2plotNB.nb.GetPage(plotNum)
995        Page.canvas.mpl_connect('motion_notify_event', OnMotion)
996        Page.views = False
997        view = False
998    Page.SetFocus()
999       
1000    Data = self.PatternTree.GetItemPyData(
1001        G2gd.GetPatternTreeItemId(self,self.Image, 'Image Controls'))
1002    Imin,Imax = Data['range'][1]
1003    step = (Imax-Imin)/5.
1004    V = np.arange(Imin,Imax,step)
1005    acolor = mpl.cm.get_cmap(Data['color'])
1006    Plot.set_title(self.PatternTree.GetItemText(self.Image)[4:])
1007    Plot.set_xlabel('azimuth',fontsize=12)
1008    Plot.set_ylabel('2-theta',fontsize=12)
1009    Plot.contour(tax,tay,taz,V,cmap=acolor)
1010    if Data['showLines']:
1011        IOtth = Data['IOtth']
1012        if Data['fullIntegrate']:
1013            LRAzim = [-180,180]
1014        else:
1015            LRAzim = Data['LRazimuth']                  #NB: integers
1016        Plot.plot([LRAzim[0],LRAzim[1]],[IOtth[0],IOtth[0]],picker=True)
1017        Plot.plot([LRAzim[0],LRAzim[1]],[IOtth[1],IOtth[1]],picker=True)
1018        if not Data['fullIntegrate']:
1019            Plot.plot([LRAzim[0],LRAzim[0]],[IOtth[0],IOtth[1]],picker=True)
1020            Plot.plot([LRAzim[1],LRAzim[1]],[IOtth[0],IOtth[1]],picker=True)
1021    if Data['setRings']:
1022        rings = np.concatenate((Data['rings']),axis=0)
1023        for xring,yring,dsp in rings:
1024            x,y = G2img.GetTthAzm(xring,yring,Data)
1025            Plot.plot(y,x,'r+')           
1026    if Data['ellipses']:           
1027        for ellipse in Data['ellipses']:
1028            ring = np.array(G2img.makeIdealRing(ellipse[:3])) #skip color
1029            x,y = np.hsplit(ring,2)
1030            tth,azm = G2img.GetTthAzm(x,y,Data)
1031            Plot.plot(azm,tth,'b,')
1032    if not newPlot:
1033        Page.toolbar.push_current()
1034        Plot.set_xlim(xylim[0])
1035        Plot.set_ylim(xylim[1])
1036        xylim = []
1037        Page.toolbar.push_current()
1038        Page.toolbar.draw()
1039    else:
1040        Page.canvas.draw()
1041       
1042       
Note: See TracBrowser for help on using the repository browser.