Changeset 2670


Ignore:
Timestamp:
Jan 28, 2017 12:12:49 PM (5 years ago)
Author:
toby
Message:

Add PDF computation to autointegrate

Location:
trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIimgGUI.py

    r2630 r2670  
    3030import GSASIIimage as G2img
    3131import GSASIImath as G2mth
     32import GSASIIpwdGUI as G2pdG
    3233import GSASIIplot as G2plt
    3334import GSASIIIO as G2IO
    3435import GSASIIgrid as G2gd
    3536import GSASIIctrls as G2G
     37import GSASIIobj as G2obj
    3638import GSASIIpy3 as G2py3
    3739
     
    4446cosd = lambda x: math.cos(x*math.pi/180.)
    4547asind = lambda x: 180.*math.asin(x)/math.pi
     48tth2q = lambda t,w:4.0*math.pi*sind(t/2.0)/w
    4649   
    4750################################################################################
     
    22062209                if self.timer.IsRunning(): self.timer.Stop()
    22072210                self.PreventReEntryTimer = False
    2208                 self.StartLoop()
     2211                if self.StartLoop():
     2212                    G2G.G2MessageBox(self,'Error in setting up integration. See console')
     2213                    return
    22092214                self.OnTimerLoop(None) # run once immediately
    22102215                if not self.Pause:
     
    22502255                    dlg.Destroy()
    22512256                return
     2257            elif btn4 == event.GetEventObject():
     2258                msg = ''
     2259                pth = G2G.GetExportPath(G2frame)
     2260                dlg = wx.FileDialog(
     2261                    self, 'Select a PDF parameter file',
     2262                    pth, self.params['pdfprm'],
     2263                    "PDF controls file (*.pdfprm)|*.pdfprm",
     2264                    wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
     2265                dlg.CenterOnParent()
     2266                try:
     2267                    if dlg.ShowModal() == wx.ID_OK:
     2268                        self.params['pdfprm'] = dlg.GetPath()
     2269                        fInp4.SetValue(self.params['pdfprm'])
     2270                        scanPDFprm()
     2271                        msg = self.checkPDFprm()
     2272                finally:
     2273                    dlg.Destroy()
     2274                if msg: G2G.G2MessageBox(self,msg,'Warning')
     2275                return
    22522276               
    22532277        def OnRadioSelect(event):
     
    23022326            finally:
    23032327                dlg.Destroy()
    2304 
     2328               
     2329        def showPDFctrls(event):
     2330            '''Called to show or hide AutoPDF widgets. Note that fInp4 must be included in the
     2331            sizer layout with .Show(True) before .Show(False) will work properly.
     2332            '''
     2333            fInp4.Enable(self.params['ComputePDF'])
     2334            fInp4.Show(self.params['ComputePDF'])
     2335            fInp4a.Enable(self.params['ComputePDF'])
     2336            btn4.Enable(self.params['ComputePDF'])
     2337            if self.params['ComputePDF']:
     2338                lbl4.SetForegroundColour("black")
     2339                lbl4a.SetForegroundColour("black")
     2340            else:
     2341                lbl4.SetForegroundColour("gray")
     2342                lbl4a.SetForegroundColour("gray")
     2343                                   
     2344        def scanPDFprm(**kw):
     2345            fInp4.invalid = not os.path.exists(fInp4.GetValue())
     2346            fInp4._IndicateValidity()
     2347               
    23052348        ##################################################
    23062349        # beginning of __init__ processing
     
    23222365        self.timer.Bind(wx.EVT_TIMER,self.OnTimerLoop)
    23232366        self.imageBase = G2frame.Image
     2367        self.params['ComputePDF'] = False
     2368        self.params['pdfDmax'] = 0.0
     2369        self.params['pdfprm'] = ''
     2370        self.pdfControls = {}
    23242371
    23252372        G2frame.PatternTree.GetSelection()
     
    23702417        lblsizr = wx.StaticBoxSizer(lbl, wx.VERTICAL)
    23712418        sizer = wx.BoxSizer(wx.HORIZONTAL)
    2372         sizer.Add(wx.StaticText(mnpnl, wx.ID_ANY,'Write to: '))
     2419        sizer.Add(wx.StaticText(mnpnl, wx.ID_ANY,'Write to: '),0,wx.ALIGN_CENTER_VERTICAL)
    23732420        fInp3 = G2G.ValidatedTxtCtrl(mnpnl,self.params,'outdir',notBlank=False,size=(300,-1))
    2374         sizer.Add(fInp3)
     2421        sizer.Add(fInp3,1,wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
    23752422        btn3 = wx.Button(mnpnl,  wx.ID_ANY, "Browse")
    23762423        btn3.Bind(wx.EVT_BUTTON, OnBrowse)
    2377         sizer.Add(btn3)
    2378         lblsizr.Add(sizer)
    2379         #lblsizr.Add(wx.StaticText(mnpnl, wx.ID_ANY,'Select format(s): '))
     2424        sizer.Add(btn3,0,wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
     2425        lblsizr.Add(sizer,0,wx.EXPAND)
    23802426        sizer = wx.BoxSizer(wx.HORIZONTAL)
    23812427        sizer.Add(wx.StaticText(mnpnl, wx.ID_ANY,'Select format(s): '))
     
    23912437        sizer.Add(G2G.G2CheckBox(mnpnl,'',self.params,'SeparateDir'))
    23922438        lblsizr.Add(sizer)
    2393         mnsizer.Add(lblsizr,0,wx.ALIGN_CENTER,1)
    2394 
    2395         #put automatic PDF controls here?
     2439        sizer = wx.BoxSizer(wx.HORIZONTAL)
     2440        sizer.Add(wx.StaticText(mnpnl, wx.ID_ANY,'Autocompute PDF'),0,wx.ALIGN_CENTER_VERTICAL)
     2441        sizer.Add(G2G.G2CheckBox(mnpnl,'',self.params,'ComputePDF',OnChange=showPDFctrls))
     2442        lbl4a = wx.StaticText(mnpnl, wx.ID_ANY,'Max detector distance: ')
     2443        sizer.Add(lbl4a,0,wx.ALIGN_CENTER_VERTICAL)
     2444        fInp4a = G2G.ValidatedTxtCtrl(mnpnl,self.params,'pdfDmax',min=0.0)
     2445        sizer.Add(fInp4a,0,wx.ALIGN_CENTER_VERTICAL)
     2446        lblsizr.Add(sizer,0)
     2447        sizer = wx.BoxSizer(wx.HORIZONTAL)
     2448        lbl4 = wx.StaticText(mnpnl, wx.ID_ANY,'PDF control: ')
     2449        sizer.Add(lbl4,0,wx.ALIGN_CENTER_VERTICAL)
     2450        fInp4 = G2G.ValidatedTxtCtrl(mnpnl,self.params,'pdfprm',notBlank=True,size=(300,-1),
     2451                                     OnLeave=scanPDFprm)
     2452        sizer.Add(fInp4,1,wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
     2453        btn4 = wx.Button(mnpnl,  wx.ID_ANY, "Browse")
     2454        btn4.Bind(wx.EVT_BUTTON, OnBrowse)
     2455        sizer.Add(btn4,0,wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
     2456        lblsizr.Add(sizer,0,wx.EXPAND)
     2457        mnsizer.Add(lblsizr,0,wx.ALIGN_CENTER|wx.EXPAND,1)
    23962458        # buttons on bottom
    23972459        mnsizer.Add(wx.StaticText(mnpnl, wx.ID_ANY,'AutoIntegration controls'),0,wx.TOP,5)
     
    24102472        sizer.Add((20,-1))
    24112473        mnsizer.Add(sizer,0,wx.EXPAND|wx.BOTTOM|wx.TOP,5)
    2412         '''or put automatic PDF controls here?
    2413         Auto PDF check box - if True:
    2414             chemical formula needed - or maybe fake it?
    2415        
    2416         '''
    24172474        # finish up window
    24182475        mnpnl.SetSizer(mnsizer)
     
    24212478        self.CenterOnParent()
    24222479        self.Show()
    2423 
     2480        showPDFctrls(None)
     2481
     2482    def checkPDFprm(self):
     2483        '''Read in the PDF (.pdfprm) parameter file and check for problems
     2484        '''
     2485        self.pdfControls = {}
     2486        msg = ''
     2487        File = None
     2488        try:
     2489            File = open(self.params['pdfprm'],'r')
     2490            S = File.readline()
     2491            while S:
     2492                if '#' in S:
     2493                    S = File.readline()
     2494                    continue
     2495                key,val = S.split(':',1)
     2496                try:
     2497                    self.pdfControls[key] = eval(val)
     2498                except:
     2499                    self.pdfControls[key] = val
     2500                S = File.readline()
     2501        except Exception as err:
     2502            msg += 'PDF processing error: Error with open or read of {}'.format(self.params['pdfprm'])
     2503            if GSASIIpath.GetConfigValue('debug'):
     2504                print(msg)
     2505                print(err)
     2506            self.pdfControls = {}
     2507            return msg
     2508        finally:
     2509            if File: File.close()
     2510        # may want to offer a substitution when not found
     2511        for key in ['Sample Bkg.','Container','Container Bkg.']:
     2512            if key not in self.pdfControls:
     2513                if msg: msg += '\n'
     2514                msg += 'Error, missing key in self.pdfControls: '+key
     2515                continue
     2516            name = self.pdfControls[key]['Name']
     2517            if not name: continue
     2518            if not G2gd.GetPatternTreeItemId(self.G2frame,self.G2frame.root,name):
     2519                if msg: msg += '\n'
     2520                msg += 'Warning, tree item for PDF '+key+' not present:\n  '+name
     2521        return msg
     2522   
    24242523    def ShowMatchingFiles(self,value,invalid=False,**kwargs):
    24252524        G2frame = self.G2frame
     
    24732572           
    24742573    def IntegrateImage(self,img):
    2475         '''Integrates a single image'''
     2574        '''Integrates a single image. Ids for created PWDR entries (more than one is possible)
     2575        are placed in G2frame.IntgOutList
     2576        '''
    24762577        G2frame = self.G2frame
    24772578        imgId = G2gd.GetPatternTreeItemId(G2frame,G2frame.root,img)
     
    25582659       
    25592660    def StartLoop(self):
    2560         '''Save current Image params for use in future integrations
     2661        '''Prepare to start autointegration timer loop.
     2662        Save current Image params for use in future integrations
    25612663        also label the window so users understand what is being used
    25622664        '''
    2563         print '\nStarting new autointegration\n'
     2665        print('\nStarting new autointegration\n')
    25642666        G2frame = self.G2frame
    25652667        # show current IMG base
     
    26222724            self.Reset = False
    26232725        G2frame.AutointPWDRnames = [] # list of created PWDR tree item names
    2624 
     2726        G2frame.AutointPDFnames = [] # list of created PWDR tree item names
     2727        # check that AutoPDF input is OK, offer chance to use alternate PDWRs if referenced ones
     2728        # are not present
     2729        if self.params['ComputePDF']:
     2730            msg = self.checkPDFprm()
     2731            if 'Error' in msg:
     2732                print(msg)
     2733                return True
     2734            elif msg:
     2735                fileList = []
     2736                id, cookie = G2frame.PatternTree.GetFirstChild(G2frame.root)
     2737                while id:
     2738                    name = G2frame.PatternTree.GetItemText(id)
     2739                    if name.startswith('PWDR '):
     2740                        fileList.append(name)
     2741                    id, cookie = G2frame.PatternTree.GetNextChild(G2frame.root, cookie)
     2742                if not fileList:
     2743                    print(msg)
     2744                    print('No PWDR entries to select')
     2745                    return True
     2746                for key in ['Sample Bkg.','Container','Container Bkg.']:
     2747                    name = self.pdfControls[key]['Name']
     2748                    if not name: continue
     2749                    if not G2gd.GetPatternTreeItemId(G2frame,G2frame.root,name):
     2750                        indx = G2G.ItemSelector(fileList, self, header='Select PDWR item',
     2751                                    title='Select a PDWR tree item for '+key+'\n(or cancel to quit)')
     2752                        if indx is None:
     2753                            print('No PWDR entry selected for '+key)
     2754                            return True
     2755                        self.pdfControls[key]['Name'] = fileList[indx]
     2756        return False
     2757               
    26252758    def OnTimerLoop(self,event):
    26262759        '''A method that is called every :meth:`PollTime` seconds that is
    2627         used to check for new files and process them. This is called only
    2628         after the "Start" button is pressed (then its label reads "Pause").
     2760        used to check for new files and process them. Integrates new images.
     2761        Also optionally sets up and computes PDF.
     2762        This is called only after the "Start" button is pressed (then its label reads "Pause").
    26292763        '''
    2630         G2frame = self.G2frame
    2631         try:
    2632             self.currImageList = sorted(
    2633                 glob.glob(os.path.join(self.imagedir,self.params['filter'])))
    2634             self.ShowMatchingFiles(self.params['filter'])
    2635         except IndexError:
    2636             self.currImageList = []
    2637             return
    2638 
    2639         if self.PreventReEntryTimer: return
    2640         self.PreventReEntryTimer = True
    2641         imageFileList = []
    2642         # integrate the images that have already been read in, but
    2643         # have not yet been processed
    2644         for img in G2gd.GetPatternTreeDataNames(G2frame,['IMG ']):
    2645             imgId = G2gd.GetPatternTreeItemId(G2frame,G2frame.root,img)
    2646             size,imagefile,imagetag = G2frame.PatternTree.GetImageLoc(imgId)
    2647             # Create a list of image files that have been read in
    2648             if imagefile not in imageFileList: imageFileList.append(imagefile)
    2649             # skip if already integrated
    2650             if img in G2frame.IntegratedList: continue
     2764        def AutoIntegrateImage(imgId):
     2765            '''Integrates an image that has been read into the data tree and updates the
     2766            AutoInt window.
     2767            '''
     2768            img = G2frame.PatternTree.GetItemText(imgId)
    26512769            controlsDict = G2frame.PatternTree.GetItemPyData(
    26522770                G2gd.GetPatternTreeItemId(G2frame,imgId, 'Image Controls'))
     
    26642782            finally:
    26652783                self.EnableButtons(True)
    2666             self.Pause |= G2frame.PauseIntegration
    26672784            self.G2frame.oldImagefile = '' # mark image as changed; reread as needed
    26682785            wx.Yield()
    26692786            self.ShowMatchingFiles(self.params['filter'])
    26702787            wx.Yield()
     2788           
     2789        def AutoComputePDF(imgId):
     2790            '''Computes a PDF for a PWDR data tree tree item
     2791            '''
     2792            for pwdr in G2frame.AutointPWDRnames[:]:
     2793                if not pwdr.startswith('PWDR '): continue
     2794                if pwdr in G2frame.AutointPDFnames: continue
     2795                PWid = G2gd.GetPatternTreeItemId(G2frame,G2frame.root,pwdr)
     2796                controlsDict = G2frame.PatternTree.GetItemPyData(
     2797                    G2gd.GetPatternTreeItemId(G2frame,imgId, 'Image Controls'))
     2798                if self.params['pdfDmax'] != 0 and controlsDict['distance'] > self.params['pdfDmax']:
     2799                    print('Skipping PDF for '+pwdr+' due to detector position')
     2800                    continue
     2801                # Setup PDF
     2802                Parms = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(
     2803                    G2frame,PWid,'Instrument Parameters'))[0]
     2804                fullLimits = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(
     2805                    G2frame,PWid,'Limits'))[0]
     2806                if 'C' in Parms['Type'][0]:
     2807                    qMax = tth2q(fullLimits[1],G2mth.getWave(Parms))
     2808                else:
     2809                    qMax = tof2q(fullLimits[0],Parms['difC'][1])
     2810                Qlimits = [0.9*qMax,qMax]
     2811
     2812                PWDRname = pwdr[4:]
     2813                item = pwdr
     2814                Comments = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(
     2815                    G2frame,imgId, 'Comments'))
     2816                ElList = {}
     2817                for item in Comments:           #grab chemical formula from Comments, if there
     2818                    if 'formula' in item[:15].lower():
     2819                        formula = item.split('=')[1].split()
     2820                        elems = formula[::2]
     2821                        nums = formula[1::2]
     2822                        formula = zip(elems,nums)
     2823                        for [elem,num] in formula:
     2824                            ElData = G2elem.GetElInfo(elem,Parms)
     2825                            ElData['FormulaNo'] = float(num)
     2826                            ElList[elem] = ElData
     2827                PDFid = G2obj.CreatePDFitems(G2frame,pwdr,ElList.copy(),Qlimits)
     2828                PDFdata = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(
     2829                    G2frame,PDFid, 'PDF Controls'))
     2830                PDFdata.update(self.pdfControls)
     2831                if ElList: PDFdata['ElList'] = ElList # override with formula from comments, if present
     2832                PDFdata['Sample']['Name'] = pwdr
     2833                # compute PDF
     2834                wx.Yield()
     2835                G2pdG.computePDF(G2frame,PDFdata)
     2836                wx.Yield()
     2837                G2pdG.OptimizePDF(G2frame,PDFdata,maxCycles=10,)
     2838                wx.Yield()
     2839                G2frame.AutointPDFnames.append(pwdr)
     2840                # save names of PDF entry to be deleted later if needed
     2841                G2frame.AutointPWDRnames.append(G2frame.PatternTree.GetItemText(PDFid))
     2842           
     2843        G2frame = self.G2frame
     2844        try:
     2845            self.currImageList = sorted(
     2846                glob.glob(os.path.join(self.imagedir,self.params['filter'])))
     2847            self.ShowMatchingFiles(self.params['filter'])
     2848        except IndexError:
     2849            self.currImageList = []
     2850            return
     2851
     2852        if self.PreventReEntryTimer: return
     2853        self.PreventReEntryTimer = True
     2854        imageFileList = []
     2855        # integrate the images that have already been read in, but
     2856        # have not yet been processed           
     2857        for img in G2gd.GetPatternTreeDataNames(G2frame,['IMG ']):
     2858            imgId = G2gd.GetPatternTreeItemId(G2frame,G2frame.root,img)
     2859            size,imagefile,imagetag = G2frame.PatternTree.GetImageLoc(imgId)
     2860            # Create a list of image files that have been read in
     2861            if imagefile not in imageFileList: imageFileList.append(imagefile)
     2862            # skip if already integrated
     2863            if img in G2frame.IntegratedList: continue
     2864            AutoIntegrateImage(imgId)
     2865            #self.Pause |= G2frame.PauseIntegration
     2866            #if self.Pause:
     2867            #    self.OnPause()
     2868            #    self.PreventReEntryTimer = False
     2869            #    return
     2870            if self.pdfControls: AutoComputePDF(imgId)
     2871            self.Pause |= G2frame.PauseIntegration
    26712872            if self.Pause:
    26722873                self.OnPause()
     
    26762877        # loop over image files matching glob, reading in any new ones
    26772878        for newImage in self.currImageList:
    2678 
    26792879            if newImage in imageFileList or self.Pause: continue # already read?
    26802880            for imgId in G2IO.ReadImages(G2frame,newImage):
    2681                 controlsDict = G2frame.PatternTree.GetItemPyData(
    2682                     G2gd.GetPatternTreeItemId(G2frame,imgId, 'Image Controls'))
    2683                 ImageMasks = G2frame.PatternTree.GetItemPyData(
    2684                     G2gd.GetPatternTreeItemId(G2frame,imgId, 'Masks'))
    2685                 if self.params['Mode'] == 'table': # look up parameter values from table
    2686                     self.ResetFromTable(controlsDict['distance'])
    2687                 # update controls from master
    2688                 controlsDict.update(self.ImageControls)
    2689                 # update masks from master w/o Thresholds
    2690                 ImageMasks.update(self.ImageMasks)
    2691                 # now integrate the image
    2692                 img = G2frame.PatternTree.GetItemText(imgId)
    2693                 self.EnableButtons(False)
    2694                 try:
    2695                     self.IntegrateImage(img)
    2696                 finally:
    2697                     self.EnableButtons(True)
     2881                AutoIntegrateImage(imgId)           
     2882                #self.Pause |= G2frame.PauseIntegration
     2883                #if self.Pause:
     2884                #    self.OnPause()
     2885                #    self.PreventReEntryTimer = False
     2886                #    return
     2887                if self.pdfControls: AutoComputePDF(imgId)
    26982888                self.Pause |= G2frame.PauseIntegration
    2699                 self.G2frame.oldImagefile = '' # mark image as changed; reread as needed
    2700                 wx.Yield()
    2701                 self.ShowMatchingFiles(self.params['filter'])
    2702                 wx.Yield()
    2703             if self.Pause:
    2704                 self.OnPause()
    2705                 break
    2706        
     2889                if self.Pause:
     2890                    self.OnPause()
     2891                    self.PreventReEntryTimer = False
     2892                    return
    27072893        if GSASIIpath.GetConfigValue('debug'):
    27082894            import datetime
  • trunk/GSASIIpwdGUI.py

    r2661 r2670  
    46214621#####  PDF controls
    46224622################################################################################           
     4623def computePDF(G2frame,data):
     4624    '''Calls :func:`GSASIIpwd.CalcPDF` to compute the PDF and put into the data tree array.
     4625    Called from OnComputePDF and OnComputeAllPDF and OnComputeAllPDF in
     4626    GSASIIimgGUI.py
     4627    '''
     4628
     4629    xydata = {}
     4630    for key in ['Sample','Sample Bkg.','Container','Container Bkg.']:
     4631        name = data[key]['Name']
     4632        if name:
     4633            xydata[key] = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,G2frame.root,name))
     4634    powId = G2gd.GetPatternTreeItemId(G2frame,G2frame.root,data['Sample']['Name'])
     4635    limits = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,powId,'Limits'))[1]
     4636    inst = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,powId,'Instrument Parameters'))[0]
     4637    auxPlot = G2pwd.CalcPDF(data,inst,limits,xydata)
     4638    data['I(Q)'] = xydata['IofQ']
     4639    data['S(Q)'] = xydata['SofQ']
     4640    data['F(Q)'] = xydata['FofQ']
     4641    data['G(R)'] = xydata['GofR']
     4642    return auxPlot
     4643
     4644def OptimizePDF(G2frame,data,showFit=True,maxCycles=5):
     4645    '''Optimize the PDF to minimize the difference between G(r) and the expected value for
     4646    low r (-4 pi r #density).
     4647    '''
     4648    import scipy.optimize as opt
     4649    SetUp = SetupPDFEval(G2frame,data)
     4650    Min,Init,Done = SetUp
     4651    xstart = Init()
     4652    if showFit:
     4653        rms = Min(xstart)
     4654        print('  Optimizing corrections to improve G(r) at low r')
     4655        print('  start: Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} (RMS:{:.4f})'.format(
     4656            data['Flat Bkg'],data['BackRatio'],data['Ruland'],rms))
     4657
     4658    res = opt.minimize(Min,xstart,bounds=([0,None],[0,1],[0.01,1]),
     4659                        method='L-BFGS-B',options={'maxiter':maxCycles},tol=0.001)
     4660    Done(res['x'])
     4661    if showFit:
     4662        if res['success']:
     4663            msg = 'Converged'
     4664        else:
     4665            msg = 'Not Converged'
     4666        print('  end:   Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} (RMS:{:.4f}) *** {} ***\n'.format(
     4667            data['Flat Bkg'],data['BackRatio'],data['Ruland'],res['fun'],msg))
     4668    return res['success']
     4669
     4670def SetupPDFEval(G2frame,data):
     4671    '''Create functions needed to optimize the PDF at low r
     4672    '''
     4673    Data = copy.deepcopy(data)
     4674    xydata = {}
     4675    for key in ['Sample','Sample Bkg.','Container','Container Bkg.']:
     4676        name = Data[key]['Name']
     4677        if name:
     4678            xydata[key] = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,G2frame.root,name))
     4679    powName = Data['Sample']['Name']
     4680    powId = G2gd.GetPatternTreeItemId(G2frame,G2frame.root,powName)
     4681    limits = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,powId,'Limits'))[1]
     4682    inst = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,powId,'Instrument Parameters'))[0]
     4683    numbDen = G2pwd.GetNumDensity(Data['ElList'],Data['Form Vol'])
     4684    BkgMax = 1.
     4685    def EvalLowPDF(arg):
     4686        '''Objective routine -- evaluates the RMS deviations in G(r)
     4687        from -4(pi)*#density*r for for r<Rmin
     4688        arguments are ['Flat Bkg','BackRatio','Ruland'] scaled so that
     4689        the min & max values are between 0 and 1.
     4690        '''
     4691        F,B,R = arg
     4692        Data['Flat Bkg'] = F*BkgMax
     4693        Data['BackRatio'] = B
     4694        Data['Ruland'] = R/10.
     4695        G2pwd.CalcPDF(Data,inst,limits,xydata)
     4696        # test low r computation
     4697        g = xydata['GofR'][1][1]
     4698        r = xydata['GofR'][1][0]
     4699        g0 = g[r < Data['Rmin']] + 4*np.pi*r[r < Data['Rmin']]*numbDen
     4700        return sum(g0**2)/len(g0)
     4701    def GetCurrentVals():
     4702        '''Get the current ['Flat Bkg','BackRatio','Ruland'] with scaling
     4703        '''
     4704        try:
     4705            F = data['Flat Bkg']/BkgMax
     4706        except:
     4707            F = 0
     4708        return [F,data['BackRatio'],max(10*data['Ruland'],.05)]
     4709    def SetFinalVals(arg):
     4710        '''Set the 'Flat Bkg', 'BackRatio' & 'Ruland' values from the
     4711        scaled, refined values and plot corrected region of G(r)
     4712        '''
     4713        F,B,R = arg
     4714        data['Flat Bkg'] = F*BkgMax
     4715        data['BackRatio'] = B
     4716        data['Ruland'] = R/10.
     4717        G2pwd.CalcPDF(data,inst,limits,xydata)
     4718    EvalLowPDF(GetCurrentVals())
     4719    BkgMax = max(xydata['IofQ'][1][1])/50.
     4720    return EvalLowPDF,GetCurrentVals,SetFinalVals
     4721   
    46234722def UpdatePDFGrid(G2frame,data):
    46244723    '''respond to selection of PWDR PDF data tree item.
     
    48214920                    try:
    48224921                        newdata[key] = eval(val)
    4823                     except SyntaxError:
     4922                    #except SyntaxError:
     4923                    except:
    48244924                        newdata[key] = val
    48254925                    S = File.readline()
     4926                File.close()
    48264927                data.update(newdata)
    48274928        finally:
     
    48644965        wx.BeginBusyCursor()
    48654966        try:
    4866             OptimizePDF(data)
     4967            OptimizePDF(G2frame,data)
    48674968        finally:
    48684969            wx.EndBusyCursor()
    48694970        wx.CallAfter(UpdatePDFGrid,G2frame,data)
    4870         OnComputePDF(event)
    4871        
    4872     def OptimizePDF(data,showFit=True,maxCycles=5):
    4873         import scipy.optimize as opt
    4874         SetUp = SetupPDFEval(data)
    4875         Min,Init,Done = SetUp
    4876         xstart = Init()
    4877         if showFit:
    4878             rms = Min(xstart)
    4879             print('  Optimizing corrections to improve G(r) at low r')
    4880             print('  start: Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} (RMS:{:.4f})'.format(
    4881                 data['Flat Bkg'],data['BackRatio'],data['Ruland'],rms))
    4882        
    4883         res = opt.minimize(Min,xstart,bounds=([0,None],[0,1],[0.01,1]),
    4884                             method='L-BFGS-B',options={'maxiter':maxCycles},tol=0.001)
    4885         Done(res['x'])
    4886         if showFit:
    4887             #print('  end:   Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} (RMS:{:.4f})'.format(
    4888             #    data['Flat Bkg'],data['BackRatio'],data['Ruland'],res['fun']),
    4889             #    end='')
    4890             print '  end:   Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} (RMS:{:.4f})'.format(
    4891                 data['Flat Bkg'],data['BackRatio'],data['Ruland'],res['fun']),
    4892             if res['success']:
    4893                 print(' *** Converged ***\n')
    4894             else:
    4895                 print(' *** not converged ***\n')
    4896         return res['success']
    4897 
    4898     def SetupPDFEval(data):
    4899         '''Create functions needed to optimize the PDF at low r
    4900         '''
    4901         Data = copy.deepcopy(data)
    4902         xydata = {}
    4903         for key in ['Sample','Sample Bkg.','Container','Container Bkg.']:
    4904             name = Data[key]['Name']
    4905             if name:
    4906                 xydata[key] = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,G2frame.root,name))
    4907         powName = Data['Sample']['Name']
    4908         powId = G2gd.GetPatternTreeItemId(G2frame,G2frame.root,powName)
    4909         limits = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,powId,'Limits'))[1]
    4910         inst = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,powId,'Instrument Parameters'))[0]
    4911         numbDen = G2pwd.GetNumDensity(Data['ElList'],Data['Form Vol'])
    4912         BkgMax = 1.
    4913         def EvalLowPDF(arg):
    4914             '''Objective routine -- evaluates the RMS deviations in G(r)
    4915             from -4(pi)r for for r<Rmin
    4916             arguments are ['Flat Bkg','BackRatio','Ruland'] scaled so that
    4917             the min & max values are between 0 and 1.
    4918             '''
    4919             F,B,R = arg
    4920             Data['Flat Bkg'] = F*BkgMax
    4921             Data['BackRatio'] = B
    4922             Data['Ruland'] = R/10.
    4923             G2pwd.CalcPDF(Data,inst,limits,xydata)
    4924             # test low r computation
    4925             g = xydata['GofR'][1][1]
    4926             r = xydata['GofR'][1][0]
    4927             g0 = g[r < Data['Rmin']] + 4*np.pi*r[r < Data['Rmin']]*numbDen
    4928             return sum(g0**2)/len(g0)
    4929         def GetCurrentVals():
    4930             '''Get the current ['Flat Bkg','BackRatio','Ruland'] with scaling
    4931             '''
    4932             try:
    4933                 F = data['Flat Bkg']/BkgMax
    4934             except:
    4935                 F = 0
    4936             return [F,data['BackRatio'],max(10*data['Ruland'],.05)]
    4937         def SetFinalVals(arg):
    4938             '''Set the 'Flat Bkg', 'BackRatio' & 'Ruland' values from the
    4939             scaled, refined values and plot corrected region of G(r)
    4940             '''
    4941             F,B,R = arg
    4942             data['Flat Bkg'] = F*BkgMax
    4943             data['BackRatio'] = B
    4944             data['Ruland'] = R/10.
    4945             G2pwd.CalcPDF(data,inst,limits,xydata)
    4946         EvalLowPDF(GetCurrentVals())
    4947         BkgMax = max(xydata['IofQ'][1][1])/50.
    4948         return EvalLowPDF,GetCurrentVals,SetFinalVals
    4949                
    4950     def ComputePDF(Data):
    4951         '''Calls :func:`GSASIIpwd.CalcPDF` to compute and the PDF. Called from OnComputePDF and OnComputeAllPDF
    4952         '''
    4953 
    4954         xydata = {}
    4955         for key in ['Sample','Sample Bkg.','Container','Container Bkg.']:
    4956             name = Data[key]['Name']
    4957             if name:
    4958                 xydata[key] = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,G2frame.root,name))
    4959         powName = Data['Sample']['Name']
    4960         powId = G2gd.GetPatternTreeItemId(G2frame,G2frame.root,powName)
    4961         limits = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,powId,'Limits'))[1]
    4962         inst = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,powId,'Instrument Parameters'))[0]
    4963         auxPlot = G2pwd.CalcPDF(Data,inst,limits,xydata)
    4964         data['I(Q)'] = xydata['IofQ']
    4965         data['S(Q)'] = xydata['SofQ']
    4966         data['F(Q)'] = xydata['FofQ']
    4967         data['G(R)'] = xydata['GofR']
    4968         return auxPlot
    4969        
     4971        OnComputePDF(event)       
     4972                       
    49704973    def OnComputePDF(event):
    49714974        '''Compute and plot PDF, in response to a menu command or a change to a
     
    49754978            G2frame.ErrorDialog('PDF error','Chemical formula not defined')
    49764979            return
    4977         auxPlot = ComputePDF(data)
     4980        auxPlot = computePDF(G2frame,data)
    49784981        if not G2frame.dataFrame.GetStatusBar():
    49794982            Status = G2frame.dataFrame.CreateStatusBar()
     
    50365039                    Data = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,id,'PDF Controls'))
    50375040                    print('  Computing {}'.format(Name))
    5038                     ComputePDF(Data)
     5041                    computePDF(G2frame,Data)
    50395042                    if od['value_1']:
    5040                         notConverged += not OptimizePDF(Data,maxCycles=10)
     5043                        notConverged += not OptimizePDF(G2frame,Data,maxCycles=10)
    50415044                id, cookie = G2frame.PatternTree.GetNextChild(G2frame.root, cookie)
    50425045        finally:
Note: See TracChangeset for help on using the changeset viewer.