Changeset 2645


Ignore:
Timestamp:
Jan 18, 2017 7:00:20 PM (5 years ago)
Author:
toby
Message:

improve PDF opt; add PDF opt to Compute All PDFs; rename to Setup PDFs

Location:
trunk
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASII.py

    r2643 r2645  
    238238
    239239    def _Add_CalculateMenuItems(self,parent):
    240         item = parent.Append(help='Make new PDFs from selected powder patterns',
    241             id=wx.ID_ANY, kind=wx.ITEM_NORMAL,text='Make new PDFs')
     240        item = parent.Append(help='Create PDF tree entries for selected powder patterns',
     241            id=wx.ID_ANY, kind=wx.ITEM_NORMAL,text='Setup PDFs')
    242242        self.MakePDF.append(item)
    243 #        item.Enable(False)
    244243        self.Bind(wx.EVT_MENU, self.OnMakePDFs, id=item.GetId())
    245244       
  • trunk/GSASIIctrls.py

    r2639 r2645  
    13211321    :param bool filterBox: If True (default) an input widget is placed on
    13221322      the window and only entries matching the entered text are shown.
     1323    :param dict extraOpts: a dict containing a entries of form label_i and value_i with extra
     1324      options to present to the user, where value_i is the default value. At present only bool
     1325      values are supported.
    13231326    :param kw: optional keyword parameters for the wx.Dialog may
    13241327      be included such as size [which defaults to `(320,310)`] and
    13251328      style (which defaults to `wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.CENTRE| wx.OK | wx.CANCEL`);
    1326       note that `wx.OK` and `wx.CANCEL` controls
     1329      note that `wx.OK` and `wx.CANCEL` style items control
    13271330      the presence of the eponymous buttons in the dialog.
    13281331    :returns: the name of the created dialog 
    13291332    '''
    13301333    def __init__(self,parent, title, header, ChoiceList, toggle=True,
    1331                  monoFont=False, filterBox=True, **kw):
     1334                 monoFont=False, filterBox=True, extraOpts={}, **kw):
    13321335        # process keyword parameters, notably style
    13331336        options = {'size':(320,310), # default Frame keywords
     
    13951398            tSizer.Add(self.rangeCapt)
    13961399            Sizer.Add(tSizer,0,wx.LEFT,12)
     1400        # Extra widgets
     1401        Sizer.Add((-1,5),0,wx.LEFT,0)
     1402        bSizer = wx.BoxSizer(wx.VERTICAL)
     1403        for lbl in sorted(extraOpts.keys()):
     1404            if not lbl.startswith('label'): continue
     1405            key = lbl.replace('label','value')
     1406            if key not in extraOpts: continue
     1407            eSizer = wx.BoxSizer(wx.HORIZONTAL)
     1408            if type(extraOpts[key]) is bool:
     1409                eSizer.Add(G2CheckBox(self,extraOpts[lbl],extraOpts,key))
     1410            else:
     1411                eSizer.Add(wx.StaticText(self,wx.ID_ANY,extraOpts[lbl]))
     1412                eSizer.Add(ValidatedTxtCtrl(self,extraOpts,key))
     1413            bSizer.Add(eSizer,0,wx.LEFT,0)
     1414        Sizer.Add(bSizer,0,wx.CENTER,0)
     1415        Sizer.Add((-1,5),0,wx.LEFT,0)
    13971416        # OK/Cancel buttons
    13981417        btnsizer = wx.StdDialogButtonSizer()
     
    14011420            self.OKbtn.SetDefault()
    14021421            btnsizer.AddButton(self.OKbtn)
     1422            self.OKbtn.Bind(wx.EVT_BUTTON,self.onOk)
    14031423        if useCANCEL:
    14041424            btn = wx.Button(self, wx.ID_CANCEL)
     1425            btn.Bind(wx.EVT_BUTTON,self.onCancel)
    14051426            btnsizer.AddButton(btn)
    14061427        btnsizer.Realize()
     
    14101431        # OK done, let's get outa here
    14111432        self.SetSizer(Sizer)
     1433        Sizer.Fit(self)
    14121434        self.CenterOnParent()
     1435       
     1436    def onOk(self,event):
     1437        parent = self.GetParent()
     1438        parent.Raise()
     1439        self.EndModal(wx.ID_OK)             
     1440       
     1441    def onCancel(self,event):
     1442        parent = self.GetParent()
     1443        parent.Raise()
     1444        self.EndModal(wx.ID_CANCEL)
    14131445       
    14141446    def OnStride(self,event):
     
    42444276    # test Grid with GridFractionEditor
    42454277    #======================================================================
    4246     tbl = [[1.,2.,3.],[1.1,2.1,3.1]]
    4247     colTypes = 3*[wg.GRID_VALUE_FLOAT+':10,5',]
    4248     Gtbl = Table(tbl,types=colTypes,rowLabels=['a','b'],colLabels=['1','2','3'])
    4249     Grid = GSGrid(frm)
    4250     Grid.SetTable(Gtbl,True)
    4251     for i in (0,1,2):
    4252         attr = wx.grid.GridCellAttr()
    4253         attr.IncRef()
    4254         attr.SetEditor(GridFractionEditor(Grid))
    4255         Grid.SetColAttr(i, attr)
    4256     frm.SetSize((400,200))
    4257     app.MainLoop()
    4258     sys.exit()
     4278    # tbl = [[1.,2.,3.],[1.1,2.1,3.1]]
     4279    # colTypes = 3*[wg.GRID_VALUE_FLOAT+':10,5',]
     4280    # Gtbl = Table(tbl,types=colTypes,rowLabels=['a','b'],colLabels=['1','2','3'])
     4281    # Grid = GSGrid(frm)
     4282    # Grid.SetTable(Gtbl,True)
     4283    # for i in (0,1,2):
     4284    #     attr = wx.grid.GridCellAttr()
     4285    #     attr.IncRef()
     4286    #     attr.SetEditor(GridFractionEditor(Grid))
     4287    #     Grid.SetColAttr(i, attr)
     4288    # frm.SetSize((400,200))
     4289    # app.MainLoop()
     4290    # sys.exit()
    42594291    #======================================================================
    42604292    # test Tutorial access
    42614293    #======================================================================
    4262     dlg = OpenTutorial(frm)
    4263     if dlg.ShowModal() == wx.ID_OK:
    4264         print "OK"
    4265     else:
    4266         print "Cancel"
    4267     dlg.Destroy()
    4268     sys.exit()
     4294    # dlg = OpenTutorial(frm)
     4295    # if dlg.ShowModal() == wx.ID_OK:
     4296    #     print "OK"
     4297    # else:
     4298    #     print "Cancel"
     4299    # dlg.Destroy()
     4300    # sys.exit()
    42694301    #======================================================================
    42704302    # test ScrolledMultiEditor
     
    43564388    for i in range(21):
    43574389        choices.append("option_"+str(i))
     4390    od = {
     4391        'label_1':'This is a bool','value_1':True,
     4392        'label_2':'This is a int','value_2':-1,
     4393        'label_3':'This is a float','value_3':1.0,
     4394        'label_4':'This is a string','value_4':'test',}
    43584395    dlg = G2MultiChoiceDialog(frm, 'Sequential refinement',
    43594396                              'Select dataset to include',
    4360                               choices)
     4397                              choices,extraOpts=od)
    43614398    sel = range(2,11,2)
    43624399    dlg.SetSelections(sel)
     
    43654402        for sel in dlg.GetSelections():
    43664403            print sel,choices[sel]
    4367    
     4404    print od
     4405    od = {}
     4406    dlg = G2MultiChoiceDialog(frm, 'Sequential refinement',
     4407                              'Select dataset to include',
     4408                              choices,extraOpts=od)
     4409    sel = range(2,11,2)
     4410    dlg.SetSelections(sel)
     4411    dlg.SetSelections((1,5))
     4412    if dlg.ShowModal() == wx.ID_OK: pass
    43684413    #======================================================================
    43694414    # test wx.MultiChoiceDialog
  • trunk/GSASIIgrid.py

    r2642 r2645  
    150150
    151151[ wxID_PDFCOPYCONTROLS, wxID_PDFSAVECONTROLS, wxID_PDFLOADCONTROLS,
    152     wxID_PDFCOMPUTE, wxID_PDFCOMPUTEALL, wxID_PDFADDELEMENT, wxID_PDFDELELEMENT, wxID_PDFOPT,
    153 ] = [wx.NewId() for item in range(8)]
     152    wxID_PDFCOMPUTE, wxID_PDFCOMPUTEALL, wxID_PDFADDELEMENT, wxID_PDFDELELEMENT, #wxID_PDFOPT,
     153] = [wx.NewId() for item in range(7)]
    154154
    155155[ wxID_MCRON,wxID_MCRLIST,wxID_MCRSAVE,wxID_MCRPLAY,
     
    21772177        self.PDFEdit.Append(help='Compute all PDFs', id=wxID_PDFCOMPUTEALL, kind=wx.ITEM_NORMAL,
    21782178            text='Compute all PDFs')
    2179         self.PDFEdit.Append(help='Optimize PDF', id=wxID_PDFOPT, kind=wx.ITEM_NORMAL,
    2180             text='Optimize corrections for r<Rmin section of current G(r)')
     2179#        self.PDFEdit.Append(help='Optimize PDF', id=wxID_PDFOPT, kind=wx.ITEM_NORMAL,
     2180#            text='Optimize corrections for r<Rmin section of current G(r)')
    21812181        self.PostfillDataMenu()
    21822182       
     
    45524552        elif G2frame.PatternTree.GetItemText(item).startswith('PDF '):
    45534553            G2frame.PatternId = item
    4554             for i in G2frame.ExportPDF: i.Enable(True)
     4554            for i in G2frame.ExportPDF: i.Enable(True) # this should be done on .gpx load; is done on OnMakePDFs (GSASII.py)
     4555            data = G2frame.PatternTree.GetItemPyData(GetPatternTreeItemId(G2frame,item,'PDF Controls'))
     4556            G2pdG.UpdatePDFGrid(G2frame,data)
    45554557            G2plt.PlotISFG(G2frame,plotType='S(Q)')
    45564558        elif G2frame.PatternTree.GetItemText(item) == 'Phases':
     
    45594561                value='Select one phase to see its parameters')           
    45604562    elif 'I(Q)' in G2frame.PatternTree.GetItemText(item):
     4563        for i in G2frame.ExportPDF: i.Enable(True) # this should be done on .gpx load; is done on OnMakePDFs (GSASII.py)
    45614564        G2frame.PatternId = G2frame.PatternTree.GetItemParent(item)
    45624565        data = G2frame.PatternTree.GetItemPyData(GetPatternTreeItemId(G2frame,G2frame.PatternId,'PDF Controls'))
     
    45644567        G2plt.PlotISFG(G2frame,plotType='I(Q)',newPlot=True)
    45654568    elif 'S(Q)' in G2frame.PatternTree.GetItemText(item):
     4569        for i in G2frame.ExportPDF: i.Enable(True) # this should be done on .gpx load; is done on OnMakePDFs (GSASII.py)
    45664570        G2frame.PatternId = G2frame.PatternTree.GetItemParent(item)
    45674571        data = G2frame.PatternTree.GetItemPyData(GetPatternTreeItemId(G2frame,G2frame.PatternId,'PDF Controls'))
     
    45694573        G2plt.PlotISFG(G2frame,plotType='S(Q)',newPlot=True)
    45704574    elif 'F(Q)' in G2frame.PatternTree.GetItemText(item):
     4575        for i in G2frame.ExportPDF: i.Enable(True) # this should be done on .gpx load; is done on OnMakePDFs (GSASII.py)
    45714576        G2frame.PatternId = G2frame.PatternTree.GetItemParent(item)
    45724577        data = G2frame.PatternTree.GetItemPyData(GetPatternTreeItemId(G2frame,G2frame.PatternId,'PDF Controls'))
     
    45744579        G2plt.PlotISFG(G2frame,plotType='F(Q)',newPlot=True)
    45754580    elif 'G(R)' in G2frame.PatternTree.GetItemText(item):
     4581        for i in G2frame.ExportPDF: i.Enable(True) # this should be done on .gpx load; is done on OnMakePDFs (GSASII.py)
    45764582        G2frame.PatternId = G2frame.PatternTree.GetItemParent(item)
    45774583        data = G2frame.PatternTree.GetItemPyData(GetPatternTreeItemId(G2frame,G2frame.PatternId,'PDF Controls'))
    45784584        G2pdG.UpdatePDFGrid(G2frame,data)
    45794585        G2plt.PlotISFG(G2frame,plotType='G(R)',newPlot=True)           
     4586    elif G2frame.PatternTree.GetItemText(item) == 'PDF Controls':
     4587        for i in G2frame.ExportPDF: i.Enable(True) # this should be done on .gpx load; is done on OnMakePDFs (GSASII.py)
     4588        G2frame.dataFrame.helpKey = G2frame.PatternTree.GetItemText(item) # special treatment to avoid PDF_PDF Controls
     4589        G2frame.PatternId = G2frame.PatternTree.GetItemParent(item)
     4590        data = G2frame.PatternTree.GetItemPyData(item)
     4591        G2pdG.UpdatePDFGrid(G2frame,data)
     4592        G2plt.PlotISFG(G2frame,plotType='I(Q)')
     4593        G2plt.PlotISFG(G2frame,plotType='S(Q)')
     4594        G2plt.PlotISFG(G2frame,plotType='F(Q)')
     4595        G2plt.PlotISFG(G2frame,plotType='G(R)')
    45804596    elif G2frame.PatternTree.GetItemText(parentID) == 'Phases':
    45814597        data = G2frame.PatternTree.GetItemPyData(item)
     
    46144630        G2plt.PlotImage(G2frame,newPlot=False)
    46154631        G2imG.UpdateStressStrain(G2frame,strsta)
    4616     elif G2frame.PatternTree.GetItemText(item) == 'PDF Controls':
    4617         G2frame.dataFrame.helpKey = G2frame.PatternTree.GetItemText(item) # special treatment, not PDF_PDF Controls
    4618         G2frame.PatternId = G2frame.PatternTree.GetItemParent(item)
    4619         for i in G2frame.ExportPDF: i.Enable(True)
    4620         data = G2frame.PatternTree.GetItemPyData(item)
    4621         G2pdG.UpdatePDFGrid(G2frame,data)
    4622         G2plt.PlotISFG(G2frame,plotType='I(Q)')
    4623         G2plt.PlotISFG(G2frame,plotType='S(Q)')
    4624         G2plt.PlotISFG(G2frame,plotType='F(Q)')
    4625         G2plt.PlotISFG(G2frame,plotType='G(R)')
    46264632    elif G2frame.PatternTree.GetItemText(item) == 'Peak List':
    46274633        G2frame.PatternId = G2frame.PatternTree.GetItemParent(item)
  • trunk/GSASIIpwdGUI.py

    r2644 r2645  
    48074807        Invoked by Optimize PDF button and from menu command.
    48084808        '''
    4809         import scipy.optimize as opt
    48104809        wx.BeginBusyCursor()
    4811         Min,Init,Done = SetupPDFEval()
    4812         xstart = Init()
    4813         rms = Min(xstart)
    4814         print('Optimizing corrections to improve G(r) at low r')
    4815         print('start: Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} (RMS:{:.2f})'.format(
    4816                 data['Flat Bkg'],data['BackRatio'],data['Ruland'],rms))
    4817        
    4818         res = opt.minimize(Min,xstart,bounds=([0,None],[0,1],[0.01,1]),
    4819                            method='L-BFGS-B',options={'maxiter':5})
    4820         Done(res['x'])     
    4821         print('end:   Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} (RMS:{:.2f})\n'.format(
    4822                 data['Flat Bkg'],data['BackRatio'],data['Ruland'],res['fun']))
    4823         wx.EndBusyCursor()
     4810        try:
     4811            OptimizePDF(data)
     4812        finally:
     4813            wx.EndBusyCursor()
    48244814        wx.CallAfter(UpdatePDFGrid,G2frame,data)
    48254815        OnComputePDF(event)
    48264816       
    4827     def SetupPDFEval():
     4817    def OptimizePDF(data,showFit=True,maxCycles=5):
     4818        import scipy.optimize as opt
     4819        Min,Init,Done = SetupPDFEval(data)
     4820        xstart = Init()
     4821        if showFit:
     4822            rms = Min(xstart)
     4823            print('  Optimizing corrections to improve G(r) at low r')
     4824            print('  start: Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} (RMS:{:.4f})'.format(
     4825                data['Flat Bkg'],data['BackRatio'],data['Ruland'],rms))
     4826       
     4827        res = opt.minimize(Min,xstart,bounds=([0,None],[0,1],[0.01,1]),
     4828                            method='L-BFGS-B',options={'maxiter':maxCycles},tol=0.001)
     4829        Done(res['x'])
     4830        if showFit:
     4831            #print('  end:   Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} (RMS:{:.4f})'.format(
     4832            #    data['Flat Bkg'],data['BackRatio'],data['Ruland'],res['fun']),
     4833            #    end='')
     4834            print '  end:   Flat Bkg={:.1f}, BackRatio={:.3f}, Ruland={:.3f} (RMS:{:.4f})'.format(
     4835                data['Flat Bkg'],data['BackRatio'],data['Ruland'],res['fun']),
     4836            if res['success']:
     4837                print(' *** Converged ***\n')
     4838            else:
     4839                print(' *** not converged ***\n')
     4840        return res['success']
     4841
     4842    def SetupPDFEval(data):
    48284843        '''Create functions needed to optimize the PDF at low r
    48294844        '''
     
    48524867            Data['BackRatio'] = B
    48534868            Data['Ruland'] = R/10.
    4854             #for key in 'Flat Bkg','BackRatio','Ruland':
    4855             #    print key,Data[key],'; ',
    48564869            G2pwd.CalcPDF(Data,inst,limits,xydata)
    48574870            # test low r computation
     
    48594872            r = xydata['GofR'][1][0]
    48604873            g0 = g[r < Data['Rmin']] + 4*np.pi*r[r < Data['Rmin']]*numbDen
    4861             #print ' Res=',sum(g0**2)
    4862             return sum(g0**2)
     4874            return sum(g0**2)/len(g0)
    48634875        def GetCurrentVals():
    48644876            '''Get the current ['Flat Bkg','BackRatio','Ruland'] with scaling
     
    49324944       
    49334945    def OnComputeAllPDF(event):
    4934         print 'Calculating PDFs:'
     4946        print('Calculating PDFs...')
     4947        choices = []
    49354948        if G2frame.PatternTree.GetCount():
    49364949            id, cookie = G2frame.PatternTree.GetFirstChild(G2frame.root)
    49374950            while id:
    49384951                Name = G2frame.PatternTree.GetItemText(id)
    4939                 if 'PDF' in Name.split()[0]:
     4952                if Name.startswith('PDF '):
    49404953                    Data = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,id,'PDF Controls'))
    49414954                    if not Data['ElList']:
    4942                         G2frame.ErrorDialog('PDF error','Chemical formula not defined for \n'+Name)
    4943                         return
    4944                     ComputePDF(Data)                   
     4955                        print('  No chemical formula for {}'.format(Name))
     4956                    else:
     4957                        choices.append(Name)
    49454958                id, cookie = G2frame.PatternTree.GetNextChild(G2frame.root, cookie)
    4946             if not G2frame.dataFrame.GetStatusBar():
    4947                 Status = G2frame.dataFrame.CreateStatusBar()
    4948                 Status.SetStatusText('All PDFs computed')
    4949             G2plt.PlotISFG(G2frame,newPlot=True,plotType='I(Q)')
    4950             G2plt.PlotISFG(G2frame,newPlot=True,plotType='S(Q)')
    4951             G2plt.PlotISFG(G2frame,newPlot=True,plotType='F(Q)')
    4952             G2plt.PlotISFG(G2frame,newPlot=True,plotType='G(R)')
    4953             print ' Done calculating PDFs:'
     4959        if not choices:
     4960            print('  No PDFs to compute\n')
     4961            return
     4962        od = {'label_1':'Optimize PDFs','value_1':True}
     4963        dlg = G2G.G2MultiChoiceDialog(
     4964            G2frame.dataFrame, 'Select PDFs to compute','Select PDFs',
     4965            choices,extraOpts=od)
     4966        try:
     4967            if dlg.ShowModal() == wx.ID_OK:
     4968                results = dlg.GetSelections()
     4969        finally:
     4970            dlg.Destroy()
     4971        if not results:
     4972            print('  No PDFs to compute\n')
     4973            return
     4974        Names = [choices[i] for i in results]
     4975        notConverged = 0
     4976        id, cookie = G2frame.PatternTree.GetFirstChild(G2frame.root)
     4977        while id:
     4978            Name = G2frame.PatternTree.GetItemText(id)
     4979            if Name in Names:
     4980                Data = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,id,'PDF Controls'))
     4981                print('  Computing {}'.format(Name))
     4982                ComputePDF(Data)
     4983                if od['value_1']:
     4984                    notConverged += not OptimizePDF(Data,maxCycles=10)
     4985            id, cookie = G2frame.PatternTree.GetNextChild(G2frame.root, cookie)
     4986        if not G2frame.dataFrame.GetStatusBar():
     4987            Status = G2frame.dataFrame.CreateStatusBar()
     4988        if od['value_1']:
     4989            msg = '{} PDFs computed; {} unconverged'.format(len(Names),notConverged)
     4990        else:
     4991            msg = '{} PDFs computed'.format(len(Names))
     4992        G2frame.dataFrame.GetStatusBar().SetStatusText(msg)
     4993        print(msg)
     4994        # what item is being plotted? -- might be better to select from tree
     4995        G2plt.PlotISFG(G2frame,newPlot=True,plotType='I(Q)')
     4996        G2plt.PlotISFG(G2frame,newPlot=True,plotType='S(Q)')
     4997        G2plt.PlotISFG(G2frame,newPlot=True,plotType='F(Q)')
     4998        G2plt.PlotISFG(G2frame,newPlot=True,plotType='G(R)')
    49544999
    49555000    # Routine UpdatePDFGrid starts here
     
    50025047    G2frame.dataFrame.Bind(wx.EVT_MENU, OnComputePDF, id=G2gd.wxID_PDFCOMPUTE)
    50035048    G2frame.dataFrame.Bind(wx.EVT_MENU, OnComputeAllPDF, id=G2gd.wxID_PDFCOMPUTEALL)
    5004     G2frame.dataFrame.Bind(wx.EVT_MENU, OnOptimizePDF, id=G2gd.wxID_PDFOPT)
     5049#    G2frame.dataFrame.Bind(wx.EVT_MENU, OnOptimizePDF, id=G2gd.wxID_PDFOPT)
    50055050    mainSizer = wx.BoxSizer(wx.VERTICAL)
    50065051
     
    51555200    Size = mainSizer.Fit(G2frame.dataFrame)
    51565201    G2frame.dataFrame.setSizePosLeft(Size)
    5157    
     5202#    G2frame.dataFrame.SendSizeEvent()  # for Mac, but not needed due to Bob's size+1 change in setSizePosLeft
Note: See TracChangeset for help on using the changeset viewer.