Changeset 4203


Ignore:
Timestamp:
Dec 15, 2019 1:52:48 PM (22 months ago)
Author:
toby
Message:

Add close and composition to G2scriptable; more doc updates

Location:
trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIElemGUI.py

    r3848 r4203  
    5959
    6060    def __init__(self, parent,oneOnly=False,ifNone=False,ifMag=False,multiple=False):
    61         'Needs a doc string'
    6261        self.oneOnly = oneOnly
    6362        self.ifNone = ifNone
  • trunk/GSASIIscriptable.py

    r4201 r4203  
    3131==================================================
    3232This section of the documentation provides an overview to API, with full documentation
    33 in the :ref:`API` section. The typical API use will be with a Python script, such as this:
    34 
    35 .. code-block::  python
    36 
    37     from __future__ import division, print_function
    38     import os,sys
    39     sys.path.insert(0,'/Users/toby/software/G2/GSASII') # needed to "find" GSAS-II modules
    40     import GSASIIscriptable as G2sc
    41     datadir = "/Users/Scratch/"
    42     gpx = G2sc.G2Project(os.path.join(datadir,'test2.gpx'))
    43     gpx.histogram(0).add_back_peak(4.5,30000,5000,0)
    44     pardict = {'set': {'Sample Parameters': ['Absorption', 'Contrast', 'DisplaceX'],
    45                        'Background': {'type': 'chebyschev-1', 'refine': True,
    46                                       'peaks':[[0,True]]}}}
    47     gpx.set_refinement(pardict)
    48 
    49 Most functionality is provided via the objects and methods described in this section.
     33in the :ref:`API` section. The typical API use will be with a Python script, such as
     34what is found in :ref:`CodeExamples`. Most functionality is provided via the objects and methods
     35summarized below.
     36
     37---------------------
     38Overview of Classes
     39---------------------
     40
     41===============================    ===============================================================================================================
     42class                              Encapsulates
     43===============================    ===============================================================================================================
     44:class:`G2Project`                  a GSAS-II project file, provides references to objects below,
     45                                    each corresponding to a tree item
     46                                    (excepting :class:`G2AtomRecord`)
     47:class:`G2Phase`                    a phase
     48:class:`G2PwdrData`                 a powder histogram
     49:class:`G2Image`                    an image
     50:class:`G2PDF`                      a PDF histogram
     51:class:`G2SeqRefRes`                the sequential results table
     52:class:`G2AtomRecord`               an atom within a phase
     53===============================    ===============================================================================================================
    5054
    5155---------------------
     
    6266==================================================    ===============================================================================================================
    6367
    64 ---------------------
    65 :class:`G2Project`
    66 ---------------------
     68---------------------------------
     69Class :class:`G2Project`
     70---------------------------------
    6771
    6872  All GSASIIscriptable scripts will need to create a :class:`G2Project` object
     
    111115==================================================    ===============================================================================================================
    112116
    113 ---------------------
    114 :class:`G2Phase`
    115 ---------------------
     117---------------------------------
     118Class :class:`G2Phase`
     119---------------------------------
     120
    116121
    117122  Another common object in GSASIIscriptable scripts is :class:`G2Phase`, used to encapsulate each phase in a project, with commonly used methods:
     
    139144==================================================    ===============================================================================================================
    140145
    141 ---------------------
    142 :class:`G2PwdrData`
    143 ---------------------
     146---------------------------------
     147Class :class:`G2PwdrData`
     148---------------------------------
    144149
    145150  Another common object in GSASIIscriptable scripts is :class:`G2PwdrData`, which encapsulate each powder diffraction histogram in a project, with commonly used methods:
     
    168173==================================================    ===============================================================================================================
    169174
    170 ---------------------
    171 :class:`G2Image`
    172 ---------------------
     175---------------------------------
     176Class :class:`G2Image`
     177---------------------------------
    173178
    174179  When working with images, there will be a :class:`G2Image` object for each image (also see :meth:`G2Project.add_image`  and :meth:`G2Project.images`).
     
    192197
    193198
    194 ---------------------
    195 :class:`G2PDF`
    196 ---------------------
     199---------------------------------
     200Class :class:`G2PDF`
     201---------------------------------
    197202
    198203  To work with PDF entries, object :class:`G2PDF`, encapsulates a PDF entry with methods:
     
    210215==================================================    ===============================================================================================================
    211216
    212 ---------------------
    213 :class:`G2SeqRefRes`
    214 ---------------------
     217---------------------------------
     218Class :class:`G2SeqRefRes`
     219---------------------------------
    215220
    216221  To work with Sequential Refinement results, object :class:`G2SeqRefRes`, encapsulates the sequential refinement table with methods:
     
    227232==================================================    ===============================================================================================================
    228233
    229 ----------------------
    230 :class:`G2AtomRecord`
    231 ----------------------
     234---------------------------------
     235Class :class:`G2AtomRecord`
     236---------------------------------
    232237
    233238  When working with phases, :class:`G2AtomRecord` objects provide access to the contents of each atom in a phase. This provides access to "properties" that can be
     
    660665Note that the parameters must match the object type and method (phase vs. histogram vs. HAP).
    661666
     667.. _CodeExamples:
     668
    662669=================================
    663670Code Examples
     
    747754    gpx.histogram(0).Export('PbSO4data','.csv','hist') # data
    748755    gpx.histogram(0).Export('PbSO4refl','.csv','refl') # reflections
     756
     757----------------------
     758Simple Refinement
     759----------------------
     760
     761GSASIIscriptable can be used to setup and perform simple refinements.
     762This example reads in an existing project (.gpx) file, adds a background
     763peak, changes some refinement flags and performs a refinement.
     764
     765.. code-block::  python
     766
     767    from __future__ import division, print_function
     768    import os,sys
     769    sys.path.insert(0,'/Users/toby/software/G2/GSASII') # needed to "find" GSAS-II modules
     770    import GSASIIscriptable as G2sc
     771    datadir = "/Users/Scratch/"
     772    gpx = G2sc.G2Project(os.path.join(datadir,'test2.gpx'))
     773    gpx.histogram(0).add_back_peak(4.5,30000,5000,0)
     774    pardict = {'set': {'Sample Parameters': ['Absorption', 'Contrast', 'DisplaceX'],
     775                       'Background': {'type': 'chebyschev-1', 'refine': True,
     776                                      'peaks':[[0,True]]}}}
     777    gpx.set_refinement(pardict)
    749778
    750779----------------------
     
    9791008============================================================
    9801009
    981 The large number of classes and modules in this module are described below.
    982 A script will have one or more G2Project objects using :class:`G2Project` and then
     1010The classes and modules in this module are described below.
     1011A script will create one or more :class:`G2Project` objects by reading
     1012a GSAS-II project (.gpx) file or creating a new one and will then
    9831013perform actions such as adding a histogram (method :meth:`G2Project.add_powder_histogram`),
    9841014adding a phase (method :meth:`G2Project.add_phase`),
     
    9911021
    9921022#============================================================================
    993 # adding a new object type
     1023# Notes for adding a new object type
    9941024# 1) add a new object class (e.g. G2PDF)
    9951025# 2) add the wrapper into G2Project (e.g. _pdfs, pdf, pdfs)
     
    19932023        return self.histogram(histname)
    19942024
     2025    def clone_powder_histogram(self, histref, newname, Y, Yerr=None):
     2026        '''Creates a copy of a powder diffraction histogram with new Y values.
     2027        The X values are not changed. The number of Y values must match the
     2028        number of X values.         
     2029
     2030        :param histref: The histogram object, the name of the histogram (str), or ranId
     2031           or histogram index.
     2032        :param str newname: The name to be assigned to the new histogram
     2033        :param list Y: A set of intensity values
     2034        :param list Yerr: A set of uncertainties for the intensity values (may be None,
     2035           sets all weights to unity)
     2036        :returns: the new histogram object (type G2PwdrData)
     2037        '''
     2038        hist = self.histogram(histref)
     2039        for i in self.names:
     2040            if i[0] == hist.name:
     2041                subkeys = i[1:]
     2042                break
     2043        else:
     2044            raise Exception("error in self.names, hist not found")
     2045        orighist = hist.name
     2046        newhist = 'PWDR '+newname
     2047        if len(Y) != len(self[orighist]['data'][1][0]):
     2048            raise Exception("clone error: length of Y does not match number of X values ({})"
     2049                                .format(len(self[orighist]['data'][1][0])))           
     2050        if Yerr is not None and len(Yerr) != len(self[orighist]['data'][1][0]):
     2051            raise Exception("clone error: length of Yerr does not match number of X values ({})"
     2052                                .format(len(self[orighist]['data'][1][0])))
     2053       
     2054        self[newhist] = copy.deepcopy(self[orighist])
     2055        # intensities
     2056        yo = self[newhist]['data'][1][1] = ma.MaskedArray(Y,mask=self[orighist]['data'][1][1].mask)
     2057       
     2058        Ymin,Ymax = yo.min(),yo.max()
     2059        # set to zero: weights, calc, bkg, obs-calc
     2060        for i in [2,3,4,5]:
     2061            self[newhist]['data'][1][i] *= 0
     2062        # weights
     2063        if Yerr is not None:
     2064            self[newhist]['data'][1][2] += 1./np.array(Yerr)**2
     2065        else:
     2066            self[newhist]['data'][1][2] += 1            # set all weights to 1
     2067        self[newhist]['data'][0] = {'wtFactor': 1.0, 'Dummy': False,
     2068                  'ranId': ran.randint(0, sys.maxsize),
     2069                  'Offset': [0.0, 0.0], 'delOffset': 0.02*Ymax,
     2070                  'refOffset': -0.1*Ymax, 'refDelt': 0.1*Ymax,
     2071                  'Yminmax': [Ymin, Ymax]}
     2072        self[newhist]['Comments'].insert(0,'Cloned from '+orighist)
     2073        self[newhist]['Reflection Lists'] = {}
     2074        self[newhist]['Index Peak List'] = [[], []]
     2075        self[newhist]['Unit Cells List'] = []
     2076        self[newhist]['Peak List'] = {'peaks': [], 'sigDict': {}}
     2077        self.names.append([newhist]+subkeys)
     2078        self.update_ids()
     2079        return self.histogram(newhist)
     2080       
    19952081    def add_simulated_powder_histogram(self, histname, iparams, Tmin, Tmax, Tstep,
    19962082                                       wavelength=None, scale=None, phases=[]):
     
    32573343
    32583344    @property
     3345    def element(self):
     3346        '''Get the associated atom's element symbol
     3347        '''
     3348        import re
     3349        try:
     3350            return re.match('^([A-Z][a-z]?)',self.data[self.ct]).group(1)
     3351        except:
     3352            raise Exception("element parse error with type {}".
     3353                                format(self.data[self.ct]))
     3354
     3355    @property
    32593356    def refinement_flags(self):
    32603357        '''Get or set refinement flags for the associated atom
     
    32813378        '''
    32823379        return self.data[self.cx+3]
    3283 
     3380   
    32843381    @occupancy.setter
    32853382    def occupancy(self, val):
    32863383        self.data[self.cx+3] = float(val)
    32873384
     3385    @property
     3386    def mult(self):
     3387        '''Get the associated atom's multiplicity value
     3388        '''
     3389        return self.data[self.cs+1]
     3390   
    32883391    @property
    32893392    def ranId(self):
     
    40534156        """
    40544157        ptrs = self.data['General']['AtomPtrs']
    4055         output = []
    4056         atoms = self.data['Atoms']
    4057         for atom in atoms:
    4058             output.append(G2AtomRecord(atom, ptrs, self.proj))
    4059         return output
     4158        return [G2AtomRecord(atom, ptrs, self.proj) for atom in self.data['Atoms']]
    40604159
    40614160    def histograms(self):
     
    40634162        as they appear in the tree (see :meth:`G2Project.histograms`).
    40644163        '''
    4065         return [i.name for i in self.proj.histograms() if i.name in self.data.get('Histograms', {})]
    4066 
     4164        return [i.name for i in self.proj.histograms() if i.name in self.data.get('Histograms', {})]
     4165   
     4166    @property
     4167    def composition(self):
     4168        '''Returns a dict where keys are atom types and values are the number of
     4169        atoms of that type in cell (such as {'H': 2.0, 'O': 1.0})
     4170        '''
     4171        out = {}
     4172        for a in self.atoms():
     4173            typ = a.element
     4174            if typ in out:
     4175                out[typ] += a.mult*a.occupancy
     4176            else:
     4177                out[typ] = a.mult*a.occupancy
     4178        return out
     4179           
     4180   
    40674181    @property
    40684182    def ranId(self):
Note: See TracChangeset for help on using the changeset viewer.