source: trunk/GSASIIobj.py @ 946

Last change on this file since 946 was 946, checked in by toby, 9 years ago

update self-docs, start work on constraints object

  • Property svn:eol-style set to native
File size: 19.9 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)
146  \         F000X            x-ray F(000) intensity (float)
147  \         F000N            neutron F(000) intensity (float)
148  \         Mydir            directory of current .gpx file (str)
149  \         MCSA controls    ?
150  \         Cell             List with 7 items: cell refinement flag (bool)
151                             a, b, c, (Angstrom, float)
152                             alpha, beta & gamma (degrees, float)
153  \         Type             for now 'nuclear' (str)
154  \         Map              dict of map parameters
155  \         SH Texture       dict of spherical harmonic preferred orientation
156                             parameters
157  \         Isotope          dict of isotopes for each atom type
158  \         Isotopes         dict of scattering lengths for each isotope
159                             combination for each element in phase 
160  \         Name             phase name (str)
161  \         SGData           Space group details,
162                             as defined in :mod:`GSASIIspc` as  :ref:`SGData definition <SGData_table>`
163  \         Pawley neg wt    Restraint value for negative Pawley intensities
164                             (float)
165  \         Flip             Charge flip controls dict?
166  \         Data plot type   ?
167  \         Mass             Mass of unit cell contents in g/mol
168  \         POhkl            March-Dollase preferred orientation direction
169  \         Z                ?
170  \         vdWRadii         ?
171  \         Color            Colors for atoms (list of (r,b,g) triplets)
172  \         AtomTypes        List of atom types
173  \         AtomMass         List of masses for atoms
174  \         doPawley         Flag for Pawley intensity extraction (bool)
175  \         NoAtoms          Number of atoms per unit cell of each type (dict)
176  \         Pawley dmin      maximum Q (as d-space) to use for Pawley
177                             extraction (float)
178  \         BondRadii        Radius for each atom used to compute
179                             interatomic distances (list of floats)
180  \         AngleRadii       Radius for each atom used to compute
181                             interatomic angles (list of floats)
182ranId           \            unique random number Id for phase (int)
183pId             \            ? (int)
184Atoms           \            Atoms in phase as a list of lists. The outer list
185                             is for each atom, the inner list contains 18
186                             items:
187                             0) atom label, 1) the atom type,
188                             2) the refinement flags, 3-6) x, y, z, frac
189                             7) site symmetry, 8) site multiplicity,
190                             9) 'I' or 'A' for iso/anisotropic,
191                             10) Uiso, 10-16) Uij, 16) unique Id #.
192                             (list of lists)
193Drawing         \            Display parameters (dict)
194\           ballScale        Size of spheres in ball-and-stick display (float)
195\           bondList         dict with bonds
196\           contourLevel     ? (float)
197\           showABC          Flag to show view point triplet (bool). True=show.
198\           viewDir          cartesian viewing direction (np.array with three
199                             elements)
200\           Zclip            clipping distance in A (float)
201\           backColor        background for plot as and R,G,B triplet
202                             (default = [0, 0, 0], black).
203                             (list with three atoms)
204\           selectedAtoms    List of selected atoms (list of int values)
205\           showRigidBodies  Flag to highlight rigid body placement
206\           sizeH            Size ratio for H atoms (float)
207\           bondRadius       Size of binds in A (float)
208\           atomPtrs         ? (list)
209\           viewPoint        list of lists. First item in list is [x,y,z]
210                             in fractional coordinates for the center of
211                             the plot. Second item ?.
212\           showHydrogen     Flag to control plotting of H atoms.
213\           unitCellBox      Flag to control display of the unit cell.
214\           ellipseProb      Probability limit for display of thermal
215                             ellipsoids in % (float).
216\           vdwScale         Multiplier of van der Waals radius for
217                             display of vdW spheres.
218\           Atoms            A list of lists with an entry for each atom
219                             that is plotted.
220\           Zstep            Step to de/increase Z-clip (float)
221\           Quaternion       Viewing quaternion (4 element np.array)
222\           radiusFactor     Distance ratio for searching for bonds. ? Bonds
223                             are located that are within r(Ra+Rb) and (Ra+Rb)/r
224                             where Ra and Rb are the atomic radii.
225\           oldxy            ? (list with two floats)
226\           cameraPos        Viewing position in A for plot (float)
227\           depthFog         ? (bool)
228RBModels        \            Rigid body assignments (note Rigid body definitions
229                             are stored in their own main top-level tree entry.)
230Pawley ref      \            Pawley reflections
231Histograms      \            A dict of dicts. The key for the outer dict is
232                             the histograms tied to this phase. The inner
233                             dict contains the combined phase/histogram
234                             parameters for items such as scale factors,
235                             size and strain parameters. (dict)
236MCSA            \            Monte-Carlo simulated annealing parameters
237==========  ===============  ====================================================
238
239Space Group Objects
240-------------------
241
242.. _SGData_table:
243
244.. index::
245   single: SGData description
246   single: Data object descriptions; SGData
247
248Space groups are interpreted by :func:`GSASIIspc.SpcGroup`
249and the information is placed in a SGdata object,
250which is a dict with these keys:
251
252.. tabularcolumns:: |l|p{4.5in}|
253
254==========  ====================================================
255  key         explanation
256==========  ====================================================
257SpGrp       space group symbol (str)
258Laue        one of the following 14 Laue classes:
259            -1, 2/m, mmm, 4/m, 4/mmm, 3R,
260            3mR, 3, 3m1, 31m, 6/m, 6/mmm, m3, m3m (str)
261SGInv       True if centrosymmetric, False if not (bool)
262SGLatt      Lattice centering type. Will be one of
263            P, A, B, C, I, F, R (str)
264SGUniq      unique axis if monoclinic. Will be
265            a, b, or c for monoclinic space groups.
266            Will be blank for non-monoclinic. (str)
267SGCen       Symmetry cell centering vectors. A (n,3) np.array
268            of centers. Will always have at least one row:
269            ``np.array([[0, 0, 0]])``
270SGOps       symmetry operations as a list in form
271            [[M1,T1],[M2,T2,...] where Mn is a 3x3 np.array
272            and T is a length 3 np.array.
273            Atom coordinates are transformed where the
274            Asymmetric unit coordinates [X=(x,y,z)] are
275            transformed using ``M*X+T ==> X'``
276SGSys       symmetry unit cell: type one of
277            'triclinic', 'monoclinic', 'orthorhombic',
278            'tetragonal', 'rhombohedral', 'trigonal',
279            'hexagonal', 'cubic' (str)
280SGPolax     Axes for space group polarity. Will be one of
281            '', 'x', 'y', 'x y', 'z', 'x z', 'y z',
282            'xyz'. In the case where axes are arbitrary
283            '111' is used (P 1, and ?).
284==========  ====================================================
285
286'''
287
288def LoadHistogramIDs(histList,idList):
289    '''Save the Id values for a series of histograms'''
290    VarName.IDdict['hists'] = {}
291    for h,i in zip(histList,idList):
292        VarName.IDdict['hists'][i] = h
293
294def LoadPhaseIDs(self):
295    pass
296
297class VarName(object):
298    '''Defines a GSAS-II variable either using the phase/atom/histogram
299    unique Id numbers or using a character string that specifies
300    variables by phase/atom/histogram number (which can change).
301    Note that :func:`LoadID` should be used to (re)load the current Ids
302    before creating or later using the VarName object.
303
304    A :class:`VarName` object can be created with a single parameter:
305   
306    :param str varname: a single value can be used to create a :class:`VarName`
307      object. The string must be of form "p:h:var" or "p:h:var:a", where
308
309     * p is the phase number (which may be left blank);
310     * h is the histogram number (which may be left blank);
311     * a is the atom number (which may be left blank in which case the third colon is omitted).
312
313    Alternately, a :class:`VarName` object can be created with exactly four positional parameters:
314
315    :param int phasenum: The number for the phase
316    :param int histnum: The number for the histogram
317    :param str varname: a single value can be used to create a :class:`VarName`
318    :param int atomnum: The number for the atom
319   
320    '''
321    IDdict = {}
322    IDdict['phases'] = {}
323    IDdict['hists'] = {}
324    IDdict['atoms'] = {}
325    # This dictionary lists descriptions for GSAS-II variables.
326    # Note that keys may contain regular expressions, where '[xyz]'
327    # matches 'x' 'y' or 'z' (equivalently '[x-z]' describes this as range of values).
328    # '.*' matches any string
329    VarDesc = {
330        # Phase vars (p::<var>)
331        'A[0-5]' : 'Reciprocal metric tensor component',
332        'Vol' : 'Unit cell volume????',
333        # Atom vars (p::<var>:a)
334        'dA[xyz]' : 'change to atomic position',
335        'AUiso':'Atomic isotropic displacement parameter',
336        'AU[123][123]':'Atomic anisotropic displacement parameter',
337        'AFrac': 'Atomic occupancy parameter',
338        # Hist & Phase (HAP) vars (p:h:<var>)
339        'Bab[AU]': 'Babinet solvent scattering coef.',
340        'D[123][123]' : 'Anisotropic strain coef.',
341        'Extinction' : 'Extinction coef.',
342        'MD' : 'March-Dollase coef.',
343        'Mustrain;.*' : 'Microstrain coef.',
344        'Scale' : 'Phase scale factor',
345        'Size;.*' : 'Crystallite size value',
346        'eA' : '?',
347        #Histogram vars (:h:<var>)
348        'Absorption' : 'Absorption coef.',
349        'Displace[XY]' : 'Debye-Scherrer sample displacement',
350        'Lam' : 'Wavelength',
351        'Polariz' : 'Polarization correction',
352        'SH/L' : 'FCJ peak asymmetry correction',
353        'Scale' : 'Histogram scale factor',
354        '[UVW]' : 'Gaussian instrument broadening',
355        '[XY]' : 'Cauchy instrument broadening',
356        'Zero' : 'Debye-Scherrer zero correction',
357        'nDebye' : 'Debye model background corr. terms',
358        'nPeaks' : 'Fixed peak  background corr. terms',
359        # Global vars (::<var>)
360        }
361    def __init__(self,*args):
362        self.phase = None
363        self.histogram = None
364        self.name = ''
365        self.atom = None
366        if len(args) == 1:
367            lst = args[0].split(':')
368            raise Exception, "Need to look up IDs"
369            self.phase = lst[0]
370            self.histogram = lst[1]
371            self.name = lst[2]
372            if len(lst) > 3:
373                self.atom = lst[3]
374        elif len(args) == 4:
375            self.phase = args[0]
376            self.histogram = args[1]
377            self.name = args[2]
378            self.atom = args[3]
379        else:
380            raise Exception,"Incorrectly called GSAS-II parameter name"
381
382    def __str__(self):
383        return self.name()
384
385    def name(self):
386        '''Formats the GSAS-II variable name as a "traditional" string (p:h:<var>:a)
387
388        :returns: the variable name as a str
389        '''
390        def _fmt(val):
391            if val is None:
392                return ""
393            return str(val)
394        return _fmt(self.phase) + ":" + _fmt(self.histogram) + _fmt(self.name) + _fmt(self.atom)
395
396    def __repr__(self):
397        '''Return the detailed contents of the object
398        '''
399        s = ""
400        if self.phase:
401            s += "Phase: " + str(self.phase) + "; "
402
403        if self.histogram:
404            s += "Histogram: " + str(self.histogram) + "; "
405           
406        if self.name:
407            s += "Variable name: " + str(self.name) + "; "
408
409        if self.atom:
410            s += "Atom number: " + str(self.atom) + "; "
411
412        return s+"("+self.name()+")"
413
414    def getDescr(self):
415        '''Return a short description for a GSAS-II variable
416
417        :returns: a short description or 'no definition' if not found
418        '''
419        # iterating over uncompiled regular expressions is not terribly fast,
420        # but this routine should not need to be all that speedy
421        for key in self.VarDesc:
422            if re.match(key, self.name):
423                return self.VarDesc[key]
424        return 'no definition'
425
426    def getDescr(self):
427        '''Return a short description for a GSAS-II variable
428
429        :returns: a short description or 'no definition' if not found
430        '''
431        # iterating over uncompiled regular expressions is not terribly fast,
432        # but this routine should not need to be all that speedy
433        for key in self.VarDesc:
434            if re.match(key, self.name):
435                return self.VarDesc[key]
436        return 'no definition'
437
438    def fullDescr(self):
439        '''Return a longer description for a GSAS-II variable
440
441        :returns: a short description or 'no definition' if not found
442        '''
443        # iterating over uncompiled regular expressions is not terribly fast,
444        # but this routine should not need to be all that speedy
445        str = self.name()
446       
447        for key in self.VarDesc:
448            if re.match(key, self.name):
449                return self.VarDesc[key]
450        return 'no definition'
451
452
453    def _show(self):
454        'For testing, shows the current lookup table'
455        print 'phases', self.IDdict['phases']
456        print 'hists', self.IDdict['hists']
457        print 'atomDict', self.IDdict['atoms']
458
Note: See TracBrowser for help on using the repository browser.