source: trunk/GSASIIobj.py @ 2820

Last change on this file since 2820 was 2820, checked in by vondreele, 6 years ago

PWDR import now scriptable for single bank patterns

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