source: trunk/GSASIIobj.py @ 3599

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

remove vars from constraints (see G2obj.removeNonRefined); new tutorial

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