source: trunk/GSASIIobj.py @ 4643

Last change on this file since 4643 was 4643, checked in by vondreele, 13 months ago

fix last few escape sequences in G2obj

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