Changeset 3298
- Timestamp:
- Feb 28, 2018 10:49:30 PM (6 years ago)
- Location:
- trunk
- Files:
-
- 1 added
- 4 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/GSASIIIO.py
r3260 r3298 827 827 print (' XY data saved to: '+filename) 828 828 829 def askSaveDirectory(G2frame):830 '''Ask the user to supply a directory name. Path name is used as the831 starting point for the next export path search.832 833 :returns: a directory name (str) or None if Cancel is pressed834 '''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 = filename844 else:845 filename = None846 finally:847 dlg.Destroy()848 return filename849 850 def askSaveFile(G2frame,defnam,extension,longFormatName):851 '''Ask the user to supply a file name852 853 :returns: a file name (str) or None if Cancel is pressed854 '''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 correct867 else:868 filename = None869 finally:870 dlg.Destroy()871 return filename872 873 829 def PDFSave(G2frame,exports,PDFsaves): 874 830 'Save a PDF I(Q), S(Q), F(Q) and G(r) in column formats' 875 831 import scipy.interpolate as scintp 876 832 if len(exports) > 1: 877 dirname = askSaveDirectory(G2frame)833 dirname = G2G.askSaveDirectory(G2frame) 878 834 if not dirname: return 879 835 else: 880 836 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.') 882 838 if not filename: return 883 839 dirname,filename = os.path.split(filename) … … 1755 1711 1756 1712 :returns: a file name (str) or None if Cancel is pressed 1713 1714 TODO: Can this be replaced with G2G.askSaveFile? 1757 1715 ''' 1758 1716 … … 1782 1740 1783 1741 :returns: a directory name (str) or None if Cancel is pressed 1742 1743 TODO: Can this be replaced with G2G.askSaveDirectory? 1784 1744 ''' 1785 1745 pth = G2G.GetExportPath(self.G2frame) -
trunk/GSASIIctrlGUI.py
r3270 r3298 80 80 defined where they are first used rather than be placed 81 81 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 82 84 ================================ ================================================================= 83 85 … … 3657 3659 else: 3658 3660 evt.StopPropagation() 3659 3661 3662 ################################################################################ 3663 ##### Get an output file or directory 3664 ################################################################################ 3665 def 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 3688 def 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 3660 3709 ################################################################################ 3661 3710 ##### Customized Notebook -
trunk/GSASIIobj.py
r3284 r3298 1478 1478 'SH/L' : 'FCJ peak asymmetry correction', 1479 1479 '([UVW])$' : 'Gaussian instrument broadening \\1', 1480 '([XY ])$' : 'Cauchy instrument broadening \\1',1480 '([XYZ])$' : 'Cauchy instrument broadening \\1', 1481 1481 'Zero' : 'Debye-Scherrer zero correction', 1482 1482 'nDebye' : 'Debye model background corr. terms', … … 1539 1539 'int$': 'peak intensity', 1540 1540 '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', 1541 1545 'C\([0-9]*,[0-9]*\)' : 'spherical harmonics preferred orientation coef.', 1542 1546 }.items(): -
trunk/GSASIIplot.py
r3296 r3298 18 18 ============================ =========================================================================== 19 19 :func:`PlotPatterns` Powder pattern plotting 20 :func:`PublishRietveldPlot` Create publication-quality Rietveld plots from :func:`PlotPatterns` plot 20 21 :func:`PlotImage` Plots of 2D detector images 21 22 :func:`PlotPeakWidths` Plot instrument broadening terms as function of 2-theta/TOF … … 146 147 from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as Canvas 147 148 from matplotlib.backends.backend_wxagg import NavigationToolbar2Wx as Toolbar 149 from matplotlib.backends.backend_agg import FigureCanvas as hcCanvas 148 150 149 151 # useful degree trig functions … … 222 224 #This can be done on request for other colors 223 225 226 # options for publication-quality Rietveld plots 227 plotOpt = {} 228 plotOpt['labelsize'] = 11 229 plotOpt['dpi'] = 600 230 plotOpt['width'] = 8. 231 plotOpt['height'] = 6. 232 plotOpt['legend'] = {} 233 plotOpt['colors'] = {} 234 plotOpt['format'] = None 235 plotOpt['initNeeded'] = True 236 plotOpt['lineList'] = ('obs','calc','bkg','zero','diff') 237 plotOpt['phaseList'] = [] 238 plotOpt['fmtChoices'] = {} 239 224 240 class _tabPlotWin(wx.Panel): 225 241 'Creates a basic tabbed plot window for GSAS-II graphics' … … 235 251 class G2PlotMpl(_tabPlotWin): 236 252 '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): 238 254 _tabPlotWin.__init__(self,parent,id=id,**kwargs) 239 255 mpl.rcParams['legend.fontsize'] = 10 240 256 self.figure = mpl.figure.Figure(dpi=dpi,figsize=(5,6)) 241 257 self.canvas = Canvas(self,-1,self.figure) 242 self.toolbar = GSASIItoolbar(self.canvas )258 self.toolbar = GSASIItoolbar(self.canvas,publish=publish) 243 259 self.toolbar.Realize() 244 260 … … 390 406 wx.CallAfter(self.SetSelectionNoRefresh,plotNum) 391 407 392 def FindPlotTab(self,label,Type,newImage=True ):408 def FindPlotTab(self,label,Type,newImage=True,publish=None): 393 409 '''Open a plot tab for initial plotting, or raise the tab if it already exists 394 410 Set a flag (Page.plotInvalid) that it has been redrawn … … 411 427 new = True 412 428 if Type == 'mpl': 413 Plot = self.addMpl(label ).gca()429 Plot = self.addMpl(label,publish=publish).gca() 414 430 elif Type == 'ogl': 415 431 Plot = self.addOgl(label) … … 453 469 #self.skipPageChange = False 454 470 455 def addMpl(self,name="" ):471 def addMpl(self,name="",publish=None): 456 472 'Add a tabbed page with a matplotlib plot' 457 page = G2PlotMpl(self.nb )473 page = G2PlotMpl(self.nb,publish=publish) 458 474 self._addPage(name,page) 459 475 return page.figure … … 551 567 arrows[direc] = wx.NewId() 552 568 553 def __init__(self,plotCanvas ):569 def __init__(self,plotCanvas,publish=None): 554 570 '''Adds additional icons to toolbar''' 555 571 # try to remove a button from the bar … … 595 611 button = self.AddSimpleTool(self.arrows[direc],_load_bitmap(icon),direc,'Zoom: '+direc) 596 612 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 598 629 def _update_view(self): 599 630 '''Overrides the post-buttonbar update action to invoke a redraw; needed for plot magnification … … 2132 2163 if 'line' not in pick: #avoid data points, etc. 2133 2164 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 2139 2171 PlotPatterns(G2frame,plotType=plottype) 2140 2172 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) 2141 2190 2142 2191 #===================================================================================== 2143 2192 # 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) 2145 2199 if not new: 2146 2200 G2frame.xylim = limits … … 2359 2413 # show plot magnification factors 2360 2414 magMarkers = [] 2415 Plot.magLbls = [] 2361 2416 multArray = np.ones_like(Pattern[1][0]) 2362 2417 if 'PWDR' in plottype and G2frame.SinglePlot and not ( … … 2396 2451 if x > xmax: 2397 2452 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) 2401 2457 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) 2404 2461 Page.toolbar.updateActions = (PlotPatterns,G2frame) 2405 2462 multArray = ma.getdata(multArray) … … 2503 2560 if 'PWDR' in plottype: 2504 2561 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 ) #background2562 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 2508 2565 elif plottype in ['SASD','REFD']: 2509 2566 Plot.set_xscale("log",nonposx='mask') … … 2513 2570 Plot.set_yscale("linear") 2514 2571 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') 2516 2573 Plot.axhline(0.,color='k') 2517 2574 Plot.set_ylim(bottom=np.min(DS[Ibeg:Ifin])*1.2,top=np.max(DS[Ibeg:Ifin])*1.2) … … 2524 2581 else: 2525 2582 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') 2527 2584 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. background2530 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') 2531 2588 elif G2frame.Weight and 'PWDR' in plottype: 2532 2589 DY = xye[1]*np.sqrt(xye[2]) … … 2534 2591 DZ = xye[3]*np.sqrt(xye[2]) 2535 2592 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) 2539 2596 Plot.axhline(0.,color='k') 2540 2597 else: 2541 2598 if G2frame.SubBack: 2542 2599 if 'PWDR' in plottype: 2543 Plot.plot(Xum,Y-W,colors[0]+pP,picker=False,clip_on=Clip_on ) #Io-Ib2544 Plot.plot(X,Z-W,colors[1],picker=False ) #Ic-Ib2600 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 2545 2602 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') 2548 2605 else: 2549 2606 if 'PWDR' in plottype: 2550 ObsLine = Plot.plot(Xum,Y,colors[0]+pP,picker=3.,clip_on=Clip_on ) #Io2551 Plot.plot(X,Z,colors[1],picker=False ) #Ic2607 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 2552 2609 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') 2555 2612 if 'PWDR' in plottype: 2556 Plot.plot(X,W,colors[2],picker=False ) #Ib2557 DifLine = Plot.plot(X,D,colors[3],picker=1. ) #Io-Ic2558 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') 2559 2616 Page.SetToolTipString('') 2560 2617 if PickId: … … 2717 2774 if DifLine[0]: 2718 2775 G2frame.dataWindow.moveDiffCurve.Enable(True) 2776 2777 def 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 2945 def 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']) 2719 3007 2720 3008 ################################################################################
Note: See TracChangeset
for help on using the changeset viewer.