source: trunk/GSASIIplot.py @ 118

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

implement busy cursor for image plotting
get right focus behavior for "KILL_FOCUS"

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    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,event=None):
556    plotNo = self.G2plotNB.nb.GetSelection()
557    if self.G2plotNB.nb.GetPageText(plotNo) == '2D Powder Image':
558        PlotImage(self,newPlot,event)
559    elif self.G2plotNB.nb.GetPageText(plotNo) == '2D Integration':
560        PlotIntegration(self,newPlot,event)
561
562def PlotImage(self,newPlot=False,event=None):
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        if self.itemPicked is None and PickName == 'Image Controls':
668            size = len(self.ImageZ)
669            Xpos = event.xdata
670            if not (Xpos and self.ifGetRing):                   #got point out of frame
671                return
672            Ypos = event.ydata
673            if Ypos and not Page.toolbar._active:         #make sure zoom/pan not selected
674                if event.button == 1:
675                    Xpix = Xpos*scalex
676                    Ypix = Ypos*scaley
677                    xpos,ypos,I,J = G2img.ImageLocalMax(self.ImageZ,20,Xpix,Ypix)
678                    if I and J:
679                        xpos += .5                              #shift to pixel center
680                        ypos += .5
681                        xpos /= scalex                          #convert to mm
682                        ypos /= scaley
683                        Data['ring'].append([xpos,ypos])
684                PlotImage(self)
685            return
686        else:
687            xpos = event.xdata
688            if xpos:                                        #avoid out of frame mouse position
689                ypos = event.ydata
690                if self.ifGetRing:
691                    xypos = [xpos,ypos]
692                    rings = Data['ring']
693                    for ring in rings:
694                        if np.allclose(ring,xypos,.01,0):
695                            rings.remove(ring)                                                                       
696                else:
697                    tth,azm,dsp = G2img.GetTthAzmDsp(xpos,ypos,Data)
698                    itemPicked = str(self.itemPicked)
699                    if 'Line2D' in itemPicked and PickName == 'Image Controls':
700                        print int(itemPicked.split('_line')[1].strip(')'))
701                        if 'line1' in itemPicked:
702                            Data['IOtth'][0] = tth
703                        elif 'line2' in itemPicked:
704                            Data['IOtth'][1] = tth
705                        elif 'line3' in itemPicked and not Data['fullIntegrate']:
706                            Data['LRazimuth'][0] = int(azm)
707                        elif 'line4' in itemPicked and not Data['fullIntegrate']:
708                            Data['LRazimuth'][1] = int(azm)
709                           
710                        if Data['LRazimuth'][1] < Data['LRazimuth'][0]:
711                            Data['LRazimuth'][1] += 360
712                        if  Data['IOtth'][0] > Data['IOtth'][1]:
713                            Data['IOtth'][0],Data['IOtth'][1] = Data['IOtth'][1],Data['IOtth'][0]
714                           
715                        self.InnerTth.SetValue("%8.2f" % (Data['IOtth'][0]))
716                        self.OuterTth.SetValue("%8.2f" % (Data['IOtth'][1]))
717                        self.Lazim.SetValue("%6d" % (Data['LRazimuth'][0]))
718                        self.Razim.SetValue("%6d" % (Data['LRazimuth'][1]))
719                    elif 'Circle' in itemPicked and PickName == 'Masks':
720                        spots = Masks['Points']
721                        newPos = itemPicked.split(')')[0].split('(')[2].split(',')
722                        newPos = np.array([float(newPos[0]),float(newPos[1])])
723                        for spot in spots:
724                            if np.allclose(np.array([spot[:2]]),newPos):
725                                spot[:2] = xpos,ypos
726                        G2imG.UpdateMasks(self,Masks)
727                    elif 'Line2D' in itemPicked and PickName == 'Masks':
728                        Obj = self.itemPicked.findobj()
729                        rings = Masks['Rings']
730                        arcs = Masks['Arcs']
731                        polygons = Masks['Polygons']
732                        for ring in self.ringList:
733                            if Obj == ring[0]:
734                                rN = ring[1]
735                                if ring[2] == 'o':
736                                    rings[rN][0] = G2img.GetTth(xpos,ypos,Data)-rings[rN][1]/2.
737                                else:
738                                    rings[rN][0] = G2img.GetTth(xpos,ypos,Data)+rings[rN][1]/2.
739                        for arc in self.arcList:
740                            if Obj == arc[0]:
741                                aN = arc[1]
742                                if arc[2] == 'o':
743                                    arcs[aN][0] = G2img.GetTth(xpos,ypos,Data)-arcs[aN][2]/2
744                                elif arc[2] == 'i':
745                                    arcs[aN][0] = G2img.GetTth(xpos,ypos,Data)+arcs[aN][2]/2
746                                elif arc[2] == 'l':
747                                    arcs[aN][1][0] = int(G2img.GetAzm(xpos,ypos,Data))
748                                else:
749                                    arcs[aN][1][1] = int(G2img.GetAzm(xpos,ypos,Data))
750                        for poly in self.polyList:
751                            if Obj == poly[0]:
752                                ind = self.itemPicked.contains(self.mousePicked)[1]['ind'][0]
753                                oldPos = np.array([self.mousePicked.xdata,self.mousePicked.ydata])
754                                pN = poly[1]
755                                for i,xy in enumerate(polygons[pN]):
756                                    if np.allclose(np.array([xy]),oldPos,atol=1.0):
757                                        polygons[pN][i] = xpos,ypos
758                        G2imG.UpdateMasks(self,Masks)
759#                    else:                  #keep for future debugging
760#                        print str(self.itemPicked),event.xdata,event.ydata,event.button
761                PlotImage(self)
762            self.itemPicked = None
763           
764    try:
765        plotNum = self.G2plotNB.plotList.index('2D Powder Image')
766        Page = self.G2plotNB.nb.GetPage(plotNum)
767        if not newPlot:
768            Plot = Page.figure.gca()          #get previous powder plot & get limits
769            xylim = Plot.get_xlim(),Plot.get_ylim()
770        Page.figure.clf()
771        Plot = Page.figure.gca()          #get a fresh plot after clf()
772       
773    except ValueError,error:
774        Plot = self.G2plotNB.add('2D Powder Image').gca()
775        plotNum = self.G2plotNB.plotList.index('2D Powder Image')
776        Page = self.G2plotNB.nb.GetPage(plotNum)
777        Page.canvas.mpl_connect('key_press_event', OnImPlotKeyPress)
778        Page.canvas.mpl_connect('motion_notify_event', OnImMotion)
779        Page.canvas.mpl_connect('pick_event', OnImPick)
780        Page.canvas.mpl_connect('button_release_event', OnImRelease)
781    if not event:                       #event from GUI TextCtrl - don't want focus to change to plot!!!
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    wx.BeginBusyCursor()
811    try:
812        MA = ma.masked_greater(ma.masked_less(self.ImageZ,Zlim[0]),Zlim[1])
813        MaskA = ma.getmaskarray(MA)
814        A = G2img.ImageCompress(MA,imScale)
815        AM = G2img.ImageCompress(MaskA,imScale)
816       
817        ImgM = Plot.imshow(AM,aspect='equal',cmap='Reds',
818            interpolation='nearest',vmin=0,vmax=2,extent=[0,Xmax,Xmax,0])
819        Img = Plot.imshow(A,aspect='equal',cmap=acolor,
820            interpolation='nearest',vmin=Imin,vmax=Imax,extent=[0,Xmax,Xmax,0])
821   
822        Plot.plot(xcent,ycent,'x')
823        if Data['showLines']:
824            LRAzim = Data['LRazimuth']                  #NB: integers
825            IOtth = Data['IOtth']
826            wave = Data['wavelength']
827            dspI = wave/(2.0*sind(IOtth[0]/2.0))
828            ellI = G2img.GetEllipse(dspI,Data)           #=False if dsp didn't yield an ellipse (ugh! a parabola or a hyperbola)
829            dspO = wave/(2.0*sind(IOtth[1]/2.0))
830            ellO = G2img.GetEllipse(dspO,Data)           #Ditto & more likely for outer ellipse
831            if Data['fullIntegrate']:
832                Azm = np.array(range(0,361))
833            else:
834                Azm = np.array(range(LRAzim[0],LRAzim[1]+1))
835            if ellI:
836                xyI = []
837                for azm in Azm:
838                    xyI.append(G2img.GetDetectorXY(dspI,azm,Data))
839                xyI = np.array(xyI)
840                arcxI,arcyI = xyI.T
841                Plot.plot(arcxI,arcyI,picker=3)
842            if ellO:
843                xyO = []
844                for azm in Azm:
845                    xyO.append(G2img.GetDetectorXY(dspO,azm,Data))
846                xyO = np.array(xyO)
847                arcxO,arcyO = xyO.T
848                Plot.plot(arcxO,arcyO,picker=3)
849            if ellO and ellI and not Data['fullIntegrate']:
850                Plot.plot([arcxI[0],arcxO[0]],[arcyI[0],arcyO[0]],picker=3)
851                Plot.plot([arcxI[-1],arcxO[-1]],[arcyI[-1],arcyO[-1]],picker=3)
852        for xring,yring in Data['ring']:
853            Plot.plot(xring,yring,'r+',picker=3)
854        if Data['setRings']:
855            rings = np.concatenate((Data['rings']),axis=0)
856            for xring,yring,dsp in rings:
857                Plot.plot(xring,yring,'r+')           
858        for ellipse in Data['ellipses']:
859            cent,phi,[width,height],col = ellipse
860            Plot.add_artist(Ellipse([cent[0],cent[1]],2*width,2*height,phi,ec=col,fc='none'))
861            Plot.text(cent[0],cent[1],'+',color=col,ha='center',va='center')
862        #masks - mask lines numbered after integration limit lines
863        spots = Masks['Points']
864        rings = Masks['Rings']
865        arcs = Masks['Arcs']
866        polygons = Masks['Polygons']
867        for x,y,d in spots:
868            Plot.add_artist(Circle((x,y),radius=d/2,fc='none',ec='r',picker=3))
869        self.ringList = []
870        for iring,(tth,thick) in enumerate(rings):
871            wave = Data['wavelength']
872            x1,y1 = np.hsplit(np.array(G2img.makeIdealRing(G2img.GetEllipse(Dsp(tth+thick/2.,wave),Data))),2)
873            x2,y2 = np.hsplit(np.array(G2img.makeIdealRing(G2img.GetEllipse(Dsp(tth-thick/2.,wave),Data))),2)
874            self.ringList.append([Plot.plot(x1,y1,'r',picker=3),iring,'o'])           
875            self.ringList.append([Plot.plot(x2,y2,'r',picker=3),iring,'i'])
876        self.arcList = []
877        for iarc,(tth,azm,thick) in enumerate(arcs):           
878            wave = Data['wavelength']
879            x1,y1 = np.hsplit(np.array(G2img.makeIdealRing(G2img.GetEllipse(Dsp(tth+thick/2.,wave),Data),azm)),2)
880            x2,y2 = np.hsplit(np.array(G2img.makeIdealRing(G2img.GetEllipse(Dsp(max(0.01,tth-thick/2.),wave),Data),azm)),2)
881            self.arcList.append([Plot.plot(x1,y1,'r',picker=3),iarc,'o'])           
882            self.arcList.append([Plot.plot(x2,y2,'r',picker=3),iarc,'i'])
883            self.arcList.append([Plot.plot([x1[0],x2[0]],[y1[0],y2[0]],'r',picker=3),iarc,'l'])
884            self.arcList.append([Plot.plot([x1[-1],x2[-1]],[y1[-1],y2[-1]],'r',picker=3),iarc,'u'])
885        self.polyList = []
886        for ipoly,polygon in enumerate(polygons):
887            x,y = np.hsplit(np.array(polygon),2)
888            self.polyList.append([Plot.plot(x,y,'r',picker=3),ipoly])           
889        colorBar = Page.figure.colorbar(Img)
890        Plot.set_xlim(xlim)
891        Plot.set_ylim(ylim)
892        if not newPlot:
893            Page.toolbar.push_current()
894            Plot.set_xlim(xylim[0])
895            Plot.set_ylim(xylim[1])
896            xylim = []
897            Page.toolbar.push_current()
898            Page.toolbar.draw()
899        else:
900            Page.canvas.draw()
901    finally:
902        wx.EndBusyCursor()
903       
904def PlotIntegration(self,newPlot=False,event=None):
905           
906    def OnMotion(event):
907        Page.canvas.SetToolTipString('')
908        Page.canvas.SetCursor(wx.CROSS_CURSOR)
909        azm = event.ydata
910        tth = event.xdata
911        if azm and tth:
912            self.G2plotNB.status.SetFields(\
913                ['','Detector 2-th =%9.3fdeg, azm = %7.2fdeg'%(tth,azm)])
914                               
915    try:
916        plotNum = self.G2plotNB.plotList.index('2D Integration')
917        Page = self.G2plotNB.nb.GetPage(plotNum)
918        if not newPlot:
919            Plot = Page.figure.gca()          #get previous plot & get limits
920            xylim = Plot.get_xlim(),Plot.get_ylim()
921        Page.figure.clf()
922        Plot = Page.figure.gca()          #get a fresh plot after clf()
923       
924    except ValueError,error:
925        Plot = self.G2plotNB.add('2D Integration').gca()
926        plotNum = self.G2plotNB.plotList.index('2D Integration')
927        Page = self.G2plotNB.nb.GetPage(plotNum)
928        Page.canvas.mpl_connect('motion_notify_event', OnMotion)
929        Page.views = False
930        view = False
931    if not event:
932        Page.SetFocus()
933       
934    Data = self.PatternTree.GetItemPyData(
935        G2gd.GetPatternTreeItemId(self,self.Image, 'Image Controls'))
936    image = self.Integrate[0]
937    xsc = self.Integrate[1]
938    ysc = self.Integrate[2]
939    Imin,Imax = Data['range'][1]
940    acolor = mpl.cm.get_cmap(Data['color'])
941    Plot.set_title(self.PatternTree.GetItemText(self.Image)[4:])
942    Plot.set_ylabel('azimuth',fontsize=12)
943    Plot.set_xlabel('2-theta',fontsize=12)
944    Img = Plot.imshow(image,cmap=acolor,vmin=Imin,vmax=Imax,interpolation='nearest', \
945        extent=[ysc[0],ysc[-1],xsc[-1],xsc[0]],aspect='auto')
946    colorBar = Page.figure.colorbar(Img)
947    if Data['setRings']:
948        rings = np.concatenate((Data['rings']),axis=0)
949        for xring,yring,dsp in rings:
950            x,y = G2img.GetTthAzm(xring,yring,Data)
951            Plot.plot(x,y,'r+')
952    if Data['ellipses']:           
953        for ellipse in Data['ellipses']:
954            ring = np.array(G2img.makeIdealRing(ellipse[:3])) #skip color
955            x,y = np.hsplit(ring,2)
956            tth,azm = G2img.GetTthAzm(x,y,Data)
957            Plot.plot(tth,azm,'b,')
958    if not newPlot:
959        Page.toolbar.push_current()
960        Plot.set_xlim(xylim[0])
961        Plot.set_ylim(xylim[1])
962        xylim = []
963        Page.toolbar.push_current()
964        Page.toolbar.draw()
965    else:
966        Page.canvas.draw()
967       
968       
969def PlotTRImage(self,tax,tay,taz,newPlot=False):
970    #a test plot routine - not normally used
971           
972    def OnMotion(event):
973        Page.canvas.SetToolTipString('')
974        Page.canvas.SetCursor(wx.CROSS_CURSOR)
975        azm = event.xdata
976        tth = event.ydata
977        if azm and tth:
978            self.G2plotNB.status.SetFields(\
979                ['','Detector 2-th =%9.3fdeg, azm = %7.2fdeg'%(tth,azm)])
980                               
981    try:
982        plotNum = self.G2plotNB.plotList.index('2D Transformed Powder Image')
983        Page = self.G2plotNB.nb.GetPage(plotNum)
984        if not newPlot:
985            Plot = Page.figure.gca()          #get previous plot & get limits
986            xylim = Plot.get_xlim(),Plot.get_ylim()
987        Page.figure.clf()
988        Plot = Page.figure.gca()          #get a fresh plot after clf()
989       
990    except ValueError,error:
991        Plot = self.G2plotNB.add('2D Transformed Powder Image').gca()
992        plotNum = self.G2plotNB.plotList.index('2D Transformed Powder Image')
993        Page = self.G2plotNB.nb.GetPage(plotNum)
994        Page.canvas.mpl_connect('motion_notify_event', OnMotion)
995        Page.views = False
996        view = False
997    Page.SetFocus()
998       
999    Data = self.PatternTree.GetItemPyData(
1000        G2gd.GetPatternTreeItemId(self,self.Image, 'Image Controls'))
1001    Imin,Imax = Data['range'][1]
1002    step = (Imax-Imin)/5.
1003    V = np.arange(Imin,Imax,step)
1004    acolor = mpl.cm.get_cmap(Data['color'])
1005    Plot.set_title(self.PatternTree.GetItemText(self.Image)[4:])
1006    Plot.set_xlabel('azimuth',fontsize=12)
1007    Plot.set_ylabel('2-theta',fontsize=12)
1008    Plot.contour(tax,tay,taz,V,cmap=acolor)
1009    if Data['showLines']:
1010        IOtth = Data['IOtth']
1011        if Data['fullIntegrate']:
1012            LRAzim = [-180,180]
1013        else:
1014            LRAzim = Data['LRazimuth']                  #NB: integers
1015        Plot.plot([LRAzim[0],LRAzim[1]],[IOtth[0],IOtth[0]],picker=True)
1016        Plot.plot([LRAzim[0],LRAzim[1]],[IOtth[1],IOtth[1]],picker=True)
1017        if not Data['fullIntegrate']:
1018            Plot.plot([LRAzim[0],LRAzim[0]],[IOtth[0],IOtth[1]],picker=True)
1019            Plot.plot([LRAzim[1],LRAzim[1]],[IOtth[0],IOtth[1]],picker=True)
1020    if Data['setRings']:
1021        rings = np.concatenate((Data['rings']),axis=0)
1022        for xring,yring,dsp in rings:
1023            x,y = G2img.GetTthAzm(xring,yring,Data)
1024            Plot.plot(y,x,'r+')           
1025    if Data['ellipses']:           
1026        for ellipse in Data['ellipses']:
1027            ring = np.array(G2img.makeIdealRing(ellipse[:3])) #skip color
1028            x,y = np.hsplit(ring,2)
1029            tth,azm = G2img.GetTthAzm(x,y,Data)
1030            Plot.plot(azm,tth,'b,')
1031    if not newPlot:
1032        Page.toolbar.push_current()
1033        Plot.set_xlim(xylim[0])
1034        Plot.set_ylim(xylim[1])
1035        xylim = []
1036        Page.toolbar.push_current()
1037        Page.toolbar.draw()
1038    else:
1039        Page.canvas.draw()
1040       
1041       
Note: See TracBrowser for help on using the repository browser.