source: trunk/GSASIIobj.py @ 963

Last change on this file since 963 was 963, checked in by toby, 8 years ago

more CIF work, more docs

  • Property svn:eol-style set to native
File size: 21.0 KB
Line 
1# TODO: change this to assemble the look-up tables of atoms, phases and hists from the tree
2# and then save/unsave those values in __init__ & __str__, etc.
3
4'''
5*GSASIIobj: Data objects*
6=========================
7
8This module defines and/or documents the data structures used in GSAS-II.
9
10
11Constraints Tree Item
12----------------------
13
14.. _Constraints_table:
15
16.. index::
17   single: Constraints object description
18   single: Data object descriptions; Constraints
19
20Constraints are stored in a dict, separated into groups.
21Note that parameter are named in the following pattern,
22p:h:<var>:n, where p is the phase number, h is the histogram number
23<var> is a variable name and n is the parameter number.
24If a parameter does not depend on a histogram or phase or is unnumbered, that
25number is omitted.
26Note that the contents of each dict item is a List where each element in the
27list is a :ref:`constraint definition objects <Constraint_definitions_table>`.
28
29The keys in the Constraints dict are:
30
31.. tabularcolumns:: |l|p{4.5in}|
32
33==========  ====================================================
34  key         explanation
35==========  ====================================================
36Hist        This specifies a list of constraints on
37            histogram-related parameters,
38            which will be of form :h:<var>:n.
39HAP         This specifies a list of constraints on parameters
40            that are defined for every histogram in each phase
41            and are of form p:h:<var>:n.           
42Phase       This specifies a list of constraints on phase
43            parameters,
44            which will be of form p::<var>:n.
45Global      This specifies a list of constraints on parameters
46            that are not tied to a histogram or phase and
47            are of form ::<var>:n
48==========  ====================================================
49
50.. _Constraint_definitions_table:
51
52.. index::
53   single: Constraint definition object description
54   single: Data object descriptions; Constraint Definition
55
56Each constraint is defined as a list using a series of terms of form
57
58::
59
60[[<mult1>, <var1>], [<mult2>, <var2>],..., <fixed val>, <vary flag>, <cons type>]
61
62Where the variable pair list item containing two values [<mult>, <var>],
63
64  * <mult> is a multiplier for the constraint (float)
65  * <var> is the name of the variable (str) (or to be implemented a :class:`VarName` object.)
66
67Note that the last three items in the list play a special role:
68
69 * <fixed val> is the fixed value for a constraint equation or is None
70 * <vary flag> is True, False or None and is intended to use to indicate if new variables
71   should be refined.
72 * <cons type> is one of four letters, 'e', 'c', 'h', 'f' that determines the type of constraint.
73
74    * 'e' defines a set of equivalent variables. Only the first variable is refined (if the
75      appropriate refine flag is set) and and all other equivalent variables in the list
76      are generated from that variable. The vary flag for those variables is ignored.
77    * 'c' defines a constraint equation of form, :math:`m_1 \\times var_1 + m_2 \\times var_2 + ... = c`
78    * 'h' defines a variable to hold (not vary). Any variable on this list is not varied, even if its refinement
79      flag is set. This is of particular value when needing to hold one or more variables in a set such as
80      the reciprocal metric tensor or anisotropic displacement parameter.
81    * 'f' defines a relationship to define a new variable according to relationship
82      :math:`newvar = m_1 \\times var_1 + m_2 \\times var_2 + ...`
83
84Covariance Tree Item
85--------------------
86
87.. _Covariance_table:
88
89.. index::
90   single: Covariance description
91   single: Data object descriptions; Covariance
92
93The Covariance tree item has results from the last least-squares run. They
94are stored in a dict with these keys:
95
96.. tabularcolumns:: |l|l|p{4in}|
97
98=============  ===============  ====================================================
99  key            sub-key        explanation
100=============  ===============  ====================================================
101newCellDict    \                dict with lattice parameters computed by
102                                :func:`GSASIIstrMath.GetNewCellParms` (dict)
103title          \                Name of gpx file(?) (str)
104variables      \                Values for all N refined variables
105                                (list of float values, length N,
106                                ordered to match varyList)
107sig            \                Uncertainty values for all N refined variables
108                                (list of float values, length N,
109                                ordered to match varyList)
110varyList       \                List of directly refined variables
111                                (list of str values, length N)
112newAtomDict    \                dict with atom position values computed in
113                                :func:`GSASIIstrMath.ApplyXYZshifts` (dict)
114Rvals          \                R-factors, GOF, Marquardt value for last
115                                refinement cycle (dict)
116\              Nobs             Number of observed data points (int)
117\              Rwp              overall weighted profile R-factor (%, float)
118\              chisq            sum[w*(Iobs-Icalc)**2] for all data
119                                note this is not the reduced chi squared (float)
120\              lamMax           Marquardt value applied to Hessian diagonal
121                                (float)
122\              GOF              The goodness-of-fit, aka square root of
123                                the reduced chi squared. (float)
124covMatrix      \                The (NxN) covVariance matrix (np.array)
125=============  ===============  ====================================================
126
127Phase Tree Item
128----------------
129
130.. _Phase_table:
131
132.. index::
133   single: Phase object description
134   single: Data object descriptions; Phase
135
136Phase information is stored in the GSAS-II data tree as children of the
137Phases item in a dict with keys:
138
139.. tabularcolumns:: |l|l|p{4in}|
140
141==========  ===============  ====================================================
142  key         sub-key        explanation
143==========  ===============  ====================================================
144General         \            Overall information for the phase (dict)
145  \         AtomPtrs         list of four locations to use to pull info
146                             from the atom records (list)
147  \         F000X            x-ray F(000) intensity (float)
148  \         F000N            neutron F(000) intensity (float)
149  \         Mydir            directory of current .gpx file (str)
150  \         MCSA controls    ?
151  \         Cell             List with 7 items: cell refinement flag (bool)
152                             a, b, c, (Angstrom, float)
153                             alpha, beta & gamma (degrees, float)
154  \         Type             for now 'nuclear' (str)
155  \         Map              dict of map parameters
156  \         SH Texture       dict of spherical harmonic preferred orientation
157                             parameters
158  \         Isotope          dict of isotopes for each atom type
159  \         Isotopes         dict of scattering lengths for each isotope
160                             combination for each element in phase 
161  \         Name             phase name (str)
162  \         SGData           Space group details as a :ref:`space group (SGData) object <SGData_table>`
163                             as defined in :func:`GSASIIspc.SpcGroup`.
164  \         Pawley neg wt    Restraint value for negative Pawley intensities
165                             (float)
166  \         Flip             Charge flip controls dict?
167  \         Data plot type   ?
168  \         Mass             Mass of unit cell contents in g/mol
169  \         POhkl            March-Dollase preferred orientation direction
170  \         Z                ?
171  \         vdWRadii         ?
172  \         Color            Colors for atoms (list of (r,b,g) triplets)
173  \         AtomTypes        List of atom types
174  \         AtomMass         List of masses for atoms
175  \         doPawley         Flag for Pawley intensity extraction (bool)
176  \         NoAtoms          Number of atoms per unit cell of each type (dict)
177  \         Pawley dmin      maximum Q (as d-space) to use for Pawley
178                             extraction (float)
179  \         BondRadii        Radius for each atom used to compute
180                             interatomic distances (list of floats)
181  \         AngleRadii       Radius for each atom used to compute
182                             interatomic angles (list of floats)
183ranId           \            unique random number Id for phase (int)
184pId             \            Phase Id number for current project (int).
185Atoms           \            Atoms in phase as a list of lists. The outer list
186                             is for each atom, the inner list contains varying
187                             items depending on the type of phase, see
188                             the :ref:`Atom Records <Atoms_table>` description.
189                             (list of lists)
190Drawing         \            Display parameters (dict)
191\           ballScale        Size of spheres in ball-and-stick display (float)
192\           bondList         dict with bonds
193\           contourLevel     ? (float)
194\           showABC          Flag to show view point triplet (bool). True=show.
195\           viewDir          cartesian viewing direction (np.array with three
196                             elements)
197\           Zclip            clipping distance in A (float)
198\           backColor        background for plot as and R,G,B triplet
199                             (default = [0, 0, 0], black).
200                             (list with three atoms)
201\           selectedAtoms    List of selected atoms (list of int values)
202\           showRigidBodies  Flag to highlight rigid body placement
203\           sizeH            Size ratio for H atoms (float)
204\           bondRadius       Size of binds in A (float)
205\           atomPtrs         ? (list)
206\           viewPoint        list of lists. First item in list is [x,y,z]
207                             in fractional coordinates for the center of
208                             the plot. Second item ?.
209\           showHydrogen     Flag to control plotting of H atoms.
210\           unitCellBox      Flag to control display of the unit cell.
211\           ellipseProb      Probability limit for display of thermal
212                             ellipsoids in % (float).
213\           vdwScale         Multiplier of van der Waals radius for
214                             display of vdW spheres.
215\           Atoms            A list of lists with an entry for each atom
216                             that is plotted.
217\           Zstep            Step to de/increase Z-clip (float)
218\           Quaternion       Viewing quaternion (4 element np.array)
219\           radiusFactor     Distance ratio for searching for bonds. ? Bonds
220                             are located that are within r(Ra+Rb) and (Ra+Rb)/r
221                             where Ra and Rb are the atomic radii.
222\           oldxy            ? (list with two floats)
223\           cameraPos        Viewing position in A for plot (float)
224\           depthFog         ? (bool)
225RBModels        \            Rigid body assignments (note Rigid body definitions
226                             are stored in their own main top-level tree entry.)
227Pawley ref      \            Pawley reflections
228Histograms      \            A dict of dicts. The key for the outer dict is
229                             the histograms tied to this phase. The inner
230                             dict contains the combined phase/histogram
231                             parameters for items such as scale factors,
232                             size and strain parameters. (dict)
233MCSA            \            Monte-Carlo simulated annealing parameters
234==========  ===============  ====================================================
235
236Space Group Objects
237-------------------
238
239.. _SGData_table:
240
241.. index::
242   single: SGData description
243   single: Data object descriptions; SGData
244
245Space groups are interpreted by :func:`GSASIIspc.SpcGroup`
246and the information is placed in a SGdata object,
247which is a dict with these keys:
248
249.. tabularcolumns:: |l|p{4.5in}|
250
251==========  ====================================================
252  key         explanation
253==========  ====================================================
254SpGrp       space group symbol (str)
255Laue        one of the following 14 Laue classes:
256            -1, 2/m, mmm, 4/m, 4/mmm, 3R,
257            3mR, 3, 3m1, 31m, 6/m, 6/mmm, m3, m3m (str)
258SGInv       True if centrosymmetric, False if not (bool)
259SGLatt      Lattice centering type. Will be one of
260            P, A, B, C, I, F, R (str)
261SGUniq      unique axis if monoclinic. Will be
262            a, b, or c for monoclinic space groups.
263            Will be blank for non-monoclinic. (str)
264SGCen       Symmetry cell centering vectors. A (n,3) np.array
265            of centers. Will always have at least one row:
266            ``np.array([[0, 0, 0]])``
267SGOps       symmetry operations as a list of form
268            ``[[M1,T1], [M2,T2],...]``
269            where :math:`M_n` is a 3x3 np.array
270            and :math:`T_n` is a length 3 np.array.
271            Atom coordinates are transformed where the
272            Asymmetric unit coordinates [X is (x,y,z)]
273            are transformed using
274            :math:`X\prime = M_n*X+T_n`
275SGSys       symmetry unit cell: type one of
276            'triclinic', 'monoclinic', 'orthorhombic',
277            'tetragonal', 'rhombohedral', 'trigonal',
278            'hexagonal', 'cubic' (str)
279SGPolax     Axes for space group polarity. Will be one of
280            '', 'x', 'y', 'x y', 'z', 'x z', 'y z',
281            'xyz'. In the case where axes are arbitrary
282            '111' is used (P 1, and ?).
283==========  ====================================================
284
285Atom Records
286------------
287
288.. _Atoms_table:
289
290.. index::
291   single: Atoms record description
292   single: Data object descriptions; Atoms record
293
294
295If ``phasedict`` points to the phase information in the data tree, then
296atoms are contained in a list of atom records (list) in
297``phasedict['Atoms']``. Also needed to read atom information
298are four pointers, ``cx,ct,cs,cia = phasedict['General']['AtomPtrs']``,
299which define locations in the atom record, as shown below.
300
301.. tabularcolumns:: |l|p{4.5in}|
302
303==============   ====================================================
304location         explanation
305==============   ====================================================
306cx,cx+1,cx+2      the x,y and z coordinates
307cx+3              fractional occupancy (also cs-1)
308ct-1              atom label
309ct                atom type
310ct+1              refinement flags
311cs                site symmetry string
312cs+1              site multiplicity
313cia               ADP flag: Isotropic ('I') or Anisotropic ('A')
314cia+1             Uiso
315cia+2...cia+6     U11, U22, U33, U12, U13, U23
316==============   ====================================================
317
318
319*Classes and routines*
320----------------------
321
322'''
323
324def LoadHistogramIDs(histList,idList):
325    '''Save the Id values for a series of histograms'''
326    VarName.IDdict['hists'] = {}
327    for h,i in zip(histList,idList):
328        VarName.IDdict['hists'][i] = h
329
330def LoadPhaseIDs(self):
331    pass
332
333class VarName(object):
334    '''Defines a GSAS-II variable either using the phase/atom/histogram
335    unique Id numbers or using a character string that specifies
336    variables by phase/atom/histogram number (which can change).
337    Note that :func:`LoadID` should be used to (re)load the current Ids
338    before creating or later using the VarName object.
339
340    A :class:`VarName` object can be created with a single parameter:
341   
342    :param str varname: a single value can be used to create a :class:`VarName`
343      object. The string must be of form "p:h:var" or "p:h:var:a", where
344
345     * p is the phase number (which may be left blank);
346     * h is the histogram number (which may be left blank);
347     * a is the atom number (which may be left blank in which case the third colon is omitted).
348
349    Alternately, a :class:`VarName` object can be created with exactly four positional parameters:
350
351    :param int phasenum: The number for the phase
352    :param int histnum: The number for the histogram
353    :param str varname: a single value can be used to create a :class:`VarName`
354    :param int atomnum: The number for the atom
355   
356    '''
357    IDdict = {}
358    IDdict['phases'] = {}
359    IDdict['hists'] = {}
360    IDdict['atoms'] = {}
361    # This dictionary lists descriptions for GSAS-II variables.
362    # Note that keys may contain regular expressions, where '[xyz]'
363    # matches 'x' 'y' or 'z' (equivalently '[x-z]' describes this as range of values).
364    # '.*' matches any string
365    VarDesc = {
366        # Phase vars (p::<var>)
367        'A[0-5]' : 'Reciprocal metric tensor component',
368        'Vol' : 'Unit cell volume????',
369        # Atom vars (p::<var>:a)
370        'dA[xyz]' : 'change to atomic position',
371        'AUiso':'Atomic isotropic displacement parameter',
372        'AU[123][123]':'Atomic anisotropic displacement parameter',
373        'AFrac': 'Atomic occupancy parameter',
374        # Hist & Phase (HAP) vars (p:h:<var>)
375        'Bab[AU]': 'Babinet solvent scattering coef.',
376        'D[123][123]' : 'Anisotropic strain coef.',
377        'Extinction' : 'Extinction coef.',
378        'MD' : 'March-Dollase coef.',
379        'Mustrain;.*' : 'Microstrain coef.',
380        'Scale' : 'Phase scale factor',
381        'Size;.*' : 'Crystallite size value',
382        'eA' : '?',
383        #Histogram vars (:h:<var>)
384        'Absorption' : 'Absorption coef.',
385        'Displace[XY]' : 'Debye-Scherrer sample displacement',
386        'Lam' : 'Wavelength',
387        'Polariz' : 'Polarization correction',
388        'SH/L' : 'FCJ peak asymmetry correction',
389        'Scale' : 'Histogram scale factor',
390        '[UVW]' : 'Gaussian instrument broadening',
391        '[XY]' : 'Cauchy instrument broadening',
392        'Zero' : 'Debye-Scherrer zero correction',
393        'nDebye' : 'Debye model background corr. terms',
394        'nPeaks' : 'Fixed peak  background corr. terms',
395        # Global vars (::<var>)
396        }
397    def __init__(self,*args):
398        self.phase = None
399        self.histogram = None
400        self.name = ''
401        self.atom = None
402        if len(args) == 1:
403            lst = args[0].split(':')
404            raise Exception, "Need to look up IDs"
405            self.phase = lst[0]
406            self.histogram = lst[1]
407            self.name = lst[2]
408            if len(lst) > 3:
409                self.atom = lst[3]
410        elif len(args) == 4:
411            self.phase = args[0]
412            self.histogram = args[1]
413            self.name = args[2]
414            self.atom = args[3]
415        else:
416            raise Exception,"Incorrectly called GSAS-II parameter name"
417
418    def __str__(self):
419        return self.name()
420
421    def name(self):
422        '''Formats the GSAS-II variable name as a "traditional" string (p:h:<var>:a)
423
424        :returns: the variable name as a str
425        '''
426        def _fmt(val):
427            if val is None:
428                return ""
429            return str(val)
430        return _fmt(self.phase) + ":" + _fmt(self.histogram) + _fmt(self.name) + _fmt(self.atom)
431
432    def __repr__(self):
433        '''Return the detailed contents of the object
434        '''
435        s = ""
436        if self.phase:
437            s += "Phase: " + str(self.phase) + "; "
438
439        if self.histogram:
440            s += "Histogram: " + str(self.histogram) + "; "
441           
442        if self.name:
443            s += "Variable name: " + str(self.name) + "; "
444
445        if self.atom:
446            s += "Atom number: " + str(self.atom) + "; "
447
448        return s+"("+self.name()+")"
449
450    def getDescr(self):
451        '''Return a short description for a GSAS-II variable
452
453        :returns: a short description or 'no definition' if not found
454        '''
455        # iterating over uncompiled regular expressions is not terribly fast,
456        # but this routine should not need to be all that speedy
457        for key in self.VarDesc:
458            if re.match(key, self.name):
459                return self.VarDesc[key]
460        return 'no definition'
461
462    def getDescr(self):
463        '''Return a short description for a GSAS-II variable
464
465        :returns: a short description or 'no definition' if not found
466        '''
467        # iterating over uncompiled regular expressions is not terribly fast,
468        # but this routine should not need to be all that speedy
469        for key in self.VarDesc:
470            if re.match(key, self.name):
471                return self.VarDesc[key]
472        return 'no definition'
473
474    def fullDescr(self):
475        '''Return a longer description for a GSAS-II variable
476
477        :returns: a short description or 'no definition' if not found
478        '''
479        # iterating over uncompiled regular expressions is not terribly fast,
480        # but this routine should not need to be all that speedy
481        str = self.name()
482       
483        for key in self.VarDesc:
484            if re.match(key, self.name):
485                return self.VarDesc[key]
486        return 'no definition'
487
488
489    def _show(self):
490        'For testing, shows the current lookup table'
491        print 'phases', self.IDdict['phases']
492        print 'hists', self.IDdict['hists']
493        print 'atomDict', self.IDdict['atoms']
494
Note: See TracBrowser for help on using the repository browser.