source: trunk/GSASIIobj.py @ 4312

Last change on this file since 4312 was 4312, checked in by toby, 3 years ago

Fix LaTeX Angstrom symbol for MathJaX again

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