Changeset 4003


Ignore:
Timestamp:
May 29, 2019 6:22:27 PM (5 years ago)
Author:
toby
Message:

fix subtle bug in plotCovar where cursor showed only initial vals; add general parameter retrieval routines

Location:
trunk
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIdataGUI.py

    r4001 r4003  
    61156115           
    61166116    def PlotSelectedColRow(calltyp=''):
    6117         '''Called to plot a selected column or row. This is called after the event is processed
    6118         so that the column or row gets selected.
    6119         Single click on row: plots histogram
    6120         Double click on row: plots V-C matrix
    6121         Single or double click on column: plots values in column
     6117        '''Called to plot a selected column or row by clicking or
     6118        double-clicking on a row or column label. N.B. This is called
     6119        after the event is processed so that the column or row has been
     6120        selected.
     6121
     6122        :param str calltyp: ='single'/'double', specifies if this was
     6123          a single- or double-click, where a single click on row
     6124          plots histogram; Double click on row plots V-C matrix;
     6125          Single or double click on column: plots values in column
    61226126        '''
    61236127        cols = G2frame.dataDisplay.GetSelectedCols()
     
    61546158        key = event.GetKeyCode()
    61556159        rows = G2frame.dataDisplay.GetSelectedRows()
    6156         print(key,rows)
     6160        #print(key,rows)
    61576161        event.Skip()
    61586162        wx.CallAfter(PlotSelectedColRow,'single')
  • trunk/GSASIIplot.py

    r3999 r4003  
    60586058           
    60596059def PlotCovariance(G2frame,Data):
    6060     'needs a doc string'
    6061     if not Data:
    6062         print ('No covariance matrix available')
    6063         return
    6064     varyList = Data['varyList']
    6065     values = Data['variables']
    6066     covMatrix = Data['covMatrix']
    6067     sig = np.sqrt(np.diag(covMatrix))
    6068     xvar = np.outer(sig,np.ones_like(sig))
    6069     covArray = np.divide(np.divide(covMatrix,xvar),xvar.T)
    6070     title = G2obj.StripUnicode(' for\n'+Data['title'],'') # matplotlib 1.x does not like unicode
    6071     newAtomDict = Data.get('newAtomDict',{})
    6072     G2frame.G2plotNB.status.DestroyChildren() #get rid of special stuff on status bar
    6073 
     6060    '''Plots the covariance matrix. Also shows values for parameters
     6061    and their standard uncertainties (esd's) or the correlation between
     6062    variables.
     6063    '''
    60746064    def OnPlotKeyPress(event):
    60756065        if event.key == 's':
     
    60906080            covFile.write('*' + 126*' ' + '*\n')
    60916081            covFile.write(128*'*' + '\n\n\n\n')
    6092             llen = len(varyList)
     6082            llen = len(Page.varyList)
    60936083            for start in range(0, llen, 8):  # split matrix into batches of 7 columns
    60946084                if llen >= start + 8:
     
    60986088                covFile.write(12*' ' + '\t')
    60996089                for idx in range(start, stop):
    6100                     covFile.write('{:^12}\t'.format(varyList[idx]))
     6090                    covFile.write('{:^12}\t'.format(Page.varyList[idx]))
    61016091                covFile.write('\n\n')
    61026092                for line in range(llen):
    6103                     covFile.write('{:>12}\t'.format(varyList[line]))
     6093                    covFile.write('{:>12}\t'.format(Page.varyList[line]))
    61046094                    for idx in range(start, stop):
    6105                         covFile.write('{: 12.6f}\t'.format(covArray[line][idx]))
     6095                        covFile.write('{: 12.6f}\t'.format(Page.covArray[line][idx]))
    61066096                    covFile.write('\n')
    61076097                covFile.write('\n\n\n')
    61086098            covFile.close()
    6109         PlotCovariance(G2frame,Data)
     6099        wx.CallAfter(PlotCovariance,G2frame,Data)
    61106100
    61116101    def OnMotion(event):
    61126102        if event.button:
    61136103            ytics = imgAx.get_yticks()
    6114             ytics = np.where(ytics<len(varyList),ytics,-1)
    6115             ylabs = [np.where(0<=i ,varyList[int(i)],' ') for i in ytics]
     6104            ytics = np.where(ytics<len(Page.varyList),ytics,-1)
     6105            ylabs = [np.where(0<=i ,Page.varyList[int(i)],' ') for i in ytics]
    61166106            imgAx.set_yticklabels(ylabs)           
    61176107        if event.xdata and event.ydata:                 #avoid out of frame errors
    61186108            xpos = int(event.xdata+.5)
    61196109            ypos = int(event.ydata+.5)
    6120             if -1 < xpos < len(varyList) and -1 < ypos < len(varyList):
     6110            if -1 < xpos < len(Page.varyList) and -1 < ypos < len(Page.varyList):
    61216111                if xpos == ypos:
    6122                     value = values[xpos]
    6123                     name = varyList[xpos]
    6124                     if varyList[xpos] in newAtomDict:
    6125                         name,value = newAtomDict[name]                       
    6126                     msg = '%s value = %.4g, esd = %.4g'%(name,value,sig[xpos])
     6112                    value = Page.values[xpos]
     6113                    name = Page.varyList[xpos]
     6114                    if Page.varyList[xpos] in Page.newAtomDict:
     6115                        name,value = Page.newAtomDict[name]                       
     6116                    msg = '%s value = %.4g, esd = %.4g'%(name,value,Page.sig[xpos])
    61276117                else:
    6128                     msg = '%s - %s: %5.3f'%(varyList[xpos],varyList[ypos],covArray[xpos][ypos])
     6118                    msg = '%s - %s: %5.3f'%(Page.varyList[xpos],Page.varyList[ypos],Page.covArray[xpos][ypos])
    61296119                Page.SetToolTipString(msg)
    61306120                G2frame.G2plotNB.status.SetStatusText(msg,1)
    61316121               
     6122    #==== PlotCovariance(G2frame,Data) starts here =========================
     6123    if not Data:
     6124        print ('No covariance matrix available')
     6125        return
    61326126    new,plotNum,Page,Plot,lim = G2frame.G2plotNB.FindPlotTab('Covariance','mpl')
    61336127    if not new:
     
    61376131        Page.canvas.mpl_connect('motion_notify_event', OnMotion)
    61386132        Page.canvas.mpl_connect('key_press_event', OnPlotKeyPress)
     6133    Page.varyList = Data['varyList']
     6134    Page.values = Data['variables']
     6135    covMatrix = Data['covMatrix']
     6136    Page.sig = np.sqrt(np.diag(covMatrix))
     6137    xvar = np.outer(Page.sig,np.ones_like(Page.sig))
     6138    Page.covArray = np.divide(np.divide(covMatrix,xvar),xvar.T)
     6139    title = G2obj.StripUnicode(' for\n'+Data['title'],'') # matplotlib 1.x does not like unicode
     6140    Page.newAtomDict = Data.get('newAtomDict',{})
     6141    G2frame.G2plotNB.status.DestroyChildren() #get rid of special stuff on status bar
    61396142    Page.Choice = ['s: to change colors','p: to save covariance as text file']
    61406143    Page.keyPress = OnPlotKeyPress
     
    61436146    G2frame.G2plotNB.status.SetStatusWidths([150,-1])   #need to reset field widths here   
    61446147    acolor = mpl.cm.get_cmap(G2frame.VcovColor)
    6145     Img = Plot.imshow(covArray,aspect='equal',cmap=acolor,interpolation='nearest',origin='lower',
     6148    Img = Plot.imshow(Page.covArray,aspect='equal',cmap=acolor,interpolation='nearest',origin='lower',
    61466149        vmin=-1.,vmax=1.)
    61476150    imgAx = Img.axes
    61486151    ytics = imgAx.get_yticks()
    6149     ylabs = [varyList[int(i)] for i in ytics[:-1]]
     6152    ylabs = [Page.varyList[int(i)] for i in ytics[:-1]]
    61506153    imgAx.set_yticklabels(ylabs)
    61516154    Page.figure.colorbar(Img)
  • trunk/GSASIIscriptable.py

    r4001 r4003  
    131131:meth:`G2Project.set_refinement`                      This is passed a single dict which is used to set parameters and flags.
    132132                                                      These actions can be performed also in :meth:`G2Project.do_refinements`.
     133:meth:`G2Project.get_Variable'                        Retrieves the value and esd for a parameter
     134:meth:`G2Project.get_Covariance'                      Retrieves values and covariance for a set of refined parameters
    133135==================================================    ===============================================================================================================
    134136
     
    240242:meth:`G2SeqRefRes.histograms`                         Provides a list of histograms used in the Sequential Refinement
    241243:meth:`G2SeqRefRes.get_cell_and_esd`                   Returns cell dimensions and standard uncertainies for a phase and histogram from the Sequential Refinement
     244:meth:`G2SeqRefRes.get_Variable'                       Retrieves the value and esd for a parameter from a particular histogram in the Sequential Refinement
     245:meth:`G2SeqRefRes.get_Covariance'                     Retrieves values and covariance for a set of refined parameters for a particular histogram
    242246==================================================    ===============================================================================================================
    243247
     
    26382642            for key in copysections:
    26392643                hist_out[key] = copy.deepcopy(hist_in[key])
     2644
     2645    def get_VaryList(self):
     2646        '''Returns a list of the refined variables in the
     2647        last refinement cycle
     2648
     2649        :returns: a list of variables or None if no refinement has been
     2650          performed.
     2651        '''
     2652        try:
     2653            return self['Covariance']['data']['varyList']
     2654        except:
     2655            return
     2656
     2657    def get_ParmList(self):
     2658        '''Returns a list of all the parameters defined in the
     2659        last refinement cycle
     2660
     2661        :returns: a list of parameters or None if no refinement has been
     2662          performed.
     2663        '''
     2664        try:
     2665            return list(self['Covariance']['data']['parmDict'].keys())
     2666        except:
     2667            return
    26402668       
     2669    def get_Variable(self,var):
     2670        '''Returns the value and standard uncertainty (esd) for a variable
     2671        parameters, as defined in the last refinement cycle
     2672
     2673        :param str var: a variable name of form '<p>:<h>:<name>', such as
     2674          ':0:Scale'
     2675        :returns: (value,esd) if the parameter is refined or
     2676          (value, None) if the variable is in a constraint or is not
     2677          refined or None if the parameter is not found.
     2678        '''
     2679        if var not in self['Covariance']['data']['parmDict']:
     2680            return None
     2681        val = self['Covariance']['data']['parmDict'][var]
     2682        try:
     2683            pos = self['Covariance']['data']['varyList'].index(var)
     2684            esd = np.sqrt(self['Covariance']['data']['covMatrix'][pos,pos])
     2685            return (val,esd)
     2686        except ValueError:
     2687            return (val,None)
     2688
     2689    def get_Covariance(self,varList):
     2690        '''Returns the values and covariance matrix for a series of variable
     2691        parameters. as defined in the last refinement cycle
     2692
     2693        :param tuple varList: a list of variable names of form '<p>:<h>:<name>'
     2694        :returns: (valueList,CovMatrix) where valueList contains the (n) values
     2695          in the same order as varList (also length n) and CovMatrix is a
     2696          (n x n) matrix. If any variable name is not found in the varyList
     2697          then None is returned.
     2698
     2699        Use this code, where sig provides standard uncertainties for
     2700        parameters and where covArray provides the correlation between
     2701        off-diagonal terms::
     2702
     2703            sig = np.sqrt(np.diag(covMatrix))
     2704            xvar = np.outer(sig,np.ones_like(sig))
     2705            covArray = np.divide(np.divide(covMatrix,xvar),xvar.T)
     2706
     2707        '''
     2708        missing = [i for i in varList if i not in self['Covariance']['data']['varyList']]
     2709        if missing:
     2710            print('Variable(s) {} were not found in the varyList'.format(missing))
     2711            return None
     2712        vals = [self['Covariance']['data']['parmDict'][i] for i in varList]
     2713        import GSASIImath as G2mth
     2714        cov = G2mth.getVCov(varList,
     2715                            self['Covariance']['data']['varyList'],
     2716                            self['Covariance']['data']['covMatrix'])
     2717        return (vals,cov)
     2718
    26412719class G2AtomRecord(G2ObjectWrapper):
    26422720    """Wrapper for an atom record. Has convenient accessors via @property.
    2643 
    26442721
    26452722    Available accessors: label, type, refinement_flags, coordinates,
     
    37983875        print('printed',[lbl[i] for i in list(uniq)+[6]])
    37993876
     3877    .. seealso::
     3878        :meth:`G2Project.seqref`
    38003879    '''
    38013880    def __init__(self, data, proj):
     
    39163995        return list(c)+[vol],cE,uniqCellIndx
    39173996   
     3997    def get_VaryList(self,hist):
     3998        '''Returns a list of the refined variables in the
     3999        last refinement cycle for the selected histogram
     4000
     4001        :param hist: Specify a histogram or using the histogram name (str)
     4002          or the index number (int) of the histogram in the sequential
     4003          refinement (not the project), numbered starting from 0.
     4004        :returns: a list of variables or None if no refinement has been
     4005          performed.
     4006        '''
     4007        try:
     4008            seqData,histData = self.RefData(hist)
     4009            return seqData['varyList']
     4010        except:
     4011            return
     4012
     4013    def get_ParmList(self,hist):
     4014        '''Returns a list of all the parameters defined in the
     4015        last refinement cycle for the selected histogram
     4016
     4017        :param hist: Specify a histogram or using the histogram name (str)
     4018          or the index number (int) of the histogram in the sequential
     4019          refinement (not the project), numbered starting from 0.
     4020        :returns: a list of parameters or None if no refinement has been
     4021          performed.
     4022        '''
     4023        try:
     4024            seqData,histData = self.RefData(hist)
     4025            return list(seqData['parmDict'].keys())
     4026        except:
     4027            return
     4028
     4029    def get_Variable(self,hist,var):
     4030        '''Returns the value and standard uncertainty (esd) for a variable
     4031        parameters, as defined for the selected histogram
     4032        in the last sequential refinement cycle
     4033
     4034        :param hist: Specify a histogram or using the histogram name (str)
     4035          or the index number (int) of the histogram in the sequential
     4036          refinement (not the project), numbered starting from 0.
     4037        :param str var: a variable name of form '<p>:<h>:<name>', such as
     4038          ':0:Scale'
     4039        :returns: (value,esd) if the parameter is refined or
     4040          (value, None) if the variable is in a constraint or is not
     4041          refined or None if the parameter is not found.
     4042        '''
     4043        try:
     4044            seqData,histData = self.RefData(hist)
     4045            val = seqData['parmDict'][var]
     4046        except:
     4047            return
     4048        try:
     4049            pos = seqData['varyList'].index(var)
     4050            esd = np.sqrt(seqData['covMatrix'][pos,pos])
     4051            return (val,esd)
     4052        except ValueError:
     4053            return (val,None)
     4054
     4055    def get_Covariance(self,hist,varList):
     4056        '''Returns the values and covariance matrix for a series of variable
     4057        parameters, as defined for the selected histogram
     4058        in the last sequential refinement cycle
     4059
     4060        :param hist: Specify a histogram or using the histogram name (str)
     4061          or the index number (int) of the histogram in the sequential
     4062          refinement (not the project), numbered starting from 0.
     4063        :param tuple varList: a list of variable names of form '<p>:<h>:<name>'
     4064        :returns: (valueList,CovMatrix) where valueList contains the (n) values
     4065          in the same order as varList (also length n) and CovMatrix is a
     4066          (n x n) matrix. If any variable name is not found in the varyList
     4067          then None is returned.
     4068
     4069        Use this code, where sig provides standard uncertainties for
     4070        parameters and where covArray provides the correlation between
     4071        off-diagonal terms::
     4072
     4073            sig = np.sqrt(np.diag(covMatrix))
     4074            xvar = np.outer(sig,np.ones_like(sig))
     4075            covArray = np.divide(np.divide(covMatrix,xvar),xvar.T)
     4076
     4077        '''
     4078        try:
     4079            seqData,histData = self.RefData(hist)
     4080        except:
     4081            print('Histogram {} not found in the sequential fit'.format(hist))
     4082            return
     4083        missing = [i for i in varList if i not in seqData['varyList']]
     4084        if missing:
     4085            print('Variable(s) {} were not found in the varyList'.format(missing))
     4086            return None
     4087        vals = [seqData['parmDict'][i] for i in varList]
     4088        import GSASIImath as G2mth
     4089        cov = G2mth.getVCov(varList,seqData['varyList'],seqData['covMatrix'])
     4090        return (vals,cov)
     4091   
    39184092    def RefData(self,hist):
    39194093        '''Provides access to the output from a particular histogram
     
    39564130       gpx.save('pdfcalc.gpx')
    39574131
     4132    .. seealso::
     4133        :meth:`G2Project.pdf`
     4134        :meth:`G2Project.pdfs`
    39584135    """
    39594136    def __init__(self, data, name, proj):
Note: See TracChangeset for help on using the changeset viewer.