Changeset 3023


Ignore:
Timestamp:
Aug 23, 2017 3:05:51 PM (6 years ago)
Author:
odonnell
Message:

remove wx dependency for GSASIIscriptable

Location:
trunk
Files:
10 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIIO.py

    r3000 r3023  
    2323   Copyright: 2008, Robert B. Von Dreele (Argonne National Laboratory)
    2424"""
    25 import wx
     25# If this is being used for GSASIIscriptable, don't depend on wx
     26try:
     27    import wx
     28except ImportError:
     29    class Placeholder(object):
     30        def __init__(self):
     31            self.Dialog = object
     32    wx = Placeholder()
    2633import math
    2734import numpy as np
     
    3340import GSASIIpath
    3441GSASIIpath.SetVersionNumber("$Revision$")
    35 import GSASIIdataGUI as G2gd
     42try:
     43    import GSASIIdataGUI as G2gd
     44except ImportError:
     45    pass
    3646import GSASIIobj as G2obj
    3747import GSASIIlattice as G2lat
    3848import GSASIImath as G2mth
    39 import GSASIIpwdGUI as G2pdG
    40 import GSASIIimgGUI as G2imG
     49try:
     50    import GSASIIpwdGUI as G2pdG
     51    import GSASIIimgGUI as G2imG
     52except ImportError:
     53    pass
    4154import GSASIIimage as G2img
    4255import GSASIIElem as G2el
    4356import GSASIIstrIO as G2stIO
    4457import GSASIImapvars as G2mv
    45 import GSASIIctrlGUI as G2G
     58try:
     59    import GSASIIctrlGUI as G2G
     60except ImportError:
     61    pass
    4662import os
    4763import os.path as ospath
  • trunk/GSASIIctrlGUI.py

    r3013 r3023  
    1717import os
    1818import sys
    19 import wx
    20 import wx.grid as wg
    21 # import wx.wizard as wz
    22 import wx.aui
    23 import wx.lib.scrolledpanel as wxscroll
    24 import matplotlib as mpl
     19try:
     20    import wx
     21    import wx.grid as wg
     22    # import wx.wizard as wz
     23    import wx.aui
     24    import wx.lib.scrolledpanel as wxscroll
     25    import wx.html        # could postpone this for quicker startup
     26    import matplotlib as mpl
     27except ImportError:
     28    raise
     29    # Dumm 'wx' so this file can be imported
     30    vals = ('TreeCtrl TextCtrl PyValidator Button ComboBox Choice CheckBox'.split() +
     31            'Dialog ID_ANY OPEN'.split())
     32    class Placeholder(object):
     33        def __init__(self, vals):
     34            for val in vals:
     35                setattr(self, val, object)
     36        def __getattr__(self, value):
     37            if value[0].isupper():
     38                return object
     39            return Placeholder([])
     40    wx = Placeholder(vals)
     41    wxscroll = Placeholder(['ScrolledPanel'])
     42    wg = Placeholder('Grid PyGridTableBase PyGridCellEditor'.split())
    2543import time
    2644import copy
    27 import wx.html        # could postpone this for quicker startup
    2845import webbrowser     # could postpone this for quicker startup
    2946
     
    3956WHITE = (255,255,255)
    4057DULL_YELLOW = (230,230,190)
    41 VERY_LIGHT_GREY = wx.Colour(235,235,235)
    42 WACV = wx.ALIGN_CENTER_VERTICAL
     58# Don't depend on wx, for scriptable
     59try:
     60    VERY_LIGHT_GREY = wx.Colour(235,235,235)
     61    WACV = wx.ALIGN_CENTER_VERTICAL
     62except:
     63    # Don't depend on GUI
     64    pass
    4365
    4466################################################################################
  • trunk/GSASIIdataGUI.py

    r3018 r3023  
    2828import numpy.ma as ma
    2929import matplotlib as mpl
    30 import OpenGL as ogl
     30try:
     31    import OpenGL as ogl
     32except ImportError:
     33    pass
    3134import scipy as sp
    3235import scipy.optimize as so
    33 import wx
    34 import wx.grid as wg
    35 #import wx.wizard as wz
    36 #import wx.aui
    37 import wx.lib.scrolledpanel as wxscroll
     36try:
     37    import wx
     38    import wx.grid as wg
     39    #import wx.wizard as wz
     40    #import wx.aui
     41    import wx.lib.scrolledpanel as wxscroll
     42except ImportError:
     43    pass
    3844import GSASIIpath
    3945GSASIIpath.SetVersionNumber("$Revision$")
  • trunk/GSASIIlog.py

    r3000 r3023  
    1515such as menu item, tree item, button press, value change and so on.
    1616'''
    17 import wx
     17try:
     18    import wx
     19except ImportError:
     20    pass
    1821import GSASIIdataGUI as G2gd
    1922import GSASIIpath
  • trunk/GSASIIobj.py

    r3000 r3023  
    1414
    1515This module defines and/or documents the data structures used in GSAS-II, as well
    16 as provides misc. support routines. 
     16as provides misc. support routines.
    1717
    1818Constraints Tree Item
     
    4343  key         explanation
    4444==========  ====================================================
    45 Hist        This specifies a list of constraints on 
     45Hist        This specifies a list of constraints on
    4646            histogram-related parameters,
    4747            which will be of form :h:<var>:n.
    4848HAP         This specifies a list of constraints on parameters
    4949            that are defined for every histogram in each phase
    50             and are of form p:h:<var>:n.           
     50            and are of form p:h:<var>:n.
    5151Phase       This specifies a list of constraints on phase
    5252            parameters,
     
    6767[[<mult1>, <var1>], [<mult2>, <var2>],..., <fixedval>, <varyflag>, <constype>]
    6868
    69 Where the variable pair list item containing two values [<mult>, <var>], where: 
     69Where the variable pair list item containing two values [<mult>, <var>], where:
    7070
    7171  * <mult> is a multiplier for the constraint (float)
     
    8686    * 'e' defines a set of equivalent variables. Only the first variable is refined (if the
    8787      appropriate refine flag is set) and and all other equivalent variables in the list
    88       are generated from that variable, using the appropriate multipliers. 
     88      are generated from that variable, using the appropriate multipliers.
    8989    * 'c' defines a constraint equation of form,
    9090      :math:`m_1 \\times var_1 + m_2 \\times var_2 + ... = c`
     
    9393      constraint and the mult value is ignored.
    9494      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 
     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
    9898      :math:`newvar = m_1 \\times var_1 + m_2 \\times var_2 + ...`
    9999
     
    124124                                (list of float values, length N,
    125125                                ordered to match varyList)
    126 varyList       \                List of directly refined variables 
     126varyList       \                List of directly refined variables
    127127                                (list of str values, length N)
    128 newAtomDict    \                dict with atom position values computed in 
     128newAtomDict    \                dict with atom position values computed in
    129129                                :func:`GSASIIstrMath.ApplyXYZshifts` (dict)
    130130Rvals          \                R-factors, GOF, Marquardt value for last
     
    171171  \         Type             'nuclear' or 'macromolecular' for now (str)
    172172  \         Map              dict of map parameters
    173   \         SH Texture       dict of spherical harmonic preferred orientation 
     173  \         SH Texture       dict of spherical harmonic preferred orientation
    174174                             parameters
    175175  \         Isotope          dict of isotopes for each atom type
    176176  \         Isotopes         dict of scattering lengths for each isotope
    177                              combination for each element in phase 
     177                             combination for each element in phase
    178178  \         Name             phase name (str)
    179179  \         SGData           Space group details as a :ref:`space group (SGData) object <SGData_table>`
     
    181181  \         Pawley neg wt    Restraint value for negative Pawley intensities
    182182                             (float)
    183   \         Flip             dict of Charge flip controls 
    184   \         Data plot type   data plot type ('Mustrain', 'Size' or 
     183  \         Flip             dict of Charge flip controls
     184  \         Data plot type   data plot type ('Mustrain', 'Size' or
    185185                             'Preferred orientation') for powder data (str)
    186186  \         Mass             Mass of unit cell contents in g/mol
    187187  \         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 
     188  \         Z                dict of atomic numbers for each atom type
     189  \         vdWRadii         dict of van der Waals radii for each atom type
    190190  \         Color            Colors for atoms (list of (r,b,g) triplets)
    191191  \         AtomTypes        List of atom types
     
    193193  \         doPawley         Flag for Pawley intensity extraction (bool)
    194194  \         NoAtoms          Number of atoms per unit cell of each type (dict)
    195   \         Pawley dmin      maximum Q (as d-space) to use for Pawley 
     195  \         Pawley dmin      maximum Q (as d-space) to use for Pawley
    196196                             extraction (float)
    197   \         BondRadii        Default radius for each atom used to compute 
     197  \         BondRadii        Default radius for each atom used to compute
    198198                             interatomic distances (list of floats)
    199   \         AngleRadii       Default radius for each atom used to compute 
     199  \         AngleRadii       Default radius for each atom used to compute
    200200                             interatomic angles (list of floats)
    201201  \         DisAglCtls       Dict with distance/angle search controls,
     
    226226\           selectedAtoms    List of selected atoms (list of int values)
    227227\           showRigidBodies  Flag to highlight rigid body placement
    228 \           sizeH            Size ratio for H atoms (float) 
     228\           sizeH            Size ratio for H atoms (float)
    229229\           bondRadius       Size of binds in A (float)
    230230\           atomPtrs         positions of x, type, site sym, ADP flag in Draw Atoms (list)
    231231\           viewPoint        list of lists. First item in list is [x,y,z]
    232232                             in fractional coordinates for the center of
    233                              the plot. Second item list of previous & current 
     233                             the plot. Second item list of previous & current
    234234                             atom number viewed (may be [0,0])
    235235\           showHydrogen     Flag to control plotting of H atoms.
     
    238238                             ellipsoids in % (float).
    239239\           vdwScale         Multiplier of van der Waals radius for
    240                              display of vdW spheres. 
     240                             display of vdW spheres.
    241241\           Atoms            A list of lists with an entry for each atom
    242242                             that is plotted.
     
    295295\           newLeBail        Whether to perform a new LeBail extraction
    296296MCSA            \            Monte-Carlo simulated annealing parameters (dict)
    297 \           
     297\
    298298==========  ===============  ====================================================
    299299
     
    306306   single: Rigid Body Data description
    307307   single: Data object descriptions; Rigid Body Data
    308    
    309 Rigid body descriptions are available for two types of rigid bodies: 'Vector' 
     308
     309Rigid body descriptions are available for two types of rigid bodies: 'Vector'
    310310and 'Residue'. Vector rigid bodies are developed by a sequence of translations each
    311311with a refinable magnitude and Residue rigid bodies are described as Cartesian coordinates
     
    322322\           VectMag          vector magnitudes in A (list)
    323323\           rbXYZ            Cartesian coordinates for Vector rigid body (list of 3 float)
    324 \           rbRef            3 assigned reference atom nos. in rigid body for origin 
     324\           rbRef            3 assigned reference atom nos. in rigid body for origin
    325325                             definition, use center of atoms flag (list of 3 int & 1 bool)
    326326\           VectRef          refinement flags for VectMag values (list of bool)
     
    334334\           rbTypes          Atom types for each atom in rigid body (list of str)
    335335\           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 
     336\           rbRef            3 assigned reference atom nos. in rigid body for origin
    337337                             definition, use center of atoms flag (list of 3 int & 1 bool)
    338338\           rbSeq            Orig,Piv,angle,Riding (list): definition of internal rigid body
     
    346346==========  ===============  ====================================================
    347347
    348 Space Group Objects 
     348Space Group Objects
    349349-------------------
    350350
     
    355355   single: Data object descriptions; Space Group Data
    356356
    357 Space groups are interpreted by :func:`GSASIIspc.SpcGroup` 
    358 and the information is placed in a SGdata object 
     357Space groups are interpreted by :func:`GSASIIspc.SpcGroup`
     358and the information is placed in a SGdata object
    359359which is a dict with these keys:
    360360
     
    391391SGPolax     Axes for space group polarity. Will be one of
    392392            '', 'x', 'y', 'x y', 'z', 'x z', 'y z',
    393             'xyz'. In the case where axes are arbitrary 
     393            'xyz'. In the case where axes are arbitrary
    394394            '111' is used (P 1, and ?).
    395395==========  ====================================================
     
    401401   single: Data object descriptions; Superspace Group Data
    402402
    403 Superspace groups [3+1] are interpreted by :func:`GSASIIspc.SSpcGroup` 
    404 and the information is placed in a SSGdata object 
     403Superspace groups [3+1] are interpreted by :func:`GSASIIspc.SSpcGroup`
     404and the information is placed in a SSGdata object
    405405which is a dict with these keys:
    406406
     
    429429If ``phasedict`` points to the phase information in the data tree, then
    430430atoms are contained in a list of atom records (list) in
    431 ``phasedict['Atoms']``. Also needed to read atom information 
    432 are four pointers, ``cx,ct,cs,cia = phasedict['General']['atomPtrs']``,
    433 which define locations in the atom record, as shown below. Items shown are 
     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
    434434always present; additional ones for macromolecular phases are marked 'mm'
    435435
     
    446446ct+1              refinement flags; combination of 'F', 'X', 'U' (str)
    447447cx,cx+1,cx+2      the x,y and z coordinates (3 floats)
     448cx+3              site occupancy (float)
    448449cs                site symmetry (str)
    449450cs+1              site multiplicity (int)
     
    467468If ``phasedict`` points to the phase information in the data tree, then
    468469drawing atoms are contained in a list of drawing atom records (list) in
    469 ``phasedict['Drawing']['Atoms']``. Also needed to read atom information 
     470``phasedict['Drawing']['Atoms']``. Also needed to read atom information
    470471are four pointers, ``cx,ct,cs,ci = phasedict['Drawing']['AtomPtrs']``,
    471 which define locations in the atom record, as shown below. Items shown are 
     472which define locations in the atom record, as shown below. Items shown are
    472473always present; additional ones for macromolecular phases are marked 'mm'
    473474
     
    517518  key                      sub-key        explanation
    518519======================  ===============  ====================================================
    519 Comments                      \           Text strings extracted from the original powder 
    520                                           data header. These cannot be changed by the user; 
     520Comments                      \           Text strings extracted from the original powder
     521                                          data header. These cannot be changed by the user;
    521522                                          it may be empty.
    522523Limits                       \            A list of two two element lists, as [[Ld,Hd],[L,H]]
    523524                                          where L and Ld are the current and default lowest
    524                                           two-theta value to be used and 
     525                                          two-theta value to be used and
    525526                                          where H and Hd are the current and default highest
    526527                                          two-theta value to be used.
     
    546547                                          Angstrom, when an alpha1, alpha2
    547548                                          source is used [1]
    548                           I(L2)/I(L1)     Ratio of Lam2 to Lam1 [1]           
    549 \                         Type            Histogram type (str) [1]: 
     549                          I(L2)/I(L1)     Ratio of Lam2 to Lam1 [1]
     550\                         Type            Histogram type (str) [1]:
    550551                                           * 'PXC' for constant wavelength x-ray
    551552                                           * 'PNC' for constant wavelength neutron
     
    578579                                          specifies if the value is refined, otherwise
    579580                                          the value is a float unless otherwise noted.
    580 \                         Scale           The histogram scale factor (refinable) 
     581\                         Scale           The histogram scale factor (refinable)
    581582\                         Absorption      The sample absorption coefficient as
    582583                                          :math:`\\mu r` where r is the radius
    583584                                          (refinable). Only valid for Debye-Scherrer geometry.
    584585\                         SurfaceRoughA   Surface roughness parameter A as defined by
    585                                           Surotti,J. Appl. Cryst, 5,325-331, 1972.(refinable - 
    586                                           only valid for Bragg-Brentano geometry)                                         
    587 \                         SurfaceRoughB   Surface roughness parameter B (refinable - 
    588                                           only valid for Bragg-Brentano geometry)                                         
     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)
    589590\                         DisplaceX,      Sample displacement from goniometer center
    590591                          DisplaceY       where Y is along the beam direction and
     
    597598                                          a CIF (str).
    598599\                         Force,          Variables that describe how the measurement
    599                           Temperature,    was performed. Not used directly in 
    600                           Humidity,       any computations. 
     600                          Temperature,    was performed. Not used directly in
     601                          Humidity,       any computations.
    601602                          Pressure,
    602603                          Voltage
     
    616617                                          Debye diffuse terms and background peaks.
    617618                                          (TODO: this needs to be expanded.)
    618 Data                          \           The data consist of a list of 6 np.arrays 
     619Data                          \           The data consist of a list of 6 np.arrays
    619620                                          containing in order:
    620621
     
    635636   single: Powder reflection object description
    636637   single: Data object descriptions; Powder Reflections
    637    
     638
    638639For every phase in a histogram, the ``Reflection Lists`` value is a dict
    639640one element of which is `'RefList'`, which is a np.array containing
     
    653654 10          reflection phase, in degrees
    654655 11          intensity correction for reflection, this times
    655              :math:`F_{obs}^2` or :math:`F_{calc}^2` gives Iobs or Icalc 
     656             :math:`F_{obs}^2` or :math:`F_{calc}^2` gives Iobs or Icalc
    656657==========  ====================================================
    657658
     
    680681  key                      sub-key        explanation
    681682======================  ===============  ====================================================
    682 Data                          \           A dict that contains the 
     683Data                          \           A dict that contains the
    683684                                          reflection table,
    684685                                          as described in the
     
    694695                                          values are floats unless otherwise noted.
    695696\                         Lam             Specifies a wavelength in Angstroms (two floats)
    696 \                         Type            Histogram type (two str values): 
     697\                         Type            Histogram type (two str values):
    697698                                           * 'SXC' for constant wavelength x-ray
    698699                                           * 'SNC' for constant wavelength neutron
     
    722723   single: Single Crystal reflection object description
    723724   single: Data object descriptions; Single Crystal Reflections
    724    
     725
    725726For every single crystal a histogram, the ``'Data'`` item contains
    726727the structure factors as an np.array in item `'RefList'`.
     
    752753   image: Image data object description
    753754   image: Image object descriptions
    754    
     755
    755756Every 2-dimensional image is stored in the GSAS-II data tree
    756757with a top-level entry named beginning with the string "IMG ". The
    757 image data are directly associated with that tree item and there 
     758image data are directly associated with that tree item and there
    758759are a series of children to that item. The routines :func:`GSASIIdataGUI.GSASII.GetUsedHistogramsAndPhasesfromTree`
    759760and :func:`GSASIIstrIO.GetUsedHistogramsAndPhases` will
     
    767768  key                      sub-key              explanation
    768769======================  ======================  ====================================================
    769 Comments                       \                Text strings extracted from the original image data 
    770                                                 header or a metafile. These cannot be changed by 
    771                                                 the user; it may be empty.                                               
    772 Image Controls              azmthOff            (float) The offset to be applied to an azimuthal 
    773                                                 value. Accomodates 
    774                                                 detector orientations other than with the detector 
     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
    775776                                                X-axis
    776777                                                horizontal.
    777778\                           background image    (list:str,float) The name of a tree item ("IMG ...") that is to be subtracted
    778                                                 during image integration multiplied by value. It must have the same size/shape as 
     779                                                during image integration multiplied by value. It must have the same size/shape as
    779780                                                the integrated image. NB: value < 0 for subtraction.
    780781\                           calibrant           (str) The material used for determining the position/orientation
    781                                                 of the image. The data is obtained from :func:`ImageCalibrants` 
     782                                                of the image. The data is obtained from :func:`ImageCalibrants`
    782783                                                and UserCalibrants.py (supplied by user).
    783784\                           calibdmin           (float) The minimum d-spacing used during the last calibration run.
     
    785786                                                calibration run.
    786787\                           center              (list:floats) The [X,Y] point in detector coordinates (mm) where the direct beam
    787                                                 strikes the detector plane as determined by calibration. This point 
    788                                                 does not have to be within the limits of the detector boundaries. 
     788                                                strikes the detector plane as determined by calibration. This point
     789                                                does not have to be within the limits of the detector boundaries.
    789790\                           centerAzm           (bool) If True then the azimuth reported for the integrated slice
    790791                                                of the image is at the center line otherwise it is at the leading edge.
    791792\                           color               (str) The name of the colormap used to display the image. Default = 'Paired'.
    792 \                           cutoff              (float) The minimum value of I/Ib for a point selected in a diffraction ring for 
    793                                                 calibration calculations. See pixLimit for details as how point is found.           
     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.
    794795\                           DetDepth            (float) Coefficient for penetration correction to distance; accounts for diffraction
    795796                                                ring offset at higher angles. Optionally determined by calibration.
     
    797798\                           distance            (float) The distance (mm) from sample to detector plane.
    798799\                           ellipses            (list:lists) Each object in ellipses is a list [center,phi,radii,color] where
    799                                                 center (list) is location (mm) of the ellipse center on the detector plane, phi is the 
     800                                                center (list) is location (mm) of the ellipse center on the detector plane, phi is the
    800801                                                rotation of the ellipse minor axis from the x-axis, and radii are the minor & major
    801802                                                radii of the ellipse. If radii[0] is negative then parameters describe a hyperbola. Color
     
    803804\                           edgemin             (float) Not used;  parameter in EdgeFinder code.
    804805\                           fullIntegrate       (bool) If True then integrate over full 360 deg azimuthal range.
    805 \                           GonioAngles         (list:floats) The 'Omega','Chi','Phi' goniometer angles used for this image. 
     806\                           GonioAngles         (list:floats) The 'Omega','Chi','Phi' goniometer angles used for this image.
    806807                                                Required for texture calculations.
    807808\                           invert_x            (bool) If True display the image with the x-axis inverted.
     
    812813                                                intensities obtained during integration.
    813814\                           outAzimuths         (int) The number of azimuth pie slices.
    814 \                           outChannels         (int) The number of 2-theta steps. 
     815\                           outChannels         (int) The number of 2-theta steps.
    815816\                           pixelSize           (list:ints) The X,Y dimensions (microns) of each pixel.
    816817\                           pixLimit            (int) A box in the image with 2*pixLimit+1 edges is searched to find the maximum.
    817818                                                This value (I) along with the minimum (Ib) in the box is reported by :func:`GSASIIimage.ImageLocalMax`
    818                                                 and subject to cutoff in :func:`GSASIIimage.makeRing`. 
     819                                                and subject to cutoff in :func:`GSASIIimage.makeRing`.
    819820                                                Locations are used to construct rings of points for calibration calcualtions.
    820 \                           PolaVal             (list:float,bool) If type='SASD' and if True, apply polarization correction to intensities from 
     821\                           PolaVal             (list:float,bool) If type='SASD' and if True, apply polarization correction to intensities from
    821822                                                integration using value.
    822 \                           rings               (list:lists) Each entry is [X,Y,dsp] where X & Y are lists of x,y coordinates around a 
     823\                           rings               (list:lists) Each entry is [X,Y,dsp] where X & Y are lists of x,y coordinates around a
    823824                                                diffraction ring with the same d-spacing (dsp)
    824 \                           ring                (list) The x,y coordinates of the >5 points on an inner ring 
     825\                           ring                (list) The x,y coordinates of the >5 points on an inner ring
    825826                                                selected by the user,
    826827\                           Range               (list) The minimum & maximum values of the image
    827 \                           rotation            (float) The angle between the x-axis and the vector about which the 
    828                                                 detector is tilted. Constrained to -180 to 180 deg.     
     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.
    829830\                           SampleShape         (str) Currently only 'Cylinder'. Sample shape for Debye-Scherrer experiments; used for absorption
    830831                                                calculations.
     
    832833                                                to cause correction to be applied.
    833834\                           setDefault          (bool) If True the use the image controls values for all new images to be read. (might be removed)
    834 \                           setRings            (bool) If True then display all the selected x,y ring positions (vida supra rings) used in the calibration.           
     835\                           setRings            (bool) If True then display all the selected x,y ring positions (vida supra rings) used in the calibration.
    835836\                           showLines           (bool) If True then isplay the integration limits to be used.
    836837\                           size                (list:int) The number of pixels on the image x & y axes
     
    838839\                           tilt                (float) The angle the detector normal makes with the incident beam; range -90 to 90.
    839840\                           wavelength          (float) Tha radiation wavelength (Angstroms) as entered by the user (or someday obtained from the image header).
    840                                                
     841
    841842Masks                       Arcs                (list: lists) Each entry [2-theta,[azimuth[0],azimuth[1]],thickness] describes an arc mask
    842843                                                to be excluded from integration
     
    850851                                                to be excluded from integration.
    851852\                           Thresholds          (list:[tuple,list]) [(Imin,Imax),[Imin,Imax]] This gives lower and upper limits for points on the image to be included
    852                                                 in integrsation. The tuple is the image intensity limits and the list are those set by the user.   
    853                                                
     853                                                in integrsation. The tuple is the image intensity limits and the list are those set by the user.
     854
    854855Stress/Strain               Sample phi          (float) Sample rotation about vertical axis.
    855856\                           Sample z            (float) Sample translation from the calibration sample position (for Sample phi = 0)
    856857                                                These will be restricted by space group symmetry; result of strain fit refinement.
    857858\                           Type                (str) 'True' or 'Conventional': The strain model used for the calculation.
    858 \                           d-zero              (list:dict) Each item is for a diffraction ring on the image; all items are from the same phase 
     859\                           d-zero              (list:dict) Each item is for a diffraction ring on the image; all items are from the same phase
    859860                                                and are used to determine the strain tensor.
    860861                                                The dictionary items are:
     
    868869                                                'ImtaObs': (list: lists) [[d],[azm]] transformed via detector calibration from ImxyObs.
    869870                                                'ImtaCalc': (list: lists [[d],[azm]] calculated d-spacing & azimuth from fit.
    870                                                
     871
    871872======================  ======================  ====================================================
    872873
     
    880881
    881882The parameter dictionary contains all of the variable parameters for the refinement.
    882 The dictionary keys are the name of the parameter (<phase>:<hist>:<name>:<atom>). 
     883The dictionary keys are the name of the parameter (<phase>:<hist>:<name>:<atom>).
    883884It is prepared in two ways. When loaded from the tree
    884885(in :meth:`GSASIIdataGUI.GSASII.MakeLSParmDict` and
    885 :meth:`GSASIIIO.ExportBaseclass.loadParmDict`), 
     886:meth:`GSASIIIO.ExportBaseclass.loadParmDict`),
    886887the values are lists with two elements: ``[value, refine flag]``
    887888
    888889When loaded from the GPX file (in
    889890:func:`GSASIIstrMain.Refine` and :func:`GSASIIstrMain.SeqRefine`), the value in the
    890 dict is the actual parameter value (usually a float, but sometimes a 
    891 letter or string flag value (such as I or A for iso/anisotropic). 
     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).
    892893
    893894
     
    925926def StripUnicode(string,subs='.'):
    926927    '''Strip non-ASCII characters from strings
    927    
     928
    928929    :param str string: string to strip Unicode characters from
    929930    :param str subs: character(s) to place into string in place of each
     
    10181019'''
    10191020# create a default space group object for P1; N.B. fails when building documentation
    1020 try: 
     1021try:
    10211022    P1SGData = G2spc.SpcGroup('P 1')[1] # data structure for default space group
    10221023except TypeError:
     
    10921093
    10931094    return phaseData
    1094                
     1095
    10951096def ReadCIF(URLorFile):
    10961097    '''Open a CIF, which may be specified as a file name or as a URL using PyCifRW
     
    11101111    #import urllib
    11111112    #ciffile = 'file:'+urllib.pathname2url(filename)
    1112    
     1113
    11131114    try:
    11141115        fp = open(URLorFile,'r')
     
    11251126    strikes twice in the same place.
    11261127
    1127     Note: this code assumes that the atom random Id (ranId) is the last 
     1128    Note: this code assumes that the atom random Id (ranId) is the last
    11281129    element each atom record.
    11291130
     
    11391140    # process phases and atoms
    11401141    PhaseIdLookup.clear()
    1141     PhaseRanIdLookup.clear()   
     1142    PhaseRanIdLookup.clear()
    11421143    AtomIdLookup.clear()
    11431144    AtomRanIdLookup.clear()
     
    11451146    for ph in Phases:
    11461147        cx,ct,cs,cia = Phases[ph]['General']['AtomPtrs']
    1147         ranId = Phases[ph]['ranId'] 
     1148        ranId = Phases[ph]['ranId']
    11481149        while ranId in PhaseRanIdLookup:
    11491150            # Found duplicate random Id! note and reassign
     
    12831284
    12841285def fmtVarDescr(varname):
    1285     '''Return a string with a more complete description for a GSAS-II variable 
     1286    '''Return a string with a more complete description for a GSAS-II variable
    12861287
    12871288    :param str varname: A full G2 variable name with 2 or 3 or 4
    12881289       colons (<p>:<h>:name[:<a>] or <p>::RBname:<r>:<t>])
    1289        
     1290
    12901291    :returns: a string with the description
    12911292    '''
     
    12941295
    12951296def VarDescr(varname):
    1296     '''Return two strings with a more complete description for a GSAS-II variable 
     1297    '''Return two strings with a more complete description for a GSAS-II variable
    12971298
    12981299    :param str name: A full G2 variable name with 2 or 3 or 4
    12991300       colons (<p>:<h>:name[:<a>] or <p>::RBname:<r>:<t>])
    1300        
     1301
    13011302    :returns: (loc,meaning) where loc describes what item the variable is mapped
    13021303      (phase, histogram, etc.) and meaning describes what the variable does.
    13031304    '''
    1304    
     1305
    13051306    # special handling for parameter names without a colons
    13061307    # for now, assume self-defining
    13071308    if varname.find(':') == -1:
    13081309        return "Global",varname
    1309        
     1310
    13101311    l = getVarDescr(varname)
    13111312    if not l:
     
    13501351            else: #modulation parm
    13511352                s = 'Atom %s wave %s in %s'%(LookupAtomLabel(l[0],l[3])[0],l[4],lbl)
    1352         elif l[3] is not None: # atom parameter, 
     1353        elif l[3] is not None: # atom parameter,
    13531354            lbl = ShortPhaseNames.get(l[0],'phase?')
    13541355            try:
     
    13781379
    13791380def getVarDescr(varname):
    1380     '''Return a short description for a GSAS-II variable 
     1381    '''Return a short description for a GSAS-II variable
    13811382
    13821383    :param str name: A full G2 variable name with 2 or 3 or 4
    13831384       colons (<p>:<h>:name[:<a1>][:<a2>])
    1384      
     1385
    13851386    :returns: a six element list as [`p`,`h`,`name`,`a1`,`a2`,`description`],
    13861387      where `p`, `h`, `a1`, `a2` are str values or `None`, for the phase number,
     
    14041405    l += [getDescr(l[2])]
    14051406    return l
    1406    
     1407
    14071408def CompileVarDesc():
    14081409    '''Set the values in the variable description lookup table (:attr:`VarDesc`)
     
    14241425    will match ``AU11``, ``AU23``,.. and `U11`, `U23` etc will be displayed
    14251426    in the value when used.
    1426    
     1427
    14271428    '''
    14281429    if reVarDesc: return # already done
     
    15381539
    15391540def getDescr(name):
    1540     '''Return a short description for a GSAS-II variable 
     1541    '''Return a short description for a GSAS-II variable
    15411542
    15421543    :param str name: The descriptive part of the variable name without colons (:)
    1543      
     1544
    15441545    :returns: a short description or None if not found
    15451546    '''
     
    15581559    fields) but only when there is more than one matching variable in the
    15591560    input variable list. So if the input is this::
    1560    
     1561
    15611562      varlist = ['0::AUiso:0', '0::AUiso:1', '1::AUiso:0']
    15621563
    15631564    then the output will be this::
    1564    
     1565
    15651566       wildList = ['*::AUiso:0', '0::AUiso:*']
    15661567
     
    15961597    '''returns a list of variable names from list varname
    15971598    that match wildcard name in varname
    1598    
     1599
    15991600    :param str varname: a G2 variable name containing a wildcard
    16001601      (such as \*::var)
    16011602    :param list varlist: the list of all variable names used in
    16021603      the current project
    1603     :returns: a list of matching GSAS-II variables (may be empty) 
     1604    :returns: a list of matching GSAS-II variables (may be empty)
    16041605    '''
    16051606    rexp = re.compile(varname.replace('*','[0-9]+'))
     
    16291630
    16301631    A :class:`G2VarObj` object can be created with a single parameter:
    1631    
     1632
    16321633    :param str/tuple varname: a single value can be used to create a :class:`G2VarObj`
    16331634      object. If a string, it must be of form "p:h:var" or "p:h:var:a", where
    16341635
    1635      * p is the phase number (which may be left blank or may be '*' to indicate all phases); 
    1636      * h is the histogram number (which may be left blank or may be '*' to indicate all histograms); 
     1636     * p is the phase number (which may be left blank or may be '*' to indicate all phases);
     1637     * h is the histogram number (which may be left blank or may be '*' to indicate all histograms);
    16371638     * a is the atom number (which may be left blank in which case the third colon is omitted).
    16381639       The atom number can be specified as '*' if a phase number is specified (not as '*').
     
    16501651    :param str varname: a single value can be used to create a :class:`G2VarObj`
    16511652    :param str/int atomnum: The number for the atom (or None or '*')
    1652    
     1653
    16531654    '''
    16541655    IDdict = {}
     
    16651666            self.phase,self.histogram,self.name,self.atom = args[0]
    16661667        elif len(args) == 1 and ':' in args[0]:
    1667             #parse a string 
     1668            #parse a string
    16681669            lst = args[0].split(':')
    16691670            if lst[0] == '*':
     
    16721673                    self.atom = lst[3]
    16731674                self.histogram = HistIdLookup.get(lst[1],[None,None])[1]
    1674             elif lst[1] == '*':           
     1675            elif lst[1] == '*':
    16751676                self.histogram = '*'
    16761677                self.phase = PhaseIdLookup.get(lst[0],[None,None])[1]
     
    17141715
    17151716    def varname(self):
    1716         '''Formats the GSAS-II variable name as a "traditional" GSAS-II variable 
     1717        '''Formats the GSAS-II variable name as a "traditional" GSAS-II variable
    17171718        string (p:h:<var>:a) or (p:h:<var>)
    17181719
     
    17411742        s = (ph + ":" + hist + ":" + str(self.name)) + a
    17421743        return s
    1743    
     1744
    17441745    def __repr__(self):
    17451746        '''Return the detailed contents of the object
     
    18101811    '''Defines a base class for the reading of input files (diffraction
    18111812    data, coordinates,...). See :ref:`Writing a Import Routine<Import_routines>`
    1812     for an explanation on how to use a subclass of this class. 
     1813    for an explanation on how to use a subclass of this class.
    18131814    '''
    18141815    class ImportException(Exception):
     
    18171818
    18181819        Good practice is that the Reader should define a value in self.errors that
    1819         tells the user some information about what is wrong with their file.         
     1820        tells the user some information about what is wrong with their file.
    18201821        '''
    18211822        pass
    1822    
     1823
    18231824    UseReader = True  # in __init__ set value of self.UseReader to False to skip use of current importer
    18241825    def __init__(self,formatName,longFormatName=None,
     
    18581859        self.readfilename = '?'
    18591860
    1860        
     1861
    18611862#    def Reader(self, filename, filepointer, ParentFrame=None, **unused):
    1862 #        '''This method must be supplied in the child class to read the file. 
     1863#        '''This method must be supplied in the child class to read the file.
    18631864#        if the read fails either return False or raise an Exception
    1864 #        preferably of type ImportException. 
     1865#        preferably of type ImportException.
    18651866#        '''
    18661867#        #start reading
     
    18861887        '''This routine will attempt to determine if the file can be read
    18871888        with the current format.
    1888         This will typically be overridden with a method that 
     1889        This will typically be overridden with a method that
    18891890        takes a quick scan of [some of]
    18901891        the file contents to do a "sanity" check if the file
    1891         appears to match the selected format. 
     1892        appears to match the selected format.
    18921893        '''
    18931894        #filepointer.seek(0) # rewind the file pointer
     
    19051906            line = l.strip()
    19061907            if len(line) == 0: # ignore blank lines
    1907                 continue 
     1908                continue
    19081909            elif line.startswith('#'): # ignore comments
    1909                 continue 
     1910                continue
    19101911            elif line.startswith('data_'): # on the right track, accept this file
    19111912                return True
     
    19141915                if all([ord(c) < 128 and ord(c) != 0 for c in str(l)]): # show only if ASCII
    19151916                    self.errors += '  '+str(l)
    1916                 else: 
     1917                else:
    19171918                    self.errors += '  (binary)'
    19181919                self.errors += '\n  Note: a CIF should only have blank lines or comments before'
    19191920                self.errors += '\n        a data_ statement begins a block.'
    1920                 return False 
     1921                return False
    19211922
    19221923######################################################################
     
    19251926
    19261927    Objects constructed that subclass this (in import/G2phase_*.py etc.) will be used
    1927     in :meth:`GSASIIdataGUI.GSASII.OnImportPhase`. 
     1928    in :meth:`GSASIIdataGUI.GSASII.OnImportPhase`.
    19281929    See :ref:`Writing a Import Routine<Import_Routines>`
    1929     for an explanation on how to use this class. 
     1930    for an explanation on how to use this class.
    19301931
    19311932    '''
     
    19491950
    19501951    See :ref:`Writing a Import Routine<Import_Routines>`
    1951     for an explanation on how to use import classes in general. The specifics 
     1952    for an explanation on how to use import classes in general. The specifics
    19521953    for reading a structure factor histogram require that
    19531954    the ``Reader()`` routine in the import
     
    19731974        for the contents of each row. Dict element 'FF'
    19741975        contains the form factor values for each element type; if this entry
    1975         is left as initialized (an empty list) it will be initialized as needed later. 
     1976        is left as initialized (an empty list) it will be initialized as needed later.
    19761977        '''
    19771978    def ReInitialize(self):
     
    19811982        self.Banks = []             #for multi bank data (usually TOF)
    19821983        self.RefDict = {'RefList':[],'FF':{},'Super':0}
    1983        
     1984
    19841985    def InitParameters(self):
    19851986        'initialize the instrument parameters structure'
     
    19961997            self.Parameters[0]['Type'] = [Type,Type]
    19971998        if Wave is not None:
    1998             self.Parameters[0]['Lam'] = [Wave,Wave]           
    1999                        
     1999            self.Parameters[0]['Lam'] = [Wave,Wave]
     2000
    20002001######################################################################
    20012002class ImportPowderData(ImportBaseclass):
     
    20032004
    20042005    Objects constructed that subclass this (in import/G2pwd_*.py etc.) will be used
    2005     in :meth:`GSASIIdataGUI.GSASII.OnImportPowder`. 
     2006    in :meth:`GSASIIdataGUI.GSASII.OnImportPowder`.
    20062007    See :ref:`Writing a Import Routine<Import_Routines>`
    2007     for an explanation on how to use this class. 
     2008    for an explanation on how to use this class.
    20082009    '''
    20092010    def __init__(self,formatName,longFormatName=None,
     
    20132014        self.clockWd = None  # used in TOF
    20142015        self.ReInitialize()
    2015        
     2016
    20162017    def ReInitialize(self):
    20172018        'Reinitialize the Reader to initial settings'
     
    20262027                np.array(yb), # calc. background (zero)
    20272028                np.array(yd), # obs-calc profiles
    2028         '''                           
     2029        '''
    20292030        self.comments = []
    20302031        self.idstring = ''
    20312032        self.Sample = SetDefaultSample() # default sample parameters
    2032         self.Controls = {}  # items to be placed in top-level Controls 
     2033        self.Controls = {}  # items to be placed in top-level Controls
    20332034        self.GSAS = None     # used in TOF
    20342035        self.repeat_instparm = True # Should a parm file be
    2035         #                             used for multiple histograms? 
     2036        #                             used for multiple histograms?
    20362037        self.instparm = None # name hint from file of instparm to use
    20372038        self.instfile = '' # full path name to instrument parameter file
     
    20472048    '''Defines a base class for the reading of files with small angle data.
    20482049    See :ref:`Writing a Import Routine<Import_Routines>`
    2049     for an explanation on how to use this class. 
     2050    for an explanation on how to use this class.
    20502051    '''
    20512052    def __init__(self,formatName,longFormatName=None,extensionlist=[],
    20522053        strictExtension=False,):
    2053            
     2054
    20542055        ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist,
    20552056            strictExtension)
    20562057        self.ReInitialize()
    2057        
     2058
    20582059    def ReInitialize(self):
    20592060        'Reinitialize the Reader to initial settings'
     
    20682069                np.array(yd), # obs-calc profiles
    20692070                np.array(yb), # preset bkg
    2070         '''                           
     2071        '''
    20712072        self.comments = []
    20722073        self.idstring = ''
     
    20812082    '''Defines a base class for the reading of files with reflectometry data.
    20822083    See :ref:`Writing a Import Routine<Import_Routines>`
    2083     for an explanation on how to use this class. 
     2084    for an explanation on how to use this class.
    20842085    '''
    20852086    def __init__(self,formatName,longFormatName=None,extensionlist=[],
    20862087        strictExtension=False,):
    2087            
     2088
    20882089        ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist,
    20892090            strictExtension)
    20902091        self.ReInitialize()
    2091        
     2092
    20922093    def ReInitialize(self):
    20932094        'Reinitialize the Reader to initial settings'
     
    21022103                np.array(yd), # obs-calc profiles
    21032104                np.array(yb), # preset bkg
    2104         '''                           
     2105        '''
    21052106        self.comments = []
    21062107        self.idstring = ''
     
    21152116    '''Defines a base class for the reading of files with PDF G(R) data.
    21162117    See :ref:`Writing a Import Routine<Import_Routines>`
    2117     for an explanation on how to use this class. 
     2118    for an explanation on how to use this class.
    21182119    '''
    21192120    def __init__(self,formatName,longFormatName=None,extensionlist=[],
    21202121        strictExtension=False,):
    2121            
     2122
    21222123        ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist,
    21232124            strictExtension)
    21242125        self.ReInitialize()
    2125        
     2126
    21262127    def ReInitialize(self):
    21272128        'Reinitialize the Reader to initial settings'
     
    21322133                np.array(x), # r-axis values
    21332134                np.array(y), # pdf g(r)
    2134         '''                           
     2135        '''
    21352136        self.comments = []
    21362137        self.idstring = ''
     
    21422143
    21432144    Images are read in only these places:
    2144    
     2145
    21452146      * Initial reading is typically done from a menu item
    21462147        with a call to :meth:`GSASIIdataGUI.GSASII.OnImportImage`
    21472148        which in turn calls :meth:`GSASIIdataGUI.GSASII.OnImportGeneric`. That calls
    21482149        methods :meth:`ExtensionValidator`, :meth:`ContentsValidator` and
    2149         :meth:`Reader`. This returns a list of reader objects for each read image. 
     2150        :meth:`Reader`. This returns a list of reader objects for each read image.
    21502151
    21512152      * Images are read alternatively in :func:`GSASIIIO.ReadImages`, which puts image info
     
    21582159    When reading an image, the ``Reader()`` routine in the ImportImage class
    21592160    should set:
    2160    
     2161
    21612162      * :attr:`Comments`: a list of strings (str),
    21622163      * :attr:`Npix`: the number of pixels in the image (int),
     
    21642165      * :attr:`Data`: a dict defining image parameters (dict). Within this dict the following
    21652166        data items are needed:
    2166        
     2167
    21672168         * 'pixelSize': size of each pixel in microns (such as ``[200,200]``.
    21682169         * 'wavelength': wavelength in Angstoms.
     
    21752176
    21762177    optional data items:
    2177    
     2178
    21782179      * :attr:`repeat`: set to True if there are additional images to
    21792180        read in the file, False otherwise
    21802181      * :attr:`repeatcount`: set to the number of the image.
    2181      
     2182
    21822183    Note that the above is initialized with :meth:`InitParameters`.
    21832184    (Also see :ref:`Writing a Import Routine<Import_Routines>`
     
    21892190            extensionlist,strictExtension)
    21902191        self.InitParameters()
    2191        
     2192
    21922193    def ReInitialize(self):
    21932194        'Reinitialize the Reader to initial settings -- not used at present'
    21942195        ImportBaseclass.ReInitialize(self)
    21952196        self.InitParameters()
    2196        
     2197
    21972198    def InitParameters(self):
    21982199        'initialize the instrument parameters structure'
     
    22122213            ParentFrame.ImageZ = self.Image   # store the image for plotting
    22132214            ParentFrame.oldImagefile = imagefile # save the name of the last image file read
    2214             ParentFrame.oldImageTag = imagetag   # save the tag of the last image file read           
     2215            ParentFrame.oldImageTag = imagetag   # save the tag of the last image file read
    22152216
    22162217#################################################################################################
     
    22272228    using :meth:`LoadExpression`. This contains only the minimum
    22282229    information that needs to be stored to save and load the expression
    2229     and how it is mapped to GSAS-II variables. 
     2230    and how it is mapped to GSAS-II variables.
    22302231    '''
    22312232    def __init__(self):
     
    22452246         * a value for to the parameter and
    22462247         * a flag to determine if the variable is refined.
    2247         ''' 
     2248        '''
    22482249        self.depVar = None
    22492250
     
    22642265        are actually in the parameter dictionary. This is checked when the
    22652266        computation for the expression is done in :meth:`SetupCalc`.
    2266        
     2267
    22672268        :param str expr: the expression
    22682269        :param list exprVarLst: parameter labels found in the expression
     
    23652366        '''Parse an expression and return a dict of called functions and
    23662367        the variables used in the expression. Returns None in case an error
    2367         is encountered. If packages are referenced in functions, they are loaded 
     2368        is encountered. If packages are referenced in functions, they are loaded
    23682369        and the functions are looked up into the modules global
    2369         workspace. 
    2370        
     2370        workspace.
     2371
    23712372        Note that no changes are made to the object other than
    23722373        saving an error message, so that this can be used for testing prior
    2373         to the save. 
     2374        to the save.
    23742375
    23752376        :returns: a list of used variables
     
    23882389            pkgdict = {}
    23892390            # no listed package, try in current namespace
    2390             if len(df) == 1: 
     2391            if len(df) == 1:
    23912392                try:
    23922393                    fxnobj = eval(f)
     
    24482449                for a, b in ast.iter_fields(node):
    24492450                    if isinstance(b, ast.AST):
    2450                         if a == 'func': 
     2451                        if a == 'func':
    24512452                            fxnlist += ['.'.join(ASTtransverse(b,True)[0])]
    24522453                            continue
     
    25032504    '''An object used to evaluate an expression from a :class:`ExpressionObj`
    25042505    object.
    2505    
     2506
    25062507    :param ExpressionObj exprObj: a :class:`~ExpressionObj` expression object with
    25072508      an expression string and mappings for the parameter labels in that object.
     
    25622563                parmsInList = False
    25632564            break
    2564            
     2565
    25652566        # set up the dicts needed to speed computations
    25662567        self.exprDict = {}
     
    26202621            if var in self.lblLookup:
    26212622                self.exprDict[self.lblLookup[var]] = parmDict[var]
    2622            
     2623
    26232624    def EvalExpression(self):
    26242625        '''Evaluate an expression. Note that the expression
     
    26532654            val = np.sum(val)
    26542655        return val
    2655        
     2656
    26562657class G2Exception(Exception):
    26572658    def __init__(self,msg):
     
    26692670        print(i.strip().rstrip())
    26702671    else:
    2671         print 70*'*'   
     2672        print 70*'*'
    26722673        for i in traceback.format_list(traceback.extract_stack()[:-1]): print(i.strip().rstrip())
    2673         print 70*'*'   
    2674                
     2674        print 70*'*'
     2675
    26752676def CreatePDFitems(G2frame,PWDRtree,ElList,Qlimits,numAtm=1,FltBkg=0,PDFnames=[]):
    26762677    '''Create and initialize a new set of PDF tree entries
     
    26832684    :param float FltBkg: flat background value
    26842685    :param list PDFnames: previously used PDF names
    2685    
     2686
    26862687    :returns: the Id of the newly created PDF entry
    26872688    '''
     
    27042705    G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='PDF Peaks'),
    27052706        {'Limits':[1.,5.],'Background':[2,[0.,-0.2*np.pi],False],'Peaks':[]})
    2706     return Id       
     2707    return Id
    27072708
    27082709
     
    27412742    calcobj2.SetupCalc(parmDict2)
    27422743    showEQ(calcobj2)
    2743    
     2744
    27442745    parmDict1 = {'0::Afrac:0':1.0, '0::Afrac:1': 1.0}
    27452746    print '\nDict = ',parmDict1
  • trunk/GSASIIplot.py

    r3013 r3023  
    1818import numpy.ma as ma
    1919import numpy.linalg as nl
    20 import wx
    21 import wx.aui
    22 import wx.glcanvas
    23 import matplotlib as mpl
    24 import matplotlib.collections as mplC
    25 import mpl_toolkits.mplot3d.axes3d as mp3d
     20# Don't depend on wx/matplotlib for scriptable
     21try:
     22    import wx
     23    import wx.aui
     24    import wx.glcanvas
     25    import matplotlib as mpl
     26    import matplotlib.collections as mplC
     27    import mpl_toolkits.mplot3d.axes3d as mp3d
     28except ImportError:
     29    pass
    2630import GSASIIpath
    2731Clip_on = GSASIIpath.GetConfigValue('Clip_on',True)
  • trunk/GSASIIpwdGUI.py

    r3000 r3023  
    1818import sys
    1919import os.path
    20 import wx
    21 import wx.grid as wg
     20# Don't depend on graphics for scriptable
     21try:
     22    import wx
     23    import wx.grid as wg
     24except ImportError:
     25    pass
    2226import numpy as np
    2327import numpy.ma as ma
  • trunk/GSASIIscriptable.py

    r3022 r3023  
    153153    '''
    154154    file = open(ProjFile,'wb')
    155     # print('save to file: {}'.format(ProjFile))
    156155    try:
    157156        for name in nameList:
     
    164163    finally:
    165164        file.close()
    166     # print('project save successful')
    167165
    168166def ImportPowder(reader,filename):
     
    888886
    889887    def refine(self, newfile=None, printFile=None, makeBack=False):
     888        # TODO migrate to RefineCore
     889        # G2strMain.RefineCore(Controls,Histograms,Phases,restraintDict,rigidbodyDict,parmDict,varyList,
     890        #      calcControls,pawleyLookup,ifPrint,printFile,dlg)
    890891        # index_ids will automatically save the project
    891892        self.index_ids()
  • trunk/GSASIIstrMain.py

    r3007 r3023  
    3737acosd = lambda x: 180.*np.arccos(x)/np.pi
    3838atan2d = lambda y,x: 180.*np.arctan2(y,x)/np.pi
    39    
     39
    4040ateln2 = 8.0*math.log(2.0)
    4141DEBUG = True
     
    4343def RefineCore(Controls,Histograms,Phases,restraintDict,rigidbodyDict,parmDict,varyList,
    4444    calcControls,pawleyLookup,ifPrint,printFile,dlg):
    45     'Core optimization routines, shared between SeqRefine and Refine'
     45    '''Core optimization routines, shared between SeqRefine and Refine
     46
     47    :returns: 5-tuple of ifOk (bool), Rvals (dict), result, covMatrix, sig
     48    '''
    4649#    print 'current',varyList
    4750#    for item in parmDict: print item,parmDict[item] ######### show dict just before refinement
     
    5356        # test code to compute GOF and save for external repeat
    5457        #args = ([Histograms,Phases,restraintDict,rigidbodyDict],parmDict,varyList,calcControls,pawleyLookup,dlg)
    55         #print '*** before fit chi**2',np.sum(G2stMth.errRefine(values,*args)**2)           
     58        #print '*** before fit chi**2',np.sum(G2stMth.errRefine(values,*args)**2)
    5659        #fl = open('beforeFit.cpickle','wb')
    5760        #import cPickle
     
    6265        Xtol = Controls['SVDtol']
    6366        Factor = Controls['shift factor']
    64         if 'Jacobian' in Controls['deriv type']:           
     67        if 'Jacobian' in Controls['deriv type']:
    6568            result = so.leastsq(G2stMth.errRefine,values,Dfun=G2stMth.dervRefine,full_output=True,
    6669                ftol=Ftol,col_deriv=True,factor=Factor,
     
    124127                    if val:
    125128                        print 'Removing parameter: ',varyList[num-i]
    126                         del(varyList[num-i])                   
     129                        del(varyList[num-i])
    127130            else:
    128131                Ipvt = result[2]['ipvt']
     
    139142    import pytexture as ptx
    140143    ptx.pyqlmninit()            #initialize fortran arrays for spherical harmonics
    141    
     144
    142145    printFile = open(ospath.splitext(GPXfile)[0]+'.lst','w')
    143146    G2stIO.ShowBanner(printFile)
    144147    varyList = []
    145148    parmDict = {}
    146     G2mv.InitVars()   
     149    G2mv.InitVars()
    147150    Controls = G2stIO.GetControls(GPXfile)
    148151    G2stIO.ShowControls(Controls,printFile)
    149152    calcControls = {}
    150     calcControls.update(Controls)           
     153    calcControls.update(Controls)
    151154    constrDict,fixedList = G2stIO.GetConstraints(GPXfile)
    152155    restraintDict = G2stIO.GetRestraints(GPXfile)
     
    199202        return False,' Constraint error'
    200203#    print G2mv.VarRemapShow(varyList)
    201    
     204
    202205    ifPrint = True
    203206    print >>printFile,'\n Refinement results:'
     
    229232        printFile.close()
    230233        return False,Msg.msg
    231    
     234
    232235#for testing purposes!!!
    233236    if DEBUG:
     
    245248    if dlg:
    246249        return True,Rvals
    247        
     250
    248251def phaseCheck(phaseVary,Phases,histogram):
    249252    '''
    250     Removes unused parameters from phase varylist if phase not in histogram 
     253    Removes unused parameters from phase varylist if phase not in histogram
    251254    '''
    252255    pIds = []
     
    263266    import pytexture as ptx
    264267    ptx.pyqlmninit()            #initialize fortran arrays for spherical harmonics
    265    
     268
    266269    printFile = open(ospath.splitext(GPXfile)[0]+'.lst','w')
    267270    print 'Starting Sequential Refinement'
    268271    G2stIO.ShowBanner(printFile)
    269272    Controls = G2stIO.GetControls(GPXfile)
    270     G2stIO.ShowControls(Controls,printFile,SeqRef=True)           
     273    G2stIO.ShowControls(Controls,printFile,SeqRef=True)
    271274    restraintDict = G2stIO.GetRestraints(GPXfile)
    272275    Histograms,Phases = G2stIO.GetUsedHistogramsAndPhases(GPXfile)
     
    351354        # do constraint processing
    352355        #reload(G2mv) # debug
    353         G2mv.InitVars()   
     356        G2mv.InitVars()
    354357        constrDict,fixedList = G2stIO.GetConstraints(GPXfile)
    355358        varyListStart = tuple(varyList) # save the original varyList before dependent vars are removed
     
    404407                print(line[:-2])
    405408            firstVaryList = newVaryList
    406        
     409
    407410        ifPrint = False
    408411        print >>printFile,'\n Refinement results for histogram: v'+histogram
     
    413416            if PlotFunction:
    414417                PlotFunction(G2frame,Histo[histogram]['Data'],histogram)
    415    
     418
    416419            print '  wR = %7.2f%%, chi**2 = %12.6g, reduced chi**2 = %6.2f, last delta chi = %.4f'%(
    417420                Rvals['Rwp'],Rvals['chisq'],Rvals['GOF']**2,Rvals['DelChi2'])
     
    420423            # the uncertainties for dependent constrained parms into the esd dict
    421424            sigDict.update(G2mv.ComputeDepESD(covMatrix,varyList,parmDict))
    422    
     425
    423426            # a dict with values & esds for dependent (constrained) parameters - avoid extraneous holds
    424427            depParmDict = {i:(parmDict[i],sigDict[i]) for i in varyListStart if i in sigDict and i not in varyList}
     
    441444            NewparmDict = {}
    442445            # make dict of varied parameters in current histogram, renamed to
    443             # next histogram, for use in next refinement. 
     446            # next histogram, for use in next refinement.
    444447            if Controls['Copy2Next'] and ihst < len(histNames)-1:
    445448                hId = Histo[histogram]['hId'] # current histogram
     
    470473    :param dict DisAglCtls: contains distance/angle radii usually defined using
    471474       :func:`GSASIIctrlGUI.DisAglDialog`
    472     :param dict DisAglData: contains phase data: 
     475    :param dict DisAglData: contains phase data:
    473476       Items 'OrigAtoms' and 'TargAtoms' contain the atoms to be used
    474477       for distance/angle origins and atoms to be used as targets.
     
    481484      **DistArray** is a dict keyed by the origin atom number where the value is a list
    482485      of distance entries. The value for each distance is a list containing:
    483      
     486
    484487        0) the target atom number (int);
    485488        1) the unit cell offsets added to x,y & z (tuple of int values)
     
    497500
    498501      The AngArray distance reference items refer directly to the index of the items in the
    499       DistArray item for the list of distances for the central atom. 
     502      DistArray item for the list of distances for the central atom.
    500503    '''
    501504    import numpy.ma as ma
    502    
     505
    503506    SGData = DisAglData['SGData']
    504507    Cell = DisAglData['Cell']
    505    
     508
    506509    Amat,Bmat = G2lat.cell2AB(Cell[:6])
    507510    covData = {}
    508     if 'covData' in DisAglData:   
     511    if 'covData' in DisAglData:
    509512        covData = DisAglData['covData']
    510513        covMatrix = covData['covMatrix']
    511514        varyList = covData['varyList']
    512515        pfx = str(DisAglData['pId'])+'::'
    513        
     516
    514517    Factor = DisAglCtls['Factors']
    515518    Radii = dict(zip(DisAglCtls['AtomTypes'],zip(DisAglCtls['BondRadii'],DisAglCtls['AngleRadii'])))
     
    587590    :param dict DisAglCtls: contains distance/angle radii usually defined using
    588591       :func:`GSASIIctrlGUI.DisAglDialog`
    589     :param dict DisAglData: contains phase data: 
     592    :param dict DisAglData: contains phase data:
    590593       Items 'OrigAtoms' and 'TargAtoms' contain the atoms to be used
    591594       for distance/angle origins and atoms to be used as targets.
    592595       Item 'SGData' has the space group information (see :ref:`Space Group object<SGData_table>`)
    593     :param file out: file object for output. Defaults to sys.stdout.   
     596    :param file out: file object for output. Defaults to sys.stdout.
    594597    '''
    595598    def MyPrint(s):
    596599        out.write(s+'\n')
    597600        # print(s,file=out) # use in Python 3
    598    
     601
    599602    def ShowBanner(name):
    600603        MyPrint(80*'*')
     
    612615            else:
    613616                line = ' %s %s'%(item.ljust(30),SGtable[2*i+1].ljust(30))
    614             MyPrint(line)   
     617            MyPrint(line)
    615618    else:
    616619        MyPrint(' ( 1)    %s'%(SGtable[0])) #triclinic case
    617620    Cell = DisAglData['Cell']
    618    
     621
    619622    Amat,Bmat = G2lat.cell2AB(Cell[:6])
    620623    covData = {}
    621     if 'covData' in DisAglData:   
     624    if 'covData' in DisAglData:
    622625        covData = DisAglData['covData']
    623626        pfx = str(DisAglData['pId'])+'::'
     
    628631        line = '\n Unit cell:'
    629632        for name,vals in zip(names,valEsd):
    630             line += name+vals 
     633            line += name+vals
    631634        MyPrint(line)
    632     else: 
     635    else:
    633636        MyPrint('\n Unit cell: a = '+('%.5f'%Cell[0])+' b = '+('%.5f'%Cell[1])+' c = '+('%.5f'%Cell[2])+
    634637            ' alpha = '+('%.3f'%Cell[3])+' beta = '+('%.3f'%Cell[4])+' gamma = '+
     
    677680    SGData = DATData['SGData']
    678681    Cell = DATData['Cell']
    679    
     682
    680683    Amat,Bmat = G2lat.cell2AB(Cell[:6])
    681684    covData = {}
    682685    pfx = ''
    683     if 'covData' in DATData:   
     686    if 'covData' in DATData:
    684687        covData = DATData['covData']
    685688        pfx = str(DATData['pId'])+'::'
     
    689692        symop = atom[-1].split('+')
    690693        if len(symop) == 1:
    691             symop.append('0,0,0')       
     694            symop.append('0,0,0')
    692695        symop[0] = int(symop[0])
    693696        symop[1] = eval(symop[1])
     
    713716        Dist,sig = G2mth.GetDATSig(Oatoms,Datoms,Amat,SGData,covData)
    714717        print ' Distance in '+DATData['Name']+' for atom sequence: ',atmSeq,'=',G2mth.ValEsd(Dist,sig)
    715                
     718
    716719def BestPlane(PlaneData):
    717720    'Needs a doc string'
     
    724727    ShowBanner(PlaneData['Name'])
    725728
    726     Cell = PlaneData['Cell']   
    727     Amat,Bmat = G2lat.cell2AB(Cell[:6])       
     729    Cell = PlaneData['Cell']
     730    Amat,Bmat = G2lat.cell2AB(Cell[:6])
    728731    Atoms = PlaneData['Atoms']
    729732    sumXYZ = np.zeros(3)
     
    750753    for i,xyz in enumerate(XYZ):
    751754        print ' %6s%10.3f%10.3f%10.3f'%(Atoms[i][1].ljust(6),xyz[0],xyz[1],xyz[2])
    752     print '\n Best plane RMS X =%8.3f, Y =%8.3f, Z =%8.3f'%(Evec[Order[2]],Evec[Order[1]],Evec[Order[0]])   
    753            
     755    print '\n Best plane RMS X =%8.3f, Y =%8.3f, Z =%8.3f'%(Evec[Order[2]],Evec[Order[1]],Evec[Order[0]])
     756
    754757def main():
    755758    'Needs a doc string'
     
    766769        exit()
    767770    print("Done. Execution time {:.2f} sec.".format(time.time()-starttime))
    768          
     771
    769772if __name__ == '__main__':
    770773    main()
  • trunk/imports/G2phase.py

    r2858 r3023  
    2222import random as ran
    2323import numpy as np
    24 import wx
     24try:
     25    import wx
     26except ImportError:
     27    wx = None
    2528import GSASIIobj as G2obj
    2629import GSASIIspc as G2spc
Note: See TracChangeset for help on using the changeset viewer.