source: trunk/GSASIIobj.py @ 4837

Last change on this file since 4837 was 4834, checked in by vondreele, 4 years ago

change 'RBf' to 'RBVf' & 'RBRf' as appropriate.

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