source: trunk/GSASIIobj.py @ 4320

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

still more minor doc adjustments

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