Changeset 3580


Ignore:
Timestamp:
Sep 1, 2018 6:55:03 PM (3 years ago)
Author:
toby
Message:

add tube tails to FPA; add grace export to Publ. plot

Location:
trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIfpaGUI.py

    r3576 r3580  
    5757    ('sample_thickness', 1., 'Depth of sample (mm)'),
    5858    ('convolution_steps', 8, 'Number of Fourier-space bins per two-theta step'),
     59    ('tube-tails_width', 0.04,'Tube filament width, in projection at takeoff angle (mm)'),
     60    ('tube-tails_L-tail', -1.,'Left-side tube tails width, in projection (mm)'),   
     61    ('tube-tails_R-tail', 1.,'Right-side tube tails width, in projection (mm)'),
     62    ('tube-tails_rel-I', 0.001,'Tube tails fractional intensity (no units)'),
    5963    ]
    6064'''FPA dict entries used in :func:`MakeTopasFPASizer`. Tuple contains
     
    232236        ctrl = G2G.ValidatedTxtCtrl(FPdlg,parmDict,lbl,size=(70,-1))
    233237        prmSizer.Add(ctrl,1,wx.ALL|wx.ALIGN_CENTER_VERTICAL,1)
    234         txt = wx.StaticText(FPdlg,wx.ID_ANY,text,size=(200,-1))
    235         txt.Wrap(180)
     238        txt = wx.StaticText(FPdlg,wx.ID_ANY,text,size=(400,-1))
     239        txt.Wrap(380)
    236240        prmSizer.Add(txt)
    237241    MainSizer.Add(prmSizer)
     
    326330        del NISTparms["receiver_slit"]
    327331
    328     #p.set_parameters(convolver="tube_tails",
    329     #        main_width=200e-6, tail_left=-1e-3,tail_right=1e-3, tail_intens=0.001
    330     #    )
     332    if InpParms.get('tube-tails_width', 0) > 0 and InpParms.get(
     333            'tube-tails_rel-I',0) > 0:
     334        NISTparms["tube_tails"] = {
     335            'main_width' : 1e-3 * InpParms.get('tube-tails_width', 0.),
     336            'tail_left' : -1e-3 * InpParms.get('tube-tails_L-tail',0.),
     337            'tail_right' : 1e-3 * InpParms.get('tube-tails_R-tail',0.),
     338            'tail_intens' : InpParms.get('tube-tails_rel-I',0.),}
     339    elif "tube_tails" in NISTparms:
     340        del NISTparms["tube_tails"]
    331341
    332342    # set Global parameters
     
    574584                style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
    575585        MakeTopasFPASizer(G2frame,FPdlg,'BBpoint',SetButtonStatus)
     586        FPdlg.CenterOnParent()
    576587        FPdlg.Raise()
    577588        FPdlg.Show()
     
    677688            style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
    678689    MakeSimSizer(G2frame,dlg)
     690    dlg.CenterOnParent()
    679691    dlg.Show()
    680692    return
  • trunk/GSASIIplot.py

    r3576 r3580  
    29592959        plotOpt['fmtChoices'] = [fmtDict[j]+', '+j for j in sorted(fmtDict)]
    29602960        plotOpt['fmtChoices'].append('Data file with plot elements, csv')
     2961        plotOpt['fmtChoices'].append('Grace input file, agr')
    29612962        if plotOpt['format'] is None:
    29622963            if 'pdf' in fmtDict:
     
    30223023        fil.write(line+'\n')
    30233024
     3025    # blocks of code used in grace .agr files
     3026    linedef = '''@{0} legend "{1}"
     3027@{0} line color {2}
     3028@{0} errorbar color {2}
     3029@{0} symbol color {2}
     3030@{0} symbol {3}
     3031@{0} symbol fill color {2}
     3032@{0} linewidth {4}
     3033@{0} symbol linewidth {6}
     3034@{0} line type {7}
     3035@{0} symbol size {5}
     3036@{0} symbol char 46
     3037@{0} symbol fill pattern 1
     3038@{0} hidden false
     3039@{0} errorbar off\n'''
     3040    linedef1 = '''@{0} legend "{1}"
     3041@{0} line color {2}
     3042@{0} errorbar color {2}
     3043@{0} symbol color {2}
     3044@{0} symbol fill color {2}
     3045@{0} symbol 11
     3046@{0} linewidth 0
     3047@{0} linestyle 0
     3048@{0} symbol size {3}
     3049@{0} symbol linewidth {4}
     3050@{0} symbol char 124
     3051@{0} symbol fill pattern 1
     3052@{0} hidden false\n'''
     3053    linedef2 = '''@{0} legend "{1}"
     3054@{0} line color {2}
     3055@{0} errorbar color {2}
     3056@{0} symbol color {2}
     3057@{0} symbol fill color {2}
     3058@{0} symbol 0
     3059@{0} linewidth 0
     3060@{0} linestyle 0
     3061@{0} symbol size 1
     3062@{0} symbol linewidth 0
     3063@{0} symbol char 124
     3064@{0} symbol fill pattern 1
     3065@{0} hidden false
     3066@{0} errorbar on
     3067@{0} errorbar size 0
     3068@{0} errorbar riser linewidth {3}\n'''
     3069    linedef3 = '''@{0} legend "{1}"
     3070@{0} line color {2}
     3071@{0} errorbar color {2}
     3072@{0} symbol color {2}
     3073@{0} symbol {3}
     3074@{0} symbol fill color {2}
     3075@{0} linewidth {4}
     3076@{0} symbol linewidth {6}
     3077@{0} line type {7}
     3078@{0} symbol size {5}
     3079@{0} symbol char 46
     3080@{0} symbol fill pattern 1
     3081@{0} hidden false
     3082@{0} errorbar off\n'''   
     3083       
     3084    def CopyRietveld2Grace(Pattern,Plot,Page,plotOpt,filename):
     3085        '''Copy the contents of the Rietveld graph from the plot window to
     3086        a Grace input file (tested with QtGrace). Uses values from Pattern
     3087        to also generate a delta/sigma plot below.
     3088        '''
     3089        def ClosestColorNumber(color):
     3090            '''Convert a RGB or RGBA value to the closest default Grace color
     3091            '''
     3092            import matplotlib.colors as mpcls
     3093            colorlist = ('white','black','red','green','blue','yellow','brown',
     3094                            'gray','purple','cyan','magenta','orange') # ordered by grace's #
     3095            if not hasattr(mpcls,'to_rgba'): mpcls = mpcls.ColorConverter()
     3096            return (np.sum(([np.array(mpcls.to_rgb(c)) for c in colorlist] -
     3097                                np.array(color[:3]))**2,axis=1)).argmin()
     3098
     3099        grace_symbols = {"":0, "o":1 ,"s":2, "D":3, "^":4, "3":5, 'v':6,
     3100            "4": 7, "+":8, "P":8, "x":9, "X":9, "*":10, ".":11}
     3101
     3102        fp = open(filename,'w')
     3103        fp.write("# Grace project file\n#\n@version 50010\n")
     3104        # size of plots on page
     3105        xmar = (.15,1.2)
     3106        ymar = (.15,.9)
     3107        top2bottom = 4. # 4 to 1 spacing for top to bottom boxes
     3108
     3109        # scaling for top box
     3110        fp.write('@g{0} hidden false\n@with g{0}\n@legend {1}\n'.format(0,"on"))
     3111        fp.write('@legend {}, {}\n'.format(xmar[1]-.2,ymar[1]-.05))
     3112        fp.write('@world xmin {}\n@world xmax {}\n'.format(Plot.get_xlim()[0],Plot.get_xlim()[1]))
     3113        fp.write('@world ymin {}\n@world ymax {}\n'.format(Plot.get_ylim()[0],Plot.get_ylim()[1]))
     3114        fp.write('@view xmin {}\n@view xmax {}\n'.format(xmar[0],xmar[1]))
     3115        fp.write('@view ymin {}\n@view ymax {}\n'.format((1./top2bottom)*(ymar[1]-ymar[0])+ymar[0],ymar[1]))
     3116        xticks = Plot.get_xaxis().get_majorticklocs()
     3117        fp.write('@{}axis tick major {}\n'.format('x',xticks[1]-xticks[0]))
     3118        yticks = Plot.get_yaxis().get_majorticklocs()   
     3119        fp.write('@{}axis tick major {}\n'.format('y',yticks[1]-yticks[0]))
     3120        fp.write('@{}axis ticklabel char size {}\n'.format('x',0)) # turns off axis labels
     3121        ylbl = Plot.get_ylabel().replace('$','')
     3122        fp.write('@{0}axis label "{1}"\n@{0}axis label char size {2}\n'.format(
     3123            'y',ylbl,float(plotOpt['labelSize'])/8.))
     3124        fp.write('@{0}axis label place spec\n@{0}axis label place {1}, {2}\n'.format('y',0.0,0.1))
     3125    # ======================================================================
     3126    # plot magnification lines and labels (first, so "under" data)
     3127        for i,l in enumerate(Plot.lines):
     3128            lbl = l.get_label()
     3129            if 'mag' not in lbl: continue
     3130            #ax0.axvline(l.get_data()[0][0],color='0.5',dashes=(1,1))
     3131            # verical line
     3132            s = '@with line\n@ line on\n@ line loctype world\n@ line g0\n'
     3133            fp.write(s)
     3134            s = '@ line {0}, {1}, {0}, {2}\n'
     3135            fp.write(s.format(
     3136                l.get_data()[0][0],Plot.get_ylim()[0],Plot.get_ylim()[1]))
     3137            s = '@ line linewidth 2\n@ line linestyle 2\n@ line color 1\n@ line arrow 0\n@line def\n'
     3138            fp.write(s)
     3139        for l in Plot.texts:
     3140            if 'mag' not in l.get_label(): continue
     3141            if l.xycoords[0] == 'data':
     3142                xpos = l.get_position()[0]
     3143            elif l.get_position()[0] == 0:
     3144                xpos = Plot.get_xlim()[0]
     3145            else:
     3146                xpos = Plot.get_xlim()[1]*.95
     3147            s = '@with string\n@    string on\n@    string loctype world\n'
     3148            fp.write(s)
     3149            s = '@    string g{0}\n@    string {1}, {2}\n@    string color 1\n'
     3150            fp.write(s.format(0,xpos,Plot.get_ylim()[1]))
     3151            s = '@    string rot 0\n@    string font 0\n@    string just 4\n'
     3152            fp.write(s)
     3153            s = '@    string char size {1}\n@    string def "{0}"\n'
     3154            fp.write(s.format(l.get_text(),float(plotOpt['labelSize'])/8.))
     3155        datnum = -1
     3156    # ======================================================================
     3157    # plot data
     3158        for l in Plot.lines:
     3159            lbl = l.get_label()
     3160            if lbl[1:] not in ('obs','calc','bkg','zero','diff'): continue
     3161            c = plotOpt['colors'].get(lbl[1:],l.get_color())
     3162            gc = ClosestColorNumber(c)
     3163            if sum(c) == 4.0: # white on white, skip
     3164                continue
     3165            marker = l.get_marker()
     3166            lineWid = l.get_lw()
     3167            siz = l.get_markersize()
     3168            mkwid = l.get_mew()
     3169            glinetyp = 1
     3170            if lbl[1:] == 'obs':
     3171                obsartist = l
     3172                gsiz = float(plotOpt['markerSiz'])/8.
     3173                marker = plotOpt['markerSym']
     3174                gmw = float(plotOpt['markerWid'])
     3175                gsym = grace_symbols.get(marker,5)
     3176                glinetyp = 0
     3177            else:
     3178                gsym = 0
     3179                gsiz = 0
     3180                gmw = 0
     3181                lineWid = float(plotOpt['lineWid'])
     3182            if plotOpt['legend'].get(lbl[1:]):
     3183                glbl = lbl[1:]
     3184            else:
     3185                glbl = ""
     3186            datnum += 1
     3187            fp.write("@type xy\n")
     3188            if lbl[1:] == 'zero':
     3189                fp.write("{} {}\n".format(Plot.get_xlim()[0],0))
     3190                fp.write("{} {}\n".format(Plot.get_xlim()[1],0))
     3191            else:
     3192                for x,y,m in zip(l.get_xdata(),l.get_ydata(),l.get_xdata().mask):
     3193                    if not m:
     3194                        fp.write("{} {}\n".format(x,y))
     3195            fp.write("&\n")
     3196            fp.write(linedef.format("s"+str(datnum),glbl,gc,gsym,lineWid,gsiz,gmw,glinetyp))
     3197    #======================================================================
     3198    # reflection markers. Create a single hidden entry for the legend
     3199    # and use error bars for the vertical lines
     3200        for l in Plot.lines:
     3201            glbl = lbl = l.get_label()
     3202            if l not in Page.tickDict.values(): continue
     3203            c = plotOpt['colors'].get(lbl,l.get_color())
     3204            gc = ClosestColorNumber(c)
     3205            siz = float(plotOpt['tickSiz'])*(Plot.get_ylim()[1] - Plot.get_ylim()[0])/(100*6) # 1% for siz=6
     3206            mkwid = float(plotOpt['tickWid'])
     3207            if sum(c) == 4.0: continue # white: ignore
     3208            if plotOpt['legend'].get(lbl):
     3209                # invisible data point for
     3210                datnum += 1
     3211                fp.write("@type xy\n")
     3212                fp.write("-1 -1\n".format(x,y))
     3213                fp.write("&\n")
     3214                fp.write(linedef1.format(
     3215                    "s"+str(datnum),glbl,gc,float(plotOpt['tickSiz'])/8.,mkwid))
     3216            # plot values with error bars
     3217            datnum += 1
     3218            fp.write("@type xydy\n")
     3219            for x,y in zip(l.get_xdata(),l.get_ydata()):
     3220                fp.write("{} {} {}\n".format(x,y,siz))
     3221            fp.write("&\n")
     3222            fp.write(linedef2.format("s"+str(datnum),'',gc,mkwid))
     3223    #======================================================================
     3224    # Start (obs-cal)/sigma plot
     3225        rsig = np.sqrt(Pattern[1][2])
     3226        rsig[rsig>1] = 1
     3227        fp.write("@type xy\n")
     3228        l = obsartist
     3229        ysig = Pattern[1][5]*rsig
     3230        # scaling for bottom box
     3231        fp.write('@g{0} hidden false\n@with g{0}\n@legend {1}\n'.format(1,"off"))
     3232        fp.write('@world xmin {}\n@world xmax {}\n'.format(Plot.get_xlim()[0],Plot.get_xlim()[1]))
     3233        fp.write('@world ymin {}\n@world ymax {}\n'.format(ysig.min(),ysig.max()))
     3234        fp.write('@view xmin {}\n@view xmax {}\n'.format(xmar[0],xmar[1]))
     3235        fp.write('@view ymin {}\n@view ymax {}\n'.format(
     3236            ymar[0],(1./top2bottom)*(ymar[1]-ymar[0])+ymar[0]))
     3237        if 'theta' in Plot.get_xlabel():
     3238            xlbl = r'2\f{Symbol}q'
     3239        elif 'TOF' in Plot.get_xlabel():
     3240            xlbl = r'TOF, \f{Symbol}m\f{}s'
     3241        else:
     3242            xlbl = Plot.get_xlabel().replace('$','')       
     3243        fp.write('@{0}axis label "{1}"\n@{0}axis label char size {2}\n'.format(
     3244            'x',xlbl,float(plotOpt['labelSize'])/8.))
     3245        fp.write('@{0}axis label "{1}"\n@{0}axis label char size {2}\n'.format(
     3246            'y',r'\f{Symbol}D/s',float(plotOpt['labelSize'])/8.))
     3247        xticks = Plot.get_xaxis().get_majorticklocs()
     3248        # come up with a "nice" tick interval for (o-c)/sig, since I am not sure
     3249        # if this can be defaulted
     3250        ytick = (ysig.max()-ysig.min())/5.
     3251        l10 = np.log10(ytick)
     3252        if l10 < 0:
     3253            yti = int(10**(1 + l10 - int(l10)))
     3254            r = -0.5
     3255        else:
     3256            yti = int(10**(l10 - int(l10)))
     3257            r = 0.5
     3258        if yti == 3:
     3259            yti = 2
     3260        elif yti > 5:
     3261            yti = 5
     3262        ytick = yti * 10**int(np.log10(ytick/yti)+.5)
     3263        fp.write('@{}axis tick major {}\n'.format('x',xticks[1]-xticks[0]))
     3264        fp.write('@{}axis tick major {}\n'.format('y',ytick))
     3265        rsig = np.sqrt(Pattern[1][2])
     3266        rsig[rsig>1] = 1
     3267        fp.write("@type xy\n")
     3268        l = obsartist
     3269        for x,y,m in zip(l.get_xdata(),Pattern[1][5]*rsig,l.get_xdata().mask):
     3270            if not m:
     3271                fp.write("{} {}\n".format(x,y))
     3272        fp.write("&\n")
     3273        fp.write(linedef3.format("s1",'',1,0,1.0,0,0,1))
     3274        fp.close()
     3275       
    30243276    def CopyRietveld2csv(Pattern,Plot,Page,filename):
    30253277        '''Copy the contents of the Rietveld graph from the plot window to
     
    30953347        longFormatName,typ = plotOpt['format'].split(',')
    30963348        fil = G2G.askSaveFile(G2frame,'','.'+typ.strip(),longFormatName)
    3097         if 'csv' in typ:
     3349        if 'csv' in typ and fil:
    30983350            CopyRietveld2csv(Pattern,Plot,Page,fil)
     3351            dlg.EndModal(wx.ID_OK)
     3352        elif 'agr' in typ and fil:
     3353            CopyRietveld2Grace(Pattern,Plot,Page,plotOpt,fil)
    30993354            dlg.EndModal(wx.ID_OK)
    31003355        elif fil:
     
    31083363        '''Respond to a change in color
    31093364        '''
    3110         lbl = plotOpt['colorButtons'].get(list(event.GetEventObject())[:3])
    3111         if lbl is None:
    3112             print('Unexpected button',lbl)
     3365#        lbl = plotOpt['colorButtons'].get(list(event.GetEventObject())[:3])
     3366        if event.GetEventObject() not in plotOpt['colorButtons']:
     3367            print('Unexpected button',str(event.GetEventObject()))
    31133368            return
     3369        lbl = plotOpt['colorButtons'][event.GetEventObject()]
    31143370        c = event.GetValue()
    31153371        plotOpt['colors'][lbl] = (c.Red()/255.,c.Green()/255.,c.Blue()/255.,c.alpha/255.)
     
    32603516    '''Copy the contents of the Rietveld graph from the plot window to another
    32613517    mpl figure which can be on screen or can be a file for hard copy.
    3262     Uses values from Pattern to also generate a delta/sigma plot below.
     3518    Uses values from Pattern to also generate a delta/sigma plot below the
     3519    main figure, since the weights are not available from the plot.
     3520
     3521    :param list Pattern: histogram object from data tree
     3522    :param mpl.axes Plot: The axes object from the Rietveld plot
     3523    :param wx.Panel Page: The tabbed panel for the Rietveld plot
     3524    :param mpl.figure figure: The figure object from the Rietveld plot
    32633525    '''
    32643526    gs = mpl.gridspec.GridSpec(2, 1, height_ratios=[4, 1])
Note: See TracChangeset for help on using the changeset viewer.