source: trunk/GSASIIobj.py @ 1138

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

major constraints revision

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 53.1 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>`.
28The constraints in this form are converted in
29:func:`GSASIIstrIO.ProcessConstraints` to the form used in :mod:`GSASIImapvars`
30
31The keys in the Constraints dict are:
32
33.. tabularcolumns:: |l|p{4.5in}|
34
35==========  ====================================================
36  key         explanation
37==========  ====================================================
38Hist        This specifies a list of constraints on
39            histogram-related parameters,
40            which will be of form :h:<var>:n.
41HAP         This specifies a list of constraints on parameters
42            that are defined for every histogram in each phase
43            and are of form p:h:<var>:n.           
44Phase       This specifies a list of constraints on phase
45            parameters,
46            which will be of form p::<var>:n.
47Global      This specifies a list of constraints on parameters
48            that are not tied to a histogram or phase and
49            are of form ::<var>:n
50==========  ====================================================
51
52.. _Constraint_definitions_table:
53
54.. index::
55   single: Constraint definition object description
56   single: Data object descriptions; Constraint Definition
57
58Each constraint is defined as an item in a list. Each constraint is of form::
59
60[[<mult1>, <var1>], [<mult2>, <var2>],..., <fixedval>, <varyflag>, <constype>]
61
62Where the variable pair list item containing two values [<mult>, <var>], where:
63
64  * <mult> is a multiplier for the constraint (float)
65  * <var> a :class:`G2VarObj` object (previously a str variable name of form
66      'p:h:name[:at]')
67
68Note that the last three items in the list play a special role:
69
70 * <fixedval> is the fixed value for a `constant equation` (``constype=c``)
71   constraint or is None. For a `New variable` (``constype=f``) constraint,
72   a variable name can be specified as a str (but this is not yet used).
73 * <varyflag> is True or False for `New variable` (``constype=f``) constraints
74   or is None. This will be implemented in the future to indicate if these variables
75   should be refined.
76 * <constype> is one of four letters, 'e', 'c', 'h', 'f' that determines the type of constraint:
77
78    * 'e' defines a set of equivalent variables. Only the first variable is refined (if the
79      appropriate refine flag is set) and and all other equivalent variables in the list
80      are generated from that variable, using the appropriate multipliers.
81    * 'c' defines a constraint equation of form,
82      :math:`m_1 \\times var_1 + m_2 \\times var_2 + ... = c`
83    * 'h' defines a variable to hold (not vary). Any variable on this list is not varied,
84      even if its refinement flag is set. Only one [mult,var] pair is allowed in a hold
85      constraint and the mult value is ignored.
86      This is of particular value when needing to hold one or more variables where a
87      single flag controls a set of variables such as, coordinates,
88      the reciprocal metric tensor or anisotropic displacement parameter.
89    * 'f' defines a new variable (function) according to relationship
90      :math:`newvar = m_1 \\times var_1 + m_2 \\times var_2 + ...`
91
92Covariance Tree Item
93--------------------
94
95.. _Covariance_table:
96
97.. index::
98   single: Covariance description
99   single: Data object descriptions; Covariance
100
101The Covariance tree item has results from the last least-squares run. They
102are stored in a dict with these keys:
103
104.. tabularcolumns:: |l|l|p{4in}|
105
106=============  ===============  ====================================================
107  key            sub-key        explanation
108=============  ===============  ====================================================
109newCellDict    \                dict with lattice parameters computed by
110                                :func:`GSASIIstrMath.GetNewCellParms` (dict)
111title          \                Name of gpx file(?) (str)
112variables      \                Values for all N refined variables
113                                (list of float values, length N,
114                                ordered to match varyList)
115sig            \                Uncertainty values for all N refined variables
116                                (list of float values, length N,
117                                ordered to match varyList)
118varyList       \                List of directly refined variables
119                                (list of str values, length N)
120newAtomDict    \                dict with atom position values computed in
121                                :func:`GSASIIstrMath.ApplyXYZshifts` (dict)
122Rvals          \                R-factors, GOF, Marquardt value for last
123                                refinement cycle (dict)
124\              Nobs             Number of observed data points (int)
125\              Rwp              overall weighted profile R-factor (%, float)
126\              chisq            sum[w*(Iobs-Icalc)**2] for all data
127                                note this is not the reduced chi squared (float)
128\              lamMax           Marquardt value applied to Hessian diagonal
129                                (float)
130\              GOF              The goodness-of-fit, aka square root of
131                                the reduced chi squared. (float)
132covMatrix      \                The (NxN) covVariance matrix (np.array)
133=============  ===============  ====================================================
134
135Phase Tree Items
136----------------
137
138.. _Phase_table:
139
140.. index::
141   single: Phase object description
142   single: Data object descriptions; Phase
143
144Phase information is stored in the GSAS-II data tree as children of the
145Phases item in a dict with keys:
146
147.. tabularcolumns:: |l|l|p{4in}|
148
149==========  ===============  ====================================================
150  key         sub-key        explanation
151==========  ===============  ====================================================
152General         \            Overall information for the phase (dict)
153  \         AtomPtrs         list of four locations to use to pull info
154                             from the atom records (list)
155  \         F000X            x-ray F(000) intensity (float)
156  \         F000N            neutron F(000) intensity (float)
157  \         Mydir            directory of current .gpx file (str)
158  \         MCSA controls    Monte Carlo-Simulated Annealing controls (dict)
159  \         Cell             List with 8 items: cell refinement flag (bool)
160                             a, b, c, (Angstrom, float)
161                             alpha, beta & gamma (degrees, float)
162                             volume (A^3, float)
163  \         Type             'nuclear' or 'macromolecular' for now (str)
164  \         Map              dict of map parameters
165  \         SH Texture       dict of spherical harmonic preferred orientation
166                             parameters
167  \         Isotope          dict of isotopes for each atom type
168  \         Isotopes         dict of scattering lengths for each isotope
169                             combination for each element in phase 
170  \         Name             phase name (str)
171  \         SGData           Space group details as a :ref:`space group (SGData) object <SGData_table>`
172                             as defined in :func:`GSASIIspc.SpcGroup`.
173  \         Pawley neg wt    Restraint value for negative Pawley intensities
174                             (float)
175  \         Flip             dict of Charge flip controls
176  \         Data plot type   data plot type ('Mustrain', 'Size' or
177                             'Preferred orientation') for powder data (str)
178  \         Mass             Mass of unit cell contents in g/mol
179  \         POhkl            March-Dollase preferred orientation direction
180  \         Z                dict of atomic numbers for each atom type
181  \         vdWRadii         dict of van der Waals radii for each atom type
182  \         Color            Colors for atoms (list of (r,b,g) triplets)
183  \         AtomTypes        List of atom types
184  \         AtomMass         List of masses for atoms
185  \         doPawley         Flag for Pawley intensity extraction (bool)
186  \         NoAtoms          Number of atoms per unit cell of each type (dict)
187  \         Pawley dmin      maximum Q (as d-space) to use for Pawley
188                             extraction (float)
189  \         BondRadii        Default radius for each atom used to compute
190                             interatomic distances (list of floats)
191  \         AngleRadii       Default radius for each atom used to compute
192                             interatomic angles (list of floats)
193  \         DisAglCtls       Dict with distance/angle search controls,
194                             which has keys 'Name', 'AtomTypes',
195                             'BondRadii', 'AngleRadii' which are as above
196                             except are possibly edited. Also contains
197                             'Factors', which is a 2 element list with
198                             a multiplier for bond and angle search range
199                             [typically (0.85,0.85)].
200ranId           \            unique random number Id for phase (int)
201pId             \            Phase Id number for current project (int).
202Atoms           \            Atoms in phase as a list of lists. The outer list
203                             is for each atom, the inner list contains varying
204                             items depending on the type of phase, see
205                             the :ref:`Atom Records <Atoms_table>` description.
206                             (list of lists)
207Drawing         \            Display parameters (dict)
208\           ballScale        Size of spheres in ball-and-stick display (float)
209\           bondList         dict with bonds
210\           contourLevel     map contour level in e/A^3 (float)
211\           showABC          Flag to show view point triplet (bool). True=show.
212\           viewDir          cartesian viewing direction (np.array with three
213                             elements)
214\           Zclip            clipping distance in A (float)
215\           backColor        background for plot as and R,G,B triplet
216                             (default = [0, 0, 0], black).
217                             (list with three atoms)
218\           selectedAtoms    List of selected atoms (list of int values)
219\           showRigidBodies  Flag to highlight rigid body placement
220\           sizeH            Size ratio for H atoms (float)
221\           bondRadius       Size of binds in A (float)
222\           atomPtrs         positions of x, type, site sym, ADP flag in Draw Atoms (list)
223\           viewPoint        list of lists. First item in list is [x,y,z]
224                             in fractional coordinates for the center of
225                             the plot. Second item list of previous & current
226                             atom number viewed (may be [0,0])
227\           showHydrogen     Flag to control plotting of H atoms.
228\           unitCellBox      Flag to control display of the unit cell.
229\           ellipseProb      Probability limit for display of thermal
230                             ellipsoids in % (float).
231\           vdwScale         Multiplier of van der Waals radius for
232                             display of vdW spheres.
233\           Atoms            A list of lists with an entry for each atom
234                             that is plotted.
235\           Zstep            Step to de/increase Z-clip (float)
236\           Quaternion       Viewing quaternion (4 element np.array)
237\           radiusFactor     Distance ratio for searching for bonds. ? Bonds
238                             are located that are within r(Ra+Rb) and (Ra+Rb)/r
239                             where Ra and Rb are the atomic radii.
240\           oldxy            previous view point (list with two floats)
241\           cameraPos        Viewing position in A for plot (float)
242\           depthFog         True if use depthFog on plot - set currently as False (bool)
243RBModels        \            Rigid body assignments (note Rigid body definitions
244                             are stored in their own main top-level tree entry.)
245Pawley ref      \            Pawley reflections
246Histograms      \            A dict of dicts. The key for the outer dict is
247                             the histograms tied to this phase. The inner
248                             dict contains the combined phase/histogram
249                             parameters for items such as scale factors,
250                             size and strain parameters. (dict)
251MCSA            \            Monte-Carlo simulated annealing parameters (dict)
252\           
253==========  ===============  ====================================================
254
255Rigid Body Objects
256------------------
257
258.. _RBData_table:
259
260.. index::
261   single: Rigid Body Data description
262   single: Data object descriptions; Rigid Body Data
263   
264Rigid body descriptions are available for two types of rigid bodies: 'Vector'
265and 'Residue'. Vector rigid bodies are developed by a sequence of translations each
266with a refinable magnitude and Residue rigid bodies are described as Cartesian coordinates
267with defined refinable torsion angles.
268
269.. tabularcolumns:: |l|l|p{4in}|
270
271==========  ===============  ====================================================
272  key         sub-key        explanation
273==========  ===============  ====================================================
274Vector      RBId             vector rigid bodies (dict of dict)
275\           AtInfo           Drad, Color: atom drawing radius & color for each atom type (dict)
276\           RBname           Name assigned by user to rigid body (str)
277\           VectMag          vector magnitudes in A (list)
278\           rbXYZ            Cartesian coordinates for Vector rigid body (list of 3 float)
279\           rbRef            3 assigned reference atom nos. in rigid body for origin
280                             definition, use center of atoms flag (list of 3 int & 1 bool)
281\           VectRef          refinement flags for VectMag values (list of bool)
282\           rbTypes          Atom types for each atom in rigid body (list of str)
283\           rbVect           Cartesian vectors for each translation used to build rigid body (list of lists)
284\           useCount         Number of times rigid body is used in any structure (int)
285Residue     RBId             residue rigid bodies (dict of dict)
286\           AtInfo           Drad, Color: atom drawing radius & color for each atom type(dict)
287\           RBname           Name assigned by user to rigid body (str)
288\           rbXYZ            Cartesian coordinates for Residue rigid body (list of 3 float)
289\           rbTypes          Atom types for each atom in rigid body (list of str)
290\           atNames          Names of each atom in rigid body (e.g. C1,N2...) (list of str)
291\           rbRef            3 assigned reference atom nos. in rigid body for origin
292                             definition, use center of atoms flag (list of 3 int & 1 bool)
293\           rbSeq            Orig,Piv,angle,Riding (list): definition of internal rigid body
294                             torsion; origin atom (int), pivot atom (int), torsion angle (float),
295                             riding atoms (list of int)
296\           SelSeq           [int,int] used by SeqSizer to identify objects
297\           useCount         Number of times rigid body is used in any structure (int)
298RBIds           \            unique Ids generated upon creation of each rigid body (dict)
299\           Vector           Ids for each Vector rigid body (list)
300\           Residue          Ids for each Residue rigid body (list)
301==========  ===============  ====================================================
302
303Space Group Objects
304-------------------
305
306.. _SGData_table:
307
308.. index::
309   single: Space Group Data description
310   single: Data object descriptions; Space Group Data
311
312Space groups are interpreted by :func:`GSASIIspc.SpcGroup`
313and the information is placed in a SGdata object
314which is a dict with these keys:
315
316.. tabularcolumns:: |l|p{4.5in}|
317
318==========  ====================================================
319  key         explanation
320==========  ====================================================
321SpGrp       space group symbol (str)
322Laue        one of the following 14 Laue classes:
323            -1, 2/m, mmm, 4/m, 4/mmm, 3R,
324            3mR, 3, 3m1, 31m, 6/m, 6/mmm, m3, m3m (str)
325SGInv       True if centrosymmetric, False if not (bool)
326SGLatt      Lattice centering type. Will be one of
327            P, A, B, C, I, F, R (str)
328SGUniq      unique axis if monoclinic. Will be
329            a, b, or c for monoclinic space groups.
330            Will be blank for non-monoclinic. (str)
331SGCen       Symmetry cell centering vectors. A (n,3) np.array
332            of centers. Will always have at least one row:
333            ``np.array([[0, 0, 0]])``
334SGOps       symmetry operations as a list of form
335            ``[[M1,T1], [M2,T2],...]``
336            where :math:`M_n` is a 3x3 np.array
337            and :math:`T_n` is a length 3 np.array.
338            Atom coordinates are transformed where the
339            Asymmetric unit coordinates [X is (x,y,z)]
340            are transformed using
341            :math:`X^\prime = M_n*X+T_n`
342SGSys       symmetry unit cell: type one of
343            'triclinic', 'monoclinic', 'orthorhombic',
344            'tetragonal', 'rhombohedral', 'trigonal',
345            'hexagonal', 'cubic' (str)
346SGPolax     Axes for space group polarity. Will be one of
347            '', 'x', 'y', 'x y', 'z', 'x z', 'y z',
348            'xyz'. In the case where axes are arbitrary
349            '111' is used (P 1, and ?).
350==========  ====================================================
351
352Atom Records
353------------
354
355.. _Atoms_table:
356
357.. index::
358   single: Atoms record description
359   single: Data object descriptions; Atoms record
360
361
362If ``phasedict`` points to the phase information in the data tree, then
363atoms are contained in a list of atom records (list) in
364``phasedict['Atoms']``. Also needed to read atom information
365are four pointers, ``cx,ct,cs,cia = phasedict['General']['atomPtrs']``,
366which define locations in the atom record, as shown below. Items shown are
367always present; additional ones for macromolecular phases are marked 'mm'
368
369.. tabularcolumns:: |l|p{4.5in}|
370
371==============   ====================================================
372location         explanation
373==============   ====================================================
374ct-4              mm - residue number (str)
375ct-3              mm - residue name (e.g. ALA) (str)
376ct-2              mm - chain label (str)
377ct-1              atom label (str)
378ct                atom type (str)
379ct+1              refinement flags; combination of 'F', 'X', 'U' (str)
380cx,cx+1,cx+2      the x,y and z coordinates (3 floats)
381cs                site symmetry (str)
382cs+1              site multiplicity (int)
383cia               ADP flag: Isotropic ('I') or Anisotropic ('A')
384cia+1             Uiso (float)
385cia+2...cia+6     U11, U22, U33, U12, U13, U23 (6 floats)
386atom[-1]                unique atom identifier (int)
387==============   ====================================================
388
389Drawing Atom Records
390--------------------
391
392.. _Drawing_atoms_table:
393
394.. index::
395   single: Drawing atoms record description
396   single: Data object descriptions; Drawing atoms record
397
398
399If ``phasedict`` points to the phase information in the data tree, then
400drawing atoms are contained in a list of drawing atom records (list) in
401``phasedict['Drawing']['Atoms']``. Also needed to read atom information
402are four pointers, ``cx,ct,cs,ci = phasedict['Drawing']['AtomPtrs']``,
403which define locations in the atom record, as shown below. Items shown are
404always present; additional ones for macromolecular phases are marked 'mm'
405
406.. tabularcolumns:: |l|p{4.5in}|
407
408==============   ====================================================
409location         explanation
410==============   ====================================================
411ct-4              mm - residue number (str)
412ct-3              mm - residue name (e.g. ALA) (str)
413ct-2              mm - chain label (str)
414ct-1              atom label (str)
415ct                atom type (str)
416cx,cx+1,cx+2      the x,y and z coordinates (3 floats)
417cs-1              Sym Op symbol; sym. op number + unit cell id (e.g. '1,0,-1') (str)
418cs                atom drawing style; e.g. 'balls & sticks' (str)
419cs+1              atom label style (e.g. 'name') (str)
420cs+2              atom color (RBG triplet) (int)
421cs+3              ADP flag: Isotropic ('I') or Anisotropic ('A')
422cs+4              Uiso (float)
423cs+5...cs+11      U11, U22, U33, U12, U13, U23 (6 floats)
424ci                unique atom identifier; matches source atom Id in Atom Records (int)
425==============   ====================================================
426
427Powder Diffraction Tree Items
428-----------------------------
429
430.. _Powder_table:
431
432.. index::
433   single: Powder data object description
434   single: Data object descriptions; Powder Data
435
436Every powder diffraction histogram is stored in the GSAS-II data tree
437with a top-level entry named beginning with the string "PWDR ". The
438diffraction data for that information are directly associated with
439that tree item and there are a series of children to that item. The
440routine :func:`~GSASII.GSASII.GetUsedHistogramsAndPhasesfromTree` will
441load this information into a dictionary where the child tree name is
442used as a key, and the information in the main entry is assigned
443a key of ``Data``, as outlined below.
444
445.. tabularcolumns:: |l|l|p{4in}|
446
447======================  ===============  ====================================================
448  key                      sub-key        explanation
449======================  ===============  ====================================================
450Limits                       \            A list of two two element lists, as [[Ld,Hd],[L,H]]
451                                          where L and Ld are the current and default lowest
452                                          two-theta value to be used and
453                                          where H and Hd are the current and default highest
454                                          two-theta value to be used.
455Reflection Lists              \           A dict with an entry for each phase in the
456                                          histogram. The contents of each dict item
457                                          is a dict containing reflections, as described in
458                                          the :ref:`Powder Reflections <PowderRefl_table>`
459                                          description.
460Instrument Parameters         \           A list containing two dicts where the possible
461                                          keys in each dict are listed below. The value
462                                          for each item is a list containing three values:
463                                          the initial value, the current value and a
464                                          refinement flag which can have a value of
465                                          True, False or 0 where 0 indicates a value that
466                                          cannot be refined. The first and second
467                                          values are floats unless otherwise noted.
468                                          Items in the first dict are noted as [1]
469\                         Lam             Specifies a wavelength in Angstroms [1]
470\                         Lam1            Specifies the primary wavelength in
471                                          Angstrom, when an alpha1, alpha2
472                                          source is used [1]
473\                         Lam2            Specifies the secondary wavelength in
474                                          Angstrom, when an alpha1, alpha2
475                                          source is used [1]
476                          I(L2)/I(L1)     Ratio of Lam2 to Lam1 [1]           
477\                         Type            Histogram type (str) [1]:
478                                           * 'PXC' for constant wavelength x-ray
479                                           * 'PNC' for constant wavelength neutron
480                                           * 'PNT' for time of flight neutron
481\                         Zero            Two-theta zero correction in *degrees* [1]
482\                         Azimuth         Azimuthal setting angle for data recorded
483                                          with differing setting angles [1]
484\                         U, V, W         Cagliotti profile coefficients
485                                          for Gaussian instrumental broadening, where the
486                                          FWHM goes as
487                                          :math:`U \\tan^2\\theta + V \\tan\\theta + W` [1]
488\                         X, Y            Cauchy (Lorentzian) instrumental broadening
489                                          coefficients [1]
490\                         SH/L            Variant of the Finger-Cox-Jephcoat asymmetric
491                                          peak broadening ratio. Note that this is the
492                                          average between S/L and H/L where S is
493                                          sample height, H is the slit height and
494                                          L is the goniometer diameter. [1]
495\                         Polariz.        Polarization coefficient. [1]
496wtFactor                      \           A weighting factor to increase or decrease
497                                          the leverage of data in the histogram (float).
498                                          A value of 1.0 weights the data with their
499                                          standard uncertainties and a larger value
500                                          increases the weighting of the data (equivalent
501                                          to decreasing the uncertainties).
502Sample Parameters             \           Specifies a dict with parameters that describe how
503                                          the data were collected, as listed
504                                          below. Refinable parameters are a list containing
505                                          a float and a bool, where the second value
506                                          specifies if the value is refined, otherwise
507                                          the value is a float unless otherwise noted.
508\                         Scale           The histogram scale factor (refinable)
509\                         Absorption      The sample absorption coefficient as
510                                          :math:`\\mu r` where r is the radius
511                                          (refinable).
512\                         DisplaceX,      Sample displacement from goniometer center
513                          DisplaceY       where Y is along the beam direction and
514                                          X is perpendicular. Units are :math:`\\mu m`
515                                          (refinable).
516\                         Phi, Chi,       Goniometer sample setting angles, in degrees.
517                          Omega
518\                         Gonio. radius   Radius of the diffractometer in mm
519\                         InstrName       A name for the instrument, used in preparing
520                                          a CIF (str).
521\                         Force,          Variables that describe how the measurement
522                          Temperature,    was performed. Not used directly in
523                          Humidity,       any computations.
524                          Pressure,
525                          Voltage
526\                         ranId           The random-number Id for the histogram
527                                          (same value as where top-level key is ranId)
528\                         Type            Type of diffraction data, may be 'Debye-Scherrer'
529                                          or 'Bragg-Brentano' (str).
530\                         Diffuse         not in use?
531hId                           \           The number assigned to the histogram when
532                                          the project is loaded or edited (can change)
533ranId                         \           A random number id for the histogram
534                                          that does not change
535Background                    \           The background is stored as a list with where
536                                          the first item in the list is list and the second
537                                          item is a dict. The list contains the background
538                                          function and its coefficients; the dict contains
539                                          Debye diffuse terms and background peaks.
540                                          (TODO: this needs to be expanded.)
541Data                          \           The data consist of a list of 6 np.arrays
542                                          containing in order:
543
544                                           1. the x-postions (two-theta in degrees),
545                                           2. the intensity values (Yobs),
546                                           3. the weights for each Yobs value
547                                           4. the computed intensity values (Ycalc)
548                                           5. the background values
549                                           6. Yobs-Ycalc
550======================  ===============  ====================================================
551
552Powder Reflection Data Structure
553--------------------------------
554
555.. _PowderRefl_table:
556
557.. index::
558   single: Powder reflection object description
559   single: Data object descriptions; Powder Reflections
560   
561For every phase in a histogram, the ``Reflection Lists`` value is a dict
562one element of which is `'RefList'`, which is a np.array containing
563reflections. The columns in that array are documented below.
564
565==========  ====================================================
566  index         explanation
567==========  ====================================================
568 0,1,2       h,k,l (float)
569 3           multiplicity
570 4           d-space, Angstrom
571 5           pos, two-theta
572 6           sig, Gaussian width
573 7           gam, Lorenzian width
574 8           :math:`F_{obs}^2`
575 9           :math:`F_{calc}^2`
576 10          reflection phase, in degrees
577 11          intensity correction for reflection, this times
578             :math:`F_{obs}^2` or :math:`F_{calc}^2` gives Iobs or Icalc
579==========  ====================================================
580
581Single Crystal Tree Items
582-------------------------
583
584.. _Xtal_table:
585
586.. index::
587   single: Single Crystal data object description
588   single: Data object descriptions; Single crystal data
589
590Every single crystal diffraction histogram is stored in the GSAS-II data tree
591with a top-level entry named beginning with the string "HKLF ". The
592diffraction data for that information are directly associated with
593that tree item and there are a series of children to that item. The
594routine :func:`~GSASII.GSASII.GetUsedHistogramsAndPhasesfromTree` will
595load this information into a dictionary where the child tree name is
596used as a key, and the information in the main entry is assigned
597a key of ``Data``, as outlined below.
598
599.. tabularcolumns:: |l|l|p{4in}|
600
601======================  ===============  ====================================================
602  key                      sub-key        explanation
603======================  ===============  ====================================================
604Data                          \           A dict that contains the
605                                          reflection table,
606                                          as described in the
607                                          :ref:`Single Crystal Reflections
608                                          <XtalRefl_table>`
609                                          description.
610
611Instrument Parameters         \           A list containing two dicts where the possible
612                                          keys in each dict are listed below. The value
613                                          for most items is a list containing two values:
614                                          the initial value, the current value.
615                                          The first and second
616                                          values are floats unless otherwise noted.
617\                         Lam             Specifies a wavelength in Angstroms (two floats)
618\                         Type            Histogram type (two str values):
619                                           * 'SXC' for constant wavelength x-ray
620                                           * 'SNC' for constant wavelength neutron
621                                           * 'SNT' for time of flight neutron
622\                         InstrName       A name for the instrument, used in preparing
623                                          a CIF (str).
624
625wtFactor                      \           A weighting factor to increase or decrease
626                                          the leverage of data in the histogram (float).
627                                          A value of 1.0 weights the data with their
628                                          standard uncertainties and a larger value
629                                          increases the weighting of the data (equivalent
630                                          to decreasing the uncertainties).
631
632hId                           \           The number assigned to the histogram when
633                                          the project is loaded or edited (can change)
634ranId                         \           A random number id for the histogram
635                                          that does not change
636======================  ===============  ====================================================
637
638Single Crystal Reflection Data Structure
639----------------------------------------
640
641.. _XtalRefl_table:
642
643.. index::
644   single: Single Crystal reflection object description
645   single: Data object descriptions; Single Crystal Reflections
646   
647For every simgle crystal a histogram, the ``'Data'`` item contains
648the structure factors as an np.array in item `'RefList'`.
649The columns in that array are documented below.
650
651==========  ====================================================
652  index         explanation
653==========  ====================================================
654 0,1,2       h,k,l (float)
655 3           multiplicity
656 4           d-space, Angstrom
657 5           :math:`F_{obs}^2`
658 6           :math:`\sigma(F_{obs}^2)`
659 7           :math:`F_{calc}^2`
660 8           :math:`F_{obs}^2T`
661 9           :math:`F_{calc}^2T`
662 10          reflection phase, in degrees
663 11          intensity correction for reflection, this times
664             :math:`F_{obs}^2` or :math:`F_{calc}^2`
665             gives Iobs or Icalc
666==========  ====================================================
667
668
669*Classes and routines*
670----------------------
671
672'''
673import random as ran
674import sys
675import GSASIIpath
676import GSASIImath as G2mth
677
678GSASIIpath.SetVersionNumber("$Revision: 1138 $")
679PhaseIdLookup = {}
680'''dict listing phase name and random Id keyed by sequential phase index as a str;
681best to access this using :func:`LookupPhaseName`
682'''
683PhaseRanIdLookup = {}
684'''dict listing phase sequential index keyed by phase random Id;
685best to access this using :func:`LookupPhaseId`
686'''
687HistIdLookup = {}
688'''dict listing histogram name and random Id, keyed by sequential histogram index as a str;
689best to access this using :func:`LookupHistName`
690'''
691HistRanIdLookup = {}
692'''dict listing histogram sequential index keyed by histogram random Id;
693best to access this using :func:`LookupHistId`
694'''
695AtomIdLookup = {}
696'''dict listing for each phase index as a str, the atom label and atom random Id,
697keyed by atom sequential index as a str;
698best to access this using :func:`LookupAtomLabel`
699'''
700AtomRanIdLookup = {}
701'''dict listing for each phase the atom sequential index keyed by atom random Id;
702best to access this using :func:`LookupAtomId`
703'''
704ShortPhaseNames = {}
705'''a dict containing a possibly shortened and when non-unique numbered
706version of the phase name. Keyed by the phase sequential index.
707'''
708ShortHistNames = {}
709'''a dict containing a possibly shortened and when non-unique numbered
710version of the histogram name. Keyed by the histogram sequential index.
711'''
712
713VarDesc = {}
714''' This dictionary lists descriptions for GSAS-II variables,
715as set in :func:`CompileVarDesc`. See that function for a description
716for how keys and values are written.
717'''
718
719reVarDesc = {}
720''' This dictionary lists descriptions for GSAS-II variables with
721the same values as :attr:`VarDesc` except that keys have been compiled as
722regular expressions. Initialized in :func:`CompileVarDesc`.
723'''
724
725def IndexAllIds(G2frame=None,Histograms=None,Phases=None):
726    '''Scan through the used phases & histograms and create an index
727    to the random numbers of phases, histograms and atoms. While doing this,
728    confirm that assigned random numbers are unique -- just in case lightning
729    strikes twice in the same place.
730
731    Note: this code assumes that the atom random Id (ranId) is the last
732    element each atom record.
733
734    TODO: do we need a lookup for rigid body variables?
735    '''
736    if G2frame:
737        Histograms,phaseDict = G2frame.GetUsedHistogramsAndPhasesfromTree()
738    else:
739        Histograms,phaseDict = Histograms,Phases
740    # process phases and atoms
741    PhaseIdLookup.clear()
742    PhaseRanIdLookup.clear()   
743    AtomIdLookup.clear()
744    AtomRanIdLookup.clear()
745    ShortPhaseNames.clear()
746    for Phase in phaseDict:
747        cx,ct,cs,cia = phaseDict[Phase]['General']['AtomPtrs']
748        ranId = phaseDict[Phase]['ranId'] 
749        while ranId in PhaseRanIdLookup:
750            # Found duplicate random Id! note and reassign
751            print ("\n\n*** Phase "+str(Phase)+" has repeated ranId. Fixing.\n")
752            phaseDict[Phase]['ranId'] = ranId = ran.randint(0,sys.maxint)
753        pId = str(phaseDict[Phase]['pId'])
754        PhaseIdLookup[pId] = (Phase,ranId)
755        PhaseRanIdLookup[ranId] = pId
756        shortname = Phase[:10]
757        while shortname in ShortPhaseNames.values():
758            shortname = Phase[:8] + ' ('+ pId + ')'
759        ShortPhaseNames[pId] = shortname
760        AtomIdLookup[pId] = {}
761        AtomRanIdLookup[pId] = {}
762        for iatm,at in enumerate(phaseDict[Phase]['Atoms']):
763            ranId = at[-1]
764            while ranId in AtomRanIdLookup[pId]: # check for dups
765                print ("\n\n*** Phase "+str(Phase)+" atom "+str(iatm)+" has repeated ranId. Fixing.\n")
766                at[-1] = ranId = ran.randint(0,sys.maxint)
767            AtomRanIdLookup[pId][ranId] = str(iatm)
768            if phaseDict[Phase]['General']['Type'] == 'macromolecular':
769                label = '%s_%s_%s_%s'%(at[ct-1],at[ct-3],at[ct-4],at[ct-2])
770            else:
771                label = at[ct-1]
772            AtomIdLookup[pId][str(iatm)] = (label,ranId)
773    # process histograms
774    HistIdLookup.clear()
775    HistRanIdLookup.clear()
776    ShortHistNames.clear()
777    for hist in Histograms:
778        ranId = Histograms[hist]['ranId']
779        while ranId in HistRanIdLookup:
780            # Found duplicate random Id! note and reassign
781            print ("\n\n*** Histogram "+str(hist)+" has repeated ranId. Fixing.\n")
782            Histograms[hist]['ranId'] = ranId = ran.randint(0,sys.maxint)
783        hId = str(Histograms[hist]['hId'])
784        HistIdLookup[hId] = (hist,ranId)
785        HistRanIdLookup[ranId] = hId
786        shortname = hist[:15]
787        while shortname in ShortHistNames.values():
788            shortname = hist[:11] + ' ('+ hId + ')'
789        ShortHistNames[hId] = shortname
790
791    return Histograms,phaseDict
792
793def LookupAtomId(pId,ranId):
794    '''Get the atom number from a phase and atom random Id
795
796    :param int/str pId: the sequential number of the phase
797    :param int ranId: the random Id assigned to an atom
798
799    :returns: the index number of the atom (str)
800    '''
801    if not AtomRanIdLookup:
802        raise Exception,'Error: LookupAtomId called before IndexAllIds was run'
803    if pId is None or pId == '':
804        raise KeyError,'Error: phase is invalid (None or blank)'
805    pId = str(pId)
806    if pId not in AtomRanIdLookup:
807        raise KeyError,'Error: LookupAtomId does not have phase '+pId
808    if ranId not in AtomRanIdLookup[pId]:
809        raise KeyError,'Error: LookupAtomId, ranId '+str(ranId)+' not in AtomRanIdLookup['+pId+']'
810    return AtomRanIdLookup[pId][ranId]
811
812def LookupAtomLabel(pId,index):
813    '''Get the atom label from a phase and atom index number
814
815    :param int/str pId: the sequential number of the phase
816    :param int index: the index of the atom in the list of atoms
817
818    :returns: the label for the atom (str) and the random Id of the atom (int)
819    '''
820    if not AtomIdLookup:
821        raise Exception,'Error: LookupAtomLabel called before IndexAllIds was run'
822    if pId is None or pId == '':
823        raise KeyError,'Error: phase is invalid (None or blank)'
824    pId = str(pId)
825    if pId not in AtomIdLookup:
826        raise KeyError,'Error: LookupAtomLabel does not have phase '+pId
827    if index not in AtomIdLookup[pId]:
828        raise KeyError,'Error: LookupAtomLabel, ranId '+str(index)+' not in AtomRanIdLookup['+pId+']'
829    return AtomIdLookup[pId][index]
830
831def LookupPhaseId(ranId):
832    '''Get the phase number and name from a phase random Id
833
834    :param int ranId: the random Id assigned to a phase
835    :returns: the sequential Id (pId) number for the phase (str)
836    '''
837    if not PhaseRanIdLookup:
838        raise Exception,'Error: LookupPhaseId called before IndexAllIds was run'
839    if ranId not in PhaseRanIdLookup:
840        raise KeyError,'Error: LookupPhaseId does not have ranId '+str(ranId)
841    return PhaseRanIdLookup[ranId]
842
843def LookupPhaseName(pId):
844    '''Get the phase number and name from a phase Id
845
846    :param int/str pId: the sequential assigned to a phase
847    :returns:  (phase,ranId) where phase is the name of the phase (str)
848      and ranId is the random # id for the phase (int)
849    '''
850    if not PhaseIdLookup:
851        raise Exception,'Error: LookupPhaseName called before IndexAllIds was run'
852    if pId is None or pId == '':
853        raise KeyError,'Error: phase is invalid (None or blank)'
854    pId = str(pId)
855    if pId not in PhaseIdLookup:
856        raise KeyError,'Error: LookupPhaseName does not have index '+pId
857    return PhaseIdLookup[pId]
858
859def LookupHistId(ranId):
860    '''Get the histogram number and name from a histogram random Id
861
862    :param int ranId: the random Id assigned to a histogram
863    :returns: the sequential Id (hId) number for the histogram (str)
864    '''
865    if not HistRanIdLookup:
866        raise Exception,'Error: LookupHistId called before IndexAllIds was run'
867    if ranId not in HistRanIdLookup:
868        raise KeyError,'Error: LookupHistId does not have ranId '+str(ranId)
869    return HistRanIdLookup[ranId]
870
871def LookupHistName(hId):
872    '''Get the histogram number and name from a histogram Id
873
874    :param int/str hId: the sequential assigned to a histogram
875    :returns:  (hist,ranId) where hist is the name of the histogram (str)
876      and ranId is the random # id for the histogram (int)
877    '''
878    if not HistIdLookup:
879        raise Exception,'Error: LookupHistName called before IndexAllIds was run'
880    if hId is None or hId == '':
881        raise KeyError,'Error: histogram is invalid (None or blank)'
882    hId = str(hId)
883    if hId not in HistIdLookup:
884        raise KeyError,'Error: LookupHistName does not have index '+hId
885    return HistIdLookup[hId]
886
887def fmtVarDescr(varname):
888    '''Return a string with a more complete description for a GSAS-II variable
889
890    TODO: This will not handle rigid body parameters yet
891
892    :param str name: A full G2 variable name with 2 or 3
893       colons (<p>:<h>:name[:<a>])
894       
895    :returns: a string with the description
896    '''
897   
898    l = getVarDescr(varname)
899    if not l:
900        return "invalid variable name ("+str(varname)+")!"
901
902    if not l[4]:
903        l[4] = "(variable needs a definition!)"
904
905    s = ""
906    if l[0] is not None and l[1] is not None: # HAP: keep short
907        lbl = ShortPhaseNames.get(l[0],'? #'+str(l[0]))
908        hlbl = ShortHistNames.get(l[1],'? #'+str(l[1]))
909        if hlbl[:4] == 'HKLF':
910            hlbl = 'Xtl='+hlbl[5:]
911        elif hlbl[:4] == 'PWDR':
912            hlbl = 'Pwd='+hlbl[5:]
913        else:
914            hlbl = 'Hist='+hlbl
915        s = "Ph="+str(lbl)+" * "+str(hlbl)+": "
916    elif l[3] is not None: # atom parameter,
917        lbl = ShortPhaseNames.get(l[0],'phase?')
918        try:
919            albl = LookupAtomLabel(l[0],l[3])[0]
920        except KeyError:
921            albl = 'Atom?'
922        s = "Atom "+str(albl)+" in "+str(lbl)+": "
923    elif l[0] is not None:
924        lbl = ShortPhaseNames.get(l[0],'phase?')
925        s = "Phase "+str(lbl)+": "
926    elif l[1] is not None:
927        hlbl = ShortHistNames.get(l[1],'? #'+str(l[1]))
928        if hlbl[:4] == 'HKLF':
929            hlbl = 'Xtl='+hlbl[5:]
930        elif hlbl[:4] == 'PWDR':
931            hlbl = 'Pwd='+hlbl[5:]
932        else:
933            hlbl = 'Hist='+hlbl
934        s = str(hlbl)+": "   
935    if not s:
936        s = 'Global: '
937    s += l[4]
938    return s
939
940def getVarDescr(varname):
941    '''Return a short description for a GSAS-II variable
942
943    :param str name: A full G2 variable name with 2 or 3
944       colons (<p>:<h>:name[:<a>])
945     
946    :returns: a five element list as [`p`,`h`,`name`,`a`,`description`],
947      where `p`, `h`, `a` are str values or `None`, for the phase number,
948      the histogram number and the atom number; `name` will always be
949      an str; and `description` is str or `None`.
950      If the variable name is incorrectly formed (for example, wrong
951      number of colons), `None` is returned instead of a list.
952    '''
953    l = varname.split(':')
954    if len(l) == 3:
955        l += [None]
956    if len(l) != 4:
957        return None
958    for i in (0,1,3):
959        if l[i] == "":
960            l[i] = None
961    l += [getDescr(l[2])]
962    return l
963   
964def CompileVarDesc():
965    '''Set the values in the variable description lookup table (:attr:`VarDesc`)
966    into :attr:`reVarDesc`. This is called in :func:`getDescr` so the initialization
967    is always done before use.
968
969    Note that keys may contain regular expressions, where '[xyz]'
970    matches 'x' 'y' or 'z' (equivalently '[x-z]' describes this as range of values).
971    '.*' matches any string. For example::
972
973    'AUiso':'Atomic isotropic displacement parameter',
974
975    will match variable ``'p::AUiso:a'``.
976    If parentheses are used in the key, the contents of those parentheses can be
977    used in the value, such as::
978
979    'AU([123][123])':'Atomic anisotropic displacement parameter U\\1',
980
981    will match ``AU11``, ``AU23``,.. and `U11`, `U23` etc will be displayed
982    in the value when used.
983   
984    '''
985    import re
986    if reVarDesc: return # already done
987    for key,value in {
988        # Phase vars (p::<var>)
989        'A([0-5])' : 'Reciprocal metric tensor component \\1',
990        'Vol' : 'Unit cell volume????',
991        # Atom vars (p::<var>:a)
992        'dA([xyz])' : 'change to atomic position \\1',
993        'AUiso':'Atomic isotropic displacement parameter',
994        'AU([123][123])':'Atomic anisotropic displacement parameter U\\1',
995        'Afrac': 'Atomic occupancy parameter',
996        # Hist & Phase (HAP) vars (p:h:<var>)
997        'Bab([AU])': 'Babinet solvent scattering coef. \\1',
998        'D([123][123])' : 'Anisotropic strain coef. \\1',
999        'Extinction' : 'Extinction coef.',
1000        'MD' : 'March-Dollase coef.',
1001        'Mustrain;.*' : 'Microstrain coef.',
1002        'Scale' : 'Phase scale factor',
1003        'Size;.*' : 'Crystallite size value',
1004        'eA' : '?',
1005        #Histogram vars (:h:<var>)
1006        'Absorption' : 'Absorption coef.',
1007        'Displace([XY])' : 'Debye-Scherrer sample displacement \\1',
1008        'Lam' : 'Wavelength',
1009        'Polariz\.' : 'Polarization correction',
1010        'SH/L' : 'FCJ peak asymmetry correction',
1011        'Scale' : 'Histogram scale factor',
1012        '([UVW])' : 'Gaussian instrument broadening \\1',
1013        '([XY])' : 'Cauchy instrument broadening \\1',
1014        'Zero' : 'Debye-Scherrer zero correction',
1015        'nDebye' : 'Debye model background corr. terms',
1016        'nPeaks' : 'Fixed peak background corr. terms',
1017        # Global vars (::<var>)
1018        }.items():
1019        VarDesc[key] = value
1020        reVarDesc[re.compile(key)] = value
1021
1022def getDescr(name):
1023    '''Return a short description for a GSAS-II variable
1024
1025    :param str name: The descriptive part of the variable name without colons (:)
1026     
1027    :returns: a short description or None if not found
1028    '''
1029
1030    CompileVarDesc() # compile the regular expressions, if needed
1031    for key in reVarDesc:
1032        m = key.match(name)
1033        if m:
1034            return m.expand(reVarDesc[key])
1035    return None
1036
1037def _lookup(dic,key):
1038    '''Lookup a key in a dictionary, where None returns an empty string
1039    but an unmatched key returns a question mark. Used in :class:`G2VarObj`
1040    '''
1041    if key is None:
1042        return ""
1043    else:
1044        return dic.get(key,'?')
1045
1046class G2VarObj(object):
1047    '''Defines a GSAS-II variable either using the phase/atom/histogram
1048    unique Id numbers or using a character string that specifies
1049    variables by phase/atom/histogram number (which can change).
1050    Note that :func:`LoadID` should be used to (re)load the current Ids
1051    before creating or later using the G2VarObj object.
1052
1053    A :class:`G2VarObj` object can be created with a single parameter:
1054   
1055    :param str varname: a single value can be used to create a :class:`G2VarObj`
1056      object. The string must be of form "p:h:var" or "p:h:var:a", where
1057
1058     * p is the phase number (which may be left blank);
1059     * h is the histogram number (which may be left blank);
1060     * a is the atom number (which may be left blank in which case the third colon is omitted).
1061
1062    Alternately, a :class:`G2VarObj` object can be created with exactly four positional parameters:
1063
1064    :param str/int phasenum: The number for the phase
1065    :param str/int histnum: The number for the histogram
1066    :param str varname: a single value can be used to create a :class:`G2VarObj`
1067    :param str/int atomnum: The number for the atom
1068   
1069    '''
1070    IDdict = {}
1071    IDdict['phases'] = {}
1072    IDdict['hists'] = {}
1073    IDdict['atoms'] = {}
1074    def __init__(self,*args):
1075        self.phase = None
1076        self.histogram = None
1077        self.name = ''
1078        self.atom = None
1079        if len(args) == 1:
1080            lst = args[0].split(':')
1081            self.phase = PhaseIdLookup.get(lst[0],[None,None])[1]
1082            self.histogram = HistIdLookup.get(lst[1],[None,None])[1]
1083            self.name = lst[2]
1084            if len(lst) > 3:
1085                self.atom = AtomIdLookup[lst[0]].get(lst[3],[None,None])[1]
1086        elif len(args) == 4:
1087            self.phase = PhaseIdLookup.get(str(args[0]),[None,None])[1]
1088            self.histogram = HistIdLookup.get(str(args[1]),[None,None])[1]
1089            self.name = args[2]
1090            self.atom = AtomIdLookup[args[0]].get(str(args[3]),[None,None])[1]
1091        else:
1092            raise Exception,"Incorrectly called GSAS-II parameter name"
1093
1094        #print "DEBUG: created ",self.phase,self.histogram,self.name,self.atom
1095
1096    def __str__(self):
1097        return self.varname()
1098
1099    def varname(self):
1100        '''Formats the GSAS-II variable name as a "traditional" GSAS-II variable
1101        string (p:h:<var>:a) or (p:h:<var>)
1102
1103        :returns: the variable name as a str
1104        '''
1105        ph = _lookup(PhaseRanIdLookup,self.phase)
1106        hist = _lookup(HistRanIdLookup,self.histogram)
1107        s = (ph + ":" + hist + ":" + 
1108             str(self.name))
1109        if self.atom:
1110            if ph in AtomRanIdLookup:
1111                s += ":" + AtomRanIdLookup[ph].get(self.atom,'?')
1112            else:
1113                s += ":?"
1114        return s
1115   
1116    def __repr__(self):
1117        '''Return the detailed contents of the object
1118        '''
1119        s = "<"
1120        if self.phase is not None:
1121            ph =  _lookup(PhaseRanIdLookup,self.phase)
1122            s += "Phase: rId=" + str(self.phase) + " (#"+ ph + "); "
1123        if self.histogram is not None:
1124            hist = _lookup(HistRanIdLookup,self.histogram)
1125            s += "Histogram: rId=" + str(self.histogram) + " (#"+ hist + "); "
1126        if self.atom is not None:
1127            s += "Atom rId=" + str(self.atom)
1128            if ph in AtomRanIdLookup:
1129                s += " (#" + AtomRanIdLookup[ph].get(self.atom,'?') + "); "
1130            else:
1131                s += " (#? -- no such phase!); "
1132        s += 'Variable name="' + str(self.name) + '">'
1133        return s+"("+self.varname()+")"
1134
1135    def __eq__(self, other):
1136        if type(other) is type(self):
1137            return (self.phase == other.phase and
1138                    self.histogram == other.histogram and
1139                    self.name == other.name and
1140                    self.atom == other.atom)
1141        return False
1142
1143    def _show(self):
1144        'For testing, shows the current lookup table'
1145        print 'phases', self.IDdict['phases']
1146        print 'hists', self.IDdict['hists']
1147        print 'atomDict', self.IDdict['atoms']
1148
Note: See TracBrowser for help on using the repository browser.