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

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

fix potential unicode errors in GSASIIdtaGUI; addition parameter definition

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 127.8 KB
Line 
1# -*- coding: utf-8 -*-
2#GSASIIobj - data objects for GSAS-II
3########### SVN repository information ###################
4# $Date: 2017-08-11 14:11:21 +0000 (Fri, 11 Aug 2017) $
5# $Author: toby $
6# $Revision: 2995 $
7# $URL: branch/2frame/GSASIIobj.py $
8# $Id: GSASIIobj.py 2995 2017-08-11 14:11:21Z toby $
9########### SVN repository information ###################
10
11'''
12*GSASIIobj: Data objects*
13=========================
14
15This module defines and/or documents the data structures used in GSAS-II, 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: 2995 $")
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        'C\([0-9]*,[0-9]*\)' : 'spherical harmonics preferred orientation coef.',
1535        }.items():
1536        VarDesc[key] = value
1537        reVarDesc[re.compile(key)] = value
1538
1539def getDescr(name):
1540    '''Return a short description for a GSAS-II variable
1541
1542    :param str name: The descriptive part of the variable name without colons (:)
1543     
1544    :returns: a short description or None if not found
1545    '''
1546
1547    CompileVarDesc() # compile the regular expressions, if needed
1548    for key in reVarDesc:
1549        m = key.match(name)
1550        if m:
1551            reVarDesc[key]
1552            return m.expand(reVarDesc[key])
1553    return None
1554
1555def GenWildCard(varlist):
1556    '''Generate wildcard versions of G2 variables. These introduce '*'
1557    for a phase, histogram or atom number (but only for one of these
1558    fields) but only when there is more than one matching variable in the
1559    input variable list. So if the input is this::
1560   
1561      varlist = ['0::AUiso:0', '0::AUiso:1', '1::AUiso:0']
1562
1563    then the output will be this::
1564   
1565       wildList = ['*::AUiso:0', '0::AUiso:*']
1566
1567    :param list varlist: an input list of GSAS-II variable names
1568      (such as 0::AUiso:0)
1569
1570    :returns: wildList, the generated list of wild card variable names.
1571    '''
1572    wild = []
1573    for i in (0,1,3):
1574        currentL = varlist[:]
1575        while currentL:
1576            item1 = currentL.pop(0)
1577            i1splt = item1.split(':')
1578            if i >= len(i1splt): continue
1579            if i1splt[i]:
1580                nextL = []
1581                i1splt[i] = '[0-9]+'
1582                rexp = re.compile(':'.join(i1splt))
1583                matchlist = [item1]
1584                for nxtitem in currentL:
1585                    if rexp.match(nxtitem):
1586                        matchlist += [nxtitem]
1587                    else:
1588                        nextL.append(nxtitem)
1589                if len(matchlist) > 1:
1590                    i1splt[i] = '*'
1591                    wild.append(':'.join(i1splt))
1592                currentL = nextL
1593    return wild
1594
1595def LookupWildCard(varname,varlist):
1596    '''returns a list of variable names from list varname
1597    that match wildcard name in varname
1598   
1599    :param str varname: a G2 variable name containing a wildcard
1600      (such as \*::var)
1601    :param list varlist: the list of all variable names used in
1602      the current project
1603    :returns: a list of matching GSAS-II variables (may be empty) 
1604    '''
1605    rexp = re.compile(varname.replace('*','[0-9]+'))
1606    return sorted([var for var in varlist if rexp.match(var)])
1607
1608
1609def _lookup(dic,key):
1610    '''Lookup a key in a dictionary, where None returns an empty string
1611    but an unmatched key returns a question mark. Used in :class:`G2VarObj`
1612    '''
1613    if key is None:
1614        return ""
1615    elif key == "*":
1616        return "*"
1617    else:
1618        return dic.get(key,'?')
1619
1620class G2VarObj(object):
1621    '''Defines a GSAS-II variable either using the phase/atom/histogram
1622    unique Id numbers or using a character string that specifies
1623    variables by phase/atom/histogram number (which can change).
1624    Note that :func:`LoadID` should be used to (re)load the current Ids
1625    before creating or later using the G2VarObj object.
1626
1627    This can store rigid body variables, but does not translate the residue # and
1628    body # to/from random Ids
1629
1630    A :class:`G2VarObj` object can be created with a single parameter:
1631   
1632    :param str/tuple varname: a single value can be used to create a :class:`G2VarObj`
1633      object. If a string, it must be of form "p:h:var" or "p:h:var:a", where
1634
1635     * p is the phase number (which may be left blank or may be '*' to indicate all phases);
1636     * h is the histogram number (which may be left blank or may be '*' to indicate all histograms);
1637     * a is the atom number (which may be left blank in which case the third colon is omitted).
1638       The atom number can be specified as '*' if a phase number is specified (not as '*').
1639       For rigid body variables, specify a will be a string of form "residue:body#"
1640
1641      Alternately a single tuple of form (Phase,Histogram,VarName,AtomID) can be used, where
1642      Phase, Histogram, and AtomID are None or are ranId values (or one can be '*')
1643      and VarName is a string. Note that if Phase is '*' then the AtomID is an atom number.
1644      For a rigid body variables, AtomID is a string of form "residue:body#".
1645
1646    If four positional arguments are supplied, they are:
1647
1648    :param str/int phasenum: The number for the phase (or None or '*')
1649    :param str/int histnum: The number for the histogram (or None or '*')
1650    :param str varname: a single value can be used to create a :class:`G2VarObj`
1651    :param str/int atomnum: The number for the atom (or None or '*')
1652   
1653    '''
1654    IDdict = {}
1655    IDdict['phases'] = {}
1656    IDdict['hists'] = {}
1657    IDdict['atoms'] = {}
1658    def __init__(self,*args):
1659        self.phase = None
1660        self.histogram = None
1661        self.name = ''
1662        self.atom = None
1663        if len(args) == 1 and (type(args[0]) is list or type(args[0]) is tuple) and len(args[0]) == 4:
1664            # single arg with 4 values
1665            self.phase,self.histogram,self.name,self.atom = args[0]
1666        elif len(args) == 1 and ':' in args[0]:
1667            #parse a string
1668            lst = args[0].split(':')
1669            if lst[0] == '*':
1670                self.phase = '*'
1671                if len(lst) > 3:
1672                    self.atom = lst[3]
1673                self.histogram = HistIdLookup.get(lst[1],[None,None])[1]
1674            elif lst[1] == '*':           
1675                self.histogram = '*'
1676                self.phase = PhaseIdLookup.get(lst[0],[None,None])[1]
1677            else:
1678                self.histogram = HistIdLookup.get(lst[1],[None,None])[1]
1679                self.phase = PhaseIdLookup.get(lst[0],[None,None])[1]
1680                if len(lst) == 4:
1681                    if lst[3] == '*':
1682                        self.atom = '*'
1683                    else:
1684                        self.atom = AtomIdLookup[lst[0]].get(lst[3],[None,None])[1]
1685                elif len(lst) == 5:
1686                    self.atom = lst[3]+":"+lst[4]
1687                elif len(lst) == 3:
1688                    pass
1689                else:
1690                    raise Exception,"Too many colons in var name "+str(args[0])
1691            self.name = lst[2]
1692        elif len(args) == 4:
1693            if args[0] == '*':
1694                self.phase = '*'
1695                self.atom = args[3]
1696            else:
1697                self.phase = PhaseIdLookup.get(str(args[0]),[None,None])[1]
1698                if args[3] == '*':
1699                    self.atom = '*'
1700                elif args[0] is not None:
1701                    self.atom = AtomIdLookup[args[0]].get(str(args[3]),[None,None])[1]
1702            if args[1] == '*':
1703                self.histogram = '*'
1704            else:
1705                self.histogram = HistIdLookup.get(str(args[1]),[None,None])[1]
1706            self.name = args[2]
1707        else:
1708            raise Exception,"Incorrectly called GSAS-II parameter name"
1709
1710        #print "DEBUG: created ",self.phase,self.histogram,self.name,self.atom
1711
1712    def __str__(self):
1713        return self.varname()
1714
1715    def varname(self):
1716        '''Formats the GSAS-II variable name as a "traditional" GSAS-II variable
1717        string (p:h:<var>:a) or (p:h:<var>)
1718
1719        :returns: the variable name as a str
1720        '''
1721        a = ""
1722        if self.phase == "*":
1723            ph = "*"
1724            if self.atom:
1725                a = ":" + str(self.atom)
1726        else:
1727            ph = _lookup(PhaseRanIdLookup,self.phase)
1728            if self.atom == '*':
1729                a = ':*'
1730            elif self.atom:
1731                if ":" in str(self.atom):
1732                    a = ":" + str(self.atom)
1733                elif ph in AtomRanIdLookup:
1734                    a = ":" + AtomRanIdLookup[ph].get(self.atom,'?')
1735                else:
1736                    a = ":?"
1737        if self.histogram == "*":
1738            hist = "*"
1739        else:
1740            hist = _lookup(HistRanIdLookup,self.histogram)
1741        s = (ph + ":" + hist + ":" + str(self.name)) + a
1742        return s
1743   
1744    def __repr__(self):
1745        '''Return the detailed contents of the object
1746        '''
1747        s = "<"
1748        if self.phase == '*':
1749            s += "Phases: all; "
1750            if self.atom is not None:
1751                if ":" in str(self.atom):
1752                    s += "Rigid body" + str(self.atom) + "; "
1753                else:
1754                    s += "Atom #" + str(self.atom) + "; "
1755        elif self.phase is not None:
1756            ph =  _lookup(PhaseRanIdLookup,self.phase)
1757            s += "Phase: rId=" + str(self.phase) + " (#"+ ph + "); "
1758            if self.atom == '*':
1759                s += "Atoms: all; "
1760            elif ":" in str(self.atom):
1761                s += "Rigid body" + str(self.atom) + "; "
1762            elif self.atom is not None:
1763                s += "Atom rId=" + str(self.atom)
1764                if ph in AtomRanIdLookup:
1765                    s += " (#" + AtomRanIdLookup[ph].get(self.atom,'?') + "); "
1766                else:
1767                    s += " (#? -- not found!); "
1768        if self.histogram == '*':
1769            s += "Histograms: all; "
1770        elif self.histogram is not None:
1771            hist = _lookup(HistRanIdLookup,self.histogram)
1772            s += "Histogram: rId=" + str(self.histogram) + " (#"+ hist + "); "
1773        s += 'Variable name="' + str(self.name) + '">'
1774        return s+" ("+self.varname()+")"
1775
1776    def __eq__(self, other):
1777        if type(other) is type(self):
1778            return (self.phase == other.phase and
1779                    self.histogram == other.histogram and
1780                    self.name == other.name and
1781                    self.atom == other.atom)
1782        return False
1783
1784    def _show(self):
1785        'For testing, shows the current lookup table'
1786        print 'phases', self.IDdict['phases']
1787        print 'hists', self.IDdict['hists']
1788        print 'atomDict', self.IDdict['atoms']
1789
1790#==========================================================================
1791def SetDefaultSample():
1792    'Fills in default items for the Sample dictionary for Debye-Scherrer & SASD'
1793    return {
1794        'InstrName':'',
1795        'ranId':ran.randint(0,sys.maxint),
1796        'Scale':[1.0,True],'Type':'Debye-Scherrer','Absorption':[0.0,False],
1797        'DisplaceX':[0.0,False],'DisplaceY':[0.0,False],'Diffuse':[],
1798        'Temperature':300.,'Pressure':0.1,'Time':0.0,
1799        'FreePrm1':0.,'FreePrm2':0.,'FreePrm3':0.,
1800        'Gonio. radius':200.0,
1801        'Omega':0.0,'Chi':0.0,'Phi':0.0,'Azimuth':0.0,
1802#SASD items
1803        'Materials':[{'Name':'vacuum','VolFrac':1.0,},{'Name':'vacuum','VolFrac':0.0,}],
1804        'Thick':1.0,'Contrast':[0.0,0.0],       #contrast & anomalous contrast
1805        'Trans':1.0,                            #measured transmission
1806        'SlitLen':0.0,                          #Slit length - in Q(A-1)
1807        }
1808######################################################################
1809class ImportBaseclass(object):
1810    '''Defines a base class for the reading of input files (diffraction
1811    data, coordinates,...). See :ref:`Writing a Import Routine<Import_routines>`
1812    for an explanation on how to use a subclass of this class.
1813    '''
1814    class ImportException(Exception):
1815        '''Defines an Exception that is used when an import routine hits an expected error,
1816        usually in .Reader.
1817
1818        Good practice is that the Reader should define a value in self.errors that
1819        tells the user some information about what is wrong with their file.         
1820        '''
1821        pass
1822   
1823    UseReader = True  # in __init__ set value of self.UseReader to False to skip use of current importer
1824    def __init__(self,formatName,longFormatName=None,
1825                 extensionlist=[],strictExtension=False,):
1826        self.formatName = formatName # short string naming file type
1827        if longFormatName: # longer string naming file type
1828            self.longFormatName = longFormatName
1829        else:
1830            self.longFormatName = formatName
1831        # define extensions that are allowed for the file type
1832        # for windows, remove any extensions that are duplicate, as case is ignored
1833        if sys.platform == 'windows' and extensionlist:
1834            extensionlist = list(set([s.lower() for s in extensionlist]))
1835        self.extensionlist = extensionlist
1836        # If strictExtension is True, the file will not be read, unless
1837        # the extension matches one in the extensionlist
1838        self.strictExtension = strictExtension
1839        self.errors = ''
1840        self.warnings = ''
1841        self.SciPy = False          #image reader needed scipy
1842        # used for readers that will use multiple passes to read
1843        # more than one data block
1844        self.repeat = False
1845        self.selections = []
1846        self.repeatcount = 0
1847        self.readfilename = '?'
1848        self.scriptable = False
1849        #print 'created',self.__class__
1850
1851    def ReInitialize(self):
1852        'Reinitialize the Reader to initial settings'
1853        self.errors = ''
1854        self.warnings = ''
1855        self.SciPy = False          #image reader needed scipy
1856        self.repeat = False
1857        self.repeatcount = 0
1858        self.readfilename = '?'
1859
1860       
1861#    def Reader(self, filename, filepointer, ParentFrame=None, **unused):
1862#        '''This method must be supplied in the child class to read the file.
1863#        if the read fails either return False or raise an Exception
1864#        preferably of type ImportException.
1865#        '''
1866#        #start reading
1867#        raise ImportException("Error occurred while...")
1868#        self.errors += "Hint for user on why the error occur
1869#        return False # if an error occurs
1870#        return True # if read OK
1871
1872    def ExtensionValidator(self, filename):
1873        '''This methods checks if the file has the correct extension
1874        Return False if this filename will not be supported by this reader
1875        Return True if the extension matches the list supplied by the reader
1876        Return None if the reader allows un-registered extensions
1877        '''
1878        if filename:
1879            ext = ospath.splitext(filename)[1]
1880            if sys.platform == 'windows': ext = ext.lower()
1881            if ext in self.extensionlist: return True
1882            if self.strictExtension: return False
1883        return None
1884
1885    def ContentsValidator(self, filepointer):
1886        '''This routine will attempt to determine if the file can be read
1887        with the current format.
1888        This will typically be overridden with a method that
1889        takes a quick scan of [some of]
1890        the file contents to do a "sanity" check if the file
1891        appears to match the selected format.
1892        '''
1893        #filepointer.seek(0) # rewind the file pointer
1894        return True
1895
1896    def CIFValidator(self, filepointer):
1897        '''A :meth:`ContentsValidator` for use to validate CIF files.
1898        '''
1899        for i,l in enumerate(filepointer):
1900            if i >= 1000: return True
1901            '''Encountered only blank lines or comments in first 1000
1902            lines. This is unlikely, but assume it is CIF anyway, since we are
1903            even less likely to find a file with nothing but hashes and
1904            blank lines'''
1905            line = l.strip()
1906            if len(line) == 0: # ignore blank lines
1907                continue 
1908            elif line.startswith('#'): # ignore comments
1909                continue 
1910            elif line.startswith('data_'): # on the right track, accept this file
1911                return True
1912            else: # found something invalid
1913                self.errors = 'line '+str(i+1)+' contains unexpected data:\n'
1914                if all([ord(c) < 128 and ord(c) != 0 for c in str(l)]): # show only if ASCII
1915                    self.errors += '  '+str(l)
1916                else: 
1917                    self.errors += '  (binary)'
1918                self.errors += '\n  Note: a CIF should only have blank lines or comments before'
1919                self.errors += '\n        a data_ statement begins a block.'
1920                return False 
1921
1922######################################################################
1923class ImportPhase(ImportBaseclass):
1924    '''Defines a base class for the reading of files with coordinates
1925
1926    Objects constructed that subclass this (in import/G2phase_*.py etc.) will be used
1927    in :meth:`GSASIIdataGUI.GSASII.OnImportPhase`.
1928    See :ref:`Writing a Import Routine<Import_Routines>`
1929    for an explanation on how to use this class.
1930
1931    '''
1932    def __init__(self,formatName,longFormatName=None,extensionlist=[],
1933        strictExtension=False,):
1934        # call parent __init__
1935        ImportBaseclass.__init__(self,formatName,longFormatName,
1936            extensionlist,strictExtension)
1937        self.Phase = None # a phase must be created with G2IO.SetNewPhase in the Reader
1938        self.Constraints = None
1939
1940######################################################################
1941class ImportStructFactor(ImportBaseclass):
1942    '''Defines a base class for the reading of files with tables
1943    of structure factors.
1944
1945    Structure factors are read with a call to :meth:`GSASIIdataGUI.GSASII.OnImportSfact`
1946    which in turn calls :meth:`GSASIIdataGUI.GSASII.OnImportGeneric`, which calls
1947    methods :meth:`ExtensionValidator`, :meth:`ContentsValidator` and
1948    :meth:`Reader`.
1949
1950    See :ref:`Writing a Import Routine<Import_Routines>`
1951    for an explanation on how to use import classes in general. The specifics
1952    for reading a structure factor histogram require that
1953    the ``Reader()`` routine in the import
1954    class need to do only a few things: It
1955    should load :attr:`RefDict` item ``'RefList'`` with the reflection list,
1956    and set :attr:`Parameters` with the instrument parameters
1957    (initialized with :meth:`InitParameters` and set with :meth:`UpdateParameters`).
1958    '''
1959    def __init__(self,formatName,longFormatName=None,extensionlist=[],
1960        strictExtension=False,):
1961        ImportBaseclass.__init__(self,formatName,longFormatName,
1962            extensionlist,strictExtension)
1963
1964        # define contents of Structure Factor entry
1965        self.Parameters = []
1966        'self.Parameters is a list with two dicts for data parameter settings'
1967        self.InitParameters()
1968        self.RefDict = {'RefList':[],'FF':{},'Super':0}
1969        self.Banks = []             #for multi bank data (usually TOF)
1970        '''self.RefDict is a dict containing the reflection information, as read from the file.
1971        Item 'RefList' contains the reflection information. See the
1972        :ref:`Single Crystal Reflection Data Structure<XtalRefl_table>`
1973        for the contents of each row. Dict element 'FF'
1974        contains the form factor values for each element type; if this entry
1975        is left as initialized (an empty list) it will be initialized as needed later.
1976        '''
1977    def ReInitialize(self):
1978        'Reinitialize the Reader to initial settings'
1979        ImportBaseclass.ReInitialize(self)
1980        self.InitParameters()
1981        self.Banks = []             #for multi bank data (usually TOF)
1982        self.RefDict = {'RefList':[],'FF':{},'Super':0}
1983       
1984    def InitParameters(self):
1985        'initialize the instrument parameters structure'
1986        Lambda = 0.70926
1987        HistType = 'SXC'
1988        self.Parameters = [{'Type':[HistType,HistType], # create the structure
1989                            'Lam':[Lambda,Lambda]
1990                            }, {}]
1991        'Parameters is a list with two dicts for data parameter settings'
1992
1993    def UpdateParameters(self,Type=None,Wave=None):
1994        'Revise the instrument parameters'
1995        if Type is not None:
1996            self.Parameters[0]['Type'] = [Type,Type]
1997        if Wave is not None:
1998            self.Parameters[0]['Lam'] = [Wave,Wave]           
1999                       
2000######################################################################
2001class ImportPowderData(ImportBaseclass):
2002    '''Defines a base class for the reading of files with powder data.
2003
2004    Objects constructed that subclass this (in import/G2pwd_*.py etc.) will be used
2005    in :meth:`GSASIIdataGUI.GSASII.OnImportPowder`.
2006    See :ref:`Writing a Import Routine<Import_Routines>`
2007    for an explanation on how to use this class.
2008    '''
2009    def __init__(self,formatName,longFormatName=None,
2010        extensionlist=[],strictExtension=False,):
2011        ImportBaseclass.__init__(self,formatName,longFormatName,
2012            extensionlist,strictExtension)
2013        self.clockWd = None  # used in TOF
2014        self.ReInitialize()
2015       
2016    def ReInitialize(self):
2017        'Reinitialize the Reader to initial settings'
2018        ImportBaseclass.ReInitialize(self)
2019        self.powderentry = ['',None,None] #  (filename,Pos,Bank)
2020        self.powderdata = [] # Powder dataset
2021        '''A powder data set is a list with items [x,y,w,yc,yb,yd]:
2022                np.array(x), # x-axis values
2023                np.array(y), # powder pattern intensities
2024                np.array(w), # 1/sig(intensity)^2 values (weights)
2025                np.array(yc), # calc. intensities (zero)
2026                np.array(yb), # calc. background (zero)
2027                np.array(yd), # obs-calc profiles
2028        '''                           
2029        self.comments = []
2030        self.idstring = ''
2031        self.Sample = SetDefaultSample() # default sample parameters
2032        self.Controls = {}  # items to be placed in top-level Controls
2033        self.GSAS = None     # used in TOF
2034        self.repeat_instparm = True # Should a parm file be
2035        #                             used for multiple histograms?
2036        self.instparm = None # name hint from file of instparm to use
2037        self.instfile = '' # full path name to instrument parameter file
2038        self.instbank = '' # inst parm bank number
2039        self.instmsg = ''  # a label that gets printed to show
2040                           # where instrument parameters are from
2041        self.numbanks = 1
2042        self.instdict = {} # place items here that will be transferred to the instrument parameters
2043        self.pwdparms = {} # place parameters that are transferred directly to the tree
2044                           # here (typically from an existing GPX file)
2045######################################################################
2046class ImportSmallAngleData(ImportBaseclass):
2047    '''Defines a base class for the reading of files with small angle data.
2048    See :ref:`Writing a Import Routine<Import_Routines>`
2049    for an explanation on how to use this class.
2050    '''
2051    def __init__(self,formatName,longFormatName=None,extensionlist=[],
2052        strictExtension=False,):
2053           
2054        ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist,
2055            strictExtension)
2056        self.ReInitialize()
2057       
2058    def ReInitialize(self):
2059        'Reinitialize the Reader to initial settings'
2060        ImportBaseclass.ReInitialize(self)
2061        self.smallangleentry = ['',None,None] #  (filename,Pos,Bank)
2062        self.smallangledata = [] # SASD dataset
2063        '''A small angle data set is a list with items [x,y,w,yc,yd]:
2064                np.array(x), # x-axis values
2065                np.array(y), # powder pattern intensities
2066                np.array(w), # 1/sig(intensity)^2 values (weights)
2067                np.array(yc), # calc. intensities (zero)
2068                np.array(yd), # obs-calc profiles
2069                np.array(yb), # preset bkg
2070        '''                           
2071        self.comments = []
2072        self.idstring = ''
2073        self.Sample = SetDefaultSample()
2074        self.GSAS = None     # used in TOF
2075        self.clockWd = None  # used in TOF
2076        self.numbanks = 1
2077        self.instdict = {} # place items here that will be transferred to the instrument parameters
2078
2079######################################################################
2080class ImportReflectometryData(ImportBaseclass):
2081    '''Defines a base class for the reading of files with reflectometry data.
2082    See :ref:`Writing a Import Routine<Import_Routines>`
2083    for an explanation on how to use this class.
2084    '''
2085    def __init__(self,formatName,longFormatName=None,extensionlist=[],
2086        strictExtension=False,):
2087           
2088        ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist,
2089            strictExtension)
2090        self.ReInitialize()
2091       
2092    def ReInitialize(self):
2093        'Reinitialize the Reader to initial settings'
2094        ImportBaseclass.ReInitialize(self)
2095        self.reflectometryentry = ['',None,None] #  (filename,Pos,Bank)
2096        self.reflectometrydata = [] # SASD dataset
2097        '''A small angle data set is a list with items [x,y,w,yc,yd]:
2098                np.array(x), # x-axis values
2099                np.array(y), # powder pattern intensities
2100                np.array(w), # 1/sig(intensity)^2 values (weights)
2101                np.array(yc), # calc. intensities (zero)
2102                np.array(yd), # obs-calc profiles
2103                np.array(yb), # preset bkg
2104        '''                           
2105        self.comments = []
2106        self.idstring = ''
2107        self.Sample = SetDefaultSample()
2108        self.GSAS = None     # used in TOF
2109        self.clockWd = None  # used in TOF
2110        self.numbanks = 1
2111        self.instdict = {} # place items here that will be transferred to the instrument parameters
2112
2113######################################################################
2114class ImportPDFData(ImportBaseclass):
2115    '''Defines a base class for the reading of files with PDF G(R) data.
2116    See :ref:`Writing a Import Routine<Import_Routines>`
2117    for an explanation on how to use this class.
2118    '''
2119    def __init__(self,formatName,longFormatName=None,extensionlist=[],
2120        strictExtension=False,):
2121           
2122        ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist,
2123            strictExtension)
2124        self.ReInitialize()
2125       
2126    def ReInitialize(self):
2127        'Reinitialize the Reader to initial settings'
2128        ImportBaseclass.ReInitialize(self)
2129        self.pdfentry = ['',None,None] #  (filename,Pos,Bank)
2130        self.pdfdata = [] # PDF G(R) dataset
2131        '''A pdf g(r) data set is a list with items [x,y]:
2132                np.array(x), # r-axis values
2133                np.array(y), # pdf g(r)
2134        '''                           
2135        self.comments = []
2136        self.idstring = ''
2137        self.numbanks = 1
2138
2139######################################################################
2140class ImportImage(ImportBaseclass):
2141    '''Defines a base class for the reading of images
2142
2143    Images are read in only these places:
2144   
2145      * Initial reading is typically done from a menu item
2146        with a call to :meth:`GSASIIdataGUI.GSASII.OnImportImage`
2147        which in turn calls :meth:`GSASIIdataGUI.GSASII.OnImportGeneric`. That calls
2148        methods :meth:`ExtensionValidator`, :meth:`ContentsValidator` and
2149        :meth:`Reader`. This returns a list of reader objects for each read image.
2150
2151      * Images are read alternatively in :func:`GSASIIIO.ReadImages`, which puts image info
2152        directly into the data tree.
2153
2154      * Images are reloaded with :func:`GSASIIIO.GetImageData`.
2155
2156    .. _Image_import_routines:
2157
2158    When reading an image, the ``Reader()`` routine in the ImportImage class
2159    should set:
2160   
2161      * :attr:`Comments`: a list of strings (str),
2162      * :attr:`Npix`: the number of pixels in the image (int),
2163      * :attr:`Image`: the actual image as a numpy array (np.array)
2164      * :attr:`Data`: a dict defining image parameters (dict). Within this dict the following
2165        data items are needed:
2166       
2167         * 'pixelSize': size of each pixel in microns (such as ``[200,200]``.
2168         * 'wavelength': wavelength in Angstoms.
2169         * 'distance': distance of detector from sample in cm.
2170         * 'center': uncalibrated center of beam on detector (such as ``[204.8,204.8]``.
2171         * 'size': size of image (such as ``[2048,2048]``).
2172         * 'ImageTag': image number or other keyword used to retrieve image from
2173           a multi-image data file (defaults to ``1`` if not specified).
2174         * 'sumfile': holds sum image file name if a sum was produced from a multi image file
2175
2176    optional data items:
2177   
2178      * :attr:`repeat`: set to True if there are additional images to
2179        read in the file, False otherwise
2180      * :attr:`repeatcount`: set to the number of the image.
2181     
2182    Note that the above is initialized with :meth:`InitParameters`.
2183    (Also see :ref:`Writing a Import Routine<Import_Routines>`
2184    for an explanation on how to use import classes in general.)
2185    '''
2186    def __init__(self,formatName,longFormatName=None,extensionlist=[],
2187        strictExtension=False,):
2188        ImportBaseclass.__init__(self,formatName,longFormatName,
2189            extensionlist,strictExtension)
2190        self.InitParameters()
2191       
2192    def ReInitialize(self):
2193        'Reinitialize the Reader to initial settings -- not used at present'
2194        ImportBaseclass.ReInitialize(self)
2195        self.InitParameters()
2196       
2197    def InitParameters(self):
2198        'initialize the instrument parameters structure'
2199        self.Comments = ['No comments']
2200        self.Data = {}
2201        self.Npix = 0
2202        self.Image = None
2203        self.repeat = False
2204        self.repeatcount = 1
2205        self.sumfile = ''
2206
2207    def LoadImage(self,ParentFrame,imagefile,imagetag=None):
2208        '''Optionally, call this after reading in an image to load it into the tree.
2209        This saves time by preventing a reread of the same information.
2210        '''
2211        if ParentFrame:
2212            ParentFrame.ImageZ = self.Image   # store the image for plotting
2213            ParentFrame.oldImagefile = imagefile # save the name of the last image file read
2214            ParentFrame.oldImageTag = imagetag   # save the tag of the last image file read           
2215
2216#################################################################################################
2217# shortcut routines
2218exp = np.exp
2219sind = sin = s = lambda x: np.sin(x*np.pi/180.)
2220cosd = cos = c = lambda x: np.cos(x*np.pi/180.)
2221tand = tan = t = lambda x: np.tan(x*np.pi/180.)
2222sqrt = sq = lambda x: np.sqrt(x)
2223pi = lambda: np.pi
2224class ExpressionObj(object):
2225    '''Defines an object with a user-defined expression, to be used for
2226    secondary fits or restraints. Object is created null, but is changed
2227    using :meth:`LoadExpression`. This contains only the minimum
2228    information that needs to be stored to save and load the expression
2229    and how it is mapped to GSAS-II variables.
2230    '''
2231    def __init__(self):
2232        self.expression = ''
2233        'The expression as a text string'
2234        self.assgnVars = {}
2235        '''A dict where keys are label names in the expression mapping to a GSAS-II
2236        variable. The value a G2 variable name.
2237        Note that the G2 variable name may contain a wild-card and correspond to
2238        multiple values.
2239        '''
2240        self.freeVars = {}
2241        '''A dict where keys are label names in the expression mapping to a free
2242        parameter. The value is a list with:
2243
2244         * a name assigned to the parameter
2245         * a value for to the parameter and
2246         * a flag to determine if the variable is refined.
2247        ''' 
2248        self.depVar = None
2249
2250        self.lastError = ('','')
2251        '''Shows last encountered error in processing expression
2252        (list of 1-3 str values)'''
2253
2254        self.distance_dict  = None  # to be used for defining atom phase/symmetry info
2255        self.distance_atoms = None  # to be used for defining atom distances
2256
2257    def LoadExpression(self,expr,exprVarLst,varSelect,varName,varValue,varRefflag):
2258        '''Load the expression and associated settings into the object. Raises
2259        an exception if the expression is not parsed, if not all functions
2260        are defined or if not all needed parameter labels in the expression
2261        are defined.
2262
2263        This will not test if the variable referenced in these definitions
2264        are actually in the parameter dictionary. This is checked when the
2265        computation for the expression is done in :meth:`SetupCalc`.
2266       
2267        :param str expr: the expression
2268        :param list exprVarLst: parameter labels found in the expression
2269        :param dict varSelect: this will be 0 for Free parameters
2270          and non-zero for expression labels linked to G2 variables.
2271        :param dict varName: Defines a name (str) associated with each free parameter
2272        :param dict varValue: Defines a value (float) associated with each free parameter
2273        :param dict varRefflag: Defines a refinement flag (bool)
2274          associated with each free parameter
2275        '''
2276        self.expression = expr
2277        self.compiledExpr = None
2278        self.freeVars = {}
2279        self.assgnVars = {}
2280        for v in exprVarLst:
2281            if varSelect[v] == 0:
2282                self.freeVars[v] = [
2283                    varName.get(v),
2284                    varValue.get(v),
2285                    varRefflag.get(v),
2286                    ]
2287            else:
2288                self.assgnVars[v] = varName[v]
2289        self.CheckVars()
2290
2291    def EditExpression(self,exprVarLst,varSelect,varName,varValue,varRefflag):
2292        '''Load the expression and associated settings from the object into
2293        arrays used for editing.
2294
2295        :param list exprVarLst: parameter labels found in the expression
2296        :param dict varSelect: this will be 0 for Free parameters
2297          and non-zero for expression labels linked to G2 variables.
2298        :param dict varName: Defines a name (str) associated with each free parameter
2299        :param dict varValue: Defines a value (float) associated with each free parameter
2300        :param dict varRefflag: Defines a refinement flag (bool)
2301          associated with each free parameter
2302
2303        :returns: the expression as a str
2304        '''
2305        for v in self.freeVars:
2306            varSelect[v] = 0
2307            varName[v] = self.freeVars[v][0]
2308            varValue[v] = self.freeVars[v][1]
2309            varRefflag[v] = self.freeVars[v][2]
2310        for v in self.assgnVars:
2311            varSelect[v] = 1
2312            varName[v] = self.assgnVars[v]
2313        return self.expression
2314
2315    def GetVaried(self):
2316        'Returns the names of the free parameters that will be refined'
2317        return ["::"+self.freeVars[v][0] for v in self.freeVars if self.freeVars[v][2]]
2318
2319    def GetVariedVarVal(self):
2320        'Returns the names and values of the free parameters that will be refined'
2321        return [("::"+self.freeVars[v][0],self.freeVars[v][1]) for v in self.freeVars if self.freeVars[v][2]]
2322
2323    def UpdateVariedVars(self,varyList,values):
2324        'Updates values for the free parameters (after a refinement); only updates refined vars'
2325        for v in self.freeVars:
2326            if not self.freeVars[v][2]: continue
2327            if "::"+self.freeVars[v][0] not in varyList: continue
2328            indx = varyList.index("::"+self.freeVars[v][0])
2329            self.freeVars[v][1] = values[indx]
2330
2331    def GetIndependentVars(self):
2332        'Returns the names of the required independent parameters used in expression'
2333        return [self.assgnVars[v] for v in self.assgnVars]
2334
2335    def CheckVars(self):
2336        '''Check that the expression can be parsed, all functions are
2337        defined and that input loaded into the object is internally
2338        consistent. If not an Exception is raised.
2339
2340        :returns: a dict with references to packages needed to
2341          find functions referenced in the expression.
2342        '''
2343        ret = self.ParseExpression(self.expression)
2344        if not ret:
2345            raise Exception("Expression parse error")
2346        exprLblList,fxnpkgdict = ret
2347        # check each var used in expression is defined
2348        defined = self.assgnVars.keys() + self.freeVars.keys()
2349        notfound = []
2350        for var in exprLblList:
2351            if var not in defined:
2352                notfound.append(var)
2353        if notfound:
2354            msg = 'Not all variables defined'
2355            msg1 = 'The following variables were not defined: '
2356            msg2 = ''
2357            for var in notfound:
2358                if msg: msg += ', '
2359                msg += var
2360            self.lastError = (msg1,'  '+msg2)
2361            raise Exception(msg)
2362        return fxnpkgdict
2363
2364    def ParseExpression(self,expr):
2365        '''Parse an expression and return a dict of called functions and
2366        the variables used in the expression. Returns None in case an error
2367        is encountered. If packages are referenced in functions, they are loaded
2368        and the functions are looked up into the modules global
2369        workspace.
2370       
2371        Note that no changes are made to the object other than
2372        saving an error message, so that this can be used for testing prior
2373        to the save.
2374
2375        :returns: a list of used variables
2376        '''
2377        self.lastError = ('','')
2378        import ast
2379        def FindFunction(f):
2380            '''Find the object corresponding to function f
2381            :param str f: a function name such as 'numpy.exp'
2382            :returns: (pkgdict,pkgobj) where pkgdict contains a dict
2383              that defines the package location(s) and where pkgobj
2384              defines the object associated with the function.
2385              If the function is not found, pkgobj is None.
2386            '''
2387            df = f.split('.')
2388            pkgdict = {}
2389            # no listed package, try in current namespace
2390            if len(df) == 1: 
2391                try:
2392                    fxnobj = eval(f)
2393                    return pkgdict,fxnobj
2394                except (AttributeError, NameError):
2395                    return None,None
2396            else:
2397                try:
2398                    fxnobj = eval(f)
2399                    pkgdict[df[0]] = eval(df[0])
2400                    return pkgdict,fxnobj
2401                except (AttributeError, NameError):
2402                    pass
2403            # includes a package, lets try to load the packages
2404            pkgname = ''
2405            path = sys.path
2406            for pkg in f.split('.')[:-1]: # if needed, descend down the tree
2407                if pkgname:
2408                    pkgname += '.' + pkg
2409                else:
2410                    pkgname = pkg
2411                fp = None
2412                try:
2413                    fp, fppath,desc = imp.find_module(pkg,path)
2414                    pkgobj = imp.load_module(pkg,fp,fppath,desc)
2415                    pkgdict[pkgname] = pkgobj
2416                    path = [fppath]
2417                except Exception as msg:
2418                    print('load of '+pkgname+' failed with error='+str(msg))
2419                    return {},None
2420                finally:
2421                    if fp: fp.close()
2422                try:
2423                    #print 'before',pkgdict.keys()
2424                    fxnobj = eval(f,globals(),pkgdict)
2425                    #print 'after 1',pkgdict.keys()
2426                    #fxnobj = eval(f,pkgdict)
2427                    #print 'after 2',pkgdict.keys()
2428                    return pkgdict,fxnobj
2429                except:
2430                    continue
2431            return None # not found
2432        def ASTtransverse(node,fxn=False):
2433            '''Transverse a AST-parsed expresson, compiling a list of variables
2434            referenced in the expression. This routine is used recursively.
2435
2436            :returns: varlist,fxnlist where
2437              varlist is a list of referenced variable names and
2438              fxnlist is a list of used functions
2439            '''
2440            varlist = []
2441            fxnlist = []
2442            if isinstance(node, list):
2443                for b in node:
2444                    v,f = ASTtransverse(b,fxn)
2445                    varlist += v
2446                    fxnlist += f
2447            elif isinstance(node, ast.AST):
2448                for a, b in ast.iter_fields(node):
2449                    if isinstance(b, ast.AST):
2450                        if a == 'func': 
2451                            fxnlist += ['.'.join(ASTtransverse(b,True)[0])]
2452                            continue
2453                        v,f = ASTtransverse(b,fxn)
2454                        varlist += v
2455                        fxnlist += f
2456                    elif isinstance(b, list):
2457                        v,f = ASTtransverse(b,fxn)
2458                        varlist += v
2459                        fxnlist += f
2460                    elif node.__class__.__name__ == "Name":
2461                        varlist += [b]
2462                    elif fxn and node.__class__.__name__ == "Attribute":
2463                        varlist += [b]
2464            return varlist,fxnlist
2465        try:
2466            exprast = ast.parse(expr)
2467        except SyntaxError:
2468            s = ''
2469            import traceback
2470            for i in traceback.format_exc().splitlines()[-3:-1]:
2471                if s: s += "\n"
2472                s += str(i)
2473            self.lastError = ("Error parsing expression:",s)
2474            return
2475        # find the variables & functions
2476        v,f = ASTtransverse(exprast)
2477        varlist = sorted(list(set(v)))
2478        fxnlist = list(set(f))
2479        pkgdict = {}
2480        # check the functions are defined
2481        for fxn in fxnlist:
2482            fxndict,fxnobj = FindFunction(fxn)
2483            if not fxnobj:
2484                self.lastError = ("Error: Invalid function",fxn,
2485                                  "is not defined")
2486                return
2487            if not hasattr(fxnobj,'__call__'):
2488                self.lastError = ("Error: Not a function.",fxn,
2489                                  "cannot be called as a function")
2490                return
2491            pkgdict.update(fxndict)
2492        return varlist,pkgdict
2493
2494    def GetDepVar(self):
2495        'return the dependent variable, or None'
2496        return self.depVar
2497
2498    def SetDepVar(self,var):
2499        'Set the dependent variable, if used'
2500        self.depVar = var
2501#==========================================================================
2502class ExpressionCalcObj(object):
2503    '''An object used to evaluate an expression from a :class:`ExpressionObj`
2504    object.
2505   
2506    :param ExpressionObj exprObj: a :class:`~ExpressionObj` expression object with
2507      an expression string and mappings for the parameter labels in that object.
2508    '''
2509    def __init__(self,exprObj):
2510        self.eObj = exprObj
2511        'The expression and mappings; a :class:`ExpressionObj` object'
2512        self.compiledExpr = None
2513        'The expression as compiled byte-code'
2514        self.exprDict = {}
2515        '''dict that defines values for labels used in expression and packages
2516        referenced by functions
2517        '''
2518        self.lblLookup = {}
2519        '''Lookup table that specifies the expression label name that is
2520        tied to a particular GSAS-II parameters in the parmDict.
2521        '''
2522        self.fxnpkgdict = {}
2523        '''a dict with references to packages needed to
2524        find functions referenced in the expression.
2525        '''
2526        self.varLookup = {}
2527        '''Lookup table that specifies the GSAS-II variable(s)
2528        indexed by the expression label name. (Used for only for diagnostics
2529        not evaluation of expression.)
2530        '''
2531        self.su = None
2532        '''Standard error evaluation where supplied by the evaluator
2533        '''
2534        # Patch: for old-style expressions with a (now removed step size)
2535        for v in self.eObj.assgnVars:
2536            if not isinstance(self.eObj.assgnVars[v], basestring):
2537                self.eObj.assgnVars[v] = self.eObj.assgnVars[v][0]
2538        self.parmDict = {}
2539        '''A copy of the parameter dictionary, for distance and angle computation
2540        '''
2541
2542    def SetupCalc(self,parmDict):
2543        '''Do all preparations to use the expression for computation.
2544        Adds the free parameter values to the parameter dict (parmDict).
2545        '''
2546        if self.eObj.expression.startswith('Dist') or self.eObj.expression.startswith('Angle'):
2547            return
2548        self.fxnpkgdict = self.eObj.CheckVars()
2549        # all is OK, compile the expression
2550        self.compiledExpr = compile(self.eObj.expression,'','eval')
2551
2552        # look at first value in parmDict to determine its type
2553        parmsInList = True
2554        for key in parmDict:
2555            val = parmDict[key]
2556            if isinstance(val, basestring):
2557                parmsInList = False
2558                break
2559            try: # check if values are in lists
2560                val = parmDict[key][0]
2561            except (TypeError,IndexError):
2562                parmsInList = False
2563            break
2564           
2565        # set up the dicts needed to speed computations
2566        self.exprDict = {}
2567        self.lblLookup = {}
2568        self.varLookup = {}
2569        for v in self.eObj.freeVars:
2570            varname = self.eObj.freeVars[v][0]
2571            varname = "::" + varname.lstrip(':').replace(' ','_').replace(':',';')
2572            self.lblLookup[varname] = v
2573            self.varLookup[v] = varname
2574            if parmsInList:
2575                parmDict[varname] = [self.eObj.freeVars[v][1],self.eObj.freeVars[v][2]]
2576            else:
2577                parmDict[varname] = self.eObj.freeVars[v][1]
2578            self.exprDict[v] = self.eObj.freeVars[v][1]
2579        for v in self.eObj.assgnVars:
2580            varname = self.eObj.assgnVars[v]
2581            if '*' in varname:
2582                varlist = LookupWildCard(varname,parmDict.keys())
2583                if len(varlist) == 0:
2584                    raise Exception,"No variables match "+str(v)
2585                for var in varlist:
2586                    self.lblLookup[var] = v
2587                if parmsInList:
2588                    self.exprDict[v] = np.array([parmDict[var][0] for var in varlist])
2589                else:
2590                    self.exprDict[v] = np.array([parmDict[var] for var in varlist])
2591                self.varLookup[v] = [var for var in varlist]
2592            elif varname in parmDict:
2593                self.lblLookup[varname] = v
2594                self.varLookup[v] = varname
2595                if parmsInList:
2596                    self.exprDict[v] = parmDict[varname][0]
2597                else:
2598                    self.exprDict[v] = parmDict[varname]
2599            else:
2600                self.exprDict[v] = None
2601#                raise Exception,"No value for variable "+str(v)
2602        self.exprDict.update(self.fxnpkgdict)
2603
2604    def UpdateVars(self,varList,valList):
2605        '''Update the dict for the expression with a set of values
2606        :param list varList: a list of variable names
2607        :param list valList: a list of corresponding values
2608        '''
2609        for var,val in zip(varList,valList):
2610            self.exprDict[self.lblLookup.get(var,'undefined: '+var)] = val
2611
2612    def UpdateDict(self,parmDict):
2613        '''Update the dict for the expression with values in a dict
2614        :param list parmDict: a dict of values some of which may be in use here
2615        '''
2616        if self.eObj.expression.startswith('Dist') or self.eObj.expression.startswith('Angle'):
2617            self.parmDict = parmDict
2618            return
2619        for var in parmDict:
2620            if var in self.lblLookup:
2621                self.exprDict[self.lblLookup[var]] = parmDict[var]
2622           
2623    def EvalExpression(self):
2624        '''Evaluate an expression. Note that the expression
2625        and mapping are taken from the :class:`ExpressionObj` expression object
2626        and the parameter values were specified in :meth:`SetupCalc`.
2627        :returns: a single value for the expression. If parameter
2628        values are arrays (for example, from wild-carded variable names),
2629        the sum of the resulting expression is returned.
2630
2631        For example, if the expression is ``'A*B'``,
2632        where A is 2.0 and B maps to ``'1::Afrac:*'``, which evaluates to::
2633
2634        [0.5, 1, 0.5]
2635
2636        then the result will be ``4.0``.
2637        '''
2638        self.su = None
2639        if self.eObj.expression.startswith('Dist'):
2640#            GSASIIpath.IPyBreak()
2641            dist = G2mth.CalcDist(self.eObj.distance_dict, self.eObj.distance_atoms, self.parmDict)
2642            return dist
2643        elif self.eObj.expression.startswith('Angle'):
2644            angle = G2mth.CalcAngle(self.eObj.angle_dict, self.eObj.angle_atoms, self.parmDict)
2645            return angle
2646        if self.compiledExpr is None:
2647            raise Exception,"EvalExpression called before SetupCalc"
2648        try:
2649            val = eval(self.compiledExpr,globals(),self.exprDict)
2650        except TypeError:
2651            val = None
2652        if not np.isscalar(val):
2653            val = np.sum(val)
2654        return val
2655       
2656class G2Exception(Exception):
2657    def __init__(self,msg):
2658        self.msg = msg
2659    def __str__(self):
2660        return repr(self.msg)
2661
2662def HowDidIgetHere(wherecalledonly=False):
2663    '''Show a traceback with calls that brought us to the current location.
2664    Used for debugging.
2665    '''
2666    import traceback
2667    if wherecalledonly:
2668        i = traceback.format_list(traceback.extract_stack()[:-1])[-2]
2669        print(i.strip().rstrip())
2670    else:
2671        print 70*'*'   
2672        for i in traceback.format_list(traceback.extract_stack()[:-1]): print(i.strip().rstrip())
2673        print 70*'*'   
2674               
2675def CreatePDFitems(G2frame,PWDRtree,ElList,Qlimits,numAtm=1,FltBkg=0,PDFnames=[]):
2676    '''Create and initialize a new set of PDF tree entries
2677
2678    :param Frame G2frame: main GSAS-II tree frame object
2679    :param str PWDRtree: name of PWDR to be used to create PDF item
2680    :param dict ElList: data structure with composition
2681    :param list Qlimits: Q limits to be used for computing the PDF
2682    :param float numAtm: no. atom in chemical formula
2683    :param float FltBkg: flat background value
2684    :param list PDFnames: previously used PDF names
2685   
2686    :returns: the Id of the newly created PDF entry
2687    '''
2688    PDFname = 'PDF '+PWDRtree[4:] # this places two spaces after PDF, which is needed is some places
2689    if PDFname in PDFnames:
2690        print('Skipping, entry already exists: '+PDFname)
2691        return None
2692    #PDFname = MakeUniqueLabel(PDFname,PDFnames)
2693    Id = G2frame.GPXtree.AppendItem(parent=G2frame.root,text=PDFname)
2694    Data = {
2695        'Sample':{'Name':PWDRtree,'Mult':1.0},
2696        'Sample Bkg.':{'Name':'','Mult':-1.0,'Refine':False},
2697        'Container':{'Name':'','Mult':-1.0,'Refine':False},
2698        'Container Bkg.':{'Name':'','Mult':-1.0},'ElList':ElList,
2699        'Geometry':'Cylinder','Diam':1.0,'Pack':0.50,'Form Vol':10.0*numAtm,'Flat Bkg':FltBkg,
2700        'DetType':'Area detector','ObliqCoeff':0.2,'Ruland':0.025,'QScaleLim':Qlimits,
2701        'Lorch':False,'BackRatio':0.0,'Rmax':100.,'noRing':False,'IofQmin':1.0,
2702        'I(Q)':[],'S(Q)':[],'F(Q)':[],'G(R)':[]}
2703    G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='PDF Controls'),Data)
2704    G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='PDF Peaks'),
2705        {'Limits':[1.,5.],'Background':[2,[0.,-0.2*np.pi],False],'Peaks':[]})
2706    return Id       
2707
2708
2709if __name__ == "__main__":
2710    # test equation evaluation
2711    def showEQ(calcobj):
2712        print 50*'='
2713        print calcobj.eObj.expression,'=',calcobj.EvalExpression()
2714        for v in sorted(calcobj.varLookup):
2715            print "  ",v,'=',calcobj.exprDict[v],'=',calcobj.varLookup[v]
2716        # print '  Derivatives'
2717        # for v in calcobj.derivStep.keys():
2718        #     print '    d(Expr)/d('+v+') =',calcobj.EvalDeriv(v)
2719
2720    obj = ExpressionObj()
2721
2722    obj.expression = "A*np.exp(B)"
2723    obj.assgnVars =  {'B': '0::Afrac:1'}
2724    obj.freeVars =  {'A': [u'A', 0.5, True]}
2725    #obj.CheckVars()
2726    calcobj = ExpressionCalcObj(obj)
2727
2728    obj1 = ExpressionObj()
2729    obj1.expression = "A*np.exp(B)"
2730    obj1.assgnVars =  {'B': '0::Afrac:*'}
2731    obj1.freeVars =  {'A': [u'Free Prm A', 0.5, True]}
2732    #obj.CheckVars()
2733    calcobj1 = ExpressionCalcObj(obj1)
2734
2735    obj2 = ExpressionObj()
2736    obj2.distance_stuff = np.array([[0,1],[1,-1]])
2737    obj2.expression = "Dist(1,2)"
2738    GSASIIpath.InvokeDebugOpts()
2739    parmDict2 = {'0::Afrac:0':[0.0,True], '0::Afrac:1': [1.0,False]}
2740    calcobj2 = ExpressionCalcObj(obj2)
2741    calcobj2.SetupCalc(parmDict2)
2742    showEQ(calcobj2)
2743   
2744    parmDict1 = {'0::Afrac:0':1.0, '0::Afrac:1': 1.0}
2745    print '\nDict = ',parmDict1
2746    calcobj.SetupCalc(parmDict1)
2747    showEQ(calcobj)
2748    calcobj1.SetupCalc(parmDict1)
2749    showEQ(calcobj1)
2750
2751    parmDict2 = {'0::Afrac:0':[0.0,True], '0::Afrac:1': [1.0,False]}
2752    print 'Dict = ',parmDict2
2753    calcobj.SetupCalc(parmDict2)
2754    showEQ(calcobj)
2755    calcobj1.SetupCalc(parmDict2)
2756    showEQ(calcobj1)
2757    calcobj2.SetupCalc(parmDict2)
2758    showEQ(calcobj2)
Note: See TracBrowser for help on using the repository browser.