source: trunk/GSASIIobj.py @ 4308

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

revisions to docs - set columns at tabs, fix up Instrument parms

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