source: trunk/GSASIIobj.py @ 4310

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

remove Angstrom symbol. MathJaX fix fails in LaTeX

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