Changeset 3999


Ignore:
Timestamp:
May 27, 2019 4:07:46 PM (3 years ago)
Author:
toby
Message:

reorg PDF computation/save as non-GUI code, add PDF to scriptable, doc build fixes

Location:
trunk
Files:
9 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIIO.py

    r3980 r3999  
    5151import GSASIIobj as G2obj
    5252import GSASIIlattice as G2lat
    53 import GSASIImath as G2mth
    5453try:
    5554    import GSASIIpwdGUI as G2pdG
     
    946945            File.write('%.3f,%.3f\n'%(x,y))   
    947946    File.close()
    948     print (' XY data saved to: '+filename)
    949            
    950 def PDFSave(G2frame,exports,PDFsaves):
    951     'Save a PDF I(Q), S(Q), F(Q) and G(r)  in column formats'
    952     import scipy.interpolate as scintp
    953     if len(exports) > 1:
    954         dirname = G2G.askSaveDirectory(G2frame)
    955         if not dirname: return
    956     else:
    957         defnam = exports[0].replace(' ','_')[5:]
    958         filename = G2G.askSaveFile(G2frame,defnam,'.gr','G(r) file, etc.')
    959         if not filename: return
    960         dirname,filename = os.path.split(filename)
    961         filename = os.path.splitext(filename)[0]
    962     for export in exports:
    963         if len(exports) > 1:
    964             filename = export.replace(' ','_')[5:]
    965         PickId = G2gd.GetGPXtreeItemId(G2frame, G2frame.root, export)
    966         PDFControls = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame, PickId,'PDF Controls'))
    967         if PDFsaves[0]:     #I(Q)
    968             iqfilename = ospath.join(dirname,filename+'.iq')
    969             iqdata = PDFControls['I(Q)'][0]
    970             iqfxn = scintp.interp1d(iqdata[0],iqdata[1],kind='linear')
    971             iqfile = open(iqfilename,'w')
    972             iqfile.write('#T I(Q) %s\n'%(export))
    973             iqfile.write('#L Q     I(Q)\n')
    974             qnew = np.arange(iqdata[0][0],iqdata[0][-1],0.005)
    975             iqnew = zip(qnew,iqfxn(qnew))
    976             for q,iq in iqnew:
    977                 iqfile.write("%15.6g %15.6g\n" % (q,iq))
    978             iqfile.close()
    979             print (' I(Q) saved to: '+iqfilename)
    980            
    981         if PDFsaves[1]:     #S(Q)
    982             sqfilename = ospath.join(dirname,filename+'.sq')
    983             sqdata = PDFControls['S(Q)'][1]
    984             sqfxn = scintp.interp1d(sqdata[0],sqdata[1],kind='linear')
    985             sqfile = open(sqfilename,'w')
    986             sqfile.write('#T S(Q) %s\n'%(export))
    987             sqfile.write('#L Q     S(Q)\n')
    988             qnew = np.arange(sqdata[0][0],sqdata[0][-1],0.005)
    989             sqnew = zip(qnew,sqfxn(qnew))
    990             for q,sq in sqnew:
    991                 sqfile.write("%15.6g %15.6g\n" % (q,sq))
    992             sqfile.close()
    993             print (' S(Q) saved to: '+sqfilename)
    994            
    995         if PDFsaves[2]:     #F(Q)
    996             fqfilename = ospath.join(dirname,filename+'.fq')
    997             fqdata = PDFControls['F(Q)'][1]
    998             fqfxn = scintp.interp1d(fqdata[0],fqdata[1],kind='linear')
    999             fqfile = open(fqfilename,'w')
    1000             fqfile.write('#T F(Q) %s\n'%(export))
    1001             fqfile.write('#L Q     F(Q)\n')
    1002             qnew = np.arange(fqdata[0][0],fqdata[0][-1],0.005)
    1003             fqnew = zip(qnew,fqfxn(qnew))
    1004             for q,fq in fqnew:
    1005                 fqfile.write("%15.6g %15.6g\n" % (q,fq))
    1006             fqfile.close()
    1007             print (' F(Q) saved to: '+fqfilename)
    1008            
    1009         if PDFsaves[3]:     #G(R)
    1010             grfilename = ospath.join(dirname,filename+'.gr')
    1011             grdata = PDFControls['G(R)'][1]
    1012             grfxn = scintp.interp1d(grdata[0],grdata[1],kind='linear')
    1013             grfile = open(grfilename,'w')
    1014             grfile.write('#T G(R) %s\n'%(export))
    1015             grfile.write('#L R     G(R)\n')
    1016             rnew = np.arange(grdata[0][0],grdata[0][-1],0.010)
    1017             grnew = zip(rnew,grfxn(rnew))
    1018             for r,gr in grnew:
    1019                 grfile.write("%15.6g %15.6g\n" % (r,gr))
    1020             grfile.close()
    1021             print (' G(R) saved to: '+grfilename)
    1022        
    1023         if PDFsaves[4]: #pdfGUI file for G(R)
    1024             pId = G2gd.GetGPXtreeItemId(G2frame, G2frame.root, 'PWDR'+export[4:])
    1025             Inst = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame, pId,'Instrument Parameters'))[0]
    1026             Limits = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame, pId,'Limits'))
    1027             grfilename = ospath.join(dirname,filename+'.gr')
    1028             grdata = PDFControls['G(R)'][1]
    1029             qdata = PDFControls['I(Q)'][1][0]
    1030             grfxn = scintp.interp1d(grdata[0],grdata[1],kind='linear')
    1031             grfile = open(grfilename,'w')
    1032             rnew = np.arange(grdata[0][0],grdata[0][-1],0.010)
    1033             grnew = zip(rnew,grfxn(rnew))
    1034 
    1035             grfile.write('[DEFAULT]\n')
    1036             grfile.write('\n')
    1037             grfile.write('version = GSAS-II-v'+str(GSASIIpath.GetVersionNumber())+'\n')
    1038             grfile.write('\n')
    1039             grfile.write('# input and output specifications\n')
    1040             grfile.write('dataformat = Qnm\n')
    1041             grfile.write('inputfile = %s\n'%(PDFControls['Sample']['Name']))
    1042             grfile.write('backgroundfile = %s\n'%(PDFControls['Sample Bkg.']['Name']))
    1043             grfile.write('outputtype = gr\n')
    1044             grfile.write('\n')
    1045             grfile.write('# PDF calculation setup\n')
    1046             if 'x' in Inst['Type']:
    1047                 grfile.write('mode = %s\n'%('xray'))
    1048             elif 'N' in Inst['Type']:
    1049                 grfile.write('mode = %s\n'%('neutron'))
    1050             wave = G2mth.getMeanWave(Inst)
    1051             grfile.write('wavelength = %.5f\n'%(wave))
    1052             formula = ''
    1053             for el in PDFControls['ElList']:
    1054                 formula += el
    1055                 num = PDFControls['ElList'][el]['FormulaNo']
    1056                 if num == round(num):
    1057                     formula += '%d'%(int(num))
    1058                 else:
    1059                     formula += '%.2f'%(num)
    1060             grfile.write('composition = %s\n'%(formula))
    1061             grfile.write('bgscale = %.3f\n'%(-PDFControls['Sample Bkg.']['Mult']))
    1062             highQ = 2.*np.pi/G2lat.Pos2dsp(Inst,Limits[1][1])
    1063             grfile.write('qmaxinst = %.2f\n'%(highQ))
    1064             grfile.write('qmin = %.5f\n'%(qdata[0]))
    1065             grfile.write('qmax = %.4f\n'%(qdata[-1]))
    1066             grfile.write('rmin = %.2f\n'%(PDFControls['Rmin']))
    1067             grfile.write('rmax = %.2f\n'%(PDFControls['Rmax']))
    1068             grfile.write('rstep = 0.01\n')
    1069            
    1070            
    1071             grfile.write('\n')
    1072             grfile.write('# End of config '+63*'-')
    1073             grfile.write('\n')
    1074             grfile.write('#### start data\n')
    1075             grfile.write('#S 1\n')
    1076             grfile.write('#L r($\AA$)  G($\AA^{-2}$)\n')           
    1077             for r,gr in grnew:
    1078                 grfile.write("%15.2F %15.6F\n" % (r,gr))
    1079             grfile.close()
    1080             print (' G(R) saved to: '+grfilename)
     947    print (' XY data saved to: '+filename)                       
    1081948   
    1082949def PeakListSave(G2frame,file,peaks):
  • trunk/GSASIIdataGUI.py

    r3995 r3999  
    41484148       
    41494149    def OnExportPDF(self,event):
    4150         #need S(Q) and G(R) to be saved here - probably best from selection?
     4150        'Save S(Q), G(R),... as selected by user'
     4151        def PDFSave(G2frame,exports,PDFsaves):
     4152            'Save a PDF I(Q), S(Q), F(Q) and G(r)  in column formats'
     4153            if len(exports) > 1:
     4154                dirname = G2G.askSaveDirectory(G2frame)
     4155                if not dirname: return
     4156            else:
     4157                defnam = exports[0].replace(' ','_')[5:]
     4158                filename = G2G.askSaveFile(G2frame,defnam,'.gr',
     4159                                               'G(r) file, etc.')
     4160                if not filename: return
     4161                dirname,filename = os.path.split(filename)
     4162                filename = os.path.splitext(filename)[0]
     4163            for export in exports:
     4164                if len(exports) > 1:
     4165                    filename = export.replace(' ','_')[5:]
     4166                PickId = GetGPXtreeItemId(G2frame, G2frame.root, export)
     4167                PDFControls = G2frame.GPXtree.GetItemPyData(
     4168                    GetGPXtreeItemId(G2frame, PickId,'PDF Controls'))
     4169                if PDFsaves[4]: #pdfGUI file for G(R)
     4170                    pId = GetGPXtreeItemId(G2frame, G2frame.root, 'PWDR'+export[4:])
     4171                    Inst = G2frame.GPXtree.GetItemPyData(
     4172                        GetGPXtreeItemId(G2frame, pId,'Instrument Parameters'))[0]
     4173                    Limits = G2frame.GPXtree.GetItemPyData(
     4174                        GetGPXtreeItemId(G2frame, pId,'Limits'))
     4175                G2fil.PDFWrite(export,os.path.join(dirname,filename),
     4176                            PDFsaves,PDFControls,Inst,Limits)
     4177       
    41514178        names = G2pdG.GetFileList(self,'PDF')
    41524179        exports = []
     
    41634190        if exports:
    41644191            PDFsaves = [od['value_1'],od['value_2'],od['value_3'],od['value_4'],od['value_5']]
    4165             G2IO.PDFSave(self,exports,PDFsaves)
     4192            PDFSave(self,exports,PDFsaves)
    41664193       
    41674194    def OnMakePDFs(self,event):
  • trunk/GSASIIfiles.py

    r3974 r3999  
    826826        masks[key] = masks.get(key,[])
    827827        masks[key] = [i for i in masks[key] if len(i)]
     828
     829def PDFWrite(PDFentry,fileroot,PDFsaves,PDFControls,Inst={},Limits=[]):
     830    '''Write PDF-related data (G(r), S(Q),...) into files, as
     831    selected.
     832
     833    :param str PDFentry: name of the PDF entry in the tree. This is
     834      used for comments in the file specifying where it came from;
     835      it can be arbitrary
     836    :param str fileroot: name of file(s) to be written. The extension
     837      will be ignored.
     838    :param list PDFsaves: flags that determine what type of file will be
     839      written:
     840      PDFsaves[0], if True writes a I(Q) file with a .iq extension
     841      PDFsaves[1], if True writes a S(Q) file with a .sq extension
     842      PDFsaves[2], if True writes a F(Q) file with a .fq extension
     843      PDFsaves[3], if True writes a G(r) file with a .gr extension
     844      PDFsaves[4], if True writes G(r) in a pdfGUI input file with
     845      a .gr extension. Note that if PDFsaves[3] and PDFsaves[4] are
     846      both True, the pdfGUI overwrites the G(r) file.
     847    :param dict PDFControls: The PDF parameters and computed results
     848    :param dict Inst: Instrument parameters from the PDWR entry used
     849      to compute the PDF. Needed only when PDFsaves[4] is True.
     850    :param list Limits: Computation limits from the PDWR entry used
     851      to compute the PDF. Needed only when PDFsaves[4] is True.
     852    '''
     853    import scipy.interpolate as scintp
     854    fileroot = os.path.splitext(fileroot)[0]
     855    if PDFsaves[0]:     #I(Q)
     856        iqfilename = fileroot+'.iq'
     857        iqdata = PDFControls['I(Q)'][1]
     858        iqfxn = scintp.interp1d(iqdata[0],iqdata[1],kind='linear')
     859        iqfile = open(iqfilename,'w')
     860        iqfile.write('#T I(Q) %s\n'%(PDFentry))
     861        iqfile.write('#L Q     I(Q)\n')
     862        qnew = np.arange(iqdata[0][0],iqdata[0][-1],0.005)
     863        iqnew = zip(qnew,iqfxn(qnew))
     864        for q,iq in iqnew:
     865            iqfile.write("%15.6g %15.6g\n" % (q,iq))
     866        iqfile.close()
     867        print (' I(Q) saved to: '+iqfilename)
     868
     869    if PDFsaves[1]:     #S(Q)
     870        sqfilename = fileroot+'.sq'
     871        sqdata = PDFControls['S(Q)'][1]
     872        sqfxn = scintp.interp1d(sqdata[0],sqdata[1],kind='linear')
     873        sqfile = open(sqfilename,'w')
     874        sqfile.write('#T S(Q) %s\n'%(PDFentry))
     875        sqfile.write('#L Q     S(Q)\n')
     876        qnew = np.arange(sqdata[0][0],sqdata[0][-1],0.005)
     877        sqnew = zip(qnew,sqfxn(qnew))
     878        for q,sq in sqnew:
     879            sqfile.write("%15.6g %15.6g\n" % (q,sq))
     880        sqfile.close()
     881        print (' S(Q) saved to: '+sqfilename)
     882
     883    if PDFsaves[2]:     #F(Q)
     884        fqfilename = fileroot+'.fq'
     885        fqdata = PDFControls['F(Q)'][1]
     886        fqfxn = scintp.interp1d(fqdata[0],fqdata[1],kind='linear')
     887        fqfile = open(fqfilename,'w')
     888        fqfile.write('#T F(Q) %s\n'%(PDFentry))
     889        fqfile.write('#L Q     F(Q)\n')
     890        qnew = np.arange(fqdata[0][0],fqdata[0][-1],0.005)
     891        fqnew = zip(qnew,fqfxn(qnew))
     892        for q,fq in fqnew:
     893            fqfile.write("%15.6g %15.6g\n" % (q,fq))
     894        fqfile.close()
     895        print (' F(Q) saved to: '+fqfilename)
     896
     897    if PDFsaves[3]:     #G(R)
     898        grfilename = fileroot+'.gr'
     899        grdata = PDFControls['G(R)'][1]
     900        grfxn = scintp.interp1d(grdata[0],grdata[1],kind='linear')
     901        grfile = open(grfilename,'w')
     902        grfile.write('#T G(R) %s\n'%(PDFentry))
     903        grfile.write('#L R     G(R)\n')
     904        rnew = np.arange(grdata[0][0],grdata[0][-1],0.010)
     905        grnew = zip(rnew,grfxn(rnew))
     906        for r,gr in grnew:
     907            grfile.write("%15.6g %15.6g\n" % (r,gr))
     908        grfile.close()
     909        print (' G(R) saved to: '+grfilename)
     910
     911    if PDFsaves[4]: #pdfGUI file for G(R)
     912        import GSASIImath as G2mth
     913        import GSASIIlattice as G2lat       
     914        grfilename = fileroot+'.gr'
     915        grdata = PDFControls['G(R)'][1]
     916        qdata = PDFControls['I(Q)'][1][0]
     917        grfxn = scintp.interp1d(grdata[0],grdata[1],kind='linear')
     918        grfile = open(grfilename,'w')
     919        rnew = np.arange(grdata[0][0],grdata[0][-1],0.010)
     920        grnew = zip(rnew,grfxn(rnew))
     921
     922        grfile.write('[DEFAULT]\n')
     923        grfile.write('\n')
     924        grfile.write('version = GSAS-II-v'+str(GSASIIpath.GetVersionNumber())+'\n')
     925        grfile.write('\n')
     926        grfile.write('# input and output specifications\n')
     927        grfile.write('dataformat = Qnm\n')
     928        grfile.write('inputfile = %s\n'%(PDFControls['Sample']['Name']))
     929        grfile.write('backgroundfile = %s\n'%(PDFControls['Sample Bkg.']['Name']))
     930        grfile.write('outputtype = gr\n')
     931        grfile.write('\n')
     932        grfile.write('# PDF calculation setup\n')
     933        if 'x' in Inst['Type']:
     934            grfile.write('mode = %s\n'%('xray'))
     935        elif 'N' in Inst['Type']:
     936            grfile.write('mode = %s\n'%('neutron'))
     937        wave = G2mth.getMeanWave(Inst)
     938        grfile.write('wavelength = %.5f\n'%(wave))
     939        formula = ''
     940        for el in PDFControls['ElList']:
     941            formula += el
     942            num = PDFControls['ElList'][el]['FormulaNo']
     943            if num == round(num):
     944                formula += '%d'%(int(num))
     945            else:
     946                formula += '%.2f'%(num)
     947        grfile.write('composition = %s\n'%(formula))
     948        grfile.write('bgscale = %.3f\n'%(-PDFControls['Sample Bkg.']['Mult']))
     949        highQ = 2.*np.pi/G2lat.Pos2dsp(Inst,Limits[1][1])
     950        grfile.write('qmaxinst = %.2f\n'%(highQ))
     951        grfile.write('qmin = %.5f\n'%(qdata[0]))
     952        grfile.write('qmax = %.4f\n'%(qdata[-1]))
     953        grfile.write('rmin = %.2f\n'%(PDFControls['Rmin']))
     954        grfile.write('rmax = %.2f\n'%(PDFControls['Rmax']))
     955        grfile.write('rstep = 0.01\n')
     956
     957
     958        grfile.write('\n')
     959        grfile.write('# End of config '+63*'-')
     960        grfile.write('\n')
     961        grfile.write('#### start data\n')
     962        grfile.write('#S 1\n')
     963        grfile.write('#L r($\AA$)  G($\AA^{-2}$)\n')           
     964        for r,gr in grnew:
     965            grfile.write("%15.2F %15.6F\n" % (r,gr))
     966        grfile.close()
     967        print (' G(R) saved to: '+grfilename)
  • trunk/GSASIIimage.py

    r3858 r3999  
    2828try:
    2929    import GSASIIplot as G2plt
    30 except (ImportError, ModuleNotFoundError): # expected in scriptable w/o matplotlib and/or wx
     30except ImportError: # expected in scriptable w/o matplotlib and/or wx
    3131    pass
    3232import GSASIIlattice as G2lat
  • trunk/GSASIIphsGUI.py

    r3998 r3999  
    50075007#        import scipy.optimize as opt
    50085008        wx.BeginBusyCursor()
    5009 #        Min,Init,Done = SetupPDFEval()
    5010 #        xstart = Init()
    5011 #        rms = Min(xstart)
    5012 #        print('Optimizing corrections to improve G(r) at low r')
    5013 #        print('start: Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} (RMS:{:.2f})'.format(
    5014 #                data['Flat Bkg'],data['BackRatio'],data['Ruland'],rms))
    5015 #       
    5016 #        res = opt.minimize(Min,xstart,bounds=([0,None],[0,1],[0.01,1]),
    5017 #                           method='L-BFGS-B',options={'maxiter':5})
    5018 #        Done(res['x'])     
    5019 #        print('end:   Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} (RMS:{:.2f})\n'.format(
    5020 #                data['Flat Bkg'],data['BackRatio'],data['Ruland'],res['fun']))
     5009        # see pwd.SetupPDFEval() and pwd.OptimizePDF() for an example minimization
    50215010        wx.EndBusyCursor()
    50225011        wx.CallAfter(UpdateLayerData)
  • trunk/GSASIIplot.py

    r3983 r3999  
    117117import numpy.ma as ma
    118118import numpy.linalg as nl
    119 from scipy.ndimage.interpolation import map_coordinates
    120 # Don't depend on wx/matplotlib for scriptable
     119# Don't depend on wx/matplotlib/scipy for scriptable; or for Sphinx docs
    121120try:
    122121    import wx
     
    127126    import matplotlib.collections as mplC
    128127    import mpl_toolkits.mplot3d.axes3d as mp3d
     128    from scipy.ndimage.interpolation import map_coordinates
    129129except ImportError:
    130130    pass
  • trunk/GSASIIpwd.py

    r3995 r3999  
    495495    auxPlot.append([R[:iFin],DofR[:iFin],'D(R) for '+RDFcontrols['UseObsCalc']])   
    496496    return auxPlot
     497
     498# PDF optimization =============================================================
     499def OptimizePDF(data,xydata,limits,inst,showFit=True,maxCycles=5):
     500    import scipy.optimize as opt
     501    numbDen = GetNumDensity(data['ElList'],data['Form Vol'])
     502    Min,Init,Done = SetupPDFEval(data,xydata,limits,inst,numbDen)
     503    xstart = Init()
     504    bakMul = data['Sample Bkg.']['Mult']
     505    if showFit:
     506        rms = Min(xstart)
     507        print('  Optimizing corrections to improve G(r) at low r')
     508        if data['Sample Bkg.'].get('Refine',False):
     509#            data['Flat Bkg'] = 0.
     510            print('  start: Ruland={:.3f}, Sample Bkg mult={:.3f} (RMS:{:.4f})'.format(
     511                data['Ruland'],data['Sample Bkg.']['Mult'],rms))
     512        else:
     513            print('  start: Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} (RMS:{:.4f})'.format(
     514                data['Flat Bkg'],data['BackRatio'],data['Ruland'],rms))
     515    if data['Sample Bkg.'].get('Refine',False):
     516        res = opt.minimize(Min,xstart,bounds=([0.01,1],[1.2*bakMul,0.8*bakMul]),
     517                    method='L-BFGS-B',options={'maxiter':maxCycles},tol=0.001)
     518    else:
     519        res = opt.minimize(Min,xstart,bounds=([0,None],[0,1],[0.01,1]),
     520                    method='L-BFGS-B',options={'maxiter':maxCycles},tol=0.001)
     521    Done(res['x'])
     522    if showFit:
     523        if res['success']:
     524            msg = 'Converged'
     525        else:
     526            msg = 'Not Converged'
     527        if data['Sample Bkg.'].get('Refine',False):
     528            print('  end:   Ruland={:.3f}, Sample Bkg mult={:.3f} (RMS:{:.4f}) *** {} ***\n'.format(
     529                data['Ruland'],data['Sample Bkg.']['Mult'],res['fun'],msg))
     530        else:
     531            print('  end:   Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f}) *** {} ***\n'.format(
     532                data['Flat Bkg'],data['BackRatio'],data['Ruland'],res['fun'],msg))
     533    return res
     534
     535def SetupPDFEval(data,xydata,limits,inst,numbDen):
     536    Data = copy.deepcopy(data)
     537    BkgMax = 1.
     538    def EvalLowPDF(arg):
     539        '''Objective routine -- evaluates the RMS deviations in G(r)
     540        from -4(pi)*#density*r for for r<Rmin
     541        arguments are ['Flat Bkg','BackRatio','Ruland'] scaled so that
     542        the min & max values are between 0 and 1.
     543        '''
     544        if Data['Sample Bkg.'].get('Refine',False):
     545            R,S = arg
     546            Data['Sample Bkg.']['Mult'] = S
     547        else:
     548            F,B,R = arg
     549            Data['Flat Bkg'] = F*BkgMax
     550            Data['BackRatio'] = B
     551        Data['Ruland'] = R/10.
     552        CalcPDF(Data,inst,limits,xydata)
     553        # test low r computation
     554        g = xydata['GofR'][1][1]
     555        r = xydata['GofR'][1][0]
     556        g0 = g[r < Data['Rmin']] + 4*np.pi*r[r < Data['Rmin']]*numbDen
     557        M = sum(g0**2)/len(g0)
     558        return M
     559    def GetCurrentVals():
     560        '''Get the current ['Flat Bkg','BackRatio','Ruland'] with scaling
     561        '''
     562        if data['Sample Bkg.'].get('Refine',False):
     563                return [max(10*data['Ruland'],.05),data['Sample']['Mult']]
     564        try:
     565            F = data['Flat Bkg']/BkgMax
     566        except:
     567            F = 0
     568        return [F,data['BackRatio'],max(10*data['Ruland'],.05)]
     569    def SetFinalVals(arg):
     570        '''Set the 'Flat Bkg', 'BackRatio' & 'Ruland' values from the
     571        scaled, refined values and plot corrected region of G(r)
     572        '''
     573        if data['Sample Bkg.'].get('Refine',False):
     574            R,S = arg
     575            data['Sample Bkg.']['Mult'] = S
     576        else:
     577            F,B,R = arg
     578            data['Flat Bkg'] = F*BkgMax
     579            data['BackRatio'] = B
     580        data['Ruland'] = R/10.
     581        CalcPDF(data,inst,limits,xydata)
     582    EvalLowPDF(GetCurrentVals())
     583    BkgMax = max(xydata['IofQ'][1][1])/50.
     584    return EvalLowPDF,GetCurrentVals,SetFinalVals
    497585
    498586################################################################################       
  • trunk/GSASIIpwdGUI.py

    r3995 r3999  
    63326332        if name.strip():
    63336333            pId = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,name)
    6334             if pId == 0:
     6334            if not pId:
    63356335                print(key,'Entry',name,'Not found.')
    63366336                problem = True
     
    63546354    low r (-4 pi r #density).
    63556355    '''
    6356     import scipy.optimize as opt
    6357     Min,Init,Done = SetupPDFEval(G2frame,data)
    6358     xstart = Init()
    6359     bakMul = data['Sample Bkg.']['Mult']
    6360     if showFit:
    6361         rms = Min(xstart)
    6362         print('  Optimizing corrections to improve G(r) at low r')
    6363         if data['Sample Bkg.'].get('Refine',False):
    6364 #            data['Flat Bkg'] = 0.
    6365             print('  start: Ruland={:.3f}, Sample Bkg mult={:.3f} (RMS:{:.4f})'.format(
    6366                 data['Ruland'],data['Sample Bkg.']['Mult'],rms))
    6367         else:
    6368             print('  start: Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} (RMS:{:.4f})'.format(
    6369                 data['Flat Bkg'],data['BackRatio'],data['Ruland'],rms))
    6370     if data['Sample Bkg.'].get('Refine',False):
    6371         res = opt.minimize(Min,xstart,bounds=([0.01,1],[1.2*bakMul,0.8*bakMul]),
    6372                     method='L-BFGS-B',options={'maxiter':maxCycles},tol=0.001)
    6373     else:
    6374         res = opt.minimize(Min,xstart,bounds=([0,None],[0,1],[0.01,1]),
    6375                     method='L-BFGS-B',options={'maxiter':maxCycles},tol=0.001)
    6376     Done(res['x'])
    6377     if showFit:
    6378         if res['success']:
    6379             msg = 'Converged'
    6380         else:
    6381             msg = 'Not Converged'
    6382         if data['Sample Bkg.'].get('Refine',False):
    6383             print('  end:   Ruland={:.3f}, Sample Bkg mult={:.3f} (RMS:{:.4f}) *** {} ***\n'.format(
    6384                 data['Ruland'],data['Sample Bkg.']['Mult'],res['fun'],msg))
    6385         else:
    6386             print('  end:   Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f}) *** {} ***\n'.format(
    6387                 data['Flat Bkg'],data['BackRatio'],data['Ruland'],res['fun'],msg))
    6388     return res['success']
    6389 
    6390 def SetupPDFEval(G2frame,data):
    6391     '''Create functions needed to optimize the PDF at low r
    6392     '''
    6393     Data = copy.deepcopy(data)
    63946356    xydata = {}
    63956357    for key in ['Sample','Sample Bkg.','Container','Container Bkg.']:
    6396         name = Data[key]['Name']
     6358        name = data[key]['Name']
    63976359        if name:
    63986360            xydata[key] = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,G2frame.root,name))
    6399     powName = Data['Sample']['Name']
     6361    powName = data['Sample']['Name']
    64006362    powId = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,powName)
    64016363    limits = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,powId,'Limits'))[1]
    64026364    inst = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,powId,'Instrument Parameters'))[0]
    6403     numbDen = G2pwd.GetNumDensity(Data['ElList'],Data['Form Vol'])
    6404     BkgMax = 1.
    6405     def EvalLowPDF(arg):
    6406         '''Objective routine -- evaluates the RMS deviations in G(r)
    6407         from -4(pi)*#density*r for for r<Rmin
    6408         arguments are ['Flat Bkg','BackRatio','Ruland'] scaled so that
    6409         the min & max values are between 0 and 1.
    6410         '''
    6411         if Data['Sample Bkg.'].get('Refine',False):
    6412             R,S = arg
    6413             Data['Sample Bkg.']['Mult'] = S
    6414         else:
    6415             F,B,R = arg
    6416             Data['Flat Bkg'] = F*BkgMax
    6417             Data['BackRatio'] = B
    6418         Data['Ruland'] = R/10.
    6419         G2pwd.CalcPDF(Data,inst,limits,xydata)
    6420         # test low r computation
    6421         g = xydata['GofR'][1][1]
    6422         r = xydata['GofR'][1][0]
    6423         g0 = g[r < Data['Rmin']] + 4*np.pi*r[r < Data['Rmin']]*numbDen
    6424         M = sum(g0**2)/len(g0)
    6425         return M
    6426     def GetCurrentVals():
    6427         '''Get the current ['Flat Bkg','BackRatio','Ruland'] with scaling
    6428         '''
    6429         if data['Sample Bkg.'].get('Refine',False):
    6430                 return [max(10*data['Ruland'],.05),data['Sample']['Mult']]
    6431         try:
    6432             F = data['Flat Bkg']/BkgMax
    6433         except:
    6434             F = 0
    6435         return [F,data['BackRatio'],max(10*data['Ruland'],.05)]
    6436     def SetFinalVals(arg):
    6437         '''Set the 'Flat Bkg', 'BackRatio' & 'Ruland' values from the
    6438         scaled, refined values and plot corrected region of G(r)
    6439         '''
    6440         if data['Sample Bkg.'].get('Refine',False):
    6441             R,S = arg
    6442             data['Sample Bkg.']['Mult'] = S
    6443         else:
    6444             F,B,R = arg
    6445             data['Flat Bkg'] = F*BkgMax
    6446             data['BackRatio'] = B
    6447         data['Ruland'] = R/10.
    6448         G2pwd.CalcPDF(data,inst,limits,xydata)
    6449     EvalLowPDF(GetCurrentVals())
    6450     BkgMax = max(xydata['IofQ'][1][1])/50.
    6451     return EvalLowPDF,GetCurrentVals,SetFinalVals
     6365    res = G2pwd.OptimizePDF(data,xydata,limits,inst,showFit,maxCycles)
     6366    return res['success']
    64526367   
    64536368def UpdatePDFGrid(G2frame,data):
     
    65336448            mulBox.Add(multSpin,0,WACV)
    65346449            fileSizer.Add(mulBox,0,WACV)
    6535             if 'Refine' in item and item['Name']:
     6450            if 'Refine' in item and item['Name'] and 'Sample' in key:
    65366451                refMult = wx.CheckBox(parent=G2frame.dataWindow,label='Refine?')
    65376452                refMult.SetValue(item['Refine'])
     
    66686583            finally:
    66696584                wx.EndBusyCursor()
     6585            OnComputePDF(event)
    66706586            wx.CallAfter(UpdatePDFGrid,G2frame,data)
    6671             OnComputePDF(event)       
    66726587                       
    66736588        def AfterChangeNoRefresh(invalid,value,tc):
     
    71177032        mainSizer.Add(SFGctrlSizer(),0,WACV)
    71187033        G2G.HorizontalLine(mainSizer,G2frame.dataWindow)
    7119     mainSizer.Add(DiffSizer(),0,WACV)
     7034        mainSizer.Add(DiffSizer(),0,WACV)
     7035    else:
     7036        mainSizer.Add(wx.StaticText(G2frame.dataWindow,wx.ID_ANY,
     7037                                     powName+' not in Tree'))
    71207038    G2frame.dataWindow.SetDataSize()
    71217039
  • trunk/GSASIIscriptable.py

    r3970 r3999  
    112112:meth:`G2Project.add_phase`                           Adds a phase to a project
    113113
     114:meth:`G2Project.add_PDF`                             Adds a PDF entry to a project (does not compute it)
     115
    114116:meth:`G2Project.histograms`                          Provides a list of histograms in the current project, as :class:`G2PwdrData` objects
    115117
     
    117119
    118120:meth:`G2Project.images`                              Provides a list of images in the current project, as :class:`G2Image` objects
     121
     122:meth:`G2Project.pdfs`                                Provides a list of PDFs in the current project, as :class:`G2PDF` objects
    119123
    120124:meth:`G2Project.do_refinements`                      This is passed a list of dictionaries, where each dict defines a refinement step.
     
    201205:meth:`G2Image.setControlFile`                        Set a image to be used as a background/dark/gain map image.
    202206==================================================    ===============================================================================================================
     207
     208
     209---------------------
     210:class:`G2PDF`
     211---------------------
     212
     213  To work with PDF entries, object :class:`G2PDF`, encapsulates a PDF entry with methods:
     214
     215.. tabularcolumns:: |l|p{3.5in}|
     216
     217==================================================    ===============================================================================================================
     218method                                                Use
     219==================================================    ===============================================================================================================
     220:meth:`G2PDF.export`                                   Used to write G(r), etc. as a file
     221:meth:`G2PDF.calculate`                                Computes the PDF using parameters in the object
     222:meth:`G2PDF.optimize`                                 Optimizes selected PDF parameters
     223:meth:`G2PDF.set_background`                           Sets the histograms used for sample background, container, etc.
     224:meth:`G2PDF.set_formula`                              Sets the chemical formula for the sample
     225==================================================    ===============================================================================================================
     226
    203227
    204228----------------------
     
    704728To change settings within histograms, images and phases, one usually needs to use
    705729methods inside :class:`G2PwdrData`, :class:`G2Image` or :class:`G2Phase`.
    706 
    707730"""
     731
     732#============================================================================
     733# adding a new object type
     734# 1) add a new object class (e.g. G2PDF)
     735# 2) add the wrapper into G2Project (e.g. _pdfs, pdf, pdfs)
     736# 3) add a new method to add the object into a project (G2Project.add_PDF)
     737# 4) add to documentation in section :class:`G2Project`
     738# 5) add a new documentation section for the new class
     739#============================================================================
     740
    708741from __future__ import division, print_function
    709742import argparse
     
    19752008        """
    19762009        return [G2Image(self.data[i],i,self) for i in self._images()]
     2010   
     2011    def _pdfs(self):
     2012        """Returns a list of all the PDF entries in the project.
     2013        """
     2014        return [i[0] for i in self.names if i[0].startswith('PDF ')]
     2015   
     2016    def pdf(self, pdfRef):
     2017        """
     2018        Gives an object representing the specified PDF entry in this project.
     2019
     2020        :param pdfRef: A reference to the desired image. Either the PDF
     2021          tree name (str), the pdf's index (int) or
     2022          a PDF object (:class:`G2PDF`)
     2023        :returns: A :class:`G2PDF` object
     2024        :raises: KeyError
     2025
     2026        .. seealso::
     2027            :meth:`~G2Project.pdfs`
     2028            :class:`~G2PDF`
     2029        """
     2030        if isinstance(pdfRef, G2PDF):
     2031            if pdfRef.proj == self:
     2032                return pdfRef
     2033            else:
     2034                raise Exception("PDF {} not in current selected project".format(pdfRef.name))
     2035        if pdfRef in self._pdfs():
     2036            return G2PDF(self.data[pdfRef], pdfRef, self)
     2037
     2038        try:
     2039            # pdfRef should be an index
     2040            num = int(pdfRef)
     2041            pdfRef = self._pdfs()[num]
     2042            return G2PDF(self.data[pdfRef], pdfRef, self)
     2043        except ValueError:
     2044            raise Exception("pdfRef {} not an object, name or PDF index in current selected project"
     2045                                .format(pdfRef))
     2046        except IndexError:
     2047            raise Exception("pdfRef {} out of range (max={}) in current selected project"
     2048                                .format(pdfRef,len(self._images())-1))
     2049    def pdfs(self):
     2050        """
     2051        Returns a list of all the PDFs in the project.
     2052
     2053        :returns: A list of :class:`G2PDF` objects
     2054        """
     2055        return [G2PDF(self.data[i],i,self) for i in self._pdfs()]
     2056       
     2057    def add_PDF(self, prmfile, histogram):
     2058        '''Creates a PDF entry that can be used to compute a PDF.
     2059        Note that this command places an entry in the project,
     2060        but :meth:`G2PDF.calculate` must be used to actually perform
     2061        the computation.
     2062
     2063        :param str datafile: The powder data file to read, a filename.
     2064        :param histogram: A reference to a histogram,
     2065          which can be reference by object, name, or number.
     2066        :returns: A :class:`G2PDF` object for the PDF entry
     2067        '''
     2068       
     2069        LoadG2fil()
     2070        PDFname = 'PDF ' + self.histogram(histogram).name[4:]
     2071        peaks = {'Limits':[1.,5.],'Background':[2,[0.,-0.2*np.pi],False],'Peaks':[]}
     2072        Controls = {
     2073            'Sample':{'Name':self.histogram(histogram).name,'Mult':1.0},
     2074            'Sample Bkg.':{'Name':'','Mult':-1.0,'Refine':False},
     2075            'Container':{'Name':'','Mult':-1.0,'Refine':False},
     2076            'Container Bkg.':{'Name':'','Mult':-1.0},
     2077            'ElList':{},
     2078            'Geometry':'Cylinder','Diam':1.0,'Pack':0.50,'Form Vol':0.0,'Flat Bkg':0,
     2079            'DetType':'Area detector','ObliqCoeff':0.2,'Ruland':0.025,'QScaleLim':[20,25],
     2080            'Lorch':False,'BackRatio':0.0,'Rmax':100.,'noRing':False,'IofQmin':1.0,'Rmin':1.0,
     2081            'I(Q)':[],'S(Q)':[],'F(Q)':[],'G(R)':[]}
     2082
     2083        fo = open(prmfile,'r')
     2084        S = fo.readline()
     2085        while S:
     2086            if '#' in S:
     2087                S = fo.readline()
     2088                continue
     2089            key,val = S.split(':',1)
     2090            try:
     2091                Controls[key] = eval(val)
     2092            except:
     2093                Controls[key] = val.strip()
     2094            S = fo.readline()
     2095        fo.close()
     2096        Controls['Sample']['Name'] = self.histogram(histogram).name
     2097        for i in 'Sample Bkg.','Container','Container Bkg.':
     2098            Controls[i]['Name'] = ''
     2099        PDFdict = {'data':None,'PDF Controls':Controls, 'PDF Peaks':peaks}
     2100        self.names.append([PDFname]+['PDF Controls', 'PDF Peaks'])
     2101        self.data[PDFname] = PDFdict
     2102        print('Adding "{}" to project'.format(PDFname))
     2103        return G2PDF(self.data[PDFname], PDFname, self)
     2104
     2105    # def seqref(self):
     2106    #     """
     2107    #     Returns a sequential refinement results object, if present
     2108
     2109    #     :returns: A :class:`G2SeqRefRes` object or None if not present
     2110    #     """
     2111    #     if 'Sequential results' not in self.data: return
     2112    #     return G2SeqRefRes(self.data['Sequential results']['data'], self)
    19772113   
    19782114    def update_ids(self):
     
    36233759                else:
    36243760                    print(u'Unknown HAP key: '+key)
     3761
     3762# class G2SeqRefRes(G2ObjectWrapper):
     3763#     '''Wrapper for a Sequential Refinement Results tree entry, containing the
     3764#     results for a refinement
     3765#     '''
     3766#     def __init__(self, data, proj):
     3767#         self.data = data
     3768#         self.proj = proj
     3769       
     3770# #    @property
     3771#     def histograms(self):
     3772#         '''returns a list of histograms in the squential fit
     3773#         '''
     3774#         return self.data['histNames']
     3775
     3776#     def get_cell_and_esd(self,phase,hist):
     3777#         import GSASIIlattice as G2lat
     3778#         cellGUIlist = [
     3779#         [['m3','m3m'],(0,)],
     3780#         [['3R','3mR'],(0,3)],
     3781#         [['3','3m1','31m','6/m','6/mmm','4/m','4/mmm'],(0,2)],
     3782#         [['mmm'],(0,1,2)],
     3783#         [['2/m'+'a'],(0,1,2,3)],
     3784#         [['2/m'+'b'],(0,1,2,4)],
     3785#         [['2/m'+'c'],(0,1,2,5)],
     3786#         [['-1'],(0,1,2,3,4,5)],
     3787#         ]
     3788
     3789#         initialCell = {}
     3790#         seqData,histData = self.RefData(hist)
     3791#         hId = histData['data'][0]['hId']
     3792#         phasedict = self.proj.phase(phase).data
     3793#         pId = phasedict['pId']
     3794#         pfx = str(pId)+'::' # prefix for A values from phase
     3795#         phfx = '%d:%d:'%(pId,hId) # Dij prefix
     3796#         RcellLbls = [pfx+'A'+str(i) for i in range(6)]
     3797#         RecpCellTerms = G2lat.cell2A(phasedict['General']['Cell'][1:7])
     3798#         zeroDict = dict(zip(RcellLbls[pId],6*[0.,]))
     3799#         SGdata = phasedict['General']['SGData']
     3800#         laue = SGdata['SGLaue']
     3801#         if laue == '2/m':
     3802#             laue += SGdata['SGUniq']
     3803#         for symlist,celllist in cellGUIlist:
     3804#             if laue in symlist:
     3805#                 uniqCellIndx = celllist
     3806#                 break
     3807#         else: # should not happen
     3808#             uniqCellIndx = list(range(6))
     3809#         for i in uniqCellIndx:
     3810#             initialCell[str(pId)+'::A'+str(i)] =  RecpCellTerms[i]
     3811
     3812
     3813#         esdLookUp = {}
     3814#         dLookup = {}
     3815#         # note that varyList keys are p:h:Dij while newCellDict keys are p::Dij
     3816#         for nKey in seqData['newCellDict']:
     3817#             uniqCellIndx = list(range(6))
     3818#         for i in uniqCellIndx:
     3819#             initialCell[str(pId)+'::A'+str(i)] =  RecpCellTerms[i]
     3820
     3821
     3822#         esdLookUp = {}
     3823#         dLookup = {}
     3824#         # note that varyList keys are p:h:Dij while newCellDict keys are p::Dij
     3825#         for nKey in seqData['newCellDict']:
     3826#             p = nKey.find('::')+1
     3827#             vKey = nKey[:p] + str(hId) + nKey[p:]
     3828#             if phfx+item.split('::')[1] in seqData['varyList']:
     3829#                 esdLookUp[newCellDict[item][0]] = item
     3830#                 dLookup[item] = newCellDict[item][0]
     3831#         covData = {'varyList': [dLookup.get(striphist(v),v) for v in seqData['varyList']],
     3832#                 'covMatrix': seqData['covMatrix']}
     3833#         A = RecpCellTerms[pId][:] # make copy of starting A values
     3834
     3835       
     3836    def RefData(self,hist):
     3837        try:
     3838            hist = self.data['histNames'][hist]
     3839        except IndexError:
     3840            raise Exception('Histogram #{} is out of range from the Sequential Refinement'
     3841                                .format(hist))
     3842        except TypeError:
     3843            pass
     3844        if hist not in self.data['histNames']:
     3845            raise Exception('Histogram {} is not included in the Sequential Refinement'
     3846                                .format(hist))
     3847        return self.data[hist],self.proj.histogram(hist).data
     3848
     3849class G2PDF(G2ObjectWrapper):
     3850    """Wrapper for a PDF tree entry, containing the information needed to
     3851    compute a PDF and the S(Q, G(r) etc. after the computation is done.
     3852    Note that in a GSASIIscriptable script, instances of G2PDF will be created by
     3853    calls to :meth:`G2Project.add_PDF` or :meth:`G2Project.pdf`, not via calls
     3854    to :meth:`G2PDF.__init__`.
     3855
     3856    Example use of G2PDF::
     3857
     3858       gpx.add_PDF('250umSiO2.pdfprm',0)
     3859       pdf.set_formula(['Si',1],['O',2])
     3860       pdf.set_background('Container',1,-0.21)
     3861       for i in range(5):
     3862           if pdf.optimize(): break
     3863       pdf.calculate()
     3864       pdf.export(gpx.filename,'S(Q), pdfGUI')
     3865       gpx.save('pdfcalc.gpx')
     3866
     3867    """
     3868    def __init__(self, data, name, proj):
     3869        self.data = data
     3870        self.name = name
     3871        self.proj = proj
     3872    def set_background(self,btype,histogram,mult=-1.,refine=False):
     3873        '''Sets a histogram to be used as the 'Sample Background',
     3874        the 'Container' or the 'Container Background.'
     3875
     3876        :param str btype: Type of background to set, must contain
     3877          the string 'samp' for Sample Background', 'cont' and 'back'
     3878          for the 'Container Background' or only 'cont' for the
     3879          'Container'. Note that capitalization and extra characters
     3880          are ignored, so the full strings (such as 'Sample
     3881          Background' & 'Container Background') can be used.
     3882       
     3883        :param histogram: A reference to a histogram,
     3884          which can be reference by object, name, or number.
     3885        :param float mult: a multiplier for the histogram; defaults
     3886          to -1.0
     3887        :param bool refine: a flag to enable refinement (only
     3888          implemented for 'Sample Background'); defaults to False
     3889        '''
     3890        if 'samp' in btype.lower():
     3891            key = 'Sample Bkg.'
     3892        elif 'cont' in btype.lower() and 'back' in btype.lower():
     3893            key = 'Container Bkg.'
     3894        elif 'cont' in btype.lower():
     3895            key = 'Container'
     3896        else:
     3897            raise Exception('btype = {} is invalid'.format(btype))
     3898        self.data['PDF Controls'][key]['Name'] = self.proj.histogram(histogram).name
     3899        self.data['PDF Controls'][key]['Mult'] = mult
     3900        self.data['PDF Controls'][key]['Refine'] = refine
     3901
     3902    def set_formula(self,*args):
     3903        '''Set the chemical formula for the PDF computation.
     3904        Use pdf.set_formula(['Si',1],['O',2]) for SiO2.
     3905
     3906        :param list item1: The element symbol and number of atoms in formula for first element
     3907        :param list item2: The element symbol and number of atoms in formula for second element,...
     3908
     3909        repeat parameters as needed for all elements in the formula.
     3910        '''
     3911        powderHist = self.proj.histogram(self.data['PDF Controls']['Sample']['Name'])
     3912        inst = powderHist.data['Instrument Parameters'][0]
     3913        ElList = self.data['PDF Controls']['ElList']
     3914        ElList.clear()
     3915        sumVol = 0.
     3916        for elem,mult in args:
     3917            ElList[elem] = G2elem.GetElInfo(elem,inst)
     3918            ElList[elem]['FormulaNo'] = mult
     3919            Avol = (4.*np.pi/3.)*ElList[elem]['Drad']**3
     3920            sumVol += Avol*ElList[elem]['FormulaNo']
     3921        self.data['PDF Controls']['Form Vol'] = max(10.0,sumVol)
     3922       
     3923    def calculate(self):
     3924        '''Compute the PDF using the current parameters. Results are set
     3925        in the PDF object arrays (self.data['PDF Controls']['G(R)'] etc.)
     3926        '''
     3927        data = self.data['PDF Controls']
     3928        xydata = {}
     3929        for key in 'Sample Bkg.','Container Bkg.','Container','Sample':
     3930            name = data[key]['Name'].strip()
     3931            if name:
     3932                xydata[key] = self.proj.histogram(name).data['data']
     3933                if key != 'Sample': continue
     3934                limits = self.proj.histogram(name).data['Limits'][1]
     3935                inst = self.proj.histogram(name).data['Instrument Parameters'][0]
     3936        G2pwd.CalcPDF(data,inst,limits,xydata)
     3937        data['I(Q)'] = xydata['IofQ']
     3938        data['S(Q)'] = xydata['SofQ']
     3939        data['F(Q)'] = xydata['FofQ']
     3940        data['G(R)'] = xydata['GofR']
     3941
     3942    def optimize(self,showFit=True,maxCycles=5):
     3943        '''Optimize the low R portion of G(R) to minimize selected
     3944        parameters. Note that this updates the parameters in the settings
     3945        (self.data['PDF Controls']) but does not update the PDF object
     3946        arrays (self.data['PDF Controls']['G(R)'] etc.) with the computed
     3947        values, use :meth:`calculate` after a fit to do that.
     3948
     3949        :param bool showFit: if True (default) the optimized parameters
     3950          are shown before and after the fit, as well as the RMS value
     3951          in the minimized region.
     3952        :param int maxCycles: the maximum number of least-squares cycles;
     3953          defaults to 5.
     3954        :returns: the result from the optimizer as True or False, depending
     3955          on if the refinement converged.
     3956        '''
     3957        data = self.data['PDF Controls']
     3958        xydata = {}
     3959        for key in 'Sample Bkg.','Container Bkg.','Container','Sample':
     3960            name = data[key]['Name'].strip()
     3961            if name:
     3962                xydata[key] = self.proj.histogram(name).data['data']
     3963                if key != 'Sample': continue
     3964                limits = self.proj.histogram(name).data['Limits'][1]
     3965                inst = self.proj.histogram(name).data['Instrument Parameters'][0]
     3966        res = G2pwd.OptimizePDF(data,xydata,limits,inst,showFit,maxCycles)
     3967        return res['success']
     3968       
     3969    def export(self,fileroot,formats):
     3970        '''Write out the PDF-related data (G(r), S(Q),...) into files
     3971
     3972        :param str fileroot: name of file(s) to be written. The extension
     3973          will be ignored and set to .iq, .sq, .fq or .gr depending
     3974          on the formats selected.
     3975        :param str formats: string specifying the file format(s) to be written,
     3976          should contain at least one of the following keywords:
     3977          I(Q), S(Q), F(Q), G(r) and/or PDFgui (capitalization and
     3978          punctuation is ignored). Note that G(r) and PDFgui should not
     3979          be specifed together.
     3980        '''
     3981        PDFsaves = 5*[False]
     3982        PDFentry = self.name
     3983        name = self.data['PDF Controls']['Sample']['Name'].strip()
     3984        limits = self.proj.histogram(name).data['Limits']
     3985        inst = self.proj.histogram(name).data['Instrument Parameters'][0]
     3986        for i,lbl in enumerate(['I(Q)', 'S(Q)', 'F(Q)', 'G(r)', 'PDFgui']):
     3987            PDFsaves[i] = lbl.lower() in formats.lower()
     3988        G2fil.PDFWrite(PDFentry,fileroot,PDFsaves,self.data['PDF Controls'],inst,limits)
    36253989
    36263990class G2Image(G2ObjectWrapper):
Note: See TracChangeset for help on using the changeset viewer.