Changeset 3288 for trunk/GSASIIplot.py


Ignore:
Timestamp:
Feb 16, 2018 3:22:26 PM (5 years ago)
Author:
toby
Message:

Add plot magnification; misc plot fixes

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIplot.py

    r3286 r3288  
    550550                  'Shrink X','Expand Y','Shrink Y'):
    551551        arrows[direc] = wx.NewId()
     552       
    552553    def __init__(self,plotCanvas):
    553554        '''Adds additional icons to toolbar'''
     555        # try to remove a button from the bar
     556        POS_CONFIG_SPLTS_BTN = 6 # position of button to remove
     557        try:
     558            self.toolitems = self.toolitems[:POS_CONFIG_SPLTS_BTN]+self.toolitems[POS_CONFIG_SPLTS_BTN+1:]
     559            deleted = True
     560        except:
     561            deleted = False
    554562        Toolbar.__init__(self,plotCanvas)
    555563        G2path = os.path.split(os.path.abspath(__file__))[0]
     564        self.updateActions = None # defines a call to be made as part of plot updates
    556565        self.plotCanvas = plotCanvas
    557         POSITION_OF_CONFIGURE_SUBPLOTS_BTN = 6 # remove one button, nos. start at 1!
    558         self.DeleteToolByPos(POSITION_OF_CONFIGURE_SUBPLOTS_BTN)    #doesn't work in miniconda
     566        # 2nd try to remove a button from the bar
     567        if not deleted: self.DeleteToolByPos(POS_CONFIG_SPLTS_BTN) #doesn't work in some wxpython versions
    559568        self.parent = self.GetParent()
    560569        key = os.path.join(G2path,'key.ico')
     
    586595                button = self.AddSimpleTool(self.arrows[direc],_load_bitmap(icon),direc,'Zoom: '+direc)
    587596            wx.EVT_TOOL.Bind(self,self.arrows[direc],button.GetId(),self.OnArrow)
    588            
     597
     598    def _update_view(self):
     599        '''Overrides the post-buttonbar update action to invoke a redraw; needed for plot magnification
     600        '''
     601        if self.updateActions:
     602            wx.CallAfter(*self.updateActions)
     603        Toolbar._update_view(self)
     604
    589605    def OnArrow(self,event):
    590606        'reposition limits to scan or zoom by button press'
     
    633649        self.parent.toolbar.draw()
    634650#        self.parent.toolbar.push_current()
     651        if self.updateActions:
     652            wx.CallAfter(*self.updateActions)
    635653       
    636654    def OnHelp(self,event):
     
    646664        parent = self.GetParent()
    647665        if parent.Choice:
    648             dlg = wx.SingleChoiceDialog(parent,'Select','Key press',list(parent.Choice))
     666            # remove the 1st entry in list if key press
     667            if 'key press' in parent.Choice[0].lower():
     668                choices = list(parent.Choice[1:])
     669            else:
     670                choices = list(parent.Choice)
     671            dlg = wx.SingleChoiceDialog(parent,'Select a keyboard command',
     672                                        'Key press list',choices)
    649673            if dlg.ShowModal() == wx.ID_OK:
    650674                sel = dlg.GetSelection()
    651                 event.key = parent.Choice[sel][0]
     675                event.key = choices[sel][0]
    652676                if event.key != ' ':
    653677                    parent.keyPress(event)
     
    655679                    dlg.Destroy()
    656680                    G2G.G2MessageBox(self.TopLevelParent,
    657                                      'Use this command from the keyboard',
     681                                     'Use this command only from the keyboard',
    658682                                     'Key not in menu')
    659683                    return
     
    15271551                G2frame.plotStyle['qPlot'] = False
    15281552                G2frame.plotStyle['dPlot'] = False
    1529         # elif event.key == 'a' and 'PWDR' in plottype and G2frame.SinglePlot and not (
    1530         #         G2frame.logPlot or G2frame.plotStyle['sqrtPlot'] or G2frame.Contour):
    1531         #     xpos = event.xdata
    1532         #     if xpos is None: return  #avoid out of frame mouse position
    1533         #     ypos = event.ydata
    1534         #     print('event',xpos)
     1553        elif event.key == 'a' and 'PWDR' in plottype and G2frame.SinglePlot and not (
     1554                 G2frame.logPlot or G2frame.plotStyle['sqrtPlot'] or G2frame.Contour):
     1555            # add a magnification region
     1556            try:
     1557                xpos = event.xdata
     1558                if xpos is None: return  #avoid out of frame mouse position
     1559                if 'Magnification' not in Pattern[0]:
     1560                    Pattern[0]['Magnification'] = []
     1561                try:
     1562                    if G2frame.plotStyle['qPlot']:
     1563                        xpos = G2lat.Dsp2pos(Parms,2.0*np.pi/xpos)
     1564                    elif G2frame.plotStyle['dPlot']:
     1565                        xpos = G2lat.Dsp2pos(Parms,xpos)
     1566                except ValueError:
     1567                    return
     1568            except AttributeError: # invoked when this is called from dialog rather than key press
     1569                xpos = (Pattern[1][0][-1]+Pattern[1][0][0])/2 # set to middle of pattern
     1570            if not Pattern[0]['Magnification']:
     1571                Pattern[0]['Magnification'] = [[None,1.]]
     1572            Pattern[0]['Magnification'] += [[xpos,2.]]
     1573            wx.CallAfter(G2gd.UpdatePWHKPlot,G2frame,plottype,G2frame.PatternId)
     1574            return
    15351575        elif event.key == 'q':
    15361576            newPlot = True
     
    18061846            ypos = pick.get_ydata()
    18071847            ind = event.ind
    1808             xy = list(zip(np.take(xpos,ind),np.take(ypos,ind)))[0]
     1848            xy = list(zip(np.take(xpos,ind),np.take(ypos,ind))[0])
    18091849            # convert from plot units
    18101850            if G2frame.plotStyle['qPlot']:                              #qplot - convert back to 2-theta
     
    18901930                Page.diffOffset = Pattern[0]['delOffset']
    18911931                G2frame.cid = Page.canvas.mpl_connect('motion_notify_event', OnDragDiffCurve)
     1932            elif G2frame.itemPicked in G2frame.MagLines: # drag of magnification marker
     1933                pick.set_dashes((1,4)) # set line as dotted sparse
     1934                Page.canvas.draw() # refresh without dotted line & save bitmap
     1935                savedplot = Page.canvas.copy_from_bbox(Page.figure.gca().bbox)
     1936                G2frame.cid = Page.canvas.mpl_connect('motion_notify_event', OnDragLine)
     1937                pick.set_dashes((1,1)) # back to dotted
    18921938            else:                         # pick of plot tick mark (is anything else possible?)
    18931939                pick = str(G2frame.itemPicked).split('(',1)[1][:-1]
     
    19572003        if G2frame.GPXtree.GetItemText(PickId) == 'Background' and event.xdata:
    19582004            if Page.toolbar._active:    # prevent ops. if a toolbar zoom button pressed
     2005                # after any mouse release event (could be a zoom), redraw magnification lines
     2006                if magLineList: wx.CallAfter(PlotPatterns,G2frame,plotType=plottype)
    19592007                return
    19602008            # Background page, deal with fixed background points
     
    19692017            # unit conversions
    19702018            xy = [event.xdata,event.ydata]
    1971             if G2frame.plotStyle['qPlot']:                              #qplot - convert back to 2-theta
    1972                 xy[0] = G2lat.Dsp2pos(Parms,2*np.pi/xy[0])
    1973             elif G2frame.plotStyle['dPlot']:                            #dplot - convert back to 2-theta
    1974                 xy[0] = G2lat.Dsp2pos(Parms,xy[0])
     2019            try:
     2020                if G2frame.plotStyle['qPlot']:                            #qplot - convert back to 2-theta
     2021                    xy[0] = G2lat.Dsp2pos(Parms,2*np.pi/xy[0])
     2022                elif G2frame.plotStyle['dPlot']:                          #dplot - convert back to 2-theta
     2023                    xy[0] = G2lat.Dsp2pos(Parms,xy[0])
     2024            except:
     2025                return
    19752026            if G2frame.plotStyle['sqrtPlot']:
    19762027                xy[1] = xy[1]**2
     
    19912042                return
    19922043       
    1993         if G2frame.itemPicked is None: return
     2044        if G2frame.itemPicked is None:
     2045            # after any mouse release event (could be a zoom), redraw magnification lines
     2046            if magLineList: wx.CallAfter(PlotPatterns,G2frame,plotType=plottype)
     2047            return
    19942048        if DifLine[0] is G2frame.itemPicked:   # respond to dragging of the difference curve
    19952049            data = G2frame.GPXtree.GetItemPyData(PickId)
     
    19982052            G2frame.itemPicked = None
    19992053            wx.CallAfter(PlotPatterns,G2frame,plotType=plottype)
     2054            return
     2055        elif G2frame.itemPicked in G2frame.MagLines: # drag of magnification marker
     2056            xpos = event.xdata
     2057            try:
     2058                if G2frame.plotStyle['qPlot']:                            #qplot - convert back to 2-theta
     2059                    xpos = G2lat.Dsp2pos(Parms,2*np.pi/xpos)
     2060                elif G2frame.plotStyle['dPlot']:                          #dplot - convert back to 2-theta
     2061                    xpos = G2lat.Dsp2pos(Parms,xpos)
     2062            except:
     2063                return
     2064            magIndex = G2frame.MagLines.index(G2frame.itemPicked)
     2065            data = G2frame.GPXtree.GetItemPyData(PickId)
     2066            data[0]['Magnification'][magIndex][0] = xpos
     2067            wx.CallAfter(G2gd.UpdatePWHKPlot,G2frame,plottype,G2frame.PatternId)
    20002068            return
    20012069        Parms,Parms2 = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,G2frame.PatternId, 'Instrument Parameters'))
     
    21552223                        'd: offset down','l: offset left','r: offset right','u: offset up','o: reset offset',
    21562224                        'q: toggle S(q) plot','m: toggle multidata plot','w: toggle (Io-Ic)/sig plot','+: no selection')
    2157 #    if 'PWDR' in plottype and G2frame.SinglePlot and not (
    2158 #                G2frame.logPlot or G2frame.plotStyle['sqrtPlot'] or G2frame.Contour):
    2159 #        Page.Choice = Page.Choice + (' a: set multiplier -- only from keyboard',)
     2225    if 'PWDR' in plottype and G2frame.SinglePlot and not (
     2226                G2frame.logPlot or G2frame.plotStyle['sqrtPlot'] or G2frame.Contour):
     2227        Page.Choice = Page.Choice + ('a: add magnification region',)
     2228    magLineList = [] # null value indicates no magnification
     2229    Page.toolbar.updateActions = None # no update actions
    21602230    G2frame.cid = None
    21612231    Page.keyPress = OnPlotKeyPress   
     
    22182288    if G2frame.logPlot:
    22192289        Title = 'log('+Title+')'
    2220     Plot.set_title(Title)
     2290    #Plot.set_title(Title) # show title only w/o magnification
    22212291    if G2frame.plotStyle['qPlot'] or plottype in ['SASD','REFD'] and not G2frame.Contour:
    22222292        Plot.set_xlabel(r'$Q, \AA^{-1}$',fontsize=16)
     
    22702340        LimitId = 0
    22712341        if Pattern[1] is None: continue # skip over uncomputed simulations
    2272 #        xye = ma.array(ma.getdata(Pattern[1]))
    22732342        xye = np.array(ma.getdata(Pattern[1]))
    22742343        bxye = G2pdG.GetFileBackground(G2frame,xye,Pattern)
     
    22882357        if not lenX:
    22892358            lenX = len(X)
     2359        # show plot magnification factors
     2360        magMarkers = []
     2361        multArray = np.ones_like(Pattern[1][0])
     2362        if 'PWDR' in plottype and G2frame.SinglePlot and not (
     2363                G2frame.logPlot or G2frame.plotStyle['sqrtPlot'] or G2frame.Contour):
     2364            magLineList = data[0].get('Magnification',[])
     2365            if ('C' in ParmList[0]['Type'][0] and G2frame.plotStyle['dPlot']
     2366                ) or ('T' in ParmList[0]['Type'][0] and G2frame.plotStyle['qPlot']
     2367                ): # reversed regions relative to data order
     2368                tcorner = 1
     2369                tpos = 1.0
     2370                halign = 'right'
     2371            else:
     2372                tcorner = 0
     2373                tpos = 1.0
     2374                halign = 'left'
     2375            ml0 = None
     2376            for x,m in magLineList:
     2377                ml = m
     2378                if int(m) == m:
     2379                    ml = int(m)
     2380                if x is None:
     2381                    magMarkers.append(None)
     2382                    multArray *= m
     2383                    ml0 = ml
     2384                    continue
     2385                multArray[Pattern[1][0]>x] = m
     2386                if G2frame.plotStyle['qPlot']:
     2387                    x = 2.*np.pi/G2lat.Pos2dsp(Parms,x)
     2388                elif G2frame.plotStyle['dPlot']:
     2389                    x = G2lat.Pos2dsp(Parms,x)
     2390                # is range in displayed range (defined after newplot)?
     2391                if not newPlot:
     2392                    (xmin,xmax),ylim = G2frame.xylim
     2393                    if x < xmin:
     2394                        ml0 = ml
     2395                        continue
     2396                    if x > xmax:
     2397                        continue
     2398                magMarkers.append(Plot.axvline(x,color='0.5',dashes=(1,1),picker=2.))
     2399                Plot.annotate("x{}".format(ml), xy=(x, tpos), xycoords=("data", "axes fraction"),
     2400                                verticalalignment='bottom',horizontalalignment=halign)
     2401            if ml0:
     2402                Plot.annotate("x{}".format(ml0), xy=(tcorner, tpos), xycoords="axes fraction",
     2403                                verticalalignment='bottom',horizontalalignment=halign)
     2404                Page.toolbar.updateActions = (PlotPatterns,G2frame)
     2405            multArray = ma.getdata(multArray)
    22902406        if 'PWDR' in plottype:
    22912407            if G2frame.plotStyle['sqrtPlot']:
     
    22932409                Y = np.where(xye[1]+bxye>=0.,np.sqrt(xye[1]+bxye),-np.sqrt(-xye[1]-bxye))
    22942410                np.seterr(invalid=olderr['invalid'])
     2411            elif 'PWDR' in plottype and G2frame.SinglePlot and not (
     2412                G2frame.logPlot or G2frame.plotStyle['sqrtPlot'] or G2frame.Contour):
     2413                Y = xye[1]*multArray+bxye+offsetY*N*Ymax/100.0
    22952414            else:
    22962415                Y = xye[1]+bxye+offsetY*N*Ymax/100.0
     
    23452464                    np.seterr(invalid=olderr['invalid'])
    23462465                else:
    2347                     Z = xye[3]+offsetY*N*Ymax/100.0
     2466                    if 'PWDR' in plottype and G2frame.SinglePlot and not (
     2467                        G2frame.logPlot or G2frame.plotStyle['sqrtPlot'] or G2frame.Contour):
     2468                        Z = xye[3]*multArray+offsetY*N*Ymax/100.0
     2469                    else:
     2470                        Z = xye[3]+offsetY*N*Ymax/100.0
    23482471                if 'PWDR' in plottype:
    23492472                    if G2frame.plotStyle['sqrtPlot']:
     
    23522475                        np.seterr(invalid=olderr['invalid'])
    23532476                        D = np.where(xye[5],(Y-Z),0.)-Pattern[0]['delOffset']
     2477                    elif 'PWDR' in plottype and G2frame.SinglePlot and not (
     2478                        G2frame.logPlot or G2frame.plotStyle['sqrtPlot'] or G2frame.Contour):
     2479                        W = xye[4]*multArray+offsetY*N*Ymax/100.0
     2480                        D = multArray*xye[5]-Pattern[0]['delOffset']  #powder background
    23542481                    else:
    23552482                        W = xye[4]+offsetY*N*Ymax/100.0
     
    24772604#        axcb = mpl.colorbar.ColorbarBase(N)
    24782605#        axcb.set_label('PDF number')
     2606    if not magLineList:
     2607        Plot.set_title(Title)
    24792608
    24802609    if PickId and not G2frame.Contour:
     
    25372666    else:
    25382667        G2frame.Lines = Lines
     2668        G2frame.MagLines = magMarkers
    25392669    if PickId and G2frame.GPXtree.GetItemText(PickId) == 'Background':
    25402670        # plot fixed background points
     
    30213151            Xb = [0.,peaks['Limits'][1]]
    30223152            Yb = [0.,Xb[1]*peaks['Background'][1][1]]
    3023             Plot.plot(Xb,Yb,color='k',dashes=(5,5))
     3153            Plot.plot(Xb,Yb,color='k',dashes=(5,5))             
    30243154#    elif G2frame.Legend:
    30253155#        Plot.legend(loc='best')
     
    61146244            SetMapPeaksText(mapPeaks)
    61156245        elif key in ['M',]and generalData['Modulated']:  #make a movie file
    6116             import imageio
     6246            try:
     6247                import imageio
     6248            except ImportError:
     6249                G2G.G2MessageBox(G2frame,
     6250                    'This command requires the Python imageio package to be installed',
     6251                    'missing package')
     6252                return
    61176253            from PIL import Image as Im
    61186254            Fname = generalData['Name']+'.gif'
Note: See TracChangeset for help on using the changeset viewer.