source: trunk/GSASIIobj.py @ 1129

Last change on this file since 1129 was 1129, checked in by vondreele, 8 years ago

add some docs to G2obj.py

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 40.9 KB
Line 
1# TODO: change this to assemble the look-up tables of atoms, phases and hists from the tree
2# and then save/unsave those values in __init__ & __str__, etc.
3
4'''
5*GSASIIobj: Data objects*
6=========================
7
8This module defines and/or documents the data structures used in GSAS-II.
9
10
11Constraints Tree Item
12----------------------
13
14.. _Constraints_table:
15
16.. index::
17   single: Constraints object description
18   single: Data object descriptions; Constraints
19
20Constraints are stored in a dict, separated into groups.
21Note that parameter are named in the following pattern,
22p:h:<var>:n, where p is the phase number, h is the histogram number
23<var> is a variable name and n is the parameter number.
24If a parameter does not depend on a histogram or phase or is unnumbered, that
25number is omitted.
26Note that the contents of each dict item is a List where each element in the
27list is a :ref:`constraint definition objects <Constraint_definitions_table>`.
28
29The keys in the Constraints dict are:
30
31.. tabularcolumns:: |l|p{4.5in}|
32
33==========  ====================================================
34  key         explanation
35==========  ====================================================
36Hist        This specifies a list of constraints on
37            histogram-related parameters,
38            which will be of form :h:<var>:n.
39HAP         This specifies a list of constraints on parameters
40            that are defined for every histogram in each phase
41            and are of form p:h:<var>:n.           
42Phase       This specifies a list of constraints on phase
43            parameters,
44            which will be of form p::<var>:n.
45Global      This specifies a list of constraints on parameters
46            that are not tied to a histogram or phase and
47            are of form ::<var>:n
48==========  ====================================================
49
50.. _Constraint_definitions_table:
51
52.. index::
53   single: Constraint definition object description
54   single: Data object descriptions; Constraint Definition
55
56Each constraint is defined as a list using a series of terms of form
57
58::
59
60[[<mult1>, <var1>], [<mult2>, <var2>],..., <fixed val>, <vary flag>, <cons type>]
61
62Where the variable pair list item containing two values [<mult>, <var>],
63
64  * <mult> is a multiplier for the constraint (float)
65  * <var> is the name of the variable (str) (or to be implemented a :class:`VarName` object.)
66
67Note that the last three items in the list play a special role:
68
69 * <fixed val> is the fixed value for a constraint equation or is None
70 * <vary flag> is True, False or None and is intended to use to indicate if new variables
71   should be refined.
72 * <cons type> is one of four letters, 'e', 'c', 'h', 'f' that determines the type of constraint.
73
74    * 'e' defines a set of equivalent variables. Only the first variable is refined (if the
75      appropriate refine flag is set) and and all other equivalent variables in the list
76      are generated from that variable. The vary flag for those variables is ignored.
77    * 'c' defines a constraint equation of form, :math:`m_1 \\times var_1 + m_2 \\times var_2 + ... = c`
78    * 'h' defines a variable to hold (not vary). Any variable on this list is not varied, even if its refinement
79      flag is set. This is of particular value when needing to hold one or more variables in a set such as
80      the reciprocal metric tensor or anisotropic displacement parameter.
81    * 'f' defines a relationship to define a new variable according to relationship
82      :math:`newvar = m_1 \\times var_1 + m_2 \\times var_2 + ...`
83
84Covariance Tree Item
85--------------------
86
87.. _Covariance_table:
88
89.. index::
90   single: Covariance description
91   single: Data object descriptions; Covariance
92
93The Covariance tree item has results from the last least-squares run. They
94are stored in a dict with these keys:
95
96.. tabularcolumns:: |l|l|p{4in}|
97
98=============  ===============  ====================================================
99  key            sub-key        explanation
100=============  ===============  ====================================================
101newCellDict    \                dict with lattice parameters computed by
102                                :func:`GSASIIstrMath.GetNewCellParms` (dict)
103title          \                Name of gpx file(?) (str)
104variables      \                Values for all N refined variables
105                                (list of float values, length N,
106                                ordered to match varyList)
107sig            \                Uncertainty values for all N refined variables
108                                (list of float values, length N,
109                                ordered to match varyList)
110varyList       \                List of directly refined variables
111                                (list of str values, length N)
112newAtomDict    \                dict with atom position values computed in
113                                :func:`GSASIIstrMath.ApplyXYZshifts` (dict)
114Rvals          \                R-factors, GOF, Marquardt value for last
115                                refinement cycle (dict)
116\              Nobs             Number of observed data points (int)
117\              Rwp              overall weighted profile R-factor (%, float)
118\              chisq            sum[w*(Iobs-Icalc)**2] for all data
119                                note this is not the reduced chi squared (float)
120\              lamMax           Marquardt value applied to Hessian diagonal
121                                (float)
122\              GOF              The goodness-of-fit, aka square root of
123                                the reduced chi squared. (float)
124covMatrix      \                The (NxN) covVariance matrix (np.array)
125=============  ===============  ====================================================
126
127Phase Tree Items
128----------------
129
130.. _Phase_table:
131
132.. index::
133   single: Phase object description
134   single: Data object descriptions; Phase
135
136Phase information is stored in the GSAS-II data tree as children of the
137Phases item in a dict with keys:
138
139.. tabularcolumns:: |l|l|p{4in}|
140
141==========  ===============  ====================================================
142  key         sub-key        explanation
143==========  ===============  ====================================================
144General         \            Overall information for the phase (dict)
145  \         AtomPtrs         list of four locations to use to pull info
146                             from the atom records (list)
147  \         F000X            x-ray F(000) intensity (float)
148  \         F000N            neutron F(000) intensity (float)
149  \         Mydir            directory of current .gpx file (str)
150  \         MCSA controls    Monte Carlo-Simulated Annealing controls (dict)
151  \         Cell             List with 8 items: cell refinement flag (bool)
152                             a, b, c, (Angstrom, float)
153                             alpha, beta & gamma (degrees, float)
154                             volume (A^3, float)
155  \         Type             'nuclear' or 'macromolecular' for now (str)
156  \         Map              dict of map parameters
157  \         SH Texture       dict of spherical harmonic preferred orientation
158                             parameters
159  \         Isotope          dict of isotopes for each atom type
160  \         Isotopes         dict of scattering lengths for each isotope
161                             combination for each element in phase 
162  \         Name             phase name (str)
163  \         SGData           Space group details as a :ref:`space group (SGData) object <SGData_table>`
164                             as defined in :func:`GSASIIspc.SpcGroup`.
165  \         Pawley neg wt    Restraint value for negative Pawley intensities
166                             (float)
167  \         Flip             dict of Charge flip controls
168  \         Data plot type   data plot type ('Mustrain', 'Size' or
169                             'Preferred orientation') for powder data (str)
170  \         Mass             Mass of unit cell contents in g/mol
171  \         POhkl            March-Dollase preferred orientation direction
172  \         Z                dict of atomic numbers for each atom type
173  \         vdWRadii         dict of van der Waals radii for each atom type
174  \         Color            Colors for atoms (list of (r,b,g) triplets)
175  \         AtomTypes        List of atom types
176  \         AtomMass         List of masses for atoms
177  \         doPawley         Flag for Pawley intensity extraction (bool)
178  \         NoAtoms          Number of atoms per unit cell of each type (dict)
179  \         Pawley dmin      maximum Q (as d-space) to use for Pawley
180                             extraction (float)
181  \         BondRadii        Default radius for each atom used to compute
182                             interatomic distances (list of floats)
183  \         AngleRadii       Default radius for each atom used to compute
184                             interatomic angles (list of floats)
185  \         DisAglCtls       Dict with distance/angle search controls,
186                             which has keys 'Name', 'AtomTypes',
187                             'BondRadii', 'AngleRadii' which are as above
188                             except are possibly edited. Also contains
189                             'Factors', which is a 2 element list with
190                             a multiplier for bond and angle search range
191                             [typically (0.85,0.85)].
192ranId           \            unique random number Id for phase (int)
193pId             \            Phase Id number for current project (int).
194Atoms           \            Atoms in phase as a list of lists. The outer list
195                             is for each atom, the inner list contains varying
196                             items depending on the type of phase, see
197                             the :ref:`Atom Records <Atoms_table>` description.
198                             (list of lists)
199Drawing         \            Display parameters (dict)
200\           ballScale        Size of spheres in ball-and-stick display (float)
201\           bondList         dict with bonds
202\           contourLevel     map contour level in e/A^3 (float)
203\           showABC          Flag to show view point triplet (bool). True=show.
204\           viewDir          cartesian viewing direction (np.array with three
205                             elements)
206\           Zclip            clipping distance in A (float)
207\           backColor        background for plot as and R,G,B triplet
208                             (default = [0, 0, 0], black).
209                             (list with three atoms)
210\           selectedAtoms    List of selected atoms (list of int values)
211\           showRigidBodies  Flag to highlight rigid body placement
212\           sizeH            Size ratio for H atoms (float)
213\           bondRadius       Size of binds in A (float)
214\           atomPtrs         positions of x, type, site sym, ADP flag in Draw Atoms (list)
215\           viewPoint        list of lists. First item in list is [x,y,z]
216                             in fractional coordinates for the center of
217                             the plot. Second item list of previous & current
218                             atom number viewed (may be [0,0])
219\           showHydrogen     Flag to control plotting of H atoms.
220\           unitCellBox      Flag to control display of the unit cell.
221\           ellipseProb      Probability limit for display of thermal
222                             ellipsoids in % (float).
223\           vdwScale         Multiplier of van der Waals radius for
224                             display of vdW spheres.
225\           Atoms            A list of lists with an entry for each atom
226                             that is plotted.
227\           Zstep            Step to de/increase Z-clip (float)
228\           Quaternion       Viewing quaternion (4 element np.array)
229\           radiusFactor     Distance ratio for searching for bonds. ? Bonds
230                             are located that are within r(Ra+Rb) and (Ra+Rb)/r
231                             where Ra and Rb are the atomic radii.
232\           oldxy            previous view point (list with two floats)
233\           cameraPos        Viewing position in A for plot (float)
234\           depthFog         True if use depthFog on plot - set currently as False (bool)
235RBModels        \            Rigid body assignments (note Rigid body definitions
236                             are stored in their own main top-level tree entry.)
237Pawley ref      \            Pawley reflections
238Histograms      \            A dict of dicts. The key for the outer dict is
239                             the histograms tied to this phase. The inner
240                             dict contains the combined phase/histogram
241                             parameters for items such as scale factors,
242                             size and strain parameters. (dict)
243MCSA            \            Monte-Carlo simulated annealing parameters (dict)
244\           
245==========  ===============  ====================================================
246
247Rigid Body Objects
248------------------
249
250.. _RBData_table:
251
252.. index::
253   single: Rigid Body Data description
254   single: Data object descriptions; Rigid Body Data
255   
256Rigid body descriptions are available for two types of rigid bodies: 'Vector'
257and 'Residue'. Vector rigid bodies are developed by a sequence of translations each
258with a refinable magnitude and Residue rigid bodies are described as Cartesian coordinates
259with defined refinable torsion angles.
260
261.. tabularcolumns:: |l|l|p{4in}|
262
263==========  ===============  ====================================================
264  key         sub-key        explanation
265==========  ===============  ====================================================
266Vector      RBId             vector rigid bodies (dict of dict)
267\           AtInfo           Drad, Color: atom drawing radius & color for each atom type (dict)
268\           RBname           Name assigned by user to rigid body (str)
269\           VectMag          vector magnitudes in A (list)
270\           rbXYZ            Cartesian coordinates for Vector rigid body (list of 3 float)
271\           rbRef            3 assigned reference atom nos. in rigid body for origin
272                             definition, use center of atoms flag (list of 3 int & 1 bool)
273\           VectRef          refinement flags for VectMag values (list of bool)
274\           rbTypes          Atom types for each atom in rigid body (list of str)
275\           rbVect           Cartesian vectors for each translation used to build rigid body (list of lists)
276\           useCount         Number of times rigid body is used in any structure (int)
277Residue     RBId             residue rigid bodies (dict of dict)
278\           AtInfo           Drad, Color: atom drawing radius & color for each atom type(dict)
279\           RBname           Name assigned by user to rigid body (str)
280\           rbXYZ            Cartesian coordinates for Residue rigid body (list of 3 float)
281\           rbTypes          Atom types for each atom in rigid body (list of str)
282\           atNames          Names of each atom in rigid body (e.g. C1,N2...) (list of str)
283\           rbRef            3 assigned reference atom nos. in rigid body for origin
284                             definition, use center of atoms flag (list of 3 int & 1 bool)
285\           rbSeq            Orig,Piv,angle,Riding (list): definition of internal rigid body
286                             torsion; origin atom (int), pivot atom (int), torsion angle (float),
287                             riding atoms (list of int)
288\           SelSeq           [int,int] used by SeqSizer to identify objects
289\           useCount         Number of times rigid body is used in any structure (int)
290RBIds           \            unique Ids generated upon creation of each rigid body (dict)
291\           Vector           Ids for each Vector rigid body (list)
292\           Residue          Ids for each Residue rigid body (list)
293==========  ===============  ====================================================
294
295Space Group Objects
296-------------------
297
298.. _SGData_table:
299
300.. index::
301   single: Space Group Data description
302   single: Data object descriptions; Space Group Data
303
304Space groups are interpreted by :func:`GSASIIspc.SpcGroup`
305and the information is placed in a SGdata object
306which is a dict with these keys:
307
308.. tabularcolumns:: |l|p{4.5in}|
309
310==========  ====================================================
311  key         explanation
312==========  ====================================================
313SpGrp       space group symbol (str)
314Laue        one of the following 14 Laue classes:
315            -1, 2/m, mmm, 4/m, 4/mmm, 3R,
316            3mR, 3, 3m1, 31m, 6/m, 6/mmm, m3, m3m (str)
317SGInv       True if centrosymmetric, False if not (bool)
318SGLatt      Lattice centering type. Will be one of
319            P, A, B, C, I, F, R (str)
320SGUniq      unique axis if monoclinic. Will be
321            a, b, or c for monoclinic space groups.
322            Will be blank for non-monoclinic. (str)
323SGCen       Symmetry cell centering vectors. A (n,3) np.array
324            of centers. Will always have at least one row:
325            ``np.array([[0, 0, 0]])``
326SGOps       symmetry operations as a list of form
327            ``[[M1,T1], [M2,T2],...]``
328            where :math:`M_n` is a 3x3 np.array
329            and :math:`T_n` is a length 3 np.array.
330            Atom coordinates are transformed where the
331            Asymmetric unit coordinates [X is (x,y,z)]
332            are transformed using
333            :math:`X^\prime = M_n*X+T_n`
334SGSys       symmetry unit cell: type one of
335            'triclinic', 'monoclinic', 'orthorhombic',
336            'tetragonal', 'rhombohedral', 'trigonal',
337            'hexagonal', 'cubic' (str)
338SGPolax     Axes for space group polarity. Will be one of
339            '', 'x', 'y', 'x y', 'z', 'x z', 'y z',
340            'xyz'. In the case where axes are arbitrary
341            '111' is used (P 1, and ?).
342==========  ====================================================
343
344Atom Records
345------------
346
347.. _Atoms_table:
348
349.. index::
350   single: Atoms record description
351   single: Data object descriptions; Atoms record
352
353
354If ``phasedict`` points to the phase information in the data tree, then
355atoms are contained in a list of atom records (list) in
356``phasedict['Atoms']``. Also needed to read atom information
357are four pointers, ``cx,ct,cs,cia = phasedict['General']['atomPtrs']``,
358which define locations in the atom record, as shown below. Items shown are
359always present; additional ones for macromolecular phases are marked 'mm'
360
361.. tabularcolumns:: |l|p{4.5in}|
362
363==============   ====================================================
364location         explanation
365==============   ====================================================
366ct-4              mm - residue number (str)
367ct-3              mm - residue name (e.g. ALA) (str)
368ct-2              mm - chain label (str)
369ct-1              atom label (str)
370ct                atom type (str)
371ct+1              refinement flags; combination of 'F', 'X', 'U' (str)
372cx,cx+1,cx+2      the x,y and z coordinates (3 floats)
373cs                site symmetry (str)
374cs+1              site multiplicity (int)
375cia               ADP flag: Isotropic ('I') or Anisotropic ('A')
376cia+1             Uiso (float)
377cia+2...cia+6     U11, U22, U33, U12, U13, U23 (6 floats)
378atom[-1]                unique atom identifier (int)
379==============   ====================================================
380
381Drawing Atom Records
382--------------------
383
384.. _Drawing_atoms_table:
385
386.. index::
387   single: Drawing atoms record description
388   single: Data object descriptions; Drawing atoms record
389
390
391If ``phasedict`` points to the phase information in the data tree, then
392drawing atoms are contained in a list of drawing atom records (list) in
393``phasedict['Drawing']['Atoms']``. Also needed to read atom information
394are four pointers, ``cx,ct,cs,ci = phasedict['Drawing']['AtomPtrs']``,
395which define locations in the atom record, as shown below. Items shown are
396always present; additional ones for macromolecular phases are marked 'mm'
397
398.. tabularcolumns:: |l|p{4.5in}|
399
400==============   ====================================================
401location         explanation
402==============   ====================================================
403ct-4              mm - residue number (str)
404ct-3              mm - residue name (e.g. ALA) (str)
405ct-2              mm - chain label (str)
406ct-1              atom label (str)
407ct                atom type (str)
408cx,cx+1,cx+2      the x,y and z coordinates (3 floats)
409cs-1              Sym Op symbol; sym. op number + unit cell id (e.g. '1,0,-1') (str)
410cs                atom drawing style; e.g. 'balls & sticks' (str)
411cs+1              atom label style (e.g. 'name') (str)
412cs+2              atom color (RBG triplet) (int)
413cs+3              ADP flag: Isotropic ('I') or Anisotropic ('A')
414cs+4              Uiso (float)
415cs+5...cs+11      U11, U22, U33, U12, U13, U23 (6 floats)
416ci                unique atom identifier; matches source atom Id in Atom Records (int)
417==============   ====================================================
418
419Powder Diffraction Tree Items
420-----------------------------
421
422.. _Powder_table:
423
424.. index::
425   single: Powder data object description
426   single: Data object descriptions; Powder Data
427
428Every powder diffraction histogram is stored in the GSAS-II data tree
429with a top-level entry named beginning with the string "PWDR ". The
430diffraction data for that information are directly associated with
431that tree item and there are a series of children to that item. The
432routine :func:`~GSASII.GSASII.GetUsedHistogramsAndPhasesfromTree` will
433load this information into a dictionary where the child tree name is
434used as a key, and the information in the main entry is assigned
435a key of ``Data``, as outlined below.
436
437.. tabularcolumns:: |l|l|p{4in}|
438
439======================  ===============  ====================================================
440  key                      sub-key        explanation
441======================  ===============  ====================================================
442Limits                       \            A list of two two element lists, as [[Ld,Hd],[L,H]]
443                                          where L and Ld are the current and default lowest
444                                          two-theta value to be used and
445                                          where H and Hd are the current and default highest
446                                          two-theta value to be used.
447Reflection Lists              \           A dict with an entry for each phase in the
448                                          histogram. The contents of each dict item
449                                          is a dict containing reflections, as described in
450                                          the :ref:`Powder Reflections <PowderRefl_table>`
451                                          description.
452Instrument Parameters         \           A list containing two dicts where the possible
453                                          keys in each dict are listed below. The value
454                                          for each item is a list containing three values:
455                                          the initial value, the current value and a
456                                          refinement flag which can have a value of
457                                          True, False or 0 where 0 indicates a value that
458                                          cannot be refined. The first and second
459                                          values are floats unless otherwise noted.
460                                          Items in the first dict are noted as [1]
461\                         Lam             Specifies a wavelength in Angstroms [1]
462\                         Lam1            Specifies the primary wavelength in
463                                          Angstrom, when an alpha1, alpha2
464                                          source is used [1]
465\                         Lam2            Specifies the secondary wavelength in
466                                          Angstrom, when an alpha1, alpha2
467                                          source is used [1]
468                          I(L2)/I(L1)     Ratio of Lam2 to Lam1 [1]           
469\                         Type            Histogram type (str) [1]:
470                                           * 'PXC' for constant wavelength x-ray
471                                           * 'PNC' for constant wavelength neutron
472                                           * 'PNT' for time of flight neutron
473\                         Zero            Two-theta zero correction in *degrees* [1]
474\                         Azimuth         Azimuthal setting angle for data recorded
475                                          with differing setting angles [1]
476\                         U, V, W         Cagliotti profile coefficients
477                                          for Gaussian instrumental broadening, where the
478                                          FWHM goes as
479                                          :math:`U \\tan^2\\theta + V \\tan\\theta + W` [1]
480\                         X, Y            Cauchy (Lorentzian) instrumental broadening
481                                          coefficients [1]
482\                         SH/L            Variant of the Finger-Cox-Jephcoat asymmetric
483                                          peak broadening ratio. Note that this is the
484                                          average between S/L and H/L where S is
485                                          sample height, H is the slit height and
486                                          L is the goniometer diameter. [1]
487\                         Polariz.        Polarization coefficient. [1]
488wtFactor                      \           A weighting factor to increase or decrease
489                                          the leverage of data in the histogram (float).
490                                          A value of 1.0 weights the data with their
491                                          standard uncertainties and a larger value
492                                          increases the weighting of the data (equivalent
493                                          to decreasing the uncertainties).
494Sample Parameters             \           Specifies a dict with parameters that describe how
495                                          the data were collected, as listed
496                                          below. Refinable parameters are a list containing
497                                          a float and a bool, where the second value
498                                          specifies if the value is refined, otherwise
499                                          the value is a float unless otherwise noted.
500\                         Scale           The histogram scale factor (refinable)
501\                         Absorption      The sample absorption coefficient as
502                                          :math:`\\mu r` where r is the radius
503                                          (refinable).
504\                         DisplaceX,      Sample displacement from goniometer center
505                          DisplaceY       where Y is along the beam direction and
506                                          X is perpendicular. Units are :math:`\\mu m`
507                                          (refinable).
508\                         Phi, Chi,       Goniometer sample setting angles, in degrees.
509                          Omega
510\                         Gonio. radius   Radius of the diffractometer in mm
511\                         InstrName       A name for the instrument, used in preparing
512                                          a CIF (str).
513\                         Force,          Variables that describe how the measurement
514                          Temperature,    was performed. Not used directly in
515                          Humidity,       any computations.
516                          Pressure,
517                          Voltage
518\                         ranId           The random-number Id for the histogram
519                                          (same value as where top-level key is ranId)
520\                         Type            Type of diffraction data, may be 'Debye-Scherrer'
521                                          or 'Bragg-Brentano' (str).
522\                         Diffuse         not in use?
523hId                           \           The number assigned to the histogram when
524                                          the project is loaded or edited (can change)
525ranId                         \           A random number id for the histogram
526                                          that does not change
527Background                    \           The background is stored as a list with where
528                                          the first item in the list is list and the second
529                                          item is a dict. The list contains the background
530                                          function and its coefficients; the dict contains
531                                          Debye diffuse terms and background peaks.
532                                          (TODO: this needs to be expanded.)
533Data                          \           The data consist of a list of 6 np.arrays
534                                          containing in order:
535
536                                           1. the x-postions (two-theta in degrees),
537                                           2. the intensity values (Yobs),
538                                           3. the weights for each Yobs value
539                                           4. the computed intensity values (Ycalc)
540                                           5. the background values
541                                           6. Yobs-Ycalc
542======================  ===============  ====================================================
543
544Powder Reflection Data Structure
545--------------------------------
546
547.. _PowderRefl_table:
548
549.. index::
550   single: Powder reflection object description
551   single: Data object descriptions; Powder Reflections
552   
553For every phase in a histogram, the ``Reflection Lists`` value is a dict
554one element of which is `'RefList'`, which is a np.array containing
555reflections. The columns in that array are documented below.
556
557==========  ====================================================
558  index         explanation
559==========  ====================================================
560 0,1,2       h,k,l (float)
561 3           multiplicity
562 4           d-space, Angstrom
563 5           pos, two-theta
564 6           sig, Gaussian width
565 7           gam, Lorenzian width
566 8           :math:`F_{obs}^2`
567 9           :math:`F_{calc}^2`
568 10          reflection phase, in degrees
569 11          intensity correction for reflection, this times
570             :math:`F_{obs}^2` or :math:`F_{calc}^2` gives Iobs or Icalc
571==========  ====================================================
572
573Single Crystal Tree Items
574-------------------------
575
576.. _Xtal_table:
577
578.. index::
579   single: Single Crystal data object description
580   single: Data object descriptions; Single crystal data
581
582Every single crystal diffraction histogram is stored in the GSAS-II data tree
583with a top-level entry named beginning with the string "HKLF ". The
584diffraction data for that information are directly associated with
585that tree item and there are a series of children to that item. The
586routine :func:`~GSASII.GSASII.GetUsedHistogramsAndPhasesfromTree` will
587load this information into a dictionary where the child tree name is
588used as a key, and the information in the main entry is assigned
589a key of ``Data``, as outlined below.
590
591.. tabularcolumns:: |l|l|p{4in}|
592
593======================  ===============  ====================================================
594  key                      sub-key        explanation
595======================  ===============  ====================================================
596Data
597                                          A dict that contains the
598                                          reflection table,
599                                          as described in the
600                                          :ref:`Single Crystal Reflections
601                                          <XtalRefl_table>`
602                                          description.
603
604Instrument Parameters         \           A list containing two dicts where the possible
605                                          keys in each dict are listed below. The value
606                                          for most items is a list containing two values:
607                                          the initial value, the current value.
608                                          The first and second
609                                          values are floats unless otherwise noted.
610\                         Lam             Specifies a wavelength in Angstroms (two floats)
611\                         Type            Histogram type (two str values):
612                                           * 'SXC' for constant wavelength x-ray
613                                           * 'SNC' for constant wavelength neutron
614                                           * 'SNT' for time of flight neutron
615\                         InstrName       A name for the instrument, used in preparing
616                                          a CIF (str).
617
618wtFactor                      \           A weighting factor to increase or decrease
619                                          the leverage of data in the histogram (float).
620                                          A value of 1.0 weights the data with their
621                                          standard uncertainties and a larger value
622                                          increases the weighting of the data (equivalent
623                                          to decreasing the uncertainties).
624
625hId                           \           The number assigned to the histogram when
626                                          the project is loaded or edited (can change)
627======================  ===============  ====================================================
628
629Single Crystal Reflection Data Structure
630----------------------------------------
631
632.. _XtalRefl_table:
633
634.. index::
635   single: Single Crystal reflection object description
636   single: Data object descriptions; Single Crystal Reflections
637   
638For every simgle crystal a histogram, the ``'Data'`` item contains
639the structure factors as an np.array in item `'RefList'`.
640The columns in that array are documented below.
641
642==========  ====================================================
643  index         explanation
644==========  ====================================================
645 0,1,2       h,k,l (float)
646 3           multiplicity
647 4           d-space, Angstrom
648 5           :math:`F_{obs}^2`
649 6           :math:`\sigma(F_{obs}^2)`
650 7           :math:`F_{calc}^2`
651 8           :math:`F_{obs}^2T`
652 9           :math:`F_{calc}^2T`
653 10          reflection phase, in degrees
654 11          intensity correction for reflection, this times
655             :math:`F_{obs}^2` or :math:`F_{calc}^2`
656             gives Iobs or Icalc
657==========  ====================================================
658
659
660*Classes and routines*
661----------------------
662
663'''
664import GSASIIpath
665GSASIIpath.SetVersionNumber("$Revision: 1129 $")
666
667def LoadHistogramIDs(histList,idList):
668    '''Save the Id values for a series of histograms'''
669    VarName.IDdict['hists'] = {}
670    for h,i in zip(histList,idList):
671        VarName.IDdict['hists'][i] = h
672
673def LoadPhaseIDs(self):
674    pass
675
676class VarName(object):
677    '''Defines a GSAS-II variable either using the phase/atom/histogram
678    unique Id numbers or using a character string that specifies
679    variables by phase/atom/histogram number (which can change).
680    Note that :func:`LoadID` should be used to (re)load the current Ids
681    before creating or later using the VarName object.
682
683    A :class:`VarName` object can be created with a single parameter:
684   
685    :param str varname: a single value can be used to create a :class:`VarName`
686      object. The string must be of form "p:h:var" or "p:h:var:a", where
687
688     * p is the phase number (which may be left blank);
689     * h is the histogram number (which may be left blank);
690     * a is the atom number (which may be left blank in which case the third colon is omitted).
691
692    Alternately, a :class:`VarName` object can be created with exactly four positional parameters:
693
694    :param int phasenum: The number for the phase
695    :param int histnum: The number for the histogram
696    :param str varname: a single value can be used to create a :class:`VarName`
697    :param int atomnum: The number for the atom
698   
699    '''
700    import re
701    IDdict = {}
702    IDdict['phases'] = {}
703    IDdict['hists'] = {}
704    IDdict['atoms'] = {}
705    # This dictionary lists descriptions for GSAS-II variables.
706    # Note that keys may contain regular expressions, where '[xyz]'
707    # matches 'x' 'y' or 'z' (equivalently '[x-z]' describes this as range of values).
708    # '.*' matches any string
709    VarDesc = {
710        # Phase vars (p::<var>)
711        'A[0-5]' : 'Reciprocal metric tensor component',
712        'Vol' : 'Unit cell volume????',
713        # Atom vars (p::<var>:a)
714        'dA[xyz]' : 'change to atomic position',
715        'AUiso':'Atomic isotropic displacement parameter',
716        'AU[123][123]':'Atomic anisotropic displacement parameter',
717        'AFrac': 'Atomic occupancy parameter',
718        # Hist & Phase (HAP) vars (p:h:<var>)
719        'Bab[AU]': 'Babinet solvent scattering coef.',
720        'D[123][123]' : 'Anisotropic strain coef.',
721        'Extinction' : 'Extinction coef.',
722        'MD' : 'March-Dollase coef.',
723        'Mustrain;.*' : 'Microstrain coef.',
724        'Scale' : 'Phase scale factor',
725        'Size;.*' : 'Crystallite size value',
726        'eA' : '?',
727        #Histogram vars (:h:<var>)
728        'Absorption' : 'Absorption coef.',
729        'Displace[XY]' : 'Debye-Scherrer sample displacement',
730        'Lam' : 'Wavelength',
731        'Polariz' : 'Polarization correction',
732        'SH/L' : 'FCJ peak asymmetry correction',
733        'Scale' : 'Histogram scale factor',
734        '[UVW]' : 'Gaussian instrument broadening',
735        '[XY]' : 'Cauchy instrument broadening',
736        'Zero' : 'Debye-Scherrer zero correction',
737        'nDebye' : 'Debye model background corr. terms',
738        'nPeaks' : 'Fixed peak  background corr. terms',
739        # Global vars (::<var>)
740        }
741    def __init__(self,*args):
742        self.phase = None
743        self.histogram = None
744        self.name = ''
745        self.atom = None
746        if len(args) == 1:
747            lst = args[0].split(':')
748            raise Exception, "Need to look up IDs"
749            self.phase = lst[0]
750            self.histogram = lst[1]
751            self.name = lst[2]
752            if len(lst) > 3:
753                self.atom = lst[3]
754        elif len(args) == 4:
755            self.phase = args[0]
756            self.histogram = args[1]
757            self.name = args[2]
758            self.atom = args[3]
759        else:
760            raise Exception,"Incorrectly called GSAS-II parameter name"
761
762    def __str__(self):
763        return self.name()
764
765    def name(self):
766        '''Formats the GSAS-II variable name as a "traditional" string (p:h:<var>:a)
767
768        :returns: the variable name as a str
769        '''
770        def _fmt(val):
771            if val is None:
772                return ""
773            return str(val)
774        return _fmt(self.phase) + ":" + _fmt(self.histogram) + _fmt(self.name) + _fmt(self.atom)
775
776    def __repr__(self):
777        '''Return the detailed contents of the object
778        '''
779        s = ""
780        if self.phase:
781            s += "Phase: " + str(self.phase) + "; "
782
783        if self.histogram:
784            s += "Histogram: " + str(self.histogram) + "; "
785           
786        if self.name:
787            s += "Variable name: " + str(self.name) + "; "
788
789        if self.atom:
790            s += "Atom number: " + str(self.atom) + "; "
791
792        return s+"("+self.name()+")"
793
794    def getDescr(self):
795        '''Return a short description for a GSAS-II variable
796
797        :returns: a short description or 'no definition' if not found
798        '''
799        # iterating over uncompiled regular expressions is not terribly fast,
800        # but this routine should not need to be all that speedy
801        for key in self.VarDesc:
802            if re.match(key, self.name):
803                return self.VarDesc[key]
804        return 'no definition'
805
806    def getDescr(self):
807        '''Return a short description for a GSAS-II variable
808
809        :returns: a short description or 'no definition' if not found
810        '''
811        # iterating over uncompiled regular expressions is not terribly fast,
812        # but this routine should not need to be all that speedy
813        for key in self.VarDesc:
814            if re.match(key, self.name):
815                return self.VarDesc[key]
816        return 'no definition'
817
818    def fullDescr(self):
819        '''Return a longer description for a GSAS-II variable
820
821        :returns: a short description or 'no definition' if not found
822        '''
823        # iterating over uncompiled regular expressions is not terribly fast,
824        # but this routine should not need to be all that speedy
825        str = self.name()
826       
827        for key in self.VarDesc:
828            if re.match(key, self.name):
829                return self.VarDesc[key]
830        return 'no definition'
831
832
833    def _show(self):
834        'For testing, shows the current lookup table'
835        print 'phases', self.IDdict['phases']
836        print 'hists', self.IDdict['hists']
837        print 'atomDict', self.IDdict['atoms']
838
Note: See TracBrowser for help on using the repository browser.