source: branch/logging/GSASIIobj.py @ 4740

Last change on this file since 4740 was 1456, checked in by vondreele, 11 years ago

consolidate HKLF parts of dervRefine & HessRefine? into new routine dervHKLF

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 95.6 KB
Line 
1# -*- coding: utf-8 -*-
2#GSASIIobj - data objects for GSAS-II
3########### SVN repository information ###################
4# $Date: 2014-08-04 19:29:15 +0000 (Mon, 04 Aug 2014) $
5# $Author: toby $
6# $Revision: 1456 $
7# $URL: branch/logging/GSASIIobj.py $
8# $Id: GSASIIobj.py 1456 2014-08-04 19:29:15Z toby $
9########### SVN repository information ###################
10
11'''
12*GSASIIobj: Data objects*
13=========================
14
15This module defines and/or documents the data structures used in GSAS-II, as well
16as provides misc. support routines.
17
18Constraints Tree Item
19----------------------
20
21.. _Constraints_table:
22
23.. index::
24   single: Constraints object description
25   single: Data object descriptions; Constraints
26
27Constraints are stored in a dict, separated into groups.
28Note that parameter are named in the following pattern,
29p:h:<var>:n, where p is the phase number, h is the histogram number
30<var> is a variable name and n is the parameter number.
31If a parameter does not depend on a histogram or phase or is unnumbered, that
32number is omitted.
33Note that the contents of each dict item is a List where each element in the
34list is a :ref:`constraint definition objects <Constraint_definitions_table>`.
35The constraints in this form are converted in
36:func:`GSASIIstrIO.ProcessConstraints` to the form used in :mod:`GSASIImapvars`
37
38The keys in the Constraints dict are:
39
40.. tabularcolumns:: |l|p{4.5in}|
41
42==========  ====================================================
43  key         explanation
44==========  ====================================================
45Hist        This specifies a list of constraints on
46            histogram-related parameters,
47            which will be of form :h:<var>:n.
48HAP         This specifies a list of constraints on parameters
49            that are defined for every histogram in each phase
50            and are of form p:h:<var>:n.           
51Phase       This specifies a list of constraints on phase
52            parameters,
53            which will be of form p::<var>:n.
54Global      This specifies a list of constraints on parameters
55            that are not tied to a histogram or phase and
56            are of form ::<var>:n
57==========  ====================================================
58
59.. _Constraint_definitions_table:
60
61.. index::
62   single: Constraint definition object description
63   single: Data object descriptions; Constraint Definition
64
65Each constraint is defined as an item in a list. Each constraint is of form::
66
67[[<mult1>, <var1>], [<mult2>, <var2>],..., <fixedval>, <varyflag>, <constype>]
68
69Where the variable pair list item containing two values [<mult>, <var>], where:
70
71  * <mult> is a multiplier for the constraint (float)
72  * <var> a :class:`G2VarObj` object (previously a str variable name of form
73      'p:h:name[:at]')
74
75Note that the last three items in the list play a special role:
76
77 * <fixedval> is the fixed value for a `constant equation` (``constype=c``)
78   constraint or is None. For a `New variable` (``constype=f``) constraint,
79   a variable name can be specified as a str (used for externally
80   generated constraints)
81 * <varyflag> is True or False for `New variable` (``constype=f``) constraints
82   or is None. This will be implemented in the future to indicate if these variables
83   should be refined.
84 * <constype> is one of four letters, 'e', 'c', 'h', 'f' that determines the type of constraint:
85
86    * 'e' defines a set of equivalent variables. Only the first variable is refined (if the
87      appropriate refine flag is set) and and all other equivalent variables in the list
88      are generated from that variable, using the appropriate multipliers.
89    * 'c' defines a constraint equation of form,
90      :math:`m_1 \\times var_1 + m_2 \\times var_2 + ... = c`
91    * 'h' defines a variable to hold (not vary). Any variable on this list is not varied,
92      even if its refinement flag is set. Only one [mult,var] pair is allowed in a hold
93      constraint and the mult value is ignored.
94      This is of particular value when needing to hold one or more variables where a
95      single flag controls a set of variables such as, coordinates,
96      the reciprocal metric tensor or anisotropic displacement parameter.
97    * 'f' defines a new variable (function) according to relationship
98      :math:`newvar = m_1 \\times var_1 + m_2 \\times var_2 + ...`
99
100Covariance Tree Item
101--------------------
102
103.. _Covariance_table:
104
105.. index::
106   single: Covariance description
107   single: Data object descriptions; Covariance
108
109The Covariance tree item has results from the last least-squares run. They
110are stored in a dict with these keys:
111
112.. tabularcolumns:: |l|l|p{4in}|
113
114=============  ===============  ====================================================
115  key            sub-key        explanation
116=============  ===============  ====================================================
117newCellDict    \                dict with lattice parameters computed by
118                                :func:`GSASIIstrMath.GetNewCellParms` (dict)
119title          \                Name of gpx file(?) (str)
120variables      \                Values for all N refined variables
121                                (list of float values, length N,
122                                ordered to match varyList)
123sig            \                Uncertainty values for all N refined variables
124                                (list of float values, length N,
125                                ordered to match varyList)
126varyList       \                List of directly refined variables
127                                (list of str values, length N)
128newAtomDict    \                dict with atom position values computed in
129                                :func:`GSASIIstrMath.ApplyXYZshifts` (dict)
130Rvals          \                R-factors, GOF, Marquardt value for last
131                                refinement cycle (dict)
132\              Nobs             Number of observed data points (int)
133\              Rwp              overall weighted profile R-factor (%, float)
134\              chisq            sum[w*(Iobs-Icalc)**2] for all data
135                                note this is not the reduced chi squared (float)
136\              lamMax           Marquardt value applied to Hessian diagonal
137                                (float)
138\              GOF              The goodness-of-fit, aka square root of
139                                the reduced chi squared. (float)
140covMatrix      \                The (NxN) covVariance matrix (np.array)
141=============  ===============  ====================================================
142
143Phase Tree Items
144----------------
145
146.. _Phase_table:
147
148.. index::
149   single: Phase object description
150   single: Data object descriptions; Phase
151
152Phase information is stored in the GSAS-II data tree as children of the
153Phases item in a dict with keys:
154
155.. tabularcolumns:: |l|l|p{4in}|
156
157==========  ===============  ====================================================
158  key         sub-key        explanation
159==========  ===============  ====================================================
160General         \            Overall information for the phase (dict)
161  \         AtomPtrs         list of four locations to use to pull info
162                             from the atom records (list)
163  \         F000X            x-ray F(000) intensity (float)
164  \         F000N            neutron F(000) intensity (float)
165  \         Mydir            directory of current .gpx file (str)
166  \         MCSA controls    Monte Carlo-Simulated Annealing controls (dict)
167  \         Cell             List with 8 items: cell refinement flag (bool)
168                             a, b, c, (Angstrom, float)
169                             alpha, beta & gamma (degrees, float)
170                             volume (A^3, float)
171  \         Type             'nuclear' or 'macromolecular' for now (str)
172  \         Map              dict of map parameters
173  \         SH Texture       dict of spherical harmonic preferred orientation
174                             parameters
175  \         Isotope          dict of isotopes for each atom type
176  \         Isotopes         dict of scattering lengths for each isotope
177                             combination for each element in phase 
178  \         Name             phase name (str)
179  \         SGData           Space group details as a :ref:`space group (SGData) object <SGData_table>`
180                             as defined in :func:`GSASIIspc.SpcGroup`.
181  \         Pawley neg wt    Restraint value for negative Pawley intensities
182                             (float)
183  \         Flip             dict of Charge flip controls
184  \         Data plot type   data plot type ('Mustrain', 'Size' or
185                             'Preferred orientation') for powder data (str)
186  \         Mass             Mass of unit cell contents in g/mol
187  \         POhkl            March-Dollase preferred orientation direction
188  \         Z                dict of atomic numbers for each atom type
189  \         vdWRadii         dict of van der Waals radii for each atom type
190  \         Color            Colors for atoms (list of (r,b,g) triplets)
191  \         AtomTypes        List of atom types
192  \         AtomMass         List of masses for atoms
193  \         doPawley         Flag for Pawley intensity extraction (bool)
194  \         NoAtoms          Number of atoms per unit cell of each type (dict)
195  \         Pawley dmin      maximum Q (as d-space) to use for Pawley
196                             extraction (float)
197  \         BondRadii        Default radius for each atom used to compute
198                             interatomic distances (list of floats)
199  \         AngleRadii       Default radius for each atom used to compute
200                             interatomic angles (list of floats)
201  \         DisAglCtls       Dict with distance/angle search controls,
202                             which has keys 'Name', 'AtomTypes',
203                             'BondRadii', 'AngleRadii' which are as above
204                             except are possibly edited. Also contains
205                             'Factors', which is a 2 element list with
206                             a multiplier for bond and angle search range
207                             [typically (0.85,0.85)].
208ranId           \            unique random number Id for phase (int)
209pId             \            Phase Id number for current project (int).
210Atoms           \            Atoms in phase as a list of lists. The outer list
211                             is for each atom, the inner list contains varying
212                             items depending on the type of phase, see
213                             the :ref:`Atom Records <Atoms_table>` description.
214                             (list of lists)
215Drawing         \            Display parameters (dict)
216\           ballScale        Size of spheres in ball-and-stick display (float)
217\           bondList         dict with bonds
218\           contourLevel     map contour level in e/A^3 (float)
219\           showABC          Flag to show view point triplet (bool). True=show.
220\           viewDir          cartesian viewing direction (np.array with three
221                             elements)
222\           Zclip            clipping distance in A (float)
223\           backColor        background for plot as and R,G,B triplet
224                             (default = [0, 0, 0], black).
225                             (list with three atoms)
226\           selectedAtoms    List of selected atoms (list of int values)
227\           showRigidBodies  Flag to highlight rigid body placement
228\           sizeH            Size ratio for H atoms (float)
229\           bondRadius       Size of binds in A (float)
230\           atomPtrs         positions of x, type, site sym, ADP flag in Draw Atoms (list)
231\           viewPoint        list of lists. First item in list is [x,y,z]
232                             in fractional coordinates for the center of
233                             the plot. Second item list of previous & current
234                             atom number viewed (may be [0,0])
235\           showHydrogen     Flag to control plotting of H atoms.
236\           unitCellBox      Flag to control display of the unit cell.
237\           ellipseProb      Probability limit for display of thermal
238                             ellipsoids in % (float).
239\           vdwScale         Multiplier of van der Waals radius for
240                             display of vdW spheres.
241\           Atoms            A list of lists with an entry for each atom
242                             that is plotted.
243\           Zstep            Step to de/increase Z-clip (float)
244\           Quaternion       Viewing quaternion (4 element np.array)
245\           radiusFactor     Distance ratio for searching for bonds. ? Bonds
246                             are located that are within r(Ra+Rb) and (Ra+Rb)/r
247                             where Ra and Rb are the atomic radii.
248\           oldxy            previous view point (list with two floats)
249\           cameraPos        Viewing position in A for plot (float)
250\           depthFog         True if use depthFog on plot - set currently as False (bool)
251RBModels        \            Rigid body assignments (note Rigid body definitions
252                             are stored in their own main top-level tree entry.)
253Pawley ref      \            Pawley reflections
254Histograms      \            A dict of dicts. The key for the outer dict is
255                             the histograms tied to this phase. The inner
256                             dict contains the combined phase/histogram
257                             parameters for items such as scale factors,
258                             size and strain parameters. (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
360Atom Records
361------------
362
363.. _Atoms_table:
364
365.. index::
366   single: Atoms record description
367   single: Data object descriptions; Atoms record
368
369
370If ``phasedict`` points to the phase information in the data tree, then
371atoms are contained in a list of atom records (list) in
372``phasedict['Atoms']``. Also needed to read atom information
373are four pointers, ``cx,ct,cs,cia = phasedict['General']['atomPtrs']``,
374which define locations in the atom record, as shown below. Items shown are
375always present; additional ones for macromolecular phases are marked 'mm'
376
377.. tabularcolumns:: |l|p{4.5in}|
378
379==============   ====================================================
380location         explanation
381==============   ====================================================
382ct-4              mm - residue number (str)
383ct-3              mm - residue name (e.g. ALA) (str)
384ct-2              mm - chain label (str)
385ct-1              atom label (str)
386ct                atom type (str)
387ct+1              refinement flags; combination of 'F', 'X', 'U' (str)
388cx,cx+1,cx+2      the x,y and z coordinates (3 floats)
389cs                site symmetry (str)
390cs+1              site multiplicity (int)
391cia               ADP flag: Isotropic ('I') or Anisotropic ('A')
392cia+1             Uiso (float)
393cia+2...cia+6     U11, U22, U33, U12, U13, U23 (6 floats)
394atom[-1]                unique atom identifier (int)
395==============   ====================================================
396
397Drawing Atom Records
398--------------------
399
400.. _Drawing_atoms_table:
401
402.. index::
403   single: Drawing atoms record description
404   single: Data object descriptions; Drawing atoms record
405
406
407If ``phasedict`` points to the phase information in the data tree, then
408drawing atoms are contained in a list of drawing atom records (list) in
409``phasedict['Drawing']['Atoms']``. Also needed to read atom information
410are four pointers, ``cx,ct,cs,ci = phasedict['Drawing']['AtomPtrs']``,
411which define locations in the atom record, as shown below. Items shown are
412always present; additional ones for macromolecular phases are marked 'mm'
413
414.. tabularcolumns:: |l|p{4.5in}|
415
416==============   ====================================================
417location         explanation
418==============   ====================================================
419ct-4              mm - residue number (str)
420ct-3              mm - residue name (e.g. ALA) (str)
421ct-2              mm - chain label (str)
422ct-1              atom label (str)
423ct                atom type (str)
424cx,cx+1,cx+2      the x,y and z coordinates (3 floats)
425cs-1              Sym Op symbol; sym. op number + unit cell id (e.g. '1,0,-1') (str)
426cs                atom drawing style; e.g. 'balls & sticks' (str)
427cs+1              atom label style (e.g. 'name') (str)
428cs+2              atom color (RBG triplet) (int)
429cs+3              ADP flag: Isotropic ('I') or Anisotropic ('A')
430cs+4              Uiso (float)
431cs+5...cs+11      U11, U22, U33, U12, U13, U23 (6 floats)
432ci                unique atom identifier; matches source atom Id in Atom Records (int)
433==============   ====================================================
434
435Powder Diffraction Tree Items
436-----------------------------
437
438.. _Powder_table:
439
440.. index::
441   single: Powder data object description
442   single: Data object descriptions; Powder Data
443
444Every powder diffraction histogram is stored in the GSAS-II data tree
445with a top-level entry named beginning with the string "PWDR ". The
446diffraction data for that information are directly associated with
447that tree item and there are a series of children to that item. The
448routines :func:`GSASII.GSASII.GetUsedHistogramsAndPhasesfromTree`
449and :func:`GSASIIstrIO.GetUsedHistogramsAndPhases` will
450load this information into a dictionary where the child tree name is
451used as a key, and the information in the main entry is assigned
452a key of ``Data``, as outlined below.
453
454.. tabularcolumns:: |l|l|p{4in}|
455
456======================  ===============  ====================================================
457  key                      sub-key        explanation
458======================  ===============  ====================================================
459Comments                      \           Text strings extracted from the original powder
460                                          data header. These cannot be changed by the user;
461                                          it may be empty.
462Limits                       \            A list of two two element lists, as [[Ld,Hd],[L,H]]
463                                          where L and Ld are the current and default lowest
464                                          two-theta value to be used and
465                                          where H and Hd are the current and default highest
466                                          two-theta value to be used.
467Reflection Lists              \           A dict with an entry for each phase in the
468                                          histogram. The contents of each dict item
469                                          is a dict containing reflections, as described in
470                                          the :ref:`Powder Reflections <PowderRefl_table>`
471                                          description.
472Instrument Parameters         \           A list containing two dicts where the possible
473                                          keys in each dict are listed below. The value
474                                          for each item is a list containing three values:
475                                          the initial value, the current value and a
476                                          refinement flag which can have a value of
477                                          True, False or 0 where 0 indicates a value that
478                                          cannot be refined. The first and second
479                                          values are floats unless otherwise noted.
480                                          Items in the first dict are noted as [1]
481\                         Lam             Specifies a wavelength in Angstroms [1]
482\                         Lam1            Specifies the primary wavelength in
483                                          Angstrom, when an alpha1, alpha2
484                                          source is used [1]
485\                         Lam2            Specifies the secondary wavelength in
486                                          Angstrom, when an alpha1, alpha2
487                                          source is used [1]
488                          I(L2)/I(L1)     Ratio of Lam2 to Lam1 [1]           
489\                         Type            Histogram type (str) [1]:
490                                           * 'PXC' for constant wavelength x-ray
491                                           * 'PNC' for constant wavelength neutron
492                                           * 'PNT' for time of flight neutron
493\                         Zero            Two-theta zero correction in *degrees* [1]
494\                         Azimuth         Azimuthal setting angle for data recorded
495                                          with differing setting angles [1]
496\                         U, V, W         Cagliotti profile coefficients
497                                          for Gaussian instrumental broadening, where the
498                                          FWHM goes as
499                                          :math:`U \\tan^2\\theta + V \\tan\\theta + W` [1]
500\                         X, Y            Cauchy (Lorentzian) instrumental broadening
501                                          coefficients [1]
502\                         SH/L            Variant of the Finger-Cox-Jephcoat asymmetric
503                                          peak broadening ratio. Note that this is the
504                                          average between S/L and H/L where S is
505                                          sample height, H is the slit height and
506                                          L is the goniometer diameter. [1]
507\                         Polariz.        Polarization coefficient. [1]
508wtFactor                      \           A weighting factor to increase or decrease
509                                          the leverage of data in the histogram (float).
510                                          A value of 1.0 weights the data with their
511                                          standard uncertainties and a larger value
512                                          increases the weighting of the data (equivalent
513                                          to decreasing the uncertainties).
514Sample Parameters             \           Specifies a dict with parameters that describe how
515                                          the data were collected, as listed
516                                          below. Refinable parameters are a list containing
517                                          a float and a bool, where the second value
518                                          specifies if the value is refined, otherwise
519                                          the value is a float unless otherwise noted.
520\                         Scale           The histogram scale factor (refinable)
521\                         Absorption      The sample absorption coefficient as
522                                          :math:`\\mu r` where r is the radius
523                                          (refinable). Only valid for Debye-Scherrer geometry.
524\                         SurfaceRoughA   Surface roughness parameter A as defined by
525                                          Surotti,J. Appl. Cryst, 5,325-331, 1972.(refinable -
526                                          only valid for Bragg-Brentano geometry)                                         
527\                         SurfaceRoughB   Surface roughness parameter B (refinable -
528                                          only valid for Bragg-Brentano geometry)                                         
529\                         DisplaceX,      Sample displacement from goniometer center
530                          DisplaceY       where Y is along the beam direction and
531                                          X is perpendicular. Units are :math:`\\mu m`
532                                          (refinable).
533\                         Phi, Chi,       Goniometer sample setting angles, in degrees.
534                          Omega
535\                         Gonio. radius   Radius of the diffractometer in mm
536\                         InstrName       A name for the instrument, used in preparing
537                                          a CIF (str).
538\                         Force,          Variables that describe how the measurement
539                          Temperature,    was performed. Not used directly in
540                          Humidity,       any computations.
541                          Pressure,
542                          Voltage
543\                         ranId           The random-number Id for the histogram
544                                          (same value as where top-level key is ranId)
545\                         Type            Type of diffraction data, may be 'Debye-Scherrer'
546                                          or 'Bragg-Brentano' (str).
547\                         Diffuse         not in use?
548hId                           \           The number assigned to the histogram when
549                                          the project is loaded or edited (can change)
550ranId                         \           A random number id for the histogram
551                                          that does not change
552Background                    \           The background is stored as a list with where
553                                          the first item in the list is list and the second
554                                          item is a dict. The list contains the background
555                                          function and its coefficients; the dict contains
556                                          Debye diffuse terms and background peaks.
557                                          (TODO: this needs to be expanded.)
558Data                          \           The data consist of a list of 6 np.arrays
559                                          containing in order:
560
561                                           0. the x-postions (two-theta in degrees),
562                                           1. the intensity values (Yobs),
563                                           2. the weights for each Yobs value
564                                           3. the computed intensity values (Ycalc)
565                                           4. the background values
566                                           5. Yobs-Ycalc
567======================  ===============  ====================================================
568
569Powder Reflection Data Structure
570--------------------------------
571
572.. _PowderRefl_table:
573
574.. index::
575   single: Powder reflection object description
576   single: Data object descriptions; Powder Reflections
577   
578For every phase in a histogram, the ``Reflection Lists`` value is a dict
579one element of which is `'RefList'`, which is a np.array containing
580reflections. The columns in that array are documented below.
581
582==========  ====================================================
583  index         explanation
584==========  ====================================================
585 0,1,2       h,k,l (float)
586 3           multiplicity
587 4           d-space, Angstrom
588 5           pos, two-theta
589 6           sig, Gaussian width
590 7           gam, Lorenzian width
591 8           :math:`F_{obs}^2`
592 9           :math:`F_{calc}^2`
593 10          reflection phase, in degrees
594 11          intensity correction for reflection, this times
595             :math:`F_{obs}^2` or :math:`F_{calc}^2` gives Iobs or Icalc
596==========  ====================================================
597
598Single Crystal Tree Items
599-------------------------
600
601.. _Xtal_table:
602
603.. index::
604   single: Single Crystal data object description
605   single: Data object descriptions; Single crystal data
606
607Every single crystal diffraction histogram is stored in the GSAS-II data tree
608with a top-level entry named beginning with the string "HKLF ". The
609diffraction data for that information are directly associated with
610that tree item and there are a series of children to that item. The
611routines :func:`GSASII.GSASII.GetUsedHistogramsAndPhasesfromTree`
612and :func:`GSASIIstrIO.GetUsedHistogramsAndPhases` will
613load this information into a dictionary where the child tree name is
614used as a key, and the information in the main entry is assigned
615a key of ``Data``, as outlined below.
616
617.. tabularcolumns:: |l|l|p{4in}|
618
619======================  ===============  ====================================================
620  key                      sub-key        explanation
621======================  ===============  ====================================================
622Data                          \           A dict that contains the
623                                          reflection table,
624                                          as described in the
625                                          :ref:`Single Crystal Reflections
626                                          <XtalRefl_table>`
627                                          description.
628
629Instrument Parameters         \           A list containing two dicts where the possible
630                                          keys in each dict are listed below. The value
631                                          for most items is a list containing two values:
632                                          the initial value, the current value.
633                                          The first and second
634                                          values are floats unless otherwise noted.
635\                         Lam             Specifies a wavelength in Angstroms (two floats)
636\                         Type            Histogram type (two str values):
637                                           * 'SXC' for constant wavelength x-ray
638                                           * 'SNC' for constant wavelength neutron
639                                           * 'SNT' for time of flight neutron
640\                         InstrName       A name for the instrument, used in preparing
641                                          a CIF (str).
642
643wtFactor                      \           A weighting factor to increase or decrease
644                                          the leverage of data in the histogram (float).
645                                          A value of 1.0 weights the data with their
646                                          standard uncertainties and a larger value
647                                          increases the weighting of the data (equivalent
648                                          to decreasing the uncertainties).
649
650hId                           \           The number assigned to the histogram when
651                                          the project is loaded or edited (can change)
652ranId                         \           A random number id for the histogram
653                                          that does not change
654======================  ===============  ====================================================
655
656Single Crystal Reflection Data Structure
657----------------------------------------
658
659.. _XtalRefl_table:
660
661.. index::
662   single: Single Crystal reflection object description
663   single: Data object descriptions; Single Crystal Reflections
664   
665For every single crystal a histogram, the ``'Data'`` item contains
666the structure factors as an np.array in item `'RefList'`.
667The columns in that array are documented below.
668
669==========  ====================================================
670  index         explanation
671==========  ====================================================
672 0,1,2       h,k,l (float)
673 3           multiplicity
674 4           d-space, Angstrom
675 5           :math:`F_{obs}^2`
676 6           :math:`\sigma(F_{obs}^2)`
677 7           :math:`F_{calc}^2`
678 8           :math:`F_{obs}^2T`
679 9           :math:`F_{calc}^2T`
680 10          reflection phase, in degrees
681 11          intensity correction for reflection, this times
682             :math:`F_{obs}^2` or :math:`F_{calc}^2`
683             gives Iobs or Icalc
684==========  ====================================================
685
686Image Data Structure
687--------------------
688
689.. _Image_table:
690
691.. index::
692   image: Image data object description
693   image: Image object descriptions
694   
695Every 2-dimensional image is stored in the GSAS-II data tree
696with a top-level entry named beginning with the string "IMG ". The
697image data are directly associated with that tree item and there
698are a series of children to that item. The routines :func:`GSASII.GSASII.GetUsedHistogramsAndPhasesfromTree`
699and :func:`GSASIIstrIO.GetUsedHistogramsAndPhases` will
700load this information into a dictionary where the child tree name is
701used as a key, and the information in the main entry is assigned
702a key of ``Data``, as outlined below.
703
704.. tabularcolumns:: |l|l|p{4in}|
705
706======================  ======================  ====================================================
707  key                      sub-key              explanation
708======================  ======================  ====================================================
709Comments                       \                Text strings extracted from the original image data
710                                                header or a metafile. These cannot be changed by 
711                                                the user; it may be empty.                                               
712Image Controls              azmthOff            (float) The offset to be applied to an azimuthal
713                                                value. Accomodates
714                                                detector orientations other than with the detector
715                                                X-axis
716                                                horizontal.
717\                           background image    (list:str,float) The name of a tree item ("IMG ...") that is to be subtracted
718                                                during image integration multiplied by value. It must have the same size/shape as
719                                                the integrated image. NB: value < 0 for subtraction.
720\                           calibrant           (str) The material used for determining the position/orientation
721                                                of the image. The data is obtained from :func:`ImageCalibrants`
722                                                and UserCalibrants.py (supplied by user).
723\                           calibdmin           (float) The minimum d-spacing used during the last calibration run.
724\                           calibskip           (int) The number of expected diffraction lines skipped during the last
725                                                calibration run.
726\                           center              (list:floats) The [X,Y] point in detector coordinates (mm) where the direct beam
727                                                strikes the detector plane as determined by calibration. This point
728                                                does not have to be within the limits of the detector boundaries.
729\                           centerAzm           (bool) If True then the azimuth reported for the integrated slice
730                                                of the image is at the center line otherwise it is at the leading edge.
731\                           color               (str) The name of the colormap used to display the image. Default = 'Paired'.
732\                           cutoff              (float) The minimum value of I/Ib for a point selected in a diffraction ring for
733                                                calibration calculations. See pixLimit for details as how point is found.           
734\                           DetDepth            (float) Coefficient for penetration correction to distance; accounts for diffraction
735                                                ring offset at higher angles. Optionally determined by calibration.
736\                           DetDepthRef         (bool) If True then refine DetDepth during calibration/recalibration calculation.
737\                           distance            (float) The distance (mm) from sample to detector plane.
738\                           ellipses            (list:lists) Each object in ellipses is a list [center,phi,radii,color] where
739                                                center (list) is location (mm) of the ellipse center on the detector plane, phi is the
740                                                rotation of the ellipse minor axis from the x-axis, and radii are the minor & major
741                                                radii of the ellipse. If radii[0] is negative then parameters describe a hyperbola. Color
742                                                is the selected drawing color (one of 'b', 'g' ,'r') for the ellipse/hyperbola.
743\                           edgemin             (float) Not used;  parameter in EdgeFinder code.
744\                           fullIntegrate       (bool) If True then integrate over full 360 deg azimuthal range.
745\                           GonioAngles         (list:floats) The 'Omega','Chi','Phi' goniometer angles used for this image.
746                                                Required for texture calculations.
747\                           invert_x            (bool) If True display the image with the x-axis inverted.
748\                           invert_y            (bool) If True display the image with the y-axis inverted.
749\                           IOtth               (list:floats) The minimum and maximum 2-theta values to be used for integration.
750\                           LRazimuth           (list:floats) The minimum and maximum azimuth values to be used for integration.
751\                           Oblique             (list:float,bool) If True apply a detector absorption correction using the value to the
752                                                intensities obtained during integration.
753\                           outAzimuths         (int) The number of azimuth pie slices.
754\                           outChannels         (int) The number of 2-theta steps.
755\                           pixelSize           (list:ints) The X,Y dimensions (microns) of each pixel.
756\                           pixLimit            (int) A box in the image with 2*pixLimit+1 edges is searched to find the maximum.
757                                                This value (I) along with the minimum (Ib) in the box is reported by :func:`GSASIIimage.ImageLocalMax`
758                                                and subject to cutoff in :func:`GSASIIimage.makeRing`.
759                                                Locations are used to construct rings of points for calibration calcualtions.
760\                           PolaVal             (list:float,bool) If type='SASD' and if True, apply polarization correction to intensities from
761                                                integration using value.
762\                           rings               (list:lists) Each entry is [X,Y,dsp] where X & Y are lists of x,y coordinates around a
763                                                diffraction ring with the same d-spacing (dsp)
764\                           ring                (list) The x,y coordinates of the >5 points on an inner ring
765                                                selected by the user,
766\                           Range               (list) The minimum & maximum values of the image
767\                           rotation            (float) The angle between the x-axis and the vector about which the
768                                                detector is tilted. Constrained to -180 to 180 deg.     
769\                           SampleShape         (str) Currently only 'Cylinder'. Sample shape for Debye-Scherrer experiments; used for absorption
770                                                calculations.
771\                           SampleAbs           (list: float,bool) Value of absorption coefficient for Debye-Scherrer experimnents, flag if True
772                                                to cause correction to be applied.
773\                           setDefault          (bool) If True the use the image controls values for all new images to be read. (might be removed)
774\                           setRings            (bool) If True then display all the selected x,y ring positions (vida supra rings) used in the calibration.           
775\                           showLines           (bool) If True then isplay the integration limits to be used.
776\                           size                (list:int) The number of pixels on the image x & y axes
777\                           type                (str) One of 'PWDR', 'SASD' or 'REFL' for powder, small angle or reflectometry data, respectively.
778\                           tilt                (float) The angle the detector normal makes with the incident beam; range -90 to 90.
779\                           wavelength          (float) Tha radiation wavelength (Angstroms) as entered by the user (or someday obtained from the image header).
780                                               
781Masks                       Arcs                (list: lists) Each entry [2-theta,[azimuth[0],azimuth[1]],thickness] describes an arc mask
782                                                to be excluded from integration
783\                           Frames              (list:lists) Each entry describes the x,y points (3 or more - mm) that describe a frame outside
784                                                of which is excluded from recalibration and integration. Only one frame is allowed.
785\                           Points              (list:lists) Each entry [x,y,radius] (mm) describes an excluded spot on the image to be excluded
786                                                from integration.
787\                           Polygons            (list:lists) Each entry is a list of 3+ [x,y] points (mm) that describe a polygon on the image
788                                                to be excluded from integration.
789\                           Rings               (list: lists) Each entry [2-theta,thickness] describes a ring mask
790                                                to be excluded from integration.
791\                           Thresholds          (list:[tuple,list]) [(Imin,Imax),[Imin,Imax]] This gives lower and upper limits for points on the image to be included
792                                                in integrsation. The tuple is the image intensity limits and the list are those set by the user.   
793                                               
794Stress/Strain               Sample phi          (float) Sample rotation about vertical axis.
795\                           Sample z            (float) Sample translation from the calibration sample position (for Sample phi = 0)
796                                                These will be restricted by space group symmetry; result of strain fit refinement.
797\                           Type                (str) 'True' or 'Conventional': The strain model used for the calculation.
798\                           d-zero              (list:dict) Each item is for a diffraction ring on the image; all items are from the same phase
799                                                and are used to determine the strain tensor.
800                                                The dictionary items are:
801                                                'Dset': (float) True d-spacing for the diffraction ring; entered by the user.
802                                                'Dcalc': (float) Average calculated d-spacing determined from strain coeff.
803                                                'Emat': (list: float) The strain tensor elements e11, e12 & e22 (e21=e12, rest are 0)
804                                                'Esig': (list: float) Esds for Emat from fitting.
805                                                'pixLimit': (int) Search range to find highest point on ring for each data point
806                                                'cutoff': (float) I/Ib cutoff for searching.
807                                                'ImxyObs': (list: lists) [[X],[Y]] observed points to be used for strain calculations.
808                                                'ImtaObs': (list: lists) [[d],[azm]] transformed via detector calibration from ImxyObs.
809                                                'ImtaCalc': (list: lists [[d],[azm]] calculated d-spacing & azimuth from fit.
810                                               
811======================  ======================  ====================================================
812
813Parameter Dictionary
814-------------------------
815
816.. _parmDict_table:
817
818.. index::
819   single: Parameter dictionary
820
821The parameter dictionary contains all of the variable parameters for the refinement.
822The dictionary keys are the name of the parameter (<phase>:<hist>:<name>:<atom>).
823It is prepared in two ways. When loaded from the tree
824(in :meth:`GSASII.GSASII.MakeLSParmDict` and
825:meth:`GSASIIIO.ExportBaseclass.loadParmDict`),
826the values are lists with two elements: ``[value, refine flag]``
827
828When loaded from the GPX file (in
829:func:`GSASIIstrMain.Refine` and :func:`GSASIIstrMain.SeqRefine`), the value in the
830dict is the actual parameter value (usually a float, but sometimes a
831letter or string flag value (such as I or A for iso/anisotropic).
832
833
834*Classes and routines*
835----------------------
836
837'''
838import re
839import imp
840import random as ran
841import sys
842import GSASIIpath
843import GSASIImath as G2mth
844import numpy as np
845
846GSASIIpath.SetVersionNumber("$Revision: 1456 $")
847
848DefaultControls = {
849    'deriv type':'analytic Hessian',    #default controls
850    'min dM/M':0.0001,'shift factor':1.,'max cyc':3,'F**2':True,
851    'minF/sig':0,
852    'Author':'no name',
853    'FreeVar1':'Sample humidity (%)',
854    'FreeVar2':'Sample voltage (V)',
855    'FreeVar3':'Applied load (MN)',
856    }
857'''Values to be used as defaults for the initial contents of the ``Controls``
858data tree item.
859'''
860
861def MakeUniqueLabel(lbl,labellist):
862    '''Make sure that every a label is unique against a list by adding
863    digits at the end until it is not found in list.
864
865    :param str lbl: the input label
866    :param list labellist: the labels that have already been encountered
867    :returns: lbl if not found in labellist or lbl with ``_1-9`` (or
868      ``_10-99``, etc.) appended at the end
869    '''
870    lbl = lbl.strip()
871    if not lbl: # deal with a blank label
872        lbl = '_1'
873    if lbl not in labellist:
874        labellist.append(lbl)
875        return lbl
876    i = 1
877    prefix = lbl
878    if '_' in lbl:
879        prefix = lbl[:lbl.rfind('_')]
880        suffix = lbl[lbl.rfind('_')+1:]
881        try:
882            i = int(suffix)+1
883        except: # suffix could not be parsed
884            i = 1
885            prefix = lbl
886    while prefix+'_'+str(i) in labellist:
887        i += 1
888    else:
889        lbl = prefix+'_'+str(i)
890        labellist.append(lbl)
891    return lbl
892
893PhaseIdLookup = {}
894'''dict listing phase name and random Id keyed by sequential phase index as a str;
895best to access this using :func:`LookupPhaseName`
896'''
897PhaseRanIdLookup = {}
898'''dict listing phase sequential index keyed by phase random Id;
899best to access this using :func:`LookupPhaseId`
900'''
901HistIdLookup = {}
902'''dict listing histogram name and random Id, keyed by sequential histogram index as a str;
903best to access this using :func:`LookupHistName`
904'''
905HistRanIdLookup = {}
906'''dict listing histogram sequential index keyed by histogram random Id;
907best to access this using :func:`LookupHistId`
908'''
909AtomIdLookup = {}
910'''dict listing for each phase index as a str, the atom label and atom random Id,
911keyed by atom sequential index as a str;
912best to access this using :func:`LookupAtomLabel`
913'''
914AtomRanIdLookup = {}
915'''dict listing for each phase the atom sequential index keyed by atom random Id;
916best to access this using :func:`LookupAtomId`
917'''
918ShortPhaseNames = {}
919'''a dict containing a possibly shortened and when non-unique numbered
920version of the phase name. Keyed by the phase sequential index.
921'''
922ShortHistNames = {}
923'''a dict containing a possibly shortened and when non-unique numbered
924version of the histogram name. Keyed by the histogram sequential index.
925'''
926
927VarDesc = {}
928''' This dictionary lists descriptions for GSAS-II variables,
929as set in :func:`CompileVarDesc`. See that function for a description
930for how keys and values are written.
931'''
932
933reVarDesc = {}
934''' This dictionary lists descriptions for GSAS-II variables with
935the same values as :attr:`VarDesc` except that keys have been compiled as
936regular expressions. Initialized in :func:`CompileVarDesc`.
937'''
938
939def IndexAllIds(Histograms,Phases):
940    '''Scan through the used phases & histograms and create an index
941    to the random numbers of phases, histograms and atoms. While doing this,
942    confirm that assigned random numbers are unique -- just in case lightning
943    strikes twice in the same place.
944
945    Note: this code assumes that the atom random Id (ranId) is the last
946    element each atom record.
947
948    This is called in three places (only): :func:`GSASIIstrIO.GetUsedHistogramsAndPhases`
949    (which loads the histograms and phases from a GPX file),
950    :meth:`~GSASII.GSASII.GetUsedHistogramsAndPhasesfromTree`
951    (which loads the histograms and phases from the data tree.) and
952    :meth:`GSASIIconstrGUI.UpdateConstraints`
953    (which displays & edits the constraints in a GUI)
954
955    TODO: do we need a lookup for rigid body variables?
956    '''
957    # process phases and atoms
958    PhaseIdLookup.clear()
959    PhaseRanIdLookup.clear()   
960    AtomIdLookup.clear()
961    AtomRanIdLookup.clear()
962    ShortPhaseNames.clear()
963    for ph in Phases:
964        cx,ct,cs,cia = Phases[ph]['General']['AtomPtrs']
965        ranId = Phases[ph]['ranId'] 
966        while ranId in PhaseRanIdLookup:
967            # Found duplicate random Id! note and reassign
968            print ("\n\n*** Phase "+str(ph)+" has repeated ranId. Fixing.\n")
969            Phases[ph]['ranId'] = ranId = ran.randint(0,sys.maxint)
970        pId = str(Phases[ph]['pId'])
971        PhaseIdLookup[pId] = (ph,ranId)
972        PhaseRanIdLookup[ranId] = pId
973        shortname = ph[:10]
974        while shortname in ShortPhaseNames.values():
975            shortname = ph[:8] + ' ('+ pId + ')'
976        ShortPhaseNames[pId] = shortname
977        AtomIdLookup[pId] = {}
978        AtomRanIdLookup[pId] = {}
979        for iatm,at in enumerate(Phases[ph]['Atoms']):
980            ranId = at[-1]
981            while ranId in AtomRanIdLookup[pId]: # check for dups
982                print ("\n\n*** Phase "+str(ph)+" atom "+str(iatm)+" has repeated ranId. Fixing.\n")
983                at[-1] = ranId = ran.randint(0,sys.maxint)
984            AtomRanIdLookup[pId][ranId] = str(iatm)
985            if Phases[ph]['General']['Type'] == 'macromolecular':
986                label = '%s_%s_%s_%s'%(at[ct-1],at[ct-3],at[ct-4],at[ct-2])
987            else:
988                label = at[ct-1]
989            AtomIdLookup[pId][str(iatm)] = (label,ranId)
990    # process histograms
991    HistIdLookup.clear()
992    HistRanIdLookup.clear()
993    ShortHistNames.clear()
994    for hist in Histograms:
995        ranId = Histograms[hist]['ranId']
996        while ranId in HistRanIdLookup:
997            # Found duplicate random Id! note and reassign
998            print ("\n\n*** Histogram "+str(hist)+" has repeated ranId. Fixing.\n")
999            Histograms[hist]['ranId'] = ranId = ran.randint(0,sys.maxint)
1000        hId = str(Histograms[hist]['hId'])
1001        HistIdLookup[hId] = (hist,ranId)
1002        HistRanIdLookup[ranId] = hId
1003        shortname = hist[:15]
1004        while shortname in ShortHistNames.values():
1005            shortname = hist[:11] + ' ('+ hId + ')'
1006        ShortHistNames[hId] = shortname
1007
1008def LookupAtomId(pId,ranId):
1009    '''Get the atom number from a phase and atom random Id
1010
1011    :param int/str pId: the sequential number of the phase
1012    :param int ranId: the random Id assigned to an atom
1013
1014    :returns: the index number of the atom (str)
1015    '''
1016    if not AtomRanIdLookup:
1017        raise Exception,'Error: LookupAtomId called before IndexAllIds was run'
1018    if pId is None or pId == '':
1019        raise KeyError,'Error: phase is invalid (None or blank)'
1020    pId = str(pId)
1021    if pId not in AtomRanIdLookup:
1022        raise KeyError,'Error: LookupAtomId does not have phase '+pId
1023    if ranId not in AtomRanIdLookup[pId]:
1024        raise KeyError,'Error: LookupAtomId, ranId '+str(ranId)+' not in AtomRanIdLookup['+pId+']'
1025    return AtomRanIdLookup[pId][ranId]
1026
1027def LookupAtomLabel(pId,index):
1028    '''Get the atom label from a phase and atom index number
1029
1030    :param int/str pId: the sequential number of the phase
1031    :param int index: the index of the atom in the list of atoms
1032
1033    :returns: the label for the atom (str) and the random Id of the atom (int)
1034    '''
1035    if not AtomIdLookup:
1036        raise Exception,'Error: LookupAtomLabel called before IndexAllIds was run'
1037    if pId is None or pId == '':
1038        raise KeyError,'Error: phase is invalid (None or blank)'
1039    pId = str(pId)
1040    if pId not in AtomIdLookup:
1041        raise KeyError,'Error: LookupAtomLabel does not have phase '+pId
1042    if index not in AtomIdLookup[pId]:
1043        raise KeyError,'Error: LookupAtomLabel, ranId '+str(index)+' not in AtomRanIdLookup['+pId+']'
1044    return AtomIdLookup[pId][index]
1045
1046def LookupPhaseId(ranId):
1047    '''Get the phase number and name from a phase random Id
1048
1049    :param int ranId: the random Id assigned to a phase
1050    :returns: the sequential Id (pId) number for the phase (str)
1051    '''
1052    if not PhaseRanIdLookup:
1053        raise Exception,'Error: LookupPhaseId called before IndexAllIds was run'
1054    if ranId not in PhaseRanIdLookup:
1055        raise KeyError,'Error: LookupPhaseId does not have ranId '+str(ranId)
1056    return PhaseRanIdLookup[ranId]
1057
1058def LookupPhaseName(pId):
1059    '''Get the phase number and name from a phase Id
1060
1061    :param int/str pId: the sequential assigned to a phase
1062    :returns:  (phase,ranId) where phase is the name of the phase (str)
1063      and ranId is the random # id for the phase (int)
1064    '''
1065    if not PhaseIdLookup:
1066        raise Exception,'Error: LookupPhaseName called before IndexAllIds was run'
1067    if pId is None or pId == '':
1068        raise KeyError,'Error: phase is invalid (None or blank)'
1069    pId = str(pId)
1070    if pId not in PhaseIdLookup:
1071        raise KeyError,'Error: LookupPhaseName does not have index '+pId
1072    return PhaseIdLookup[pId]
1073
1074def LookupHistId(ranId):
1075    '''Get the histogram number and name from a histogram random Id
1076
1077    :param int ranId: the random Id assigned to a histogram
1078    :returns: the sequential Id (hId) number for the histogram (str)
1079    '''
1080    if not HistRanIdLookup:
1081        raise Exception,'Error: LookupHistId called before IndexAllIds was run'
1082    if ranId not in HistRanIdLookup:
1083        raise KeyError,'Error: LookupHistId does not have ranId '+str(ranId)
1084    return HistRanIdLookup[ranId]
1085
1086def LookupHistName(hId):
1087    '''Get the histogram number and name from a histogram Id
1088
1089    :param int/str hId: the sequential assigned to a histogram
1090    :returns:  (hist,ranId) where hist is the name of the histogram (str)
1091      and ranId is the random # id for the histogram (int)
1092    '''
1093    if not HistIdLookup:
1094        raise Exception,'Error: LookupHistName called before IndexAllIds was run'
1095    if hId is None or hId == '':
1096        raise KeyError,'Error: histogram is invalid (None or blank)'
1097    hId = str(hId)
1098    if hId not in HistIdLookup:
1099        raise KeyError,'Error: LookupHistName does not have index '+hId
1100    return HistIdLookup[hId]
1101
1102def fmtVarDescr(varname):
1103    '''Return a string with a more complete description for a GSAS-II variable
1104
1105    :param str varname: A full G2 variable name with 2 or 3 or 4
1106       colons (<p>:<h>:name[:<a>] or <p>::RBname:<r>:<t>])
1107       
1108    :returns: a string with the description
1109    '''
1110    s,l = VarDescr(varname)
1111    return s+": "+l
1112
1113def VarDescr(varname):
1114    '''Return two strings with a more complete description for a GSAS-II variable
1115
1116    :param str name: A full G2 variable name with 2 or 3 or 4
1117       colons (<p>:<h>:name[:<a>] or <p>::RBname:<r>:<t>])
1118       
1119    :returns: (loc,meaning) where loc describes what item the variable is mapped
1120      (phase, histogram, etc.) and meaning describes what the variable does.
1121    '''
1122   
1123    # special handling for parameter names without a colons
1124    # for now, assume self-defining
1125    if varname.find(':') == -1:
1126        return "Global",varname
1127       
1128    l = getVarDescr(varname)
1129    if not l:
1130        return ("invalid variable name ("+str(varname)+")!"),""
1131#        return "invalid variable name!",""
1132
1133    if not l[-1]:
1134        l[-1] = "(variable needs a definition! Set it in CompileVarDesc)"
1135
1136    if len(l) == 3:         #SASD variable name!
1137        s = 'component:'+l[1]
1138        return s,l[-1]
1139    s = ""
1140    if l[0] is not None and l[1] is not None: # HAP: keep short
1141        if l[2] == "Scale": # fix up ambigous name
1142            l[5] = "Phase fraction"
1143        if l[0] == '*':
1144            lbl = 'all'
1145        else:
1146            lbl = ShortPhaseNames.get(l[0],'? #'+str(l[0]))
1147        if l[1] == '*':
1148            hlbl = 'all'
1149        else:
1150            hlbl = ShortHistNames.get(l[1],'? #'+str(l[1]))
1151        if hlbl[:4] == 'HKLF':
1152            hlbl = 'Xtl='+hlbl[5:]
1153        elif hlbl[:4] == 'PWDR':
1154            hlbl = 'Pwd='+hlbl[5:]
1155        else:
1156            hlbl = 'Hist='+hlbl
1157        s = "Ph="+str(lbl)+" * "+str(hlbl)
1158    else:
1159        if l[2] == "Scale": # fix up ambigous name: must be scale factor, since not HAP
1160            l[5] = "Scale factor"
1161        if l[2] == 'Back': # background parameters are "special", alas
1162            s = 'Hist='+ShortHistNames.get(l[1],'? #'+str(l[1]))
1163            l[-1] += ' #'+str(l[3])
1164        elif l[4] is not None: # rigid body parameter
1165            lbl = ShortPhaseNames.get(l[0],'phase?')
1166            s = "Res #"+str(l[3])+" body #"+str(l[4])+" in "+str(lbl)
1167        elif l[3] is not None: # atom parameter,
1168            lbl = ShortPhaseNames.get(l[0],'phase?')
1169            try:
1170                albl = LookupAtomLabel(l[0],l[3])[0]
1171            except KeyError:
1172                albl = 'Atom?'
1173            s = "Atom "+str(albl)+" in "+str(lbl)
1174        elif l[0] == '*':
1175            s = "All phases "
1176        elif l[0] is not None:
1177            lbl = ShortPhaseNames.get(l[0],'phase?')
1178            s = "Phase "+str(lbl)
1179        elif l[1] == '*':
1180            s = 'All hists'
1181        elif l[1] is not None:
1182            hlbl = ShortHistNames.get(l[1],'? #'+str(l[1]))
1183            if hlbl[:4] == 'HKLF':
1184                hlbl = 'Xtl='+hlbl[5:]
1185            elif hlbl[:4] == 'PWDR':
1186                hlbl = 'Pwd='+hlbl[5:]
1187            else:
1188                hlbl = 'Hist='+hlbl
1189            s = str(hlbl)
1190    if not s:
1191        s = 'Global'
1192    return s,l[-1]
1193
1194def getVarDescr(varname):
1195    '''Return a short description for a GSAS-II variable
1196
1197    :param str name: A full G2 variable name with 2 or 3 or 4
1198       colons (<p>:<h>:name[:<a1>][:<a2>])
1199     
1200    :returns: a six element list as [`p`,`h`,`name`,`a1`,`a2`,`description`],
1201      where `p`, `h`, `a1`, `a2` are str values or `None`, for the phase number,
1202      the histogram number and the atom number; `name` will always be
1203      a str; and `description` is str or `None`.
1204      If the variable name is incorrectly formed (for example, wrong
1205      number of colons), `None` is returned instead of a list.
1206    '''
1207    l = varname.split(':')
1208    if len(l) == 2:     #SASD parameter name
1209        return varname,l[0],getDescr(l[1])
1210    if len(l) == 3:
1211        l += [None,None]
1212    elif len(l) == 4:
1213        l += [None]
1214    elif len(l) != 5:
1215        return None
1216    for i in (0,1,3,4):
1217        if l[i] == "":
1218            l[i] = None
1219    l += [getDescr(l[2])]
1220    return l
1221   
1222def CompileVarDesc():
1223    '''Set the values in the variable description lookup table (:attr:`VarDesc`)
1224    into :attr:`reVarDesc`. This is called in :func:`getDescr` so the initialization
1225    is always done before use.
1226
1227    Note that keys may contain regular expressions, where '[xyz]'
1228    matches 'x' 'y' or 'z' (equivalently '[x-z]' describes this as range of values).
1229    '.*' matches any string. For example::
1230
1231    'AUiso':'Atomic isotropic displacement parameter',
1232
1233    will match variable ``'p::AUiso:a'``.
1234    If parentheses are used in the key, the contents of those parentheses can be
1235    used in the value, such as::
1236
1237    'AU([123][123])':'Atomic anisotropic displacement parameter U\\1',
1238
1239    will match ``AU11``, ``AU23``,.. and `U11`, `U23` etc will be displayed
1240    in the value when used.
1241   
1242    '''
1243    if reVarDesc: return # already done
1244    for key,value in {
1245        # derived or other sequential vars
1246        '([abc])$' : 'Lattice parameter, \\1, from Ai and Djk', # N.B. '$' prevents match if any characters follow
1247        u'\u03B1' : u'Lattice parameter, \u03B1, from Ai and Djk',
1248        u'\u03B2' : u'Lattice parameter, \u03B2, from Ai and Djk',
1249        u'\u03B3' : u'Lattice parameter, \u03B3, from Ai and Djk',
1250        # ambiguous, alas:
1251        'Scale' : 'Phase or Histogram scale factor',
1252        # Phase vars (p::<var>)
1253        'A([0-5])' : 'Reciprocal metric tensor component \\1',
1254        'Vol' : 'Unit cell volume',
1255        # Atom vars (p::<var>:a)
1256        'dA([xyz])$' : 'change to atomic coordinate, \\1',
1257        'A([xyz])$' : '\\1 fractional atomic coordinate',
1258        'AUiso':'Atomic isotropic displacement parameter',
1259        'AU([123][123])':'Atomic anisotropic displacement parameter U\\1',
1260        'Afrac': 'Atomic occupancy parameter',
1261        # Hist & Phase (HAP) vars (p:h:<var>)
1262        'Back': 'Background term',
1263        'BkPkint;(.*)':'Background peak #\\1 intensity',
1264        'BkPkpos;(.*)':'Background peak #\\1 position',
1265        'BkPksig;(.*)':'Background peak #\\1 Gaussian width',
1266        'BkPkgam;(.*)':'Background peak #\\1 Cauchy width',
1267        'Bab([AU])': 'Babinet solvent scattering coef. \\1',
1268        'D([123][123])' : 'Anisotropic strain coef. \\1',
1269        'Extinction' : 'Extinction coef.',
1270        'MD' : 'March-Dollase coef.',
1271        'Mustrain;.*' : 'Microstrain coef.',
1272        'Size;.*' : 'Crystallite size value',
1273        'eA$' : 'Cubic mustrain value',
1274        'Ep$' : 'Primary extinction',
1275        'Es$' : 'Secondary type II extinction',
1276        'Eg$' : 'Secondary type I extinction',
1277        #Histogram vars (:h:<var>)
1278        'Absorption' : 'Absorption coef.',
1279        'Displace([XY])' : 'Debye-Scherrer sample displacement \\1',
1280        'Lam' : 'Wavelength',
1281        'Polariz\.' : 'Polarization correction',
1282        'SH/L' : 'FCJ peak asymmetry correction',
1283        '([UVW])$' : 'Gaussian instrument broadening \\1',
1284        '([XY])$' : 'Cauchy instrument broadening \\1',
1285        'Zero' : 'Debye-Scherrer zero correction',
1286        'nDebye' : 'Debye model background corr. terms',
1287        'nPeaks' : 'Fixed peak background corr. terms',
1288        'RBV.*' : 'Vector rigid body parameter',
1289        'RBR.*' : 'Residue rigid body parameter',
1290        'RBRO([aijk])' : 'Residue rigid body orientation parameter',
1291        'RBRP([xyz])' : 'Residue rigid body position parameter',
1292        'RBRTr;.*' : 'Residue rigid body torsion parameter',
1293        'RBR([TLS])([123AB][123AB])' : 'Residue rigid body group disp. param.',
1294        # Global vars (::<var>)
1295        'constr([0-9]*)' : 'Parameter from constraint',
1296        # SASD vars (l:<var>;l = component)
1297        'Aspect ratio' : 'Particle aspect ratio',
1298        'Length' : 'Cylinder length',
1299        'Diameter' : 'Cylinder/disk diameter',
1300        'Thickness' : 'Disk thickness',
1301        'Dist' : 'Interparticle distance',
1302        'VolFr' : 'Dense scatterer volume fraction',
1303        'epis' : 'Sticky sphere epsilon',
1304        'Sticky' : 'Stickyness',
1305        'Depth' : 'Well depth',
1306        'Width' : 'Well width',
1307        'Volume' : 'Particle volume',
1308        'Radius' : 'Sphere/cylinder/disk radius',
1309        'Mean' : 'Particle mean radius',
1310        'StdDev' : 'Standard deviation in Mean',
1311        'G$': 'Guinier prefactor',
1312        'Rg$': 'Guinier radius of gyration',
1313        'B$': 'Porod prefactor',
1314        'P$': 'Porod power',
1315        'Cutoff': 'Porod cutoff',
1316        'PkInt': 'Bragg peak intensity',
1317        'PkPos': 'Bragg peak position',
1318        'PkSig': 'Bragg peak sigma',
1319        'PkGam': 'Bragg peak gamma',
1320        'e([12][12])' : 'strain tensor e\1',   # strain vars e11, e22, e12
1321        'Dcalc': 'Calc. d-spacing',
1322        }.items():
1323        VarDesc[key] = value
1324        reVarDesc[re.compile(key)] = value
1325
1326def getDescr(name):
1327    '''Return a short description for a GSAS-II variable
1328
1329    :param str name: The descriptive part of the variable name without colons (:)
1330     
1331    :returns: a short description or None if not found
1332    '''
1333
1334    CompileVarDesc() # compile the regular expressions, if needed
1335    for key in reVarDesc:
1336        m = key.match(name)
1337        if m:
1338            return m.expand(reVarDesc[key])
1339    return None
1340
1341def GenWildCard(varlist):
1342    '''Generate wildcard versions of G2 variables. These introduce '*'
1343    for a phase, histogram or atom number (but only for one of these
1344    fields) but only when there is more than one matching variable in the
1345    input variable list. So if the input is this::
1346   
1347      varlist = ['0::AUiso:0', '0::AUiso:1', '1::AUiso:0']
1348
1349    then the output will be this::
1350   
1351       wildList = ['*::AUiso:0', '0::AUiso:*']
1352
1353    :param list varlist: an input list of GSAS-II variable names
1354      (such as 0::AUiso:0)
1355
1356    :returns: wildList, the generated list of wild card variable names.
1357    '''
1358    wild = []
1359    for i in (0,1,3):
1360        currentL = varlist[:]
1361        while currentL:
1362            item1 = currentL.pop(0)
1363            i1splt = item1.split(':')
1364            if i >= len(i1splt): continue
1365            if i1splt[i]:
1366                nextL = []
1367                i1splt[i] = '[0-9]+'
1368                rexp = re.compile(':'.join(i1splt))
1369                matchlist = [item1]
1370                for nxtitem in currentL:
1371                    if rexp.match(nxtitem):
1372                        matchlist += [nxtitem]
1373                    else:
1374                        nextL.append(nxtitem)
1375                if len(matchlist) > 1:
1376                    i1splt[i] = '*'
1377                    wild.append(':'.join(i1splt))
1378                currentL = nextL
1379    return wild
1380
1381def LookupWildCard(varname,varlist):
1382    '''returns a list of variable names from list varname
1383    that match wildcard name in varname
1384   
1385    :param str varname: a G2 variable name containing a wildcard
1386      (such as \*::var)
1387    :param list varlist: the list of all variable names used in
1388      the current project
1389    :returns: a list of matching GSAS-II variables (may be empty) 
1390    '''
1391    rexp = re.compile(varname.replace('*','[0-9]+'))
1392    return sorted([var for var in varlist if rexp.match(var)])
1393
1394
1395def _lookup(dic,key):
1396    '''Lookup a key in a dictionary, where None returns an empty string
1397    but an unmatched key returns a question mark. Used in :class:`G2VarObj`
1398    '''
1399    if key is None:
1400        return ""
1401    elif key == "*":
1402        return "*"
1403    else:
1404        return dic.get(key,'?')
1405
1406class G2VarObj(object):
1407    '''Defines a GSAS-II variable either using the phase/atom/histogram
1408    unique Id numbers or using a character string that specifies
1409    variables by phase/atom/histogram number (which can change).
1410    Note that :func:`LoadID` should be used to (re)load the current Ids
1411    before creating or later using the G2VarObj object.
1412
1413    This can store rigid body variables, but does not translate the residue # and
1414    body # to/from random Ids
1415
1416    A :class:`G2VarObj` object can be created with a single parameter:
1417   
1418    :param str/tuple varname: a single value can be used to create a :class:`G2VarObj`
1419      object. If a string, it must be of form "p:h:var" or "p:h:var:a", where
1420
1421     * p is the phase number (which may be left blank or may be '*' to indicate all phases);
1422     * h is the histogram number (which may be left blank or may be '*' to indicate all histograms);
1423     * a is the atom number (which may be left blank in which case the third colon is omitted).
1424       The atom number can be specified as '*' if a phase number is specified (not as '*').
1425       For rigid body variables, specify a will be a string of form "residue:body#"
1426
1427      Alternately a single tuple of form (Phase,Histogram,VarName,AtomID) can be used, where
1428      Phase, Histogram, and AtomID are None or are ranId values (or one can be '*')
1429      and VarName is a string. Note that if Phase is '*' then the AtomID is an atom number.
1430      For a rigid body variables, AtomID is a string of form "residue:body#".
1431
1432    If four positional arguments are supplied, they are:
1433
1434    :param str/int phasenum: The number for the phase (or None or '*')
1435    :param str/int histnum: The number for the histogram (or None or '*')
1436    :param str varname: a single value can be used to create a :class:`G2VarObj`
1437    :param str/int atomnum: The number for the atom (or None or '*')
1438   
1439    '''
1440    IDdict = {}
1441    IDdict['phases'] = {}
1442    IDdict['hists'] = {}
1443    IDdict['atoms'] = {}
1444    def __init__(self,*args):
1445        self.phase = None
1446        self.histogram = None
1447        self.name = ''
1448        self.atom = None
1449        if len(args) == 1 and (type(args[0]) is list or type(args[0]) is tuple) and len(args[0]) == 4:
1450            # single arg with 4 values
1451            self.phase,self.histogram,self.name,self.atom = args[0]
1452        elif len(args) == 1 and ':' in args[0]:
1453            #parse a string
1454            lst = args[0].split(':')
1455            if lst[0] == '*':
1456                self.phase = '*'
1457                if len(lst) > 3:
1458                    self.atom = lst[3]
1459                self.histogram = HistIdLookup.get(lst[1],[None,None])[1]
1460            elif lst[1] == '*':           
1461                self.histogram = '*'
1462                self.phase = PhaseIdLookup.get(lst[0],[None,None])[1]
1463            else:
1464                self.histogram = HistIdLookup.get(lst[1],[None,None])[1]
1465                self.phase = PhaseIdLookup.get(lst[0],[None,None])[1]
1466                if len(lst) == 4:
1467                    if lst[3] == '*':
1468                        self.atom = '*'
1469                    else:
1470                        self.atom = AtomIdLookup[lst[0]].get(lst[3],[None,None])[1]
1471                elif len(lst) == 5:
1472                    self.atom = lst[3]+":"+lst[4]
1473                elif len(lst) == 3:
1474                    pass
1475                else:
1476                    raise Exception,"Too many colons in var name "+str(args[0])
1477            self.name = lst[2]
1478        elif len(args) == 4:
1479            if args[0] == '*':
1480                self.phase = '*'
1481                self.atom = args[3]
1482            else:
1483                self.phase = PhaseIdLookup.get(str(args[0]),[None,None])[1]
1484                if args[3] == '*':
1485                    self.atom = '*'
1486                elif args[0] is not None:
1487                    self.atom = AtomIdLookup[args[0]].get(str(args[3]),[None,None])[1]
1488            if args[1] == '*':
1489                self.histogram = '*'
1490            else:
1491                self.histogram = HistIdLookup.get(str(args[1]),[None,None])[1]
1492            self.name = args[2]
1493        else:
1494            raise Exception,"Incorrectly called GSAS-II parameter name"
1495
1496        #print "DEBUG: created ",self.phase,self.histogram,self.name,self.atom
1497
1498    def __str__(self):
1499        return self.varname()
1500
1501    def varname(self):
1502        '''Formats the GSAS-II variable name as a "traditional" GSAS-II variable
1503        string (p:h:<var>:a) or (p:h:<var>)
1504
1505        :returns: the variable name as a str
1506        '''
1507        a = ""
1508        if self.phase == "*":
1509            ph = "*"
1510            if self.atom:
1511                a = ":" + str(self.atom)
1512        else:
1513            ph = _lookup(PhaseRanIdLookup,self.phase)
1514            if self.atom == '*':
1515                a = ':*'
1516            elif self.atom:
1517                if ":" in str(self.atom):
1518                    a = ":" + str(self.atom)
1519                elif ph in AtomRanIdLookup:
1520                    a = ":" + AtomRanIdLookup[ph].get(self.atom,'?')
1521                else:
1522                    a = ":?"
1523        if self.histogram == "*":
1524            hist = "*"
1525        else:
1526            hist = _lookup(HistRanIdLookup,self.histogram)
1527        s = (ph + ":" + hist + ":" + str(self.name)) + a
1528        return s
1529   
1530    def __repr__(self):
1531        '''Return the detailed contents of the object
1532        '''
1533        s = "<"
1534        if self.phase == '*':
1535            s += "Phases: all; "
1536            if self.atom is not None:
1537                if ":" in str(self.atom):
1538                    s += "Rigid body" + str(self.atom) + "; "
1539                else:
1540                    s += "Atom #" + str(self.atom) + "; "
1541        elif self.phase is not None:
1542            ph =  _lookup(PhaseRanIdLookup,self.phase)
1543            s += "Phase: rId=" + str(self.phase) + " (#"+ ph + "); "
1544            if self.atom == '*':
1545                s += "Atoms: all; "
1546            elif ":" in self(self.atom):
1547                s += "Rigid body" + str(self.atom) + "; "
1548            elif self.atom is not None:
1549                s += "Atom rId=" + str(self.atom)
1550                if ph in AtomRanIdLookup:
1551                    s += " (#" + AtomRanIdLookup[ph].get(self.atom,'?') + "); "
1552                else:
1553                    s += " (#? -- not found!); "
1554        if self.histogram == '*':
1555            s += "Histograms: all; "
1556        elif self.histogram is not None:
1557            hist = _lookup(HistRanIdLookup,self.histogram)
1558            s += "Histogram: rId=" + str(self.histogram) + " (#"+ hist + "); "
1559        s += 'Variable name="' + str(self.name) + '">'
1560        return s+" ("+self.varname()+")"
1561
1562    def __eq__(self, other):
1563        if type(other) is type(self):
1564            return (self.phase == other.phase and
1565                    self.histogram == other.histogram and
1566                    self.name == other.name and
1567                    self.atom == other.atom)
1568        return False
1569
1570    def _show(self):
1571        'For testing, shows the current lookup table'
1572        print 'phases', self.IDdict['phases']
1573        print 'hists', self.IDdict['hists']
1574        print 'atomDict', self.IDdict['atoms']
1575
1576#==========================================================================
1577# shortcut routines
1578exp = np.exp
1579sind = sin = s = lambda x: np.sin(x*np.pi/180.)
1580cosd = cos = c = lambda x: np.cos(x*np.pi/180.)
1581tand = tan = t = lambda x: np.tan(x*np.pi/180.)
1582sqrt = sq = lambda x: np.sqrt(x)
1583pi = lambda: np.pi
1584class ExpressionObj(object):
1585    '''Defines an object with a user-defined expression, to be used for
1586    secondary fits or restraints. Object is created null, but is changed
1587    using :meth:`LoadExpression`. This contains only the minimum
1588    information that needs to be stored to save and load the expression
1589    and how it is mapped to GSAS-II variables.
1590    '''
1591    def __init__(self):
1592        self.expression = ''
1593        'The expression as a text string'
1594        self.assgnVars = {}
1595        '''A dict where keys are label names in the expression mapping to a GSAS-II
1596        variable. The value a G2 variable name.
1597        Note that the G2 variable name may contain a wild-card and correspond to
1598        multiple values.
1599        '''
1600        self.freeVars = {}
1601        '''A dict where keys are label names in the expression mapping to a free
1602        parameter. The value is a list with:
1603
1604         * a name assigned to the parameter
1605         * a value for to the parameter and
1606         * a flag to determine if the variable is refined.
1607        ''' 
1608        self.depVar = None
1609
1610        self.lastError = ('','')
1611        '''Shows last encountered error in processing expression
1612        (list of 1-3 str values)'''
1613
1614    def LoadExpression(self,expr,exprVarLst,varSelect,varName,varValue,varRefflag):
1615        '''Load the expression and associated settings into the object. Raises
1616        an exception if the expression is not parsed, if not all functions
1617        are defined or if not all needed parameter labels in the expression
1618        are defined.
1619
1620        This will not test if the variable referenced in these definitions
1621        are actually in the parameter dictionary. This is checked when the
1622        computation for the expression is done in :meth:`SetupCalc`.
1623       
1624        :param str expr: the expression
1625        :param list exprVarLst: parameter labels found in the expression
1626        :param dict varSelect: this will be 0 for Free parameters
1627          and non-zero for expression labels linked to G2 variables.
1628        :param dict varName: Defines a name (str) associated with each free parameter
1629        :param dict varValue: Defines a value (float) associated with each free parameter
1630        :param dict varRefflag: Defines a refinement flag (bool)
1631          associated with each free parameter
1632        '''
1633        self.expression = expr
1634        self.compiledExpr = None
1635        self.freeVars = {}
1636        self.assgnVars = {}
1637        for v in exprVarLst:
1638            if varSelect[v] == 0:
1639                self.freeVars[v] = [
1640                    varName.get(v),
1641                    varValue.get(v),
1642                    varRefflag.get(v),
1643                    ]
1644            else:
1645                self.assgnVars[v] = varName[v]
1646        self.CheckVars()
1647
1648    def EditExpression(self,exprVarLst,varSelect,varName,varValue,varRefflag):
1649        '''Load the expression and associated settings from the object into
1650        arrays used for editing.
1651
1652        :param list exprVarLst: parameter labels found in the expression
1653        :param dict varSelect: this will be 0 for Free parameters
1654          and non-zero for expression labels linked to G2 variables.
1655        :param dict varName: Defines a name (str) associated with each free parameter
1656        :param dict varValue: Defines a value (float) associated with each free parameter
1657        :param dict varRefflag: Defines a refinement flag (bool)
1658          associated with each free parameter
1659
1660        :returns: the expression as a str
1661        '''
1662        for v in self.freeVars:
1663            varSelect[v] = 0
1664            varName[v] = self.freeVars[v][0]
1665            varValue[v] = self.freeVars[v][1]
1666            varRefflag[v] = self.freeVars[v][2]
1667        for v in self.assgnVars:
1668            varSelect[v] = 1
1669            varName[v] = self.assgnVars[v]
1670        return self.expression
1671
1672    def GetVaried(self):
1673        'Returns the names of the free parameters that will be refined'
1674        return ["::"+self.freeVars[v][0] for v in self.freeVars if self.freeVars[v][2]]
1675
1676    def GetVariedVarVal(self):
1677        'Returns the names and values of the free parameters that will be refined'
1678        return [("::"+self.freeVars[v][0],self.freeVars[v][1]) for v in self.freeVars if self.freeVars[v][2]]
1679
1680    def UpdateVariedVars(self,varyList,values):
1681        'Updates values for the free parameters (after a refinement); only updates refined vars'
1682        for v in self.freeVars:
1683            if not self.freeVars[v][2]: continue
1684            if "::"+self.freeVars[v][0] not in varyList: continue
1685            indx = varyList.index("::"+self.freeVars[v][0])
1686            self.freeVars[v][1] = values[indx]
1687
1688    def GetIndependentVars(self):
1689        'Returns the names of the required independent parameters used in expression'
1690        return [self.assgnVars[v] for v in self.assgnVars]
1691
1692    def CheckVars(self):
1693        '''Check that the expression can be parsed, all functions are
1694        defined and that input loaded into the object is internally
1695        consistent. If not an Exception is raised.
1696
1697        :returns: a dict with references to packages needed to
1698          find functions referenced in the expression.
1699        '''
1700        ret = self.ParseExpression(self.expression)
1701        if not ret:
1702            raise Exception("Expression parse error")
1703        exprLblList,fxnpkgdict = ret
1704        # check each var used in expression is defined
1705        defined = self.assgnVars.keys() + self.freeVars.keys()
1706        notfound = []
1707        for var in exprLblList:
1708            if var not in defined:
1709                notfound.append(var)
1710        if notfound:
1711            msg = 'Not all variables defined'
1712            msg1 = 'The following variables were not defined: '
1713            msg2 = ''
1714            for var in notfound:
1715                if msg: msg += ', '
1716                msg += var
1717            self.lastError = (msg1,'  '+msg2)
1718            raise Exception(msg)
1719        return fxnpkgdict
1720
1721    def ParseExpression(self,expr):
1722        '''Parse an expression and return a dict of called functions and
1723        the variables used in the expression. Returns None in case an error
1724        is encountered. If packages are referenced in functions, they are loaded
1725        and the functions are looked up into the modules global
1726        workspace.
1727       
1728        Note that no changes are made to the object other than
1729        saving an error message, so that this can be used for testing prior
1730        to the save.
1731
1732        :returns: a list of used variables
1733        '''
1734        self.lastError = ('','')
1735        import ast
1736        def FindFunction(f):
1737            '''Find the object corresponding to function f
1738            :param str f: a function name such as 'numpy.exp'
1739            :returns: (pkgdict,pkgobj) where pkgdict contains a dict
1740              that defines the package location(s) and where pkgobj
1741              defines the object associated with the function.
1742              If the function is not found, pkgobj is None.
1743            '''
1744            df = f.split('.')
1745            pkgdict = {}
1746            # no listed package, try in current namespace
1747            if len(df) == 1: 
1748                try:
1749                    fxnobj = eval(f)
1750                    return pkgdict,fxnobj
1751                except (AttributeError, NameError):
1752                    return None,None
1753            else:
1754                try:
1755                    fxnobj = eval(f)
1756                    pkgdict[df[0]] = eval(df[0])
1757                    return pkgdict,fxnobj
1758                except (AttributeError, NameError):
1759                    pass
1760            # includes a package, lets try to load the packages
1761            pkgname = ''
1762            path = sys.path
1763            for pkg in f.split('.')[:-1]: # if needed, descend down the tree
1764                if pkgname:
1765                    pkgname += '.' + pkg
1766                else:
1767                    pkgname = pkg
1768                fp = None
1769                try:
1770                    fp, fppath,desc = imp.find_module(pkg,path)
1771                    pkgobj = imp.load_module(pkg,fp,fppath,desc)
1772                    pkgdict[pkgname] = pkgobj
1773                    path = [fppath]
1774                except Exception as msg:
1775                    print('load of '+pkgname+' failed with error='+str(msg))
1776                    return {},None
1777                finally:
1778                    if fp: fp.close()
1779                try:
1780                    #print 'before',pkgdict.keys()
1781                    fxnobj = eval(f,globals(),pkgdict)
1782                    #print 'after 1',pkgdict.keys()
1783                    #fxnobj = eval(f,pkgdict)
1784                    #print 'after 2',pkgdict.keys()
1785                    return pkgdict,fxnobj
1786                except:
1787                    continue
1788            return None # not found
1789        def ASTtransverse(node,fxn=False):
1790            '''Transverse a AST-parsed expresson, compiling a list of variables
1791            referenced in the expression. This routine is used recursively.
1792
1793            :returns: varlist,fxnlist where
1794              varlist is a list of referenced variable names and
1795              fxnlist is a list of used functions
1796            '''
1797            varlist = []
1798            fxnlist = []
1799            if isinstance(node, list):
1800                for b in node:
1801                    v,f = ASTtransverse(b,fxn)
1802                    varlist += v
1803                    fxnlist += f
1804            elif isinstance(node, ast.AST):
1805                for a, b in ast.iter_fields(node):
1806                    if isinstance(b, ast.AST):
1807                        if a == 'func': 
1808                            fxnlist += ['.'.join(ASTtransverse(b,True)[0])]
1809                            continue
1810                        v,f = ASTtransverse(b,fxn)
1811                        varlist += v
1812                        fxnlist += f
1813                    elif isinstance(b, list):
1814                        v,f = ASTtransverse(b,fxn)
1815                        varlist += v
1816                        fxnlist += f
1817                    elif node.__class__.__name__ == "Name":
1818                        varlist += [b]
1819                    elif fxn and node.__class__.__name__ == "Attribute":
1820                        varlist += [b]
1821            return varlist,fxnlist
1822        try:
1823            exprast = ast.parse(expr)
1824        except SyntaxError as err:
1825            s = ''
1826            import traceback
1827            for i in traceback.format_exc().splitlines()[-3:-1]:
1828                if s: s += "\n"
1829                s += str(i)
1830            self.lastError = ("Error parsing expression:",s)
1831            return
1832        # find the variables & functions
1833        v,f = ASTtransverse(exprast)
1834        varlist = sorted(list(set(v)))
1835        fxnlist = list(set(f))
1836        pkgdict = {}
1837        # check the functions are defined
1838        for fxn in fxnlist:
1839            fxndict,fxnobj = FindFunction(fxn)
1840            if not fxnobj:
1841                self.lastError = ("Error: Invalid function",fxn,
1842                                  "is not defined")
1843                return
1844            if not hasattr(fxnobj,'__call__'):
1845                self.lastError = ("Error: Not a function.",fxn,
1846                                  "cannot be called as a function")
1847                return
1848            pkgdict.update(fxndict)
1849        return varlist,pkgdict
1850
1851    def GetDepVar(self):
1852        'return the dependent variable, or None'
1853        return self.depVar
1854
1855    def SetDepVar(self,var):
1856        'Set the dependent variable, if used'
1857        self.depVar = var
1858#==========================================================================
1859class ExpressionCalcObj(object):
1860    '''An object used to evaluate an expression from a :class:`ExpressionObj`
1861    object.
1862   
1863    :param ExpressionObj exprObj: a :class:`~ExpressionObj` expression object with
1864      an expression string and mappings for the parameter labels in that object.
1865    '''
1866    def __init__(self,exprObj):
1867        self.eObj = exprObj
1868        'The expression and mappings; a :class:`ExpressionObj` object'
1869        self.compiledExpr = None
1870        'The expression as compiled byte-code'
1871        self.exprDict = {}
1872        '''dict that defines values for labels used in expression and packages
1873        referenced by functions
1874        '''
1875        self.lblLookup = {}
1876        '''Lookup table that specifies the expression label name that is
1877        tied to a particular GSAS-II parameters in the parmDict.
1878        '''
1879        self.fxnpkgdict = {}
1880        '''a dict with references to packages needed to
1881        find functions referenced in the expression.
1882        '''
1883        self.varLookup = {}
1884        '''Lookup table that specifies the GSAS-II variable(s)
1885        indexed by the expression label name. (Used for only for diagnostics
1886        not evaluation of expression.)
1887        '''
1888        # Patch: for old-style expressions with a (now removed step size)
1889        for v in self.eObj.assgnVars:
1890            if not isinstance(self.eObj.assgnVars[v], basestring):
1891                self.eObj.assgnVars[v] = self.eObj.assgnVars[v][0]
1892
1893    def SetupCalc(self,parmDict):
1894        '''Do all preparations to use the expression for computation.
1895        Adds the free parameter values to the parameter dict (parmDict).
1896        '''
1897        self.fxnpkgdict = self.eObj.CheckVars()
1898        # all is OK, compile the expression
1899        self.compiledExpr = compile(self.eObj.expression,'','eval')
1900
1901        # look at first value in parmDict to determine its type
1902        parmsInList = True
1903        for key in parmDict:
1904            val = parmDict[key]
1905            if isinstance(val, basestring):
1906                parmsInList = False
1907                break
1908            try: # check if values are in lists
1909                val = parmDict[key][0]
1910            except (TypeError,IndexError):
1911                parmsInList = False
1912            break
1913           
1914        # set up the dicts needed to speed computations
1915        self.exprDict = {}
1916        self.lblLookup = {}
1917        self.varLookup = {}
1918        for v in self.eObj.freeVars:
1919            varname = self.eObj.freeVars[v][0]
1920            varname = "::" + varname.lstrip(':').replace(' ','_').replace(':',';')
1921            self.lblLookup[varname] = v
1922            self.varLookup[v] = varname
1923            if parmsInList:
1924                parmDict[varname] = [self.eObj.freeVars[v][1],self.eObj.freeVars[v][2]]
1925            else:
1926                parmDict[varname] = self.eObj.freeVars[v][1]
1927            self.exprDict[v] = self.eObj.freeVars[v][1]
1928        for v in self.eObj.assgnVars:
1929            varname = self.eObj.assgnVars[v]
1930            if '*' in varname:
1931                varlist = LookupWildCard(varname,parmDict.keys())
1932                if len(varlist) == 0:
1933                    raise Exception,"No variables match "+str(v)
1934                for var in varlist:
1935                    self.lblLookup[var] = v
1936                if parmsInList:
1937                    self.exprDict[v] = np.array([parmDict[var][0] for var in varlist])
1938                else:
1939                    self.exprDict[v] = np.array([parmDict[var] for var in varlist])
1940                self.varLookup[v] = [var for var in varlist]
1941            elif varname in parmDict:
1942                self.lblLookup[varname] = v
1943                self.varLookup[v] = varname
1944                if parmsInList:
1945                    self.exprDict[v] = parmDict[varname][0]
1946                else:
1947                    self.exprDict[v] = parmDict[varname]
1948            else:
1949                raise Exception,"No value for variable "+str(v)
1950        self.exprDict.update(self.fxnpkgdict)
1951
1952    def UpdateVars(self,varList,valList):
1953        '''Update the dict for the expression with a set of values
1954        :param list varList: a list of variable names
1955        :param list valList: a list of corresponding values
1956        '''
1957        for var,val in zip(varList,valList):
1958            self.exprDict[self.lblLookup.get(var,'undefined: '+var)] = val
1959
1960    def UpdateDict(self,parmDict):
1961        '''Update the dict for the expression with values in a dict
1962        :param list parmDict: a dict of values some of which may be in use here
1963        '''
1964        for var in parmDict:
1965            if var in self.lblLookup:
1966                self.exprDict[self.lblLookup[var]] = parmDict[var]
1967           
1968    def EvalExpression(self):
1969        '''Evaluate an expression. Note that the expression
1970        and mapping are taken from the :class:`ExpressionObj` expression object
1971        and the parameter values were specified in :meth:`SetupCalc`.
1972        :returns: a single value for the expression. If parameter
1973        values are arrays (for example, from wild-carded variable names),
1974        the sum of the resulting expression is returned.
1975
1976        For example, if the expression is ``'A*B'``,
1977        where A is 2.0 and B maps to ``'1::Afrac:*'``, which evaluates to::
1978
1979        [0.5, 1, 0.5]
1980
1981        then the result will be ``4.0``.
1982        '''
1983        if self.compiledExpr is None:
1984            raise Exception,"EvalExpression called before SetupCalc"
1985        val = eval(self.compiledExpr,globals(),self.exprDict)
1986        if not np.isscalar(val):
1987            val = np.sum(val)
1988        return val
1989
1990
1991if __name__ == "__main__":
1992    # test equation evaluation
1993    def showEQ(calcobj):
1994        print 50*'='
1995        print calcobj.eObj.expression,'=',calcobj.EvalExpression()
1996        for v in sorted(calcobj.varLookup):
1997            print "  ",v,'=',calcobj.exprDict[v],'=',calcobj.varLookup[v]
1998        # print '  Derivatives'
1999        # for v in calcobj.derivStep.keys():
2000        #     print '    d(Expr)/d('+v+') =',calcobj.EvalDeriv(v)
2001
2002    obj = ExpressionObj()
2003
2004    obj.expression = "A*np.exp(B)"
2005    obj.assgnVars =  {'B': '0::Afrac:1'}
2006    obj.freeVars =  {'A': [u'A', 0.5, True]}
2007    #obj.CheckVars()
2008    parmDict2 = {'0::Afrac:0':[0.0,True], '0::Afrac:1': [1.0,False]}
2009    calcobj = ExpressionCalcObj(obj)
2010    calcobj.SetupCalc(parmDict2)
2011    showEQ(calcobj)
2012
2013    obj.expression = "A*np.exp(B)"
2014    obj.assgnVars =  {'B': '0::Afrac:*'}
2015    obj.freeVars =  {'A': [u'Free Prm A', 0.5, True]}
2016    #obj.CheckVars()
2017    parmDict1 = {'0::Afrac:0':1.0, '0::Afrac:1': 1.0}
2018    calcobj = ExpressionCalcObj(obj)
2019    calcobj.SetupCalc(parmDict1)
2020    showEQ(calcobj)
2021
2022    calcobj.SetupCalc(parmDict2)
2023    showEQ(calcobj)
Note: See TracBrowser for help on using the repository browser.