source: branch/2frame/GSASIIobj.py @ 2994

Last change on this file since 2994 was 2994, checked in by odonnell, 4 years ago

revised HAP parameter docs

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 127.7 KB
Line 
1# -*- coding: utf-8 -*-
2#GSASIIobj - data objects for GSAS-II
3########### SVN repository information ###################
4# $Date: 2017-08-10 21:04:56 +0000 (Thu, 10 Aug 2017) $
5# $Author: odonnell $
6# $Revision: 2994 $
7# $URL: branch/2frame/GSASIIobj.py $
8# $Id: GSASIIobj.py 2994 2017-08-10 21:04:56Z odonnell $
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, as well
16as provides misc. support routines.
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 (used for externally
80   generated constraints)
81 * <varyflag> is True or False for `New variable` (``constype=f``) constraints
82   or is None. This will be implemented in the future to indicate if these variables
83   should be refined.
84 * <constype> is one of four letters, 'e', 'c', 'h', 'f' that determines the type of constraint:
85
86    * 'e' defines a set of equivalent variables. Only the first variable is refined (if the
87      appropriate refine flag is set) and and all other equivalent variables in the list
88      are generated from that variable, using the appropriate multipliers.
89    * 'c' defines a constraint equation of form,
90      :math:`m_1 \\times var_1 + m_2 \\times var_2 + ... = c`
91    * 'h' defines a variable to hold (not vary). Any variable on this list is not varied,
92      even if its refinement flag is set. Only one [mult,var] pair is allowed in a hold
93      constraint and the mult value is ignored.
94      This is of particular value when needing to hold one or more variables where a
95      single flag controls a set of variables such as, coordinates,
96      the reciprocal metric tensor or anisotropic displacement parameter.
97    * 'f' defines a new variable (function) according to relationship
98      :math:`newvar = m_1 \\times var_1 + m_2 \\times var_2 + ...`
99
100Covariance Tree Item
101--------------------
102
103.. _Covariance_table:
104
105.. index::
106   single: Covariance description
107   single: Data object descriptions; Covariance
108
109The Covariance tree item has results from the last least-squares run. They
110are stored in a dict with these keys:
111
112.. tabularcolumns:: |l|l|p{4in}|
113
114=============  ===============  ====================================================
115  key            sub-key        explanation
116=============  ===============  ====================================================
117newCellDict    \                dict with lattice parameters computed by
118                                :func:`GSASIIstrMath.GetNewCellParms` (dict)
119title          \                Name of gpx file(?) (str)
120variables      \                Values for all N refined variables
121                                (list of float values, length N,
122                                ordered to match varyList)
123sig            \                Uncertainty values for all N refined variables
124                                (list of float values, length N,
125                                ordered to match varyList)
126varyList       \                List of directly refined variables
127                                (list of str values, length N)
128newAtomDict    \                dict with atom position values computed in
129                                :func:`GSASIIstrMath.ApplyXYZshifts` (dict)
130Rvals          \                R-factors, GOF, Marquardt value for last
131                                refinement cycle (dict)
132\              Nobs             Number of observed data points (int)
133\              Rwp              overall weighted profile R-factor (%, float)
134\              chisq            sum[w*(Iobs-Icalc)**2] for all data
135                                note this is not the reduced chi squared (float)
136\              lamMax           Marquardt value applied to Hessian diagonal
137                                (float)
138\              GOF              The goodness-of-fit, aka square root of
139                                the reduced chi squared. (float)
140covMatrix      \                The (NxN) covVariance matrix (np.array)
141=============  ===============  ====================================================
142
143Phase Tree Items
144----------------
145
146.. _Phase_table:
147
148.. index::
149   single: Phase object description
150   single: Data object descriptions; Phase
151
152Phase information is stored in the GSAS-II data tree as children of the
153Phases item in a dict with keys:
154
155.. tabularcolumns:: |l|l|p{4in}|
156
157==========  ===============  ====================================================
158  key         sub-key        explanation
159==========  ===============  ====================================================
160General         \            Overall information for the phase (dict)
161  \         AtomPtrs         list of four locations to use to pull info
162                             from the atom records (list)
163  \         F000X            x-ray F(000) intensity (float)
164  \         F000N            neutron F(000) intensity (float)
165  \         Mydir            directory of current .gpx file (str)
166  \         MCSA controls    Monte Carlo-Simulated Annealing controls (dict)
167  \         Cell             List with 8 items: cell refinement flag (bool)
168                             a, b, c, (Angstrom, float)
169                             alpha, beta & gamma (degrees, float)
170                             volume (A^3, float)
171  \         Type             'nuclear' or 'macromolecular' for now (str)
172  \         Map              dict of map parameters
173  \         SH Texture       dict of spherical harmonic preferred orientation
174                             parameters
175  \         Isotope          dict of isotopes for each atom type
176  \         Isotopes         dict of scattering lengths for each isotope
177                             combination for each element in phase 
178  \         Name             phase name (str)
179  \         SGData           Space group details as a :ref:`space group (SGData) object <SGData_table>`
180                             as defined in :func:`GSASIIspc.SpcGroup`.
181  \         Pawley neg wt    Restraint value for negative Pawley intensities
182                             (float)
183  \         Flip             dict of Charge flip controls
184  \         Data plot type   data plot type ('Mustrain', 'Size' or
185                             'Preferred orientation') for powder data (str)
186  \         Mass             Mass of unit cell contents in g/mol
187  \         POhkl            March-Dollase preferred orientation direction
188  \         Z                dict of atomic numbers for each atom type
189  \         vdWRadii         dict of van der Waals radii for each atom type
190  \         Color            Colors for atoms (list of (r,b,g) triplets)
191  \         AtomTypes        List of atom types
192  \         AtomMass         List of masses for atoms
193  \         doPawley         Flag for Pawley intensity extraction (bool)
194  \         NoAtoms          Number of atoms per unit cell of each type (dict)
195  \         Pawley dmin      maximum Q (as d-space) to use for Pawley
196                             extraction (float)
197  \         BondRadii        Default radius for each atom used to compute
198                             interatomic distances (list of floats)
199  \         AngleRadii       Default radius for each atom used to compute
200                             interatomic angles (list of floats)
201  \         DisAglCtls       Dict with distance/angle search controls,
202                             which has keys 'Name', 'AtomTypes',
203                             'BondRadii', 'AngleRadii' which are as above
204                             except are possibly edited. Also contains
205                             'Factors', which is a 2 element list with
206                             a multiplier for bond and angle search range
207                             [typically (0.85,0.85)].
208ranId           \            unique random number Id for phase (int)
209pId             \            Phase Id number for current project (int).
210Atoms           \            Atoms in phase as a list of lists. The outer list
211                             is for each atom, the inner list contains varying
212                             items depending on the type of phase, see
213                             the :ref:`Atom Records <Atoms_table>` description.
214                             (list of lists)
215Drawing         \            Display parameters (dict)
216\           ballScale        Size of spheres in ball-and-stick display (float)
217\           bondList         dict with bonds
218\           contourLevel     map contour level in e/A^3 (float)
219\           showABC          Flag to show view point triplet (bool). True=show.
220\           viewDir          cartesian viewing direction (np.array with three
221                             elements)
222\           Zclip            clipping distance in A (float)
223\           backColor        background for plot as and R,G,B triplet
224                             (default = [0, 0, 0], black).
225                             (list with three atoms)
226\           selectedAtoms    List of selected atoms (list of int values)
227\           showRigidBodies  Flag to highlight rigid body placement
228\           sizeH            Size ratio for H atoms (float)
229\           bondRadius       Size of binds in A (float)
230\           atomPtrs         positions of x, type, site sym, ADP flag in Draw Atoms (list)
231\           viewPoint        list of lists. First item in list is [x,y,z]
232                             in fractional coordinates for the center of
233                             the plot. Second item list of previous & current
234                             atom number viewed (may be [0,0])
235\           showHydrogen     Flag to control plotting of H atoms.
236\           unitCellBox      Flag to control display of the unit cell.
237\           ellipseProb      Probability limit for display of thermal
238                             ellipsoids in % (float).
239\           vdwScale         Multiplier of van der Waals radius for
240                             display of vdW spheres.
241\           Atoms            A list of lists with an entry for each atom
242                             that is plotted.
243\           Zstep            Step to de/increase Z-clip (float)
244\           Quaternion       Viewing quaternion (4 element np.array)
245\           radiusFactor     Distance ratio for searching for bonds. ? Bonds
246                             are located that are within r(Ra+Rb) and (Ra+Rb)/r
247                             where Ra and Rb are the atomic radii.
248\           oldxy            previous view point (list with two floats)
249\           cameraPos        Viewing position in A for plot (float)
250\           depthFog         True if use depthFog on plot - set currently as False (bool)
251RBModels        \            Rigid body assignments (note Rigid body definitions
252                             are stored in their own main top-level tree entry.)
253Pawley ref      \            Pawley reflections
254Histograms      \            A dict of dicts. The key for the outer dict is
255                             the histograms tied to this phase. The inner
256                             dict contains the combined phase/histogram
257                             parameters for items such as scale factors,
258                             size and strain parameters. The following are the
259                             keys to the inner dict. (dict)
260\           Babinet          For protein crystallography. Dictionary with two
261                             entries, 'BabA', 'BabU'
262\           Extinction       Extinction parameter (list of float, bool)
263\           HStrain          Hydrostatic strain. List of two lists. The first is
264                             a list of the HStrain parameters (1, 2, 3, 4, or 6
265                             depending on unit cell), the second is a list of boolean
266                             refinement parameters (same length)
267\           Histogram        The name of the associated histogram (str)
268\           LeBail           Flag for LeBail extraction (bool)
269\           Mustrain         List of microstrain parameters, in order:
270
271                               0. Type, one of u'generalized', u'isotropic',
272                                  u'uniaxial'
273                               1. Isotropic/uniaxial parameters - list of 3 floats
274                               2. Refinement flags - list of 3 bools
275                               3. Microstrain axis - list of 3 ints, [h, k, l]
276                               4. Generalized mustrain parameters - list of 2-6
277                                  floats, depending on space group
278                               5. Generalized refinement flags - list of bools,
279                                  corresponding to the parameters of (4)
280\           Pref.Ori.        Preferred Orientation. List of eight parameters.
281                             Items marked SH are only used for Spherical Harmonics.
282
283                               0. Type, 'MD' for March-Dollase or 'SH' for
284                                  Spherical Harmonics
285                               1. Value, float
286                               2. Refinement flag, bool
287                               3. Preferred direction, list of ints, [h, k, l]
288                               4. SH - number of terms, int
289                               5. SH - dict
290                               6. SH - list
291                               7. SH - float
292\           Scale            Phase fraction, list of [float, bool].
293\           Show             bool
294\           Use              bool
295\           newLeBail        Whether to perform a new LeBail extraction
296MCSA            \            Monte-Carlo simulated annealing parameters (dict)
297\           
298==========  ===============  ====================================================
299
300Rigid Body Objects
301------------------
302
303.. _RBData_table:
304
305.. index::
306   single: Rigid Body Data description
307   single: Data object descriptions; Rigid Body Data
308   
309Rigid body descriptions are available for two types of rigid bodies: 'Vector'
310and 'Residue'. Vector rigid bodies are developed by a sequence of translations each
311with a refinable magnitude and Residue rigid bodies are described as Cartesian coordinates
312with defined refinable torsion angles.
313
314.. tabularcolumns:: |l|l|p{4in}|
315
316==========  ===============  ====================================================
317  key         sub-key        explanation
318==========  ===============  ====================================================
319Vector      RBId             vector rigid bodies (dict of dict)
320\           AtInfo           Drad, Color: atom drawing radius & color for each atom type (dict)
321\           RBname           Name assigned by user to rigid body (str)
322\           VectMag          vector magnitudes in A (list)
323\           rbXYZ            Cartesian coordinates for Vector rigid body (list of 3 float)
324\           rbRef            3 assigned reference atom nos. in rigid body for origin
325                             definition, use center of atoms flag (list of 3 int & 1 bool)
326\           VectRef          refinement flags for VectMag values (list of bool)
327\           rbTypes          Atom types for each atom in rigid body (list of str)
328\           rbVect           Cartesian vectors for each translation used to build rigid body (list of lists)
329\           useCount         Number of times rigid body is used in any structure (int)
330Residue     RBId             residue rigid bodies (dict of dict)
331\           AtInfo           Drad, Color: atom drawing radius & color for each atom type(dict)
332\           RBname           Name assigned by user to rigid body (str)
333\           rbXYZ            Cartesian coordinates for Residue rigid body (list of 3 float)
334\           rbTypes          Atom types for each atom in rigid body (list of str)
335\           atNames          Names of each atom in rigid body (e.g. C1,N2...) (list of str)
336\           rbRef            3 assigned reference atom nos. in rigid body for origin
337                             definition, use center of atoms flag (list of 3 int & 1 bool)
338\           rbSeq            Orig,Piv,angle,Riding (list): definition of internal rigid body
339                             torsion; origin atom (int), pivot atom (int), torsion angle (float),
340                             riding atoms (list of int)
341\           SelSeq           [int,int] used by SeqSizer to identify objects
342\           useCount         Number of times rigid body is used in any structure (int)
343RBIds           \            unique Ids generated upon creation of each rigid body (dict)
344\           Vector           Ids for each Vector rigid body (list)
345\           Residue          Ids for each Residue rigid body (list)
346==========  ===============  ====================================================
347
348Space Group Objects
349-------------------
350
351.. _SGData_table:
352
353.. index::
354   single: Space Group Data description
355   single: Data object descriptions; Space Group Data
356
357Space groups are interpreted by :func:`GSASIIspc.SpcGroup`
358and the information is placed in a SGdata object
359which is a dict with these keys:
360
361.. tabularcolumns:: |l|p{4.5in}|
362
363==========  ====================================================
364  key         explanation
365==========  ====================================================
366SpGrp       space group symbol (str)
367Laue        one of the following 14 Laue classes:
368            -1, 2/m, mmm, 4/m, 4/mmm, 3R,
369            3mR, 3, 3m1, 31m, 6/m, 6/mmm, m3, m3m (str)
370SGInv       True if centrosymmetric, False if not (bool)
371SGLatt      Lattice centering type. Will be one of
372            P, A, B, C, I, F, R (str)
373SGUniq      unique axis if monoclinic. Will be
374            a, b, or c for monoclinic space groups.
375            Will be blank for non-monoclinic. (str)
376SGCen       Symmetry cell centering vectors. A (n,3) np.array
377            of centers. Will always have at least one row:
378            ``np.array([[0, 0, 0]])``
379SGOps       symmetry operations as a list of form
380            ``[[M1,T1], [M2,T2],...]``
381            where :math:`M_n` is a 3x3 np.array
382            and :math:`T_n` is a length 3 np.array.
383            Atom coordinates are transformed where the
384            Asymmetric unit coordinates [X is (x,y,z)]
385            are transformed using
386            :math:`X^\prime = M_n*X+T_n`
387SGSys       symmetry unit cell: type one of
388            'triclinic', 'monoclinic', 'orthorhombic',
389            'tetragonal', 'rhombohedral', 'trigonal',
390            'hexagonal', 'cubic' (str)
391SGPolax     Axes for space group polarity. Will be one of
392            '', 'x', 'y', 'x y', 'z', 'x z', 'y z',
393            'xyz'. In the case where axes are arbitrary
394            '111' is used (P 1, and ?).
395==========  ====================================================
396
397.. _SSGData_table:
398
399.. index::
400   single: Superspace Group Data description
401   single: Data object descriptions; Superspace Group Data
402
403Superspace groups [3+1] are interpreted by :func:`GSASIIspc.SSpcGroup`
404and the information is placed in a SSGdata object
405which is a dict with these keys:
406
407.. tabularcolumns:: |l|p{4.5in}|
408
409==========  ====================================================
410  key         explanation
411==========  ====================================================
412SSpGrp      superspace group symbol extension to space group
413            symbol, accidental spaces removed
414SSGCen      4D cell centering vectors [0,0,0,0] at least
415SSGOps      4D symmetry operations as [M,T] so that M*x+T = x'
416==========  ====================================================
417
418
419Atom Records
420------------
421
422.. _Atoms_table:
423
424.. index::
425   single: Atoms record description
426   single: Data object descriptions; Atoms record
427
428
429If ``phasedict`` points to the phase information in the data tree, then
430atoms are contained in a list of atom records (list) in
431``phasedict['Atoms']``. Also needed to read atom information
432are four pointers, ``cx,ct,cs,cia = phasedict['General']['atomPtrs']``,
433which define locations in the atom record, as shown below. Items shown are
434always present; additional ones for macromolecular phases are marked 'mm'
435
436.. tabularcolumns:: |l|p{4.5in}|
437
438==============   ====================================================
439location         explanation
440==============   ====================================================
441ct-4              mm - residue number (str)
442ct-3              mm - residue name (e.g. ALA) (str)
443ct-2              mm - chain label (str)
444ct-1              atom label (str)
445ct                atom type (str)
446ct+1              refinement flags; combination of 'F', 'X', 'U' (str)
447cx,cx+1,cx+2      the x,y and z coordinates (3 floats)
448cs                site symmetry (str)
449cs+1              site multiplicity (int)
450cia               ADP flag: Isotropic ('I') or Anisotropic ('A')
451cia+1             Uiso (float)
452cia+2...cia+7     U11, U22, U33, U12, U13, U23 (6 floats)
453atom[cia+8]       unique atom identifier (int)
454
455==============   ====================================================
456
457Drawing Atom Records
458--------------------
459
460.. _Drawing_atoms_table:
461
462.. index::
463   single: Drawing atoms record description
464   single: Data object descriptions; Drawing atoms record
465
466
467If ``phasedict`` points to the phase information in the data tree, then
468drawing atoms are contained in a list of drawing atom records (list) in
469``phasedict['Drawing']['Atoms']``. Also needed to read atom information
470are four pointers, ``cx,ct,cs,ci = phasedict['Drawing']['AtomPtrs']``,
471which define locations in the atom record, as shown below. Items shown are
472always present; additional ones for macromolecular phases are marked 'mm'
473
474.. tabularcolumns:: |l|p{4.5in}|
475
476==============   ====================================================
477location         explanation
478==============   ====================================================
479ct-4              mm - residue number (str)
480ct-3              mm - residue name (e.g. ALA) (str)
481ct-2              mm - chain label (str)
482ct-1              atom label (str)
483ct                atom type (str)
484cx,cx+1,cx+2      the x,y and z coordinates (3 floats)
485cs-1              Sym Op symbol; sym. op number + unit cell id (e.g. '1,0,-1') (str)
486cs                atom drawing style; e.g. 'balls & sticks' (str)
487cs+1              atom label style (e.g. 'name') (str)
488cs+2              atom color (RBG triplet) (int)
489cs+3              ADP flag: Isotropic ('I') or Anisotropic ('A')
490cs+4              Uiso (float)
491cs+5...cs+11      U11, U22, U33, U12, U13, U23 (6 floats)
492ci                unique atom identifier; matches source atom Id in Atom Records (int)
493==============   ====================================================
494
495Powder Diffraction Tree Items
496-----------------------------
497
498.. _Powder_table:
499
500.. index::
501   single: Powder data object description
502   single: Data object descriptions; Powder Data
503
504Every powder diffraction histogram is stored in the GSAS-II data tree
505with a top-level entry named beginning with the string "PWDR ". The
506diffraction data for that information are directly associated with
507that tree item and there are a series of children to that item. The
508routines :func:`GSASIIdataGUI.GSASII.GetUsedHistogramsAndPhasesfromTree`
509and :func:`GSASIIstrIO.GetUsedHistogramsAndPhases` will
510load this information into a dictionary where the child tree name is
511used as a key, and the information in the main entry is assigned
512a key of ``Data``, as outlined below.
513
514.. tabularcolumns:: |p{1in}|p{1in}|p{4in}|
515
516======================  ===============  ====================================================
517  key                      sub-key        explanation
518======================  ===============  ====================================================
519Comments                      \           Text strings extracted from the original powder
520                                          data header. These cannot be changed by the user;
521                                          it may be empty.
522Limits                       \            A list of two two element lists, as [[Ld,Hd],[L,H]]
523                                          where L and Ld are the current and default lowest
524                                          two-theta value to be used and
525                                          where H and Hd are the current and default highest
526                                          two-theta value to be used.
527Reflection Lists              \           A dict with an entry for each phase in the
528                                          histogram. The contents of each dict item
529                                          is a dict containing reflections, as described in
530                                          the :ref:`Powder Reflections <PowderRefl_table>`
531                                          description.
532Instrument Parameters         \           A list containing two dicts where the possible
533                                          keys in each dict are listed below. The value
534                                          for each item is a list containing three values:
535                                          the initial value, the current value and a
536                                          refinement flag which can have a value of
537                                          True, False or 0 where 0 indicates a value that
538                                          cannot be refined. The first and second
539                                          values are floats unless otherwise noted.
540                                          Items in the first dict are noted as [1]
541\                         Lam             Specifies a wavelength in Angstroms [1]
542\                         Lam1            Specifies the primary wavelength in
543                                          Angstrom, when an alpha1, alpha2
544                                          source is used [1]
545\                         Lam2            Specifies the secondary wavelength in
546                                          Angstrom, when an alpha1, alpha2
547                                          source is used [1]
548                          I(L2)/I(L1)     Ratio of Lam2 to Lam1 [1]           
549\                         Type            Histogram type (str) [1]:
550                                           * 'PXC' for constant wavelength x-ray
551                                           * 'PNC' for constant wavelength neutron
552                                           * 'PNT' for time of flight neutron
553\                         Zero            Two-theta zero correction in *degrees* [1]
554\                         Azimuth         Azimuthal setting angle for data recorded
555                                          with differing setting angles [1]
556\                         U, V, W         Cagliotti profile coefficients
557                                          for Gaussian instrumental broadening, where the
558                                          FWHM goes as
559                                          :math:`U \\tan^2\\theta + V \\tan\\theta + W` [1]
560\                         X, Y            Cauchy (Lorentzian) instrumental broadening
561                                          coefficients [1]
562\                         SH/L            Variant of the Finger-Cox-Jephcoat asymmetric
563                                          peak broadening ratio. Note that this is the
564                                          average between S/L and H/L where S is
565                                          sample height, H is the slit height and
566                                          L is the goniometer diameter. [1]
567\                         Polariz.        Polarization coefficient. [1]
568wtFactor                      \           A weighting factor to increase or decrease
569                                          the leverage of data in the histogram (float).
570                                          A value of 1.0 weights the data with their
571                                          standard uncertainties and a larger value
572                                          increases the weighting of the data (equivalent
573                                          to decreasing the uncertainties).
574Sample Parameters             \           Specifies a dict with parameters that describe how
575                                          the data were collected, as listed
576                                          below. Refinable parameters are a list containing
577                                          a float and a bool, where the second value
578                                          specifies if the value is refined, otherwise
579                                          the value is a float unless otherwise noted.
580\                         Scale           The histogram scale factor (refinable)
581\                         Absorption      The sample absorption coefficient as
582                                          :math:`\\mu r` where r is the radius
583                                          (refinable). Only valid for Debye-Scherrer geometry.
584\                         SurfaceRoughA   Surface roughness parameter A as defined by
585                                          Surotti,J. Appl. Cryst, 5,325-331, 1972.(refinable -
586                                          only valid for Bragg-Brentano geometry)                                         
587\                         SurfaceRoughB   Surface roughness parameter B (refinable -
588                                          only valid for Bragg-Brentano geometry)                                         
589\                         DisplaceX,      Sample displacement from goniometer center
590                          DisplaceY       where Y is along the beam direction and
591                                          X is perpendicular. Units are :math:`\\mu m`
592                                          (refinable).
593\                         Phi, Chi,       Goniometer sample setting angles, in degrees.
594                          Omega
595\                         Gonio. radius   Radius of the diffractometer in mm
596\                         InstrName       A name for the instrument, used in preparing
597                                          a CIF (str).
598\                         Force,          Variables that describe how the measurement
599                          Temperature,    was performed. Not used directly in
600                          Humidity,       any computations.
601                          Pressure,
602                          Voltage
603\                         ranId           The random-number Id for the histogram
604                                          (same value as where top-level key is ranId)
605\                         Type            Type of diffraction data, may be 'Debye-Scherrer'
606                                          or 'Bragg-Brentano' (str).
607\                         Diffuse         not in use?
608hId                           \           The number assigned to the histogram when
609                                          the project is loaded or edited (can change)
610ranId                         \           A random number id for the histogram
611                                          that does not change
612Background                    \           The background is stored as a list with where
613                                          the first item in the list is list and the second
614                                          item is a dict. The list contains the background
615                                          function and its coefficients; the dict contains
616                                          Debye diffuse terms and background peaks.
617                                          (TODO: this needs to be expanded.)
618Data                          \           The data consist of a list of 6 np.arrays
619                                          containing in order:
620
621                                           0. the x-postions (two-theta in degrees),
622                                           1. the intensity values (Yobs),
623                                           2. the weights for each Yobs value
624                                           3. the computed intensity values (Ycalc)
625                                           4. the background values
626                                           5. Yobs-Ycalc
627======================  ===============  ====================================================
628
629Powder Reflection Data Structure
630--------------------------------
631
632.. _PowderRefl_table:
633
634.. index::
635   single: Powder reflection object description
636   single: Data object descriptions; Powder Reflections
637   
638For every phase in a histogram, the ``Reflection Lists`` value is a dict
639one element of which is `'RefList'`, which is a np.array containing
640reflections. The 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           pos, two-theta
649 6           sig, Gaussian width
650 7           gam, Lorenzian width
651 8           :math:`F_{obs}^2`
652 9           :math:`F_{calc}^2`
653 10          reflection phase, in degrees
654 11          intensity correction for reflection, this times
655             :math:`F_{obs}^2` or :math:`F_{calc}^2` gives Iobs or Icalc
656==========  ====================================================
657
658Single Crystal Tree Items
659-------------------------
660
661.. _Xtal_table:
662
663.. index::
664   single: Single Crystal data object description
665   single: Data object descriptions; Single crystal data
666
667Every single crystal diffraction histogram is stored in the GSAS-II data tree
668with a top-level entry named beginning with the string "HKLF ". The
669diffraction data for that information are directly associated with
670that tree item and there are a series of children to that item. The
671routines :func:`GSASIIdataGUI.GSASII.GetUsedHistogramsAndPhasesfromTree`
672and :func:`GSASIIstrIO.GetUsedHistogramsAndPhases` will
673load this information into a dictionary where the child tree name is
674used as a key, and the information in the main entry is assigned
675a key of ``Data``, as outlined below.
676
677.. tabularcolumns:: |l|l|p{4in}|
678
679======================  ===============  ====================================================
680  key                      sub-key        explanation
681======================  ===============  ====================================================
682Data                          \           A dict that contains the
683                                          reflection table,
684                                          as described in the
685                                          :ref:`Single Crystal Reflections
686                                          <XtalRefl_table>`
687                                          description.
688
689Instrument Parameters         \           A list containing two dicts where the possible
690                                          keys in each dict are listed below. The value
691                                          for most items is a list containing two values:
692                                          the initial value, the current value.
693                                          The first and second
694                                          values are floats unless otherwise noted.
695\                         Lam             Specifies a wavelength in Angstroms (two floats)
696\                         Type            Histogram type (two str values):
697                                           * 'SXC' for constant wavelength x-ray
698                                           * 'SNC' for constant wavelength neutron
699                                           * 'SNT' for time of flight neutron
700\                         InstrName       A name for the instrument, used in preparing
701                                          a CIF (str).
702
703wtFactor                      \           A weighting factor to increase or decrease
704                                          the leverage of data in the histogram (float).
705                                          A value of 1.0 weights the data with their
706                                          standard uncertainties and a larger value
707                                          increases the weighting of the data (equivalent
708                                          to decreasing the uncertainties).
709
710hId                           \           The number assigned to the histogram when
711                                          the project is loaded or edited (can change)
712ranId                         \           A random number id for the histogram
713                                          that does not change
714======================  ===============  ====================================================
715
716Single Crystal Reflection Data Structure
717----------------------------------------
718
719.. _XtalRefl_table:
720
721.. index::
722   single: Single Crystal reflection object description
723   single: Data object descriptions; Single Crystal Reflections
724   
725For every single crystal a histogram, the ``'Data'`` item contains
726the structure factors as an np.array in item `'RefList'`.
727The columns in that array are documented below.
728
729==========  ====================================================
730  index         explanation
731==========  ====================================================
732 0,1,2       h,k,l (float)
733 3           multiplicity
734 4           d-space, Angstrom
735 5           :math:`F_{obs}^2`
736 6           :math:`\sigma(F_{obs}^2)`
737 7           :math:`F_{calc}^2`
738 8           :math:`F_{obs}^2T`
739 9           :math:`F_{calc}^2T`
740 10          reflection phase, in degrees
741 11          intensity correction for reflection, this times
742             :math:`F_{obs}^2` or :math:`F_{calc}^2`
743             gives Iobs or Icalc
744==========  ====================================================
745
746Image Data Structure
747--------------------
748
749.. _Image_table:
750
751.. index::
752   image: Image data object description
753   image: Image object descriptions
754   
755Every 2-dimensional image is stored in the GSAS-II data tree
756with a top-level entry named beginning with the string "IMG ". The
757image data are directly associated with that tree item and there
758are a series of children to that item. The routines :func:`GSASIIdataGUI.GSASII.GetUsedHistogramsAndPhasesfromTree`
759and :func:`GSASIIstrIO.GetUsedHistogramsAndPhases` will
760load this information into a dictionary where the child tree name is
761used as a key, and the information in the main entry is assigned
762a key of ``Data``, as outlined below.
763
764.. tabularcolumns:: |l|l|p{4in}|
765
766======================  ======================  ====================================================
767  key                      sub-key              explanation
768======================  ======================  ====================================================
769Comments                       \                Text strings extracted from the original image data
770                                                header or a metafile. These cannot be changed by 
771                                                the user; it may be empty.                                               
772Image Controls              azmthOff            (float) The offset to be applied to an azimuthal
773                                                value. Accomodates
774                                                detector orientations other than with the detector
775                                                X-axis
776                                                horizontal.
777\                           background image    (list:str,float) The name of a tree item ("IMG ...") that is to be subtracted
778                                                during image integration multiplied by value. It must have the same size/shape as
779                                                the integrated image. NB: value < 0 for subtraction.
780\                           calibrant           (str) The material used for determining the position/orientation
781                                                of the image. The data is obtained from :func:`ImageCalibrants`
782                                                and UserCalibrants.py (supplied by user).
783\                           calibdmin           (float) The minimum d-spacing used during the last calibration run.
784\                           calibskip           (int) The number of expected diffraction lines skipped during the last
785                                                calibration run.
786\                           center              (list:floats) The [X,Y] point in detector coordinates (mm) where the direct beam
787                                                strikes the detector plane as determined by calibration. This point
788                                                does not have to be within the limits of the detector boundaries.
789\                           centerAzm           (bool) If True then the azimuth reported for the integrated slice
790                                                of the image is at the center line otherwise it is at the leading edge.
791\                           color               (str) The name of the colormap used to display the image. Default = 'Paired'.
792\                           cutoff              (float) The minimum value of I/Ib for a point selected in a diffraction ring for
793                                                calibration calculations. See pixLimit for details as how point is found.           
794\                           DetDepth            (float) Coefficient for penetration correction to distance; accounts for diffraction
795                                                ring offset at higher angles. Optionally determined by calibration.
796\                           DetDepthRef         (bool) If True then refine DetDepth during calibration/recalibration calculation.
797\                           distance            (float) The distance (mm) from sample to detector plane.
798\                           ellipses            (list:lists) Each object in ellipses is a list [center,phi,radii,color] where
799                                                center (list) is location (mm) of the ellipse center on the detector plane, phi is the
800                                                rotation of the ellipse minor axis from the x-axis, and radii are the minor & major
801                                                radii of the ellipse. If radii[0] is negative then parameters describe a hyperbola. Color
802                                                is the selected drawing color (one of 'b', 'g' ,'r') for the ellipse/hyperbola.
803\                           edgemin             (float) Not used;  parameter in EdgeFinder code.
804\                           fullIntegrate       (bool) If True then integrate over full 360 deg azimuthal range.
805\                           GonioAngles         (list:floats) The 'Omega','Chi','Phi' goniometer angles used for this image.
806                                                Required for texture calculations.
807\                           invert_x            (bool) If True display the image with the x-axis inverted.
808\                           invert_y            (bool) If True display the image with the y-axis inverted.
809\                           IOtth               (list:floats) The minimum and maximum 2-theta values to be used for integration.
810\                           LRazimuth           (list:floats) The minimum and maximum azimuth values to be used for integration.
811\                           Oblique             (list:float,bool) If True apply a detector absorption correction using the value to the
812                                                intensities obtained during integration.
813\                           outAzimuths         (int) The number of azimuth pie slices.
814\                           outChannels         (int) The number of 2-theta steps.
815\                           pixelSize           (list:ints) The X,Y dimensions (microns) of each pixel.
816\                           pixLimit            (int) A box in the image with 2*pixLimit+1 edges is searched to find the maximum.
817                                                This value (I) along with the minimum (Ib) in the box is reported by :func:`GSASIIimage.ImageLocalMax`
818                                                and subject to cutoff in :func:`GSASIIimage.makeRing`.
819                                                Locations are used to construct rings of points for calibration calcualtions.
820\                           PolaVal             (list:float,bool) If type='SASD' and if True, apply polarization correction to intensities from
821                                                integration using value.
822\                           rings               (list:lists) Each entry is [X,Y,dsp] where X & Y are lists of x,y coordinates around a
823                                                diffraction ring with the same d-spacing (dsp)
824\                           ring                (list) The x,y coordinates of the >5 points on an inner ring
825                                                selected by the user,
826\                           Range               (list) The minimum & maximum values of the image
827\                           rotation            (float) The angle between the x-axis and the vector about which the
828                                                detector is tilted. Constrained to -180 to 180 deg.     
829\                           SampleShape         (str) Currently only 'Cylinder'. Sample shape for Debye-Scherrer experiments; used for absorption
830                                                calculations.
831\                           SampleAbs           (list: float,bool) Value of absorption coefficient for Debye-Scherrer experimnents, flag if True
832                                                to cause correction to be applied.
833\                           setDefault          (bool) If True the use the image controls values for all new images to be read. (might be removed)
834\                           setRings            (bool) If True then display all the selected x,y ring positions (vida supra rings) used in the calibration.           
835\                           showLines           (bool) If True then isplay the integration limits to be used.
836\                           size                (list:int) The number of pixels on the image x & y axes
837\                           type                (str) One of 'PWDR', 'SASD' or 'REFL' for powder, small angle or reflectometry data, respectively.
838\                           tilt                (float) The angle the detector normal makes with the incident beam; range -90 to 90.
839\                           wavelength          (float) Tha radiation wavelength (Angstroms) as entered by the user (or someday obtained from the image header).
840                                               
841Masks                       Arcs                (list: lists) Each entry [2-theta,[azimuth[0],azimuth[1]],thickness] describes an arc mask
842                                                to be excluded from integration
843\                           Frames              (list:lists) Each entry describes the x,y points (3 or more - mm) that describe a frame outside
844                                                of which is excluded from recalibration and integration. Only one frame is allowed.
845\                           Points              (list:lists) Each entry [x,y,radius] (mm) describes an excluded spot on the image to be excluded
846                                                from integration.
847\                           Polygons            (list:lists) Each entry is a list of 3+ [x,y] points (mm) that describe a polygon on the image
848                                                to be excluded from integration.
849\                           Rings               (list: lists) Each entry [2-theta,thickness] describes a ring mask
850                                                to be excluded from integration.
851\                           Thresholds          (list:[tuple,list]) [(Imin,Imax),[Imin,Imax]] This gives lower and upper limits for points on the image to be included
852                                                in integrsation. The tuple is the image intensity limits and the list are those set by the user.   
853                                               
854Stress/Strain               Sample phi          (float) Sample rotation about vertical axis.
855\                           Sample z            (float) Sample translation from the calibration sample position (for Sample phi = 0)
856                                                These will be restricted by space group symmetry; result of strain fit refinement.
857\                           Type                (str) 'True' or 'Conventional': The strain model used for the calculation.
858\                           d-zero              (list:dict) Each item is for a diffraction ring on the image; all items are from the same phase
859                                                and are used to determine the strain tensor.
860                                                The dictionary items are:
861                                                'Dset': (float) True d-spacing for the diffraction ring; entered by the user.
862                                                'Dcalc': (float) Average calculated d-spacing determined from strain coeff.
863                                                'Emat': (list: float) The strain tensor elements e11, e12 & e22 (e21=e12, rest are 0)
864                                                'Esig': (list: float) Esds for Emat from fitting.
865                                                'pixLimit': (int) Search range to find highest point on ring for each data point
866                                                'cutoff': (float) I/Ib cutoff for searching.
867                                                'ImxyObs': (list: lists) [[X],[Y]] observed points to be used for strain calculations.
868                                                'ImtaObs': (list: lists) [[d],[azm]] transformed via detector calibration from ImxyObs.
869                                                'ImtaCalc': (list: lists [[d],[azm]] calculated d-spacing & azimuth from fit.
870                                               
871======================  ======================  ====================================================
872
873Parameter Dictionary
874-------------------------
875
876.. _parmDict_table:
877
878.. index::
879   single: Parameter dictionary
880
881The parameter dictionary contains all of the variable parameters for the refinement.
882The dictionary keys are the name of the parameter (<phase>:<hist>:<name>:<atom>).
883It is prepared in two ways. When loaded from the tree
884(in :meth:`GSASIIdataGUI.GSASII.MakeLSParmDict` and
885:meth:`GSASIIIO.ExportBaseclass.loadParmDict`),
886the values are lists with two elements: ``[value, refine flag]``
887
888When loaded from the GPX file (in
889:func:`GSASIIstrMain.Refine` and :func:`GSASIIstrMain.SeqRefine`), the value in the
890dict is the actual parameter value (usually a float, but sometimes a
891letter or string flag value (such as I or A for iso/anisotropic).
892
893
894*Classes and routines*
895----------------------
896
897'''
898import re
899import imp
900import random as ran
901import sys
902import os.path as ospath
903import cPickle
904import GSASIIpath
905import GSASIImath as G2mth
906import GSASIIspc as G2spc
907import numpy as np
908
909GSASIIpath.SetVersionNumber("$Revision: 2994 $")
910
911DefaultControls = {
912    'deriv type':'analytic Hessian',
913    'min dM/M':0.001,'shift factor':1.,'max cyc':3,'F**2':False,'SVDtol':1.e-6,
914    'UsrReject':{'minF/sig':0,'MinExt':0.01,'MaxDF/F':100.,'MaxD':500.,'MinD':0.05},
915    'Copy2Next':False,'Reverse Seq':False,'HatomFix':False,
916    'Author':'no name',
917    'FreePrm1':'Sample humidity (%)',
918    'FreePrm2':'Sample voltage (V)',
919    'FreePrm3':'Applied load (MN)',
920    'ShowCell':False,
921    }
922'''Values to be used as defaults for the initial contents of the ``Controls``
923data tree item.
924'''
925def StripUnicode(string,subs='.'):
926    '''Strip non-ASCII characters from strings
927   
928    :param str string: string to strip Unicode characters from
929    :param str subs: character(s) to place into string in place of each
930      Unicode character. Defaults to '.'
931
932    :returns: a new string with only ASCII characters
933    '''
934    s = ''
935    for c in string:
936        if ord(c) < 128:
937            s += c
938        else:
939            s += subs
940    return s.encode('ascii','replace')
941
942def MakeUniqueLabel(lbl,labellist):
943    '''Make sure that every a label is unique against a list by adding
944    digits at the end until it is not found in list.
945
946    :param str lbl: the input label
947    :param list labellist: the labels that have already been encountered
948    :returns: lbl if not found in labellist or lbl with ``_1-9`` (or
949      ``_10-99``, etc.) appended at the end
950    '''
951    lbl = StripUnicode(lbl.strip(),'_')
952    if not lbl: # deal with a blank label
953        lbl = '_1'
954    if lbl not in labellist:
955        labellist.append(lbl)
956        return lbl
957    i = 1
958    prefix = lbl
959    if '_' in lbl:
960        prefix = lbl[:lbl.rfind('_')]
961        suffix = lbl[lbl.rfind('_')+1:]
962        try:
963            i = int(suffix)+1
964        except: # suffix could not be parsed
965            i = 1
966            prefix = lbl
967    while prefix+'_'+str(i) in labellist:
968        i += 1
969    else:
970        lbl = prefix+'_'+str(i)
971        labellist.append(lbl)
972    return lbl
973
974PhaseIdLookup = {}
975'''dict listing phase name and random Id keyed by sequential phase index as a str;
976best to access this using :func:`LookupPhaseName`
977'''
978PhaseRanIdLookup = {}
979'''dict listing phase sequential index keyed by phase random Id;
980best to access this using :func:`LookupPhaseId`
981'''
982HistIdLookup = {}
983'''dict listing histogram name and random Id, keyed by sequential histogram index as a str;
984best to access this using :func:`LookupHistName`
985'''
986HistRanIdLookup = {}
987'''dict listing histogram sequential index keyed by histogram random Id;
988best to access this using :func:`LookupHistId`
989'''
990AtomIdLookup = {}
991'''dict listing for each phase index as a str, the atom label and atom random Id,
992keyed by atom sequential index as a str;
993best to access this using :func:`LookupAtomLabel`
994'''
995AtomRanIdLookup = {}
996'''dict listing for each phase the atom sequential index keyed by atom random Id;
997best to access this using :func:`LookupAtomId`
998'''
999ShortPhaseNames = {}
1000'''a dict containing a possibly shortened and when non-unique numbered
1001version of the phase name. Keyed by the phase sequential index.
1002'''
1003ShortHistNames = {}
1004'''a dict containing a possibly shortened and when non-unique numbered
1005version of the histogram name. Keyed by the histogram sequential index.
1006'''
1007
1008VarDesc = {}
1009''' This dictionary lists descriptions for GSAS-II variables,
1010as set in :func:`CompileVarDesc`. See that function for a description
1011for how keys and values are written.
1012'''
1013
1014reVarDesc = {}
1015''' This dictionary lists descriptions for GSAS-II variables with
1016the same values as :attr:`VarDesc` except that keys have been compiled as
1017regular expressions. Initialized in :func:`CompileVarDesc`.
1018'''
1019# create a default space group object for P1; N.B. fails when building documentation
1020try: 
1021    P1SGData = G2spc.SpcGroup('P 1')[1] # data structure for default space group
1022except TypeError:
1023    pass
1024
1025def GetPhaseNames(fl):
1026    ''' Returns a list of phase names found under 'Phases' in GSASII gpx file
1027    NB: there is another one of these in GSASIIstrIO.py that uses the gpx filename
1028
1029    :param file fl: opened .gpx file
1030    :return: list of phase names
1031    '''
1032    PhaseNames = []
1033    while True:
1034        try:
1035            data = cPickle.load(fl)
1036        except EOFError:
1037            break
1038        datum = data[0]
1039        if 'Phases' == datum[0]:
1040            for datus in data[1:]:
1041                PhaseNames.append(datus[0])
1042    fl.seek(0)          #reposition file
1043    return PhaseNames
1044
1045def SetNewPhase(Name='New Phase',SGData=None,cell=None,Super=None):
1046    '''Create a new phase dict with default values for various parameters
1047
1048    :param str Name: Name for new Phase
1049
1050    :param dict SGData: space group data from :func:`GSASIIspc:SpcGroup`;
1051      defaults to data for P 1
1052
1053    :param list cell: unit cell parameter list; defaults to
1054      [1.0,1.0,1.0,90.,90,90.,1.]
1055
1056    '''
1057    if SGData is None: SGData = P1SGData
1058    if cell is None: cell=[1.0,1.0,1.0,90.,90,90.,1.]
1059    phaseData = {
1060        'ranId':ran.randint(0,sys.maxint),
1061        'General':{
1062            'Name':Name,
1063            'Type':'nuclear',
1064            'Modulated':False,
1065            'AtomPtrs':[3,1,7,9],
1066            'SGData':SGData,
1067            'Cell':[False,]+cell,
1068            'Pawley dmin':1.0,
1069            'Data plot type':'None',
1070            'SH Texture':{
1071                'Order':0,
1072                'Model':'cylindrical',
1073                'Sample omega':[False,0.0],
1074                'Sample chi':[False,0.0],
1075                'Sample phi':[False,0.0],
1076                'SH Coeff':[False,{}],
1077                'SHShow':False,
1078                'PFhkl':[0,0,1],
1079                'PFxyz':[0,0,1],
1080                'PlotType':'Pole figure',
1081                'Penalty':[['',],0.1,False,1.0]}},
1082        'Atoms':[],
1083        'Drawing':{},
1084        'Histograms':{},
1085        'Pawley ref':[],
1086        'RBModels':{},
1087        }
1088    if Super and Super.get('Use',False):
1089        phaseData['General'].update({'Modulated':True,'Super':True,'SuperSg':Super['ssSymb']})
1090        phaseData['General']['SSGData'] = G2spc.SSpcGroup(SGData,Super['ssSymb'])
1091        phaseData['General']['SuperVec'] = [Super['ModVec'],False,Super['maxH']]
1092
1093    return phaseData
1094               
1095def ReadCIF(URLorFile):
1096    '''Open a CIF, which may be specified as a file name or as a URL using PyCifRW
1097    (from James Hester).
1098    The open routine gets confused with DOS names that begin with a letter and colon
1099    "C:\dir\" so this routine will try to open the passed name as a file and if that
1100    fails, try it as a URL
1101
1102    :param str URLorFile: string containing a URL or a file name. Code will try first
1103      to open it as a file and then as a URL.
1104
1105    :returns: a PyCifRW CIF object.
1106    '''
1107    import CifFile as cif # PyCifRW from James Hester
1108
1109    # alternate approach:
1110    #import urllib
1111    #ciffile = 'file:'+urllib.pathname2url(filename)
1112   
1113    try:
1114        fp = open(URLorFile,'r')
1115        cf = cif.ReadCif(fp)
1116        fp.close()
1117        return cf
1118    except IOError:
1119        return cif.ReadCif(URLorFile)
1120
1121def IndexAllIds(Histograms,Phases):
1122    '''Scan through the used phases & histograms and create an index
1123    to the random numbers of phases, histograms and atoms. While doing this,
1124    confirm that assigned random numbers are unique -- just in case lightning
1125    strikes twice in the same place.
1126
1127    Note: this code assumes that the atom random Id (ranId) is the last
1128    element each atom record.
1129
1130    This is called in three places (only): :func:`GSASIIstrIO.GetUsedHistogramsAndPhases`
1131    (which loads the histograms and phases from a GPX file),
1132    :meth:`~GSASIIdataGUI.GSASII.GetUsedHistogramsAndPhasesfromTree`
1133    (which loads the histograms and phases from the data tree.) and
1134    :meth:`GSASIIconstrGUI.UpdateConstraints`
1135    (which displays & edits the constraints in a GUI)
1136
1137    TODO: do we need a lookup for rigid body variables?
1138    '''
1139    # process phases and atoms
1140    PhaseIdLookup.clear()
1141    PhaseRanIdLookup.clear()   
1142    AtomIdLookup.clear()
1143    AtomRanIdLookup.clear()
1144    ShortPhaseNames.clear()
1145    for ph in Phases:
1146        cx,ct,cs,cia = Phases[ph]['General']['AtomPtrs']
1147        ranId = Phases[ph]['ranId'] 
1148        while ranId in PhaseRanIdLookup:
1149            # Found duplicate random Id! note and reassign
1150            print ("\n\n*** Phase "+str(ph)+" has repeated ranId. Fixing.\n")
1151            Phases[ph]['ranId'] = ranId = ran.randint(0,sys.maxint)
1152        pId = str(Phases[ph]['pId'])
1153        PhaseIdLookup[pId] = (ph,ranId)
1154        PhaseRanIdLookup[ranId] = pId
1155        shortname = ph  #[:10]
1156        while shortname in ShortPhaseNames.values():
1157            shortname = ph[:8] + ' ('+ pId + ')'
1158        ShortPhaseNames[pId] = shortname
1159        AtomIdLookup[pId] = {}
1160        AtomRanIdLookup[pId] = {}
1161        for iatm,at in enumerate(Phases[ph]['Atoms']):
1162            ranId = at[cia+8]
1163            while ranId in AtomRanIdLookup[pId]: # check for dups
1164                print ("\n\n*** Phase "+str(ph)+" atom "+str(iatm)+" has repeated ranId. Fixing.\n")
1165                at[cia+8] = ranId = ran.randint(0,sys.maxint)
1166            AtomRanIdLookup[pId][ranId] = str(iatm)
1167            if Phases[ph]['General']['Type'] == 'macromolecular':
1168                label = '%s_%s_%s_%s'%(at[ct-1],at[ct-3],at[ct-4],at[ct-2])
1169            else:
1170                label = at[ct-1]
1171            AtomIdLookup[pId][str(iatm)] = (label,ranId)
1172    # process histograms
1173    HistIdLookup.clear()
1174    HistRanIdLookup.clear()
1175    ShortHistNames.clear()
1176    for hist in Histograms:
1177        ranId = Histograms[hist]['ranId']
1178        while ranId in HistRanIdLookup:
1179            # Found duplicate random Id! note and reassign
1180            print ("\n\n*** Histogram "+str(hist)+" has repeated ranId. Fixing.\n")
1181            Histograms[hist]['ranId'] = ranId = ran.randint(0,sys.maxint)
1182        hId = str(Histograms[hist]['hId'])
1183        HistIdLookup[hId] = (hist,ranId)
1184        HistRanIdLookup[ranId] = hId
1185        shortname = hist[:15]
1186        while shortname in ShortHistNames.values():
1187            shortname = hist[:11] + ' ('+ hId + ')'
1188        ShortHistNames[hId] = shortname
1189
1190def LookupAtomId(pId,ranId):
1191    '''Get the atom number from a phase and atom random Id
1192
1193    :param int/str pId: the sequential number of the phase
1194    :param int ranId: the random Id assigned to an atom
1195
1196    :returns: the index number of the atom (str)
1197    '''
1198    if not AtomRanIdLookup:
1199        raise Exception,'Error: LookupAtomId called before IndexAllIds was run'
1200    if pId is None or pId == '':
1201        raise KeyError,'Error: phase is invalid (None or blank)'
1202    pId = str(pId)
1203    if pId not in AtomRanIdLookup:
1204        raise KeyError,'Error: LookupAtomId does not have phase '+pId
1205    if ranId not in AtomRanIdLookup[pId]:
1206        raise KeyError,'Error: LookupAtomId, ranId '+str(ranId)+' not in AtomRanIdLookup['+pId+']'
1207    return AtomRanIdLookup[pId][ranId]
1208
1209def LookupAtomLabel(pId,index):
1210    '''Get the atom label from a phase and atom index number
1211
1212    :param int/str pId: the sequential number of the phase
1213    :param int index: the index of the atom in the list of atoms
1214
1215    :returns: the label for the atom (str) and the random Id of the atom (int)
1216    '''
1217    if not AtomIdLookup:
1218        raise Exception,'Error: LookupAtomLabel called before IndexAllIds was run'
1219    if pId is None or pId == '':
1220        raise KeyError,'Error: phase is invalid (None or blank)'
1221    pId = str(pId)
1222    if pId not in AtomIdLookup:
1223        raise KeyError,'Error: LookupAtomLabel does not have phase '+pId
1224    if index not in AtomIdLookup[pId]:
1225        raise KeyError,'Error: LookupAtomLabel, ranId '+str(index)+' not in AtomRanIdLookup['+pId+']'
1226    return AtomIdLookup[pId][index]
1227
1228def LookupPhaseId(ranId):
1229    '''Get the phase number and name from a phase random Id
1230
1231    :param int ranId: the random Id assigned to a phase
1232    :returns: the sequential Id (pId) number for the phase (str)
1233    '''
1234    if not PhaseRanIdLookup:
1235        raise Exception,'Error: LookupPhaseId called before IndexAllIds was run'
1236    if ranId not in PhaseRanIdLookup:
1237        raise KeyError,'Error: LookupPhaseId does not have ranId '+str(ranId)
1238    return PhaseRanIdLookup[ranId]
1239
1240def LookupPhaseName(pId):
1241    '''Get the phase number and name from a phase Id
1242
1243    :param int/str pId: the sequential assigned to a phase
1244    :returns:  (phase,ranId) where phase is the name of the phase (str)
1245      and ranId is the random # id for the phase (int)
1246    '''
1247    if not PhaseIdLookup:
1248        raise Exception,'Error: LookupPhaseName called before IndexAllIds was run'
1249    if pId is None or pId == '':
1250        raise KeyError,'Error: phase is invalid (None or blank)'
1251    pId = str(pId)
1252    if pId not in PhaseIdLookup:
1253        raise KeyError,'Error: LookupPhaseName does not have index '+pId
1254    return PhaseIdLookup[pId]
1255
1256def LookupHistId(ranId):
1257    '''Get the histogram number and name from a histogram random Id
1258
1259    :param int ranId: the random Id assigned to a histogram
1260    :returns: the sequential Id (hId) number for the histogram (str)
1261    '''
1262    if not HistRanIdLookup:
1263        raise Exception,'Error: LookupHistId called before IndexAllIds was run'
1264    if ranId not in HistRanIdLookup:
1265        raise KeyError,'Error: LookupHistId does not have ranId '+str(ranId)
1266    return HistRanIdLookup[ranId]
1267
1268def LookupHistName(hId):
1269    '''Get the histogram number and name from a histogram Id
1270
1271    :param int/str hId: the sequential assigned to a histogram
1272    :returns:  (hist,ranId) where hist is the name of the histogram (str)
1273      and ranId is the random # id for the histogram (int)
1274    '''
1275    if not HistIdLookup:
1276        raise Exception,'Error: LookupHistName called before IndexAllIds was run'
1277    if hId is None or hId == '':
1278        raise KeyError,'Error: histogram is invalid (None or blank)'
1279    hId = str(hId)
1280    if hId not in HistIdLookup:
1281        raise KeyError,'Error: LookupHistName does not have index '+hId
1282    return HistIdLookup[hId]
1283
1284def fmtVarDescr(varname):
1285    '''Return a string with a more complete description for a GSAS-II variable
1286
1287    :param str varname: A full G2 variable name with 2 or 3 or 4
1288       colons (<p>:<h>:name[:<a>] or <p>::RBname:<r>:<t>])
1289       
1290    :returns: a string with the description
1291    '''
1292    s,l = VarDescr(varname)
1293    return s+": "+l
1294
1295def VarDescr(varname):
1296    '''Return two strings with a more complete description for a GSAS-II variable
1297
1298    :param str name: A full G2 variable name with 2 or 3 or 4
1299       colons (<p>:<h>:name[:<a>] or <p>::RBname:<r>:<t>])
1300       
1301    :returns: (loc,meaning) where loc describes what item the variable is mapped
1302      (phase, histogram, etc.) and meaning describes what the variable does.
1303    '''
1304   
1305    # special handling for parameter names without a colons
1306    # for now, assume self-defining
1307    if varname.find(':') == -1:
1308        return "Global",varname
1309       
1310    l = getVarDescr(varname)
1311    if not l:
1312        return ("invalid variable name ("+str(varname)+")!"),""
1313#        return "invalid variable name!",""
1314
1315    if not l[-1]:
1316        l[-1] = "(variable needs a definition! Set it in CompileVarDesc)"
1317
1318    if len(l) == 3:         #SASD variable name!
1319        s = 'component:'+l[1]
1320        return s,l[-1]
1321    s = ""
1322    if l[0] is not None and l[1] is not None: # HAP: keep short
1323        if l[2] == "Scale": # fix up ambigous name
1324            l[5] = "Phase fraction"
1325        if l[0] == '*':
1326            lbl = 'Seq. ref.'
1327        else:
1328            lbl = ShortPhaseNames.get(l[0],'? #'+str(l[0]))
1329        if l[1] == '*':
1330            hlbl = 'Seq. ref.'
1331        else:
1332            hlbl = ShortHistNames.get(l[1],'? #'+str(l[1]))
1333        if hlbl[:4] == 'HKLF':
1334            hlbl = 'Xtl='+hlbl[5:]
1335        elif hlbl[:4] == 'PWDR':
1336            hlbl = 'Pwd='+hlbl[5:]
1337        else:
1338            hlbl = 'Hist='+hlbl
1339        s = "Ph="+str(lbl)+" * "+str(hlbl)
1340    else:
1341        if l[2] == "Scale": # fix up ambigous name: must be scale factor, since not HAP
1342            l[5] = "Scale factor"
1343        if l[2] == 'Back': # background parameters are "special", alas
1344            s = 'Hist='+ShortHistNames.get(l[1],'? #'+str(l[1]))
1345            l[-1] += ' #'+str(l[3])
1346        elif l[4] is not None: # rigid body parameter or modulation parm
1347            lbl = ShortPhaseNames.get(l[0],'phase?')
1348            if 'RB' in l[2]:    #rigid body parm
1349                s = "Res #"+str(l[3])+" body #"+str(l[4])+" in "+str(lbl)
1350            else: #modulation parm
1351                s = 'Atom %s wave %s in %s'%(LookupAtomLabel(l[0],l[3])[0],l[4],lbl)
1352        elif l[3] is not None: # atom parameter,
1353            lbl = ShortPhaseNames.get(l[0],'phase?')
1354            try:
1355                albl = LookupAtomLabel(l[0],l[3])[0]
1356            except KeyError:
1357                albl = 'Atom?'
1358            s = "Atom "+str(albl)+" in "+str(lbl)
1359        elif l[0] == '*':
1360            s = "All phases "
1361        elif l[0] is not None:
1362            lbl = ShortPhaseNames.get(l[0],'phase?')
1363            s = "Phase "+str(lbl)
1364        elif l[1] == '*':
1365            s = 'All hists'
1366        elif l[1] is not None:
1367            hlbl = ShortHistNames.get(l[1],'? #'+str(l[1]))
1368            if hlbl[:4] == 'HKLF':
1369                hlbl = 'Xtl='+hlbl[5:]
1370            elif hlbl[:4] == 'PWDR':
1371                hlbl = 'Pwd='+hlbl[5:]
1372            else:
1373                hlbl = 'Hist='+hlbl
1374            s = str(hlbl)
1375    if not s:
1376        s = 'Global'
1377    return s,l[-1]
1378
1379def getVarDescr(varname):
1380    '''Return a short description for a GSAS-II variable
1381
1382    :param str name: A full G2 variable name with 2 or 3 or 4
1383       colons (<p>:<h>:name[:<a1>][:<a2>])
1384     
1385    :returns: a six element list as [`p`,`h`,`name`,`a1`,`a2`,`description`],
1386      where `p`, `h`, `a1`, `a2` are str values or `None`, for the phase number,
1387      the histogram number and the atom number; `name` will always be
1388      a str; and `description` is str or `None`.
1389      If the variable name is incorrectly formed (for example, wrong
1390      number of colons), `None` is returned instead of a list.
1391    '''
1392    l = varname.split(':')
1393    if len(l) == 2:     #SASD parameter name
1394        return varname,l[0],getDescr(l[1])
1395    if len(l) == 3:
1396        l += [None,None]
1397    elif len(l) == 4:
1398        l += [None]
1399    elif len(l) != 5:
1400        return None
1401    for i in (0,1,3,4):
1402        if l[i] == "":
1403            l[i] = None
1404    l += [getDescr(l[2])]
1405    return l
1406   
1407def CompileVarDesc():
1408    '''Set the values in the variable description lookup table (:attr:`VarDesc`)
1409    into :attr:`reVarDesc`. This is called in :func:`getDescr` so the initialization
1410    is always done before use.
1411
1412    Note that keys may contain regular expressions, where '[xyz]'
1413    matches 'x' 'y' or 'z' (equivalently '[x-z]' describes this as range of values).
1414    '.*' matches any string. For example::
1415
1416    'AUiso':'Atomic isotropic displacement parameter',
1417
1418    will match variable ``'p::AUiso:a'``.
1419    If parentheses are used in the key, the contents of those parentheses can be
1420    used in the value, such as::
1421
1422    'AU([123][123])':'Atomic anisotropic displacement parameter U\\1',
1423
1424    will match ``AU11``, ``AU23``,.. and `U11`, `U23` etc will be displayed
1425    in the value when used.
1426   
1427    '''
1428    if reVarDesc: return # already done
1429    for key,value in {
1430        # derived or other sequential vars
1431        '([abc])$' : 'Lattice parameter, \\1, from Ai and Djk', # N.B. '$' prevents match if any characters follow
1432        u'\u03B1' : u'Lattice parameter, \u03B1, from Ai and Djk',
1433        u'\u03B2' : u'Lattice parameter, \u03B2, from Ai and Djk',
1434        u'\u03B3' : u'Lattice parameter, \u03B3, from Ai and Djk',
1435        # ambiguous, alas:
1436        'Scale' : 'Phase or Histogram scale factor',
1437        # Phase vars (p::<var>)
1438        'A([0-5])' : 'Reciprocal metric tensor component \\1',
1439        '[vV]ol' : 'Unit cell volume', # probably an error that both upper and lower case are used
1440        # Atom vars (p::<var>:a)
1441        'dA([xyz])$' : 'change to atomic coordinate, \\1',
1442        'A([xyz])$' : '\\1 fractional atomic coordinate',
1443        'AUiso':'Atomic isotropic displacement parameter',
1444        'AU([123][123])':'Atomic anisotropic displacement parameter U\\1',
1445        'Afrac': 'Atomic site fraction parameter',
1446        'Amul': 'Atomic site multiplicity value',
1447        'AM([xyz])$' : 'Atomic magnetic moment parameter, \\1',
1448        # Hist & Phase (HAP) vars (p:h:<var>)
1449        'Back': 'Background term',
1450        'BkPkint;(.*)':'Background peak #\\1 intensity',
1451        'BkPkpos;(.*)':'Background peak #\\1 position',
1452        'BkPksig;(.*)':'Background peak #\\1 Gaussian width',
1453        'BkPkgam;(.*)':'Background peak #\\1 Cauchy width',
1454        'Bab([AU])': 'Babinet solvent scattering coef. \\1',
1455        'D([123][123])' : 'Anisotropic strain coef. \\1',
1456        'Extinction' : 'Extinction coef.',
1457        'MD' : 'March-Dollase coef.',
1458        'Mustrain;.*' : 'Microstrain coef.',
1459        'Size;.*' : 'Crystallite size value',
1460        'eA$' : 'Cubic mustrain value',
1461        'Ep$' : 'Primary extinction',
1462        'Es$' : 'Secondary type II extinction',
1463        'Eg$' : 'Secondary type I extinction',
1464        'Flack' : 'Flack parameter',
1465        'TwinFr' : 'Twin fraction',
1466        #Histogram vars (:h:<var>)
1467        'Absorption' : 'Absorption coef.',
1468        'Displace([XY])' : 'Debye-Scherrer sample displacement \\1',
1469        'Lam' : 'Wavelength',
1470        'Polariz\.' : 'Polarization correction',
1471        'SH/L' : 'FCJ peak asymmetry correction',
1472        '([UVW])$' : 'Gaussian instrument broadening \\1',
1473        '([XY])$' : 'Cauchy instrument broadening \\1',
1474        'Zero' : 'Debye-Scherrer zero correction',
1475        'nDebye' : 'Debye model background corr. terms',
1476        'nPeaks' : 'Fixed peak background corr. terms',
1477        'RBV.*' : 'Vector rigid body parameter',
1478        'RBR.*' : 'Residue rigid body parameter',
1479        'RBRO([aijk])' : 'Residue rigid body orientation parameter',
1480        'RBRP([xyz])' : 'Residue rigid body position parameter',
1481        'RBRTr;.*' : 'Residue rigid body torsion parameter',
1482        'RBR([TLS])([123AB][123AB])' : 'Residue rigid body group disp. param.',
1483        'constr([0-9]*)' : 'Parameter from constraint',
1484        # supersymmetry parameters  p::<var>:a:o 'Flen','Fcent'?
1485        'mV([0-2])$' : 'Modulation vector component \\1',
1486        'Fsin'  :   'Sin site fraction modulation',
1487        'Fcos'  :   'Cos site fraction modulation',
1488        'Fzero'  :   'Crenel function offset',      #may go away
1489        'Fwid'   :   'Crenel function width',
1490        'Tmin'   :   'ZigZag/Block min location',
1491        'Tmax'   :   'ZigZag/Block max location',
1492        '([XYZ])max': 'ZigZag/Block max value for \\1',
1493        '([XYZ])sin'  : 'Sin position wave for \\1',
1494        '([XYZ])cos'  : 'Cos position wave for \\1',
1495        'U([123][123])sin$' :  'Sin thermal wave for U\\1',
1496        'U([123][123])cos$' :  'Cos thermal wave for U\\1',
1497        'M([XYZ])sin$' :  'Sin mag. moment wave for \\1',
1498        'M([XYZ])cos$' :  'Cos mag. moment wave for \\1',
1499        # PDF peak parms (l:<var>;l = peak no.)
1500        'PDFpos'  : 'PDF peak position',
1501        'PDFmag'  : 'PDF peak magnitude',
1502        'PDFsig'  : 'PDF peak std. dev.',
1503        # SASD vars (l:<var>;l = component)
1504        'Aspect ratio' : 'Particle aspect ratio',
1505        'Length' : 'Cylinder length',
1506        'Diameter' : 'Cylinder/disk diameter',
1507        'Thickness' : 'Disk thickness',
1508        'Shell thickness' : 'Multiplier to get inner(<1) or outer(>1) sphere radius',
1509        'Dist' : 'Interparticle distance',
1510        'VolFr' : 'Dense scatterer volume fraction',
1511        'epis' : 'Sticky sphere epsilon',
1512        'Sticky' : 'Stickyness',
1513        'Depth' : 'Well depth',
1514        'Width' : 'Well width',
1515        'Volume' : 'Particle volume',
1516        'Radius' : 'Sphere/cylinder/disk radius',
1517        'Mean' : 'Particle mean radius',
1518        'StdDev' : 'Standard deviation in Mean',
1519        'G$': 'Guinier prefactor',
1520        'Rg$': 'Guinier radius of gyration',
1521        'B$': 'Porod prefactor',
1522        'P$': 'Porod power',
1523        'Cutoff': 'Porod cutoff',
1524        'PkInt': 'Bragg peak intensity',
1525        'PkPos': 'Bragg peak position',
1526        'PkSig': 'Bragg peak sigma',
1527        'PkGam': 'Bragg peak gamma',
1528        'e([12][12])' : 'strain tensor e\1',   # strain vars e11, e22, e12
1529        'Dcalc': 'Calc. d-spacing',
1530        'Back$': 'background parameter',
1531        'pos$': 'peak position',
1532        'int$': 'peak intensity',
1533        'WgtFrac':'phase weight fraction',
1534        }.items():
1535        VarDesc[key] = value
1536        reVarDesc[re.compile(key)] = value
1537
1538def getDescr(name):
1539    '''Return a short description for a GSAS-II variable
1540
1541    :param str name: The descriptive part of the variable name without colons (:)
1542     
1543    :returns: a short description or None if not found
1544    '''
1545
1546    CompileVarDesc() # compile the regular expressions, if needed
1547    for key in reVarDesc:
1548        m = key.match(name)
1549        if m:
1550            reVarDesc[key]
1551            return m.expand(reVarDesc[key])
1552    return None
1553
1554def GenWildCard(varlist):
1555    '''Generate wildcard versions of G2 variables. These introduce '*'
1556    for a phase, histogram or atom number (but only for one of these
1557    fields) but only when there is more than one matching variable in the
1558    input variable list. So if the input is this::
1559   
1560      varlist = ['0::AUiso:0', '0::AUiso:1', '1::AUiso:0']
1561
1562    then the output will be this::
1563   
1564       wildList = ['*::AUiso:0', '0::AUiso:*']
1565
1566    :param list varlist: an input list of GSAS-II variable names
1567      (such as 0::AUiso:0)
1568
1569    :returns: wildList, the generated list of wild card variable names.
1570    '''
1571    wild = []
1572    for i in (0,1,3):
1573        currentL = varlist[:]
1574        while currentL:
1575            item1 = currentL.pop(0)
1576            i1splt = item1.split(':')
1577            if i >= len(i1splt): continue
1578            if i1splt[i]:
1579                nextL = []
1580                i1splt[i] = '[0-9]+'
1581                rexp = re.compile(':'.join(i1splt))
1582                matchlist = [item1]
1583                for nxtitem in currentL:
1584                    if rexp.match(nxtitem):
1585                        matchlist += [nxtitem]
1586                    else:
1587                        nextL.append(nxtitem)
1588                if len(matchlist) > 1:
1589                    i1splt[i] = '*'
1590                    wild.append(':'.join(i1splt))
1591                currentL = nextL
1592    return wild
1593
1594def LookupWildCard(varname,varlist):
1595    '''returns a list of variable names from list varname
1596    that match wildcard name in varname
1597   
1598    :param str varname: a G2 variable name containing a wildcard
1599      (such as \*::var)
1600    :param list varlist: the list of all variable names used in
1601      the current project
1602    :returns: a list of matching GSAS-II variables (may be empty) 
1603    '''
1604    rexp = re.compile(varname.replace('*','[0-9]+'))
1605    return sorted([var for var in varlist if rexp.match(var)])
1606
1607
1608def _lookup(dic,key):
1609    '''Lookup a key in a dictionary, where None returns an empty string
1610    but an unmatched key returns a question mark. Used in :class:`G2VarObj`
1611    '''
1612    if key is None:
1613        return ""
1614    elif key == "*":
1615        return "*"
1616    else:
1617        return dic.get(key,'?')
1618
1619class G2VarObj(object):
1620    '''Defines a GSAS-II variable either using the phase/atom/histogram
1621    unique Id numbers or using a character string that specifies
1622    variables by phase/atom/histogram number (which can change).
1623    Note that :func:`LoadID` should be used to (re)load the current Ids
1624    before creating or later using the G2VarObj object.
1625
1626    This can store rigid body variables, but does not translate the residue # and
1627    body # to/from random Ids
1628
1629    A :class:`G2VarObj` object can be created with a single parameter:
1630   
1631    :param str/tuple varname: a single value can be used to create a :class:`G2VarObj`
1632      object. If a string, it must be of form "p:h:var" or "p:h:var:a", where
1633
1634     * p is the phase number (which may be left blank or may be '*' to indicate all phases);
1635     * h is the histogram number (which may be left blank or may be '*' to indicate all histograms);
1636     * a is the atom number (which may be left blank in which case the third colon is omitted).
1637       The atom number can be specified as '*' if a phase number is specified (not as '*').
1638       For rigid body variables, specify a will be a string of form "residue:body#"
1639
1640      Alternately a single tuple of form (Phase,Histogram,VarName,AtomID) can be used, where
1641      Phase, Histogram, and AtomID are None or are ranId values (or one can be '*')
1642      and VarName is a string. Note that if Phase is '*' then the AtomID is an atom number.
1643      For a rigid body variables, AtomID is a string of form "residue:body#".
1644
1645    If four positional arguments are supplied, they are:
1646
1647    :param str/int phasenum: The number for the phase (or None or '*')
1648    :param str/int histnum: The number for the histogram (or None or '*')
1649    :param str varname: a single value can be used to create a :class:`G2VarObj`
1650    :param str/int atomnum: The number for the atom (or None or '*')
1651   
1652    '''
1653    IDdict = {}
1654    IDdict['phases'] = {}
1655    IDdict['hists'] = {}
1656    IDdict['atoms'] = {}
1657    def __init__(self,*args):
1658        self.phase = None
1659        self.histogram = None
1660        self.name = ''
1661        self.atom = None
1662        if len(args) == 1 and (type(args[0]) is list or type(args[0]) is tuple) and len(args[0]) == 4:
1663            # single arg with 4 values
1664            self.phase,self.histogram,self.name,self.atom = args[0]
1665        elif len(args) == 1 and ':' in args[0]:
1666            #parse a string
1667            lst = args[0].split(':')
1668            if lst[0] == '*':
1669                self.phase = '*'
1670                if len(lst) > 3:
1671                    self.atom = lst[3]
1672                self.histogram = HistIdLookup.get(lst[1],[None,None])[1]
1673            elif lst[1] == '*':           
1674                self.histogram = '*'
1675                self.phase = PhaseIdLookup.get(lst[0],[None,None])[1]
1676            else:
1677                self.histogram = HistIdLookup.get(lst[1],[None,None])[1]
1678                self.phase = PhaseIdLookup.get(lst[0],[None,None])[1]
1679                if len(lst) == 4:
1680                    if lst[3] == '*':
1681                        self.atom = '*'
1682                    else:
1683                        self.atom = AtomIdLookup[lst[0]].get(lst[3],[None,None])[1]
1684                elif len(lst) == 5:
1685                    self.atom = lst[3]+":"+lst[4]
1686                elif len(lst) == 3:
1687                    pass
1688                else:
1689                    raise Exception,"Too many colons in var name "+str(args[0])
1690            self.name = lst[2]
1691        elif len(args) == 4:
1692            if args[0] == '*':
1693                self.phase = '*'
1694                self.atom = args[3]
1695            else:
1696                self.phase = PhaseIdLookup.get(str(args[0]),[None,None])[1]
1697                if args[3] == '*':
1698                    self.atom = '*'
1699                elif args[0] is not None:
1700                    self.atom = AtomIdLookup[args[0]].get(str(args[3]),[None,None])[1]
1701            if args[1] == '*':
1702                self.histogram = '*'
1703            else:
1704                self.histogram = HistIdLookup.get(str(args[1]),[None,None])[1]
1705            self.name = args[2]
1706        else:
1707            raise Exception,"Incorrectly called GSAS-II parameter name"
1708
1709        #print "DEBUG: created ",self.phase,self.histogram,self.name,self.atom
1710
1711    def __str__(self):
1712        return self.varname()
1713
1714    def varname(self):
1715        '''Formats the GSAS-II variable name as a "traditional" GSAS-II variable
1716        string (p:h:<var>:a) or (p:h:<var>)
1717
1718        :returns: the variable name as a str
1719        '''
1720        a = ""
1721        if self.phase == "*":
1722            ph = "*"
1723            if self.atom:
1724                a = ":" + str(self.atom)
1725        else:
1726            ph = _lookup(PhaseRanIdLookup,self.phase)
1727            if self.atom == '*':
1728                a = ':*'
1729            elif self.atom:
1730                if ":" in str(self.atom):
1731                    a = ":" + str(self.atom)
1732                elif ph in AtomRanIdLookup:
1733                    a = ":" + AtomRanIdLookup[ph].get(self.atom,'?')
1734                else:
1735                    a = ":?"
1736        if self.histogram == "*":
1737            hist = "*"
1738        else:
1739            hist = _lookup(HistRanIdLookup,self.histogram)
1740        s = (ph + ":" + hist + ":" + str(self.name)) + a
1741        return s
1742   
1743    def __repr__(self):
1744        '''Return the detailed contents of the object
1745        '''
1746        s = "<"
1747        if self.phase == '*':
1748            s += "Phases: all; "
1749            if self.atom is not None:
1750                if ":" in str(self.atom):
1751                    s += "Rigid body" + str(self.atom) + "; "
1752                else:
1753                    s += "Atom #" + str(self.atom) + "; "
1754        elif self.phase is not None:
1755            ph =  _lookup(PhaseRanIdLookup,self.phase)
1756            s += "Phase: rId=" + str(self.phase) + " (#"+ ph + "); "
1757            if self.atom == '*':
1758                s += "Atoms: all; "
1759            elif ":" in str(self.atom):
1760                s += "Rigid body" + str(self.atom) + "; "
1761            elif self.atom is not None:
1762                s += "Atom rId=" + str(self.atom)
1763                if ph in AtomRanIdLookup:
1764                    s += " (#" + AtomRanIdLookup[ph].get(self.atom,'?') + "); "
1765                else:
1766                    s += " (#? -- not found!); "
1767        if self.histogram == '*':
1768            s += "Histograms: all; "
1769        elif self.histogram is not None:
1770            hist = _lookup(HistRanIdLookup,self.histogram)
1771            s += "Histogram: rId=" + str(self.histogram) + " (#"+ hist + "); "
1772        s += 'Variable name="' + str(self.name) + '">'
1773        return s+" ("+self.varname()+")"
1774
1775    def __eq__(self, other):
1776        if type(other) is type(self):
1777            return (self.phase == other.phase and
1778                    self.histogram == other.histogram and
1779                    self.name == other.name and
1780                    self.atom == other.atom)
1781        return False
1782
1783    def _show(self):
1784        'For testing, shows the current lookup table'
1785        print 'phases', self.IDdict['phases']
1786        print 'hists', self.IDdict['hists']
1787        print 'atomDict', self.IDdict['atoms']
1788
1789#==========================================================================
1790def SetDefaultSample():
1791    'Fills in default items for the Sample dictionary for Debye-Scherrer & SASD'
1792    return {
1793        'InstrName':'',
1794        'ranId':ran.randint(0,sys.maxint),
1795        'Scale':[1.0,True],'Type':'Debye-Scherrer','Absorption':[0.0,False],
1796        'DisplaceX':[0.0,False],'DisplaceY':[0.0,False],'Diffuse':[],
1797        'Temperature':300.,'Pressure':0.1,'Time':0.0,
1798        'FreePrm1':0.,'FreePrm2':0.,'FreePrm3':0.,
1799        'Gonio. radius':200.0,
1800        'Omega':0.0,'Chi':0.0,'Phi':0.0,'Azimuth':0.0,
1801#SASD items
1802        'Materials':[{'Name':'vacuum','VolFrac':1.0,},{'Name':'vacuum','VolFrac':0.0,}],
1803        'Thick':1.0,'Contrast':[0.0,0.0],       #contrast & anomalous contrast
1804        'Trans':1.0,                            #measured transmission
1805        'SlitLen':0.0,                          #Slit length - in Q(A-1)
1806        }
1807######################################################################
1808class ImportBaseclass(object):
1809    '''Defines a base class for the reading of input files (diffraction
1810    data, coordinates,...). See :ref:`Writing a Import Routine<Import_routines>`
1811    for an explanation on how to use a subclass of this class.
1812    '''
1813    class ImportException(Exception):
1814        '''Defines an Exception that is used when an import routine hits an expected error,
1815        usually in .Reader.
1816
1817        Good practice is that the Reader should define a value in self.errors that
1818        tells the user some information about what is wrong with their file.         
1819        '''
1820        pass
1821   
1822    UseReader = True  # in __init__ set value of self.UseReader to False to skip use of current importer
1823    def __init__(self,formatName,longFormatName=None,
1824                 extensionlist=[],strictExtension=False,):
1825        self.formatName = formatName # short string naming file type
1826        if longFormatName: # longer string naming file type
1827            self.longFormatName = longFormatName
1828        else:
1829            self.longFormatName = formatName
1830        # define extensions that are allowed for the file type
1831        # for windows, remove any extensions that are duplicate, as case is ignored
1832        if sys.platform == 'windows' and extensionlist:
1833            extensionlist = list(set([s.lower() for s in extensionlist]))
1834        self.extensionlist = extensionlist
1835        # If strictExtension is True, the file will not be read, unless
1836        # the extension matches one in the extensionlist
1837        self.strictExtension = strictExtension
1838        self.errors = ''
1839        self.warnings = ''
1840        self.SciPy = False          #image reader needed scipy
1841        # used for readers that will use multiple passes to read
1842        # more than one data block
1843        self.repeat = False
1844        self.selections = []
1845        self.repeatcount = 0
1846        self.readfilename = '?'
1847        self.scriptable = False
1848        #print 'created',self.__class__
1849
1850    def ReInitialize(self):
1851        'Reinitialize the Reader to initial settings'
1852        self.errors = ''
1853        self.warnings = ''
1854        self.SciPy = False          #image reader needed scipy
1855        self.repeat = False
1856        self.repeatcount = 0
1857        self.readfilename = '?'
1858
1859       
1860#    def Reader(self, filename, filepointer, ParentFrame=None, **unused):
1861#        '''This method must be supplied in the child class to read the file.
1862#        if the read fails either return False or raise an Exception
1863#        preferably of type ImportException.
1864#        '''
1865#        #start reading
1866#        raise ImportException("Error occurred while...")
1867#        self.errors += "Hint for user on why the error occur
1868#        return False # if an error occurs
1869#        return True # if read OK
1870
1871    def ExtensionValidator(self, filename):
1872        '''This methods checks if the file has the correct extension
1873        Return False if this filename will not be supported by this reader
1874        Return True if the extension matches the list supplied by the reader
1875        Return None if the reader allows un-registered extensions
1876        '''
1877        if filename:
1878            ext = ospath.splitext(filename)[1]
1879            if sys.platform == 'windows': ext = ext.lower()
1880            if ext in self.extensionlist: return True
1881            if self.strictExtension: return False
1882        return None
1883
1884    def ContentsValidator(self, filepointer):
1885        '''This routine will attempt to determine if the file can be read
1886        with the current format.
1887        This will typically be overridden with a method that
1888        takes a quick scan of [some of]
1889        the file contents to do a "sanity" check if the file
1890        appears to match the selected format.
1891        '''
1892        #filepointer.seek(0) # rewind the file pointer
1893        return True
1894
1895    def CIFValidator(self, filepointer):
1896        '''A :meth:`ContentsValidator` for use to validate CIF files.
1897        '''
1898        for i,l in enumerate(filepointer):
1899            if i >= 1000: return True
1900            '''Encountered only blank lines or comments in first 1000
1901            lines. This is unlikely, but assume it is CIF anyway, since we are
1902            even less likely to find a file with nothing but hashes and
1903            blank lines'''
1904            line = l.strip()
1905            if len(line) == 0: # ignore blank lines
1906                continue 
1907            elif line.startswith('#'): # ignore comments
1908                continue 
1909            elif line.startswith('data_'): # on the right track, accept this file
1910                return True
1911            else: # found something invalid
1912                self.errors = 'line '+str(i+1)+' contains unexpected data:\n'
1913                if all([ord(c) < 128 and ord(c) != 0 for c in str(l)]): # show only if ASCII
1914                    self.errors += '  '+str(l)
1915                else: 
1916                    self.errors += '  (binary)'
1917                self.errors += '\n  Note: a CIF should only have blank lines or comments before'
1918                self.errors += '\n        a data_ statement begins a block.'
1919                return False 
1920
1921######################################################################
1922class ImportPhase(ImportBaseclass):
1923    '''Defines a base class for the reading of files with coordinates
1924
1925    Objects constructed that subclass this (in import/G2phase_*.py etc.) will be used
1926    in :meth:`GSASIIdataGUI.GSASII.OnImportPhase`.
1927    See :ref:`Writing a Import Routine<Import_Routines>`
1928    for an explanation on how to use this class.
1929
1930    '''
1931    def __init__(self,formatName,longFormatName=None,extensionlist=[],
1932        strictExtension=False,):
1933        # call parent __init__
1934        ImportBaseclass.__init__(self,formatName,longFormatName,
1935            extensionlist,strictExtension)
1936        self.Phase = None # a phase must be created with G2IO.SetNewPhase in the Reader
1937        self.Constraints = None
1938
1939######################################################################
1940class ImportStructFactor(ImportBaseclass):
1941    '''Defines a base class for the reading of files with tables
1942    of structure factors.
1943
1944    Structure factors are read with a call to :meth:`GSASIIdataGUI.GSASII.OnImportSfact`
1945    which in turn calls :meth:`GSASIIdataGUI.GSASII.OnImportGeneric`, which calls
1946    methods :meth:`ExtensionValidator`, :meth:`ContentsValidator` and
1947    :meth:`Reader`.
1948
1949    See :ref:`Writing a Import Routine<Import_Routines>`
1950    for an explanation on how to use import classes in general. The specifics
1951    for reading a structure factor histogram require that
1952    the ``Reader()`` routine in the import
1953    class need to do only a few things: It
1954    should load :attr:`RefDict` item ``'RefList'`` with the reflection list,
1955    and set :attr:`Parameters` with the instrument parameters
1956    (initialized with :meth:`InitParameters` and set with :meth:`UpdateParameters`).
1957    '''
1958    def __init__(self,formatName,longFormatName=None,extensionlist=[],
1959        strictExtension=False,):
1960        ImportBaseclass.__init__(self,formatName,longFormatName,
1961            extensionlist,strictExtension)
1962
1963        # define contents of Structure Factor entry
1964        self.Parameters = []
1965        'self.Parameters is a list with two dicts for data parameter settings'
1966        self.InitParameters()
1967        self.RefDict = {'RefList':[],'FF':{},'Super':0}
1968        self.Banks = []             #for multi bank data (usually TOF)
1969        '''self.RefDict is a dict containing the reflection information, as read from the file.
1970        Item 'RefList' contains the reflection information. See the
1971        :ref:`Single Crystal Reflection Data Structure<XtalRefl_table>`
1972        for the contents of each row. Dict element 'FF'
1973        contains the form factor values for each element type; if this entry
1974        is left as initialized (an empty list) it will be initialized as needed later.
1975        '''
1976    def ReInitialize(self):
1977        'Reinitialize the Reader to initial settings'
1978        ImportBaseclass.ReInitialize(self)
1979        self.InitParameters()
1980        self.Banks = []             #for multi bank data (usually TOF)
1981        self.RefDict = {'RefList':[],'FF':{},'Super':0}
1982       
1983    def InitParameters(self):
1984        'initialize the instrument parameters structure'
1985        Lambda = 0.70926
1986        HistType = 'SXC'
1987        self.Parameters = [{'Type':[HistType,HistType], # create the structure
1988                            'Lam':[Lambda,Lambda]
1989                            }, {}]
1990        'Parameters is a list with two dicts for data parameter settings'
1991
1992    def UpdateParameters(self,Type=None,Wave=None):
1993        'Revise the instrument parameters'
1994        if Type is not None:
1995            self.Parameters[0]['Type'] = [Type,Type]
1996        if Wave is not None:
1997            self.Parameters[0]['Lam'] = [Wave,Wave]           
1998                       
1999######################################################################
2000class ImportPowderData(ImportBaseclass):
2001    '''Defines a base class for the reading of files with powder data.
2002
2003    Objects constructed that subclass this (in import/G2pwd_*.py etc.) will be used
2004    in :meth:`GSASIIdataGUI.GSASII.OnImportPowder`.
2005    See :ref:`Writing a Import Routine<Import_Routines>`
2006    for an explanation on how to use this class.
2007    '''
2008    def __init__(self,formatName,longFormatName=None,
2009        extensionlist=[],strictExtension=False,):
2010        ImportBaseclass.__init__(self,formatName,longFormatName,
2011            extensionlist,strictExtension)
2012        self.clockWd = None  # used in TOF
2013        self.ReInitialize()
2014       
2015    def ReInitialize(self):
2016        'Reinitialize the Reader to initial settings'
2017        ImportBaseclass.ReInitialize(self)
2018        self.powderentry = ['',None,None] #  (filename,Pos,Bank)
2019        self.powderdata = [] # Powder dataset
2020        '''A powder data set is a list with items [x,y,w,yc,yb,yd]:
2021                np.array(x), # x-axis values
2022                np.array(y), # powder pattern intensities
2023                np.array(w), # 1/sig(intensity)^2 values (weights)
2024                np.array(yc), # calc. intensities (zero)
2025                np.array(yb), # calc. background (zero)
2026                np.array(yd), # obs-calc profiles
2027        '''                           
2028        self.comments = []
2029        self.idstring = ''
2030        self.Sample = SetDefaultSample() # default sample parameters
2031        self.Controls = {}  # items to be placed in top-level Controls
2032        self.GSAS = None     # used in TOF
2033        self.repeat_instparm = True # Should a parm file be
2034        #                             used for multiple histograms?
2035        self.instparm = None # name hint from file of instparm to use
2036        self.instfile = '' # full path name to instrument parameter file
2037        self.instbank = '' # inst parm bank number
2038        self.instmsg = ''  # a label that gets printed to show
2039                           # where instrument parameters are from
2040        self.numbanks = 1
2041        self.instdict = {} # place items here that will be transferred to the instrument parameters
2042        self.pwdparms = {} # place parameters that are transferred directly to the tree
2043                           # here (typically from an existing GPX file)
2044######################################################################
2045class ImportSmallAngleData(ImportBaseclass):
2046    '''Defines a base class for the reading of files with small angle data.
2047    See :ref:`Writing a Import Routine<Import_Routines>`
2048    for an explanation on how to use this class.
2049    '''
2050    def __init__(self,formatName,longFormatName=None,extensionlist=[],
2051        strictExtension=False,):
2052           
2053        ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist,
2054            strictExtension)
2055        self.ReInitialize()
2056       
2057    def ReInitialize(self):
2058        'Reinitialize the Reader to initial settings'
2059        ImportBaseclass.ReInitialize(self)
2060        self.smallangleentry = ['',None,None] #  (filename,Pos,Bank)
2061        self.smallangledata = [] # SASD dataset
2062        '''A small angle data set is a list with items [x,y,w,yc,yd]:
2063                np.array(x), # x-axis values
2064                np.array(y), # powder pattern intensities
2065                np.array(w), # 1/sig(intensity)^2 values (weights)
2066                np.array(yc), # calc. intensities (zero)
2067                np.array(yd), # obs-calc profiles
2068                np.array(yb), # preset bkg
2069        '''                           
2070        self.comments = []
2071        self.idstring = ''
2072        self.Sample = SetDefaultSample()
2073        self.GSAS = None     # used in TOF
2074        self.clockWd = None  # used in TOF
2075        self.numbanks = 1
2076        self.instdict = {} # place items here that will be transferred to the instrument parameters
2077
2078######################################################################
2079class ImportReflectometryData(ImportBaseclass):
2080    '''Defines a base class for the reading of files with reflectometry data.
2081    See :ref:`Writing a Import Routine<Import_Routines>`
2082    for an explanation on how to use this class.
2083    '''
2084    def __init__(self,formatName,longFormatName=None,extensionlist=[],
2085        strictExtension=False,):
2086           
2087        ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist,
2088            strictExtension)
2089        self.ReInitialize()
2090       
2091    def ReInitialize(self):
2092        'Reinitialize the Reader to initial settings'
2093        ImportBaseclass.ReInitialize(self)
2094        self.reflectometryentry = ['',None,None] #  (filename,Pos,Bank)
2095        self.reflectometrydata = [] # SASD dataset
2096        '''A small angle data set is a list with items [x,y,w,yc,yd]:
2097                np.array(x), # x-axis values
2098                np.array(y), # powder pattern intensities
2099                np.array(w), # 1/sig(intensity)^2 values (weights)
2100                np.array(yc), # calc. intensities (zero)
2101                np.array(yd), # obs-calc profiles
2102                np.array(yb), # preset bkg
2103        '''                           
2104        self.comments = []
2105        self.idstring = ''
2106        self.Sample = SetDefaultSample()
2107        self.GSAS = None     # used in TOF
2108        self.clockWd = None  # used in TOF
2109        self.numbanks = 1
2110        self.instdict = {} # place items here that will be transferred to the instrument parameters
2111
2112######################################################################
2113class ImportPDFData(ImportBaseclass):
2114    '''Defines a base class for the reading of files with PDF G(R) data.
2115    See :ref:`Writing a Import Routine<Import_Routines>`
2116    for an explanation on how to use this class.
2117    '''
2118    def __init__(self,formatName,longFormatName=None,extensionlist=[],
2119        strictExtension=False,):
2120           
2121        ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist,
2122            strictExtension)
2123        self.ReInitialize()
2124       
2125    def ReInitialize(self):
2126        'Reinitialize the Reader to initial settings'
2127        ImportBaseclass.ReInitialize(self)
2128        self.pdfentry = ['',None,None] #  (filename,Pos,Bank)
2129        self.pdfdata = [] # PDF G(R) dataset
2130        '''A pdf g(r) data set is a list with items [x,y]:
2131                np.array(x), # r-axis values
2132                np.array(y), # pdf g(r)
2133        '''                           
2134        self.comments = []
2135        self.idstring = ''
2136        self.numbanks = 1
2137
2138######################################################################
2139class ImportImage(ImportBaseclass):
2140    '''Defines a base class for the reading of images
2141
2142    Images are read in only these places:
2143   
2144      * Initial reading is typically done from a menu item
2145        with a call to :meth:`GSASIIdataGUI.GSASII.OnImportImage`
2146        which in turn calls :meth:`GSASIIdataGUI.GSASII.OnImportGeneric`. That calls
2147        methods :meth:`ExtensionValidator`, :meth:`ContentsValidator` and
2148        :meth:`Reader`. This returns a list of reader objects for each read image.
2149
2150      * Images are read alternatively in :func:`GSASIIIO.ReadImages`, which puts image info
2151        directly into the data tree.
2152
2153      * Images are reloaded with :func:`GSASIIIO.GetImageData`.
2154
2155    .. _Image_import_routines:
2156
2157    When reading an image, the ``Reader()`` routine in the ImportImage class
2158    should set:
2159   
2160      * :attr:`Comments`: a list of strings (str),
2161      * :attr:`Npix`: the number of pixels in the image (int),
2162      * :attr:`Image`: the actual image as a numpy array (np.array)
2163      * :attr:`Data`: a dict defining image parameters (dict). Within this dict the following
2164        data items are needed:
2165       
2166         * 'pixelSize': size of each pixel in microns (such as ``[200,200]``.
2167         * 'wavelength': wavelength in Angstoms.
2168         * 'distance': distance of detector from sample in cm.
2169         * 'center': uncalibrated center of beam on detector (such as ``[204.8,204.8]``.
2170         * 'size': size of image (such as ``[2048,2048]``).
2171         * 'ImageTag': image number or other keyword used to retrieve image from
2172           a multi-image data file (defaults to ``1`` if not specified).
2173         * 'sumfile': holds sum image file name if a sum was produced from a multi image file
2174
2175    optional data items:
2176   
2177      * :attr:`repeat`: set to True if there are additional images to
2178        read in the file, False otherwise
2179      * :attr:`repeatcount`: set to the number of the image.
2180     
2181    Note that the above is initialized with :meth:`InitParameters`.
2182    (Also see :ref:`Writing a Import Routine<Import_Routines>`
2183    for an explanation on how to use import classes in general.)
2184    '''
2185    def __init__(self,formatName,longFormatName=None,extensionlist=[],
2186        strictExtension=False,):
2187        ImportBaseclass.__init__(self,formatName,longFormatName,
2188            extensionlist,strictExtension)
2189        self.InitParameters()
2190       
2191    def ReInitialize(self):
2192        'Reinitialize the Reader to initial settings -- not used at present'
2193        ImportBaseclass.ReInitialize(self)
2194        self.InitParameters()
2195       
2196    def InitParameters(self):
2197        'initialize the instrument parameters structure'
2198        self.Comments = ['No comments']
2199        self.Data = {}
2200        self.Npix = 0
2201        self.Image = None
2202        self.repeat = False
2203        self.repeatcount = 1
2204        self.sumfile = ''
2205
2206    def LoadImage(self,ParentFrame,imagefile,imagetag=None):
2207        '''Optionally, call this after reading in an image to load it into the tree.
2208        This saves time by preventing a reread of the same information.
2209        '''
2210        if ParentFrame:
2211            ParentFrame.ImageZ = self.Image   # store the image for plotting
2212            ParentFrame.oldImagefile = imagefile # save the name of the last image file read
2213            ParentFrame.oldImageTag = imagetag   # save the tag of the last image file read           
2214
2215#################################################################################################
2216# shortcut routines
2217exp = np.exp
2218sind = sin = s = lambda x: np.sin(x*np.pi/180.)
2219cosd = cos = c = lambda x: np.cos(x*np.pi/180.)
2220tand = tan = t = lambda x: np.tan(x*np.pi/180.)
2221sqrt = sq = lambda x: np.sqrt(x)
2222pi = lambda: np.pi
2223class ExpressionObj(object):
2224    '''Defines an object with a user-defined expression, to be used for
2225    secondary fits or restraints. Object is created null, but is changed
2226    using :meth:`LoadExpression`. This contains only the minimum
2227    information that needs to be stored to save and load the expression
2228    and how it is mapped to GSAS-II variables.
2229    '''
2230    def __init__(self):
2231        self.expression = ''
2232        'The expression as a text string'
2233        self.assgnVars = {}
2234        '''A dict where keys are label names in the expression mapping to a GSAS-II
2235        variable. The value a G2 variable name.
2236        Note that the G2 variable name may contain a wild-card and correspond to
2237        multiple values.
2238        '''
2239        self.freeVars = {}
2240        '''A dict where keys are label names in the expression mapping to a free
2241        parameter. The value is a list with:
2242
2243         * a name assigned to the parameter
2244         * a value for to the parameter and
2245         * a flag to determine if the variable is refined.
2246        ''' 
2247        self.depVar = None
2248
2249        self.lastError = ('','')
2250        '''Shows last encountered error in processing expression
2251        (list of 1-3 str values)'''
2252
2253        self.distance_dict  = None  # to be used for defining atom phase/symmetry info
2254        self.distance_atoms = None  # to be used for defining atom distances
2255
2256    def LoadExpression(self,expr,exprVarLst,varSelect,varName,varValue,varRefflag):
2257        '''Load the expression and associated settings into the object. Raises
2258        an exception if the expression is not parsed, if not all functions
2259        are defined or if not all needed parameter labels in the expression
2260        are defined.
2261
2262        This will not test if the variable referenced in these definitions
2263        are actually in the parameter dictionary. This is checked when the
2264        computation for the expression is done in :meth:`SetupCalc`.
2265       
2266        :param str expr: the expression
2267        :param list exprVarLst: parameter labels found in the expression
2268        :param dict varSelect: this will be 0 for Free parameters
2269          and non-zero for expression labels linked to G2 variables.
2270        :param dict varName: Defines a name (str) associated with each free parameter
2271        :param dict varValue: Defines a value (float) associated with each free parameter
2272        :param dict varRefflag: Defines a refinement flag (bool)
2273          associated with each free parameter
2274        '''
2275        self.expression = expr
2276        self.compiledExpr = None
2277        self.freeVars = {}
2278        self.assgnVars = {}
2279        for v in exprVarLst:
2280            if varSelect[v] == 0:
2281                self.freeVars[v] = [
2282                    varName.get(v),
2283                    varValue.get(v),
2284                    varRefflag.get(v),
2285                    ]
2286            else:
2287                self.assgnVars[v] = varName[v]
2288        self.CheckVars()
2289
2290    def EditExpression(self,exprVarLst,varSelect,varName,varValue,varRefflag):
2291        '''Load the expression and associated settings from the object into
2292        arrays used for editing.
2293
2294        :param list exprVarLst: parameter labels found in the expression
2295        :param dict varSelect: this will be 0 for Free parameters
2296          and non-zero for expression labels linked to G2 variables.
2297        :param dict varName: Defines a name (str) associated with each free parameter
2298        :param dict varValue: Defines a value (float) associated with each free parameter
2299        :param dict varRefflag: Defines a refinement flag (bool)
2300          associated with each free parameter
2301
2302        :returns: the expression as a str
2303        '''
2304        for v in self.freeVars:
2305            varSelect[v] = 0
2306            varName[v] = self.freeVars[v][0]
2307            varValue[v] = self.freeVars[v][1]
2308            varRefflag[v] = self.freeVars[v][2]
2309        for v in self.assgnVars:
2310            varSelect[v] = 1
2311            varName[v] = self.assgnVars[v]
2312        return self.expression
2313
2314    def GetVaried(self):
2315        'Returns the names of the free parameters that will be refined'
2316        return ["::"+self.freeVars[v][0] for v in self.freeVars if self.freeVars[v][2]]
2317
2318    def GetVariedVarVal(self):
2319        'Returns the names and values of the free parameters that will be refined'
2320        return [("::"+self.freeVars[v][0],self.freeVars[v][1]) for v in self.freeVars if self.freeVars[v][2]]
2321
2322    def UpdateVariedVars(self,varyList,values):
2323        'Updates values for the free parameters (after a refinement); only updates refined vars'
2324        for v in self.freeVars:
2325            if not self.freeVars[v][2]: continue
2326            if "::"+self.freeVars[v][0] not in varyList: continue
2327            indx = varyList.index("::"+self.freeVars[v][0])
2328            self.freeVars[v][1] = values[indx]
2329
2330    def GetIndependentVars(self):
2331        'Returns the names of the required independent parameters used in expression'
2332        return [self.assgnVars[v] for v in self.assgnVars]
2333
2334    def CheckVars(self):
2335        '''Check that the expression can be parsed, all functions are
2336        defined and that input loaded into the object is internally
2337        consistent. If not an Exception is raised.
2338
2339        :returns: a dict with references to packages needed to
2340          find functions referenced in the expression.
2341        '''
2342        ret = self.ParseExpression(self.expression)
2343        if not ret:
2344            raise Exception("Expression parse error")
2345        exprLblList,fxnpkgdict = ret
2346        # check each var used in expression is defined
2347        defined = self.assgnVars.keys() + self.freeVars.keys()
2348        notfound = []
2349        for var in exprLblList:
2350            if var not in defined:
2351                notfound.append(var)
2352        if notfound:
2353            msg = 'Not all variables defined'
2354            msg1 = 'The following variables were not defined: '
2355            msg2 = ''
2356            for var in notfound:
2357                if msg: msg += ', '
2358                msg += var
2359            self.lastError = (msg1,'  '+msg2)
2360            raise Exception(msg)
2361        return fxnpkgdict
2362
2363    def ParseExpression(self,expr):
2364        '''Parse an expression and return a dict of called functions and
2365        the variables used in the expression. Returns None in case an error
2366        is encountered. If packages are referenced in functions, they are loaded
2367        and the functions are looked up into the modules global
2368        workspace.
2369       
2370        Note that no changes are made to the object other than
2371        saving an error message, so that this can be used for testing prior
2372        to the save.
2373
2374        :returns: a list of used variables
2375        '''
2376        self.lastError = ('','')
2377        import ast
2378        def FindFunction(f):
2379            '''Find the object corresponding to function f
2380            :param str f: a function name such as 'numpy.exp'
2381            :returns: (pkgdict,pkgobj) where pkgdict contains a dict
2382              that defines the package location(s) and where pkgobj
2383              defines the object associated with the function.
2384              If the function is not found, pkgobj is None.
2385            '''
2386            df = f.split('.')
2387            pkgdict = {}
2388            # no listed package, try in current namespace
2389            if len(df) == 1: 
2390                try:
2391                    fxnobj = eval(f)
2392                    return pkgdict,fxnobj
2393                except (AttributeError, NameError):
2394                    return None,None
2395            else:
2396                try:
2397                    fxnobj = eval(f)
2398                    pkgdict[df[0]] = eval(df[0])
2399                    return pkgdict,fxnobj
2400                except (AttributeError, NameError):
2401                    pass
2402            # includes a package, lets try to load the packages
2403            pkgname = ''
2404            path = sys.path
2405            for pkg in f.split('.')[:-1]: # if needed, descend down the tree
2406                if pkgname:
2407                    pkgname += '.' + pkg
2408                else:
2409                    pkgname = pkg
2410                fp = None
2411                try:
2412                    fp, fppath,desc = imp.find_module(pkg,path)
2413                    pkgobj = imp.load_module(pkg,fp,fppath,desc)
2414                    pkgdict[pkgname] = pkgobj
2415                    path = [fppath]
2416                except Exception as msg:
2417                    print('load of '+pkgname+' failed with error='+str(msg))
2418                    return {},None
2419                finally:
2420                    if fp: fp.close()
2421                try:
2422                    #print 'before',pkgdict.keys()
2423                    fxnobj = eval(f,globals(),pkgdict)
2424                    #print 'after 1',pkgdict.keys()
2425                    #fxnobj = eval(f,pkgdict)
2426                    #print 'after 2',pkgdict.keys()
2427                    return pkgdict,fxnobj
2428                except:
2429                    continue
2430            return None # not found
2431        def ASTtransverse(node,fxn=False):
2432            '''Transverse a AST-parsed expresson, compiling a list of variables
2433            referenced in the expression. This routine is used recursively.
2434
2435            :returns: varlist,fxnlist where
2436              varlist is a list of referenced variable names and
2437              fxnlist is a list of used functions
2438            '''
2439            varlist = []
2440            fxnlist = []
2441            if isinstance(node, list):
2442                for b in node:
2443                    v,f = ASTtransverse(b,fxn)
2444                    varlist += v
2445                    fxnlist += f
2446            elif isinstance(node, ast.AST):
2447                for a, b in ast.iter_fields(node):
2448                    if isinstance(b, ast.AST):
2449                        if a == 'func': 
2450                            fxnlist += ['.'.join(ASTtransverse(b,True)[0])]
2451                            continue
2452                        v,f = ASTtransverse(b,fxn)
2453                        varlist += v
2454                        fxnlist += f
2455                    elif isinstance(b, list):
2456                        v,f = ASTtransverse(b,fxn)
2457                        varlist += v
2458                        fxnlist += f
2459                    elif node.__class__.__name__ == "Name":
2460                        varlist += [b]
2461                    elif fxn and node.__class__.__name__ == "Attribute":
2462                        varlist += [b]
2463            return varlist,fxnlist
2464        try:
2465            exprast = ast.parse(expr)
2466        except SyntaxError:
2467            s = ''
2468            import traceback
2469            for i in traceback.format_exc().splitlines()[-3:-1]:
2470                if s: s += "\n"
2471                s += str(i)
2472            self.lastError = ("Error parsing expression:",s)
2473            return
2474        # find the variables & functions
2475        v,f = ASTtransverse(exprast)
2476        varlist = sorted(list(set(v)))
2477        fxnlist = list(set(f))
2478        pkgdict = {}
2479        # check the functions are defined
2480        for fxn in fxnlist:
2481            fxndict,fxnobj = FindFunction(fxn)
2482            if not fxnobj:
2483                self.lastError = ("Error: Invalid function",fxn,
2484                                  "is not defined")
2485                return
2486            if not hasattr(fxnobj,'__call__'):
2487                self.lastError = ("Error: Not a function.",fxn,
2488                                  "cannot be called as a function")
2489                return
2490            pkgdict.update(fxndict)
2491        return varlist,pkgdict
2492
2493    def GetDepVar(self):
2494        'return the dependent variable, or None'
2495        return self.depVar
2496
2497    def SetDepVar(self,var):
2498        'Set the dependent variable, if used'
2499        self.depVar = var
2500#==========================================================================
2501class ExpressionCalcObj(object):
2502    '''An object used to evaluate an expression from a :class:`ExpressionObj`
2503    object.
2504   
2505    :param ExpressionObj exprObj: a :class:`~ExpressionObj` expression object with
2506      an expression string and mappings for the parameter labels in that object.
2507    '''
2508    def __init__(self,exprObj):
2509        self.eObj = exprObj
2510        'The expression and mappings; a :class:`ExpressionObj` object'
2511        self.compiledExpr = None
2512        'The expression as compiled byte-code'
2513        self.exprDict = {}
2514        '''dict that defines values for labels used in expression and packages
2515        referenced by functions
2516        '''
2517        self.lblLookup = {}
2518        '''Lookup table that specifies the expression label name that is
2519        tied to a particular GSAS-II parameters in the parmDict.
2520        '''
2521        self.fxnpkgdict = {}
2522        '''a dict with references to packages needed to
2523        find functions referenced in the expression.
2524        '''
2525        self.varLookup = {}
2526        '''Lookup table that specifies the GSAS-II variable(s)
2527        indexed by the expression label name. (Used for only for diagnostics
2528        not evaluation of expression.)
2529        '''
2530        self.su = None
2531        '''Standard error evaluation where supplied by the evaluator
2532        '''
2533        # Patch: for old-style expressions with a (now removed step size)
2534        for v in self.eObj.assgnVars:
2535            if not isinstance(self.eObj.assgnVars[v], basestring):
2536                self.eObj.assgnVars[v] = self.eObj.assgnVars[v][0]
2537        self.parmDict = {}
2538        '''A copy of the parameter dictionary, for distance and angle computation
2539        '''
2540
2541    def SetupCalc(self,parmDict):
2542        '''Do all preparations to use the expression for computation.
2543        Adds the free parameter values to the parameter dict (parmDict).
2544        '''
2545        if self.eObj.expression.startswith('Dist') or self.eObj.expression.startswith('Angle'):
2546            return
2547        self.fxnpkgdict = self.eObj.CheckVars()
2548        # all is OK, compile the expression
2549        self.compiledExpr = compile(self.eObj.expression,'','eval')
2550
2551        # look at first value in parmDict to determine its type
2552        parmsInList = True
2553        for key in parmDict:
2554            val = parmDict[key]
2555            if isinstance(val, basestring):
2556                parmsInList = False
2557                break
2558            try: # check if values are in lists
2559                val = parmDict[key][0]
2560            except (TypeError,IndexError):
2561                parmsInList = False
2562            break
2563           
2564        # set up the dicts needed to speed computations
2565        self.exprDict = {}
2566        self.lblLookup = {}
2567        self.varLookup = {}
2568        for v in self.eObj.freeVars:
2569            varname = self.eObj.freeVars[v][0]
2570            varname = "::" + varname.lstrip(':').replace(' ','_').replace(':',';')
2571            self.lblLookup[varname] = v
2572            self.varLookup[v] = varname
2573            if parmsInList:
2574                parmDict[varname] = [self.eObj.freeVars[v][1],self.eObj.freeVars[v][2]]
2575            else:
2576                parmDict[varname] = self.eObj.freeVars[v][1]
2577            self.exprDict[v] = self.eObj.freeVars[v][1]
2578        for v in self.eObj.assgnVars:
2579            varname = self.eObj.assgnVars[v]
2580            if '*' in varname:
2581                varlist = LookupWildCard(varname,parmDict.keys())
2582                if len(varlist) == 0:
2583                    raise Exception,"No variables match "+str(v)
2584                for var in varlist:
2585                    self.lblLookup[var] = v
2586                if parmsInList:
2587                    self.exprDict[v] = np.array([parmDict[var][0] for var in varlist])
2588                else:
2589                    self.exprDict[v] = np.array([parmDict[var] for var in varlist])
2590                self.varLookup[v] = [var for var in varlist]
2591            elif varname in parmDict:
2592                self.lblLookup[varname] = v
2593                self.varLookup[v] = varname
2594                if parmsInList:
2595                    self.exprDict[v] = parmDict[varname][0]
2596                else:
2597                    self.exprDict[v] = parmDict[varname]
2598            else:
2599                self.exprDict[v] = None
2600#                raise Exception,"No value for variable "+str(v)
2601        self.exprDict.update(self.fxnpkgdict)
2602
2603    def UpdateVars(self,varList,valList):
2604        '''Update the dict for the expression with a set of values
2605        :param list varList: a list of variable names
2606        :param list valList: a list of corresponding values
2607        '''
2608        for var,val in zip(varList,valList):
2609            self.exprDict[self.lblLookup.get(var,'undefined: '+var)] = val
2610
2611    def UpdateDict(self,parmDict):
2612        '''Update the dict for the expression with values in a dict
2613        :param list parmDict: a dict of values some of which may be in use here
2614        '''
2615        if self.eObj.expression.startswith('Dist') or self.eObj.expression.startswith('Angle'):
2616            self.parmDict = parmDict
2617            return
2618        for var in parmDict:
2619            if var in self.lblLookup:
2620                self.exprDict[self.lblLookup[var]] = parmDict[var]
2621           
2622    def EvalExpression(self):
2623        '''Evaluate an expression. Note that the expression
2624        and mapping are taken from the :class:`ExpressionObj` expression object
2625        and the parameter values were specified in :meth:`SetupCalc`.
2626        :returns: a single value for the expression. If parameter
2627        values are arrays (for example, from wild-carded variable names),
2628        the sum of the resulting expression is returned.
2629
2630        For example, if the expression is ``'A*B'``,
2631        where A is 2.0 and B maps to ``'1::Afrac:*'``, which evaluates to::
2632
2633        [0.5, 1, 0.5]
2634
2635        then the result will be ``4.0``.
2636        '''
2637        self.su = None
2638        if self.eObj.expression.startswith('Dist'):
2639#            GSASIIpath.IPyBreak()
2640            dist = G2mth.CalcDist(self.eObj.distance_dict, self.eObj.distance_atoms, self.parmDict)
2641            return dist
2642        elif self.eObj.expression.startswith('Angle'):
2643            angle = G2mth.CalcAngle(self.eObj.angle_dict, self.eObj.angle_atoms, self.parmDict)
2644            return angle
2645        if self.compiledExpr is None:
2646            raise Exception,"EvalExpression called before SetupCalc"
2647        try:
2648            val = eval(self.compiledExpr,globals(),self.exprDict)
2649        except TypeError:
2650            val = None
2651        if not np.isscalar(val):
2652            val = np.sum(val)
2653        return val
2654       
2655class G2Exception(Exception):
2656    def __init__(self,msg):
2657        self.msg = msg
2658    def __str__(self):
2659        return repr(self.msg)
2660
2661def HowDidIgetHere(wherecalledonly=False):
2662    '''Show a traceback with calls that brought us to the current location.
2663    Used for debugging.
2664    '''
2665    import traceback
2666    if wherecalledonly:
2667        i = traceback.format_list(traceback.extract_stack()[:-1])[-2]
2668        print(i.strip().rstrip())
2669    else:
2670        print 70*'*'   
2671        for i in traceback.format_list(traceback.extract_stack()[:-1]): print(i.strip().rstrip())
2672        print 70*'*'   
2673               
2674def CreatePDFitems(G2frame,PWDRtree,ElList,Qlimits,numAtm=1,FltBkg=0,PDFnames=[]):
2675    '''Create and initialize a new set of PDF tree entries
2676
2677    :param Frame G2frame: main GSAS-II tree frame object
2678    :param str PWDRtree: name of PWDR to be used to create PDF item
2679    :param dict ElList: data structure with composition
2680    :param list Qlimits: Q limits to be used for computing the PDF
2681    :param float numAtm: no. atom in chemical formula
2682    :param float FltBkg: flat background value
2683    :param list PDFnames: previously used PDF names
2684   
2685    :returns: the Id of the newly created PDF entry
2686    '''
2687    PDFname = 'PDF '+PWDRtree[4:] # this places two spaces after PDF, which is needed is some places
2688    if PDFname in PDFnames:
2689        print('Skipping, entry already exists: '+PDFname)
2690        return None
2691    #PDFname = MakeUniqueLabel(PDFname,PDFnames)
2692    Id = G2frame.GPXtree.AppendItem(parent=G2frame.root,text=PDFname)
2693    Data = {
2694        'Sample':{'Name':PWDRtree,'Mult':1.0},
2695        'Sample Bkg.':{'Name':'','Mult':-1.0,'Refine':False},
2696        'Container':{'Name':'','Mult':-1.0,'Refine':False},
2697        'Container Bkg.':{'Name':'','Mult':-1.0},'ElList':ElList,
2698        'Geometry':'Cylinder','Diam':1.0,'Pack':0.50,'Form Vol':10.0*numAtm,'Flat Bkg':FltBkg,
2699        'DetType':'Area detector','ObliqCoeff':0.2,'Ruland':0.025,'QScaleLim':Qlimits,
2700        'Lorch':False,'BackRatio':0.0,'Rmax':100.,'noRing':False,'IofQmin':1.0,
2701        'I(Q)':[],'S(Q)':[],'F(Q)':[],'G(R)':[]}
2702    G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='PDF Controls'),Data)
2703    G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='PDF Peaks'),
2704        {'Limits':[1.,5.],'Background':[2,[0.,-0.2*np.pi],False],'Peaks':[]})
2705    return Id       
2706
2707
2708if __name__ == "__main__":
2709    # test equation evaluation
2710    def showEQ(calcobj):
2711        print 50*'='
2712        print calcobj.eObj.expression,'=',calcobj.EvalExpression()
2713        for v in sorted(calcobj.varLookup):
2714            print "  ",v,'=',calcobj.exprDict[v],'=',calcobj.varLookup[v]
2715        # print '  Derivatives'
2716        # for v in calcobj.derivStep.keys():
2717        #     print '    d(Expr)/d('+v+') =',calcobj.EvalDeriv(v)
2718
2719    obj = ExpressionObj()
2720
2721    obj.expression = "A*np.exp(B)"
2722    obj.assgnVars =  {'B': '0::Afrac:1'}
2723    obj.freeVars =  {'A': [u'A', 0.5, True]}
2724    #obj.CheckVars()
2725    calcobj = ExpressionCalcObj(obj)
2726
2727    obj1 = ExpressionObj()
2728    obj1.expression = "A*np.exp(B)"
2729    obj1.assgnVars =  {'B': '0::Afrac:*'}
2730    obj1.freeVars =  {'A': [u'Free Prm A', 0.5, True]}
2731    #obj.CheckVars()
2732    calcobj1 = ExpressionCalcObj(obj1)
2733
2734    obj2 = ExpressionObj()
2735    obj2.distance_stuff = np.array([[0,1],[1,-1]])
2736    obj2.expression = "Dist(1,2)"
2737    GSASIIpath.InvokeDebugOpts()
2738    parmDict2 = {'0::Afrac:0':[0.0,True], '0::Afrac:1': [1.0,False]}
2739    calcobj2 = ExpressionCalcObj(obj2)
2740    calcobj2.SetupCalc(parmDict2)
2741    showEQ(calcobj2)
2742   
2743    parmDict1 = {'0::Afrac:0':1.0, '0::Afrac:1': 1.0}
2744    print '\nDict = ',parmDict1
2745    calcobj.SetupCalc(parmDict1)
2746    showEQ(calcobj)
2747    calcobj1.SetupCalc(parmDict1)
2748    showEQ(calcobj1)
2749
2750    parmDict2 = {'0::Afrac:0':[0.0,True], '0::Afrac:1': [1.0,False]}
2751    print 'Dict = ',parmDict2
2752    calcobj.SetupCalc(parmDict2)
2753    showEQ(calcobj)
2754    calcobj1.SetupCalc(parmDict2)
2755    showEQ(calcobj1)
2756    calcobj2.SetupCalc(parmDict2)
2757    showEQ(calcobj2)
Note: See TracBrowser for help on using the repository browser.