Changeset 3023
- Timestamp:
- Aug 23, 2017 3:05:51 PM (6 years ago)
- Location:
- trunk
- Files:
-
- 10 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/GSASIIIO.py
r3000 r3023 23 23 Copyright: 2008, Robert B. Von Dreele (Argonne National Laboratory) 24 24 """ 25 import wx 25 # If this is being used for GSASIIscriptable, don't depend on wx 26 try: 27 import wx 28 except ImportError: 29 class Placeholder(object): 30 def __init__(self): 31 self.Dialog = object 32 wx = Placeholder() 26 33 import math 27 34 import numpy as np … … 33 40 import GSASIIpath 34 41 GSASIIpath.SetVersionNumber("$Revision$") 35 import GSASIIdataGUI as G2gd 42 try: 43 import GSASIIdataGUI as G2gd 44 except ImportError: 45 pass 36 46 import GSASIIobj as G2obj 37 47 import GSASIIlattice as G2lat 38 48 import GSASIImath as G2mth 39 import GSASIIpwdGUI as G2pdG 40 import GSASIIimgGUI as G2imG 49 try: 50 import GSASIIpwdGUI as G2pdG 51 import GSASIIimgGUI as G2imG 52 except ImportError: 53 pass 41 54 import GSASIIimage as G2img 42 55 import GSASIIElem as G2el 43 56 import GSASIIstrIO as G2stIO 44 57 import GSASIImapvars as G2mv 45 import GSASIIctrlGUI as G2G 58 try: 59 import GSASIIctrlGUI as G2G 60 except ImportError: 61 pass 46 62 import os 47 63 import os.path as ospath -
trunk/GSASIIctrlGUI.py
r3013 r3023 17 17 import os 18 18 import 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 19 try: 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 27 except 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()) 25 43 import time 26 44 import copy 27 import wx.html # could postpone this for quicker startup28 45 import webbrowser # could postpone this for quicker startup 29 46 … … 39 56 WHITE = (255,255,255) 40 57 DULL_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 59 try: 60 VERY_LIGHT_GREY = wx.Colour(235,235,235) 61 WACV = wx.ALIGN_CENTER_VERTICAL 62 except: 63 # Don't depend on GUI 64 pass 43 65 44 66 ################################################################################ -
trunk/GSASIIdataGUI.py
r3018 r3023 28 28 import numpy.ma as ma 29 29 import matplotlib as mpl 30 import OpenGL as ogl 30 try: 31 import OpenGL as ogl 32 except ImportError: 33 pass 31 34 import scipy as sp 32 35 import 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 36 try: 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 42 except ImportError: 43 pass 38 44 import GSASIIpath 39 45 GSASIIpath.SetVersionNumber("$Revision$") -
trunk/GSASIIlog.py
r3000 r3023 15 15 such as menu item, tree item, button press, value change and so on. 16 16 ''' 17 import wx 17 try: 18 import wx 19 except ImportError: 20 pass 18 21 import GSASIIdataGUI as G2gd 19 22 import GSASIIpath -
trunk/GSASIIobj.py
r3000 r3023 14 14 15 15 This module defines and/or documents the data structures used in GSAS-II, as well 16 as provides misc. support routines. 16 as provides misc. support routines. 17 17 18 18 Constraints Tree Item … … 43 43 key explanation 44 44 ========== ==================================================== 45 Hist This specifies a list of constraints on 45 Hist This specifies a list of constraints on 46 46 histogram-related parameters, 47 47 which will be of form :h:<var>:n. 48 48 HAP This specifies a list of constraints on parameters 49 49 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. 51 51 Phase This specifies a list of constraints on phase 52 52 parameters, … … 67 67 [[<mult1>, <var1>], [<mult2>, <var2>],..., <fixedval>, <varyflag>, <constype>] 68 68 69 Where the variable pair list item containing two values [<mult>, <var>], where: 69 Where the variable pair list item containing two values [<mult>, <var>], where: 70 70 71 71 * <mult> is a multiplier for the constraint (float) … … 86 86 * 'e' defines a set of equivalent variables. Only the first variable is refined (if the 87 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. 88 are generated from that variable, using the appropriate multipliers. 89 89 * 'c' defines a constraint equation of form, 90 90 :math:`m_1 \\times var_1 + m_2 \\times var_2 + ... = c` … … 93 93 constraint and the mult value is ignored. 94 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 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 98 :math:`newvar = m_1 \\times var_1 + m_2 \\times var_2 + ...` 99 99 … … 124 124 (list of float values, length N, 125 125 ordered to match varyList) 126 varyList \ List of directly refined variables 126 varyList \ List of directly refined variables 127 127 (list of str values, length N) 128 newAtomDict \ dict with atom position values computed in 128 newAtomDict \ dict with atom position values computed in 129 129 :func:`GSASIIstrMath.ApplyXYZshifts` (dict) 130 130 Rvals \ R-factors, GOF, Marquardt value for last … … 171 171 \ Type 'nuclear' or 'macromolecular' for now (str) 172 172 \ Map dict of map parameters 173 \ SH Texture dict of spherical harmonic preferred orientation 173 \ SH Texture dict of spherical harmonic preferred orientation 174 174 parameters 175 175 \ Isotope dict of isotopes for each atom type 176 176 \ Isotopes dict of scattering lengths for each isotope 177 combination for each element in phase 177 combination for each element in phase 178 178 \ Name phase name (str) 179 179 \ SGData Space group details as a :ref:`space group (SGData) object <SGData_table>` … … 181 181 \ Pawley neg wt Restraint value for negative Pawley intensities 182 182 (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 185 185 'Preferred orientation') for powder data (str) 186 186 \ Mass Mass of unit cell contents in g/mol 187 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 188 \ Z dict of atomic numbers for each atom type 189 \ vdWRadii dict of van der Waals radii for each atom type 190 190 \ Color Colors for atoms (list of (r,b,g) triplets) 191 191 \ AtomTypes List of atom types … … 193 193 \ doPawley Flag for Pawley intensity extraction (bool) 194 194 \ 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 196 196 extraction (float) 197 \ BondRadii Default radius for each atom used to compute 197 \ BondRadii Default radius for each atom used to compute 198 198 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 200 200 interatomic angles (list of floats) 201 201 \ DisAglCtls Dict with distance/angle search controls, … … 226 226 \ selectedAtoms List of selected atoms (list of int values) 227 227 \ showRigidBodies Flag to highlight rigid body placement 228 \ sizeH Size ratio for H atoms (float) 228 \ sizeH Size ratio for H atoms (float) 229 229 \ bondRadius Size of binds in A (float) 230 230 \ atomPtrs positions of x, type, site sym, ADP flag in Draw Atoms (list) 231 231 \ viewPoint list of lists. First item in list is [x,y,z] 232 232 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 234 234 atom number viewed (may be [0,0]) 235 235 \ showHydrogen Flag to control plotting of H atoms. … … 238 238 ellipsoids in % (float). 239 239 \ vdwScale Multiplier of van der Waals radius for 240 display of vdW spheres. 240 display of vdW spheres. 241 241 \ Atoms A list of lists with an entry for each atom 242 242 that is plotted. … … 295 295 \ newLeBail Whether to perform a new LeBail extraction 296 296 MCSA \ Monte-Carlo simulated annealing parameters (dict) 297 \ 297 \ 298 298 ========== =============== ==================================================== 299 299 … … 306 306 single: Rigid Body Data description 307 307 single: Data object descriptions; Rigid Body Data 308 309 Rigid body descriptions are available for two types of rigid bodies: 'Vector' 308 309 Rigid body descriptions are available for two types of rigid bodies: 'Vector' 310 310 and 'Residue'. Vector rigid bodies are developed by a sequence of translations each 311 311 with a refinable magnitude and Residue rigid bodies are described as Cartesian coordinates … … 322 322 \ VectMag vector magnitudes in A (list) 323 323 \ 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 325 325 definition, use center of atoms flag (list of 3 int & 1 bool) 326 326 \ VectRef refinement flags for VectMag values (list of bool) … … 334 334 \ rbTypes Atom types for each atom in rigid body (list of str) 335 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 336 \ rbRef 3 assigned reference atom nos. in rigid body for origin 337 337 definition, use center of atoms flag (list of 3 int & 1 bool) 338 338 \ rbSeq Orig,Piv,angle,Riding (list): definition of internal rigid body … … 346 346 ========== =============== ==================================================== 347 347 348 Space Group Objects 348 Space Group Objects 349 349 ------------------- 350 350 … … 355 355 single: Data object descriptions; Space Group Data 356 356 357 Space groups are interpreted by :func:`GSASIIspc.SpcGroup` 358 and the information is placed in a SGdata object 357 Space groups are interpreted by :func:`GSASIIspc.SpcGroup` 358 and the information is placed in a SGdata object 359 359 which is a dict with these keys: 360 360 … … 391 391 SGPolax Axes for space group polarity. Will be one of 392 392 '', '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 394 394 '111' is used (P 1, and ?). 395 395 ========== ==================================================== … … 401 401 single: Data object descriptions; Superspace Group Data 402 402 403 Superspace groups [3+1] are interpreted by :func:`GSASIIspc.SSpcGroup` 404 and the information is placed in a SSGdata object 403 Superspace groups [3+1] are interpreted by :func:`GSASIIspc.SSpcGroup` 404 and the information is placed in a SSGdata object 405 405 which is a dict with these keys: 406 406 … … 429 429 If ``phasedict`` points to the phase information in the data tree, then 430 430 atoms 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 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 434 434 always present; additional ones for macromolecular phases are marked 'mm' 435 435 … … 446 446 ct+1 refinement flags; combination of 'F', 'X', 'U' (str) 447 447 cx,cx+1,cx+2 the x,y and z coordinates (3 floats) 448 cx+3 site occupancy (float) 448 449 cs site symmetry (str) 449 450 cs+1 site multiplicity (int) … … 467 468 If ``phasedict`` points to the phase information in the data tree, then 468 469 drawing 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 470 471 are four pointers, ``cx,ct,cs,ci = phasedict['Drawing']['AtomPtrs']``, 471 which define locations in the atom record, as shown below. Items shown are 472 which define locations in the atom record, as shown below. Items shown are 472 473 always present; additional ones for macromolecular phases are marked 'mm' 473 474 … … 517 518 key sub-key explanation 518 519 ====================== =============== ==================================================== 519 Comments \ Text strings extracted from the original powder 520 data header. These cannot be changed by the user; 520 Comments \ Text strings extracted from the original powder 521 data header. These cannot be changed by the user; 521 522 it may be empty. 522 523 Limits \ A list of two two element lists, as [[Ld,Hd],[L,H]] 523 524 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 525 526 where H and Hd are the current and default highest 526 527 two-theta value to be used. … … 546 547 Angstrom, when an alpha1, alpha2 547 548 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]: 550 551 * 'PXC' for constant wavelength x-ray 551 552 * 'PNC' for constant wavelength neutron … … 578 579 specifies if the value is refined, otherwise 579 580 the value is a float unless otherwise noted. 580 \ Scale The histogram scale factor (refinable) 581 \ Scale The histogram scale factor (refinable) 581 582 \ Absorption The sample absorption coefficient as 582 583 :math:`\\mu r` where r is the radius 583 584 (refinable). Only valid for Debye-Scherrer geometry. 584 585 \ 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) 589 590 \ DisplaceX, Sample displacement from goniometer center 590 591 DisplaceY where Y is along the beam direction and … … 597 598 a CIF (str). 598 599 \ 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. 601 602 Pressure, 602 603 Voltage … … 616 617 Debye diffuse terms and background peaks. 617 618 (TODO: this needs to be expanded.) 618 Data \ The data consist of a list of 6 np.arrays 619 Data \ The data consist of a list of 6 np.arrays 619 620 containing in order: 620 621 … … 635 636 single: Powder reflection object description 636 637 single: Data object descriptions; Powder Reflections 637 638 638 639 For every phase in a histogram, the ``Reflection Lists`` value is a dict 639 640 one element of which is `'RefList'`, which is a np.array containing … … 653 654 10 reflection phase, in degrees 654 655 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 656 657 ========== ==================================================== 657 658 … … 680 681 key sub-key explanation 681 682 ====================== =============== ==================================================== 682 Data \ A dict that contains the 683 Data \ A dict that contains the 683 684 reflection table, 684 685 as described in the … … 694 695 values are floats unless otherwise noted. 695 696 \ Lam Specifies a wavelength in Angstroms (two floats) 696 \ Type Histogram type (two str values): 697 \ Type Histogram type (two str values): 697 698 * 'SXC' for constant wavelength x-ray 698 699 * 'SNC' for constant wavelength neutron … … 722 723 single: Single Crystal reflection object description 723 724 single: Data object descriptions; Single Crystal Reflections 724 725 725 726 For every single crystal a histogram, the ``'Data'`` item contains 726 727 the structure factors as an np.array in item `'RefList'`. … … 752 753 image: Image data object description 753 754 image: Image object descriptions 754 755 755 756 Every 2-dimensional image is stored in the GSAS-II data tree 756 757 with a top-level entry named beginning with the string "IMG ". The 757 image data are directly associated with that tree item and there 758 image data are directly associated with that tree item and there 758 759 are a series of children to that item. The routines :func:`GSASIIdataGUI.GSASII.GetUsedHistogramsAndPhasesfromTree` 759 760 and :func:`GSASIIstrIO.GetUsedHistogramsAndPhases` will … … 767 768 key sub-key explanation 768 769 ====================== ====================== ==================================================== 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 770 Comments \ 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. 773 Image Controls azmthOff (float) The offset to be applied to an azimuthal 774 value. Accomodates 775 detector orientations other than with the detector 775 776 X-axis 776 777 horizontal. 777 778 \ 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 779 780 the integrated image. NB: value < 0 for subtraction. 780 781 \ 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` 782 783 and UserCalibrants.py (supplied by user). 783 784 \ calibdmin (float) The minimum d-spacing used during the last calibration run. … … 785 786 calibration run. 786 787 \ 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. 789 790 \ centerAzm (bool) If True then the azimuth reported for the integrated slice 790 791 of the image is at the center line otherwise it is at the leading edge. 791 792 \ 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. 794 795 \ DetDepth (float) Coefficient for penetration correction to distance; accounts for diffraction 795 796 ring offset at higher angles. Optionally determined by calibration. … … 797 798 \ distance (float) The distance (mm) from sample to detector plane. 798 799 \ 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 800 801 rotation of the ellipse minor axis from the x-axis, and radii are the minor & major 801 802 radii of the ellipse. If radii[0] is negative then parameters describe a hyperbola. Color … … 803 804 \ edgemin (float) Not used; parameter in EdgeFinder code. 804 805 \ 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. 806 807 Required for texture calculations. 807 808 \ invert_x (bool) If True display the image with the x-axis inverted. … … 812 813 intensities obtained during integration. 813 814 \ 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. 815 816 \ pixelSize (list:ints) The X,Y dimensions (microns) of each pixel. 816 817 \ pixLimit (int) A box in the image with 2*pixLimit+1 edges is searched to find the maximum. 817 818 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`. 819 820 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 821 822 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 823 824 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 825 826 selected by the user, 826 827 \ 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. 829 830 \ SampleShape (str) Currently only 'Cylinder'. Sample shape for Debye-Scherrer experiments; used for absorption 830 831 calculations. … … 832 833 to cause correction to be applied. 833 834 \ 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. 835 836 \ showLines (bool) If True then isplay the integration limits to be used. 836 837 \ size (list:int) The number of pixels on the image x & y axes … … 838 839 \ tilt (float) The angle the detector normal makes with the incident beam; range -90 to 90. 839 840 \ wavelength (float) Tha radiation wavelength (Angstroms) as entered by the user (or someday obtained from the image header). 840 841 841 842 Masks Arcs (list: lists) Each entry [2-theta,[azimuth[0],azimuth[1]],thickness] describes an arc mask 842 843 to be excluded from integration … … 850 851 to be excluded from integration. 851 852 \ 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 854 855 Stress/Strain Sample phi (float) Sample rotation about vertical axis. 855 856 \ Sample z (float) Sample translation from the calibration sample position (for Sample phi = 0) 856 857 These will be restricted by space group symmetry; result of strain fit refinement. 857 858 \ 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 859 860 and are used to determine the strain tensor. 860 861 The dictionary items are: … … 868 869 'ImtaObs': (list: lists) [[d],[azm]] transformed via detector calibration from ImxyObs. 869 870 'ImtaCalc': (list: lists [[d],[azm]] calculated d-spacing & azimuth from fit. 870 871 871 872 ====================== ====================== ==================================================== 872 873 … … 880 881 881 882 The 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>). 883 The dictionary keys are the name of the parameter (<phase>:<hist>:<name>:<atom>). 883 884 It is prepared in two ways. When loaded from the tree 884 885 (in :meth:`GSASIIdataGUI.GSASII.MakeLSParmDict` and 885 :meth:`GSASIIIO.ExportBaseclass.loadParmDict`), 886 :meth:`GSASIIIO.ExportBaseclass.loadParmDict`), 886 887 the values are lists with two elements: ``[value, refine flag]`` 887 888 888 889 When loaded from the GPX file (in 889 890 :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). 891 dict is the actual parameter value (usually a float, but sometimes a 892 letter or string flag value (such as I or A for iso/anisotropic). 892 893 893 894 … … 925 926 def StripUnicode(string,subs='.'): 926 927 '''Strip non-ASCII characters from strings 927 928 928 929 :param str string: string to strip Unicode characters from 929 930 :param str subs: character(s) to place into string in place of each … … 1018 1019 ''' 1019 1020 # create a default space group object for P1; N.B. fails when building documentation 1020 try: 1021 try: 1021 1022 P1SGData = G2spc.SpcGroup('P 1')[1] # data structure for default space group 1022 1023 except TypeError: … … 1092 1093 1093 1094 return phaseData 1094 1095 1095 1096 def ReadCIF(URLorFile): 1096 1097 '''Open a CIF, which may be specified as a file name or as a URL using PyCifRW … … 1110 1111 #import urllib 1111 1112 #ciffile = 'file:'+urllib.pathname2url(filename) 1112 1113 1113 1114 try: 1114 1115 fp = open(URLorFile,'r') … … 1125 1126 strikes twice in the same place. 1126 1127 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 1128 1129 element each atom record. 1129 1130 … … 1139 1140 # process phases and atoms 1140 1141 PhaseIdLookup.clear() 1141 PhaseRanIdLookup.clear() 1142 PhaseRanIdLookup.clear() 1142 1143 AtomIdLookup.clear() 1143 1144 AtomRanIdLookup.clear() … … 1145 1146 for ph in Phases: 1146 1147 cx,ct,cs,cia = Phases[ph]['General']['AtomPtrs'] 1147 ranId = Phases[ph]['ranId'] 1148 ranId = Phases[ph]['ranId'] 1148 1149 while ranId in PhaseRanIdLookup: 1149 1150 # Found duplicate random Id! note and reassign … … 1283 1284 1284 1285 def 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 1286 1287 1287 1288 :param str varname: A full G2 variable name with 2 or 3 or 4 1288 1289 colons (<p>:<h>:name[:<a>] or <p>::RBname:<r>:<t>]) 1289 1290 1290 1291 :returns: a string with the description 1291 1292 ''' … … 1294 1295 1295 1296 def 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 1297 1298 1298 1299 :param str name: A full G2 variable name with 2 or 3 or 4 1299 1300 colons (<p>:<h>:name[:<a>] or <p>::RBname:<r>:<t>]) 1300 1301 1301 1302 :returns: (loc,meaning) where loc describes what item the variable is mapped 1302 1303 (phase, histogram, etc.) and meaning describes what the variable does. 1303 1304 ''' 1304 1305 1305 1306 # special handling for parameter names without a colons 1306 1307 # for now, assume self-defining 1307 1308 if varname.find(':') == -1: 1308 1309 return "Global",varname 1309 1310 1310 1311 l = getVarDescr(varname) 1311 1312 if not l: … … 1350 1351 else: #modulation parm 1351 1352 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, 1353 1354 lbl = ShortPhaseNames.get(l[0],'phase?') 1354 1355 try: … … 1378 1379 1379 1380 def getVarDescr(varname): 1380 '''Return a short description for a GSAS-II variable 1381 '''Return a short description for a GSAS-II variable 1381 1382 1382 1383 :param str name: A full G2 variable name with 2 or 3 or 4 1383 1384 colons (<p>:<h>:name[:<a1>][:<a2>]) 1384 1385 1385 1386 :returns: a six element list as [`p`,`h`,`name`,`a1`,`a2`,`description`], 1386 1387 where `p`, `h`, `a1`, `a2` are str values or `None`, for the phase number, … … 1404 1405 l += [getDescr(l[2])] 1405 1406 return l 1406 1407 1407 1408 def CompileVarDesc(): 1408 1409 '''Set the values in the variable description lookup table (:attr:`VarDesc`) … … 1424 1425 will match ``AU11``, ``AU23``,.. and `U11`, `U23` etc will be displayed 1425 1426 in the value when used. 1426 1427 1427 1428 ''' 1428 1429 if reVarDesc: return # already done … … 1538 1539 1539 1540 def getDescr(name): 1540 '''Return a short description for a GSAS-II variable 1541 '''Return a short description for a GSAS-II variable 1541 1542 1542 1543 :param str name: The descriptive part of the variable name without colons (:) 1543 1544 1544 1545 :returns: a short description or None if not found 1545 1546 ''' … … 1558 1559 fields) but only when there is more than one matching variable in the 1559 1560 input variable list. So if the input is this:: 1560 1561 1561 1562 varlist = ['0::AUiso:0', '0::AUiso:1', '1::AUiso:0'] 1562 1563 1563 1564 then the output will be this:: 1564 1565 1565 1566 wildList = ['*::AUiso:0', '0::AUiso:*'] 1566 1567 … … 1596 1597 '''returns a list of variable names from list varname 1597 1598 that match wildcard name in varname 1598 1599 1599 1600 :param str varname: a G2 variable name containing a wildcard 1600 1601 (such as \*::var) 1601 1602 :param list varlist: the list of all variable names used in 1602 1603 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) 1604 1605 ''' 1605 1606 rexp = re.compile(varname.replace('*','[0-9]+')) … … 1629 1630 1630 1631 A :class:`G2VarObj` object can be created with a single parameter: 1631 1632 1632 1633 :param str/tuple varname: a single value can be used to create a :class:`G2VarObj` 1633 1634 object. If a string, it must be of form "p:h:var" or "p:h:var:a", where 1634 1635 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); 1637 1638 * a is the atom number (which may be left blank in which case the third colon is omitted). 1638 1639 The atom number can be specified as '*' if a phase number is specified (not as '*'). … … 1650 1651 :param str varname: a single value can be used to create a :class:`G2VarObj` 1651 1652 :param str/int atomnum: The number for the atom (or None or '*') 1652 1653 1653 1654 ''' 1654 1655 IDdict = {} … … 1665 1666 self.phase,self.histogram,self.name,self.atom = args[0] 1666 1667 elif len(args) == 1 and ':' in args[0]: 1667 #parse a string 1668 #parse a string 1668 1669 lst = args[0].split(':') 1669 1670 if lst[0] == '*': … … 1672 1673 self.atom = lst[3] 1673 1674 self.histogram = HistIdLookup.get(lst[1],[None,None])[1] 1674 elif lst[1] == '*': 1675 elif lst[1] == '*': 1675 1676 self.histogram = '*' 1676 1677 self.phase = PhaseIdLookup.get(lst[0],[None,None])[1] … … 1714 1715 1715 1716 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 1717 1718 string (p:h:<var>:a) or (p:h:<var>) 1718 1719 … … 1741 1742 s = (ph + ":" + hist + ":" + str(self.name)) + a 1742 1743 return s 1743 1744 1744 1745 def __repr__(self): 1745 1746 '''Return the detailed contents of the object … … 1810 1811 '''Defines a base class for the reading of input files (diffraction 1811 1812 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. 1813 1814 ''' 1814 1815 class ImportException(Exception): … … 1817 1818 1818 1819 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. 1820 1821 ''' 1821 1822 pass 1822 1823 1823 1824 UseReader = True # in __init__ set value of self.UseReader to False to skip use of current importer 1824 1825 def __init__(self,formatName,longFormatName=None, … … 1858 1859 self.readfilename = '?' 1859 1860 1860 1861 1861 1862 # 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. 1863 1864 # if the read fails either return False or raise an Exception 1864 # preferably of type ImportException. 1865 # preferably of type ImportException. 1865 1866 # ''' 1866 1867 # #start reading … … 1886 1887 '''This routine will attempt to determine if the file can be read 1887 1888 with the current format. 1888 This will typically be overridden with a method that 1889 This will typically be overridden with a method that 1889 1890 takes a quick scan of [some of] 1890 1891 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. 1892 1893 ''' 1893 1894 #filepointer.seek(0) # rewind the file pointer … … 1905 1906 line = l.strip() 1906 1907 if len(line) == 0: # ignore blank lines 1907 continue 1908 continue 1908 1909 elif line.startswith('#'): # ignore comments 1909 continue 1910 continue 1910 1911 elif line.startswith('data_'): # on the right track, accept this file 1911 1912 return True … … 1914 1915 if all([ord(c) < 128 and ord(c) != 0 for c in str(l)]): # show only if ASCII 1915 1916 self.errors += ' '+str(l) 1916 else: 1917 else: 1917 1918 self.errors += ' (binary)' 1918 1919 self.errors += '\n Note: a CIF should only have blank lines or comments before' 1919 1920 self.errors += '\n a data_ statement begins a block.' 1920 return False 1921 return False 1921 1922 1922 1923 ###################################################################### … … 1925 1926 1926 1927 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`. 1928 1929 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. 1930 1931 1931 1932 ''' … … 1949 1950 1950 1951 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 1952 1953 for reading a structure factor histogram require that 1953 1954 the ``Reader()`` routine in the import … … 1973 1974 for the contents of each row. Dict element 'FF' 1974 1975 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. 1976 1977 ''' 1977 1978 def ReInitialize(self): … … 1981 1982 self.Banks = [] #for multi bank data (usually TOF) 1982 1983 self.RefDict = {'RefList':[],'FF':{},'Super':0} 1983 1984 1984 1985 def InitParameters(self): 1985 1986 'initialize the instrument parameters structure' … … 1996 1997 self.Parameters[0]['Type'] = [Type,Type] 1997 1998 if Wave is not None: 1998 self.Parameters[0]['Lam'] = [Wave,Wave] 1999 1999 self.Parameters[0]['Lam'] = [Wave,Wave] 2000 2000 2001 ###################################################################### 2001 2002 class ImportPowderData(ImportBaseclass): … … 2003 2004 2004 2005 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`. 2006 2007 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. 2008 2009 ''' 2009 2010 def __init__(self,formatName,longFormatName=None, … … 2013 2014 self.clockWd = None # used in TOF 2014 2015 self.ReInitialize() 2015 2016 2016 2017 def ReInitialize(self): 2017 2018 'Reinitialize the Reader to initial settings' … … 2026 2027 np.array(yb), # calc. background (zero) 2027 2028 np.array(yd), # obs-calc profiles 2028 ''' 2029 ''' 2029 2030 self.comments = [] 2030 2031 self.idstring = '' 2031 2032 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 2033 2034 self.GSAS = None # used in TOF 2034 2035 self.repeat_instparm = True # Should a parm file be 2035 # used for multiple histograms? 2036 # used for multiple histograms? 2036 2037 self.instparm = None # name hint from file of instparm to use 2037 2038 self.instfile = '' # full path name to instrument parameter file … … 2047 2048 '''Defines a base class for the reading of files with small angle data. 2048 2049 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. 2050 2051 ''' 2051 2052 def __init__(self,formatName,longFormatName=None,extensionlist=[], 2052 2053 strictExtension=False,): 2053 2054 2054 2055 ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist, 2055 2056 strictExtension) 2056 2057 self.ReInitialize() 2057 2058 2058 2059 def ReInitialize(self): 2059 2060 'Reinitialize the Reader to initial settings' … … 2068 2069 np.array(yd), # obs-calc profiles 2069 2070 np.array(yb), # preset bkg 2070 ''' 2071 ''' 2071 2072 self.comments = [] 2072 2073 self.idstring = '' … … 2081 2082 '''Defines a base class for the reading of files with reflectometry data. 2082 2083 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. 2084 2085 ''' 2085 2086 def __init__(self,formatName,longFormatName=None,extensionlist=[], 2086 2087 strictExtension=False,): 2087 2088 2088 2089 ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist, 2089 2090 strictExtension) 2090 2091 self.ReInitialize() 2091 2092 2092 2093 def ReInitialize(self): 2093 2094 'Reinitialize the Reader to initial settings' … … 2102 2103 np.array(yd), # obs-calc profiles 2103 2104 np.array(yb), # preset bkg 2104 ''' 2105 ''' 2105 2106 self.comments = [] 2106 2107 self.idstring = '' … … 2115 2116 '''Defines a base class for the reading of files with PDF G(R) data. 2116 2117 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. 2118 2119 ''' 2119 2120 def __init__(self,formatName,longFormatName=None,extensionlist=[], 2120 2121 strictExtension=False,): 2121 2122 2122 2123 ImportBaseclass.__init__(self,formatName,longFormatName,extensionlist, 2123 2124 strictExtension) 2124 2125 self.ReInitialize() 2125 2126 2126 2127 def ReInitialize(self): 2127 2128 'Reinitialize the Reader to initial settings' … … 2132 2133 np.array(x), # r-axis values 2133 2134 np.array(y), # pdf g(r) 2134 ''' 2135 ''' 2135 2136 self.comments = [] 2136 2137 self.idstring = '' … … 2142 2143 2143 2144 Images are read in only these places: 2144 2145 2145 2146 * Initial reading is typically done from a menu item 2146 2147 with a call to :meth:`GSASIIdataGUI.GSASII.OnImportImage` 2147 2148 which in turn calls :meth:`GSASIIdataGUI.GSASII.OnImportGeneric`. That calls 2148 2149 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. 2150 2151 2151 2152 * Images are read alternatively in :func:`GSASIIIO.ReadImages`, which puts image info … … 2158 2159 When reading an image, the ``Reader()`` routine in the ImportImage class 2159 2160 should set: 2160 2161 2161 2162 * :attr:`Comments`: a list of strings (str), 2162 2163 * :attr:`Npix`: the number of pixels in the image (int), … … 2164 2165 * :attr:`Data`: a dict defining image parameters (dict). Within this dict the following 2165 2166 data items are needed: 2166 2167 2167 2168 * 'pixelSize': size of each pixel in microns (such as ``[200,200]``. 2168 2169 * 'wavelength': wavelength in Angstoms. … … 2175 2176 2176 2177 optional data items: 2177 2178 2178 2179 * :attr:`repeat`: set to True if there are additional images to 2179 2180 read in the file, False otherwise 2180 2181 * :attr:`repeatcount`: set to the number of the image. 2181 2182 2182 2183 Note that the above is initialized with :meth:`InitParameters`. 2183 2184 (Also see :ref:`Writing a Import Routine<Import_Routines>` … … 2189 2190 extensionlist,strictExtension) 2190 2191 self.InitParameters() 2191 2192 2192 2193 def ReInitialize(self): 2193 2194 'Reinitialize the Reader to initial settings -- not used at present' 2194 2195 ImportBaseclass.ReInitialize(self) 2195 2196 self.InitParameters() 2196 2197 2197 2198 def InitParameters(self): 2198 2199 'initialize the instrument parameters structure' … … 2212 2213 ParentFrame.ImageZ = self.Image # store the image for plotting 2213 2214 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 2215 2216 2216 2217 ################################################################################################# … … 2227 2228 using :meth:`LoadExpression`. This contains only the minimum 2228 2229 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. 2230 2231 ''' 2231 2232 def __init__(self): … … 2245 2246 * a value for to the parameter and 2246 2247 * a flag to determine if the variable is refined. 2247 ''' 2248 ''' 2248 2249 self.depVar = None 2249 2250 … … 2264 2265 are actually in the parameter dictionary. This is checked when the 2265 2266 computation for the expression is done in :meth:`SetupCalc`. 2266 2267 2267 2268 :param str expr: the expression 2268 2269 :param list exprVarLst: parameter labels found in the expression … … 2365 2366 '''Parse an expression and return a dict of called functions and 2366 2367 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 2368 2369 and the functions are looked up into the modules global 2369 workspace. 2370 2370 workspace. 2371 2371 2372 Note that no changes are made to the object other than 2372 2373 saving an error message, so that this can be used for testing prior 2373 to the save. 2374 to the save. 2374 2375 2375 2376 :returns: a list of used variables … … 2388 2389 pkgdict = {} 2389 2390 # no listed package, try in current namespace 2390 if len(df) == 1: 2391 if len(df) == 1: 2391 2392 try: 2392 2393 fxnobj = eval(f) … … 2448 2449 for a, b in ast.iter_fields(node): 2449 2450 if isinstance(b, ast.AST): 2450 if a == 'func': 2451 if a == 'func': 2451 2452 fxnlist += ['.'.join(ASTtransverse(b,True)[0])] 2452 2453 continue … … 2503 2504 '''An object used to evaluate an expression from a :class:`ExpressionObj` 2504 2505 object. 2505 2506 2506 2507 :param ExpressionObj exprObj: a :class:`~ExpressionObj` expression object with 2507 2508 an expression string and mappings for the parameter labels in that object. … … 2562 2563 parmsInList = False 2563 2564 break 2564 2565 2565 2566 # set up the dicts needed to speed computations 2566 2567 self.exprDict = {} … … 2620 2621 if var in self.lblLookup: 2621 2622 self.exprDict[self.lblLookup[var]] = parmDict[var] 2622 2623 2623 2624 def EvalExpression(self): 2624 2625 '''Evaluate an expression. Note that the expression … … 2653 2654 val = np.sum(val) 2654 2655 return val 2655 2656 2656 2657 class G2Exception(Exception): 2657 2658 def __init__(self,msg): … … 2669 2670 print(i.strip().rstrip()) 2670 2671 else: 2671 print 70*'*' 2672 print 70*'*' 2672 2673 for i in traceback.format_list(traceback.extract_stack()[:-1]): print(i.strip().rstrip()) 2673 print 70*'*' 2674 2674 print 70*'*' 2675 2675 2676 def CreatePDFitems(G2frame,PWDRtree,ElList,Qlimits,numAtm=1,FltBkg=0,PDFnames=[]): 2676 2677 '''Create and initialize a new set of PDF tree entries … … 2683 2684 :param float FltBkg: flat background value 2684 2685 :param list PDFnames: previously used PDF names 2685 2686 2686 2687 :returns: the Id of the newly created PDF entry 2687 2688 ''' … … 2704 2705 G2frame.GPXtree.SetItemPyData(G2frame.GPXtree.AppendItem(Id,text='PDF Peaks'), 2705 2706 {'Limits':[1.,5.],'Background':[2,[0.,-0.2*np.pi],False],'Peaks':[]}) 2706 return Id 2707 return Id 2707 2708 2708 2709 … … 2741 2742 calcobj2.SetupCalc(parmDict2) 2742 2743 showEQ(calcobj2) 2743 2744 2744 2745 parmDict1 = {'0::Afrac:0':1.0, '0::Afrac:1': 1.0} 2745 2746 print '\nDict = ',parmDict1 -
trunk/GSASIIplot.py
r3013 r3023 18 18 import numpy.ma as ma 19 19 import 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 21 try: 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 28 except ImportError: 29 pass 26 30 import GSASIIpath 27 31 Clip_on = GSASIIpath.GetConfigValue('Clip_on',True) -
trunk/GSASIIpwdGUI.py
r3000 r3023 18 18 import sys 19 19 import os.path 20 import wx 21 import wx.grid as wg 20 # Don't depend on graphics for scriptable 21 try: 22 import wx 23 import wx.grid as wg 24 except ImportError: 25 pass 22 26 import numpy as np 23 27 import numpy.ma as ma -
trunk/GSASIIscriptable.py
r3022 r3023 153 153 ''' 154 154 file = open(ProjFile,'wb') 155 # print('save to file: {}'.format(ProjFile))156 155 try: 157 156 for name in nameList: … … 164 163 finally: 165 164 file.close() 166 # print('project save successful')167 165 168 166 def ImportPowder(reader,filename): … … 888 886 889 887 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) 890 891 # index_ids will automatically save the project 891 892 self.index_ids() -
trunk/GSASIIstrMain.py
r3007 r3023 37 37 acosd = lambda x: 180.*np.arccos(x)/np.pi 38 38 atan2d = lambda y,x: 180.*np.arctan2(y,x)/np.pi 39 39 40 40 ateln2 = 8.0*math.log(2.0) 41 41 DEBUG = True … … 43 43 def RefineCore(Controls,Histograms,Phases,restraintDict,rigidbodyDict,parmDict,varyList, 44 44 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 ''' 46 49 # print 'current',varyList 47 50 # for item in parmDict: print item,parmDict[item] ######### show dict just before refinement … … 53 56 # test code to compute GOF and save for external repeat 54 57 #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) 56 59 #fl = open('beforeFit.cpickle','wb') 57 60 #import cPickle … … 62 65 Xtol = Controls['SVDtol'] 63 66 Factor = Controls['shift factor'] 64 if 'Jacobian' in Controls['deriv type']: 67 if 'Jacobian' in Controls['deriv type']: 65 68 result = so.leastsq(G2stMth.errRefine,values,Dfun=G2stMth.dervRefine,full_output=True, 66 69 ftol=Ftol,col_deriv=True,factor=Factor, … … 124 127 if val: 125 128 print 'Removing parameter: ',varyList[num-i] 126 del(varyList[num-i]) 129 del(varyList[num-i]) 127 130 else: 128 131 Ipvt = result[2]['ipvt'] … … 139 142 import pytexture as ptx 140 143 ptx.pyqlmninit() #initialize fortran arrays for spherical harmonics 141 144 142 145 printFile = open(ospath.splitext(GPXfile)[0]+'.lst','w') 143 146 G2stIO.ShowBanner(printFile) 144 147 varyList = [] 145 148 parmDict = {} 146 G2mv.InitVars() 149 G2mv.InitVars() 147 150 Controls = G2stIO.GetControls(GPXfile) 148 151 G2stIO.ShowControls(Controls,printFile) 149 152 calcControls = {} 150 calcControls.update(Controls) 153 calcControls.update(Controls) 151 154 constrDict,fixedList = G2stIO.GetConstraints(GPXfile) 152 155 restraintDict = G2stIO.GetRestraints(GPXfile) … … 199 202 return False,' Constraint error' 200 203 # print G2mv.VarRemapShow(varyList) 201 204 202 205 ifPrint = True 203 206 print >>printFile,'\n Refinement results:' … … 229 232 printFile.close() 230 233 return False,Msg.msg 231 234 232 235 #for testing purposes!!! 233 236 if DEBUG: … … 245 248 if dlg: 246 249 return True,Rvals 247 250 248 251 def phaseCheck(phaseVary,Phases,histogram): 249 252 ''' 250 Removes unused parameters from phase varylist if phase not in histogram 253 Removes unused parameters from phase varylist if phase not in histogram 251 254 ''' 252 255 pIds = [] … … 263 266 import pytexture as ptx 264 267 ptx.pyqlmninit() #initialize fortran arrays for spherical harmonics 265 268 266 269 printFile = open(ospath.splitext(GPXfile)[0]+'.lst','w') 267 270 print 'Starting Sequential Refinement' 268 271 G2stIO.ShowBanner(printFile) 269 272 Controls = G2stIO.GetControls(GPXfile) 270 G2stIO.ShowControls(Controls,printFile,SeqRef=True) 273 G2stIO.ShowControls(Controls,printFile,SeqRef=True) 271 274 restraintDict = G2stIO.GetRestraints(GPXfile) 272 275 Histograms,Phases = G2stIO.GetUsedHistogramsAndPhases(GPXfile) … … 351 354 # do constraint processing 352 355 #reload(G2mv) # debug 353 G2mv.InitVars() 356 G2mv.InitVars() 354 357 constrDict,fixedList = G2stIO.GetConstraints(GPXfile) 355 358 varyListStart = tuple(varyList) # save the original varyList before dependent vars are removed … … 404 407 print(line[:-2]) 405 408 firstVaryList = newVaryList 406 409 407 410 ifPrint = False 408 411 print >>printFile,'\n Refinement results for histogram: v'+histogram … … 413 416 if PlotFunction: 414 417 PlotFunction(G2frame,Histo[histogram]['Data'],histogram) 415 418 416 419 print ' wR = %7.2f%%, chi**2 = %12.6g, reduced chi**2 = %6.2f, last delta chi = %.4f'%( 417 420 Rvals['Rwp'],Rvals['chisq'],Rvals['GOF']**2,Rvals['DelChi2']) … … 420 423 # the uncertainties for dependent constrained parms into the esd dict 421 424 sigDict.update(G2mv.ComputeDepESD(covMatrix,varyList,parmDict)) 422 425 423 426 # a dict with values & esds for dependent (constrained) parameters - avoid extraneous holds 424 427 depParmDict = {i:(parmDict[i],sigDict[i]) for i in varyListStart if i in sigDict and i not in varyList} … … 441 444 NewparmDict = {} 442 445 # 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. 444 447 if Controls['Copy2Next'] and ihst < len(histNames)-1: 445 448 hId = Histo[histogram]['hId'] # current histogram … … 470 473 :param dict DisAglCtls: contains distance/angle radii usually defined using 471 474 :func:`GSASIIctrlGUI.DisAglDialog` 472 :param dict DisAglData: contains phase data: 475 :param dict DisAglData: contains phase data: 473 476 Items 'OrigAtoms' and 'TargAtoms' contain the atoms to be used 474 477 for distance/angle origins and atoms to be used as targets. … … 481 484 **DistArray** is a dict keyed by the origin atom number where the value is a list 482 485 of distance entries. The value for each distance is a list containing: 483 486 484 487 0) the target atom number (int); 485 488 1) the unit cell offsets added to x,y & z (tuple of int values) … … 497 500 498 501 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. 500 503 ''' 501 504 import numpy.ma as ma 502 505 503 506 SGData = DisAglData['SGData'] 504 507 Cell = DisAglData['Cell'] 505 508 506 509 Amat,Bmat = G2lat.cell2AB(Cell[:6]) 507 510 covData = {} 508 if 'covData' in DisAglData: 511 if 'covData' in DisAglData: 509 512 covData = DisAglData['covData'] 510 513 covMatrix = covData['covMatrix'] 511 514 varyList = covData['varyList'] 512 515 pfx = str(DisAglData['pId'])+'::' 513 516 514 517 Factor = DisAglCtls['Factors'] 515 518 Radii = dict(zip(DisAglCtls['AtomTypes'],zip(DisAglCtls['BondRadii'],DisAglCtls['AngleRadii']))) … … 587 590 :param dict DisAglCtls: contains distance/angle radii usually defined using 588 591 :func:`GSASIIctrlGUI.DisAglDialog` 589 :param dict DisAglData: contains phase data: 592 :param dict DisAglData: contains phase data: 590 593 Items 'OrigAtoms' and 'TargAtoms' contain the atoms to be used 591 594 for distance/angle origins and atoms to be used as targets. 592 595 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. 594 597 ''' 595 598 def MyPrint(s): 596 599 out.write(s+'\n') 597 600 # print(s,file=out) # use in Python 3 598 601 599 602 def ShowBanner(name): 600 603 MyPrint(80*'*') … … 612 615 else: 613 616 line = ' %s %s'%(item.ljust(30),SGtable[2*i+1].ljust(30)) 614 MyPrint(line) 617 MyPrint(line) 615 618 else: 616 619 MyPrint(' ( 1) %s'%(SGtable[0])) #triclinic case 617 620 Cell = DisAglData['Cell'] 618 621 619 622 Amat,Bmat = G2lat.cell2AB(Cell[:6]) 620 623 covData = {} 621 if 'covData' in DisAglData: 624 if 'covData' in DisAglData: 622 625 covData = DisAglData['covData'] 623 626 pfx = str(DisAglData['pId'])+'::' … … 628 631 line = '\n Unit cell:' 629 632 for name,vals in zip(names,valEsd): 630 line += name+vals 633 line += name+vals 631 634 MyPrint(line) 632 else: 635 else: 633 636 MyPrint('\n Unit cell: a = '+('%.5f'%Cell[0])+' b = '+('%.5f'%Cell[1])+' c = '+('%.5f'%Cell[2])+ 634 637 ' alpha = '+('%.3f'%Cell[3])+' beta = '+('%.3f'%Cell[4])+' gamma = '+ … … 677 680 SGData = DATData['SGData'] 678 681 Cell = DATData['Cell'] 679 682 680 683 Amat,Bmat = G2lat.cell2AB(Cell[:6]) 681 684 covData = {} 682 685 pfx = '' 683 if 'covData' in DATData: 686 if 'covData' in DATData: 684 687 covData = DATData['covData'] 685 688 pfx = str(DATData['pId'])+'::' … … 689 692 symop = atom[-1].split('+') 690 693 if len(symop) == 1: 691 symop.append('0,0,0') 694 symop.append('0,0,0') 692 695 symop[0] = int(symop[0]) 693 696 symop[1] = eval(symop[1]) … … 713 716 Dist,sig = G2mth.GetDATSig(Oatoms,Datoms,Amat,SGData,covData) 714 717 print ' Distance in '+DATData['Name']+' for atom sequence: ',atmSeq,'=',G2mth.ValEsd(Dist,sig) 715 718 716 719 def BestPlane(PlaneData): 717 720 'Needs a doc string' … … 724 727 ShowBanner(PlaneData['Name']) 725 728 726 Cell = PlaneData['Cell'] 727 Amat,Bmat = G2lat.cell2AB(Cell[:6]) 729 Cell = PlaneData['Cell'] 730 Amat,Bmat = G2lat.cell2AB(Cell[:6]) 728 731 Atoms = PlaneData['Atoms'] 729 732 sumXYZ = np.zeros(3) … … 750 753 for i,xyz in enumerate(XYZ): 751 754 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 754 757 def main(): 755 758 'Needs a doc string' … … 766 769 exit() 767 770 print("Done. Execution time {:.2f} sec.".format(time.time()-starttime)) 768 771 769 772 if __name__ == '__main__': 770 773 main() -
trunk/imports/G2phase.py
r2858 r3023 22 22 import random as ran 23 23 import numpy as np 24 import wx 24 try: 25 import wx 26 except ImportError: 27 wx = None 25 28 import GSASIIobj as G2obj 26 29 import GSASIIspc as G2spc
Note: See TracChangeset
for help on using the changeset viewer.