source: trunk/GSASIIobj.py @ 3711

Last change on this file since 3711 was 3711, checked in by toby, 4 years ago

major constraint update: move conflicting equivs to constraints; allow a formula for multiplier; update docs extensively. New routine EvaluateMultipliers? needed to evaluate formulae

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