Changeset 4671


Ignore:
Timestamp:
Dec 12, 2020 1:30:31 PM (12 months ago)
Author:
vondreele
Message:

add refinable multiplier for a fixed background; multiplier is now normally > 0
usable for peak fitting and Rietved refinement
add the fixed background entry to all background defaults
fix bug in GetDetectorXY fo when cursor outside image - returns [0,0] not None; changes elsewhere to use this
GetTthAzmDsp? now returns explicit list not assumed tuple
put the abs in the nl.qr test for singularities in HessianLSQ
Add 'BF mult' to name list in G2obj
put a try - except TypeError? around setting plot style stuff in PlotPatterns?
Remove the setting of Pattern[0]BackFile? - this was redundant for PWDR
remove picker/pickradius from linescan plot - failed
remove the alternate fixed background definition ('_fixedVary', etc.)
clear the PhaseReaderClass?Drawing? dictionary upon import of phase from a gpx file

Location:
trunk
Files:
14 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIIO.py

    r4661 r4671  
    929929        if 'PWDR' in Aname:
    930930            G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='Background'),[['chebyschev-1',1,3,1.0,0.0,0.0],
    931                 {'nDebye':0,'debyeTerms':[],'nPeaks':0,'peaksList':[]}])
     931                {'nDebye':0,'debyeTerms':[],'nPeaks':0,'peaksList':[],'background PWDR':['',1.0,False]}])
    932932        inst = [dict(zip(names,zip(parms,parms,codes))),{}]
    933933        for item in inst[0]:
  • trunk/GSASIIctrlGUI.py

    r4659 r4671  
    68166816                    G2frame.GPXtree.AppendItem(Id,text='Background'),
    68176817                    rd.pwdparms.get('Background',
    6818                         [['chebyschev-1',True,3,1.0,0.0,0.0],{'nDebye':0,'debyeTerms':[],'nPeaks':0,'peaksList':[]}])
    6819                         )
     6818                        [['chebyschev-1',True,3,1.0,0.0,0.0],{'nDebye':0,'debyeTerms':[],'nPeaks':0,'peaksList':[],
     6819                        'background PWDR':['',1.0,False]}]))
    68206820                G2frame.GPXtree.SetItemPyData(
    68216821                    G2frame.GPXtree.AppendItem(Id,text='Instrument Parameters'),
  • trunk/GSASIIdataGUI.py

    r4664 r4671  
    19681968                self.GPXtree.AppendItem(Id,text='Background'),
    19691969                rd.pwdparms.get('Background',
    1970                     [['chebyschev-1',True,3,1.0,0.0,0.0],{'nDebye':0,'debyeTerms':[],'nPeaks':0,'peaksList':[]}])
    1971                     )
     1970                    [['chebyschev-1',True,3,1.0,0.0,0.0],{'nDebye':0,'debyeTerms':[],'nPeaks':0,'peaksList':[],
     1971                    'background PWDR':['',1.0,False]}]))
    19721972            self.GPXtree.SetItemPyData(
    19731973                self.GPXtree.AppendItem(Id,text='Instrument Parameters'),
     
    21652165            self.GPXtree.AppendItem(Id,text='Background'),
    21662166            [['chebyschev-1',True,3,1.0,0.0,0.0],
    2167              {'nDebye':0,'debyeTerms':[],'nPeaks':0,'peaksList':[]}])
     2167             {'nDebye':0,'debyeTerms':[],'nPeaks':0,'peaksList':[],'background PWDR':['',1.0,False]}])
    21682168        self.GPXtree.SetItemPyData(
    21692169            self.GPXtree.AppendItem(Id,text='Instrument Parameters'),
     
    22992299            self.GPXtree.AppendItem(Id,text='Background'),
    23002300            [['chebyschev-1',True,3,1.0,0.0,0.0],
    2301              {'nDebye':0,'debyeTerms':[],'nPeaks':0,'peaksList':[]}])
     2301             {'nDebye':0,'debyeTerms':[],'nPeaks':0,'peaksList':[],'background PWDR':['',1.0,False]}])
    23022302        self.GPXtree.SetItemPyData(
    23032303            self.GPXtree.AppendItem(Id,text='Instrument Parameters'),
     
    38033803                        self.GPXtree.SetItemPyData(self.GPXtree.AppendItem(Id,text='Limits'),[tuple(Xminmax),Xminmax])
    38043804                        self.GPXtree.SetItemPyData(self.GPXtree.AppendItem(Id,text='Background'),[['chebyschev-1',True,3,1.0,0.0,0.0],
    3805                             {'nDebye':0,'debyeTerms':[],'nPeaks':0,'peaksList':[]}])
     3805                            {'nDebye':0,'debyeTerms':[],'nPeaks':0,'peaksList':[],'background PWDR':['',1.0,False]}])
    38063806                        self.GPXtree.SetItemPyData(self.GPXtree.AppendItem(Id,text='Instrument Parameters'),Inst)
    38073807                        self.GPXtree.SetItemPyData(self.GPXtree.AppendItem(Id,text='Sample Parameters'),Sample)
  • trunk/GSASIIimage.py

    r4593 r4671  
    503503    xyz = LinePlaneCollision(dxyz0,dxyz1,vect,2.*dist*vect)
    504504    if xyz is None:
    505         return None
     505        return np.zeros(2)
     506#        return None
    506507    xyz = np.inner(xyz,makeMat(-data['det2theta'],1).T)
    507508    xyz -= np.array([0.,0.,dist])                 #translate back
     
    638639    distsq = data['distance']**2
    639640    G = ((dx-x0x)**2+(dy-x0y)**2+distsq)/distsq       #for geometric correction = 1/cos(2theta)^2 if tilt=0.
    640     return tth,azm,G,dsp
     641    return [tth,azm,G,dsp]
    641642   
    642643def GetTth(x,y,data):
     
    763764    Ty = np.zeros_like(Tx)
    764765    dsp = wave/(2.0*npsind(Tx/2.0))
    765     xy = np.array([GetDetectorXY(d,azm,data) for d in dsp]).T
     766    xy = [GetDetectorXY(d,azm,data) for d in dsp]
     767    xy = np.array(xy).T
    766768    xy[1] *= scalex
    767769    xy[0] *= scaley
     
    14591461            XY = np.array(ringxy).T
    14601462            Th,Azm = GetTthAzm(XY[0],XY[1],Controls)
    1461             pola = G2pwd.Polarization(Controls['PolaVal'][0],Th,Azm-90.)[0]
     1463            pola = G2pwd.Polarization(Controls['PolaVal'][0],Th,Azm-90.)[0]     #get pola not dpola
    14621464            ring['ImxyCalc'] = np.array(ringxy).T[:2]
    14631465            ringint = np.array([float(Image[int(x*scalex),int(y*scaley)]) for y,x in np.array(ringxy)[:,:2]])
    14641466            ringint /= np.mean(ringint)
    1465             ringint /= pola
     1467            ringint /= pola[0]      #just 1st column
    14661468            G2fil.G2Print (' %s %.3f %s %.3f %s %d'%('d-spacing',ring['Dcalc'],'sig(MRD):',np.sqrt(np.var(ringint)),'# points:',len(ringint)))
    14671469            RingsAI.append(np.array(list(zip(ringazm,ringint))).T)
  • trunk/GSASIIimgGUI.py

    r4635 r4671  
    17141714                x0 = G2img.GetDetectorXY(dsp0,0.0,Controls)[0]
    17151715                x1 = G2img.GetDetectorXY(dsp1,0.0,Controls)[0]
    1716                 if x0 is None or x1 is None:
     1716                if not np.any(x0) or not np.any(x1):
    17171717                    raise Exception
    17181718                nChans = int(1000*(x1-x0)/Controls['pixelSize'][0])//2
     
    17491749                    x0 = G2img.GetDetectorXY(dsp0,0.0,Controls)[0]
    17501750                    x1 = G2img.GetDetectorXY(dsp1,0.0,Controls)[0]
    1751                     if x0 is None or x1 is None:
     1751                    if not np.any(x0) or not np.any(x1):
    17521752                        raise Exception
    17531753                    nChans = int(1000*(x1-x0)/Controls['pixelSize'][0])//2
  • trunk/GSASIImath.py

    r4614 r4671  
    191191                Ainv,Nzeros = pinv(Amatlam,xtol)    #do Moore-Penrose inversion (via SVD)
    192192            except nl.LinAlgError:
    193                 psing = list(np.where(np.diag(nl.qr(Amatlam)[1]) < 1.e-14)[0])
     193                psing = list(np.where(np.abs(np.diag(nl.qr(Amatlam)[1])) < 1.e-14)[0])
    194194                G2fil.G2Print('ouch #1 bad SVD inversion; change parameterization for ',psing, mode='error')
    195195                return [x0,None,{'num cyc':icycle,'fvec':M,'nfev':nfev,'lamMax':lamMax,'psing':psing,'SVD0':-1}]
     
    321321        except nl.LinAlgError:
    322322            G2fil.G2Print('ouch #1 bad SVD inversion; change parameterization', mode='warn')
    323             psing = list(np.where(np.diag(nl.qr(Amat)[1]) < 1.e-14)[0])
     323            psing = list(np.where(np.abs(np.diag(nl.qr(Amat)[1])) < 1.e-14)[0])
    324324            return [x0,None,{'num cyc':icycle,'fvec':M,'nfev':nfev,'lamMax':0.,'psing':psing,'SVD0':-1}]
    325325        Xvec = np.inner(Ainv,Yvec)      #solve
  • trunk/GSASIIobj.py

    r4661 r4671  
    18131813        'Amul': 'Atomic site multiplicity value',
    18141814        'AM([xyz])$' : 'Atomic magnetic moment parameter, \\1',
    1815         # Hist & Phase (HAP) vars (p:h:<var>)
     1815        # Hist (:h:<var>) & Phase (HAP) vars (p:h:<var>)
    18161816        'Back': 'Background term',
    18171817        'BkPkint;(.*)':'Background peak #\\1 intensity',
     
    18191819        'BkPksig;(.*)':'Background peak #\\1 Gaussian width',
    18201820        'BkPkgam;(.*)':'Background peak #\\1 Cauchy width',
     1821#        'Back File' : 'Background file name',
     1822        'BF mult' : 'Background file multiplier',
    18211823        'Bab([AU])': 'Babinet solvent scattering coef. \\1',
    18221824        'D([123][123])' : 'Anisotropic strain coef. \\1',
  • trunk/GSASIIplot.py

    r4665 r4671  
    27002700        G2frame.lastPlotType = None
    27012701    if plotType == 'PWDR':
    2702         Parms,Parms2 = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,
    2703             G2frame.PatternId, 'Instrument Parameters'))
    2704         if G2frame.lastPlotType != Parms['Type'][1]:
    2705             if GSASIIpath.GetConfigValue('debug'):
    2706                 print('triggering newplot from G2frame.lastPlotType')
    2707             Ymax = max(data[1][1])
    2708             if Page.plotStyle['sqrtPlot']:
    2709                 Page.plotStyle['delOffset'] = .02*np.sqrt(Ymax)
    2710                 Page.plotStyle['refOffset'] = -0.1*np.sqrt(Ymax)
    2711                 Page.plotStyle['refDelt'] = .1*np.sqrt(Ymax)
    2712             else:
    2713                 Page.plotStyle['delOffset'] = .02*Ymax
    2714                 Page.plotStyle['refOffset'] = -0.1*Ymax
    2715                 Page.plotStyle['refDelt'] = .1*Ymax
    2716             newPlot = True
    2717         G2frame.lastPlotType = Parms['Type'][1]
     2702        try:
     2703            Parms,Parms2 = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,
     2704                G2frame.PatternId, 'Instrument Parameters'))
     2705            if G2frame.lastPlotType != Parms['Type'][1]:
     2706                if GSASIIpath.GetConfigValue('debug'):
     2707                    print('triggering newplot from G2frame.lastPlotType')
     2708                Ymax = max(data[1][1])
     2709                if Page.plotStyle['sqrtPlot']:
     2710                    Page.plotStyle['delOffset'] = .02*np.sqrt(Ymax)
     2711                    Page.plotStyle['refOffset'] = -0.1*np.sqrt(Ymax)
     2712                    Page.plotStyle['refDelt'] = .1*np.sqrt(Ymax)
     2713                else:
     2714                    Page.plotStyle['delOffset'] = .02*Ymax
     2715                    Page.plotStyle['refOffset'] = -0.1*Ymax
     2716                    Page.plotStyle['refDelt'] = .1*Ymax
     2717                newPlot = True
     2718            G2frame.lastPlotType = Parms['Type'][1]
     2719        except TypeError:       #bad id from GetGPXtreeItemId - skip
     2720            pass
    27182721       
    27192722    try:
     
    28702873        Pattern.append(G2frame.GPXtree.GetItemText(PatternId))
    28712874        PlotList = [Pattern,]
    2872         PId = G2gd.GetGPXtreeItemId(G2frame,G2frame.PatternId, 'Background')
    2873         Pattern[0]['BackFile'] = ['',-1.0,False]
    2874         if PId:
    2875             Pattern[0]['BackFile'] =  G2frame.GPXtree.GetItemPyData(PId)[1].get('background PWDR',['',-1.0,False])
     2875        # PId = G2gd.GetGPXtreeItemId(G2frame,G2frame.PatternId, 'Background')
     2876        # Pattern[0]['BackFile'] = ['',-1.0,False]
     2877        # if PId:
     2878        #     Pattern[0]['BackFile'] =  G2frame.GPXtree.GetItemPyData(PId)[1].get('background PWDR',['',-1.0,False])
    28762879        Parms,Parms2 = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,
    28772880            G2frame.PatternId, 'Instrument Parameters'))
     
    29052908                Ymax = max(Pattern[1][1])
    29062909                Page.plotStyle.update({'Offset':[0.0,0.0],'delOffset':0.02*Ymax,'refOffset':-0.1*Ymax,'refDelt':0.1*Ymax,})
    2907             PId = G2gd.GetGPXtreeItemId(G2frame,G2frame.PatternId, 'Background')
    2908             Pattern[0]['BackFile'] = ['',-1.0,False]
    2909             if PId:
    2910                 Pattern[0]['BackFile'] =  G2frame.GPXtree.GetItemPyData(PId)[1].get('background PWDR',['',-1.0,False])
     2910            # PId = G2gd.GetGPXtreeItemId(G2frame,G2frame.PatternId, 'Background')
     2911            # Pattern[0]['BackFile'] = ['',-1.0,False]
     2912            # if PId:
     2913            #     Pattern[0]['BackFile'] =  G2frame.GPXtree.GetItemPyData(PId)[1].get('background PWDR',['',-1.0,False])
    29112914            PlotList.append(Pattern)
    29122915            ParmList.append(G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,
     
    29252928    for ip,Pattern in enumerate(PlotList):
    29262929        xye = Pattern[1]
    2927         #bxye = G2pdG.GetFileBackground(G2frame,xye,Pattern)
    29282930        if xye[1] is None: continue
    29292931        if Ymax is None: Ymax = max(xye[1])
     
    69016903    for azm in Azm:
    69026904        XY = G2img.GetDetectorXY(Dsp(np.squeeze(angI),wave),azm,Data)
    6903         if XY is not None:
     6905        if np.any(XY):
    69046906            xy1.append(XY)      #what about hyperbola
    69056907        XY = G2img.GetDetectorXY(Dsp(np.squeeze(angO),wave),azm,Data)
    6906         if XY is not None:
     6908        if np.any(XY):
    69076909            xy2.append(XY)      #what about hyperbola
    69086910    return np.array(xy1).T,np.array(xy2).T
     
    75807582            if not Xpos or not Ypos or Page.toolbar.AnyActive():  #got point out of frame or zoom/pan selected
    75817583                return
    7582             dsp = G2img.GetDsp(Xpos,Ypos,Data)
     7584            dsp = float(G2img.GetDsp(Xpos,Ypos,Data))
    75837585            StrSta['d-zero'].append({'Dset':dsp,'Dcalc':0.0,'pixLimit':10,'cutoff':0.5,'Ivar':0.0,
    75847586                'ImxyObs':[[],[]],'ImxyCalc':[[],[]],'ImtaObs':[[],[]],'ImtaCalc':[[],[]],'Emat':[1.0,1.0,1.0],'Ivar':0})
     
    78287830            xyO = G2img.GetDetectorXY(dspO,azm,Data)
    78297831            Plot.plot([xyI[0],xyO[0]],[xyI[1],xyO[1]],
    7830                                 picker=True,pickradius=3,label='linescan')
     7832#                picker=True,pickradius=3,label='linescan')
     7833                picker=False,label='linescan')
    78317834                   
    78327835        if G2frame.PickId and G2frame.GPXtree.GetItemText(G2frame.PickId) in ['Image Controls',]:
     
    84368439                    G2frame.G2plotNB.status.SetStatusText('New quaternion: %.2f+, %.2fi+ ,%.2fj+, %.2fk'%(Q[0],Q[1],Q[2],Q[3]),1)
    84378440                Draw('move')
    8438         elif drawingData.get('showSlice'):
     8441        elif drawingData.get('showSlice',False):
    84398442            View = GL.glGetIntegerv(GL.GL_VIEWPORT)
    84408443            Tx,Ty,Tz = drawingData['viewPoint'][0]
     
    84428445            Cx,Cy,Cz = GLU.gluUnProject(newxy[0],View[3]-newxy[1],tz)
    84438446            rho = G2mth.getRho([Cx,Cy,Cz],mapData)
    8444             if drawingData.get('showSlice') in [1,3]:
     8447            if drawingData.get('showSlice',False) in [1,3]:
    84458448                contlevels = contourSet.get_array()
    84468449                contstr = str(contlevels).strip('[]')
  • trunk/GSASIIpwd.py

    r4592 r4671  
    228228
    229229    :param Pola: polarization coefficient e.g 1.0 fully polarized, 0.5 unpolarized
    230     :param Azm: azimuthal angle e.g. 0.0 in plane of polarization
     230    :param Azm: azimuthal angle e.g. 0.0 in plane of polarization - can be numpy array
    231231    :param Tth: 2-theta scattering angle - can be numpy array
    232232      which (if either) of these is "right"?
    233     :return: (pola, dpdPola)
     233    :return: (pola, dpdPola) - both 2-d arrays
    234234      * pola = ((1-Pola)*npcosd(Azm)**2+Pola*npsind(Azm)**2)*npcosd(Tth)**2+ \
    235235        (1-Pola)*npsind(Azm)**2+Pola*npcosd(Azm)**2
     
    856856    return intens*Df(xdata)*DX/dx
    857857
    858 def getBackground(pfx,parmDict,bakType,dataType,xdata,fixedBkg={}):
     858def getBackground(pfx,parmDict,bakType,dataType,xdata,fixback=None):
    859859    '''Computes the background from vars pulled from gpx file or tree.
    860860    '''
     
    985985            G2fil.G2Print ('**** WARNING - backround peak '+str(iD)+' sigma is negative; fix & try again ****')
    986986            break
    987     # fixed background from file
    988     if len(fixedBkg) >= 3:
    989         mult = fixedBkg.get('_fixedMult',0.0)
    990         if len(fixedBkg.get('_fixedValues',[])) != len(yb):
    991             G2fil.G2Print('Lengths of backgrounds do not agree: yb={}, fixed={}'.format(
    992                 len(yb),len(fixedBkg.get('_fixedValues',[]))))
    993         elif mult:
    994             yb -= mult*fixedBkg.get('_fixedValues',[]) # N.B. mult is negative
    995             sumBk[0] = sum(yb)
     987    if fixback is not None:   
     988        yb += parmDict[pfx+'BF mult']*fixback
     989        sumBk[0] = sum(yb)
    996990    return yb,sumBk
    997991   
    998 def getBackgroundDerv(hfx,parmDict,bakType,dataType,xdata):
     992def getBackgroundDerv(hfx,parmDict,bakType,dataType,xdata,fixback=None):
    999993    'needs a doc string'
    1000994    if 'T' in dataType:
     
    10131007    dyddb = np.zeros(shape=(3*parmDict[hfx+'nDebye'],len(xdata)))
    10141008    dydpk = np.zeros(shape=(4*parmDict[hfx+'nPeaks'],len(xdata)))
     1009    dydfb = []
    10151010    cw = np.diff(xdata)
    10161011    cw = np.append(cw,cw[-1])
     
    11261121            G2fil.G2Print ('**** WARNING - backround peak '+str(iD)+' sigma is negative; fix & try again ****')
    11271122            break       
    1128     return dydb,dyddb,dydpk
     1123    # fixed background from file
     1124    if  fixback is not None:
     1125        dydfb = fixback
     1126    return dydb,dyddb,dydpk,dydfb
    11291127
    11301128#use old fortran routine
     
    12811279    return G2lat.sortHKLd(HKLs,True,True,True)
    12821280
    1283 def getPeakProfile(dataType,parmDict,xdata,varyList,bakType):
     1281def getPeakProfile(dataType,parmDict,xdata,fixback,varyList,bakType):
    12841282    'Computes the profile for a powder pattern'
    12851283   
    1286     yb = getBackground('',parmDict,bakType,dataType,xdata)[0]
     1284    yb = getBackground('',parmDict,bakType,dataType,xdata,fixback)[0]
    12871285    yc = np.zeros_like(yb)
    12881286    cw = np.diff(xdata)
     
    14341432                return yb+yc
    14351433           
    1436 def getPeakProfileDerv(dataType,parmDict,xdata,varyList,bakType):
     1434def getPeakProfileDerv(dataType,parmDict,xdata,fixback,varyList,bakType):
    14371435    'needs a doc string'
    14381436# needs to return np.array([dMdx1,dMdx2,...]) in same order as varylist = backVary,insVary,peakVary order
    14391437    dMdv = np.zeros(shape=(len(varyList),len(xdata)))
    1440     dMdb,dMddb,dMdpk = getBackgroundDerv('',parmDict,bakType,dataType,xdata)
     1438    dMdb,dMddb,dMdpk,dMdfb = getBackgroundDerv('',parmDict,bakType,dataType,xdata,fixback)
    14411439    if 'Back;0' in varyList:            #background derivs are in front if present
    14421440        dMdv[0:len(dMdb)] = dMdb
     
    17121710            except KeyError:        #no more peaks to process
    17131711                break
     1712    if 'BF mult' in varyList:
     1713        dMdv[varyList.index('BF mult')] = fixback
     1714       
    17141715    return dMdv
    17151716       
     
    17641765    backDict.update(peaksDict)
    17651766    backVary += peaksVary
     1767    if 'background PWDR' in Background[1]:
     1768        backDict['Back File'] = Background[1]['background PWDR'][0]
     1769        backDict['BF mult'] = Background[1]['background PWDR'][1]
     1770        if len(Background[1]['background PWDR']) > 2:
     1771            if Background[1]['background PWDR'][2]:
     1772                backVary += ['BF mult',]
    17661773    return bakType,backDict,backVary
    17671774   
     
    18741881      data[1] is the y-values, data[2] are weight values, data[3], [4] and [5] are
    18751882      calc, background and difference intensities, respectively.
    1876     :param array fixback: fixed background values
     1883    :param array fixback: fixed background array; same size as data[0-5]
    18771884    :param list prevVaryList: Used in sequential refinements to override the
    18781885      variable list. Defaults as an empty list.
     
    19131920            except KeyError:
    19141921                break
     1922        if 'BF mult' in parmList:
     1923            Background[1]['background PWDR'][1] = parmList['BF mult']
    19151924               
    19161925    def BackgroundPrint(Background,sigDict):
     
    19691978                print (ptstr)
    19701979                print (sigstr)
     1980        if 'BF mult' in sigDict:
     1981            print('Background file mult: %.3f(%d)'%(Background[1]['background PWDR'][1],int(1000*sigDict['BF mult'])))
    19711982                           
    19721983    def SetInstParms(Inst):
     
    21192130            print ('%s'%(('Peak'+str(i+1)).center(8)),ptstr)
    21202131               
    2121     def devPeakProfile(values,xdata,ydata, weights,dataType,parmdict,varylist,bakType,dlg):
     2132    def devPeakProfile(values,xdata,ydata,fixback, weights,dataType,parmdict,varylist,bakType,dlg):
    21222133        parmdict.update(zip(varylist,values))
    2123         return np.sqrt(weights)*getPeakProfileDerv(dataType,parmdict,xdata,varylist,bakType)
     2134        return np.sqrt(weights)*getPeakProfileDerv(dataType,parmdict,xdata,fixback,varylist,bakType)
    21242135           
    2125     def errPeakProfile(values,xdata,ydata,weights,dataType,parmdict,varylist,bakType,dlg):       
     2136    def errPeakProfile(values,xdata,ydata,fixback,weights,dataType,parmdict,varylist,bakType,dlg):       
    21262137        parmdict.update(zip(varylist,values))
    2127         M = np.sqrt(weights)*(getPeakProfile(dataType,parmdict,xdata,varylist,bakType)-ydata)
     2138        M = np.sqrt(weights)*(getPeakProfile(dataType,parmdict,xdata,fixback,varylist,bakType)-ydata)
    21282139        Rwp = min(100.,np.sqrt(np.sum(M**2)/np.sum(weights*ydata**2))*100.)
    21292140        if dlg:
     
    21692180        badVary = []
    21702181        result = so.leastsq(errPeakProfile,values,Dfun=devPeakProfile,full_output=True,ftol=Ftol,col_deriv=True,
    2171                args=(x[xBeg:xFin],(y+fixback)[xBeg:xFin],wtFactor*w[xBeg:xFin],dataType,parmDict,varyList,bakType,dlg))
     2182               args=(x[xBeg:xFin],y[xBeg:xFin],fixback[xBeg:xFin],wtFactor*w[xBeg:xFin],dataType,parmDict,varyList,bakType,dlg))
    21722183        ncyc = int(result[2]['nfev']/2)
    21732184        runtime = time.time()-begin   
    21742185        chisq = np.sum(result[2]['fvec']**2)
    21752186        Values2Dict(parmDict, varyList, result[0])
    2176         Rvals['Rwp'] = np.sqrt(chisq/np.sum(wtFactor*w[xBeg:xFin]*(y+fixback)[xBeg:xFin]**2))*100.      #to %
     2187        Rvals['Rwp'] = np.sqrt(chisq/np.sum(wtFactor*w[xBeg:xFin]*y[xBeg:xFin]**2))*100.      #to %
    21772188        Rvals['GOF'] = chisq/(xFin-xBeg-len(varyList))       #reduced chi^2
    21782189        G2fil.G2Print ('Number of function calls: %d Number of observations: %d Number of parameters: %d'%(result[2]['nfev'],xFin-xBeg,len(varyList)))
     
    22002211    if dlg: dlg.Destroy()
    22012212    sigDict = dict(zip(varyList,sig))
    2202     yb[xBeg:xFin] = getBackground('',parmDict,bakType,dataType,x[xBeg:xFin])[0]-fixback[xBeg:xFin]
    2203     yc[xBeg:xFin] = getPeakProfile(dataType,parmDict,x[xBeg:xFin],varyList,bakType)-fixback[xBeg:xFin]
     2213    yb[xBeg:xFin] = getBackground('',parmDict,bakType,dataType,x[xBeg:xFin],fixback[xBeg:xFin])[0]
     2214    yc[xBeg:xFin] = getPeakProfile(dataType,parmDict,x[xBeg:xFin],fixback[xBeg:xFin],varyList,bakType)
    22042215    yd[xBeg:xFin] = y[xBeg:xFin]-yc[xBeg:xFin]
    22052216    GetBackgroundParms(parmDict,Background)
     
    41704181    gplot = plotter.add('FCJ-Voigt, 11BM').gca()
    41714182    gplot.plot(xdata,getBackground('',parmDict0,bakType,'PXC',xdata)[0])   
    4172     gplot.plot(xdata,getPeakProfile(parmDict0,xdata,varyList,bakType))
     4183    gplot.plot(xdata,getPeakProfile(parmDict0,xdata,np.zeros_like(xdata),varyList,bakType))
    41734184    fplot = plotter.add('FCJ-Voigt, Ka1+2').gca()
    41744185    fplot.plot(xdata,getBackground('',parmDict1,bakType,'PXC',xdata)[0])   
    4175     fplot.plot(xdata,getPeakProfile(parmDict1,xdata,varyList,bakType))
     4186    fplot.plot(xdata,getPeakProfile(parmDict1,xdata,np.zeros_like(xdata),varyList,bakType))
    41764187   
    41774188def test1():
     
    41794190    time0 = time.time()
    41804191    for i in range(100):
    4181         getPeakProfile(parmDict1,xdata,varyList,bakType)
     4192        getPeakProfile(parmDict1,xdata,np.zeros_like(xdata),varyList,bakType)
    41824193    G2fil.G2Print ('100+6*Ka1-2 peaks=1200 peaks %.2f'%time.time()-time0)
    41834194   
     
    41874198    xdata = np.linspace(5.6,5.8,400)
    41884199    hplot = plotter.add('derivatives test for '+name).gca()
    4189     hplot.plot(xdata,getPeakProfileDerv(parmDict2,xdata,varyList,bakType)[0])
    4190     y0 = getPeakProfile(parmDict2,xdata,varyList,bakType)
     4200    hplot.plot(xdata,getPeakProfileDerv(parmDict2,xdata,np.zeros_like(xdata),varyList,bakType)[0])
     4201    y0 = getPeakProfile(parmDict2,xdata,np.zeros_like(xdata),varyList,bakType)
    41914202    parmDict2[name] += delt
    4192     y1 = getPeakProfile(parmDict2,xdata,varyList,bakType)
     4203    y1 = getPeakProfile(parmDict2,xdata,np.zeros_like(xdata),varyList,bakType)
    41934204    hplot.plot(xdata,(y1-y0)/delt,'r+')
    41944205   
  • trunk/GSASIIpwdGUI.py

    r4667 r4671  
    284284################################################################################
    285285
    286 def GetFileBackground(G2frame,xye,Pattern):
     286def GetFileBackground(G2frame,xye,background,scale=True):
    287287    bxye = np.zeros(len(xye[1]))
    288     if 'BackFile' in Pattern[0]:
    289         backfile,mult = Pattern[0]['BackFile'][:2]
     288    mult = 1.0
     289    if 'background PWDR' in background[1]:
     290        backfile,mult = background[1]['background PWDR'][:2]
    290291        if backfile:
    291292            bId = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,backfile)
    292293            if bId:
    293                 bxye = mult*G2frame.GPXtree.GetItemPyData(bId)[1][1]
     294                bxye = G2frame.GPXtree.GetItemPyData(bId)[1][1]
    294295            else:
    295296                print('Error: background PWDR {} not found'.format(backfile))
    296                 Pattern[0]['BackFile'][0] = ''
    297     return bxye
     297                background[1]['background PWDR'] = ['',1.0,False]
     298    if scale:
     299        return bxye*mult
     300    else:
     301        return bxye
    298302   
    299303def IsHistogramInAnyPhase(G2frame,histoName):
     
    641645        PatternId = G2frame.PatternId
    642646        limits = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Limits'))[1]
     647        background = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Background'))
    643648        inst,inst2 = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Instrument Parameters'))
    644649        Pattern = G2frame.GPXtree.GetItemPyData(PatternId)
    645650        profile = Pattern[1]
    646         bxye = GetFileBackground(G2frame,profile,Pattern)
     651        bxye = GetFileBackground(G2frame,profile,background)
    647652        x0 = profile[0]
    648653        iBeg = np.searchsorted(x0,limits[0])
    649654        iFin = np.searchsorted(x0,limits[1])
    650655        x = x0[iBeg:iFin]
    651         y0 = (profile[1]+bxye)[iBeg:iFin]
     656        y0 = (profile[1]-bxye)[iBeg:iFin]
    652657        ysig = 1.0*np.std(y0)
    653658        offset = [-1,1]
     
    834839                Pattern = G2frame.GPXtree.GetItemPyData(PatternId)
    835840                data = Pattern[1]
    836                 fixback = GetFileBackground(G2frame,data,Pattern)
     841                fixback = GetFileBackground(G2frame,data,background,scale=False)
    837842                peaks['sigDict'],result,sig,Rvals,varyList,parmDict,fullvaryList,badVary = G2pwd.DoPeakFit(FitPgm,peaks['peaks'],
    838843                    background,limits,inst,inst2,data,fixback,prevVaryList,oneCycle,controls)   #needs wtFactor after controls?
     
    881886        data = Pattern[1]
    882887        wtFactor = Pattern[0]['wtFactor']
    883         bxye = GetFileBackground(G2frame,data,Pattern)
     888        bxye = GetFileBackground(G2frame,data,background,scale=False)
    884889        dlg = wx.ProgressDialog('Residual','Peak fit Rwp = ',101.0,
    885890            style = wx.PD_ELAPSED_TIME|wx.PD_AUTO_HIDE|wx.PD_REMAINING_TIME|wx.PD_CAN_ABORT)
     
    11371142    reflGrid.SetScrollRate(10,10)
    11381143    G2frame.reflGrid = reflGrid
    1139     mainSizer.Add(reflGrid,1,wx.ALL|wx.EXPAND,1)
     1144#    mainSizer.Add(reflGrid,1,wx.ALL|wx.EXPAND,1)
     1145    mainSizer.Add(reflGrid)
     1146    mainSizer.Add(G2G.HelpButton(G2frame.dataWindow,helpIndex=G2frame.dataWindow.helpKey))
    11401147    G2frame.dataWindow.SetDataSize()
    11411148
     
    11571164            PKflags = []
    11581165            for term in backDict['peaksList']:
    1159                 PKflags.append(term[1::2])           
     1166                PKflags.append(term[1::2])
     1167        FBflag = backDict['background PWDR'][2]
    11601168        hst = G2frame.GPXtree.GetItemText(G2frame.PatternId)
    11611169        histList = GetHistsLikeSelected(G2frame)
     
    11821190            if bkDict['nPeaks'] == backDict['nPeaks']:
    11831191                for i,term in enumerate(bkDict['peaksList']):
    1184                     term[1::2] = copy.copy(PKflags[i])                   
     1192                    term[1::2] = copy.copy(PKflags[i])
     1193            backData[1]['background PWDR'] = copy.copy(FBflag)
    11851194           
    11861195    def OnBackCopy(event):
     
    16011610        def OnBackPWDR(event):
    16021611            data[1]['background PWDR'][0] = back.GetValue()
    1603             if  data[1]['background PWDR'][0]:
     1612            if len(data[1]['background PWDR'][0]):
    16041613                curHist = G2frame.GPXtree.GetItemPyData(G2frame.PatternId)
    16051614                Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,data[1]['background PWDR'][0])
     
    16151624                    data[1]['background PWDR'][0] = back.GetValue()
    16161625                    return
     1626            else:
     1627                data[1]['background PWDR'][2] = False
    16171628            CalcBack()
    16181629            G2plt.PlotPatterns(G2frame,plotType='PWDR')
     1630            wx.CallLater(100,UpdateBackground,G2frame,data)
    16191631       
    16201632        def AfterChange(invalid,value,tc):
     
    16221634            CalcBack()
    16231635            G2plt.PlotPatterns(G2frame,plotType='PWDR')
     1636           
     1637        def OnBackFit(event):
     1638            data[1]['background PWDR'][2] = not data[1]['background PWDR'][2]           
    16241639
    16251640        fileSizer = wx.BoxSizer(wx.VERTICAL)
     
    16381653        backMult = G2G.ValidatedTxtCtrl(G2frame.dataWindow,data[1]['background PWDR'],1,nDig=(10,3),OnLeave=AfterChange)
    16391654        backSizer.Add(backMult,0,WACV)
     1655        if len(data[1]['background PWDR'][0]):
     1656            backFit = wx.CheckBox(G2frame.dataWindow,label=' Refine?')
     1657            backFit.SetValue(data[1]['background PWDR'][2])
     1658            backFit.Bind(wx.EVT_CHECKBOX, OnBackFit)
     1659            backSizer.Add(backFit,0,WACV)
    16401660        fileSizer.Add(backSizer)
    16411661        return fileSizer
    16421662   
    16431663    def CalcBack(PatternId=G2frame.PatternId):
    1644             limits = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Limits'))[1]
    1645             inst,inst2 = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Instrument Parameters'))
    1646             backData = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Background'))
    1647             dataType = inst['Type'][0]
    1648             insDict = {inskey:inst[inskey][1] for inskey in inst}
    1649             parmDict = {}
    1650             bakType,bakDict,bakVary = G2pwd.SetBackgroundParms(data)
    1651             parmDict.update(bakDict)
    1652             parmDict.update(insDict)
    1653             pwddata = G2frame.GPXtree.GetItemPyData(PatternId)
    1654             xBeg = np.searchsorted(pwddata[1][0],limits[0])
    1655             xFin = np.searchsorted(pwddata[1][0],limits[1])
    1656             fixBack = backData[1]['background PWDR']
    1657             try:    #typically bad grid value or no fixed bkg file
    1658                 Id = G2gd.GetGPXtreeItemId(G2frame,G2frame.root,fixBack[0])
    1659                 fixData = G2frame.GPXtree.GetItemPyData(Id)
    1660                 fixedBkg = {'_fixedVary':False,'_fixedMult':fixBack[1],'_fixedValues':fixData[1][1][xBeg:xFin]}
    1661                 pwddata[1][4][xBeg:xFin] = G2pwd.getBackground('',parmDict,bakType,dataType,pwddata[1][0][xBeg:xFin],fixedBkg)[0]
    1662             except:
    1663                 pass
     1664        limits = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Limits'))[1]
     1665        inst,inst2 = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Instrument Parameters'))
     1666        backData = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(G2frame,PatternId, 'Background'))
     1667        dataType = inst['Type'][0]
     1668        insDict = {inskey:inst[inskey][1] for inskey in inst}
     1669        parmDict = {}
     1670        bakType,bakDict,bakVary = G2pwd.SetBackgroundParms(data)
     1671        parmDict.update(bakDict)
     1672        parmDict.update(insDict)
     1673        pwddata = G2frame.GPXtree.GetItemPyData(PatternId)
     1674        xBeg = np.searchsorted(pwddata[1][0],limits[0])
     1675        xFin = np.searchsorted(pwddata[1][0],limits[1])
     1676        fixBack = GetFileBackground(G2frame,pwddata[1],backData,scale=False)
     1677        pwddata[1][4][xBeg:xFin] = G2pwd.getBackground('',parmDict,bakType,dataType,pwddata[1][0][xBeg:xFin],fixBack[xBeg:xFin])[0]
    16641678
    16651679    # UpdateBackground execution starts here   
    16661680    if len(data) < 2:       #add Debye diffuse & peaks scattering here
    1667         data.append({'nDebye':0,'debyeTerms':[],'nPeaks':0,'peaksList':[]})
     1681        data.append({'nDebye':0,'debyeTerms':[],'nPeaks':0,'peaksList':[],'background PWDR':['',1.0,False]})
    16681682    if 'nPeaks' not in data[1]:
    1669         data[1].update({'nPeaks':0,'peaksList':[]})
     1683        data[1].update({'nPeaks':0,'peaksList':[],'background PWDR':['',1.0,False]})
     1684    if 'background PWDR' not in data[1]:
     1685        data[1].update({'background PWDR':['',1.0,False]})
     1686    elif len(data[1]['background PWDR']) < 3:
     1687        data[1]['background PWDR'].append(False)
    16701688    G2frame.dataWindow.currentGrids = []
    16711689    G2gd.SetDataMenuBar(G2frame,G2frame.dataWindow.BackMenu)
     
    50045022                G2frame.RefList = ''
    50055023                phaseName = ''
     5024    G2frame.dataWindow.GetSizer().Add(G2G.HelpButton(G2frame.dataWindow,helpIndex=G2frame.dataWindow.helpKey))
    50065025    if phaseName: ShowReflTable(phaseName)
    50075026    G2frame.refBook.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CHANGED, OnPageChanged)
  • trunk/GSASIIscriptable.py

    r4659 r4671  
    16811681
    16821682    default_background = [['chebyschev-1', False, 3, 1.0, 0.0, 0.0],
    1683                           {'nDebye': 0, 'debyeTerms': [], 'nPeaks': 0, 'peaksList': []}]
     1683        {'nDebye': 0, 'debyeTerms': [], 'nPeaks': 0,
     1684        'peaksList': [],'background PWDR':['',1.0,False]}]
    16841685
    16851686    output_dict = {u'Reflection Lists': {},
  • trunk/GSASIIstrIO.py

    r4666 r4671  
    606606                xB = np.searchsorted(x,Limits[0])
    607607                xF = np.searchsorted(x,Limits[1])+1
    608                 h['_fixedValues'] = allHistograms[fixedBkg[0]]['Data'][1][xB:xF]
    609                 h['_fixedMult'],h['_fixedVary'] = fixedBkg[1:]
     608                h['fixback'] = allHistograms[fixedBkg[0]]['Data'][1][xB:xF]
    610609            except KeyError: # would happen if a referenced histogram were renamed or deleted
    611610                G2fil.G2Print('Warning: For hist "{}" unresolved background reference to hist "{}"'
     
    31753174        backDict.update(peakDict)
    31763175        backVary += peakVary
     3176        if 'background PWDR' in Background[1]:
     3177            backDict[':'+str(hId)+':Back File'] = Background[1]['background PWDR'][0]
     3178            backDict[':'+str(hId)+':BF mult'] = Background[1]['background PWDR'][1]
     3179            try:
     3180                if Background[1]['background PWDR'][2]:
     3181                    backVary.append(':'+str(hId)+':BF mult')
     3182            except IndexError:  # old version withut refine flag
     3183                pass
    31773184        return bakType,backDict,backVary           
    31783185       
     
    32633270                    line += '%12.3f %5s'%(term[2*i],bool(term[2*i+1]))                   
    32643271                pFile.write(line+'\n')
     3272        if 'background PWDR' in DebyePeaks:
     3273            try:
     3274                pFile.write(' Fixed background file: %s; mult: %.3f  Refine? %s\n'%(DebyePeaks['background PWDR'][0],
     3275                    DebyePeaks['background PWDR'][1],DebyePeaks['background PWDR'][2]))
     3276            except IndexError:  #old version without refine flag
     3277                pass
    32653278       
    32663279    def PrintInstParms(Inst):
     
    34143427                    if name in sigDict:
    34153428                        backSig[lenBack+3*DebyePeaks['nDebye']+4*i+j] = sigDict[name]
     3429        if pfx+'BF mult' in sigDict:
     3430            DebyePeaks['background PWDR'][1] = parmDict[pfx+'BF mult']
     3431            backSig.append(sigDict[pfx+'BF mult'])
     3432               
    34163433        return backSig
    34173434       
     
    35003517                        ptstr += 12*' '
    35013518                pFile.write(ptstr+'\n')
     3519        if 'background PWDR' in DebyePeaks and DebyePeaks['background PWDR'][2]:
     3520            pFile.write(' Fixed background scale: %.3f(%d)\n'%(DebyePeaks['background PWDR'][1],int(1000*backSig[-1])))
    35023521        sumBk = np.array(Histogram['sumBk'])
    35033522        pFile.write(' Background sums: empirical %.3g, Debye %.3g, peaks %.3g, Total %.3g\n'%
  • trunk/GSASIIstrMath.py

    r4665 r4671  
    31903190    hfx = ':%d:'%(hId)
    31913191    bakType = calcControls[hfx+'bakType']
    3192     fixedBkg = {i:Histogram['Background'][1][i] for i in Histogram['Background'][1] if i.startswith("_")}
    3193     yb,Histogram['sumBk'] = G2pwd.getBackground(hfx,parmDict,bakType,calcControls[hfx+'histType'],x,fixedBkg)
     3192    fixback = Histogram['Background'][1].get('fixback',None)
     3193    yb,Histogram['sumBk'] = G2pwd.getBackground(hfx,parmDict,bakType,calcControls[hfx+'histType'],x,fixback)
    31943194    yc = np.zeros_like(yb)
    31953195    cw = np.diff(ma.getdata(x))
     
    34413441    bakType = calcControls[hfx+'bakType']
    34423442    dMdv = np.zeros(shape=(len(varylist),len(x)))
    3443     dMdb,dMddb,dMdpk = G2pwd.getBackgroundDerv(hfx,parmDict,bakType,calcControls[hfx+'histType'],x)
     3443    fixback = Histogram['Background'][1].get('fixback',None)
     3444    dMdb,dMddb,dMdpk,dMdfb = G2pwd.getBackgroundDerv(hfx,parmDict,bakType,calcControls[hfx+'histType'],x,fixback)
    34443445    if prc == 0 and hfx+'Back;0' in varylist: # for now assume that Back;x vars to not appear in constraints
    34453446        bBpos = varylist.index(hfx+'Back;0')
     
    34603461                ip = names.index(parm)
    34613462                dMdv[varylist.index(name)] += dMdpk[4*Id+ip]
     3463    if hfx+'BF mult' in varylist:
     3464        dMdv[varylist.index(hfx+'BF mult')] += dMdfb
    34623465    cw = np.diff(ma.getdata(x))
    34633466    cw = np.append(cw,cw[-1])
  • trunk/imports/G2phase_GPX.py

    r4410 r4671  
    8181        self.Phase['Pawley ref'] = []       # & any Pawley refl.
    8282        self.Phase['RBModels'] = {}
     83        self.Phase['Drawing'] = {}
    8384        if 'MCSA' in self.Phase:
    8485            del self.Phase['MCSA']
Note: See TracChangeset for help on using the changeset viewer.