Changeset 1496


Ignore:
Timestamp:
Sep 14, 2014 7:48:39 PM (7 years ago)
Author:
vondreele
Message:

Add sequential peak fitting.
Change Back:n to Back;n for background parameters
Also DebyeA, etc.

Location:
trunk
Files:
8 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIgrid.py

    r1481 r1496  
    117117
    118118[ wxID_UNDO,wxID_LSQPEAKFIT,wxID_LSQONECYCLE,wxID_RESETSIGGAM,wxID_CLEARPEAKS,wxID_AUTOSEARCH,
    119 ] = [wx.NewId() for item in range(6)]
     119    wxID_PEAKSCOPY, wxID_SEQPEAKFIT,
     120] = [wx.NewId() for item in range(8)]
    120121
    121122[  wxID_INDXRELOAD, wxID_INDEXPEAKS, wxID_REFINECELL, wxID_COPYCELL, wxID_MAKENEWPHASE,
     
    29202921        self.AutoSearch = self.PeakEdit.Append(help='Automatic peak search',
    29212922            id=wxID_AUTOSEARCH, kind=wx.ITEM_NORMAL,text='Auto search')
     2923        self.PeakCopy = self.PeakEdit.Append(help='Copy peaks to other histograms',
     2924            id=wxID_PEAKSCOPY, kind=wx.ITEM_NORMAL,text='Peak copy')
    29222925        self.UnDo = self.PeakEdit.Append(help='Undo last least squares refinement',
    29232926            id=wxID_UNDO, kind=wx.ITEM_NORMAL,text='UnDo')
    2924         self.PeakFit = self.PeakEdit.Append(id=wxID_LSQPEAKFIT, kind=wx.ITEM_NORMAL,text='LSQ PeakFit',
    2925             help='Peak fitting via least-squares' )
    2926         self.PFOneCycle = self.PeakEdit.Append(id=wxID_LSQONECYCLE, kind=wx.ITEM_NORMAL,text='LSQ one cycle',
    2927             help='One cycle of Peak fitting via least-squares' )
     2927        self.PeakFit = self.PeakEdit.Append(id=wxID_LSQPEAKFIT, kind=wx.ITEM_NORMAL,text='Peakfit',
     2928            help='Peak fitting' )
     2929        self.PFOneCycle = self.PeakEdit.Append(id=wxID_LSQONECYCLE, kind=wx.ITEM_NORMAL,text='Peakfit one cycle',
     2930            help='One cycle of Peak fitting' )
     2931        self.SeqPeakFit = self.PeakEdit.Append(id=wxID_SEQPEAKFIT, kind=wx.ITEM_NORMAL,text='Seq PeakFit',
     2932            help='Sequential Peak fitting for all histograms' )
     2933        wxID_PEAKSCOPY
    29282934        self.PeakEdit.Append(id=wxID_RESETSIGGAM, kind=wx.ITEM_NORMAL,
    29292935            text='Reset sig and gam',help='Reset sigma and gamma to global fit' )
  • trunk/GSASIImapvars.py

    r1489 r1496  
    11721172#    if e: print 'error=',e
    11731173#    if w: print 'error=',w
    1174 #    varyList = ['0::A0', '0::AUiso:0', '0::Afrac:1', '0::Afrac:2', '0::Afrac:3', '0::Afrac:4', '0::dAx:5', '0::dAy:5', '0::dAz:5', '0::AUiso:5', ':0:Back:0', ':0:Back:1', ':0:Back:2', ':0:Back:3', ':0:Back:4', ':0:Back:5', ':0:Back:6', ':0:Back:7', ':0:Back:8', ':0:Back:9', ':0:Back:10', ':0:Back:11', ':0:U', ':0:V', ':0:W', ':0:X', ':0:Y', ':0:Scale', ':0:DisplaceX', ':0:DisplaceY']
     1174#    varyList = ['0::A0', '0::AUiso:0', '0::Afrac:1', '0::Afrac:2', '0::Afrac:3', '0::Afrac:4', '0::dAx:5', '0::dAy:5', '0::dAz:5', '0::AUiso:5', ':0:Back;0', ':0:Back;1', ':0:Back;2', ':0:Back;3', ':0:Back;4', ':0:Back;5', ':0:Back;6', ':0:Back;7', ':0:Back;8', ':0:Back;9', ':0:Back;10', ':0:Back;11', ':0:U', ':0:V', ':0:W', ':0:X', ':0:Y', ':0:Scale', ':0:DisplaceX', ':0:DisplaceY']
    11751175#    constrDict = [
    11761176#        {'0::Afrac:4': 24.0, '0::Afrac:1': 16.0, '0::Afrac:3': 24.0, '0::Afrac:2': 16.0},
  • trunk/GSASIIobj.py

    r1456 r1496  
    13201320        'e([12][12])' : 'strain tensor e\1',   # strain vars e11, e22, e12
    13211321        'Dcalc': 'Calc. d-spacing',
     1322        'Back$': 'background parameter',
     1323        'pos$': 'peak position',
     1324        'int$': 'peak intensity',
    13221325        }.items():
    13231326        VarDesc[key] = value
  • trunk/GSASIIpwd.py

    r1493 r1496  
    526526    cw = np.append(cw,cw[-1])
    527527    while True:
    528         key = pfx+'Back:'+str(nBak)
     528        key = pfx+'Back;'+str(nBak)
    529529        if key in parmDict:
    530530            nBak += 1
     
    534534        dt = xdata[-1]-xdata[0]   
    535535        for iBak in range(nBak):
    536             key = pfx+'Back:'+str(iBak)
     536            key = pfx+'Back;'+str(iBak)
    537537            if bakType == 'chebyschev':
    538538                yb += parmDict[key]*(2.*(xdata-xdata[0])/dt-1.)**iBak
     
    541541    elif bakType in ['lin interpolate','inv interpolate','log interpolate',]:
    542542        if nBak == 1:
    543             yb = np.ones_like(xdata)*parmDict[pfx+'Back:0']
     543            yb = np.ones_like(xdata)*parmDict[pfx+'Back;0']
    544544        elif nBak == 2:
    545545            dX = xdata[-1]-xdata[0]
    546546            T2 = (xdata-xdata[0])/dX
    547547            T1 = 1.0-T2
    548             yb = parmDict[pfx+'Back:0']*T1+parmDict[pfx+'Back:1']*T2
     548            yb = parmDict[pfx+'Back;0']*T1+parmDict[pfx+'Back;1']*T2
    549549        else:
    550550            if bakType == 'lin interpolate':
     
    558558            bakVals = np.zeros(nBak)
    559559            for i in range(nBak):
    560                 bakVals[i] = parmDict[pfx+'Back:'+str(i)]
     560                bakVals[i] = parmDict[pfx+'Back;'+str(i)]
    561561            bakInt = si.interp1d(bakPos,bakVals,'linear')
    562562            yb = bakInt(xdata)
     
    575575    while True:
    576576        try:
    577             dbA = parmDict[pfx+'DebyeA:'+str(iD)]
    578             dbR = parmDict[pfx+'DebyeR:'+str(iD)]
    579             dbU = parmDict[pfx+'DebyeU:'+str(iD)]
     577            dbA = parmDict[pfx+'DebyeA;'+str(iD)]
     578            dbR = parmDict[pfx+'DebyeR;'+str(iD)]
     579            dbU = parmDict[pfx+'DebyeU;'+str(iD)]
    580580            yb += ff*dbA*np.sin(q*dbR)*np.exp(-dbU*q**2)/(q*dbR)
    581581            iD += 1       
     
    618618    nBak = 0
    619619    while True:
    620         key = hfx+'Back:'+str(nBak)
     620        key = hfx+'Back;'+str(nBak)
    621621        if key in parmDict:
    622622            nBak += 1
     
    678678            if hfx+'difC' in parmDict:
    679679                q = 2*np.pi*parmDict[hfx+'difC']/xdata
    680             dbA = parmDict[hfx+'DebyeA:'+str(iD)]
    681             dbR = parmDict[hfx+'DebyeR:'+str(iD)]
    682             dbU = parmDict[hfx+'DebyeU:'+str(iD)]
     680            dbA = parmDict[hfx+'DebyeA;'+str(iD)]
     681            dbR = parmDict[hfx+'DebyeR;'+str(iD)]
     682            dbU = parmDict[hfx+'DebyeU;'+str(iD)]
    683683            sqr = np.sin(q*dbR)/(q*dbR)
    684684            cqr = np.cos(q*dbR)
     
    918918    dMdv = np.zeros(shape=(len(varyList),len(xdata)))
    919919    dMdb,dMddb,dMdpk = getBackgroundDerv('',parmDict,bakType,dataType,xdata)
    920     if 'Back:0' in varyList:            #background derivs are in front if present
     920    if 'Back;0' in varyList:            #background derivs are in front if present
    921921        dMdv[0:len(dMdb)] = dMdb
    922922    names = ['DebyeA','DebyeR','DebyeU']
     
    11231123    bakType,bakFlag = Background[0][:2]
    11241124    backVals = Background[0][3:]
    1125     backNames = ['Back:'+str(i) for i in range(len(backVals))]
     1125    backNames = ['Back;'+str(i) for i in range(len(backVals))]
    11261126    Debye = Background[1]           #also has background peaks stuff
    11271127    backDict = dict(zip(backNames,backVals))
     
    12551255        while True:
    12561256            try:
    1257                 bakName = 'Back:'+str(iBak)
     1257                bakName = 'Back;'+str(iBak)
    12581258                Background[0][iBak+3] = parmList[bakName]
    12591259                iBak += 1
     
    12891289            for i,back in enumerate(Background[0][3:]):
    12901290                ptstr += ptfmt % (back)
    1291                 sigstr += ptfmt % (sigDict['Back:'+str(i)])
     1291                sigstr += ptfmt % (sigDict['Back;'+str(i)])
    12921292            print ptstr
    12931293            print sigstr
     
    15051505        begin = time.time()
    15061506        values =  np.array(Dict2Values(parmDict, varyList))
     1507        Rvals = {}
    15071508        if FitPgm == 'LSQ':
    15081509            try:
     
    15151516            chisq = np.sum(result[2]['fvec']**2)
    15161517            Values2Dict(parmDict, varyList, result[0])
    1517             Rwp = np.sqrt(chisq/np.sum(w[xBeg:xFin]*y[xBeg:xFin]**2))*100.      #to %
    1518             GOF = chisq/(xFin-xBeg-len(varyList))       #reduced chi^2
     1518            Rvals['Rwp'] = np.sqrt(chisq/np.sum(w[xBeg:xFin]*y[xBeg:xFin]**2))*100.      #to %
     1519            Rvals['GOF'] = chisq/(xFin-xBeg-len(varyList))       #reduced chi^2
    15191520            print 'Number of function calls:',result[2]['nfev'],' Number of observations: ',xFin-xBeg,' Number of parameters: ',len(varyList)
    15201521            print 'fitpeak time = %8.3fs, %8.3fs/cycle'%(runtime,runtime/ncyc)
    1521             print 'Rwp = %7.2f%%, chi**2 = %12.6g, reduced chi**2 = %6.2f'%(Rwp,chisq,GOF)
     1522            print 'Rwp = %7.2f%%, chi**2 = %12.6g, reduced chi**2 = %6.2f'%(Rvals['Rwp'],chisq,Rvals['GOF'])
    15221523            try:
    1523                 sig = np.sqrt(np.diag(result[1])*GOF)
     1524                sig = np.sqrt(np.diag(result[1])*Rvals['GOF'])
    15241525                if np.any(np.isnan(sig)):
    15251526                    print '*** Least squares aborted - some invalid esds possible ***'
     
    15471548    GetPeaksParms(Inst,parmDict,Peaks,varyList)   
    15481549    PeaksPrint(dataType,parmDict,sigDict,varyList)
    1549     return sigDict
     1550    return sigDict,result,sig,Rvals,varyList,parmDict
    15501551
    15511552def calcIncident(Iparm,xdata):
  • trunk/GSASIIpwdGUI.py

    r1493 r1496  
    330330            data['peaks'].append(G2mth.setPeakparms(inst,inst2,pos,mag))
    331331        UpdatePeakGrid(G2frame,data)
    332         G2plt.PlotPatterns(G2frame,plotType='PWDR')       
     332        G2plt.PlotPatterns(G2frame,plotType='PWDR')
     333       
     334    def OnCopyPeaks(event):
     335        hst = G2frame.PatternTree.GetItemText(G2frame.PatternId)
     336        histList = GetHistsLikeSelected(G2frame)
     337        if not histList:
     338            G2frame.ErrorDialog('No match','No histograms match '+hst,G2frame.dataFrame)
     339            return
     340        copyList = []
     341        dlg = G2gd.G2MultiChoiceDialog(
     342            G2frame.dataFrame,
     343            'Copy peak list from\n'+str(hst[5:])+' to...',
     344            'Copy peaks', histList)
     345        try:
     346            if dlg.ShowModal() == wx.ID_OK:
     347                for i in dlg.GetSelections():
     348                    copyList.append(histList[i])
     349        finally:
     350            dlg.Destroy()
     351        for item in copyList:
     352            Id = G2gd.GetPatternTreeItemId(G2frame,G2frame.root,item)
     353            G2frame.PatternTree.SetItemPyData(
     354                G2gd.GetPatternTreeItemId(G2frame,Id,'Peak List'),copy.copy(data))
    333355   
    334356    def OnUnDo(event):
     
    368390    def OnOneCycle(event):
    369391        OnPeakFit('LSQ',oneCycle=True)
     392       
     393    def OnSeqPeakFit(event):
     394        hst = G2frame.PatternTree.GetItemText(G2frame.PatternId)
     395        histList = GetHistsLikeSelected(G2frame)
     396        if not histList:
     397            G2frame.ErrorDialog('No match','No histograms match '+hst,G2frame.dataFrame)
     398            return
     399        sel = []
     400        dlg = G2gd.G2MultiChoiceDialog(G2frame.dataFrame, 'Sequential peak fits',
     401             'Select dataset to include',histList)
     402        dlg.SetSelections(sel)
     403        names = []
     404        if dlg.ShowModal() == wx.ID_OK:
     405            for sel in dlg.GetSelections():
     406                names.append(histList[sel])
     407        dlg.Destroy()
     408        SeqResult = {'histNames':names}
     409        dlg.Destroy()
     410        dlg = wx.ProgressDialog('Sequential peak fit','Data set name = '+names[0],len(names),
     411            style = wx.PD_ELAPSED_TIME|wx.PD_AUTO_HIDE|wx.PD_REMAINING_TIME|wx.PD_CAN_ABORT)
     412        controls = {'deriv type':'analytic','min dM/M':0.0001,}
     413        print 'Peak Fitting with '+controls['deriv type']+' derivatives:'
     414        oneCycle = False
     415        FitPgm = 'LSQ'
     416        try:
     417            for i,name in enumerate(names):
     418                print ' Sequential fit for ',name
     419                GoOn = dlg.Update(i,newmsg='Data set name = '+name)[0]
     420                if not GoOn:
     421                    break
     422                PatternId =  G2gd.GetPatternTreeItemId(G2frame,G2frame.root,name)
     423                peaks = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,PatternId, 'Peak List'))
     424                background = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,PatternId, 'Background'))
     425                limits = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,PatternId, 'Limits'))[1]
     426                inst,inst2 = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,PatternId, 'Instrument Parameters'))
     427                data = G2frame.PatternTree.GetItemPyData(PatternId)[1]
     428                wx.BeginBusyCursor()
     429                dlg2 = wx.ProgressDialog('Residual','Peak fit Rwp = ',101.0,
     430                    style = wx.PD_ELAPSED_TIME|wx.PD_AUTO_HIDE|wx.PD_REMAINING_TIME|wx.PD_CAN_ABORT)
     431                screenSize = wx.ClientDisplayRect()
     432                Size = dlg.GetSize()
     433                dlg2.SetPosition(wx.Point(screenSize[2]-Size[0]-305,screenSize[1]+5))
     434                try:
     435                    peaks['sigDict'],result,sig,Rvals,varyList,parmDict = G2pwd.DoPeakFit(FitPgm,peaks['peaks'],
     436                        background,limits,inst,inst2,data,oneCycle,controls,dlg2)
     437                finally:
     438                    dlg2.Destroy()   
     439                G2frame.PatternTree.SetItemPyData(G2gd.GetPatternTreeItemId(G2frame,PatternId, 'Peak List'),peaks)
     440                SeqResult[name] = {'variables':result[0],'varyList':varyList,'sig':sig,'Rvals':Rvals,
     441                    'covMatrix':np.eye(len(result[0])),'title':name,'parmDict':parmDict}
     442            else:
     443                dlg.Destroy()
     444                print ' ***** Sequential peak fit successful *****'
     445        finally:
     446            wx.EndBusyCursor()   
     447        Id =  G2gd.GetPatternTreeItemId(G2frame,G2frame.root,'Sequential results')
     448        if Id:
     449            G2frame.PatternTree.SetItemPyData(Id,SeqResult)
     450        else:
     451            Id = G2frame.PatternTree.AppendItem(parent=G2frame.root,text='Sequential results')
     452            G2frame.PatternTree.SetItemPyData(Id,SeqResult)
     453        G2frame.PatternTree.SelectItem(Id)
    370454       
    371455    def OnClearPeaks(event):
     
    402486        dlg.SetPosition(wx.Point(screenSize[2]-Size[0]-305,screenSize[1]+5))
    403487        try:
    404             peaks['sigDict'] = G2pwd.DoPeakFit(FitPgm,peaks['peaks'],background,limits,inst,inst2,data,oneCycle,controls,dlg)
     488            peaks['sigDict'] = G2pwd.DoPeakFit(FitPgm,peaks['peaks'],background,limits,inst,inst2,data,oneCycle,controls,dlg)[0]
    405489        finally:
    406490            wx.EndBusyCursor()   
     
    502586    Status.SetStatusText('Global refine: select refine column & press Y or N')
    503587    G2frame.Bind(wx.EVT_MENU, OnAutoSearch, id=G2gd.wxID_AUTOSEARCH)
     588    G2frame.Bind(wx.EVT_MENU, OnCopyPeaks, id=G2gd.wxID_PEAKSCOPY)
    504589    G2frame.Bind(wx.EVT_MENU, OnUnDo, id=G2gd.wxID_UNDO)
    505590    G2frame.Bind(wx.EVT_MENU, OnLSQPeakFit, id=G2gd.wxID_LSQPEAKFIT)
    506591    G2frame.Bind(wx.EVT_MENU, OnOneCycle, id=G2gd.wxID_LSQONECYCLE)
     592    G2frame.Bind(wx.EVT_MENU, OnSeqPeakFit, id=G2gd.wxID_SEQPEAKFIT)
    507593    G2frame.Bind(wx.EVT_MENU, OnClearPeaks, id=G2gd.wxID_CLEARPEAKS)
    508594    G2frame.Bind(wx.EVT_MENU, OnResetSigGam, id=G2gd.wxID_RESETSIGGAM)
    509595    if data['peaks']:
    510596        G2frame.dataFrame.AutoSearch.Enable(False)
     597        G2frame.dataFrame.PeakCopy.Enable(True)
    511598        G2frame.dataFrame.PeakFit.Enable(True)
    512599        G2frame.dataFrame.PFOneCycle.Enable(True)
     600        G2frame.dataFrame.SeqPeakFit.Enable(True)
    513601    else:
    514602        G2frame.dataFrame.PeakFit.Enable(False)
     603        G2frame.dataFrame.PeakCopy.Enable(False)
    515604        G2frame.dataFrame.PFOneCycle.Enable(False)
    516605        G2frame.dataFrame.AutoSearch.Enable(True)
     606        G2frame.dataFrame.SeqPeakFit.Enable(False)
    517607    G2frame.PickTable = []
    518608    rowLabels = []
  • trunk/GSASIIstrIO.py

    r1490 r1496  
    22002200        bakType,bakFlag = Back[:2]
    22012201        backVals = Back[3:]
    2202         backNames = [':'+str(hId)+':Back:'+str(i) for i in range(len(backVals))]
     2202        backNames = [':'+str(hId)+':Back;'+str(i) for i in range(len(backVals))]
    22032203        backDict = dict(zip(backNames,backVals))
    22042204        backVary = []
     
    22102210        debyeList = []
    22112211        for i in range(DebyePeaks['nDebye']):
    2212             debyeNames = [':'+str(hId)+':DebyeA:'+str(i),':'+str(hId)+':DebyeR:'+str(i),':'+str(hId)+':DebyeU:'+str(i)]
     2212            debyeNames = [':'+str(hId)+':DebyeA;'+str(i),':'+str(hId)+':DebyeR;'+str(i),':'+str(hId)+':DebyeU;'+str(i)]
    22132213            debyeDict.update(dict(zip(debyeNames,DebyePeaks['debyeTerms'][i][::2])))
    22142214            debyeList += zip(debyeNames,DebyePeaks['debyeTerms'][i][1::2])
     
    24342434        backSig = [0 for i in range(lenBack+3*DebyePeaks['nDebye']+4*DebyePeaks['nPeaks'])]
    24352435        for i in range(lenBack):
    2436             Back[3+i] = parmDict[pfx+'Back:'+str(i)]
    2437             if pfx+'Back:'+str(i) in sigDict:
    2438                 backSig[i] = sigDict[pfx+'Back:'+str(i)]
     2436            Back[3+i] = parmDict[pfx+'Back;'+str(i)]
     2437            if pfx+'Back;'+str(i) in sigDict:
     2438                backSig[i] = sigDict[pfx+'Back;'+str(i)]
    24392439        if DebyePeaks['nDebye']:
    24402440            for i in range(DebyePeaks['nDebye']):
  • trunk/GSASIIstrMath.py

    r1495 r1496  
    17441744    dMdv = np.zeros(shape=(len(varylist),len(x)))
    17451745    dMdb,dMddb,dMdpk = G2pwd.getBackgroundDerv(hfx,parmDict,bakType,calcControls[hfx+'histType'],x)
    1746     if hfx+'Back:0' in varylist: # for now assume that Back:x vars to not appear in constraints
    1747         bBpos =varylist.index(hfx+'Back:0')
     1746    if hfx+'Back;0' in varylist: # for now assume that Back;x vars to not appear in constraints
     1747        bBpos =varylist.index(hfx+'Back;0')
    17481748        dMdv[bBpos:bBpos+len(dMdb)] = dMdb
    17491749    names = [hfx+'DebyeA',hfx+'DebyeR',hfx+'DebyeU']
    17501750    for name in varylist:
    17511751        if 'Debye' in name:
    1752             id = int(name.split(':')[-1])
    1753             parm = name[:int(name.rindex(':'))]
     1752            id = int(name.split(';')[-1])
     1753            parm = name[:int(name.rindex(';'))]
    17541754            ip = names.index(parm)
    17551755            dMdv[varylist.index(name)] = dMddb[3*id+ip]
  • trunk/exports/G2export_CIF.py

    r1261 r1496  
    278278            l = "    "
    279279            for i,v in enumerate(fxn[3:]):
    280                 name = '%sBack:%d'%(hfx,i)
     280                name = '%sBack;%d'%(hfx,i)
    281281                sig = self.sigDict.get(name,-0.009)
    282282                if len(l) > 60:
     
    287287            if bkgdict['nDebye']:
    288288                txt += '\n  Background Debye function parameters: A, R, U:'
    289                 names = ['A:','R:','U:']
     289                names = ['A;','R;','U;']
    290290                for i in range(bkgdict['nDebye']):
    291291                    txt += '\n    '
     
    296296            if bkgdict['nPeaks']:
    297297                txt += '\n  Background peak parameters: pos, int, sig, gam:'
    298                 names = ['pos:','int:','sig:','gam:']
     298                names = ['pos;','int;','sig;','gam;']
    299299                for i in range(bkgdict['nPeaks']):
    300300                    txt += '\n    '
Note: See TracChangeset for help on using the changeset viewer.