source: trunk/GSASIIobj.py @ 4370

Last change on this file since 4370 was 4370, checked in by vondreele, 3 years ago

Add new parameter to Data tab - Layer DispSizerThis? is intended to cover multilayered materials of different phases with layers perpendicular to beam - it might have other uses.

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