Changeset 3298


Ignore:
Timestamp:
Feb 28, 2018 10:49:30 PM (6 years ago)
Author:
toby
Message:

add publication quality Rietveld plots

Location:
trunk
Files:
1 added
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIIO.py

    r3260 r3298  
    827827    print (' XY data saved to: '+filename)
    828828           
    829 def askSaveDirectory(G2frame):
    830     '''Ask the user to supply a directory name. Path name is used as the
    831     starting point for the next export path search.
    832 
    833     :returns: a directory name (str) or None if Cancel is pressed
    834     '''
    835     pth = G2G.GetExportPath(G2frame)
    836     dlg = wx.DirDialog(
    837             G2frame, 'Input directory where file(s) will be written', pth,
    838             wx.DD_DEFAULT_STYLE)
    839     dlg.CenterOnParent()
    840     try:
    841         if dlg.ShowModal() == wx.ID_OK:
    842             filename = dlg.GetPath()
    843             G2frame.LastExportDir = filename
    844         else:
    845             filename = None
    846     finally:
    847         dlg.Destroy()
    848     return filename
    849 
    850 def askSaveFile(G2frame,defnam,extension,longFormatName):
    851     '''Ask the user to supply a file name
    852 
    853     :returns: a file name (str) or None if Cancel is pressed
    854     '''
    855 
    856     pth = G2G.GetExportPath(G2frame)
    857     dlg = wx.FileDialog(
    858         G2frame, 'Input name for file to write', pth, defnam,
    859         longFormatName+' (*'+extension+')|*'+extension,
    860         wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
    861     dlg.CenterOnParent()
    862     try:
    863         if dlg.ShowModal() == wx.ID_OK:
    864             filename = dlg.GetPath()
    865             G2frame.LastExportDir = os.path.split(filename)[0]
    866             filename = os.path.splitext(filename)[0]+extension # make sure extension is correct
    867         else:
    868             filename = None
    869     finally:
    870         dlg.Destroy()
    871     return filename
    872 
    873829def PDFSave(G2frame,exports,PDFsaves):
    874830    'Save a PDF I(Q), S(Q), F(Q) and G(r)  in column formats'
    875831    import scipy.interpolate as scintp
    876832    if len(exports) > 1:
    877         dirname = askSaveDirectory(G2frame)
     833        dirname = G2G.askSaveDirectory(G2frame)
    878834        if not dirname: return
    879835    else:
    880836        defnam = exports[0].replace(' ','_')[5:]
    881         filename = askSaveFile(G2frame,defnam,'.gr','G(r) file, etc.')
     837        filename = G2G.askSaveFile(G2frame,defnam,'.gr','G(r) file, etc.')
    882838        if not filename: return
    883839        dirname,filename = os.path.split(filename)
     
    17551711
    17561712        :returns: a file name (str) or None if Cancel is pressed
     1713
     1714        TODO: Can this be replaced with G2G.askSaveFile?
    17571715        '''
    17581716       
     
    17821740
    17831741        :returns: a directory name (str) or None if Cancel is pressed
     1742
     1743        TODO: Can this be replaced with G2G.askSaveDirectory?
    17841744        '''
    17851745        pth = G2G.GetExportPath(self.G2frame)
  • trunk/GSASIIctrlGUI.py

    r3270 r3298  
    8080                                   defined where they are first used rather than be placed
    8181                                   yet a third location somewhere in this module.
     82:func:`askSaveFile`                Get a file name from user
     83:func:`askSaveDirectory`           Get a directory name from user
    8284================================  =================================================================
    8385
     
    36573659        else:
    36583660            evt.StopPropagation()
    3659            
     3661
     3662################################################################################
     3663#####  Get an output file or directory
     3664################################################################################           
     3665def askSaveFile(G2frame,defnam,extension,longFormatName):
     3666    '''Ask the user to supply a file name
     3667
     3668    :returns: a file name (str) or None if Cancel is pressed
     3669    '''
     3670
     3671    pth = GetExportPath(G2frame)
     3672    dlg = wx.FileDialog(
     3673        G2frame, 'Input name for file to write', pth, defnam,
     3674        longFormatName+' (*'+extension+')|*'+extension,
     3675        wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
     3676    dlg.CenterOnParent()
     3677    try:
     3678        if dlg.ShowModal() == wx.ID_OK:
     3679            filename = dlg.GetPath()
     3680            G2frame.LastExportDir = os.path.split(filename)[0]
     3681            filename = os.path.splitext(filename)[0]+extension # make sure extension is correct
     3682        else:
     3683            filename = None
     3684    finally:
     3685        dlg.Destroy()
     3686    return filename
     3687
     3688def askSaveDirectory(G2frame):
     3689    '''Ask the user to supply a directory name. Path name is used as the
     3690    starting point for the next export path search.
     3691
     3692    :returns: a directory name (str) or None if Cancel is pressed
     3693    '''
     3694    pth = GetExportPath(G2frame)
     3695    dlg = wx.DirDialog(
     3696            G2frame, 'Input directory where file(s) will be written', pth,
     3697            wx.DD_DEFAULT_STYLE)
     3698    dlg.CenterOnParent()
     3699    try:
     3700        if dlg.ShowModal() == wx.ID_OK:
     3701            filename = dlg.GetPath()
     3702            G2frame.LastExportDir = filename
     3703        else:
     3704            filename = None
     3705    finally:
     3706        dlg.Destroy()
     3707    return filename
     3708
    36603709################################################################################
    36613710#####  Customized Notebook
  • trunk/GSASIIobj.py

    r3284 r3298  
    14781478        'SH/L' : 'FCJ peak asymmetry correction',
    14791479        '([UVW])$' : 'Gaussian instrument broadening \\1',
    1480         '([XY])$' : 'Cauchy instrument broadening \\1',
     1480        '([XYZ])$' : 'Cauchy instrument broadening \\1',
    14811481        'Zero' : 'Debye-Scherrer zero correction',
    14821482        'nDebye' : 'Debye model background corr. terms',
     
    15391539        'int$': 'peak intensity',
    15401540        'WgtFrac':'phase weight fraction',
     1541        'alpha':'TOF profile term',
     1542        'beta-[01q]':'TOF profile term',
     1543        'sig-[012q]':'TOF profile term',
     1544        'dif[ABC]':'TOF to d-space calibration',
    15411545        'C\([0-9]*,[0-9]*\)' : 'spherical harmonics preferred orientation coef.',
    15421546        }.items():
  • trunk/GSASIIplot.py

    r3296 r3298  
    1818============================  ===========================================================================
    1919:func:`PlotPatterns`          Powder pattern plotting
     20:func:`PublishRietveldPlot`   Create publication-quality Rietveld plots from :func:`PlotPatterns` plot
    2021:func:`PlotImage`             Plots of 2D detector images
    2122:func:`PlotPeakWidths`        Plot instrument broadening terms as function of 2-theta/TOF
     
    146147from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as Canvas
    147148from matplotlib.backends.backend_wxagg import NavigationToolbar2Wx as Toolbar
     149from matplotlib.backends.backend_agg import FigureCanvas as hcCanvas
    148150
    149151# useful degree trig functions
     
    222224#This can be done on request for other colors
    223225
     226# options for publication-quality Rietveld plots
     227plotOpt = {}
     228plotOpt['labelsize'] = 11
     229plotOpt['dpi'] = 600
     230plotOpt['width'] = 8.
     231plotOpt['height'] = 6.
     232plotOpt['legend'] = {}
     233plotOpt['colors'] = {}
     234plotOpt['format'] = None
     235plotOpt['initNeeded'] = True
     236plotOpt['lineList']  = ('obs','calc','bkg','zero','diff')
     237plotOpt['phaseList']  = []
     238plotOpt['fmtChoices']  = {}
     239
    224240class _tabPlotWin(wx.Panel):   
    225241    'Creates a basic tabbed plot window for GSAS-II graphics'
     
    235251class G2PlotMpl(_tabPlotWin):   
    236252    'Creates a Matplotlib 2-D plot in the GSAS-II graphics window'
    237     def __init__(self,parent,id=-1,dpi=None,**kwargs):
     253    def __init__(self,parent,id=-1,dpi=None,publish=None,**kwargs):
    238254        _tabPlotWin.__init__(self,parent,id=id,**kwargs)
    239255        mpl.rcParams['legend.fontsize'] = 10
    240256        self.figure = mpl.figure.Figure(dpi=dpi,figsize=(5,6))
    241257        self.canvas = Canvas(self,-1,self.figure)
    242         self.toolbar = GSASIItoolbar(self.canvas)
     258        self.toolbar = GSASIItoolbar(self.canvas,publish=publish)
    243259        self.toolbar.Realize()
    244260       
     
    390406            wx.CallAfter(self.SetSelectionNoRefresh,plotNum)
    391407
    392     def FindPlotTab(self,label,Type,newImage=True):
     408    def FindPlotTab(self,label,Type,newImage=True,publish=None):
    393409        '''Open a plot tab for initial plotting, or raise the tab if it already exists
    394410        Set a flag (Page.plotInvalid) that it has been redrawn
     
    411427            new = True
    412428            if Type == 'mpl':
    413                 Plot = self.addMpl(label).gca()
     429                Plot = self.addMpl(label,publish=publish).gca()
    414430            elif Type == 'ogl':
    415431                Plot = self.addOgl(label)
     
    453469        #self.skipPageChange = False
    454470               
    455     def addMpl(self,name=""):
     471    def addMpl(self,name="",publish=None):
    456472        'Add a tabbed page with a matplotlib plot'
    457         page = G2PlotMpl(self.nb)
     473        page = G2PlotMpl(self.nb,publish=publish)
    458474        self._addPage(name,page)
    459475        return page.figure
     
    551567        arrows[direc] = wx.NewId()
    552568       
    553     def __init__(self,plotCanvas):
     569    def __init__(self,plotCanvas,publish=None):
    554570        '''Adds additional icons to toolbar'''
    555571        # try to remove a button from the bar
     
    595611                button = self.AddSimpleTool(self.arrows[direc],_load_bitmap(icon),direc,'Zoom: '+direc)
    596612            wx.EVT_TOOL.Bind(self,self.arrows[direc],button.GetId(),self.OnArrow)
    597 
     613        id = wx.NewId()
     614        G2path = os.path.split(os.path.abspath(__file__))[0]
     615        if publish:
     616            self.addPublish(publish)
     617
     618    def addPublish(self,callBack):
     619        id = wx.NewId()
     620        G2path = os.path.split(os.path.abspath(__file__))[0]
     621        if 'phoenix' in wx.version():
     622            button = self.AddTool(id,'Publish plot',_load_bitmap(os.path.join(G2path,'publish.ico')),
     623                                  'Create publishable version of plot')
     624        else:
     625            button = self.AddSimpleTool(id,_load_bitmap(os.path.join(G2path,'publish.ico')),
     626                                        'Publish plot','Create publishable version of plot')
     627        wx.EVT_TOOL.Bind(self,id,button.GetId(),callBack)
     628           
    598629    def _update_view(self):
    599630        '''Overrides the post-buttonbar update action to invoke a redraw; needed for plot magnification
     
    21322163                if 'line' not in pick:       #avoid data points, etc.
    21332164                    data = G2frame.GPXtree.GetItemPyData(G2frame.PatternId)
    2134                     num = Page.phaseList.index(pick)
    2135                     if num:
    2136                         data[0]['refDelt'] = -(event.ydata-Pattern[0]['refOffset'])/num
    2137                     else:       #1st row of refl ticks
    2138                         data[0]['refOffset'] = event.ydata
     2165                    if pick in Page.phaseList:
     2166                        num = Page.phaseList.index(pick)
     2167                        if num:
     2168                            data[0]['refDelt'] = -(event.ydata-Pattern[0]['refOffset'])/num
     2169                        else:       #1st row of refl ticks
     2170                            data[0]['refOffset'] = event.ydata
    21392171        PlotPatterns(G2frame,plotType=plottype)
    21402172        G2frame.itemPicked = None
     2173       
     2174    def PublishPlot(event):
     2175        msg = ""
     2176        if 'PWDR' not in plottype:
     2177            msg += " * only PWDR histograms can be used"
     2178        if G2frame.Contour or not G2frame.SinglePlot:
     2179            if msg: msg += '\n'
     2180            msg += " * only when a single histogram is plotted"
     2181        if G2frame.logPlot or G2frame.plotStyle['sqrtPlot']:
     2182            if msg: msg += '\n'
     2183            msg += " * only when the intensity scale is linear (not log or sqrt)"
     2184        if msg:
     2185            msg = 'Publication export is only available under limited plot settings\n'+msg
     2186            G2G.G2MessageBox(G2frame,msg,'Wrong plot settings')
     2187            print(msg)
     2188        else:
     2189            PublishRietveldPlot(G2frame,Pattern,Plot,Page)
    21412190
    21422191    #=====================================================================================
    21432192    # beginning PlotPatterns execution
    2144     new,plotNum,Page,Plot,limits = G2frame.G2plotNB.FindPlotTab('Powder Patterns','mpl')
     2193    if plottype not in ['SASD','REFD'] and 'PWDR' in G2frame.GPXtree.GetItemText(G2frame.PickId):
     2194        publish = PublishPlot
     2195    else:
     2196        publish = None
     2197    new,plotNum,Page,Plot,limits = G2frame.G2plotNB.FindPlotTab('Powder Patterns','mpl',
     2198                                                                publish=publish)
    21452199    if not new:
    21462200        G2frame.xylim = limits
     
    23592413        # show plot magnification factors
    23602414        magMarkers = []
     2415        Plot.magLbls = []
    23612416        multArray = np.ones_like(Pattern[1][0])
    23622417        if 'PWDR' in plottype and G2frame.SinglePlot and not (
     
    23962451                    if x > xmax:
    23972452                        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)
     2453                magMarkers.append(Plot.axvline(x,color='0.5',dashes=(1,1),picker=2.,label='_magline'))
     2454                lbl = Plot.annotate("x{}".format(ml), xy=(x, tpos), xycoords=("data", "axes fraction"),
     2455                                verticalalignment='bottom',horizontalalignment=halign,label='_maglbl')
     2456                Plot.magLbls.append(lbl)
    24012457            if ml0:
    2402                 Plot.annotate("x{}".format(ml0), xy=(tcorner, tpos), xycoords="axes fraction",
    2403                                 verticalalignment='bottom',horizontalalignment=halign)
     2458                lbl = Plot.annotate("x{}".format(ml0), xy=(tcorner, tpos), xycoords="axes fraction",
     2459                                verticalalignment='bottom',horizontalalignment=halign,label='_maglbl')
     2460                Plot.magLbls.append(lbl)
    24042461                Page.toolbar.updateActions = (PlotPatterns,G2frame)
    24052462            multArray = ma.getdata(multArray)
     
    25032560                    if 'PWDR' in plottype:
    25042561                        Plot.set_yscale("log",nonposy='mask')
    2505                         Plot.plot(X,Y,colors[0]+pP,picker=3.,clip_on=Clip_on)
    2506                         Plot.plot(X,Z,colors[1],picker=False)
    2507                         Plot.plot(X,W,colors[2],picker=False)     #background
     2562                        Plot.plot(X,Y,colors[0]+pP,picker=3.,clip_on=Clip_on,label='_obs')
     2563                        Plot.plot(X,Z,colors[1],picker=False,label='_calc')
     2564                        Plot.plot(X,W,colors[2],picker=False,label='_bkg')     #background
    25082565                    elif plottype in ['SASD','REFD']:
    25092566                        Plot.set_xscale("log",nonposx='mask')
     
    25132570                            Plot.set_yscale("linear")
    25142571                            DS = (YB-ZB)*np.sqrt(xye[2])
    2515                             Plot.plot(X[Ibeg:Ifin],DS[Ibeg:Ifin],colors[3],picker=False)
     2572                            Plot.plot(X[Ibeg:Ifin],DS[Ibeg:Ifin],colors[3],picker=False,label='_diff')
    25162573                            Plot.axhline(0.,color='k')
    25172574                            Plot.set_ylim(bottom=np.min(DS[Ibeg:Ifin])*1.2,top=np.max(DS[Ibeg:Ifin])*1.2)                                                   
     
    25242581                                else:
    25252582                                    Plot.errorbar(X,YB,yerr=Sample['Scale'][0]*np.sqrt(1./(Pattern[0]['wtFactor']*xye[2])),
    2526                                         ecolor=colors[0],picker=3.,clip_on=Clip_on)
     2583                                        ecolor=colors[0],picker=3.,clip_on=Clip_on,label='_obs')
    25272584                            else:
    2528                                 Plot.plot(X,YB,colors[0]+pP,picker=3.,clip_on=Clip_on)
    2529                             Plot.plot(X,W,colors[2],picker=False)     #const. background
    2530                             Plot.plot(X,ZB,colors[1],picker=False)
     2585                                Plot.plot(X,YB,colors[0]+pP,picker=3.,clip_on=Clip_on,label='_obs')
     2586                            Plot.plot(X,W,colors[2],picker=False,label='_bkg')     #const. background
     2587                            Plot.plot(X,ZB,colors[1],picker=False,label='_calc')
    25312588                elif G2frame.Weight and 'PWDR' in plottype:
    25322589                    DY = xye[1]*np.sqrt(xye[2])
     
    25342591                    DZ = xye[3]*np.sqrt(xye[2])
    25352592                    DS = xye[5]*np.sqrt(xye[2])-Ymax*Pattern[0]['delOffset']
    2536                     ObsLine = Plot.plot(X,DY,colors[0]+pP,picker=3.,clip_on=Clip_on)         #Io/sig(Io)
    2537                     Plot.plot(X,DZ,colors[1],picker=False)                    #Ic/sig(Io)
    2538                     DifLine = Plot.plot(X,DS,colors[3],picker=1.)                    #(Io-Ic)/sig(Io)
     2593                    ObsLine = Plot.plot(X,DY,colors[0]+pP,picker=3.,clip_on=Clip_on,label='_obs')         #Io/sig(Io)
     2594                    Plot.plot(X,DZ,colors[1],picker=False,label='_calc')                    #Ic/sig(Io)
     2595                    DifLine = Plot.plot(X,DS,colors[3],picker=1.,label='_diff')                    #(Io-Ic)/sig(Io)
    25392596                    Plot.axhline(0.,color='k')
    25402597                else:
    25412598                    if G2frame.SubBack:
    25422599                        if 'PWDR' in plottype:
    2543                             Plot.plot(Xum,Y-W,colors[0]+pP,picker=False,clip_on=Clip_on)  #Io-Ib
    2544                             Plot.plot(X,Z-W,colors[1],picker=False)               #Ic-Ib
     2600                            Plot.plot(Xum,Y-W,colors[0]+pP,picker=False,clip_on=Clip_on,label='_obs')  #Io-Ib
     2601                            Plot.plot(X,Z-W,colors[1],picker=False,label='_calc')               #Ic-Ib
    25452602                        else:
    2546                             Plot.plot(X,YB,colors[0]+pP,picker=3.,clip_on=Clip_on)
    2547                             Plot.plot(X,ZB,colors[1],picker=False)
     2603                            Plot.plot(X,YB,colors[0]+pP,picker=3.,clip_on=Clip_on,label='_obs')
     2604                            Plot.plot(X,ZB,colors[1],picker=False,label='_calc')
    25482605                    else:
    25492606                        if 'PWDR' in plottype:
    2550                             ObsLine = Plot.plot(Xum,Y,colors[0]+pP,picker=3.,clip_on=Clip_on)    #Io
    2551                             Plot.plot(X,Z,colors[1],picker=False)                 #Ic
     2607                            ObsLine = Plot.plot(Xum,Y,colors[0]+pP,picker=3.,clip_on=Clip_on,label='_obs')    #Io
     2608                            Plot.plot(X,Z,colors[1],picker=False,label='_calc')                 #Ic
    25522609                        else:
    2553                             Plot.plot(X,YB,colors[0]+pP,picker=3.,clip_on=Clip_on)
    2554                             Plot.plot(X,ZB,colors[1],picker=False)
     2610                            Plot.plot(X,YB,colors[0]+pP,picker=3.,clip_on=Clip_on,label='_obs')
     2611                            Plot.plot(X,ZB,colors[1],picker=False,label='_calc')
    25552612                    if 'PWDR' in plottype:
    2556                         Plot.plot(X,W,colors[2],picker=False)                 #Ib
    2557                         DifLine = Plot.plot(X,D,colors[3],picker=1.)                 #Io-Ic
    2558                     Plot.axhline(0.,color='k')
     2613                        Plot.plot(X,W,colors[2],picker=False,label='_bkg')                 #Ib
     2614                        DifLine = Plot.plot(X,D,colors[3],picker=1.,label='_diff')                 #Io-Ic
     2615                    Plot.axhline(0.,color='k',label='_zero')
    25592616                Page.SetToolTipString('')
    25602617                if PickId:
     
    27172774        if DifLine[0]:
    27182775            G2frame.dataWindow.moveDiffCurve.Enable(True)
     2776           
     2777def PublishRietveldPlot(G2frame,Pattern,Plot,Page):
     2778    '''Show a customizable "Rietveld" plot and export as a publication-quality
     2779    file. Will only work when a single pattern is displayed.
     2780
     2781    :param wx.Frame G2Frame: the main GSAS-II window
     2782    :param list Pattern: list of np.array items with obs, calc (etc.) diffraction pattern
     2783    :param mpl.axes Plot: axes of the graph in plot window
     2784    :param wx.Panel Page: tabbed panel containing the plot
     2785    '''
     2786    def Initialize():
     2787        '''Set up initial values in plotOpt
     2788        '''
     2789        plotOpt['initNeeded'] = False
     2790        # create a temporary hard-copy figure to get output options
     2791        figure = mpl.figure.Figure(dpi=200,figsize=(6,8))
     2792        canvas = hcCanvas(figure)
     2793        fmtDict = canvas.get_supported_filetypes()
     2794        figure.clear()
     2795        plotOpt['fmtChoices'] = [fmtDict[j]+', '+j for j in sorted(fmtDict)]
     2796        if plotOpt['format'] is None:
     2797            if 'pdf' in fmtDict:
     2798                plotOpt['format'] = fmtDict['pdf'] + ', pdf'
     2799            else:
     2800                plotOpt['format'] = plotOpt['fmtChoices'][0]
     2801    def GetColors():
     2802        '''Set up initial values in plotOpt for colors and legend
     2803        '''
     2804        plotOpt['phaseList']  = []
     2805        for i,l in enumerate(Plot.lines):
     2806            lbl = l.get_label()
     2807            if 'mag' in lbl:
     2808                pass
     2809            elif lbl[1:] in plotOpt['lineList']:
     2810                if lbl[1:] in plotOpt['colors']: continue
     2811                plotOpt['colors'][lbl[1:]] = mpl.colors.to_rgba(l.get_color())
     2812                plotOpt['legend'][lbl[1:]] = False
     2813            elif l in Page.tickDict.values():
     2814                plotOpt['phaseList'] .append(lbl)
     2815                if lbl in plotOpt['colors']: continue
     2816                plotOpt['colors'][lbl] = mpl.colors.to_rgba(l.get_color())
     2817                plotOpt['legend'][lbl] = True
     2818
     2819    def RefreshPlot(*args):
     2820        '''Update the plot on the dialog
     2821        '''
     2822        figure.clear()
     2823        CopyRietveldPlot(G2frame,Pattern,Plot,Page,figure)
     2824        figure.canvas.draw()
     2825    def onSave(event):
     2826        '''Write the current plot to a file
     2827        '''
     2828        hcfigure = mpl.figure.Figure(dpi=plotOpt['dpi'],figsize=(plotOpt['width'],plotOpt['height']))
     2829        hccanvas = hcCanvas(hcfigure)
     2830        CopyRietveldPlot(G2frame,Pattern,Plot,Page,hcfigure)
     2831        longFormatName,type = plotOpt['format'].split(',')
     2832        fil = G2G.askSaveFile(G2frame,'','.'+type.strip(),longFormatName)
     2833        if fil:
     2834            hcfigure.savefig(fil,format=type.strip())
     2835            dlg.EndModal(wx.ID_OK)
     2836    def onTextSize(event):
     2837        '''Respond to a change in text size from the slider
     2838        '''
     2839        if plotOpt['labelsize'] != event.GetInt():
     2840            plotOpt['labelsize'] = event.GetInt()
     2841            RefreshPlot()
     2842    def OnSelectColour(event):
     2843        '''Respond to a change in color
     2844        '''
     2845        lbl = plotOpt['colorButtons'].get(event.GetEventObject())
     2846        if lbl is None:
     2847            print('Unexpected button',lbl)
     2848            return
     2849        c = event.GetValue()
     2850        plotOpt['colors'][lbl] = (c.Red()/255.,c.Green()/255.,c.Blue()/255.,c.alpha/255.)
     2851        RefreshPlot()
     2852
     2853    # start of PublishRietveldPlot
     2854    if plotOpt['initNeeded']: Initialize()
     2855    GetColors()           
     2856    dlg = wx.Dialog(G2frame,
     2857                style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
     2858    vbox = wx.BoxSizer(wx.VERTICAL)
     2859    # text size slider
     2860    hbox = wx.BoxSizer(wx.HORIZONTAL)
     2861    txt = wx.StaticText(dlg,wx.ID_ANY,'Text size')
     2862    hbox.Add(txt,0,wx.ALL|wx.ALIGN_CENTER_VERTICAL)
     2863    slider = wx.Slider(dlg, wx.ID_ANY, plotOpt['labelsize'],
     2864                       10, 25, size=(250, -1),
     2865                style=wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS
     2866            )
     2867    slider.Bind(wx.EVT_SLIDER,onTextSize)
     2868    hbox.Add(slider,0,wx.ALL)
     2869   
     2870    # table of colors and legend options
     2871    cols = 1+len(plotOpt['lineList']) + len(plotOpt['phaseList'] )
     2872    if cols > 9: # if lots of phases, move table to separate line (might be better to count label lengths)
     2873        vbox.Add(hbox,0,wx.ALL|wx.ALIGN_CENTER)
     2874        hbox = wx.BoxSizer(wx.HORIZONTAL)
     2875    gsizer = wx.FlexGridSizer(cols=cols,hgap=2,vgap=2)
     2876    gsizer.Add((-1,-1))
     2877    for lbl in list(plotOpt['lineList']) + list(plotOpt['phaseList'] ):
     2878        gsizer.Add(wx.StaticText(dlg,wx.ID_ANY,lbl[:15]),0,wx.ALL)
     2879    gsizer.Add(wx.StaticText(dlg,wx.ID_ANY,'Include in legend'),0,wx.ALL)
     2880    for lbl in list(plotOpt['lineList']) + list(plotOpt['phaseList'] ):
     2881        ch = G2G.G2CheckBox(dlg,'',plotOpt['legend'],lbl,RefreshPlot)
     2882        gsizer.Add(ch,0,wx.ALL|wx.ALIGN_CENTER)
     2883    gsizer.Add(wx.StaticText(dlg,wx.ID_ANY,'Color'),0,wx.ALL)
     2884    plotOpt['colorButtons'] = {}
     2885    for lbl in list(plotOpt['lineList']) + list(plotOpt['phaseList']):
     2886        import  wx.lib.colourselect as csel
     2887        color = wx.Colour(*[255*i for i in plotOpt['colors'][lbl]])
     2888        b = csel.ColourSelect(dlg, -1, '', color)
     2889        b.Bind(csel.EVT_COLOURSELECT, OnSelectColour)
     2890        plotOpt['colorButtons'][b] = lbl
     2891        gsizer.Add(b,0,wx.ALL|wx.ALIGN_CENTER)
     2892    hbox.Add(gsizer,0,wx.ALL)
     2893    vbox.Add(hbox,0,wx.ALL|wx.ALIGN_CENTER)
     2894
     2895    # hard copy options
     2896    hbox = wx.BoxSizer(wx.HORIZONTAL)
     2897    txt = wx.StaticText(dlg,wx.ID_ANY,'Hard copy  ')
     2898    hbox.Add(txt,0,wx.ALL|wx.ALIGN_CENTER_VERTICAL)
     2899    txt = wx.StaticText(dlg,wx.ID_ANY,'Pixels/inch:')
     2900    hbox.Add(txt,0,wx.ALL|wx.ALIGN_CENTER_VERTICAL)
     2901    val = G2G.ValidatedTxtCtrl(dlg,plotOpt,'dpi',min=75,max=1000,size=(40,-1))
     2902    hbox.Add(val,0,wx.ALL)
     2903    txt = wx.StaticText(dlg,wx.ID_ANY,' Width (in):')
     2904    hbox.Add(txt,0,wx.ALL|wx.ALIGN_CENTER_VERTICAL)
     2905    val = G2G.ValidatedTxtCtrl(dlg,plotOpt,'width',min=3.,max=20.,nDig=(5,1),size=(45,-1))
     2906    hbox.Add(val,0,wx.ALL)
     2907    txt = wx.StaticText(dlg,wx.ID_ANY,' Height (in):')
     2908    hbox.Add(txt,0,wx.ALL|wx.ALIGN_CENTER_VERTICAL)
     2909    val = G2G.ValidatedTxtCtrl(dlg,plotOpt,'height',min=3.,max=20.,nDig=(5,1),size=(45,-1))
     2910    hbox.Add(val,0,wx.ALL)
     2911    txt = wx.StaticText(dlg,wx.ID_ANY,'File format:')
     2912    hbox.Add(txt,0,wx.ALL|wx.ALIGN_CENTER_VERTICAL)
     2913    val = G2G.EnumSelector(dlg,plotOpt,'format',plotOpt['fmtChoices'])
     2914    hbox.Add(val,0,wx.ALL)
     2915    vbox.Add(hbox,0,wx.ALL|wx.ALIGN_CENTER)
     2916
     2917    # screen preview
     2918    figure = mpl.figure.Figure(figsize=(plotOpt['width'],plotOpt['height']))
     2919    canvas = Canvas(dlg,-1,figure)
     2920    vbox.Add(canvas,1,wx.ALL|wx.EXPAND,1)
     2921
     2922    # buttons at bottom
     2923    btnsizer = wx.StdDialogButtonSizer()
     2924    btn = wx.Button(dlg, wx.ID_CANCEL)
     2925    btnsizer.AddButton(btn)
     2926    btn = wx.Button(dlg, wx.ID_SAVE)
     2927    btn.SetDefault()
     2928    btn.Bind(wx.EVT_BUTTON,onSave)
     2929    btnsizer.AddButton(btn)
     2930    btnsizer.Realize()
     2931    vbox.Add((-1,5))
     2932    vbox.Add(btnsizer, 0, wx.ALIGN_CENTER|wx.ALL, 5)
     2933    dlg.SetSizer(vbox)
     2934    vbox.Fit(dlg)
     2935    dlg.Layout()
     2936    dlg.CenterOnParent()
     2937
     2938    CopyRietveldPlot(G2frame,Pattern,Plot,Page,figure)     # preview plot
     2939    figure.canvas.draw()
     2940
     2941    dlg.ShowModal()
     2942    dlg.Destroy()
     2943    return
     2944
     2945def CopyRietveldPlot(G2frame,Pattern,Plot,Page,figure):
     2946    '''Copy the contents of the Rietveld graph from the plot window to another
     2947    mpl figure which can be on screen or can be a file for hard copy.
     2948    Uses values from Pattern to also generate a delta/sigma plot below.
     2949    '''
     2950    gs = mpl.gridspec.GridSpec(2, 1, height_ratios=[4, 1])
     2951    ax0 = figure.add_subplot(gs[0])
     2952    ax1 = figure.add_subplot(gs[1])
     2953    figure.subplots_adjust(left=plotOpt['labelsize']/100.,bottom=plotOpt['labelsize']/150.,
     2954                           right=.98,top=1.-plotOpt['labelsize']/200.,hspace=0.0)
     2955    ax0.tick_params('x',direction='in',labelbottom=False)
     2956    ax0.tick_params(labelsize=plotOpt['labelsize'])
     2957    ax1.tick_params(labelsize=plotOpt['labelsize'])
     2958    ax1.set_xlabel(Plot.get_xlabel(),fontsize=plotOpt['labelsize'])
     2959    ax0.set_ylabel(Plot.get_ylabel(),fontsize=plotOpt['labelsize'])
     2960    ax1.set_ylabel(r'$\Delta/\sigma$',fontsize=plotOpt['labelsize'])
     2961    ax0.set_xlim(Plot.get_xlim())
     2962    ax1.set_xlim(Plot.get_xlim())
     2963    ax0.set_ylim(Plot.get_ylim())
     2964   
     2965    legLbl = []
     2966    legLine = []
     2967    for i,l in enumerate(Plot.lines):
     2968        lbl = l.get_label()
     2969        if 'mag' in lbl:
     2970            ax0.axvline(l.get_data()[0][0],color='0.5',dashes=(1,1))
     2971        elif lbl[1:] in ('obs','calc','bkg','zero','diff'):
     2972            if plotOpt['legend'].get(lbl[1:]):
     2973                uselbl = lbl[1:]
     2974                legLbl.append(uselbl)
     2975            else:
     2976                uselbl = lbl
     2977            c = plotOpt['colors'].get(lbl[1:],l.get_color())
     2978            art = ax0.plot(l.get_xdata(),l.get_ydata(),color=c,
     2979                     lw=l.get_lw(),label=uselbl,ls=l.get_ls(),
     2980                     marker=l.get_marker(),ms=l.get_ms()
     2981                     )
     2982            if plotOpt['legend'].get(lbl[1:]):
     2983                legLine.append(art[0])
     2984        elif l in Page.tickDict.values():
     2985            if not plotOpt['legend'].get(lbl):
     2986                lbl = '_'+lbl
     2987            c = plotOpt['colors'].get(lbl,l.get_color())
     2988            art = ax0.plot(l.get_xdata(),l.get_ydata(),color=c,
     2989                     lw=l.get_lw(),ls=l.get_ls(),label=lbl,
     2990                     marker=l.get_marker(),ms=l.get_ms(),
     2991                     )
     2992            if plotOpt['legend'].get(lbl):
     2993                legLbl.append(lbl)
     2994                legLine.append(art[0])
     2995    for l in Plot.texts:
     2996        if 'mag' not in l.get_label(): continue
     2997        ax0.annotate(l.get_text(),
     2998                    xy=(l.get_position()), xycoords=l.xycoords,
     2999                    verticalalignment='bottom',
     3000                    horizontalalignment=l.get_horizontalalignment(),
     3001                    fontsize=plotOpt['labelsize'])
     3002    rsig = np.sqrt(Pattern[1][2])
     3003    rsig[rsig>1] = 1
     3004    ax1.plot(Pattern[1][0],Pattern[1][5]*rsig,color='k')
     3005    if legLine:
     3006        ax0.legend(legLine,legLbl,loc='best',fontsize=plotOpt['labelsize'])
    27193007   
    27203008################################################################################
Note: See TracChangeset for help on using the changeset viewer.