source: trunk/GSASIIobj.py @ 1145

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

move DefaultControls? out of g2grid to avoid wx requirement; now import mmCIF reflection files

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