source: trunk/GSASIIobj.py @ 4303

Last change on this file since 4303 was 4303, checked in by toby, 22 months ago

fix scriptable for multiple image files and xfer correction in @4286

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