source: trunk/GSASIIobj.py @ 3806

Last change on this file since 3806 was 3806, checked in by toby, 4 years ago

redo parameter lookup to provide numerical deriv step size (see G2obj.getVarStep)

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