Changeset 5572
- Timestamp:
- May 9, 2023 9:43:48 PM (7 months ago)
- Location:
- trunk
- Files:
-
- 46 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/ElementTable.py
r5464 r5572 1 1 # -*- coding: utf-8 -*- 2 2 ''' 3 *ElementTable: Periodic Table Data*4 -----------------------------------5 6 3 Element table data for building periodic table with valences & JMOL colors. 7 4 Need these in case we go back to this periodic table coloring scheme. -
trunk/FormFactors.py
r4808 r5572 1 1 # -*- coding: utf-8 -*- 2 2 ''' 3 *FormFactors: Scattering Data*4 ------------------------------5 6 3 Contains atomic scattering factors from 7 4 "New Analytical Scattering Factor Functions for Free Atoms -
trunk/GSASII.py
r5508 r5572 10 10 ########### SVN repository information ################### 11 11 ''' 12 *GSASII: GSAS-II GUI* 13 ===================== 14 15 File GSASII.py is the script to start the GSAS-II graphical user 16 interface (GUI). 17 This script imports GSASIIpath, which does some minor initialization 18 and then (before any wxPython calls can be made) creates a wx.App application. 19 A this point :func:`GSASIIpath.SetBinaryPath` is called to establish 20 the directory where GSAS-II binaries are found. If the binaries 21 are not installed or are incompatible with the OS/Python packages, 22 the user is asked if they should be updated from the subversion site. 23 The wxPython app is then passed to :func:`GSASIIdataGUI.GSASIImain`, 24 which creates the GSAS-II GUI and finally the event loop is started. 25 26 Keyboard Menu Shortcuts 27 ---------------------------------------- 28 29 Shortcuts for commonly-used menu commands are created by adding a 30 menu command with a "\tctrl+" addition such as:: 31 32 item = parent.Append(wx.ID_ANY,'&Refine\tCtrl+R','Perform a refinement') 33 34 This will allow the above menu command to be executed with a "Control-R" 35 keyboard command (on MacOS this will be "Command+R" rather than "Control-R") as well as using the menu to access that action. The following table lists the 36 keyboard letters/numbers that have GSAS-II assigned actions. 37 are system assigned. Note that there are also plotting keyboard commands that are 38 implemented in :mod:`GSASIIplot`. 39 These can be discovered from the "K" button on the plot menu bar as they 40 vary depending on the type of plot. 41 42 .. tabularcolumns:: |c|p{4in}| 43 44 ========== ==================================================== 45 key explanation 46 ========== ==================================================== 47 O Open project (File menu) 48 E Reopen recent (File menu) 49 S Save project (File menu) 50 B Project browser (File menu) 51 Q Quit (File menu). This is system assigned on MacOS 52 F4 Quit (File menu). This is system-assigned 53 on Windows 54 55 L View LS parms (Calculate menu) 56 R Refine/Sequential Refine (Calculate menu) 57 I Parameter Impact (Calculate menu) 58 59 U Check for updates (Help menu) 60 T Tutorials (Help menu) 61 F1 Help on current tree item (Help menu). 62 This is system-assigned 63 64 P Peakfit (Peak Fitting menu, requires selection of 65 Histogram Peak) 66 67 M Minimize GSAS-II windows (MacOS Windows menu). 68 This is system-assigned 69 ========== ==================================================== 70 12 A single class, :class:`G2App`, is defined here to create 13 an wxPython application. This is only used on 14 MacOS. For other platforms ``wx.App()`` is called directly. 71 15 ''' 72 16 -
trunk/GSASIIElem.py
r5464 r5572 1 1 # -*- coding: utf-8 -*- 2 """3 *GSASIIElem: functions for element types*4 -----------------------------------------5 6 """7 2 # Copyright: 2008, Robert B. Von Dreele & Brian H. Toby (Argonne National Laboratory) 8 3 ########### SVN repository information ################### … … 13 8 # $Id$ 14 9 ########### SVN repository information ################### 10 """ 11 Routines used to define element settings follow. 12 """ 15 13 16 14 import math -
trunk/GSASIIIO.py
r5394 r5572 8 8 ########### SVN repository information ################### 9 9 ''' 10 *GSASIIIO: Misc I/O routines* 11 ============================= 12 13 Module with miscellaneous routines for input and output. Many 14 are GUI routines to interact with user. 15 16 Includes support for image reading. 17 18 Also includes base class for data export routines (TODO: should move) 10 Misc routines for input and output, including image reading follow. 19 11 20 12 TODO: This module needs some work to separate wx from non-wx routines. GUI -
trunk/GSASIIctrlGUI.py
r5550 r5572 8 8 # $Id$ 9 9 ########### SVN repository information ################### 10 '''Documentation for all the routines in module :mod:`GSASIIctrlGUI` 11 follows. 10 12 ''' 11 *GSASIIctrlGUI: Custom GUI controls* 12 --------------------------------------------- 13 14 A library of GUI controls for reuse throughout GSAS-II, as indexed below 15 16 .. tabularcolumns:: |l|p{4in}| 17 18 ================================ ================================================================= 19 Class or function name Description 20 ================================ ================================================================= 21 :class:`EnumSelector` A combo box with a built-in call back routine that 22 automatically sets a dict or list entry. 23 :class:`DisAglDialog` Distance/Angle Controls input dialog. 24 :class:`FlagSetDialog` Dialog that provides a table of items along with a 25 checkbox for each. 26 :class:`G2ChoiceButton` A customized wx.Choice that automatically initializes to 27 the initial value and saves the choice directly into a dict 28 or list value. Optionally calls function when a 29 choice is selected 30 :class:`G2CheckBox` A customized wx.CheckBox that automatically initializes to 31 the initial value and saves the choice directly into a dict 32 or list value. Optionally calls function when a 33 choice is selected 34 :func:`G2CheckBoxFrontLbl` A version of :class:`G2CheckBox` that places the label 35 for the check box in front. Otherwise works the same. 36 :func:`G2RadioButtons` Creates a series of grouped radio buttons. 37 :class:`G2SliderWidget` A customized combination of a wx.Slider and a validated 38 wx.TextCtrl (see :class:`ValidatedTxtCtrl`). 39 :class:`G2Slider` A wrapped version of wx.Slider that implements scaling 40 :class:`G2SpinWidget` A customized combination of a wx.SpinButton and a validated 41 wx.TextCtrl (see :class:`ValidatedTxtCtrl`). 42 :class:`G2ColumnIDDialog` A dialog for matching column data to desired items; some 43 columns may be ignored. 44 :class:`G2HistoDataDialog` A dialog for global edits to histogram data globally 45 :class:`G2MultiChoiceDialog` Dialog similar to wx.MultiChoiceDialog, but provides 46 a filter to select choices and buttons to make selection 47 of multiple items more simple. 48 :class:`G2MultiChoiceWindow` Similar to :class:`G2MultiChoiceDialog` but provides 49 a sizer that can be placed in a frame or panel. 50 :class:`G2SingleChoiceDialog` Dialog similar to wx.SingleChoiceDialog, but provides 51 a filter to help search through choices. 52 :class:`HelpButton` Creates a button labeled with a "?" that when pressed 53 displays help text in a modal message window 54 or web browser. 55 :class:`MultiColumnSelection` A dialog that builds a multicolumn table, word wrapping 56 is used for the 2nd, 3rd,... columns. 57 :class:`MultiDataDialog` Dialog to obtain multiple data values from user, 58 with optional range validation; items can be float, str or bool 59 :class:`MultiIntegerDialog` Dialog to obtain multiple integer values from user, 60 with a description for each value and optional 61 defaults. 62 :class:`MultiStringDialog` Dialog to obtain multiple string values from user, 63 with a description for each value and optional 64 defaults. 65 :class:`OrderBox` Creates a wx.Panel with scrollbars where items can be 66 ordered into columns. 67 :class:`SortableLstCtrl` Creates a wx.Panel for a table of data that 68 can be sorted by clicking on a column label. 69 :class:`ScrolledMultiEditor` wx.Dialog for editing many dict- or list-contained items. 70 with validation. Results are placed in dict or list. 71 :class:`SGMagSpinBox` Special version of MessageBox that displays magnetic spin text 72 :class:`SGMessageBox` Special version of MessageBox that displays space group & 73 super space group text in two blocks 74 :class:`SingleFloatDialog` Dialog to obtain a single float value from user, with 75 optional range validation. 76 :class:`SingleIntDialog` Dialog to obtain a single integer value from user, 77 with optional range validation. 78 :class:`SingleStringDialog` Dialog to obtain a single string value from user, 79 with optional an optional default value. 80 :class:`ValidatedTxtCtrl` A text control with a built-in call back routine to set dict 81 or list elements. Optionally validates input as float, int or 82 for strings non-blank. Value is set when focus changes 83 :func:`CallScrolledMultiEditor` Routine for editing many dict- or list-contained items. 84 using the :class:`ScrolledMultiEditor` dialog 85 :func:`Define_wxId` Create a unique wx.Id symbol in _initMenus in :mod:`GSASIIdataGUI`. 86 Such symbols are needed when the menu item is defined in a 87 different location from the wx.Bind that links the menu item 88 to a function. This function allows all the menu Ids to be 89 defined as the menus are created in one place and then can be 90 used in Bind elsewhere in the code. 91 :func:`G2MessageBox` Displays text typically used for errors or warnings. 92 :func:`ShowScrolledInfo` Displays longer text where scrolling is possibly needed 93 :func:`G2ScrolledGrid` Displays a multicolumn table of information with 94 possible scroll bars 95 :func:`ShowScrolledColText` Displays tabular text with scrolling where needed 96 :func:`GetItemOrder` Creates a dialog for ordering items into columns 97 :func:`GetImportFile` Gets one ore more file from the appropriate import 98 directory, which can be overridden. Arguments follow those 99 of :func:`wx.FileDialog` 100 :func:`HorizontalLine` Places a line in a Frame or Dialog to separate sections. 101 :func:`ItemSelector` Select a single item or multiple items from list of choices. 102 Creates and then destroys a wx.Dialog and returns the 103 selections(s). 104 :func:`SelectEdit1Var` Select a variable from a list, then edit it and select 105 histograms to copy it to. 106 :func:`askSaveFile` Get a file name from user 107 :func:`askSaveDirectory` Get a directory name from user 108 :func:`BlockSelector` Select a single block for instrument parameters 109 :func:`MultipleBlockSelector` Select one or more blocks of data, used for 110 CIF powder histogram imports only 111 :func:`MultipleChoicesSelector` Dialog for displaying fairly complex choices, used for 112 CIF powder histogram imports only 113 :func:`PhaseSelector` Select a phase from a list (used for phase importers) 114 :class:`gpxFileSelector` File browser dialog for opening existing .gpx files 115 :class:`ScrolledStaticText` A wx.StaticText widget that fits a large string into a 116 small space by scrolling it 117 :func:`ReadOnlyTextCtrl` A wx.TextCtrl widget to be used wx.StaticText 118 (no edits allowed) text appears in a box. 119 :func:`setColorButton` A button for color selection as a replacement 120 for wx.ColourSelect 121 ================================ ================================================================= 122 123 Other miscellaneous non-GUI routines that may be of use for GUI-related actions: 124 125 .. tabularcolumns:: |l|p{4in}| 126 127 ================================ ================================================================= 128 Function name Description 129 ================================ ================================================================= 130 :func:`StripIndents` Regularizes the intentation from a string with multiple 131 newline characters by removing spaces at the beginning 132 of each line. 133 :func:`StripUnicode` Removes unicode characters from strings 134 :func:`GetImportPath` Determines the default location to use for importing files. 135 Tries sequentially :attr:`G2frame.TutorialImportDir`, 136 config var ``Import_directory`` and 137 :attr:`G2frame.LastImportDir`. 138 :func:`GetExportPath` Determines the default location to use for writing files. 139 Tries sequentially :attr:`G2frame.LastExportDir` and 140 :attr:`G2frame.LastGPXdir` 141 ================================ ================================================================= 142 143 Documentation for all the routines in module :mod:`GSASIIctrlGUI`. 144 145 ''' 13 # Documentation moved to doc/source/GSASIIGUIr.rst 14 # 146 15 from __future__ import division, print_function 147 16 import os -
trunk/GSASIIdata.py
r4364 r5572 9 9 ########### SVN repository information ################### 10 10 ''' 11 *GSASIIdata: Data for computations*12 -----------------------------------13 14 11 At present this module defines one dict, ``ramachandranDist``, 15 12 which contains arrays for All and specific amino acids. -
trunk/GSASIIfiles.py
r5496 r5572 8 8 ########### SVN repository information ################### 9 9 ''' 10 *GSASIIfiles: data (non-GUI) I/O routines*11 ==========================================12 13 Module with miscellaneous routines for input and output from files.14 15 10 This module should not contain any references to wxPython so that it 16 11 can be imported for scriptable use or potentially on clients where 17 12 wx is not installed. 18 13 19 Future refactoring: This module and GSASIIIO.pyneeds some work to20 move non-wx routines here. It may will likely make sense to rename the module(s)21 at that point.14 Future refactoring: This module and :mod:`GSASIIIO` needs some work to 15 move non-wx routines to here. It will likely make sense to rename the 16 GSASIIIO module after that is done. 22 17 ''' 23 18 from __future__ import division, print_function -
trunk/GSASIIimage.py
r5551 r5572 1 1 # -*- coding: utf-8 -*- 2 #GSASII image calculations: ellipse fitting & image integration2 #GSASII image calculations: Image calibration, masking & integration routines. 3 3 ########### SVN repository information ################### 4 4 # $Date$ … … 9 9 ########### SVN repository information ################### 10 10 ''' 11 *GSASIIimage: Image calc module* 12 ================================ 13 14 Ellipse fitting & image integration 15 11 Classes and routines defined in :mod:`GSASIIimage` follow. 16 12 ''' 13 17 14 from __future__ import division, print_function 18 15 import math -
trunk/GSASIIindex.py
r5472 r5572 10 10 ########### SVN repository information ################### 11 11 ''' 12 *GSASIIindex: Cell Indexing Module* 13 =================================== 14 15 Cell indexing program: variation on that of A. Coehlo 16 includes cell refinement from peak positions 12 Classes and routines defined in :mod:`GSASIIindex` follow. 17 13 ''' 18 14 -
trunk/GSASIIlattice.py
r5553 r5572 1 1 # -*- coding: utf-8 -*- 2 '''3 *GSASIIlattice: Unit cells*4 ---------------------------5 6 Perform lattice-related computations7 8 Note that *G* is the reciprocal lattice tensor, and *g* is its inverse,9 :math:`G = g^{-1}`, where10 11 .. math::12 13 g = \\left( \\begin{matrix}14 a^2 & a b\\cos\\gamma & a c\\cos\\beta \\\\15 a b\\cos\\gamma & b^2 & b c \\cos\\alpha \\\\16 a c\\cos\\beta & b c \\cos\\alpha & c^217 \\end{matrix}\\right)18 19 The "*A* tensor" terms are defined as20 :math:`A = (\\begin{matrix} G_{11} & G_{22} & G_{33} & 2G_{12} & 2G_{13} & 2G_{23}\\end{matrix})` and *A* can be used in this fashion:21 :math:`d^* = \\sqrt {A_0 h^2 + A_1 k^2 + A_2 l^2 + A_3 hk + A_4 hl + A_5 kl}`, where22 *d* is the d-spacing, and :math:`d^*` is the reciprocal lattice spacing,23 :math:`Q = 2 \\pi d^* = 2 \\pi / d`.24 Note that GSAS-II variables ``p::Ai`` (i = 0, 1,... 5) and ``p`` is a phase number are25 used for the *Ai* values. See :func:`A2cell`, :func:`cell2A` for interconversion between A and26 unit cell parameters; :func:`cell2Gmat` :func:`Gmat2cell` for G and cell parameters.27 28 When the hydrostatic/elastic strain coefficients (*Dij*, :math:`D_{ij}`) are used, they are added to the29 *A* tensor terms (Ai, :math:`A_{i}`) so that A is redefined30 :math:`A = (\\begin{matrix} A_{0} + D_{11} & A_{1} + D_{22} & A_{2} + D_{33} & A_{3} + D_{12} & A_{4} + D_{13} & A_{5} + D_{23}\\end{matrix})`. See :func:`cellDijFill`.31 Note that GSAS-II variables ``p:h:Dij`` (i,j = 1, 2, 3) and ``p`` is a phase number32 and ``h`` a histogram number are used for the *Dij* values.33 '''34 2 ########### SVN repository information ################### 35 3 # $Date$ … … 39 7 # $Id$ 40 8 ########### SVN repository information ################### 9 ''' 10 :mod:`GSASIIlattice` Classes & routines follow 11 ''' 41 12 from __future__ import division, print_function 42 13 import math -
trunk/GSASIIlog.py
r4800 r5572 9 9 ########### SVN repository information ################### 10 10 ''' 11 *GSASIIlog: Logging of "Actions"*12 ---------------------------------13 14 11 Module to provide logging services, e.g. track and replay "actions" 15 12 such as menu item, tree item, button press, value change and so on. -
trunk/GSASIImapvars.py
r5538 r5572 10 10 ########### SVN repository information ################### 11 11 """ 12 *GSASIImapvars: Parameter constraints* 13 ====================================== 14 15 Module to implements algebraic contraints, parameter redefinition 16 and parameter simplification contraints. 17 18 19 *Externally-Accessible Routines* 20 --------------------------------- 21 22 To define a set of constrained and unconstrained relations, one 23 defines a list of dictionary defining constraint parameters and their 24 values, a list of fixed values for each constraint and a list of 25 parameters to be varied. In addition, one uses 26 :func:`StoreEquivalence` to define parameters that are equivalent. 27 See the :ref:`Constraints Processing section<Constraints_processing>` for details on how 28 processing of constraints is done. 29 30 .. tabularcolumns:: |l|p{4in}| 31 32 ============================= =================================================================== 33 routine explanation 34 ============================= =================================================================== 35 :func:`InitVars` This is used to clear out all defined previously 36 defined constraint information 37 38 :func:`StoreEquivalence` Implements parameter redefinition. 39 This should be called for every set of equivalence relationships. 40 Use :func:`StoreEquivalence` before calling 41 :func:`GenerateConstraints` 42 43 :func:`ProcessConstraints` Initially constraints of all types are maintained in lists of 44 dict entries that are stored in the data tree, 45 with parameters are stored as 46 :class:`~GSASIIobj.G2VarObj` objects so that they can 47 be resolved if the phase/histogram order changes. 48 :func:`ProcessConstraints` processes this list of dict entries, 49 separating the "Equivalence", "Hold", âConstâ and âNew Varâ 50 entries for subsequent use. 51 See the :ref:`Constraint Reorganization <ProcessConstraints>` 52 section for more details. 53 54 :func:`EvaluateMultipliers` Convert any string-specified (formula-based) multipliers to 55 numbers. Call this before using :func:`GenerateConstraints`. 56 At present only values in dict for phase (atom/cell) parameters 57 are used to evaluate multipliers containint formulae, 58 but this could be changed if needed. 59 60 :func:`GenerateConstraints` Generates the internally-used tables from constraints and 61 equivalences. Checks for internal consistency and repairs 62 problems where possible. See the 63 :ref:`Constraint Checking and Grouping <GenerateConstraints>` 64 and :ref:`Equivalence Checking<CheckEquivalences>` 65 sections for more details. 66 67 :func:`Map2Dict` To determine values for any parameters created in this module, 68 call Map2Dict. This will not apply contraints. 69 70 :func:`Dict2Map` To apply the constraints and equivalences, call this. 71 It takes values from the new independent parameters and 72 constraints, and applies them to the parameter dict. 73 74 :func:`Dict2Deriv` This determines derivatives on independent parameters 75 from those on dependent ones. 76 77 :func:`ComputeDepESD` Use ComputeDepESD to compute uncertainties on dependent variables. 78 79 :func:`VarRemapShow` Use this to show a summary of the parameter remapping. 80 Call after :func:`GenerateConstraints`. 81 ============================= =================================================================== 82 83 Types of constraints 84 -------------------- 85 86 There are four ways to specify constraints, as listed below. 87 Note that constraints are initially stored in the 88 main section of the GSAS-II data tree under heading ``Constraints``. 89 This dict has four keys, 'Hist', 'HAP', 'Global', and 'Phase', 90 each containing a list of constraints. An additional set of constraints 91 are generated for each phase based on symmetry considerations by calling 92 :func:`GSASIIstrIO.GetPhaseData`. 93 94 Note that in the constraints, as stored in the GSAS-II data tree, parameters 95 are stored as :class:`GSASIIobj.G2VarObj` objects, as these objects allow for 96 changes in numbering of phases, histograms and atoms since :class:`GSASIIobj.G2VarObj` objects 97 use random Id's for references. 98 When constraints are interpreted (in :func:`ProcessConstraints`), 99 these references are resolved to the numbered objects by looking up random Id's 100 so that the parameter object is converted to a string of form ``ph:hst:VARNAM:at``. 101 102 Constraints are initially stored as described in the 103 :ref:`constraint definitions <Constraint_definitions_table>`, where the last value in the 104 list determines which type of constraint is defined. 105 106 Alternate parameters (New Var) 107 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 108 109 Parameter redefinition ("New Var" constraints) 110 is done by creating an expression that relates several 111 parameters: :: 112 113 Mx1 * Px + My1 * Py +... = ::newvar1 114 Mx2 * Px + Mz2 * Pz + ... = ::newvar2 115 116 where Pj is a GSAS-II parameter name and Mjk is a constant (float) multiplier. 117 Alternately, multipliers Mjk can contain a formula (str) that will be evaluated prior 118 to the start of the refinement. In a formula, GSAS-II parameters will be replaced by the 119 value of the parameter before the formula is evaluated, so ``'np.cos(0::Ax:2)'`` is a valid 120 multiplier. At present, only phase (atom/cell) parameters are available for use in 121 a formula, from the GUI but this can be expanded if needed. 122 123 This type of constraint describes an alternate 124 degree of freedom where parameter Px and Py, etc. are varied to keep 125 their ratio 126 fixed according the expression. A new variable parameter is assigned to each degree of 127 freedom when refined. An example where this can be valuable is when 128 two parameters, P1 and P2, have similar values and are highly correlated. It is often better to create a new variable, Ps = P1 + P2, and refine Ps. 129 In the later stages of refinement, a second 130 variable, Pd = P1 - P2, can be defined and it can be seen if refining Pd is 131 supported by the data. Another use will be to define parameters that 132 express "irrep modes" in terms of the fundamental structural parameters. 133 134 The "New Var" constraints are stored as a type "f" 135 :ref:`constraint (see definitions)<Constraint_definitions_table>`. 136 137 Constrained parameters (Const) 138 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 139 140 A constraint on a set of variables can be supplied in the form of a 141 linear algebraic equation: :: 142 143 Nx1 * Px + Ny1 * Py +... = C1 144 145 where Cn is a constant (float), where Pj is a GSAS-II parameter name, 146 and where Njk is a constant multiplier (float) or a formula (str) that will be evaluated prior 147 to the start of the refinement. In a formula, GSAS-II parameters will be replaced by the 148 value of the parameter before the formula is evaluated, so ``'np.cos(0::Ax:2)'`` is a valid 149 multiplier. At present, only phase (atom/cell) parameters are available for use in 150 a formula, but this can be expanded if needed. 151 152 These equations set an interdependence between parameters. 153 Common uses of parameter constraints are to set rules that decrease the number of parameters, 154 such as restricting the sum of fractional occupancies for atoms that share 155 a site to sum to unity, thus reducing the effective number of variables by one. 156 Likewise, the Uiso value for a H atom "riding" on a C, N or O atom 157 can be related by a fixed offset (the so called B+1 "rule"). 158 159 The "Const" constraints are stored as a type "c" 160 :ref:`constraint (see definitions)<Constraint_definitions_table>`. 161 162 Equivalenced parameters (Equiv) 163 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 164 165 A simplifed way to set up a constraint equation is to define an equivalence, 166 which can be of form: :: 167 168 C1 * P1 = C2 * Py 169 170 or:: 171 172 C1 * P1 = C2 * P2 = C3 * P3 = ... 173 174 where Cn is a constant (float), where Pj is a GSAS-II parameter name. This 175 means that parameters Py (or P2 and P3) are determined from (or "slaved" to) 176 parameter P1. Alternately, equivalences can be created with :func:`StoreEquivalence` 177 where the multipliers can be a formula (str) that will be evaluated prior to the start of 178 the refinement. In a formula, GSAS-II parameters will be replaced by the value of the 179 parameter before the formula is evaluated, so a multiplier can be specifed as ``'2*np.cos(0::Ax:2)'``. 180 At present, only phase (atom/cell) parameters are available for use in 181 such a formula, but this can be expanded if needed. 182 183 The first parameter (P1 above) 184 is considered the independent variable 185 and the remaining parameters are dependent variables. The dependent variables 186 are then set from the independent variable. 187 188 Note that a constraint expression is conceptually identical to 189 defining constraint equations. 190 The previous set of equalities could also be written as a set of constraint 191 equations in this way: :: 192 193 C1 * P1 - C2 * P2 = 0 194 C1 * P1 - C3 * P3 = 0 195 ... 196 197 In practice, however, 198 equivalenced parameters are processed in a 199 different and more direct manner than constraint equations. 200 201 A parameter can be used in multiple 202 equivalences where it is an independent variable, 203 but if a parameter were used both as a dependent and independent variable then the order that 204 shifts are applied becomes potentially significant. As an example, in this case these two 205 equivalences are "chained":: 206 207 C1 * P1 = C2 * P2 208 C2 * P2 = C3 * P3 209 210 where P2 is both a dependent and independent variable. Likewise, if a parameter is used both in equivalences 211 and in "New Var" or "Const" constraints, it also becomes unclear how this should be processed. It is 212 possible to specify equivalences that conflict with constraints. 213 Should parameter be used as both a dependent and an independent variable or if a parameter is used both in 214 an the equivalence and in a "New Var" or "Const" constraints, the equivalence 215 is converted to a constraint (Const) to 216 avoid conflicts. The equivalences that require this are addressed in ::func:`GenerateConstraints` where 217 :func:`CheckEquivalences` is used to locate problematic variables in equivalences 218 and then change these equivalences to "Const" equations. Also, unneeded equivalences are removed. 219 220 For an example of how equivalences may be used, consider 221 a material that has **N** O atoms in the asymmetric unit, all in fairly similar bonding environments 222 and where the diffraction data are sparse. One may wish to reduce the complexity of the model fit to 223 these data by defining Uiso for all O atoms to be the same. This is done by selecting Uiso for any one O atom 224 as an independent variable in a equivalence and setting the remaining **N-1** other O atom Uiso 225 variables as dependent parameters with multipliers of 1. This will require that all O atom Uiso values 226 be identical. 227 The results of this refinement will be simpler to understand than if a set of 228 constraint equations is used, because the refined parameter (named as ``ph::Uiso:n``) will be the 229 independent variable, corresponding to the first O atom and all other variables would be 230 expressed in terms of that variable with a single Equivalence expression. 231 The alternate would require **N-1** constraint equations, leaving one degree of freedom with a 232 variable would that is likely only indirectly related to the Uiso values. 233 234 Equivalenced parameters ("EQUIV" constraints), when defined by users, 235 or when created to relate phases, are stored as a type "e" 236 :ref:`constraint (see definitions)<Constraint_definitions_table>`. 237 Symmetry-generated equivalences are generated prior 238 to display or refinement in :func:`GSASIIstrIO.GetPhaseData`. 239 These are not stored in the data tree. 240 241 Hold parameters (Fixed) 242 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 243 244 When parameters are refined where a single refinement flag determines that several variables 245 are refined at the same time (examples are: cell parameters, atom positions, anisotropic 246 displacement parameters, magnetic moments,...) it can be useful to specify that a 247 specific parameter should not be varied. These will most commonly be generated due to symmetry, 248 but under specific conditions, there may be other good reasons to constrain a parameter. 249 250 The "Hold" constraints are stored as a type "h" 251 :ref:`constraint (see definitions)<Constraint_definitions_table>`. 252 253 .. _Constraints_processing: 254 255 Constraint Processing 256 --------------------- 257 258 When constraints will be used or edited, they are processed using a series of 259 calls. This is done in GSAS-II from several locations: 260 261 * For error checking from the tree in :mod:`GSASIIconstrGUI`, 262 :func:`GSASIIconstrGUI.CheckConstraints` loads constraints from 263 the data tree. 264 265 * When the table of refined parameters is shown, constraints are also 266 processed in function :func:`GSASIIdataGUI.GSASII.OnShowLSParms` using 267 :func:`GSASIIconstrGUI.CheckConstraints` 268 269 * To write parameters in the Export sections of the program, 270 :func:`GSASIIIO.loadParmDict` loads results as well as constraints 271 from the tree. This works a bit differently from the above, so it 272 makes direct calls to the constraints routines. 273 274 * For error checking from a GPX file 275 :func:`GSASIIstrIO.ReadCheckConstraints` loads constraints 276 (called in :mod:`GSASIIdataGUI` and :mod:`GSASIIscriptable`), 277 which is similar to :func:`GSASIIconstrGUI.CheckConstraints`. 278 :func:`~GSASIIstrIO.ReadCheckConstraints` is called by 279 :meth:`GSASIIdataGUI.GSASII.OnRefine` and 280 :meth:`GSASIIdataGUI.GSASII.OnSeqRefine` 281 before constraints are generated for use in refinements so they can 282 be shown in the GUI. This is also called to check for errors in 283 :class:`GSASIIscriptable.G2Project`. 284 285 * To create the constraints for use in a refinement, in 286 :mod:`GSASIIstrMain`, functions :func:`GSASIIstrMain.Refine` and 287 :func:`GSASIIstrMain.SeqRefine` load and process the constraints again. 288 This is repeated here because :func:`~GSASIIstrMain.Refine` and 289 :func:`~GSASIIstrMain.SeqRefine` are intended to operate as stand-alone 290 routines that may be called directly. 291 292 * After sequential fits have been completed, the previously processed 293 constraint info is read from the sequential results section of the 294 data tree. Function 295 :func:`GSASIIseqGUI.UpdateSeqResults` displays the sequential results 296 table also processes constraints. 297 298 TODO: Note that G2stIO.makeTwinFrConstr is called only in one place. It probably needs to be included in all of the above. 299 300 When constraints are processed, the following steps are used: 301 302 #. Constraints are stored in separate lists in the data tree to 303 simplify their creation and their GUI display. 304 In the initial processing, all of the stored constraints are appended 305 into a single list. 306 307 #. Then :func:`InitVars` is used to initialize the global variables in 308 this module (:mod:`GSASIImapvars`). This may be done before the previous 309 step. 310 311 #. Then :func:`ProcessConstraints` is used to initially process the 312 constraints user-supplied constraints (from the data tree), 313 as described in :ref:`Constraint Reorganization <ProcessConstraints>`. 314 When constraints are read from a GPX file, rather than the data tree, use 315 :func:`GSASIIstrIO.ReadConstraints` (which calls :func:`ProcessConstraints`). 316 317 #. Symmetry-generated equivalences are then created in 318 :func:`GSASIIstrIO.GetPhaseData`, which also calls 319 :func:`GSASIIstrIO.cellVary` and for Pawley refinements 320 :func:`GSASIIstrIO.GetPawleyConstr`. These are entered directly into this 321 module's globals using :func:`StoreEquivalence`. 322 323 #. Constraints/equivalences are then checked for possible conflicts with 324 :func:`GenerateConstraints`, this requires grouping the constraints, 325 as described below. 326 327 #. :func:`GenerateConstraints` is then called to 328 create the constraints that will be used, 329 :ref:`see below <GenerateConstraints>` for more details. 330 331 #. For debugging constraints, :func:`VarRemapShow` can be called after 332 :func:`GenerateConstraints` to display the generated constraints. 333 334 .. _ProcessConstraints: 335 336 Constraint Reorganization (:func:`ProcessConstraints`) 337 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 338 339 :func:`ProcessConstraints` is used to initially process the 340 constraints from the list of dict entries. The "Const" and "New Var" are placed into two 341 lists (:data:`constrDict` and :data:`fixedList`) that are later used for parameter 342 grouping (in :func:`GenerateConstraints`). "Hold" and "Equivalence" constraints are 343 separated into separate storage. 344 345 For "**Const**" entries, 346 a dict with multiple entries is placed in :data:`constrDict` where 347 each dict key is the parameter name and the value is the multiplier for the parameter, 348 while :data:`fixedList` gets a string value corresponding to the constant value for 349 the expression. 350 351 For "**New Var**" entries, 352 a dict with multiple entries defined identically to 353 to that used in "Const" entries. The differences between "New Var" and "Const" entries is 354 that for "Const" entries, a constant value (as a string) is placed in :data:`fixedList` while 355 for "New Var" entries corresponding entry in :data:`fixedList` is None. 356 Also, one or two additional entries are created in the dict for "New Var" constraints: 357 an entry with key "_vary" is given the value of True or False 358 depending on the refinement flag setting; 359 an entry with key "_name" will be created if the "New Var" parameter has a supplied name. 360 361 For "**Hold**" entries, 362 User-supplied âHoldâ constraints are stored in global variable :data:`holdParmList`. 363 Initialized in :func:`InitVars`; set in :func:`StoreHold`. Type of hold is stored in 364 :data:`holdParmType`. 365 366 **Equivalences** are stored using :func:`StoreEquivalence` into this module's globals 367 (:data:`dependentParmList`, :data:`arrayList`, :data:`invarrayList`, :data:`indParmList`, 368 and :data:`symGenList`). 369 For each equivalence: 370 371 * a list with one entry, the name of the independent parameter is placed in :data:`indParmList`; 372 * a list with one or more parameter name is placed in :data:`dependentParmList`; 373 * the value None is added to :data:`arrayList`; 374 * a list of multipliers for each dependent variable is placed in :data:`invarrayList` 375 * an entry of either True or False is placed in :data:`symGenList`, where True indicates that the entry has been generated from symmetry. 376 377 The output from :func:`ProcessConstraints` will have the form as below, 378 where the first entry is a "Const" and the second is a "New Var". 379 380 .. code-block:: python 381 382 constrDict = [ 383 {'0:12:Scale': 2.0, '0:14:Scale': 4.0, '0:13:Scale': 3.0, '0:0:Scale': 0.5}, 384 {'2::C(10,6,1)': 1.0, '1::C(10,6,1)': 1.0, '_vary':True}] 385 fixedList = ['5.0', None] 386 387 .. _GenerateConstraints: 388 389 Constraint Checking and Grouping (:func:`GenerateConstraints`) 390 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 391 392 Function :func:`GenerateConstraints` is used to 393 process the parameter equivalences and constraint lists created in 394 :func:`ProcessConstraints` (``constrDict`` and ``fixedList``). :func:`GenerateConstraints` 395 is used to generate error/warning messages, to set up lists that are used to show this 396 information for the GUI (using :func:`getConstrError`) and to 397 generate the information stored in :ref:`global arrays <GlobalVariables>` that are used later to 398 apply the constraints. 399 400 When a sequential refinement is in progress, the constraints are scanned for parameters 401 that have a wildcard (*) for the histogram number, such as 1:*:Scale which would refer 402 to the phase fraction for Phase ` in every histogram. The "*" will be replaced with 403 the number of the current histogram. 404 405 Equivalences are checked with :func:`CheckEquivalences` (described in detail 406 :ref:`below <CheckEquivalences>`). This may result in the creation of additional "Hold" 407 and "Constr" constraints being added to the ``constrDict`` and ``fixedList`` lists. 408 409 The "Const" and "New Var" constraint expressions are then scanned for problems: 410 411 Constraints cannot be processed without changes if any of the terms within have the following: 412 413 * **Undefined parameters** or **Multiplier of zero** 414 415 If any parameters in a constraint are undefined or have a parameter multiplier of zero 416 the constraint group is not used. 417 418 If some, but not all, parameters in a constraint are undefined or have a parameter 419 multiplier of zero and remaining valid parameters will be set as "Hold". 420 One exception: atom position constraints (p::dA[xyz]:#) will be assumed as zero. 421 422 * **Hold (Fixed) parameters** and **Unvaried parameters**: New Var constraints 423 424 If any parameters in a new var constraint are either not refined, or are marked as "Hold" 425 the constraint can not be varied. Any parameters in that group will be set as "Hold" 426 427 * **Hold (Fixed) parameters** and **Unvaried parameters**: Constraint Equations 428 429 If any parameters in a constraint equation are either not refined, or are marked as "Hold" 430 those parameters can be removed from the constraint, with an adjustment of the equation 431 sum. 432 433 Constraint expressions ("Const" and "New Var") are sorted by routine :func:`GroupConstraints` into 434 groups so that each group contains the minimum number of entries that 435 ensures each parameter is referenced in only one group. 436 This is done by scanning the 437 list of dicts in :data:`constrDict` one by one and making a list 438 of parameters used in that constraint expression. Any expression that contains 439 a parameter in that list is added to the current group and those 440 parameters are added to this list of parameters. The list of ungrouped 441 expressions is then scanned again until no more expressions are added to the 442 current group. This process is repeated until every expression has been 443 placed in a group. Function :func:`GroupConstraints` returns two lists of lists. 444 The first has, for each group, a list of the indices in :data:`constrDict` 445 that comprise the group (there can be only one). The second list contains, 446 for each group, the unique parameter names in that group. 447 448 Each constraint group is then processed. First, wildcard parameters are 449 renamed (in a sequential refinement). Any held parameters that are used 450 in constraints are noted as errors. The number of refined parameters and 451 the number of parameters that are not defined in the current refinement are 452 also noted. It is fine if all parameters in a group are not defined or all are 453 not varied, but if some are defined and others not or some are varied and 454 others not, this constitutes an error. 455 456 The contents of each group is then examined. Groups with a single 457 parameter (holds) are ignored. Then for each group, the number 458 of parameters in the group (Np) and the number of expressions in the 459 group (Nc) are counted and for each expression. If Nc > Np, then the constraint 460 is overdetermined, which also constitutes an error. 461 462 The parameter multipliers for each expression are then assembled: 463 464 :: 465 466 M1a * P1 + M2a * P2 +... Mka * Pk 467 M1b * P1 + M2b * P2 +... Mkb * Pk 468 ... 469 M1j * P1 + M2j * P2 +... Mkj * Pk 470 471 472 From this it becomes possible to create a Nc x Np matrix, which is 473 called the constraint matrix: 474 475 .. math:: 476 477 \\left( \\begin{matrix} 478 M_{1a} & M_{2a} &... & M_{ka} \\\\ 479 M_{1b} & M_{2b} &... & M_{kb} \\\\ 480 ... \\\\ 481 M_{1j} & M_{2j} &... & M_{kj} 482 \\end{matrix}\\right) 483 484 When Nc<Np, then additional rows need to be added to the matrix and to 485 the vector that contains the value for each row (:data:`fixedList`) where 486 values are ``None`` for New Vars and a constant for fixed values. 487 This then can describe a system of Np simultaneous equations: 488 489 .. math:: 490 491 \\left( \\begin{matrix} 492 M_{1a} & M_{2a} &... & M_{ka} \\\\ 493 M_{1b} & M_{2b} &... & M_{kb} \\\\ 494 ... \\\\ 495 M_{1j} & M_{2j} &... & M_{kj} 496 \\end{matrix}\\right) 497 \\left( \\begin{matrix} 498 P_{1} \\\\ 499 P_{2} \\\\ 500 ... \\\\ 501 P_{k} 502 \\end{matrix}\\right) 503 = 504 \\left( \\begin{matrix} 505 C_{1} & C_{2} & ... & C_{k} 506 \\end{matrix}\\right) 507 508 This is done by creating a square matrix from the group using 509 :func:`_FillArray`. The top Nc rows in the matrix are filled 510 as described above. Then :func:`_RowEchelon` is used to see if 511 those entries in the matrix can be coverted to row-echelon form. This 512 will raise an Exception there is linear dependence between the initial Nc rows 513 (which means that no matter what values are used for any remaining rows, that the matrix 514 will be singular). If that is not the case and Nc<Np then any remaining rows that 515 were not specified are filled in. For each of these rows, first only the 516 diagonal element in that row of the matrix is set to 1 517 and the upper portion of the matrix is again tested with :func:`_RowEchelon` 518 to check for linear independence. This is likely to be non-singular, 519 but should :func:`_RowEchelon` fail, 520 :func:`_FillArray` will then try setting each other element in that row to either 521 1 or -1. One of those options should be linearly independent from every other 522 row of the matrix. 523 524 The 525 `Gram-Schmidt process <http://en.wikipedia.org/wiki/Gram-Schmidt>`_, 526 implemented in :func:`GramSchmidtOrtho`, is used to find orthonormal unit 527 vectors which are used to replace the remaining Np-Nc rows of the matrix. This will fail with 528 a ``ConstraintException`` if this is not possible (singular matrix), but that would be 529 unexpected since the matrix could be converted to row-echelon form. The 530 Gram-Schmidt result is placed in :data:`constrArr` as a numpy array. 531 532 Rows in the matrix corresponding to "New Var" constraints and those that 533 were generated by the Gram-Schmidt process are provided with parameter names. 534 These names are generated using :data:`paramPrefix`, which is set to ``"::constr"``, 535 plus a number to make the new parameter name unique, 536 unless a name was specified for the 537 "New Var" entry by using a ``"_name"`` element in the constraint dict. 538 539 Finally the parameters used as input to the constraint are placed in 540 this module's globals 541 :data:`dependentParmList` and the constraint matrix is 542 placed in into :data:`arrayList`. This can be used to compute 543 the initial values for "New Var" parameters. The inverse of the 544 constraint matrix is placed in :data:`invarrayList` and a list 545 of the "New Var" parameters and a list of the fixed values (as str's) 546 is placed in :data:`indParmList`. 547 Finally the appropriate entry in :data:`symGenList` is set to 548 False to indicate that this is not a symmetry generated constraint. 549 550 .. _CheckEquivalences: 551 552 Equivalence Checking and Reorganization (:func:`CheckEquivalences`) 553 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 554 555 Equivalences need to be checked for usages that could be internally conflicted 556 or have possible conflicts with other constraints. 557 558 **Mixed parameter use:** 559 560 **Note** that cycling through the equivalences may be needed to find all mixed-use 561 parameters, see below. 562 563 * A parameter should not show up as a dependent variable in two equivalence expressions, 564 such as:: 565 566 ::x1 -> ::x3 567 ::x2 -> ::x3 568 569 This will be processed by turning the equivalences into two constraint equations:: 570 571 ::x1 - ::x3 = 0 572 ::x2 - ::x3 = 0 573 574 which can be satisfied when ``::x1 = ::x2 = ::x3``. If ``::x1`` and ``::x2`` had been 575 intended to be independent parameters, then the above equivalences would be conflict and 576 cannot be statisfied. 577 578 * If a parameter is used both as an independent and as a dependent variable (*chaining*), 579 as is in these two equivalence expressions:: 580 581 ::x1 -> ::x2 & ::x4 582 ::x2 -> ::x3 583 584 This can also be addressed by turning these equivalences into three constraint equations:: 585 586 ::x1 - ::x2 = 0 587 ::x1 - ::x4 = 0 588 ::x2 - ::x3 = 0 589 590 which can be satisfied when ``::x1 = ::x2 = ::x3 = ::x4`` 591 592 * Use of parameters in both equivalences and "Const" or "New Var" constraint expressions makes 593 logical sense:: 594 595 ::x1 -> ::x2 & ::x4 596 ::x2 + ::x3 = 0 597 598 This can also be addressed by turning the equivalence into two constraint equations:: 599 600 ::x1 - ::x2 = 0 601 ::x1 - ::x4 = 0 602 603 With the addition of the "Const" equation (``::x2 + ::x3 = 0``), the solution will require 604 ``::x1 = ::x2 = -1.0*::x3 = ::x4`` 605 606 * Cycling is needed to find all equivalences that must be converted. 607 Consider this set of constraints:: 608 609 ::x2 + ::x3 = 0 610 ::x1 -> ::x2 611 ::x1 -> ::x4 612 613 In the first pass the equivalence with ``::x2`` would be converted to a "Const" constraint 614 and in the second pass 615 the other equivalence with ``::x1`` would be converted. 616 617 618 **Mixing Hold (Fixed) parameters in equivalences** 619 620 * If one parameter (or more) is designated as a "Hold" in an equivalence, then all parameters in that 621 equivalence cannot be varied. Considering this equivalence:: 622 623 ::x1 -> ::x2 & ::x4 624 625 If any of the three parameters (``::x1``, ``::x2``, or `::x4`) are marked as Hold, then 626 the other two parameters may not be varied and will also be set with a "Hold". 627 628 629 **Unvaried parameters in equivalences** 630 631 * If no parameters in an equivalence are varied, then the equivalence is ignored. 632 633 * If only some parameters are marked as varied then 634 *none of the parameters can be varied*; any varied parameters will be set with a "Hold". 635 636 637 **Undefined parameters in equivalences** 638 639 Parameters may be placed in equivalences that are not actually defined in a project. 640 This can occur in two ways. If an equivalence is created in the GUI for a parameter that 641 is later supplanted with a different model (for example, changing from isotropic size 642 broadening to uniaxial broadening replaces the isotropic broadening term with two different 643 uniaxial terms) or symmetry may require restrictions on anisotropic ADPs that are not 644 in use). 645 646 * If the independent parameter is undefined, then any dependent parameters that are defined 647 are set as "Hold" and the equivalence is ignored. 648 649 * If all dependent parameters are undefined, then the equivalence is ignored. 650 651 * If a dependent parameter is undefined, then that parameter is dropped from the equivalence. 652 653 654 **Multiplier of zero in equivalences** 655 656 Any dependent parameter that has a multiplier of zero will be dropped from the equivalence. 657 If no terms remain, then the equivalence is ignored. (Independent parameters do not 658 have a multiplier). 659 660 661 .. _GlobalVariables: 662 663 *Global Variables* 664 ------------------ 665 666 This module uses a number of global variables. One set is used to store the 667 constraints and equivalences after processing by :func:`StoreEquivalence` and 668 :func:`GenerateConstraints`. 669 These globals are expected to be used only by this module's (:mod:`GSASIImapvars`) internal routines. 670 671 Lists with information from Constraint Equation and New Var constraints. Each entry 672 in these variables is related to a group of constraints. 673 674 .. tabularcolumns:: |l|p{4.5in}| 675 676 ============================= =================================================================== 677 variable explanation 678 ============================= =================================================================== 679 :data:`dependentParmList` a list containing group of lists of 680 parameters used in the group. 681 The columns of the matrices in :data:`arrayList` match 682 the order of parameters here. 683 Note that parameters listed in 684 dependentParmList will not be included in the Hessian as their 685 derivatives will not affect the model 686 687 :data:`indParmList` a list containing groups of variables or constants matching 688 the columns of the matrices in :data:`invarrayList`. 689 690 :data:`arrayList` a list containing group of relationship matrices to relate 691 parameters in dependentParmList to those in indParmList. 692 693 :data:`invarrayList` a list containing group of relationship matrices to relate 694 parameters in indParmList to those in dependentParmList. 695 Unlikely to be used externally. 696 697 :data:`symGenList` a list of boolean values that will be True to indicate 698 that an equivalence was generated internally GSAS-II 699 meaning it is generated based on symmetry, twining 700 or Pawley overlap. 701 702 ============================= =================================================================== 703 704 Lists with information from Hold and Equivalence constraints. Each entry 705 in these variables is related to a group of constraints. 706 707 .. tabularcolumns:: |l|p{4.5in}| 708 709 ============================= =================================================================== 710 variable explanation 711 ============================= =================================================================== 712 :data:`holdParmList` a list of parameters that have been marked as "Hold". 713 Unlikely to be accessed outside this module. 714 Initialized in :func:`InitVars`; set in :func:`StoreHold`. 715 716 :data:`holdParmType` The reason why a parameter has been marked as "Hold". 717 Unlikely to be accessed outside this module. 718 Initialized in :func:`InitVars`; set in :func:`StoreHold`. 719 720 :data:`constrParms` dict with lists of variables in equivalences, 721 constraint equations and new var expressions. 722 Used within :func:`GetIndependentVars`, 723 and :func:`GetDependentVars`. 724 Best if not referenced outside this module. 725 Contains elements: 726 727 * 'dep-equiv': dependent parameters set by equivalences 728 * 'dep-constr': dependent parameters set by 729 constraint equations or new var expressions 730 * 'indep-equiv': dependent parameters used in equivalences 731 * 'indep-constr': dependent parameters created from 732 constraint equations or new var expressions 733 734 :data:`saveVaryList` a list of the varied parameters used when constraints 735 were last processed. 736 ============================= =================================================================== 737 738 739 A second set of global variables are set in :func:`GenerateConstraints` with lists of parameter 740 names from equivalences and constraints. Used in :func:`CheckEquivalences` and 741 :func:`getConstrError`. 742 743 .. tabularcolumns:: |l|p{4.5in}| 744 745 ============================= =================================================================== 746 variable explanation 747 ============================= =================================================================== 748 :data:`depVarList` a list of the parameters used in equivalences as dependent 749 parameters for all equivalences initially specified (including 750 those to be reclassified as "Constr" constraints.) 751 752 :data:`indepVarList` a list of the parameters used in equivalences as independent 753 parameters for all equivalences initially specified (including 754 those to be reclassified as "Constr" constraints.) 755 756 :data:`constrVarList` a list of the parameters that are used in "Constr" or 757 "New Var" constraints. Does not include those in equivalences 758 to be reclassified as "Constr" constraints.) 759 ============================= =================================================================== 760 761 762 A third set of global variables to store equivalence warning information. 763 Set in :func:`CheckEquivalences` and :func:`GenerateConstraints`. 764 Used in :func:`getConstrError` to display warning messages. 765 766 .. tabularcolumns:: |l|p{4.5in}| 767 768 ============================= =================================================================== 769 variable explanation 770 ============================= =================================================================== 771 :data:`convVarList` parameters in equivalences that were converted to "Const" 772 constraints 773 774 :data:`multdepVarList` parameters used as dependent parameters in equivalences 775 multiple times 776 777 :data:`unvariedParmsList` parameters used in equivalences and constraints 778 that are not varied 779 780 :data:`undefinedVars` parameters used in equivalences 781 that are not defined in the parameter dict (parmDict) 782 783 :data:`groupErrors` parameters in constraints that cause grouping errors 784 ============================= =================================================================== 785 786 787 788 *GSASIImapvars Routines/variables* 789 --------------------------------------- 12 Classes and routines defined in :mod:`GSASIImapvars` follow. 790 13 791 14 Note that parameter names in GSAS-II are strings of form ``<ph#>:<hst#>:<nam>`` or ``<ph#>::<nam>:<at#>`` … … 793 16 ``<nam>`` is a name that determines the parameter type (see :func:`GSASIIobj.CompileVarDesc`). When 794 17 stored in the data tree, parameters are saved as :class:`GSASIIobj.G2VarObj` objects 795 so that they can be resolved if the phase/histogram order changes. 796 18 so that they can be resolved if the phase/histogram order changes. 797 19 """ 20 # Note that documentation for GSASIImapvars.py has been moved 21 # to file docs/source/GSASIImapvars.rst 798 22 799 23 from __future__ import division, print_function -
trunk/GSASIImath.py
r5556 r5572 9 9 ########### SVN repository information ################### 10 10 ''' 11 *GSASIImath: computation module* 12 ================================ 13 14 Routines for least-squares minimization and other stuff 15 11 Routines defined in :mod:`GSASIImath` follow. 16 12 ''' 13 17 14 from __future__ import division, print_function 18 15 import random as rn -
trunk/GSASIImpsubs.py
r5114 r5572 1 1 # -*- coding: utf-8 -*- 2 '''3 *GSASIImpsubs: routines used in multiprocessing*4 -------------------------------------------------5 6 The routines here are called either directly when GSAS-II is used without multiprocessing7 or in separate cores when multiprocessing is used.8 9 These routines are designed to be used in one of two ways:10 11 * when multiprocessing is12 enabled (see global variable useMP) the computational routines are called in13 separate Python interpreter that is created and then deleted after use.14 15 * when useMP is False, these routines are called directly from the main "thread".16 17 Note that :func:`GSASIImpsubs.InitMP` should be called before any of the other routines18 in this module are used.19 '''20 2 ########### SVN repository information ################### 21 3 # $Date$ … … 25 7 # $Id$ 26 8 ########### SVN repository information ################### 9 ''' 10 The routines here are called either directly when GSAS-II is used without multiprocessing 11 or in separate cores when multiprocessing is used. 12 13 These routines are designed to be used in one of two ways: 14 15 * when multiprocessing is 16 enabled (see global variable useMP) the computational routines are called in 17 separate Python interpreter that is created and then deleted after use. 18 19 * when useMP is False, these routines are called directly from the main "thread". 20 21 Note that :func:`GSASIImpsubs.InitMP` should be called before any of the other routines 22 in this module are used. 23 ''' 27 24 from __future__ import division, print_function 28 25 import multiprocessing as mp -
trunk/GSASIIobj.py
r5571 r5572 10 10 11 11 ''' 12 *GSASIIobj: Data objects* 13 ========================= 14 15 This module defines and/or documents the data structures used in GSAS-II, as well 16 as provides misc. support routines. 17 18 .. Next command allows \\AA to be used in HTML 19 20 .. only:: html 21 22 :math:`\renewcommand\AA{\text{Ã 23 }}` 24 25 .. _VarNames_table: 26 27 .. index:: 28 single: Parameter names 29 single: GSAS-II variable naming 30 31 Variable names in GSAS-II 32 ---------------------------- 33 34 Parameter are named using the following pattern, 35 ``p:h:<var>:n``, where ``<var>`` is a variable name, as shown in the following table. Also, 36 ``p`` is the phase number, ``h`` is the histogram number, 37 and ``n`` is the atom parameter number 38 If a parameter does not depend on a histogram, phase or atom, ``h``, ``p`` and/or ``n`` will be omitted, 39 so ``p::<var>:n``, ``:h:<var>`` and ``p:h:<var>`` are all valid names. 40 41 .. include:: vars.rst 42 43 .. _Constraints_table: 44 45 .. index:: 46 single: Constraints object description 47 single: Data object descriptions; Constraints 48 49 Constraints Tree Item 50 ---------------------- 51 52 Constraints are stored in a dict, separated into groups. 53 Note that parameter are named in the following pattern, 54 p:h:<var>:n, where p is the phase number, h is the histogram number 55 <var> is a variable name and n is the parameter number. 56 If a parameter does not depend on a histogram or phase or is unnumbered, that 57 number is omitted. 58 Note that the contents of each dict item is a List where each element in the 59 list is a :ref:`constraint definition objects <Constraint_definitions_table>`. 60 The constraints in this form are converted in 61 :func:`GSASIImapvars.ProcessConstraints` to the form used in :mod:`GSASIImapvars` 62 63 The keys in the Constraints dict are: 64 65 .. tabularcolumns:: |l|p{4.5in}| 66 67 ========== ==================================================== 68 key explanation 69 ========== ==================================================== 70 Hist This specifies a list of constraints on 71 histogram-related parameters, 72 which will be of form :h:<var>:n. 73 HAP This specifies a list of constraints on parameters 74 that are defined for every histogram in each phase 75 and are of form p:h:<var>:n. 76 Phase This specifies a list of constraints on phase 77 parameters, 78 which will be of form p::<var>:n. 79 Global This specifies a list of constraints on parameters 80 that are not tied to a histogram or phase and 81 are of form ::<var>:n 82 ========== ==================================================== 83 84 .. _Constraint_definitions_table: 85 86 .. index:: 87 single: Constraint definition object description 88 single: Data object descriptions; Constraint Definition 89 90 Each constraint is defined as an item in a list. Each constraint is of form:: 91 92 [[<mult1>, <var1>], [<mult2>, <var2>],..., <fixedval>, <varyflag>, <constype>] 93 94 Where the variable pair list item containing two values [<mult>, <var>], where: 95 96 * <mult> is a multiplier for the constraint (float) 97 * <var> a :class:`G2VarObj` object. (Note that in very old .gpx files this might be a str with a variable name of form 'p:h:name[:at]') 98 99 Note that the last three items in the list play a special role: 100 101 * <fixedval> is the fixed value for a `constant equation` (``constype=c``) 102 constraint or is None. For a `New variable` (``constype=f``) constraint, 103 a variable name can be specified as a str (used for externally 104 generated constraints) 105 * <varyflag> is True or False for `New variable` (``constype=f``) constraints 106 or is None. This indicates if this variable should be refined. 107 * <constype> is one of four letters, 'e', 'c', 'h', 'f' that determines the type of constraint: 108 109 * 'e' defines a set of equivalent variables. Only the first variable is refined (if the 110 appropriate refine flag is set) and and all other equivalent variables in the list 111 are generated from that variable, using the appropriate multipliers. 112 * 'c' defines a constraint equation of form, 113 :math:`m_1 \\times var_1 + m_2 \\times var_2 + ... = c` 114 * 'h' defines a variable to hold (not vary). Any variable on this list is not varied, 115 even if its refinement flag is set. Only one [mult,var] pair is allowed in a hold 116 constraint and the mult value is ignored. 117 This is of particular value when needing to hold one or more variables where a 118 single flag controls a set of variables such as, coordinates, 119 the reciprocal metric tensor or anisotropic displacement parameter. 120 * 'f' defines a new variable (function) according to relationship 121 :math:`newvar = m_1 \\times var_1 + m_2 \\times var_2 + ...` 122 123 .. _Covariance_table: 124 125 .. index:: 126 single: Covariance description 127 single: Data object descriptions; Covariance 128 129 Covariance Tree Item 130 -------------------- 131 132 The Covariance tree item has results from the last least-squares run. They 133 are stored in a dict with these keys: 134 135 .. tabularcolumns:: |l|l|p{4in}| 136 137 ============= =============== ==================================================== 138 key sub-key explanation 139 ============= =============== ==================================================== 140 newCellDict \\ (dict) ith lattice parameters computed by 141 :func:`GSASIIstrMath.GetNewCellParms` 142 title \\ (str) Name of gpx file(?) 143 variables \\ (list) Values for all N refined variables 144 (list of float values, length N, 145 ordered to match varyList) 146 sig \\ (list) Uncertainty values for all N refined variables 147 (list of float values, length N, 148 ordered to match varyList) 149 varyList \\ (list of str values, length N) List of directly refined variables 150 151 newAtomDict \\ (dict) atom position values computed in 152 :func:`GSASIIstrMath.ApplyXYZshifts` 153 Rvals \\ (dict) R-factors, GOF, Marquardt value for last 154 refinement cycle 155 \\ Nobs (int) Number of observed data points 156 \\ Rwp (float) overall weighted profile R-factor (%) 157 \\ chisq (float) :math:`\\sum w*(I_{obs}-I_{calc})^2` 158 for all data. 159 Note: this is not the reduced :math:`\\chi^2`. 160 \\ lamMax (float) Marquardt value applied to Hessian diagonal 161 \\ GOF (float) The goodness-of-fit, aka square root of 162 the reduced chi squared. 163 covMatrix \\ (np.array) The (NxN) covVariance matrix 164 ============= =============== ==================================================== 165 166 .. _Phase_table: 167 168 .. index:: 169 single: Phase object description 170 single: Data object descriptions; Phase 171 172 Phase Tree Items 173 ---------------- 174 175 Phase information is stored in the GSAS-II data tree as children of the 176 Phases item in a dict with keys: 177 178 .. tabularcolumns:: |l|l|p{4in}| 179 180 ========== =============== ===================================================================================================== 181 key sub-key explanation 182 ========== =============== ===================================================================================================== 183 General \\ (dict) Overall information for the phase 184 \\ 3Dproj (list of str) projections for 3D pole distribution plots 185 \\ AngleRadii (list of floats) Default radius for each atom used to compute 186 interatomic angles 187 \\ AtomMass (list of floats) Masses for atoms 188 \\ AtomPtrs (list of int) four locations (cx,ct,cs & cu) to use to pull info 189 from the atom records 190 \\ AtomTypes (llist of str) Atom types 191 \\ BondRadii (list of floats) Default radius for each atom used to compute 192 interatomic distances 193 \\ Cell Unit cell parameters & ref. flag 194 (list with 8 items. All but first item are float.) 195 196 0: cell refinement flag (True/False), 197 198 1-3: a, b, c, (:math:`\\AA`) 199 200 4-6: alpha, beta & gamma, (degrees) 201 202 7: volume (:math:`\\AA^3`) 203 204 \\ Color (list of (r,b,g) triplets) Colors for atoms 205 \\ Compare (dict) Polygon comparison parameters 206 \\ Data plot type (str) data plot type ('Mustrain', 'Size' or 207 'Preferred orientation') for powder data 208 \\ DisAglCtls (dDict) with distance/angle search controls, 209 which has keys 'Name', 'AtomTypes', 210 'BondRadii', 'AngleRadii' which are as above 211 except are possibly edited. Also contains 212 'Factors', which is a 2 element list with 213 a multiplier for bond and angle search range 214 [typically (0.85,0.85)]. 215 \\ F000X (float) x-ray F(000) intensity 216 \\ F000N (float) neutron F(000) intensity 217 \\ Flip (dict) Charge flip controls 218 \\ HydIds (dict) geometrically generated hydrogen atoms 219 \\ Isotope (dict) Isotopes for each atom type 220 \\ Isotopes (dict) Scattering lengths for each isotope 221 combination for each element in phase 222 \\ MCSA controls (dict) Monte Carlo-Simulated Annealing controls 223 \\ Map (dict) Map parameters 224 \\ Mass (float) Mass of unit cell contents in g/mol 225 \\ Modulated (bool) True if phase modulated 226 \\ Mydir (str) Directory of current .gpx file 227 \\ Name (str) Phase name 228 \\ NoAtoms (dict) Number of atoms per unit cell of each type 229 \\ POhkl (list) March-Dollase preferred orientation direction 230 \\ Pawley dmin (float) maximum Q (as d-space) to use for Pawley extraction 231 \\ Pawley dmax (float) minimum Q (as d-space) to use for Pawley extraction 232 \\ Pawley neg wt (float) Restraint value for negative Pawley intensities 233 \\ SGData (object) Space group details as a 234 :ref:`space group (SGData) <SGData_table>` 235 object, as defined in :func:`GSASIIspc.SpcGroup`. 236 \\ SH Texture (dict) Spherical harmonic preferred orientation parameters 237 \\ Super (int) dimension of super group (0,1 only) 238 \\ Type (str) phase type (e.g. 'nuclear') 239 \\ Z (dict) Atomic numbers for each atom type 240 \\ doDysnomia (bool) flag for max ent map modification via Dysnomia 241 \\ doPawley (bool) Flag for Pawley intensity extraction 242 \\ vdWRadii (dict) Van der Waals radii for each atom type 243 ranId \\ (int) unique random number Id for phase 244 pId \\ (int) Phase Id number for current project. 245 Atoms \\ (list of lists) Atoms in phase as a list of lists. The outer list 246 is for each atom, the inner list contains varying 247 items depending on the type of phase, see 248 the :ref:`Atom Records <Atoms_table>` description. 249 Drawing \\ (dict) Display parameters 250 \\ Atoms (list of lists) with an entry for each atom that is drawn 251 \\ Plane (list) Controls for contour density plane display 252 \\ Quaternion (4 element np.array) Viewing quaternion 253 \\ Zclip (float) clipping distance in :math:`\\AA` 254 \\ Zstep (float) Step to de/increase Z-clip 255 \\ atomPtrs (list) positions of x, type, site sym, ADP flag in Draw Atoms 256 \\ backColor (list) background for plot as and R,G,B triplet 257 (default = [0, 0, 0], black). 258 \\ ballScale (float) Radius of spheres in ball-and-stick display 259 \\ bondList (dict) Bonds 260 \\ bondRadius (float) Radius of binds in :math:`\\AA` 261 \\ cameraPos (float) Viewing position in :math:`\\AA` for plot 262 \\ contourLevel (float) map contour level in :math:`e/\\AA^3` 263 \\ contourMax (float) map contour maximum 264 \\ depthFog (bool) True if use depthFog on plot - set currently as False 265 \\ ellipseProb (float) Probability limit for display of thermal 266 ellipsoids in % . 267 \\ magMult (float) multiplier for magnetic moment arrows 268 \\ mapSize (float) x & y dimensions of contourmap (fixed internally) 269 \\ modelView (4,4 array) from openGL drawing transofmation matrix 270 \\ oldxy (list with two floats) previous view point 271 \\ radiusFactor (float) Distance ratio for searching for bonds. Bonds 272 are located that are within r(Ra+Rb) and (Ra+Rb)/r 273 where Ra and Rb are the atomic radii. 274 \\ selectedAtoms (list of int values) List of selected atoms 275 \\ showABC (bool) Flag to show view point triplet. True=show. 276 \\ showHydrogen (bool) Flag to control plotting of H atoms. 277 \\ showRigidBodies (bool) Flag to highlight rigid body placement 278 \\ showSlice (bool) flag to show contour map 279 \\ sizeH (float) Size ratio for H atoms 280 \\ unitCellBox (bool) Flag to control display of the unit cell. 281 \\ vdwScale (float) Multiplier of van der Waals radius for display of vdW spheres. 282 \\ viewDir (np.array with three floats) cartesian viewing direction 283 \\ viewPoint (list of lists) First item in list is [x,y,z] 284 in fractional coordinates for the center of 285 the plot. Second item list of previous & current 286 atom number viewed (may be [0,0]) 287 ISODISTORT \\ (dict) contains controls for running ISODISTORT and results from it 288 \\ ISOmethod (int) ISODISTORT method (currently 1 or 4; 2 & 3 not implemented in GSAS-II) 289 \\ ParentCIF (str) parent cif file name for ISODISTORT method 4 290 \\ ChildCIF (str) child cif file name for ISODISTORT method 4 291 \\ SGselect (dict) selection list for lattice types in radio result from ISODISTORT method 1 292 \\ selection (int) chosen selection from radio 293 \\ radio (list) results from ISODISTORT method 1 294 \\ ChildMatrix (3x3 array) transformation matrix for method 3 (not currently used) 295 \\ ChildSprGp (str) child space group for method 3 (not currently used) 296 \\ ChildCell (str) cell ordering for nonstandard orthorhombic ChildSprGrp in method 3 (not currently used) 297 \\ G2ModeList (list) ISODISTORT mode names 298 \\ modeDispl (list) distortion mode values; refinable parameters 299 \\ ISOmodeDispl (list) distortion mode values as determined in method 4 by ISODISTORT 300 \\ NormList (list) ISODISTORT normalization values; to convert mode value to fractional coordinate dsplacement 301 \\ G2parentCoords (list) full set of parent structure coordinates transformed to child structure; starting basis for mode displacements 302 \\ G2VarList (list) 303 \\ IsoVarList (list) 304 \\ G2coordOffset (list) only adjustible set of parent structure coordinates 305 \\ G2OccVarList (list) 306 \\ Var2ModeMatrix (array) atom variable to distortion mode transformation 307 \\ Mode2VarMatrix (array) distortion mode to atom variable transformation 308 \\ rundata (dict) saved input information for use by ISODISTORT method 1 309 310 RBModels \\ Rigid body assignments (note Rigid body definitions 311 are stored in their own main top-level tree entry.) 312 RMC \\ (dict) RMCProfile, PDFfit & fullrmc controls 313 Pawley ref \\ (list) Pawley reflections 314 Histograms \\ (dict of dicts) The key for the outer dict is 315 the histograms tied to this phase. The inner 316 dict contains the combined phase/histogram 317 parameters for items such as scale factors, 318 size and strain parameters. The following are the 319 keys to the inner dict. (dict) 320 \\ Babinet (dict) For protein crystallography. Dictionary with two 321 entries, 'BabA', 'BabU' 322 \\ Extinction (list of float, bool) Extinction parameter 323 \\ Flack (list of [float, bool]) Flack parameter & refine flag 324 \\ HStrain (list of two lists) Hydrostatic strain. The first is 325 a list of the HStrain parameters (1, 2, 3, 4, or 6 326 depending on unit cell), the second is a list of boolean 327 refinement parameters (same length) 328 \\ Histogram (str) The name of the associated histogram 329 \\ Layer Disp (list of [float, bool]) Layer displacement in beam direction & refine flag 330 \\ LeBail (bool) Flag for LeBail extraction 331 \\ Mustrain (list) Microstrain parameters, in order: 332 333 0. Type, one of u'isotropic', u'uniaxial', u'generalized' 334 1. Isotropic/uniaxial parameters - list of 3 floats 335 2. Refinement flags - list of 3 bools 336 3. Microstrain axis - list of 3 ints, [h, k, l] 337 4. Generalized mustrain parameters - list of 2-6 floats, depending on space group 338 5. Generalized refinement flags - list of bools, corresponding to the parameters of (4) 339 \\ Pref.Ori. (list) Preferred Orientation. List of eight parameters. 340 Items marked SH are only used for Spherical Harmonics. 341 342 0. (str) Type, 'MD' for March-Dollase or 'SH' for Spherical Harmonics 343 1. (float) Value 344 2. (bool) Refinement flag 345 3. (list) Preferred direction, list of ints, [h, k, l] 346 4. (int) SH - number of terms 347 5. (dict) SH - 348 6. (list) SH 349 7. (float) SH 350 \\ Scale (list of [float, bool]) Phase fraction & refine flag 351 \\ Size List of crystallite size parameters, in order: 352 353 0. (str) Type, one of u'isotropic', u'uniaxial', u'ellipsoidal' 354 1. (list) Isotropic/uniaxial parameters - list of 3 floats 355 2. (list) Refinement flags - list of 3 bools 356 3. (list) Size axis - list of 3 ints, [h, k, l] 357 4. (list) Ellipsoidal size parameters - list of 6 floats 358 5. (list) Ellipsoidal refinement flags - list of bools, corresponding to the parameters of (4) 359 \\ Use (bool) True if this histogram is to be used in refinement 360 MCSA \\ (dict) Monte-Carlo simulated annealing parameters 361 ========== =============== ===================================================================================================== 362 363 .. _RBData_table: 364 365 .. index:: 366 single: Rigid Body Data description 367 single: Data object descriptions; Rigid Body Data 368 369 Rigid Body Objects 370 ------------------ 371 372 Rigid body descriptions are available for two types of rigid bodies: 'Vector' 373 and 'Residue'. Vector rigid bodies are developed by a sequence of translations each 374 with a refinable magnitude and Residue rigid bodies are described as Cartesian coordinates 375 with defined refinable torsion angles. 376 377 .. tabularcolumns:: |l|l|p{4in}| 378 379 ========== =============== ==================================================== 380 key sub-key explanation 381 ========== =============== ==================================================== 382 Vector RBId (dict of dict) vector rigid bodies 383 \\ AtInfo (dict) Drad, Color: atom drawing radius & color for each atom type 384 \\ RBname (str) Name assigned by user to rigid body 385 \\ VectMag (list) vector magnitudes in :math:`\\AA` 386 \\ rbXYZ (list of 3 float Cartesian coordinates for Vector rigid body ) 387 \\ rbRef (list of 3 int & 1 bool) 3 assigned reference atom nos. in rigid body for origin 388 definition, use center of atoms flag 389 \\ VectRef (list of bool refinement flags for VectMag values ) 390 \\ rbTypes (list of str) Atom types for each atom in rigid body 391 \\ rbVect (list of lists) Cartesian vectors for each translation used to build rigid body 392 \\ useCount (int) Number of times rigid body is used in any structure 393 Residue RBId (dict of dict) residue rigid bodies 394 \\ AtInfo (dict) Drad, Color: atom drawing radius & color for each atom type 395 \\ RBname (str) Name assigned by user to rigid body 396 \\ rbXYZ (list of 3 float) Cartesian coordinates for Residue rigid body 397 \\ rbTypes (list of str) Atom types for each atom in rigid body 398 \\ atNames (list of str) Names of each atom in rigid body (e.g. C1,N2...) 399 \\ rbRef (list of 3 int & 1 bool) 3 assigned reference atom nos. in rigid body for origin 400 definition, use center of atoms flag 401 \\ rbSeq (list) Orig,Piv,angle,Riding : definition of internal rigid body 402 torsion; origin atom (int), pivot atom (int), torsion angle (float), 403 riding atoms (list of int) 404 \\ SelSeq (int,int) used by SeqSizer to identify objects 405 \\ useCount (int)Number of times rigid body is used in any structure 406 RBIds \\ (dict) unique Ids generated upon creation of each rigid body 407 \\ Vector (list) Ids for each Vector rigid body 408 \\ Residue (list) Ids for each Residue rigid body 409 ========== =============== ==================================================== 410 411 .. _SGData_table: 412 413 .. index:: 414 single: Space Group Data description 415 single: Data object descriptions; Space Group Data 416 417 Space Group Objects 418 ------------------- 419 420 Space groups are interpreted by :func:`GSASIIspc.SpcGroup` 421 and the information is placed in a SGdata object 422 which is a dict with these keys. Magnetic ones are marked "mag" 423 424 .. tabularcolumns:: |l|p{4.5in}| 425 426 ========== ======================================================================================== 427 key explanation 428 ========== ======================================================================================== 429 BNSlattsym mag - (str) BNS magnetic space group symbol and centering vector 430 GenFlg mag - (list) symmetry generators indices 431 GenSym mag - (list) names for each generator 432 MagMom mag - (list) "time reversals" for each magnetic operator 433 MagPtGp mag - (str) Magnetic point group symbol 434 MagSpGrp mag - (str) Magnetic space group symbol 435 OprNames mag - (list) names for each space group operation 436 SGCen (np.array) Symmetry cell centering vectors. A (n,3) np.array 437 of centers. Will always have at least one row: ``np.array([[0, 0, 0]])`` 438 SGFixed (bool) Only True if phase mported from a magnetic cif file 439 then the space group can not be changed by the user because 440 operator set from cif may be nonstandard 441 SGGen (list) generators 442 SGGray (bool) True if space group is a gray group (incommensurate magnetic structures) 443 SGInv (bool) True if centrosymmetric, False if not 444 SGLatt (str)Lattice centering type. Will be one of 445 P, A, B, C, I, F, R 446 SGLaue (str) one of the following 14 Laue classes: 447 -1, 2/m, mmm, 4/m, 4/mmm, 3R, 448 3mR, 3, 3m1, 31m, 6/m, 6/mmm, m3, m3m 449 SGOps (list) symmetry operations as a list of form 450 ``[[M1,T1], [M2,T2],...]`` 451 where :math:`M_n` is a 3x3 np.array 452 and :math:`T_n` is a length 3 np.array. 453 Atom coordinates are transformed where the 454 Asymmetric unit coordinates [X is (x,y,z)] 455 are transformed using 456 :math:`X^\\prime = M_n*X+T_n` 457 SGPolax (str) Axes for space group polarity. Will be one of 458 '', 'x', 'y', 'x y', 'z', 'x z', 'y z', 459 'xyz'. In the case where axes are arbitrary 460 '111' is used (P 1, and ?). 461 SGPtGrp (str) Point group of the space group 462 SGUniq unique axis if monoclinic. Will be 463 a, b, or c for monoclinic space groups. 464 Will be blank for non-monoclinic. 465 SGSpin mag - (list) of spin flip operatiors (+1 or -1) for the space group operations 466 SGSys (str) symmetry unit cell: type one of 467 'triclinic', 'monoclinic', 'orthorhombic', 468 'tetragonal', 'rhombohedral', 'trigonal', 469 'hexagonal', 'cubic' 470 SSGK1 (list) Superspace multipliers 471 SpGrp (str) space group symbol 472 SpnFlp mag - (list) Magnetic spin flips for every magnetic space group operator 473 ========== ======================================================================================== 474 475 .. _SSGData_table: 476 477 .. index:: 478 single: Superspace Group Data description 479 single: Data object descriptions; Superspace Group Data 480 481 Superspace groups [3+1] are interpreted by :func:`GSASIIspc.SSpcGroup` 482 and the information is placed in a SSGdata object 483 which is a dict with these keys: 484 485 .. tabularcolumns:: |l|p{4.5in}| 486 487 ========== ==================================================== 488 key explanation 489 ========== ==================================================== 490 SSGCen (list) 4D cell centering vectors [0,0,0,0] at least 491 SSGK1 (list) Superspace multipliers 492 SSGOps (list) 4D symmetry operations as [M,T] so that M*x+T = x' 493 SSpGrp (str) superspace group symbol extension to space group 494 symbol, accidental spaces removed 495 modQ (list) modulation/propagation vector 496 modSymb (list of str) Modulation symbols 497 ========== ==================================================== 498 499 500 Phase Information 501 -------------------- 502 503 .. index:: 504 single: Phase information record description 505 506 Phase information is placed in one of the following keys: 507 508 .. tabularcolumns:: |l|p{4.5in}| 509 510 ========== ============================================================== 511 key explanation 512 ========== ============================================================== 513 General Overall information about a phase 514 Histograms Information about each histogram linked to the 515 current phase as well as parameters that 516 are defined for each histogram and phase 517 (such as sample peak widths and preferred 518 orientation parameters. 519 Atoms Contains a list of atoms, as described in the 520 :ref:`Atom Records <Atoms_table>` description. 521 Drawing Parameters that determine how the phase is 522 displayed, including a list of atoms to be 523 included, as described in the 524 :ref:`Drawing Atom Records <Drawing_atoms_table>` 525 description 526 MCSA Monte-Carlo simulated annealing parameters 527 pId The index of each phase in the project, numbered 528 starting at 0 529 ranId An int value with a unique value for each phase 530 RBModels A list of dicts with parameters for each 531 rigid body inserted into the current phase, 532 as defined in the 533 :ref:`Rigid Body Insertions <Rigid_Body_Insertions>`. 534 Note that the rigid bodies are defined as 535 :ref:`Rigid Body Objects <RBData_table>` 536 RMC PDF modeling parameters 537 Pawley ref Pawley refinement parameters 538 539 ========== ============================================================== 540 541 .. _Atoms_table: 542 543 .. index:: 544 single: Atoms record description 545 single: Data object descriptions; Atoms record 546 547 -------------------- 548 Atom Records 549 -------------------- 550 551 If ``phasedict`` points to the phase information in the data tree, then 552 atoms are contained in a list of atom records (list) in 553 ``phasedict['Atoms']``. Also needed to read atom information 554 are four pointers, ``cx,ct,cs,cia = phasedict['General']['AtomPtrs']``, 555 which define locations in the atom record, as shown below. Items shown are 556 always present; additional ones for macromolecular phases are marked 'mm', 557 and those for magnetic structures are marked 'mg' 558 559 .. tabularcolumns:: |l|p{4.5in}| 560 561 ============== ==================================================== 562 location explanation 563 ============== ==================================================== 564 ct-4 mm - (str) residue number 565 ct-3 mm - (str) residue name (e.g. ALA) 566 ct-2 mm - (str) chain label 567 ct-1 (str) atom label 568 ct (str) atom type 569 ct+1 (str) refinement flags; combination of 'F', 'X', 'U', 'M' 570 cx,cx+1,cx+2 (3 floats) the x,y and z coordinates 571 cx+3 (float) site occupancy 572 cx+4,cx+5,cx+6 mg - (list) atom magnetic moment along a,b,c in Bohr magnetons 573 cs (str) site symmetry 574 cs+1 (int) site multiplicity 575 cia (str) ADP flag: Isotropic ('I') or Anisotropic ('A') 576 cia+1 (float) Uiso 577 cia+2...cia+7 (6 floats) U11, U22, U33, U12, U13, U23 578 atom[cia+8] (int) unique atom identifier 579 580 ============== ==================================================== 581 582 .. _Drawing_atoms_table: 583 584 .. index:: 585 single: Drawing atoms record description 586 single: Data object descriptions; Drawing atoms record 587 588 ---------------------------- 589 Drawing Atom Records 590 ---------------------------- 591 592 If ``phasedict`` points to the phase information in the data tree, then 593 drawing atoms are contained in a list of drawing atom records (list) in 594 ``phasedict['Drawing']['Atoms']``. Also needed to read atom information 595 are four pointers, ``cx,ct,cs,ci = phasedict['Drawing']['AtomPtrs']``, 596 which define locations in the atom record, as shown below. Items shown are 597 always present; additional ones for macromolecular phases are marked 'mm', 598 and those for magnetic structures are marked 'mg' 599 600 .. tabularcolumns:: |l|p{4.5in}| 601 602 ============== =================================================================================== 603 location explanation 604 ============== =================================================================================== 605 ct-4 mm - (str) residue number 606 ct-3 mm - (str) residue name (e.g. ALA) 607 ct-2 mm - (str) chain label 608 ct-1 (str) atom label 609 ct (str) atom type 610 cx,cx+1,cx+2 (3 floats) the x,y and z coordinates 611 cx+3,cx+4,cx+5 mg - (3 floats) atom magnetic moment along a,b,c in Bohr magnetons 612 cs-1 (str) Sym Op symbol; sym. op number + unit cell id (e.g. '1,0,-1') 613 cs (str) atom drawing style; e.g. 'balls & sticks' 614 cs+1 (str) atom label style (e.g. 'name') 615 cs+2 (int) atom color (RBG triplet) 616 cs+3 (str) ADP flag: Isotropic ('I') or Anisotropic ('A') 617 cs+4 (float) Uiso 618 cs+5...cs+11 (6 floats) U11, U22, U33, U12, U13, U23 619 ci (int) unique atom identifier; matches source atom Id in Atom Records 620 ============== =================================================================================== 621 622 .. _Rigid_Body_Insertions: 623 624 ---------------------------- 625 Rigid Body Insertions 626 ---------------------------- 627 628 If ``phasedict`` points to the phase information in the data tree, then 629 rigid body information is contained in list(s) in 630 ``phasedict['RBModels']['Residue']`` and/or ``phasedict['RBModels']['Vector']`` 631 for each rigid body inserted into the current phase. 632 633 .. tabularcolumns:: |l|p{4.5in}| 634 635 ============== =================================================================================== 636 key explanation 637 ============== =================================================================================== 638 fixOrig Should the origin be fixed (when editing, not the refinement flag) 639 Ids Ids for assignment of atoms in the rigid body 640 numChain Chain number for macromolecular fits 641 Orient Orientation of the RB as a quaternion and a refinement flag (' ', 'A' or 'AV') 642 OrientVec Orientation of the RB expressed as a vector and azimuthal rotation angle 643 Orig Origin of the RB in fractional coordinates and refinement flag (bool) 644 RBId References the unique ID of a rigid body in the 645 :ref:`Rigid Body Objects <RBData_table>` 646 RBname The name for the rigid body (str) 647 AtomFrac The atom fractions for the rigid body 648 ThermalMotion The thermal motion description for the rigid body, which includes a choice for 649 the model and can include TLS parameters or an overall Uiso value. 650 Torsions Defines the torsion angle and refinement flag for each torsion defined in 651 the :ref:`Rigid Body Object <RBData_table>` 652 ============== =================================================================================== 653 654 .. _Powder_table: 655 656 .. index:: 657 single: Powder data object description 658 single: Data object descriptions; Powder Data 659 660 Powder Diffraction Tree Items 661 ----------------------------- 662 663 Every powder diffraction histogram is stored in the GSAS-II data tree 664 with a top-level entry named beginning with the string "PWDR ". The 665 diffraction data for that information are directly associated with 666 that tree item and there are a series of children to that item. The 667 routines :func:`GSASIIdataGUI.GSASII.GetUsedHistogramsAndPhasesfromTree` 668 and :func:`GSASIIstrIO.GetUsedHistogramsAndPhases` will 669 load this information into a dictionary where the child tree name is 670 used as a key, and the information in the main entry is assigned 671 a key of ``Data``, as outlined below. 672 673 .. tabularcolumns:: |p{1in}|p{1in}|p{4in}| 674 675 ====================== =============== =========================================================== 676 key sub-key explanation 677 ====================== =============== =========================================================== 678 Comments \\ (list of str) Text strings extracted from the original powder 679 data header. These cannot be changed by the user; 680 it may be empty. 681 Limits \\ (list) two two element lists, as [[Ld,Hd],[L,H]] 682 where L and Ld are the current and default lowest 683 two-theta value to be used and 684 where H and Hd are the current and default highest 685 two-theta value to be used. 686 Reflection Lists \\ (dict of dicts) with an entry for each phase in the 687 histogram. The contents of each dict item 688 is a dict containing reflections, as described in 689 the :ref:`Powder Reflections <PowderRefl_table>` 690 description. 691 Instrument Parameters \\ (dict) The instrument parameters uses different dicts 692 for the constant wavelength (CW) and time-of-flight (TOF) 693 cases. See below for the descriptions of each. 694 wtFactor \\ (float) A weighting factor to increase or decrease 695 the leverage of data in the histogram . 696 A value of 1.0 weights the data with their 697 standard uncertainties and a larger value 698 increases the weighting of the data (equivalent 699 to decreasing the uncertainties). 700 Sample Parameters \\ (dict) Parameters that describe how 701 the data were collected, as listed 702 below. Refinable parameters are a list containing 703 a float and a bool, where the second value 704 specifies if the value is refined, otherwise 705 the value is a float unless otherwise noted. 706 \\ Scale The histogram scale factor (refinable) 707 \\ Absorption The sample absorption coefficient as 708 :math:`\\mu r` where r is the radius 709 (refinable). Only valid for Debye-Scherrer geometry. 710 \\ SurfaceRoughA Surface roughness parameter A as defined by 711 Surotti, *J. Appl. Cryst*, **5**, 325-331, 1972. 712 (refinable - only valid for Bragg-Brentano geometry) 713 \\ SurfaceRoughB Surface roughness parameter B (refinable - 714 only valid for Bragg-Brentano geometry) 715 \\ DisplaceX, Sample displacement from goniometer center 716 DisplaceY where Y is along the beam direction and 717 X is perpendicular. Units are :math:`\\mu m` 718 (refinable). 719 \\ Phi, Chi, Goniometer sample setting angles, in degrees. 720 Omega 721 \\ Gonio. radius Radius of the diffractometer in mm 722 \\ InstrName (str) A name for the instrument, used in preparing 723 a CIF . 724 \\ Force, Variables that describe how the measurement 725 Temperature, was performed. Not used directly in 726 Humidity, any computations. 727 Pressure, 728 Voltage 729 \\ ranId (int) The random-number Id for the histogram 730 (same value as where top-level key is ranId) 731 \\ Type (str) Type of diffraction data, may be 'Debye-Scherrer' 732 or 'Bragg-Brentano' . 733 hId \\ (int) The number assigned to the histogram when 734 the project is loaded or edited (can change) 735 ranId \\ (int) A random number id for the histogram 736 that does not change 737 Background \\ (list) The background is stored as a list with where 738 the first item in the list is list and the second 739 item is a dict. The list contains the background 740 function and its coefficients; the dict contains 741 Debye diffuse terms and background peaks. 742 (TODO: this needs to be expanded.) 743 Data \\ (list) The data consist of a list of 6 np.arrays 744 containing in order: 745 746 0. the x-postions (two-theta in degrees), 747 1. the intensity values (Yobs), 748 2. the weights for each Yobs value 749 3. the computed intensity values (Ycalc) 750 4. the background values 751 5. Yobs-Ycalc 752 ====================== =============== =========================================================== 753 754 .. _CWPowder_table: 755 756 .. index:: 757 single: Powder data CW Instrument Parameters 758 759 ----------------------------- 760 CW Instrument Parameters 761 ----------------------------- 762 763 Instrument Parameters are placed in a list of two dicts, 764 where the keys in the first dict are listed below. Note that the dict contents are different for 765 constant wavelength (CW) vs. time-of-flight (TOF) histograms. 766 The value for each item is a list containing three values: the initial value, the current value 767 and a refinement flag which can have a value of True, False or 0 where 0 indicates a value that 768 cannot be refined. The first and second values are floats unless otherwise noted. 769 Items not refined are noted as [*] 770 771 .. tabularcolumns:: |l|p{1in}|p{4in}| 772 773 ======================== =============== =========================================================== 774 key sub-key explanation 775 ======================== =============== =========================================================== 776 Instrument Parameters[0] Type [*] (str) Histogram type: 777 * 'PXC' for constant wavelength x-ray 778 * 'PNC' for constant wavelength neutron 779 \\ Bank [*] (int) Data set number in a multidata file (usually 1) 780 \\ Lam (float) Specifies a wavelength in :math:`\\AA` 781 \\ Lam1 [*] (float) Specifies the primary wavelength in 782 :math:`\\AA`, used in place of Lam 783 when an :math:`\\alpha_1, \\alpha_2` 784 source is used. 785 \\ Lam2 [*] (float) Specifies the secondary wavelength in 786 :math:`\\AA`, used with Lam1 787 \\ I(L2)/I(L1) (float) Ratio of Lam2 to Lam1, used with Lam1 788 \\ Zero (float) Two-theta zero correction in *degrees* 789 \\ Azimuth [*] (float) Azimuthal setting angle for data recorded with differing setting angles 790 \\ U, V, W (float) Cagliotti profile coefficients 791 for Gaussian instrumental broadening, where the 792 FWHM goes as 793 :math:`U \\tan^2\\theta + V \\tan\\theta + W` 794 \\ X, Y, Z (float) Cauchy (Lorentzian) instrumental broadening coefficients 795 \\ SH/L (float) Variant of the Finger-Cox-Jephcoat asymmetric 796 peak broadening ratio. Note that this is the 797 sum of S/L and H/L where S is 798 sample height, H is the slit height and 799 L is the goniometer diameter. 800 \\ Polariz. (float) Polarization coefficient. 801 Instrument Parameters[1] (empty dict) 802 ======================== =============== =========================================================== 803 804 .. _TOFPowder_table: 805 806 .. index:: 807 single: Powder data TOF Instrument Parameters 808 809 ----------------------------- 810 TOF Instrument Parameters 811 ----------------------------- 812 813 Instrument Parameters are also placed in a list of two dicts, 814 where the keys in each dict listed below, but here for 815 time-of-flight (TOF) histograms. 816 The value for each item is a list containing three values: the initial value, the current value 817 and a refinement flag which can have a value of True, False or 0 where 0 indicates a value that 818 cannot be refined. The first and second values are floats unless otherwise noted. 819 Items not refined are noted as [*] 820 821 .. tabularcolumns:: |l|p{1.5in}|p{4in}| 822 823 ======================== =============== =========================================================== 824 key sub-key explanation 825 ======================== =============== =========================================================== 826 Instrument Parameters[0] Type [*] (str) Histogram type: 827 * 'PNT' for time of flight neutron 828 \\ Bank (int) Data set number in a multidata file 829 \\ 2-theta [*] (float) Nominal scattering angle for the detector 830 \\ fltPath [*] (float) Total flight path source-sample-detector 831 \\ Azimuth [*] (float) Azimuth angle for detector right hand rotation 832 from horizontal away from source 833 \\ difC,difA, (float) Diffractometer constants for conversion of d-spacing to TOF 834 difB in microseconds 835 \\ Zero (float) Zero point offset (microseconds) 836 \\ alpha (float) Exponential rise profile coefficients 837 \\ beta-0 (float) Exponential decay profile coefficients 838 beta-1 839 beta-q 840 \\ sig-0 (float) Gaussian profile coefficients 841 sig-1 842 sig-2 843 sig-q 844 \\ X,Y,Z (float) Lorentzian profile coefficients 845 Instrument Parameters[1] Pdabc (list of 4 float lists) Originally created for use in gsas as optional tables 846 of d, alp, bet, d-true; for a reflection alpha & beta are obtained via interpolation 847 from the d-spacing and these tables. The d-true column is apparently unused. 848 ======================== =============== =========================================================== 849 850 851 .. _PowderRefl_table: 852 853 .. index:: 854 single: Powder reflection object description 855 single: Data object descriptions; Powder Reflections 856 857 Powder Reflection Data Structure 858 -------------------------------- 859 860 For every phase in a histogram, the ``Reflection Lists`` value is a dict 861 one element of which is `'RefList'`, which is a np.array containing 862 reflections. The columns in that array are documented below. 863 864 ========== ==================================================== 865 index explanation 866 ========== ==================================================== 867 0,1,2 h,k,l (float) 868 3 (int) multiplicity 869 4 (float) d-space, :math:`\\AA` 870 5 (float) pos, two-theta 871 6 (float) sig, Gaussian width 872 7 (float) gam, Lorenzian width 873 8 (float) :math:`F_{obs}^2` 874 9 (float) :math:`F_{calc}^2` 875 10 (float) reflection phase, in degrees 876 11 (float) intensity correction for reflection, this times 877 :math:`F_{obs}^2` or :math:`F_{calc}^2` gives Iobs or Icalc 878 12 (float) Preferred orientation correction 879 13 (float) Transmission (absorption correction) 880 14 (float) Extinction correction 881 ========== ==================================================== 882 883 .. _Xtal_table: 884 885 .. index:: 886 single: Single Crystal data object description 887 single: Data object descriptions; Single crystal data 888 889 Single Crystal Tree Items 890 ------------------------- 891 892 Every single crystal diffraction histogram is stored in the GSAS-II data tree 893 with a top-level entry named beginning with the string "HKLF ". The 894 diffraction data for that information are directly associated with 895 that tree item and there are a series of children to that item. The 896 routines :func:`GSASIIdataGUI.GSASII.GetUsedHistogramsAndPhasesfromTree` 897 and :func:`GSASIIstrIO.GetUsedHistogramsAndPhases` will 898 load this information into a dictionary where the child tree name is 899 used as a key, and the information in the main entry is assigned 900 a key of ``Data``, as outlined below. 901 902 .. tabularcolumns:: |l|l|p{4in}| 903 904 ====================== =============== ==================================================== 905 key sub-key explanation 906 ====================== =============== ==================================================== 907 Data \\ (dict) that contains the 908 reflection table, 909 as described in the 910 :ref:`Single Crystal Reflections 911 <XtalRefl_table>` 912 description. 913 914 Instrument Parameters \\ (list) containing two dicts where the possible 915 keys in each dict are listed below. The value 916 for most items is a list containing two values: 917 the initial value, the current value. 918 The first and second 919 values are floats unless otherwise noted. 920 \\ Lam (two floats) Specifies a wavelength in :math:`\\AA` 921 \\ Type (two str values) Histogram type : 922 * 'SXC' for constant wavelength x-ray 923 * 'SNC' for constant wavelength neutron 924 * 'SNT' for time of flight neutron 925 * 'SEC' for constant wavelength electrons (e.g. micro-ED) 926 \\ InstrName (str) A name for the instrument, used in preparing a CIF 927 wtFactor \\ (float) A weighting factor to increase or decrease 928 the leverage of data in the histogram. 929 A value of 1.0 weights the data with their 930 standard uncertainties and a larger value 931 increases the weighting of the data (equivalent 932 to decreasing the uncertainties). 933 934 hId \\ (int) The number assigned to the histogram when 935 the project is loaded or edited (can change) 936 ranId \\ (int) A random number id for the histogram 937 that does not change 938 ====================== =============== ==================================================== 939 940 .. _XtalRefl_table: 941 942 .. index:: 943 single: Single Crystal reflection object description 944 single: Data object descriptions; Single Crystal Reflections 945 946 Single Crystal Reflection Data Structure 947 ---------------------------------------- 948 949 For every single crystal a histogram, the ``'Data'`` item contains 950 the structure factors as an np.array in item `'RefList'`. 951 The columns in that array are documented below. 952 953 .. tabularcolumns:: |l|p{4in}| 954 955 ========== ==================================================== 956 index explanation 957 ========== ==================================================== 958 0,1,2 (float) h,k,l 959 3 (int) multiplicity 960 4 (float) d-space, :math:`\\AA` 961 5 (float) :math:`F_{obs}^2` 962 6 (float) :math:`\\sigma(F_{obs}^2)` 963 7 (float) :math:`F_{calc}^2` 964 8 (float) :math:`F_{obs}^2T` 965 9 (float) :math:`F_{calc}^2T` 966 10 (float) reflection phase, in degrees 967 11 (float) intensity correction for reflection, this times 968 :math:`F_{obs}^2` or :math:`F_{calc}^2` 969 gives Iobs or Icalc 970 ========== ==================================================== 971 972 .. _Image_table: 973 974 .. index:: 975 image: Image data object description 976 image: Image object descriptions 977 978 Image Data Structure 979 -------------------- 980 981 Every 2-dimensional image is stored in the GSAS-II data tree 982 with a top-level entry named beginning with the string "IMG ". The 983 image data are directly associated with that tree item and there 984 are a series of children to that item. The routines :func:`GSASIIdataGUI.GSASII.GetUsedHistogramsAndPhasesfromTree` 985 and :func:`GSASIIstrIO.GetUsedHistogramsAndPhases` will 986 load this information into a dictionary where the child tree name is 987 used as a key, and the information in the main entry is assigned 988 a key of ``Data``, as outlined below. 989 990 .. tabularcolumns:: |l|l|p{4in}| 991 992 ====================== ====================== ==================================================== 993 key sub-key explanation 994 ====================== ====================== ==================================================== 995 Comments \\ (list of str) Text strings extracted from the original image data 996 header or a metafile. These cannot be changed by 997 the user; it may be empty. 998 Image Controls azmthOff (float) The offset to be applied to an azimuthal 999 value. Accomodates 1000 detector orientations other than with the detector 1001 X-axis 1002 horizontal. 1003 \\ background image (list:str,float) The name of a tree item ("IMG ...") that is to be subtracted 1004 during image integration multiplied by value. It must have the same size/shape as 1005 the integrated image. NB: value < 0 for subtraction. 1006 \\ calibrant (str) The material used for determining the position/orientation 1007 of the image. The data is obtained from :func:`ImageCalibrants` 1008 and UserCalibrants.py (supplied by user). 1009 \\ calibdmin (float) The minimum d-spacing used during the last calibration run. 1010 \\ calibskip (int) The number of expected diffraction lines skipped during the last 1011 calibration run. 1012 \\ center (list:floats) The [X,Y] point in detector coordinates (mm) where the direct beam 1013 strikes the detector plane as determined by calibration. This point 1014 does not have to be within the limits of the detector boundaries. 1015 \\ centerAzm (bool) If True then the azimuth reported for the integrated slice 1016 of the image is at the center line otherwise it is at the leading edge. 1017 \\ color (str) The name of the colormap used to display the image. Default = 'Paired'. 1018 \\ cutoff (float) The minimum value of I/Ib for a point selected in a diffraction ring for 1019 calibration calculations. See pixLimit for details as how point is found. 1020 \\ DetDepth (float) Coefficient for penetration correction to distance; accounts for diffraction 1021 ring offset at higher angles. Optionally determined by calibration. 1022 \\ DetDepthRef (bool) If True then refine DetDepth during calibration/recalibration calculation. 1023 \\ distance (float) The distance (mm) from sample to detector plane. 1024 \\ ellipses (list:lists) Each object in ellipses is a list [center,phi,radii,color] where 1025 center (list) is location (mm) of the ellipse center on the detector plane, phi is the 1026 rotation of the ellipse minor axis from the x-axis, and radii are the minor & major 1027 radii of the ellipse. If radii[0] is negative then parameters describe a hyperbola. Color 1028 is the selected drawing color (one of 'b', 'g' ,'r') for the ellipse/hyperbola. 1029 \\ edgemin (float) Not used; parameter in EdgeFinder code. 1030 \\ fullIntegrate (bool) If True then integrate over full 360 deg azimuthal range. 1031 \\ GonioAngles (list:floats) The 'Omega','Chi','Phi' goniometer angles used for this image. 1032 Required for texture calculations. 1033 \\ invert_x (bool) If True display the image with the x-axis inverted. 1034 \\ invert_y (bool) If True display the image with the y-axis inverted. 1035 \\ IOtth (list:floats) The minimum and maximum 2-theta values to be used for integration. 1036 \\ LRazimuth (list:floats) The minimum and maximum azimuth values to be used for integration. 1037 \\ Oblique (list:float,bool) If True apply a detector absorption correction using the value to the 1038 intensities obtained during integration. 1039 \\ outAzimuths (int) The number of azimuth pie slices. 1040 \\ outChannels (int) The number of 2-theta steps. 1041 \\ pixelSize (list:ints) The X,Y dimensions (microns) of each pixel. 1042 \\ pixLimit (int) A box in the image with 2*pixLimit+1 edges is searched to find the maximum. 1043 This value (I) along with the minimum (Ib) in the box is reported by :func:`GSASIIimage.ImageLocalMax` 1044 and subject to cutoff in :func:`GSASIIimage.makeRing`. 1045 Locations are used to construct rings of points for calibration calcualtions. 1046 \\ PolaVal (list:float,bool) If type='SASD' and if True, apply polarization correction to intensities from 1047 integration using value. 1048 \\ rings (list:lists) Each entry is [X,Y,dsp] where X & Y are lists of x,y coordinates around a 1049 diffraction ring with the same d-spacing (dsp) 1050 \\ ring (list) The x,y coordinates of the >5 points on an inner ring 1051 selected by the user, 1052 \\ Range (list) The minimum & maximum values of the image 1053 \\ rotation (float) The angle between the x-axis and the vector about which the 1054 detector is tilted. Constrained to -180 to 180 deg. 1055 \\ SampleShape (str) Currently only 'Cylinder'. Sample shape for Debye-Scherrer experiments; used for absorption 1056 calculations. 1057 \\ SampleAbs (list: float,bool) Value of absorption coefficient for Debye-Scherrer experimnents, flag if True 1058 to cause correction to be applied. 1059 \\ setDefault (bool) If True the use the image controls values for all new images to be read. (might be removed) 1060 \\ setRings (bool) If True then display all the selected x,y ring positions (vida supra rings) used in the calibration. 1061 \\ showLines (bool) If True then isplay the integration limits to be used. 1062 \\ size (list:int) The number of pixels on the image x & y axes 1063 \\ type (str) One of 'PWDR', 'SASD' or 'REFL' for powder, small angle or reflectometry data, respectively. 1064 \\ tilt (float) The angle the detector normal makes with the incident beam; range -90 to 90. 1065 \\ wavelength (float) The radiation wavelength (:math:`\\AA`) as entered by the user 1066 (or someday obtained from the image header). 1067 Masks Arcs (list: lists) Each entry [2-theta,[azimuth[0],azimuth[1]],thickness] describes an arc mask 1068 to be excluded from integration 1069 \\ Frames (list:lists) Each entry describes the x,y points (3 or more - mm) that describe a frame outside 1070 of which is excluded from recalibration and integration. Only one frame is allowed. 1071 \\ Points (list:lists) Each entry [x,y,radius] (mm) describes an excluded spot on the image to be excluded 1072 from integration. 1073 \\ Polygons (list:lists) Each entry is a list of 3+ [x,y] points (mm) that describe a polygon on the image 1074 to be excluded from integration. 1075 \\ Rings (list: lists) Each entry [2-theta,thickness] describes a ring mask 1076 to be excluded from integration. 1077 \\ Thresholds (list:[tuple,list]) [(Imin,Imax),[Imin,Imax]] This gives lower and upper limits for points on the image to be included 1078 in integrsation. The tuple is the image intensity limits and the list are those set by the user. 1079 \\ SpotMask (dict: int & array) 1080 'esdMul'(int) number of standard deviations above mean ring intensity to mask 1081 'spotMask' (bool array) the spot mask for every pixel in image 1082 1083 Stress/Strain Sample phi (float) Sample rotation about vertical axis. 1084 \\ Sample z (float) Sample translation from the calibration sample position (for Sample phi = 0) 1085 These will be restricted by space group symmetry; result of strain fit refinement. 1086 \\ Type (str) 'True' or 'Conventional': The strain model used for the calculation. 1087 \\ d-zero (list:dict) Each item is for a diffraction ring on the image; all items are from the same phase 1088 and are used to determine the strain tensor. 1089 The dictionary items are: 1090 'Dset': (float) True d-spacing for the diffraction ring; entered by the user. 1091 'Dcalc': (float) Average calculated d-spacing determined from strain coeff. 1092 'Emat': (list: float) The strain tensor elements e11, e12 & e22 (e21=e12, rest are 0) 1093 'Esig': (list: float) Esds for Emat from fitting. 1094 'pixLimit': (int) Search range to find highest point on ring for each data point 1095 'cutoff': (float) I/Ib cutoff for searching. 1096 'ImxyObs': (list: lists) [[X],[Y]] observed points to be used for strain calculations. 1097 'ImtaObs': (list: lists) [[d],[azm]] transformed via detector calibration from ImxyObs. 1098 'ImtaCalc': (list: lists [[d],[azm]] calculated d-spacing & azimuth from fit. 1099 1100 ====================== ====================== ==================================================== 1101 1102 .. _parmDict_table: 1103 1104 .. index:: 1105 single: Parameter dictionary 1106 1107 Parameter Dictionary 1108 ------------------------- 1109 1110 The parameter dictionary contains all of the variable parameters for the refinement. 1111 The dictionary keys are the name of the parameter (<phase>:<hist>:<name>:<atom>). 1112 It is prepared in two ways. When loaded from the tree 1113 (in :meth:`GSASIIdataGUI.GSASII.MakeLSParmDict` and 1114 :meth:`GSASIIIO.ExportBaseclass.loadParmDict`), 1115 the values are lists with two elements: ``[value, refine flag]`` 1116 1117 When loaded from the GPX file (in 1118 :func:`GSASIIstrMain.Refine` and :func:`GSASIIstrMain.SeqRefine`), the value in the 1119 dict is the actual parameter value (usually a float, but sometimes a 1120 letter or string flag value (such as I or A for iso/anisotropic). 1121 1122 Texture implementation 1123 ------------------------------ 1124 1125 There are two different places where texture can be treated in GSAS-II. 1126 One is for mitigating the effects of texture in a structural refinement. 1127 The other is for texture characterization. 1128 1129 For reducing the effect of texture in a structural refinement 1130 there are entries labeled preferred orientation in each phase's 1131 data tab. Two different approaches can be used for this, the March-Dollase 1132 model and spherical harmonics. 1133 1134 For the March-Dollase model, one axis in reciprocal space is designated as 1135 unique (defaulting to the 001 axis) and reflections are corrected 1136 according to the angle they make with this axis depending on 1137 the March-Dollase ratio. (If unity, no correction is made). 1138 The ratio can be greater than one or less than one depending on if 1139 crystallites oriented along the designated axis are 1140 overrepresented or underrepresented. For most crystal systems there is an 1141 obvious choice for the direction of the unique axis and then only a single 1142 term needs to be refined. If the number is close to 1, then the correction 1143 is not needed. 1144 1145 The second method for reducing the effect of texture in a structural 1146 refinement is to create a crystallite orientation probability surface as an 1147 expansion in terms spherical harmonic functions. Only functions consistent with 1148 cylindrical diffraction suymmetry and having texture symmetry 1149 consistent with the Laue class of phase are used and are allowed, 1150 so the higher the symmetry the fewer terms that are available for a given spherical harmonics order. 1151 To use this correction, select the lowest order that provides 1152 refinable terms and perform a refinement. If the texture index remains close to 1153 one, then the correction is not needed. If a significant improvement is 1154 noted in the profile Rwp, one may wish to see if a higher order expansion 1155 gives an even larger improvement. 1156 1157 To characterize texture in a material, generally one needs data collected with the 1158 sample at multiple orientations or, for TOF, with detectors at multiple 1159 locations around the sample. In this case the detector orientation is given in 1160 each histogram's Sample Parameters and the sample's orientation is described 1161 with the Euler angles specifed on the phase's Texture tab, which is also 1162 where the texture type (cylindrical, rolling,...) and the spherical 1163 harmonic order is selected. This should not be used with a single dataset and 1164 should not be used if the preferred orientations corrections are used. 1165 1166 The coordinate system used for texture characterization is defined where 1167 the sample coordinates (Psi, gamma) are defined with an instrument coordinate 1168 system (I, J, K) such that K is normal to the diffraction plane and J is coincident with the 1169 direction of the incident radiation beam toward the source. We further define 1170 a standard set of right-handed goniometer eulerian angles (Omega, Chi, Phi) so that Omega and Phi are 1171 rotations about K and Chi is a rotation about J when Omega = 0. Finally, as the sample 1172 may be mounted so that the sample coordinate system (Is, Js, Ks) does not coincide with 1173 the instrument coordinate system (I, J, K), we define three eulerian sample rotation angles 1174 (Omega-s, Chi-s, Phi-s) that describe the rotation from (Is, Js, Ks) to (I, J, K). The sample rotation 1175 angles are defined so that with the goniometer angles at zero Omega-s and Phi-s are rotations 1176 about K and Chi-s is a rotation about J. 1177 1178 Three typical examples: 1179 1180 1) Bragg-Brentano laboratory diffractometer: Chi=0 1181 2) Debye-Scherrer counter detector; sample capillary axis perpendicular to diffraction plane: Chi=90 1182 3) Debye-Scherrer 2D area detector positioned directly behind sample; sample capillary axis horizontal; Chi=0 1183 1184 NB: The area detector azimuthal angle will equal 0 in horizontal plane to right as viewed from x-ray source and will equal 1185 90 at vertical "up" direction. 1186 1187 ISODISTORT implementation 1188 ------------------------------ 1189 1190 CIFs prepared with the ISODISTORT web site 1191 https://stokes.byu.edu/iso/isodistort_version5.6.1/isodistort.php 1192 [B. J. Campbell, H. T. Stokes, D. E. Tanner, and D. M. Hatch, "ISODISPLACE: An Internet Tool for Exploring Structural Distortions." 1193 J. Appl. Cryst. 39, 607-614 (2006).] can be read into GSAS-II using import CIF. This will cause constraints to be established for 1194 structural distortion modes read from the CIF. At present, of the five types of modes only displacive(``_iso_displacivemode``...) 1195 and occupancy (``_iso_occupancymode``...) are processed. Not yet processed: ``_iso_magneticmode``..., 1196 ``_iso_rotationalmode``... & ``_iso_strainmode``... 1197 1198 The CIF importer :mod:`G2phase_CIF` implements class :class:`G2phase_CIF.CIFPhaseReader` which offers two methods associated 1199 with ISODISTORT (ID) input. Method :meth:`G2phase_CIF.CIFPhaseReader.ISODISTORT_test` checks to see if a CIF block contains 1200 the loops with ``_iso_displacivemode_label`` or ``_iso_occupancymode_label`` items. If so, method 1201 :meth:`G2phase_CIF.CIFPhaseReader.ISODISTORT_proc` is called to read and interpret them. The results are placed into the 1202 reader object's ``.Phase`` class variable as a dict item with key ``'ISODISTORT'``. 1203 1204 Note that each mode ID has a long label with a name such as Pm-3m[1/2,1/2,1/2]R5+(a,a,0)[La:b:dsp]T1u(a). Function 1205 :func:`G2phase_CIF.ISODISTORT_shortLbl` is used to create a short name for this, such as R5_T1u(a) which is made unique 1206 by addition of _n if the short name is duplicated. As each mode is processed, a constraint corresponding to that mode is 1207 created and is added to list in the reader object's ``.Constraints`` class variable. Items placed into that list can either 1208 be a list, which corresponds to a function (new var) type :ref:`constraint definition <Constraints_table>` entry, or an item 1209 can be a dict, which provides help information for each constraint. 1210 1211 ------------------------------ 1212 Displacive modes 1213 ------------------------------ 1214 1215 The coordinate variables, as named by ISODISTORT, are placed in ``.Phase['ISODISTORT']['IsoVarList']`` and the 1216 corresponding :class:`GSASIIobj.G2VarObj` objects for each are placed in ``.Phase['ISODISTORT']['G2VarList']``. 1217 The mode variables, as named by ISODISTORT, are placed in ``.Phase['ISODISTORT']['IsoModeList']`` and the 1218 corresponding :class:`GSASIIobj.G2VarObj` objects for each are placed in ``.Phase['ISODISTORT']['G2ModeList']``. 1219 [Use ``str(G2VarObj)`` to get the variable name from the G2VarObj object, but note that the phase number, *n*, for the prefix 1220 "*n*::" cannot be determined as the phase number is not yet assigned.] 1221 1222 Displacive modes are a bit complex in that they relate to delta displacements, relative to an offset value for each coordinate, 1223 and because the modes are normalized. While GSAS-II also uses displacements, these are added to the coordinates after 1224 each refinement cycle and then the delta values are set to zero. 1225 ISODISTORT uses fixed offsets (subtracted from the actual position 1226 to obtain the delta values) that are taken from the parent structure coordinate and the initial offset value 1227 (in ``_iso_deltacoordinate_value``) and these are placed in 1228 ``.Phase['ISODISTORT']['G2coordOffset']`` in the same order as ``.Phase['ISODISTORT']['G2ModeList']``, 1229 ``.Phase['ISODISTORT']['IsoVarList']`` and ''.Phase[ISODISTORT']['G2parentCoords']''.' 1230 1231 The normalization factors (which the delta values are divided by) 1232 are taken from ``_iso_displacivemodenorm_value`` and are placed in ``.Phase['ISODISTORT']['NormList']`` in the same 1233 order as as ``...['IsoModeList']`` and ``...['G2ModeList']``. 1234 1235 The CIF contains a sparse matrix, from the ``loop_`` containing ``_iso_displacivemodematrix_value`` which provides the equations 1236 for determining the mode values from the coordinates, that matrix is placed in ``.Phase['ISODISTORT']['Mode2VarMatrix']``. 1237 The matrix is inverted to produce ``.Phase['ISODISTORT']['Var2ModeMatrix']``, which determines how to compute the 1238 mode values from the delta coordinate values. These values are used for the in :func:`GSASIIconstrGUI.ShowIsoDistortCalc`, 1239 which shows coordinate and mode values, the latter with s.u. values. 1240 1241 ------------------------------ 1242 Occupancy modes 1243 ------------------------------ 1244 1245 1246 The delta occupancy variables, as named by ISODISTORT, are placed in 1247 ``.Phase['ISODISTORT']['OccVarList']`` and the corresponding :class:`GSASIIobj.G2VarObj` objects for each are placed 1248 in ``.Phase['ISODISTORT']['G2OccVarList']``. The mode variables, as named by ISODISTORT, are placed in 1249 ``.Phase['ISODISTORT']['OccModeList']`` and the corresponding :class:`GSASIIobj.G2VarObj` objects for each are placed 1250 in ``.Phase['ISODISTORT']['G2OccModeList']``. 1251 1252 Occupancy modes, like Displacive modes, are also refined as delta values. However, GSAS-II directly refines the fractional 1253 occupancies. Offset values for each atom, are taken from ``_iso_occupancy_formula`` and are placed in 1254 ``.Phase['ISODISTORT']['ParentOcc]``. (Offset values are subtracted from the actual position to obtain the delta values.) 1255 Modes are normalized (where the mode values are divided by the normalization factor) are taken from ``_iso_occupancymodenorm_value`` 1256 and are placed in ``.Phase['ISODISTORT']['OccNormList']`` in the same order as as ``...['OccModeList']`` and 1257 ``...['G2OccModeList']``. 1258 1259 The CIF contains a sparse matrix, from the ``loop_`` containing ``_iso_occupancymodematrix_value``, which provides the 1260 equations for determining the mode values from the coordinates. That matrix is placed in ``.Phase['ISODISTORT']['Occ2VarMatrix']``. 1261 The matrix is inverted to produce ``.Phase['ISODISTORT']['Var2OccMatrix']``, which determines how to compute the 1262 mode values from the delta coordinate values. 1263 1264 1265 ------------------------------ 1266 Mode Computations 1267 ------------------------------ 1268 1269 Constraints are processed after the CIF has been read in :meth:`GSASIIdataGUI.GSASII.OnImportPhase` or 1270 :meth:`GSASIIscriptable.G2Project.add_phase` by moving them from the reader object's ``.Constraints`` 1271 class variable to the Constraints tree entry's ['Phase'] list (for list items defining constraints) or 1272 the Constraints tree entry's ['_Explain'] dict (for dict items defining constraint help information) 1273 1274 The information in ``.Phase['ISODISTORT']`` is used in :func:`GSASIIconstrGUI.ShowIsoDistortCalc` which shows coordinate and mode 1275 values, the latter with s.u. values. This can be called from the Constraints and Phase/Atoms tree items. 1276 1277 Before each refinement, constraints are processed as :ref:`described elsewhere <Constraints_processing>`. After a refinement 1278 is complete, :func:`GSASIIstrIO.PrintIndependentVars` shows the shifts and s.u.'s on the refined modes, 1279 using GSAS-II values, but :func:`GSASIIstrIO.PrintISOmodes` prints the ISODISTORT modes as computed in the web site. 1280 1281 1282 .. _ParameterLimits: 1283 1284 .. index:: 1285 single: Parameter limits 1286 1287 Parameter Limits 1288 ------------------------------ 1289 1290 One of the most often requested "enhancements" for GSAS-II would be the inclusion 1291 of constraints to force parameters such as occupancies or Uiso values to stay within 1292 expected ranges. While it is possible for users to supply their own restraints that would 1293 perform this by supplying an appropriate expression with the "General" restraints, the 1294 GSAS-II authors do not feel that use of restraints or constraints are a good solution for 1295 this common problem where parameters refine to non-physical values. This is because when 1296 this occurs, most likely one of the following cases is occurring: 1297 1298 #. there is a significant problem 1299 with the model, for example for an x-ray fit if an O atom is placed where a S is actually 1300 present, the Uiso will refine artificially small or the occupancy much larger than unity 1301 to try to compensate for the missing electrons; or 1302 1303 #. the data are simply insensitive 1304 to the parameter or combination of parameters, for example unless very high-Q data 1305 are included, the effects of a occupancy and Uiso value can have compensating effects, 1306 so an assumption must be made; likewise, with neutron data natural-abundance V atoms 1307 are nearly invisible due to weak coherent scattering. No parameters can be fit for a 1308 V atom with neutrons. 1309 1310 #. the parameter is non-physical (such as a negative Uiso value) but within 1311 two sigma (sigma = standard uncertainty, aka e.s.d.) of a reasonable value, 1312 in which case the 1313 value is not problematic as it is experimentally indistinguishable from an 1314 expected value. 1315 1316 #. there is a systematic problem with the data (experimental error) 1317 1318 In all these cases, this situation needs to be reviewed by a crystallographer to decide 1319 how to best determine a structural model for these data. An implementation with a constraint 1320 or restraint is likely to simply hide the problem from the user, making it more probable 1321 that a poor model choice is obtained. 1322 1323 What GSAS-II does implement is to allow users to specify ranges for parameters 1324 that works by disabling 1325 refinement of parameters that refine beyond either a lower limit or an upper limit, where 1326 either or both may be optionally specified. Parameters limits are specified in the Controls 1327 tree entry in dicts named as ``Controls['parmMaxDict']`` and ``Controls['parmMinDict']``, where 1328 the keys are :class:`G2VarObj` objects corresponding to standard GSAS-II variable 1329 (see :func:`getVarDescr` and :func:`CompileVarDesc`) names, where a 1330 wildcard ('*') may optionally be used for histogram number or atom number 1331 (phase number is intentionally not allowed as a wildcard as it makes little sense 1332 to group the same parameter together different phases). Note 1333 that :func:`prmLookup` is used to see if a name matches a wildcard. The upper or lower limit 1334 is placed into these dicts as a float value. These values can be edited using the window 1335 created by the Calculate/"View LS parms" menu command or in scripting with the 1336 :meth:`GSASIIscriptable.G2Project.set_Controls` function. 1337 In the GUI, a checkbox labeled "match all histograms/atoms" is used to insert a wildcard 1338 into the appropriate part of the variable name. 1339 1340 When a refinement is conducted, routine :func:`GSASIIstrMain.dropOOBvars` is used to 1341 find parameters that have refined to values outside their limits. If this occurs, the parameter 1342 is set to the limiting value and the variable name is added to a list of frozen variables 1343 (as a :class:`G2VarObj` objects) kept in a list in the 1344 ``Controls['parmFrozen']`` dict. In a sequential refinement, this is kept separate for 1345 each histogram as a list in 1346 ``Controls['parmFrozen'][histogram]`` (where the key is the histogram name) or as a list in 1347 ``Controls['parmFrozen']['FrozenList']`` for a non-sequential fit. 1348 This allows different variables 1349 to be frozen in each section of a sequential fit. 1350 Frozen parameters are not included in refinements through removal from the 1351 list of parameters to be refined (``varyList``) in :func:`GSASIIstrMain.Refine` or 1352 :func:`GSASIIstrMain.SeqRefine`. 1353 The data window for the Controls tree item shows the number of Frozen variables and 1354 the individual variables can be viewed with the Calculate/"View LS parms" menu window or 1355 obtained with :meth:`GSASIIscriptable.G2Project.get_Frozen`. 1356 Once a variable is frozen, it will not be refined in any 1357 future refinements unless the the variable is removed (manually) from the list. This can also 1358 be done with the Calculate/"View LS parms" menu window or 1359 :meth:`GSASIIscriptable.G2Project.set_Frozen`. 1360 1361 1362 .. seealso:: 1363 :class:`G2VarObj` 1364 :func:`getVarDescr` 1365 :func:`CompileVarDesc` 1366 :func:`prmLookup` 1367 :class:`GSASIIctrlGUI.ShowLSParms` 1368 :class:`GSASIIctrlGUI.VirtualVarBox` 1369 :func:`GSASIIstrIO.SetUsedHistogramsAndPhases` 1370 :func:`GSASIIstrIO.SaveUpdatedHistogramsAndPhases` 1371 :func:`GSASIIstrIO.SetSeqResult` 1372 :func:`GSASIIstrMain.dropOOBvars` 1373 :meth:`GSASIIscriptable.G2Project.set_Controls` 1374 :meth:`GSASIIscriptable.G2Project.get_Frozen` 1375 :meth:`GSASIIscriptable.G2Project.set_Frozen` 1376 1377 *Classes and routines* 1378 ---------------------- 1379 12 Classes and routines defined in :mod:`GSASIIobj` follow. 1380 13 ''' 14 # Note that documentation for GSASIIobj.py has been moved 15 # to file docs/source/GSASIIobj.rst 16 1381 17 from __future__ import division, print_function 1382 18 import platform -
trunk/GSASIIpath.py
r5551 r5572 9 9 ########### SVN repository information ################### 10 10 ''' 11 *GSASIIpath: locations & updates* 12 --------------------------------- 13 14 Routines for dealing with file locations, etc. 15 16 Determines the location of the compiled (.pyd or .so) libraries. 17 18 Interfaces with subversion (svn): 19 Determine the subversion release number by determining the highest version number 20 where :func:`SetVersionNumber` is called (best done in every GSASII file). 21 Other routines will update GSASII from the subversion server if svn can be 22 found. 23 24 Accesses configuration options, as defined in config.py 11 :mod:`GSASIIpath` Classes & routines follow 25 12 ''' 26 13 -
trunk/GSASIIplot.py
r5552 r5572 8 8 ########### SVN repository information ################### 9 9 ''' 10 *GSASIIplot: plotting routines* 11 =============================== 12 13 This module performs all visualization using matplotlib and OpenGL graphics. The following plotting 14 routines are defined: 15 16 ============================ =========================================================================== 17 plotting routine action 18 ============================ =========================================================================== 19 :func:`PlotPatterns` Powder pattern plotting 20 :func:`PublishRietveldPlot` Create publication-quality Rietveld plots from :func:`PlotPatterns` plot 21 :func:`PlotImage` Plots of 2D detector images 22 :func:`PlotPeakWidths` Plot instrument broadening terms as function of 2-theta/TOF 23 :func:`PlotCovariance` Show covariance terms in 2D 24 :func:`PlotStructure` Crystal structure plotting with balls, sticks, lines, 25 ellipsoids, polyhedra and magnetic moments 26 :func:`PlotBeadModel` Plots representation of protein shape from small angle scattering 27 :func:`Plot1DSngl` 1D stick plots of structure factors 28 :func:`PlotSngl` Structure factor plotting 29 :func:`Plot3DSngl` 3D Structure factor plotting 30 :func:`PlotDeltSig` Normal probability plot (powder or single crystal) 31 :func:`PlotISFG` PDF analysis: displays I(Q), S(Q), F(Q) and G(r) 32 :func:`PlotCalib` CW or TOF peak calibration 33 :func:`PlotXY` Simple plot of xy data 34 :func:`PlotXYZ` Simple contour plot of xyz data 35 :func:`PlotXYZvect` Quiver Plot for 3D cartesian vectors 36 :func:`Plot3dXYZ` Surface Plot for 3D vectors 37 :func:`PlotAAProb` Protein "quality" plot 38 :func:`PlotStrain` Plot of strain data, used for diagnostic purposes 39 :func:`PlotSASDSizeDist` Small angle scattering size distribution plot 40 :func:`PlotPowderLines` Plot powder pattern as a stick plot (vertical lines) 41 :func:`PlotSizeStrainPO` Plot 3D mustrain/size/preferred orientation figure 42 :func:`PlotTexture` Pole figure, inverse pole figure plotting 43 :func:`ModulationPlot` Plots modulation information 44 :func:`PlotTorsion` Plots MC torsion angles 45 :func:`PlotRama` Ramachandran of energetically allowed regions for dihedral 46 angles in protein 47 :func:`PlotSelectedSequence` Plot one or more sets of values selected from the sequential 48 refinement table 49 :func:`PlotIntegration` Rectified plot of 2D image after image integration with 2-theta and 50 azimuth as coordinates 51 :func:`PlotTRImage` test plot routine 52 :func:`PlotRigidBody` show rigid body structures as balls & sticks 53 :func:`PlotLayers` show layer structures as balls & sticks 54 :func:`PlotFPAconvolutors` plots the convolutors from Fundamental Parameters 55 :func:`PlotClusterXYZ` plots the result of cluster analysis 56 ============================ =========================================================================== 57 58 These plotting routines place their graphics in the GSAS-II Plot Window, which contains a 59 :class:`G2PlotNoteBook` tabbed panel allowing multiple plots to be viewed. Methods 60 :meth:`G2PlotNoteBook.addMpl` (2-D matplotlib), 61 :meth:`G2PlotNoteBook.add3D` (3-D matplotlib), and 62 :meth:`G2PlotNoteBook.addOgl` (OpenGL) are used to 63 create tabbed plot objects to hold plots of the following classes: 64 :class:`G2PlotMpl` (2-D matplotlib), 65 :class:`G2Plot3D` (3-D matplotlib), and 66 :class:`G2PlotOgl` (OpenGL). Note that two :class:`G2PlotNoteBook` methods are 67 potentially used to determine how plot updates after a refinement are handled: 68 69 ============================================ ======================================================== 70 class method description 71 ============================================ ======================================================== 72 :meth:`G2PlotNoteBook.RegisterRedrawRoutine` This specifies a function 73 to redraw the plot after the data tree has been 74 reloaded. Be sure this updates data 75 objects with new values from the tree, when needed. 76 77 :meth:`G2PlotNoteBook.SetNoDelete` Use this to indicate that a plot does not need to be 78 updated after a refinement and should not be closed. 79 ============================================ ======================================================== 80 81 These two methods define the following attributes (variables) in the plot tab classes: 82 83 ====================== =============== ============================================================ 84 variable default use 85 ====================== =============== ============================================================ 86 replotFunction None Defines a routine to be called to update the plot 87 after a refinement (unless None). Use 88 :meth:`G2PlotNoteBook.RegisterRedrawRoutine` 89 to define this (and replotArgs & replotKwArgs). 90 Plotting functions that take significant time 91 to complete should probably not use this.) 92 replotArgs [] Defines the positional arguments to be supplied to 93 the replotFunction function or method. 94 replotKwArgs {} Defines the keyword arguments to be supplied to 95 the replotFunction function or method. 96 plotRequiresRedraw True If set to True, after a refinement, the plot will be 97 closed (in :func:`GSASIIdataGUI.GSASII.CleanupOldPlots`) 98 if it was not updated after the refinement. Set this to 99 False using :meth:`G2PlotNoteBook.SetNoDelete` 100 for plots that should not be deleted or do 101 not change based on refinement results. 102 plotInvalid False Used to track if a plot has been updated. Set to False 103 in :meth:`G2PlotNoteBook.FindPlotTab` when a plot is 104 drawn. After a refinement is completed, method 105 :func:`GSASIIdataGUI.GSASII.ResetPlots` sets 106 plotInvalid to False for all plots before any routines 107 are called. 108 ====================== =============== ============================================================ 109 110 Note that the plot toolbar is customized with :class:`GSASIItoolbar` 111 10 Classes and routines defined in :mod:`GSASIIplot` follow. 112 11 ''' 12 # Note that documentation for GSASIIplot.py has been moved 13 # to file docs/source/GSASIIplot.rst 14 15 113 16 from __future__ import division, print_function 114 17 import platform -
trunk/GSASIIpwd.py
r5568 r5572 1 1 #/usr/bin/env python 2 2 # -*- coding: utf-8 -*- 3 '''4 *GSASIIpwd: Powder calculations module*5 ==============================================6 7 This version hacked to provide Laue Fringe fitting.8 9 '''10 3 ########### SVN repository information ################### 11 4 # $Date$ … … 15 8 # $Id$ 16 9 ########### SVN repository information ################### 10 ''' 11 Classes and routines defined in :mod:`GSASIIpwd` follow. 12 ''' 13 17 14 from __future__ import division, print_function 18 15 import sys -
trunk/GSASIIpy3.py
r5352 r5572 1 1 ''' 2 *GSASIIpy3: Python 3.x Routines* 3 ================================ 4 5 Module to hold python 3-compatible code, to keep it separate from 6 code that will break with __future__ options. 7 2 Python 3 specific routines follow. TODO: refactor this code into 3 :mod:`GSASIIfiles` 8 4 ''' 9 5 from __future__ import division, print_function -
trunk/GSASIIsasd.py
r5114 r5572 1 1 #/usr/bin/env python 2 2 # -*- coding: utf-8 -*- 3 '''4 *GSASII small angle calculation module*5 =======================================6 7 '''8 3 ########### SVN repository information ################### 9 4 # $Date$ … … 13 8 # $Id$ 14 9 ########### SVN repository information ################### 10 ''' 11 Classes and routines defined in :mod:`GSASIIsasd` follow. 12 ''' 15 13 from __future__ import division, print_function 16 14 import os -
trunk/GSASIIscriptable.py
r5556 r5572 10 10 # 11 11 """ 12 *GSASIIscriptable: Scripting Interface* 13 ======================================= 14 15 Routines to use an increasing amount of GSAS-II's capabilities from scripts, 16 without use of the graphical user interface (GUI). GSASIIscriptable can create and access 17 GSAS-II project (.gpx) files and can directly perform image handling and refinements. 18 The module defines wrapper classes (inheriting from :class:`G2ObjectWrapper`) for a growing number 19 of data tree items. 20 21 GSASIIscriptable can be used in two ways. It offers a command-line mode 22 (see :ref:`CommandlineInterface`) that 23 provides access a number of features without writing Python scripts 24 via shell/batch commands. The more widely used and more powerful mode of GSASIIscriptable is 25 use is through Python scripts that 26 call the module's application interface (API), see API summary that follows or the :ref:`API` 27 section. 28 29 ================================================== 30 Application Interface (API) Summary 31 ================================================== 32 This section of the documentation provides an overview to API, with full documentation 33 in the :ref:`API` section. The typical API use will be with a Python script, such as 34 what is found in :ref:`CodeExamples`. Most functionality is provided via the objects and methods 35 summarized below. 36 37 --------------------- 38 Overview of Classes 39 --------------------- 40 41 .. tabularcolumns:: |l|p{4in}| 42 43 =============================== =============================================================================================================== 44 class Encapsulates 45 =============================== =============================================================================================================== 46 :class:`G2Project` A GSAS-II project file, provides references to objects below, 47 each corresponding to a tree item 48 (exception is :class:`G2AtomRecord`) 49 :class:`G2Phase` Provides phase information access 50 (also provides access to atom info via :class:`G2AtomRecord`) 51 :class:`G2AtomRecord` Access to an atom within a phase 52 :class:`G2PwdrData` Access to powder histogram info 53 :class:`G2Image` Access to image info 54 :class:`G2PDF` PDF histogram info 55 :class:`G2SeqRefRes` The sequential results table 56 =============================== =============================================================================================================== 57 58 --------------------- 59 Functions 60 --------------------- 61 62 A small amount of the Scriptable code does not require use of objects. 63 64 .. tabularcolumns:: |l|p{4in}| 65 66 ================================================== =============================================================================================================== 67 method Use 68 ================================================== =============================================================================================================== 69 :func:`GenerateReflections` Generates a list of unique powder reflections 70 :func:`SetPrintLevel` Sets the amout of output generated when running a script 71 ================================================== =============================================================================================================== 72 73 --------------------------------- 74 Class :class:`G2Project` 75 --------------------------------- 76 77 All GSASIIscriptable scripts will need to create a :class:`G2Project` object 78 either for a new GSAS-II project or to read in an existing project (.gpx) file. 79 The most commonly used routines in this object are: 80 81 .. tabularcolumns:: |l|p{3.in}| 82 83 ================================================== =============================================================================================================== 84 method Use 85 ================================================== =============================================================================================================== 86 :meth:`G2Project.save` Writes the current project to disk. 87 88 :meth:`G2Project.add_powder_histogram` Used to read in powder diffraction data into a project file. 89 90 :meth:`G2Project.add_simulated_powder_histogram` Defines a "dummy" powder diffraction data that will be simulated after a refinement step. 91 92 :meth:`G2Project.add_image` Reads in an image into a project. 93 94 :meth:`G2Project.add_phase` Adds a phase to a project 95 96 :meth:`G2Project.add_PDF` Adds a PDF entry to a project (does not compute it) 97 98 :meth:`G2Project.histograms` Provides a list of histograms in the current project, as :class:`G2PwdrData` objects 99 100 :meth:`G2Project.phases` Provides a list of phases defined in the current project, as :class:`G2Phase` objects 101 102 :meth:`G2Project.images` Provides a list of images in the current project, as :class:`G2Image` objects 103 104 :meth:`G2Project.pdfs` Provides a list of PDFs in the current project, as :class:`G2PDF` objects 105 106 :meth:`G2Project.seqref` Returns a :class:`G2SeqRefRes` object if there are Sequential Refinement results 107 108 :meth:`G2Project.do_refinements` This is passed a list of dictionaries, where each dict defines a refinement step. 109 Passing a list with a single empty dict initiates a refinement with the current 110 parameters and flags. A refinement dict sets up a single refinement step 111 (as described in :ref:`Project_dicts`). Also see :ref:`Refinement_recipe`. 112 113 :meth:`G2Project.set_refinement` This is passed a single dict which is used to set parameters and flags. 114 These actions can be performed also in :meth:`G2Project.do_refinements`. 115 :meth:`G2Project.get_Variable` Retrieves the value and esd for a parameter 116 :meth:`G2Project.get_Covariance` Retrieves values and covariance for a set of refined parameters 117 :meth:`G2Project.set_Controls` Set overall GSAS-II control settings such as number of cycles and to set up a sequential 118 fit. (Also see :meth:`G2Project.get_Controls` to read values.) 119 :meth:`G2Project.imageMultiDistCalib` Performs a global calibration fit with images at multiple distance settings. 120 :meth:`G2Project.get_Constraints` Retrieves :ref:`constraint definition <Constraint_definitions_table>` entries. 121 :meth:`G2Project.add_HoldConstr` Adds a hold constraint on one or more variables 122 :meth:`G2Project.add_EquivConstr` Adds an equivalence constraint on two or more variables 123 :meth:`G2Project.add_EqnConstr` Adds an equation-type constraint on two or more variables 124 :meth:`G2Project.add_NewVarConstr` Adds an new variable as a constraint on two or more variables 125 ================================================== =============================================================================================================== 126 127 --------------------------------- 128 Class :class:`G2Phase` 129 --------------------------------- 130 131 132 Another common object in GSASIIscriptable scripts is :class:`G2Phase`, used to encapsulate each phase in a project, with commonly used methods: 133 134 .. tabularcolumns:: |l|p{3.5in}| 135 136 ================================================== =============================================================================================================== 137 method Use 138 ================================================== =============================================================================================================== 139 :meth:`G2Phase.set_refinements` Provides a mechanism to set values and refinement flags for the phase. See :ref:`Phase_parameters_table` 140 for more details. This information also can be supplied within a call to :meth:`G2Project.do_refinements` 141 or :meth:`G2Project.set_refinement`. 142 :meth:`G2Phase.clear_refinements` Unsets refinement flags for the phase. 143 :meth:`G2Phase.set_HAP_refinements` Provides a mechanism to set values and refinement flags for parameters specific to both this phase and 144 one of its histograms. See :ref:`HAP_parameters_table`. This information also can be supplied within 145 a call to :meth:`G2Project.do_refinements` or :meth:`G2Project.set_refinement`. 146 :meth:`G2Phase.clear_HAP_refinements` Clears refinement flags specific to both this phase and one of its histograms. 147 :meth:`G2Phase.getHAPvalues` Returns values of parameters specific to both this phase and one of its histograms. 148 :meth:`G2Phase.copyHAPvalues` Copies HAP settings between from one phase/histogram and to other histograms in same phase. 149 :meth:`G2Phase.atoms` Returns a list of atoms in the phase 150 :meth:`G2Phase.atom` Returns an atom from its label 151 :meth:`G2Phase.histograms` Returns a list of histograms linked to the phase 152 :meth:`G2Phase.get_cell` Returns unit cell parameters (also see :meth:`G2Phase.get_cell_and_esd`) 153 :meth:`G2Phase.export_CIF` Writes a CIF for the phase 154 :meth:`G2Phase.setSampleProfile` Sets sample broadening parameters 155 :meth:`G2Phase.clearDistRestraint` Clears any previously defined bond distance restraint(s) for the selected phase 156 :meth:`G2Phase.addDistRestraint` Finds and defines new bond distance restraint(s) for the selected phase 157 :meth:`G2Phase.setDistRestraintWeight` Sets the weighting factor for the bond distance restraints 158 159 ================================================== =============================================================================================================== 160 161 --------------------------------- 162 Class :class:`G2PwdrData` 163 --------------------------------- 164 165 Another common object in GSASIIscriptable scripts is :class:`G2PwdrData`, which encapsulate each powder diffraction histogram in a project, with commonly used methods: 166 167 .. tabularcolumns:: |l|p{3.5in}| 168 169 ================================================== =============================================================================================================== 170 method Use 171 ================================================== =============================================================================================================== 172 :meth:`G2PwdrData.set_refinements` Provides a mechanism to set values and refinement flags for the powder histogram. See 173 :ref:`Histogram_parameters_table` for details. 174 :meth:`G2PwdrData.clear_refinements` Unsets refinement flags for the the powder histogram. 175 :meth:`G2PwdrData.residuals` Reports R-factors etc. for the the powder histogram (also see :meth:`G2PwdrData.get_wR`) 176 :meth:`G2PwdrData.add_back_peak` Adds a background peak to the histogram. Also see :meth:`G2PwdrData.del_back_peak` and 177 :meth:`G2PwdrData.ref_back_peak`. 178 :meth:`G2PwdrData.fit_fixed_points` Fits background to the specified fixed points. 179 :meth:`G2PwdrData.getdata` Provides access to the diffraction data associated with the histogram. 180 :meth:`G2PwdrData.reflections` Provides access to the reflection lists for the histogram. 181 :meth:`G2PwdrData.Export` Writes the diffraction data or reflection list into a file 182 :meth:`G2PwdrData.add_peak` Adds a peak to the peak list. Also see :ref:`PeakRefine`. 183 :meth:`G2PwdrData.set_peakFlags` Sets refinement flags for peaks 184 :meth:`G2PwdrData.refine_peaks` Starts a peak/background fitting cycle, returns refinement results 185 :attr:`G2PwdrData.Peaks` Provides access to the peak list data structure 186 :attr:`G2PwdrData.PeakList` Provides the peak list parameter values 187 :meth:`G2PwdrData.Export_peaks` Writes the peak parameters to a text file 188 :meth:`G2PwdrData.set_background` Sets a background histogram that will be subtracted (point by point) from the current histogram. 189 ================================================== =============================================================================================================== 190 191 --------------------------------- 192 Class :class:`G2Image` 193 --------------------------------- 194 195 When working with images, there will be a :class:`G2Image` object for each image (also see :meth:`G2Project.add_image` and :meth:`G2Project.images`). 196 197 .. tabularcolumns:: |l|p{3.5in}| 198 199 ================================================== =============================================================================================================== 200 method Use 201 ================================================== =============================================================================================================== 202 :meth:`G2Image.Recalibrate` Invokes a recalibration fit starting from the current Image Controls calibration coefficients. 203 :meth:`G2Image.Integrate` Invokes an image integration All parameters Image Controls will have previously been set. 204 :meth:`G2Image.setControl` Set an Image Controls parameter in the current image. 205 :meth:`G2Image.getControl` Return an Image Controls parameter in the current image. 206 :meth:`G2Image.findControl` Get the names of Image Controls parameters. 207 :meth:`G2Image.loadControls` Load controls from a .imctrl file (also see :meth:`G2Image.saveControls`). 208 :meth:`G2Image.loadMasks` Load masks from a .immask file. 209 :meth:`G2Image.setVary` Set a refinement flag for Image Controls parameter in the current image. (Also see :meth:`G2Image.getVary`) 210 :meth:`G2Image.setCalibrant` Set a calibrant type (or show choices) for the current image. 211 :meth:`G2Image.setControlFile` Set a image to be used as a background/dark/gain map image. 212 ================================================== =============================================================================================================== 213 214 215 --------------------------------- 216 Class :class:`G2PDF` 217 --------------------------------- 218 219 To work with PDF entries, object :class:`G2PDF`, encapsulates a PDF entry with methods: 220 221 .. tabularcolumns:: |l|p{3.5in}| 222 223 ================================================== =============================================================================================================== 224 method Use 225 ================================================== =============================================================================================================== 226 :meth:`G2PDF.export` Used to write G(r), etc. as a file 227 :meth:`G2PDF.calculate` Computes the PDF using parameters in the object 228 :meth:`G2PDF.optimize` Optimizes selected PDF parameters 229 :meth:`G2PDF.set_background` Sets the histograms used for sample background, container, etc. 230 :meth:`G2PDF.set_formula` Sets the chemical formula for the sample 231 ================================================== =============================================================================================================== 232 233 --------------------------------- 234 Class :class:`G2SeqRefRes` 235 --------------------------------- 236 237 To work with Sequential Refinement results, object :class:`G2SeqRefRes`, encapsulates the sequential refinement table with methods: 238 239 .. tabularcolumns:: |l|p{3.5in}| 240 241 ================================================== =============================================================================================================== 242 method Use 243 ================================================== =============================================================================================================== 244 :meth:`G2SeqRefRes.histograms` Provides a list of histograms used in the Sequential Refinement 245 :meth:`G2SeqRefRes.get_cell_and_esd` Returns cell dimensions and standard uncertainies for a phase and histogram from the Sequential Refinement 246 :meth:`G2SeqRefRes.get_Variable` Retrieves the value and esd for a parameter from a particular histogram in the Sequential Refinement 247 :meth:`G2SeqRefRes.get_Covariance` Retrieves values and covariance for a set of refined parameters for a particular histogram 248 ================================================== =============================================================================================================== 249 250 --------------------------------- 251 Class :class:`G2AtomRecord` 252 --------------------------------- 253 254 When working with phases, :class:`G2AtomRecord` objects provide access to the contents of each atom in a phase. This provides access to "properties" that can be 255 used to get values of much of the atoms associated settings: label, type, refinement_flags, coordinates, occupancy, ranId, adp_flag, and uiso. In addition, 256 refinement_flags, occupancy and uiso can be used to set values. See the :class:`G2AtomRecord` docs and source code. 257 258 .. _Refinement_dicts: 259 260 ===================== 261 Refinement parameters 262 ===================== 263 While scripts can be written that setup refinements by changing individual parameters 264 through calls to the methods associated with objects that wrap each data tree item, 265 many of these actions can be combined into fairly complex dict structures to conduct refinement 266 steps. Use of these dicts is required with the :ref:`CommandlineInterface`. This section of the 267 documentation describes these dicts. 268 269 .. _Project_dicts: 270 271 ----------------------------- 272 Project-level Parameter Dict 273 ----------------------------- 274 275 As noted below (:ref:`Refinement_parameters_kinds`), there are three types of refinement parameters, 276 which can be accessed individually by the objects that encapsulate individual phases and histograms 277 but it will often be simplest to create a composite dictionary 278 that is used at the project-level. A dict is created with keys 279 "set" and "clear" that can be supplied to :meth:`G2Project.set_refinement` 280 (or :meth:`G2Project.do_refinements`, see :ref:`Refinement_recipe` below) that will 281 determine parameter values and will determine which parameters will be refined. 282 283 The specific keys and subkeys that can be used are defined in tables 284 :ref:`Histogram_parameters_table`, :ref:`Phase_parameters_table` and :ref:`HAP_parameters_table`. 285 286 Note that optionally a list of histograms and/or phases can be supplied in the call to 287 :meth:`G2Project.set_refinement`, but if not specified, the default is to use all defined 288 phases and histograms. 289 290 As an example: 291 292 .. code-block:: python 293 294 pardict = {'set': { 'Limits': [0.8, 12.0], 295 'Sample Parameters': ['Absorption', 'Contrast', 'DisplaceX'], 296 'Background': {'type': 'chebyschev-1', 'refine': True, 297 'peaks':[[0,True],[1,1,1]] }}, 298 'clear': {'Instrument Parameters': ['U', 'V', 'W']}} 299 my_project.set_refinement(pardict) 300 301 .. _Refinement_recipe: 302 303 ------------------------ 304 Refinement recipe 305 ------------------------ 306 307 Building on the :ref:`Project_dicts`, 308 it is possible to specify a sequence of refinement actions as a list of 309 these dicts and supplying this list 310 as an argument to :meth:`G2Project.do_refinements`. 311 312 As an example, this code performs the same actions as in the example in the section above: 313 314 .. code-block:: python 315 316 pardict = {'set': { 'Limits': [0.8, 12.0], 317 'Sample Parameters': ['Absorption', 'Contrast', 'DisplaceX'], 318 'Background': {'type': 'chebyschev-1', 'refine': True}}, 319 'clear': {'Instrument Parameters': ['U', 'V', 'W']}} 320 my_project.do_refinements([pardict]) 321 322 However, in addition to setting a number of parameters, this example will perform a refinement as well, 323 after setting the parameters. More than one refinement can be performed by including more 324 than one dict in the list. 325 326 In this example, two refinement steps will be performed: 327 328 .. code-block:: python 329 330 my_project.do_refinements([pardict,pardict1]) 331 332 333 The keys defined in the following table 334 may be used in a dict supplied to :meth:`G2Project.do_refinements`. Note that keys ``histograms`` 335 and ``phases`` are used to limit actions to specific sets of parameters within the project. 336 337 .. tabularcolumns:: |l|p{4in}| 338 339 ========== ============================================================================ 340 key explanation 341 ========== ============================================================================ 342 set Specifies a dict with keys and subkeys as described in the 343 :ref:`Refinement_parameters_fmt` section. Items listed here 344 will be set to be refined. 345 clear Specifies a dict, as above for set, except that parameters are 346 cleared and thus will not be refined. 347 once Specifies a dict as above for set, except that parameters are 348 set for the next cycle of refinement and are cleared once the 349 refinement step is completed. 350 skip Normally, once parameters are processed with a set/clear/once 351 action(s), a refinement is started. If skip is defined as True 352 (or any other value) the refinement step is not performed. 353 output If a file name is specified for output is will be used to save 354 the current refinement. 355 histograms Should contain a list of histogram(s) to be used for the 356 set/clear/once action(s) on :ref:`Histogram_parameters_table` or 357 :ref:`HAP_parameters_table`. Note that this will be 358 ignored for :ref:`Phase_parameters_table`. Histograms may be 359 specified as a list of strings [('PWDR ...'),...], indices 360 [0,1,2] or as list of objects [hist1, hist2]. 361 phases Should contain a list of phase(s) to be used for the 362 set/clear/once action(s) on :ref:`Phase_parameters_table` or 363 :ref:`HAP_parameters_table`. Note that this will be 364 ignored for :ref:`Histogram_parameters_table`. 365 Phases may be specified as a list of strings 366 [('Phase name'),...], indices [0,1,2] or as list of objects 367 [phase0, phase2]. 368 call Specifies a function to call after a refinement is completed. 369 The value supplied can be the object (typically a function) 370 that will be called or a string that will evaluate (in the 371 namespace inside :meth:`G2Project.iter_refinements` where 372 ``self`` references the project.) 373 Nothing is called if this is not specified. 374 callargs Provides a list of arguments that will be passed to the function 375 in call (if any). If call is defined and callargs is not, the 376 current <tt>G2Project</tt> is passed as a single argument. 377 ========== ============================================================================ 378 379 An example that performs a series of refinement steps follows: 380 381 .. code-block:: python 382 383 reflist = [ 384 {"set": { "Limits": { "low": 0.7 }, 385 "Background": { "no. coeffs": 3, 386 "refine": True }}}, 387 {"set": { "LeBail": True, 388 "Cell": True }}, 389 {"set": { "Sample Parameters": ["DisplaceX"]}}, 390 {"set": { "Instrument Parameters": ["U", "V", "W", "X", "Y"]}}, 391 {"set": { "Mustrain": { "type": "uniaxial", 392 "refine": "equatorial", 393 "direction": [0, 0, 1]}}}, 394 {"set": { "Mustrain": { "type": "uniaxial", 395 "refine": "axial"}}}, 396 {"clear": { "LeBail": True}, 397 "set": { "Atoms": { "Mn": "X" }}}, 398 {"set": { "Atoms": { "O1": "X", "O2": "X" }}},] 399 my_project.do_refinements(reflist) 400 401 402 In this example, a separate refinement step will be performed for each dict in the list. The keyword 403 "skip" can be used to specify a dict that should not include a refinement. 404 Note that in the second from last refinement step, parameters are both set and cleared. 405 406 .. _Refinement_parameters_kinds: 407 408 ---------------------------- 409 Refinement parameter types 410 ---------------------------- 411 412 Note that parameters and refinement flags used in GSAS-II fall into three classes: 413 414 * **Histogram**: There will be a set of these for each dataset loaded into a 415 project file. The parameters available depend on the type of histogram 416 (Bragg-Brentano, Single-Crystal, TOF,...). Typical Histogram parameters 417 include the overall scale factor, background, instrument and sample parameters; 418 see the :ref:`Histogram_parameters_table` table for a list of the histogram 419 parameters where access has been provided. 420 421 * **Phase**: There will be a set of these for each phase loaded into a 422 project file. While some parameters are found in all types of phases, 423 others are only found in certain types (modulated, magnetic, protein...). 424 Typical phase parameters include unit cell lengths and atomic positions; see the 425 :ref:`Phase_parameters_table` table for a list of the phase 426 parameters where access has been provided. 427 428 * **Histogram-and-phase** (HAP): There is a set of these for every histogram 429 that is associated with each phase, so that if there are ``N`` phases and ``M`` 430 histograms, there can be ``N*M`` total sets of "HAP" parameters sets (fewer if all 431 histograms are not linked to all phases.) Typical HAP parameters include the 432 phase fractions, sample microstrain and crystallite size broadening terms, 433 hydrostatic strain perturbations of the unit cell and preferred orientation 434 values. 435 See the :ref:`HAP_parameters_table` table for the HAP parameters where access has 436 been provided. 437 438 .. _Refinement_parameters_fmt: 439 440 ================================= 441 Specifying Refinement Parameters 442 ================================= 443 444 Refinement parameter values and flags to turn refinement on and off are specified within dictionaries, 445 where the details of these dicts are organized depends on the 446 type of parameter (see :ref:`Refinement_parameters_kinds`), with a different set 447 of keys (as described below) for each of the three types of parameters. 448 449 .. _Histogram_parameters_table: 450 451 -------------------- 452 Histogram parameters 453 -------------------- 454 455 This table describes the dictionaries supplied to :func:`G2PwdrData.set_refinements` 456 and :func:`G2PwdrData.clear_refinements`. As an example, 457 458 .. code-block:: python 459 460 hist.set_refinements({"Background": {"no.coeffs": 3, "refine": True}, 461 "Sample Parameters": ["Scale"], 462 "Limits": [10000, 40000]}) 463 464 With :meth:`G2Project.do_refinements`, these parameters should be placed inside a dict with a key 465 ``set``, ``clear``, or ``once``. Values will be set for all histograms, unless the ``histograms`` 466 key is used to define specific histograms. As an example: 467 468 .. code-block:: python 469 470 gsas_proj.do_refinements([ 471 {'set': { 472 'Background': {'no.coeffs': 3, 'refine': True}, 473 'Sample Parameters': ['Scale'], 474 'Limits': [10000, 40000]}, 475 'histograms': [1,2]} 476 ]) 477 478 Note that below in the Instrument Parameters section, 479 related profile parameters (such as U and V) are grouped together but 480 separated by commas to save space in the table. 481 482 .. tabularcolumns:: |l|l|p{3.5in}| 483 484 ===================== ==================== ================================================= 485 key subkey explanation 486 ===================== ==================== ================================================= 487 Limits The range of 2-theta (degrees) or TOF (in 488 microsec) range of values to use. Can 489 be either a dictionary of 'low' and/or 'high', 490 or a list of 2 items [low, high] 491 \\ low Sets the low limit 492 \\ high Sets the high limit 493 494 Sample Parameters Should be provided as a **list** of subkeys 495 to set or clear,\\e.g. ['DisplaceX', 'Scale'] 496 \\ Absorption 497 \\ Contrast 498 \\ DisplaceX Sample displacement along the X direction 499 \\ DisplaceY Sample displacement along the Y direction 500 \\ Scale Histogram Scale factor 501 502 Background Sample background. Value will be a dict or 503 a boolean. If True or False, the refine 504 parameter for background is set to that. 505 Note that background peaks are not handled 506 via this; see 507 :meth:`G2PwdrData.ref_back_peak` instead. 508 When value is a dict, 509 supply any of the following keys: 510 \\ type The background model, e.g. 'chebyschev-1' 511 \\ refine The value of the refine flag, boolean 512 \\ 'no. coeffs' Number of coefficients to use, integer 513 \\ coeffs List of floats, literal values for background 514 \\ FixedPoints List of (2-theta, intensity) values for fixed points 515 \\ 'fit fixed points' If True, triggers a fit to the fixed points to 516 be calculated. It is calculated when this key is 517 detected, regardless of calls to refine. 518 \\ peaks Specifies a set of flags for refining 519 background peaks as a nested list. There may 520 be an item for each defined background peak 521 (or fewer) and each item is a list with the flag 522 values for pos,int,sig & gam (fewer than 4 values 523 are allowed). 524 525 Instrument Parameters As in Sample Paramters, provide as a **list** of 526 subkeys to 527 set or clear, e.g. ['X', 'Y', 'Zero', 'SH/L'] 528 \\ U, V, W Gaussian peak profile terms 529 \\ X, Y, Z Lorentzian peak profile terms 530 \\ alpha, beta-0, TOF profile terms 531 beta-1, beta-q, 532 \\ sig-0, sig-1, TOF profile terms 533 sig-2, sig-q 534 \\ difA, difB, difC TOF Calibration constants 535 \\ Zero Zero shift 536 \\ SH/L Finger-Cox-Jephcoat low-angle peak asymmetry 537 \\ Polariz. Polarization parameter 538 \\ Lam Lambda, the incident wavelength 539 ===================== ==================== ================================================= 540 541 .. _Phase_parameters_table: 542 543 ---------------- 544 Phase parameters 545 ---------------- 546 547 This table describes the dictionaries supplied to :func:`G2Phase.set_refinements` 548 and :func:`G2Phase.clear_refinements`. With :meth:`G2Project.do_refinements`, 549 these parameters should be placed inside a dict with a key 550 ``set``, ``clear``, or ``once``. Values will be set for all phases, unless the ``phases`` 551 key is used to define specific phase(s). 552 553 554 .. tabularcolumns:: |l|p{4.5in}| 555 556 ======= ========================================================== 557 key explanation 558 ======= ========================================================== 559 Cell Whether or not to refine the unit cell. 560 Atoms Dictionary of atoms and refinement flags. 561 Each key should be an atom label, e.g. 562 'O3', 'Mn5', and each value should be 563 a string defining what values to refine. 564 Values can be any combination of 'F' 565 for site fraction, 'X' for position, 566 and 'U' for Debye-Waller factor 567 LeBail Enables LeBail intensity extraction. 568 ======= ========================================================== 569 570 571 .. _HAP_parameters_table: 572 573 574 Histogram-and-phase parameters 575 ------------------------------ 576 577 This table describes the dictionaries supplied to :func:`G2Phase.set_HAP_refinements` 578 and :func:`G2Phase.clear_HAP_refinements`. When supplied to 579 :meth:`G2Project.do_refinements`, these parameters should be placed inside a dict with a key 580 ``set``, ``clear``, or ``once``. Values will be set for all histograms used in each phase, 581 unless the ``histograms`` and ``phases`` keys are used to define specific phases and histograms. 582 583 .. tabularcolumns:: |l|l|p{3.5in}| 584 585 ============= ========== ============================================================ 586 key subkey explanation 587 ============= ========== ============================================================ 588 Babinet Should be a **list** of the following 589 subkeys. If not, assumes both 590 BabA and BabU 591 \\ BabA 592 \\ BabU 593 Extinction Boolean, True to refine. 594 HStrain Boolean or list/tuple, True to refine all 595 appropriate D\\ :sub:`ij` terms or False 596 to not refine any. If a list/tuple, will 597 be a set of True & False values for each 598 D\\ :sub:`ij` term; number of items must 599 match number of terms. 600 Mustrain 601 \\ type Mustrain model. One of 'isotropic', 602 'uniaxial', or 'generalized'. **Should always 603 be included when Mustrain is used.** 604 \\ direction For uniaxial only. A list of three 605 integers, 606 the [hkl] direction of the axis. 607 \\ refine Usually boolean, set to True to refine. 608 or False to clear. 609 For uniaxial model, can specify a value 610 of 'axial' or 'equatorial' to set that flag 611 to True or a single 612 boolean sets both axial and equatorial. 613 Size 614 \\ type Size broadening model. One of 'isotropic', 615 'uniaxial', or 'ellipsoid'. **Should always 616 be specified when Size is used.** 617 \\ direction For uniaxial only. A list of three 618 integers, 619 the [hkl] direction of the axis. 620 \\ refine Boolean, True to refine. 621 \\ value float, size value in microns 622 Pref.Ori. Boolean, True to refine 623 Show Boolean, True to refine 624 Use Boolean, True to refine 625 Scale Phase fraction; Boolean, True to refine 626 ============= ========== ============================================================ 627 628 ------------------------ 629 Histogram/Phase objects 630 ------------------------ 631 Each phase and powder histogram in a :class:`G2Project` object has an associated 632 object. Parameters within each individual object can be turned on and off by calling 633 :meth:`G2PwdrData.set_refinements` or :meth:`G2PwdrData.clear_refinements` 634 for histogram parameters; 635 :meth:`G2Phase.set_refinements` or :meth:`G2Phase.clear_refinements` 636 for phase parameters; and :meth:`G2Phase.set_HAP_refinements` or 637 :meth:`G2Phase.clear_HAP_refinements`. As an example, if some_histogram is a histogram object (of type :class:`G2PwdrData`), use this to set parameters in that histogram: 638 639 .. code-block:: python 640 641 params = { 'Limits': [0.8, 12.0], 642 'Sample Parameters': ['Absorption', 'Contrast', 'DisplaceX'], 643 'Background': {'type': 'chebyschev-1', 'refine': True}} 644 some_histogram.set_refinements(params) 645 646 Likewise to turn refinement flags on, use code such as this: 647 648 .. code-block:: python 649 650 params = { 'Instrument Parameters': ['U', 'V', 'W']} 651 some_histogram.set_refinements(params) 652 653 and to turn these refinement flags, off use this (Note that the 654 ``.clear_refinements()`` methods will usually will turn off refinement even 655 if a refinement parameter is set in the dict to True.): 656 657 .. code-block:: python 658 659 params = { 'Instrument Parameters': ['U', 'V', 'W']} 660 some_histogram.clear_refinements(params) 661 662 For phase parameters, use code such as this: 663 664 .. code-block:: python 665 666 params = { 'LeBail': True, 'Cell': True, 667 'Atoms': { 'Mn1': 'X', 668 'O3': 'XU', 669 'V4': 'FXU'}} 670 some_histogram.set_refinements(params) 671 672 and here is an example for HAP parameters: 673 674 .. code-block:: python 675 676 params = { 'Babinet': 'BabA', 677 'Extinction': True, 678 'Mustrain': { 'type': 'uniaxial', 679 'direction': [0, 0, 1], 680 'refine': True}} 681 some_phase.set_HAP_refinements(params) 682 683 Note that the parameters must match the object type and method (phase vs. histogram vs. HAP). 684 685 .. _AccessingOtherItems: 686 687 =================================== 688 Access to other parameter settings 689 =================================== 690 691 There are several hundred different types of values that can be stored in a 692 GSAS-II project (.gpx) file. All can be changed from the GUI but only a 693 subset have direct mechanism implemented for change from the GSASIIscriptable 694 API. In practice all parameters in a .gpx file can be edited via scripting, 695 but sometimes determining what should be set to implement a parameter 696 change can be complex. 697 Several routines, :meth:`G2Phase.getHAPentryList`, 698 :meth:`G2Phase.getPhaseEntryList` and :meth:`G2PwdrData.getHistEntryList` 699 (and their related get...Value and set.Value entries), 700 provide a mechanism to discover what the GUI is changing inside a .gpx file. 701 702 As an example, a user in changing the data type for a histogram from Debye-Scherrer 703 mode to Bragg-Brentano. This capability is not directly exposed in the API. To 704 find out what changes when the histogram type is changed we can create a short script 705 that displays the contents of all the histogram settings: 706 707 .. code-block:: python 708 709 from __future__ import division, print_function 710 import os,sys 711 sys.path.insert(0,'/Users/toby/software/G2/GSASII') 712 import GSASIIscriptable as G2sc 713 gpx = G2sc.G2Project('/tmp/test.gpx') 714 h = gpx.histograms()[0] 715 for h in h.getHistEntryList(): 716 print(h) 717 718 This can be run with a command like this:: 719 720 python test.py > before.txt 721 722 (This will create file ``before.txt``, which will contain hundreds of lines.) 723 724 At this point open the project file, ``test.gpx`` in the GSAS-II GUI and 725 change in Histogram/Sample Parameters the diffractometer type from Debye-Scherrer 726 mode to Bragg-Brentano and then save the file. 727 728 Rerun the previous script creating a new file:: 729 730 python test.py > after.txt 731 732 Finally look for the differences between files ``before.txt`` and ``after.txt`` using a tool 733 such as diff (on Linux/OS X) or fc (in Windows). 734 735 in Windows:: 736 737 Z:\\>fc before.txt after.txt 738 Comparing files before.txt and after.txt 739 ***** before.txt 740 fill_value = 1e+20) 741 , 'PWDR Co_PCP_Act_d900-00030.fxye Bank 1', 'PWDR Co_PCP_Act_d900-00030.fxye Ban 742 k 1']) 743 (['Comments'], <class 'list'>, ['Co_PCP_Act_d900-00030.tif #0001 Azm= 180.00']) 744 ***** AFTER.TXT 745 fill_value = 1e+20) 746 , 'PWDR Co_PCP_Act_d900-00030.fxye Bank 1', 'PWDR Co_PCP_Act_d900-00030.fxye Ban 747 k 1', 'PWDR Co_PCP_Act_d900-00030.fxye Bank 1'] 748 749 (['Comments'], <class 'list'>, ['Co_PCP_Act_d900-00030.tif #0001 Azm= 180.00']) 750 ***** 751 752 ***** before.txt 753 (['Sample Parameters', 'Scale'], <class 'list'>, [1.276313196832068, True]) 754 (['Sample Parameters', 'Type'], <class 'str'>, 'Debye-Scherrer') 755 (['Sample Parameters', 'Absorption'], <class 'list'>, [0.0, False]) 756 ***** AFTER.TXT 757 (['Sample Parameters', 'Scale'], <class 'list'>, [1.276313196832068, True]) 758 (['Sample Parameters', 'Type'], <class 'str'>, 'Bragg-Brentano') 759 (['Sample Parameters', 'Absorption'], <class 'list'>, [0.0, False]) 760 ***** 761 762 in Linux/Mac:: 763 764 bht14: toby$ diff before.txt after.txt 765 103c103 766 < , 'PWDR Co_PCP_Act_d900-00030.fxye Bank 1', 'PWDR Co_PCP_Act_d900-00030.fxye Bank 1']) 767 --- 768 > , 'PWDR Co_PCP_Act_d900-00030.fxye Bank 1', 'PWDR Co_PCP_Act_d900-00030.fxye Bank 1', 'PWDR Co_PCP_Act_d900-00030.fxye Bank 1']) 769 111c111 770 < (['Sample Parameters', 'Type'], <class 'str'>, 'Debye-Scherrer') 771 --- 772 > (['Sample Parameters', 'Type'], <class 'str'>, 'Bragg-Brentano') 773 774 From this we can see there are two changes that took place. One is fairly obscure, 775 where the histogram name is added to a list, which can be ignored, but the second change 776 occurs in a straight-forward way and we discover that a simple call:: 777 778 h.setHistEntryValue(['Sample Parameters', 'Type'], 'Bragg-Brentano') 779 780 can be used to change the histogram type. 781 782 .. _CodeExamples: 783 784 ================================= 785 Code Examples 786 ================================= 787 788 .. _PeakRefine: 789 790 -------------------- 791 Peak Fitting 792 -------------------- 793 794 Peak refinement is performed with routines 795 :meth:`G2PwdrData.add_peak`, :meth:`G2PwdrData.set_peakFlags` and 796 :meth:`G2PwdrData.refine_peaks`. Method :meth:`G2PwdrData.Export_peaks` and 797 properties :attr:`G2PwdrData.Peaks` and :attr:`G2PwdrData.PeakList` 798 provide ways to access the results. Note that when peak parameters are 799 refined with :meth:`~G2PwdrData.refine_peaks`, the background may also 800 be refined. Use :meth:`G2PwdrData.set_refinements` to change background 801 settings and the range of data used in the fit. See below for an example 802 peak refinement script, where the data files are taken from the 803 "Rietveld refinement with CuKa lab Bragg-Brentano powder data" tutorial 804 (in https://subversion.xray.aps.anl.gov/pyGSAS/Tutorials/LabData/data/). 805 806 .. code-block:: python 807 808 from __future__ import division, print_function 809 import os,sys 810 sys.path.insert(0,'/Users/toby/software/G2/GSASII') # needed to "find" GSAS-II modules 811 import GSASIIscriptable as G2sc 812 datadir = os.path.expanduser("~/Scratch/peakfit") 813 PathWrap = lambda fil: os.path.join(datadir,fil) 814 gpx = G2sc.G2Project(newgpx=PathWrap('pkfit.gpx')) 815 hist = gpx.add_powder_histogram(PathWrap('FAP.XRA'), PathWrap('INST_XRY.PRM'), 816 fmthint='GSAS powder') 817 hist.set_refinements({'Limits': [16.,24.], 818 'Background': {"no. coeffs": 2,'type': 'chebyschev-1', 'refine': True} 819 }) 820 peak1 = hist.add_peak(1, ttheta=16.8) 821 peak2 = hist.add_peak(1, ttheta=18.9) 822 peak3 = hist.add_peak(1, ttheta=21.8) 823 peak4 = hist.add_peak(1, ttheta=22.9) 824 hist.set_peakFlags(area=True) 825 hist.refine_peaks() 826 hist.set_peakFlags(area=True,pos=True) 827 hist.refine_peaks() 828 hist.set_peakFlags(area=True, pos=True, sig=True, gam=True) 829 res = hist.refine_peaks() 830 print('peak positions: ',[i[0] for i in hist.PeakList]) 831 for i in range(len(hist.Peaks['peaks'])): 832 print('peak',i,'pos=',hist.Peaks['peaks'][i][0],'sig=',hist.Peaks['sigDict']['pos'+str(i)]) 833 hist.Export_peaks('pkfit.txt') 834 #gpx.save() # gpx file is not written without this 835 836 ----------------------- 837 Pattern Simulation 838 ----------------------- 839 840 This shows two examples where a structure is read from a CIF, a 841 pattern is computed using a instrument parameter file to specify the 842 probe type (neutrons here) and wavelength. 843 844 The first example uses a CW neutron instrument parameter file. 845 The pattern is computed over a 2Ξ range of 5 to 120 degrees 846 with 1000 points. 847 The pattern and reflection list are written into files. 848 Data files are found in the 849 `Scripting Tutorial <https://subversion.xray.aps.anl.gov/pyGSAS/Tutorials/PythonScript/data/>`_. 850 851 .. code-block:: python 852 853 import os,sys 854 sys.path.insert(0,'/Users/toby/software/G2/GSASII') 855 import GSASIIscriptable as G2sc 856 datadir = "/Users/toby/software/G2/Tutorials/PythonScript/data" 857 PathWrap = lambda fil: os.path.join(datadir,fil) 858 gpx = G2sc.G2Project(newgpx='PbSO4sim.gpx') # create a project 859 phase0 = gpx.add_phase(PathWrap("PbSO4-Wyckoff.cif"), 860 phasename="PbSO4",fmthint='CIF') # add a phase to the project 861 # add a simulated histogram and link it to the previous phase(s) 862 hist1 = gpx.add_simulated_powder_histogram("PbSO4 simulation", 863 PathWrap("inst_d1a.prm"),5.,120.,Npoints=1000, 864 phases=gpx.phases(),scale=500000.) 865 gpx.do_refinements() # calculate pattern 866 gpx.save() 867 # save results 868 gpx.histogram(0).Export('PbSO4data','.csv','hist') # data 869 gpx.histogram(0).Export('PbSO4refl','.csv','refl') # reflections 870 871 This example uses bank#2 from a TOF neutron instrument parameter file. 872 The pattern is computed over a TOF range of 14 to 35 milliseconds with 873 the default of 2500 points. 874 This uses the same CIF as in the example before, but the instrument is found in the 875 `TOF-CW Joint Refinement Tutorial <https://subversion.xray.aps.anl.gov/pyGSAS/Tutorials/TOF-CW Joint Refinement/data>`_ 876 tutorial. 877 878 .. code-block:: python 879 880 import os,sys 881 sys.path.insert(0,'/Users/toby/software/G2/GSASII') 882 import GSASIIscriptable as G2sc 883 cifdir = "/Users/toby/software/G2/Tutorials/PythonScript/data" 884 datadir = "/Users/toby/software/G2/Tutorials/TOF-CW Joint Refinement/data" 885 gpx = G2sc.G2Project(newgpx='/tmp/PbSO4simT.gpx') # create a project 886 phase0 = gpx.add_phase(os.path.join(cifdir,"PbSO4-Wyckoff.cif"), 887 phasename="PbSO4",fmthint='CIF') # add a phase to the project 888 hist1 = gpx.add_simulated_powder_histogram("PbSO4 simulation", 889 os.path.join(datadir,"POWGEN_1066.instprm"),14.,35., 890 phases=gpx.phases(),ibank=2) 891 gpx.do_refinements([{}]) 892 gpx.save() 893 894 ---------------------- 895 Simple Refinement 896 ---------------------- 897 898 GSASIIscriptable can be used to setup and perform simple refinements. 899 This example reads in an existing project (.gpx) file, adds a background 900 peak, changes some refinement flags and performs a refinement. 901 902 .. code-block:: python 903 904 from __future__ import division, print_function 905 import os,sys 906 sys.path.insert(0,'/Users/toby/software/G2/GSASII') # needed to "find" GSAS-II modules 907 import GSASIIscriptable as G2sc 908 datadir = "/Users/Scratch/" 909 gpx = G2sc.G2Project(os.path.join(datadir,'test2.gpx')) 910 gpx.histogram(0).add_back_peak(4.5,30000,5000,0) 911 pardict = {'set': {'Sample Parameters': ['Absorption', 'Contrast', 'DisplaceX'], 912 'Background': {'type': 'chebyschev-1', 'refine': True, 913 'peaks':[[0,True]]}}} 914 gpx.set_refinement(pardict) 915 916 ---------------------- 917 Sequential Refinement 918 ---------------------- 919 920 GSASIIscriptable can be used to setup and perform sequential refinements. This example script 921 is used to take the single-dataset fit at the end of Step 1 of the 922 `Sequential Refinement tutorial <https://subversion.xray.aps.anl.gov/pyGSAS/Tutorials/SeqRefine/SequentialTutorial.htm>`_ 923 and turn on and off refinement flags, add histograms and setup the sequential fit, which is then run: 924 925 .. code-block:: python 926 927 import os,sys,glob 928 sys.path.insert(0,'/Users/toby/software/G2/GSASII') 929 import GSASIIscriptable as G2sc 930 datadir = os.path.expanduser("~/Scratch/SeqTut2019Mar") 931 PathWrap = lambda fil: os.path.join(datadir,fil) 932 # load and rename project 933 gpx = G2sc.G2Project(PathWrap('7Konly.gpx')) 934 gpx.save(PathWrap('SeqRef.gpx')) 935 # turn off some variables; turn on Dijs 936 for p in gpx.phases(): 937 p.set_refinements({"Cell": False}) 938 gpx.phase(0).set_HAP_refinements( 939 {'Scale': False, 940 "Size": {'type':'isotropic', 'refine': False}, 941 "Mustrain": {'type':'uniaxial', 'refine': False}, 942 "HStrain":True,}) 943 gpx.phase(1).set_HAP_refinements({'Scale': False}) 944 gpx.histogram(0).clear_refinements({'Background':False, 945 'Sample Parameters':['DisplaceX'],}) 946 gpx.histogram(0).ref_back_peak(0,[]) 947 gpx.phase(1).set_HAP_refinements({"HStrain":(1,1,1,0)}) 948 for fil in sorted(glob.glob(PathWrap('*.fxye'))): # load in remaining fxye files 949 if '00' in fil: continue 950 gpx.add_powder_histogram(fil, PathWrap('OH_00.prm'), fmthint="GSAS powder",phases='all') 951 # copy HAP values, background, instrument params. & limits, not sample params. 952 gpx.copyHistParms(0,'all',['b','i','l']) 953 for p in gpx.phases(): p.copyHAPvalues(0,'all') 954 # setup and launch sequential fit 955 gpx.set_Controls('sequential',gpx.histograms()) 956 gpx.set_Controls('cycles',10) 957 gpx.set_Controls('seqCopy',True) 958 gpx.refine() 959 960 .. _ImageProc: 961 962 ---------------------- 963 Image Processing 964 ---------------------- 965 966 A sample script where an image is read, assigned calibration values from a file 967 and then integrated follows. 968 The data files are found in the 969 `Scripting Tutorial <https://subversion.xray.aps.anl.gov/pyGSAS/Tutorials/PythonScript/data/>`_. 970 971 .. code-block:: python 972 973 import os,sys 974 sys.path.insert(0,'/Users/toby/software/G2/GSASII') 975 import GSASIIscriptable as G2sc 976 datadir = "/tmp" 977 PathWrap = lambda fil: os.path.join(datadir,fil) 978 979 gpx = G2sc.G2Project(newgpx=PathWrap('inttest.gpx')) 980 imlst = gpx.add_image(PathWrap('Si_free_dc800_1-00000.tif'),fmthint="TIF") 981 imlst[0].loadControls(PathWrap('Si_free_dc800_1-00000.imctrl')) 982 pwdrList = imlst[0].Integrate() 983 gpx.save() 984 985 This example shows a computation similar to what is done in tutorial 986 `Area Detector Calibration with Multiple Distances <https://subversion.xray.aps.anl.gov/pyGSAS/Tutorials/DeterminingWavelength/DeterminingWavelength.html>`_ 987 988 .. code-block:: python 989 990 import os,sys,glob 991 sys.path.insert(0,'/Users/toby/software/G2/GSASII') 992 import GSASIIscriptable as G2sc 993 PathWrap = lambda fil: os.path.join( 994 "/Users/toby/wp/Active/MultidistanceCalibration/multimg", 995 fil) 996 997 gpx = G2sc.G2Project(newgpx='/tmp/img.gpx') 998 for f in glob.glob(PathWrap('*.tif')): 999 im = gpx.add_image(f,fmthint="TIF") 1000 # image parameter settings 1001 defImgVals = {'wavelength': 0.24152, 'center': [206., 205.], 1002 'pixLimit': 2, 'cutoff': 5.0, 'DetDepth': 0.055,'calibdmin': 1.,} 1003 # set controls and vary options, then fit 1004 for img in gpx.images(): 1005 img.setCalibrant('Si SRM640c') 1006 img.setVary('*',False) 1007 img.setVary(['det-X', 'det-Y', 'phi', 'tilt', 'wave'], True) 1008 img.setControls(defImgVals) 1009 img.Recalibrate() 1010 img.Recalibrate() # 2nd run better insures convergence 1011 gpx.save() 1012 # make dict of images for sorting 1013 images = {img.getControl('setdist'):img for img in gpx.images()} 1014 # show values 1015 for key in sorted(images.keys()): 1016 img = images[key] 1017 c = img.getControls() 1018 print(c['distance'],c['wavelength']) 1019 1020 .. _MultiDist_Example: 1021 1022 ---------------------- 1023 Image Calibration 1024 ---------------------- 1025 1026 This example performs a number of cycles of constrained fitting. 1027 A project is created with the images found in a directory, setting initial 1028 parameters as the images are read. The initial values 1029 for the calibration are not very good, so a :meth:`G2Image.Recalibrate` is done 1030 to quickly improve the fit. Once that is done, a fit of all images is performed 1031 where the wavelength, an offset and detector orientation are constrained to 1032 be the same for all images. The detector penetration correction is then added. 1033 Note that as the calibration values improve, the algorithm is able to find more 1034 points on diffraction rings to use for calibration and the number of "ring picks" 1035 increase. The calibration is repeated until that stops increasing significantly (<10%). 1036 Detector control files are then created. 1037 The files used for this exercise are found in the 1038 `Area Detector Calibration Tutorial <https://subversion.xray.aps.anl.gov/pyGSAS/Tutorials/DeterminingWavelength/data/>`_ 1039 (see 1040 `Area Detector Calibration with Multiple Distances <https://subversion.xray.aps.anl.gov/pyGSAS/Tutorials/DeterminingWavelength/DeterminingWavelength.html>`_ ). 1041 1042 .. code-block:: python 1043 1044 import os,sys,glob 1045 sys.path.insert(0,'/Users/toby/software/G2/GSASII') 1046 import GSASIIscriptable as G2sc 1047 PathWrap = lambda fil: os.path.join( 1048 "/Users/toby/wp/Active/MultidistanceCalibration/multimg", 1049 fil) 1050 1051 gpx = G2sc.G2Project(newgpx='/tmp/calib.gpx') 1052 for f in glob.glob(PathWrap('*.tif')): 1053 im = gpx.add_image(f,fmthint="TIF") 1054 # starting image parameter settings 1055 defImgVals = {'wavelength': 0.240, 'center': [206., 205.], 1056 'pixLimit': 2, 'cutoff': 5.0, 'DetDepth': 0.03,'calibdmin': 0.5,} 1057 # set controls and vary options, then initial fit 1058 for img in gpx.images(): 1059 img.setCalibrant('Si SRM640c') 1060 img.setVary('*',False) 1061 img.setVary(['det-X', 'det-Y', 'phi', 'tilt', 'wave'], True) 1062 img.setControls(defImgVals) 1063 if img.getControl('setdist') > 900: 1064 img.setControls({'calibdmin': 1.,}) 1065 img.Recalibrate() 1066 G2sc.SetPrintLevel('warn') # cut down on output 1067 result,covData = gpx.imageMultiDistCalib() 1068 print('1st global fit: initial ring picks',covData['obs']) 1069 print({i:result[i] for i in result if '-' not in i}) 1070 # add parameter to all images & refit multiple times 1071 for img in gpx.images(): img.setVary('dep',True) 1072 ringpicks = covData['obs'] 1073 delta = ringpicks 1074 while delta > ringpicks/10: 1075 result,covData = gpx.imageMultiDistCalib(verbose=False) 1076 delta = covData['obs'] - ringpicks 1077 print('ring picks went from',ringpicks,'to',covData['obs']) 1078 print({i:result[i] for i in result if '-' not in i}) 1079 ringpicks = covData['obs'] 1080 # once more for good measure & printout 1081 result,covData = gpx.imageMultiDistCalib(verbose=True) 1082 # create image control files 1083 for img in gpx.images(): 1084 img.saveControls(os.path.splitext(img.name)[0]+'.imctrl') 1085 gpx.save() 1086 1087 .. _HistExport: 1088 1089 -------------------- 1090 Histogram Export 1091 -------------------- 1092 1093 This example shows how to export a series of histograms from a collection of 1094 .gpx (project) files. The Python ``glob()`` function is used to find all files 1095 matching a wildcard in the specified directory (``dataloc``). For each file 1096 there is a loop over histograms in that project and for each histogram 1097 :meth:`G2PwdrData.Export` is called to write out the contents of that histogram 1098 as CSV (comma-separated variable) file that contains data positions, 1099 observed, computed and backgroun intensities as well as weighting for each 1100 point and Q. Note that for the Export call, there is more than one choice of 1101 exporter that can write ``.csv`` extension files, so the export hint must 1102 be specified. 1103 1104 .. code-block:: python 1105 1106 import os,sys,glob 1107 sys.path.insert(0,'/Users/toby/software/G2/GSASII') # change this 1108 import GSASIIscriptable as G2sc 1109 1110 dataloc = "/Users/toby/Scratch/" # where to find data 1111 PathWrap = lambda fil: os.path.join(dataloc,fil) # EZ way 2 add dir to filename 1112 1113 for f in glob.glob(PathWrap('bkg*.gpx')): # put filename prefix here 1114 print(f) 1115 gpx = G2sc.G2Project(f) 1116 for i,h in enumerate(gpx.histograms()): 1117 hfil = os.path.splitext(f)[0]+'_'+str(i) # file to write 1118 print('\t',h.name,hfil+'.csv') 1119 h.Export(hfil,'.csv','histogram CSV') 1120 1121 .. _CommandlineInterface: 1122 1123 ======================================= 1124 Installation of GSASIIscriptable 1125 ======================================= 1126 1127 It is assumed that most people using GSASIIscriptable will also want to use the GUI, for this the standard 1128 `installation instructions <https://subversion.xray.aps.anl.gov/trac/pyGSAS#Installationinstructions>`_ should be followed. The GUI includes all files needed to run scriptable. 1129 Noting that not all GSAS-II capabilities are not available 1130 by scripting -- yet. Even if the scripting API were to be fully completed, 1131 there will still be some things that GSAS-II does 1132 with the GUI would be almost impossible to implement without a 1133 interactive graphical view of the data. 1134 1135 Nonetheless, there may be times where it does make sense to install GSAS-II without all of the GUI components, for example on a compute server. As `described here 1136 <https://gsas-ii.readthedocs.io/en/latest/packages.html#scripting-requirements>`_ the minimal python requirements are only numpy and scipy. It is assumed that 1137 anyone able to use scripting is well posed to install from the command line. 1138 Below are example commands to install GSAS-II for use for scripting only. 1139 1140 **Installing a minimal Python configuration**: Note I have chosen below 1141 to use the free 1142 miniconda installer from Anaconda, Inc., but there are also plenty of 1143 other ways to install Python, Numpy and Scipy on Linux, Windows and MacOS. 1144 For Linux a reasonable alternative is to install these packages 1145 (and perhaps others as below) using the Linux dist (``apt-get`` etc.). 1146 1147 .. code-block:: bash 1148 1149 bash ~/Downloads/Miniconda3-latest-<platform>-x86_64.sh -b -p /loc/pyg2script 1150 source /loc/pyg2script/bin/activate 1151 conda install numpy scipy matplotlib pillow h5py hdf5 svn 1152 1153 Some discussion on these commands follows: 1154 1155 * the 1st command (bash) assumes that the appropriate version of Miniconda has been downloaded from https://docs.conda.io/en/latest/miniconda.html and ``/loc/pyg2script`` is where I have selected for python to be installed. You might want to use something like ``~/pyg2script``. 1156 * the 2nd command (source) is needed to access Python with miniconda. 1157 * the 3rd command (conda) installs all possible packages that might be used by scripting, but matplotlib, pillow, and hdf5 are not commonly needed and could be omitted. The svn package is not needed (for example on Linux) where this has been installed in another way. 1158 1159 Once svn and Python has been installed and is in the path, use these commands to install GSAS-II: 1160 1161 .. code-block:: bash 1162 1163 svn co https://subversion.xray.aps.anl.gov/pyGSAS/trunk /loc/GSASII 1164 python /loc/GSASII/GSASIIscriptable.py 1165 1166 Notes on these commands: 1167 1168 * the 1st command (svn) is used to download the GSAS-II software. ``/loc/GSASII`` is the location where I decided to install the software. You can select something different. 1169 * the 2nd command (python) is used to invoke GSAS-II scriptable for the first time, which is needed to load the binary files from the server. 1170 1171 ======================================= 1172 GSASIIscriptable Command-line Interface 1173 ======================================= 1174 1175 The routines described above are intended to be called from a Python script, but an 1176 alternate way to access some of the same functionality is to 1177 invoke the ``GSASIIscriptable.py`` script from 1178 the command line usually from within a shell script or batch file. 1179 This mode of accessing GSAS-II scripting does not appear to get much use and 1180 is no longer being developed. Please do communicate to the developers if 1181 keeping this mode of access would be of value in your work. 1182 1183 To use the command-line mode is done with a command like this:: 1184 1185 python <path/>GSASIIscriptable.py <subcommand> <file.gpx> <options> 1186 1187 The following subcommands are defined: 1188 1189 * create, see :func:`create` 1190 * add, see :func:`add` 1191 * dump, see :func:`dump` 1192 * refine, see :func:`refine` 1193 * export, :func:`export` 1194 * browse, see :func:`IPyBrowse` 1195 1196 Run:: 1197 1198 python GSASIIscriptable.py --help 1199 1200 to show the available subcommands, and inspect each subcommand with 1201 `python GSASIIscriptable.py <subcommand> --help` or see the documentation for each of the above routines. 1202 1203 .. _JsonFormat: 1204 1205 ------------------------- 1206 Parameters in JSON files 1207 ------------------------- 1208 1209 The refine command requires two inputs: an existing GSAS-II project (.gpx) file and 1210 a JSON format file 1211 (see `Introducing JSON <http://json.org/>`_) that contains a single dict. 1212 This dict may have two keys: 1213 1214 refinements: 1215 This defines the a set of refinement steps in a JSON representation of a 1216 :ref:`Refinement_recipe` list. 1217 1218 code: 1219 This optionally defines Python code that will be executed after the project is loaded, 1220 but before the refinement is started. This can be used to execute Python code to change 1221 parameters that are not accessible via a :ref:`Refinement_recipe` dict (note that the 1222 project object is accessed with variable ``proj``) or to define code that will be called 1223 later (see key ``call`` in the :ref:`Refinement_recipe` section.) 1224 1225 JSON website: `Introducing JSON <http://json.org/>`_. 1226 1227 .. _API: 1228 1229 ============================================================ 1230 API: Complete Documentation 1231 ============================================================ 1232 1233 The classes and modules in this module are described below. 12 Classes and routines defined in :mod:`GSASIIscriptable` follow. 1234 13 A script will create one or more :class:`G2Project` objects by reading 1235 14 a GSAS-II project (.gpx) file or creating a new one and will then … … 1240 19 1241 20 To change settings within histograms, images and phases, one usually needs to use 1242 methods inside :class:`G2PwdrData`, :class:`G2Image` or :class:`G2Phase`. 21 methods inside :class:`G2PwdrData`, :class:`G2Image` or :class:`G2Phase`. 1243 22 """ 23 # Note that documentation for GSASIIscriptable.py has been moved 24 # to file docs/source/GSASIIscriptable.rst 1244 25 1245 26 #============================================================================ -
trunk/GSASIIspc.py
r5513 r5572 1 1 # -*- coding: utf-8 -*- 2 """3 *GSASIIspc: Space group module*4 -------------------------------5 6 Space group interpretation routines. Note that space group information is7 stored in a :ref:`Space Group (SGData)<SGData_table>` object.8 9 """10 2 ########### SVN repository information ################### 11 3 # $Date$ … … 15 7 # $Id$ 16 8 ########### SVN repository information ################### 9 ''':mod:`GSASIIspc` Classes & routines follow 10 ''' 17 11 from __future__ import division, print_function 18 12 import numpy as np -
trunk/ImageCalibrants.py
r4889 r5572 1 1 """ 2 *ImageCalibrants: Calibration Standards*3 ----------------------------------------4 5 2 GSASII powder calibrants in dictionary ``ImageCalibrants.Calibrants`` 6 3 containing substances commonly used for powder calibrations for image data. -
trunk/ReadMarCCDFrame.py
r5329 r5572 1 1 #!/usr/bin/env python 2 from __future__ import division, print_function 3 '''Defines a routine to read from MARCCD files 2 4 ''' 3 *ReadMarCCDFrame: Read Mar Files* 4 --------------------------------- 5 6 ''' 7 from __future__ import division, print_function 5 8 6 """ 9 7 from /opt/marccd/documentation/header.txt 10 8 11 9 MarCCD Header Documentataion -
trunk/Substances.py
r4094 r5572 1 #/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 ########### SVN repository information ################### 4 # $Date$ 5 # $Author$ 6 # $Revision$ 7 # $URL$ 8 # $Id$ 9 ########### SVN repository information ################### 1 10 """ 2 *Substances: Define Materials*3 ---------------------------------------------------------------------------------4 5 11 Defines materials commonly found in small angle & reflectometry experiments. 6 12 GSASII substances as a dictionary ''Substances.Substances'' with these materials. … … 11 17 12 18 Density & Volume are optional, if one missing it is calculated from the other; if both 13 are missing then Volume is estimated from composition & assuming 10 A^3 for each atom,19 are missing then Volume is estimated from composition & assuming 10 \\AA^3 for each atom. 14 20 Density is calculated from that Volume. 15 21 See examples below for what is needed. -
trunk/atmdata.py
r5494 r5572 1 1 ''' 2 *atmdata: Table of atomic data*3 ---------------------------------4 5 2 The entries here are: 6 3 -
trunk/config_example.py
r5443 r5572 9 9 ########### SVN repository information ################### 10 10 ''' 11 *config_example.py: Configuration options*12 -------------------------------------------13 14 11 This file contains optional configuration options for GSAS-II. The variables 15 12 in this file can be copied to file config.py, which is imported if present. -
trunk/defaultIparms.py
r4578 r5572 10 10 ########### SVN repository information ################### 11 11 ''' 12 *defaultIparms: Table of instrument parameters*13 -----------------------------------------------14 15 12 Defines some default instrument parameters. 16 13 Format for each is a list of strings finished with a '\n'. -
trunk/docs/source/GSASII.rst
r2027 r5572 1 Main routine: GSASII.py 2 =========================== 3 4 *GSASII: GSAS-II GUI* 5 ---------------------------------------- 6 7 File GSASII.py is the script to start the GSAS-II graphical user 8 interface (GUI). 9 This script imports GSASIIpath, which does some minor initialization 10 and then (before any wxPython calls can be made) creates a wx.App application. 11 A this point :func:`GSASIIpath.SetBinaryPath` is called to establish 12 the directory where GSAS-II binaries are found. If the binaries 13 are not installed or are incompatible with the OS/Python packages, 14 the user is asked if they should be updated from the subversion site. 15 The wxPython app is then passed to :func:`GSASIIdataGUI.GSASIImain`, 16 which creates the GSAS-II GUI and finally the event loop is started. 17 18 Keyboard Menu Shortcuts 19 ---------------------------------------- 20 21 Shortcuts for commonly-used menu commands are created by adding a 22 menu command with a "\tctrl+" addition such as:: 23 24 item = parent.Append(wx.ID_ANY,'&Refine\tCtrl+R','Perform a refinement') 25 26 This will allow the above menu command to be executed with a "Control-R" 27 keyboard command (on MacOS this will be "Command+R" rather than "Control-R") as well as using the menu to access that action. The following table lists the 28 keyboard letters/numbers that have GSAS-II assigned actions. 29 are system assigned. Note that there are also plotting keyboard commands that are 30 implemented in :mod:`GSASIIplot`. 31 These can be discovered from the "K" button on the plot menu bar as they 32 vary depending on the type of plot. 33 34 .. tabularcolumns:: |c|p{4in}| 35 36 ========== ==================================================== 37 key explanation 38 ========== ==================================================== 39 O Open project (File menu) 40 E Reopen recent (File menu) 41 S Save project (File menu) 42 B Project browser (File menu) 43 Q Quit (File menu). This is system assigned on MacOS 44 F4 Quit (File menu). This is system-assigned 45 on Windows 46 47 L View LS parms (Calculate menu) 48 R Refine/Sequential Refine (Calculate menu) 49 I Parameter Impact (Calculate menu) 50 51 U Check for updates (Help menu) 52 T Tutorials (Help menu) 53 F1 Help on current tree item (Help menu). 54 This is system-assigned 55 56 P Peakfit (Peak Fitting menu, requires selection of 57 Histogram Peak) 58 59 M Minimize GSAS-II windows (MacOS Windows menu). 60 This is system-assigned 61 ========== ==================================================== 62 63 GSAS-II contents 64 ---------------------------------------- 65 66 1 67 .. automodule:: GSASII 2 68 :members: 69 :private-members: 70 :special-members: -
trunk/docs/source/GSASIIGUIr.rst
r4800 r5572 1 1 *GSAS-II GUI Utility Modules* 2 2 ============================== 3 4 --------------------------------------------- 5 *GSASIIctrlGUI: Custom GUI controls* 6 --------------------------------------------- 7 8 A library of GUI controls for reuse throughout GSAS-II, as indexed below 9 10 .. tabularcolumns:: |l|p{4in}| 11 12 ================================ ================================================================= 13 Class or function name Description 14 ================================ ================================================================= 15 :class:`EnumSelector` A combo box with a built-in call back routine that 16 automatically sets a dict or list entry. 17 :class:`DisAglDialog` Distance/Angle Controls input dialog. 18 :class:`FlagSetDialog` Dialog that provides a table of items along with a 19 checkbox for each. 20 :class:`G2ChoiceButton` A customized wx.Choice that automatically initializes to 21 the initial value and saves the choice directly into a dict 22 or list value. Optionally calls function when a 23 choice is selected 24 :class:`G2CheckBox` A customized wx.CheckBox that automatically initializes to 25 the initial value and saves the choice directly into a dict 26 or list value. Optionally calls function when a 27 choice is selected 28 :func:`G2CheckBoxFrontLbl` A version of :class:`G2CheckBox` that places the label 29 for the check box in front. Otherwise works the same. 30 :func:`G2RadioButtons` Creates a series of grouped radio buttons. 31 :class:`G2SliderWidget` A customized combination of a wx.Slider and a validated 32 wx.TextCtrl (see :class:`ValidatedTxtCtrl`). 33 :class:`G2Slider` A wrapped version of wx.Slider that implements scaling 34 :class:`G2SpinWidget` A customized combination of a wx.SpinButton and a validated 35 wx.TextCtrl (see :class:`ValidatedTxtCtrl`). 36 :class:`G2ColumnIDDialog` A dialog for matching column data to desired items; some 37 columns may be ignored. 38 :class:`G2HistoDataDialog` A dialog for global edits to histogram data globally 39 :class:`G2MultiChoiceDialog` Dialog similar to wx.MultiChoiceDialog, but provides 40 a filter to select choices and buttons to make selection 41 of multiple items more simple. 42 :class:`G2MultiChoiceWindow` Similar to :class:`G2MultiChoiceDialog` but provides 43 a sizer that can be placed in a frame or panel. 44 :class:`G2SingleChoiceDialog` Dialog similar to wx.SingleChoiceDialog, but provides 45 a filter to help search through choices. 46 :class:`HelpButton` Creates a button labeled with a "?" that when pressed 47 displays help text in a modal message window 48 or web browser. 49 :class:`MultiColumnSelection` A dialog that builds a multicolumn table, word wrapping 50 is used for the 2nd, 3rd,... columns. 51 :class:`MultiDataDialog` Dialog to obtain multiple data values from user, 52 with optional range validation; items can be float, str or bool 53 :class:`MultiIntegerDialog` Dialog to obtain multiple integer values from user, 54 with a description for each value and optional 55 defaults. 56 :class:`MultiStringDialog` Dialog to obtain multiple string values from user, 57 with a description for each value and optional 58 defaults. 59 :class:`OrderBox` Creates a wx.Panel with scrollbars where items can be 60 ordered into columns. 61 :class:`SortableLstCtrl` Creates a wx.Panel for a table of data that 62 can be sorted by clicking on a column label. 63 :class:`ScrolledMultiEditor` wx.Dialog for editing many dict- or list-contained items. 64 with validation. Results are placed in dict or list. 65 :class:`SGMagSpinBox` Special version of MessageBox that displays magnetic spin text 66 :class:`SGMessageBox` Special version of MessageBox that displays space group & 67 super space group text in two blocks 68 :class:`SingleFloatDialog` Dialog to obtain a single float value from user, with 69 optional range validation. 70 :class:`SingleIntDialog` Dialog to obtain a single integer value from user, 71 with optional range validation. 72 :class:`SingleStringDialog` Dialog to obtain a single string value from user, 73 with optional an optional default value. 74 :class:`ValidatedTxtCtrl` A text control with a built-in call back routine to set dict 75 or list elements. Optionally validates input as float, int or 76 for strings non-blank. Value is set when focus changes 77 :func:`CallScrolledMultiEditor` Routine for editing many dict- or list-contained items. 78 using the :class:`ScrolledMultiEditor` dialog 79 :func:`Define_wxId` Create a unique wx.Id symbol in _initMenus in :mod:`GSASIIdataGUI`. 80 Such symbols are needed when the menu item is defined in a 81 different location from the wx.Bind that links the menu item 82 to a function. This function allows all the menu Ids to be 83 defined as the menus are created in one place and then can be 84 used in Bind elsewhere in the code. 85 :func:`G2MessageBox` Displays text typically used for errors or warnings. 86 :func:`ShowScrolledInfo` Displays longer text where scrolling is possibly needed 87 :func:`G2ScrolledGrid` Displays a multicolumn table of information with 88 possible scroll bars 89 :func:`ShowScrolledColText` Displays tabular text with scrolling where needed 90 :func:`GetItemOrder` Creates a dialog for ordering items into columns 91 :func:`GetImportFile` Gets one ore more file from the appropriate import 92 directory, which can be overridden. Arguments follow those 93 of :func:`wx.FileDialog` 94 :func:`HorizontalLine` Places a line in a Frame or Dialog to separate sections. 95 :func:`ItemSelector` Select a single item or multiple items from list of choices. 96 Creates and then destroys a wx.Dialog and returns the 97 selections(s). 98 :func:`SelectEdit1Var` Select a variable from a list, then edit it and select 99 histograms to copy it to. 100 :func:`askSaveFile` Get a file name from user 101 :func:`askSaveDirectory` Get a directory name from user 102 :func:`BlockSelector` Select a single block for instrument parameters 103 :func:`MultipleBlockSelector` Select one or more blocks of data, used for 104 CIF powder histogram imports only 105 :func:`MultipleChoicesSelector` Dialog for displaying fairly complex choices, used for 106 CIF powder histogram imports only 107 :func:`PhaseSelector` Select a phase from a list (used for phase importers) 108 :class:`gpxFileSelector` File browser dialog for opening existing .gpx files 109 :class:`ScrolledStaticText` A wx.StaticText widget that fits a large string into a 110 small space by scrolling it 111 :func:`ReadOnlyTextCtrl` A wx.TextCtrl widget to be used wx.StaticText 112 (no edits allowed) text appears in a box. 113 :func:`setColorButton` A button for color selection as a replacement 114 for wx.ColourSelect 115 ================================ ================================================================= 116 117 Other miscellaneous non-GUI routines that may be of use for GUI-related actions: 118 119 .. tabularcolumns:: |l|p{4in}| 120 121 ================================ ================================================================= 122 Function name Description 123 ================================ ================================================================= 124 :func:`StripIndents` Regularizes the intentation from a string with multiple 125 newline characters by removing spaces at the beginning 126 of each line. 127 :func:`StripUnicode` Removes unicode characters from strings 128 :func:`GetImportPath` Determines the default location to use for importing files. 129 Tries sequentially :attr:`G2frame.TutorialImportDir`, 130 config var ``Import_directory`` and 131 :attr:`G2frame.LastImportDir`. 132 :func:`GetExportPath` Determines the default location to use for writing files. 133 Tries sequentially :attr:`G2frame.LastExportDir` and 134 :attr:`G2frame.LastGPXdir` 135 ================================ ================================================================= 136 137 138 GSASIIctrlGUI Classes & Routines 139 --------------------------------------------- 3 140 4 141 .. automodule:: GSASIIctrlGUI 5 142 :members: 6 143 144 --------------------------------------------- 145 *GSASIIIO: Misc I/O routines* 146 --------------------------------------------- 147 148 Module with miscellaneous routines for input and output. Many 149 are GUI routines to interact with user. 150 151 Includes support for image reading. 152 153 Also includes base class for data export routines (TODO: should move) 154 155 GSASIIIO Classes & Routines 156 --------------------------------------------- 157 7 158 .. automodule:: GSASIIIO 8 159 :members: 9 160 161 --------------------------------------------- 162 *GSASIIpy3: Python 3.x Routines* 163 --------------------------------------------- 164 165 Module to hold Python 3-compatible code, to keep it separate from 166 code that will break with __future__ options. 167 168 GSASIIIO Classes & Routines 169 --------------------------------------------- 170 10 171 .. automodule:: GSASIIpy3 11 172 :members: 173 174 --------------------------------------------- 175 *gltext: draw OpenGL text* 176 --------------------------------------------- 12 177 13 178 .. automodule:: gltext -
trunk/docs/source/GSASIIimage.rst
r2027 r5572 1 *GSASIIimage: Image calc module* 2 ================================ 3 4 *Summary/Contents* 5 ---------------------------- 6 7 Image calibration, masking & image integration routines. 8 9 .. contents:: Section Contents 10 11 *GSASIIimage Routines* 12 ------------------------------------ 13 14 1 15 .. automodule:: GSASIIimage 2 16 :members: 17 :private-members: 18 :special-members: -
trunk/docs/source/GSASIIindex.rst
r2027 r5572 1 *GSASIIindex: Cell Indexing Module* 2 =================================== 3 4 *Summary/Contents* 5 ---------------------------- 6 7 Unit cell indexing routines (based on work of A. Coehlo) and 8 cell refinement from peak positions 9 10 .. contents:: Section Contents 11 12 *GSASIIindex routines* 13 ------------------------------------ 14 1 15 .. automodule:: GSASIIindex 2 16 :members: 17 :private-members: 18 :special-members: -
trunk/docs/source/GSASIImapvars.rst
r2027 r5572 1 *GSASIImapvars: Param Constraints* 2 ================================================= 3 4 *Summary/Contents* 5 ---------------------------- 6 7 Module to implements algebraic contraints, parameter redefinition 8 and parameter simplification contraints. 9 10 .. contents:: Section Contents 11 12 *Externally-Accessible Routines* 13 --------------------------------- 14 15 To define a set of constrained and unconstrained relations, one 16 defines a list of dictionary defining constraint parameters and their 17 values, a list of fixed values for each constraint and a list of 18 parameters to be varied. In addition, one uses 19 :func:`StoreEquivalence` to define parameters that are equivalent. 20 See the :ref:`Constraints Processing section<Constraints_processing>` for details on how 21 processing of constraints is done. 22 23 .. tabularcolumns:: |l|p{4in}| 24 25 ============================= =================================================================== 26 routine explanation 27 ============================= =================================================================== 28 :func:`InitVars` This is used to clear out all defined previously 29 defined constraint information 30 31 :func:`StoreEquivalence` Implements parameter redefinition. 32 This should be called for every set of equivalence relationships. 33 Use :func:`StoreEquivalence` before calling 34 :func:`GenerateConstraints` 35 36 :func:`ProcessConstraints` Initially constraints of all types are maintained in lists of 37 dict entries that are stored in the data tree, 38 with parameters are stored as 39 :class:`~GSASIIobj.G2VarObj` objects so that they can 40 be resolved if the phase/histogram order changes. 41 :func:`ProcessConstraints` processes this list of dict entries, 42 separating the "Equivalence", "Hold", âConstâ and âNew Varâ 43 entries for subsequent use. 44 See the :ref:`Constraint Reorganization <ProcessConstraints>` 45 section for more details. 46 47 :func:`EvaluateMultipliers` Convert any string-specified (formula-based) multipliers to 48 numbers. Call this before using :func:`GenerateConstraints`. 49 At present only values in dict for phase (atom/cell) parameters 50 are used to evaluate multipliers containint formulae, 51 but this could be changed if needed. 52 53 :func:`GenerateConstraints` Generates the internally-used tables from constraints and 54 equivalences. Checks for internal consistency and repairs 55 problems where possible. See the 56 :ref:`Constraint Checking and Grouping <GenerateConstraints>` 57 and :ref:`Equivalence Checking<CheckEquivalences>` 58 sections for more details. 59 60 :func:`Map2Dict` To determine values for any parameters created in this module, 61 call Map2Dict. This will not apply contraints. 62 63 :func:`Dict2Map` To apply the constraints and equivalences, call this. 64 It takes values from the new independent parameters and 65 constraints, and applies them to the parameter dict. 66 67 :func:`Dict2Deriv` This determines derivatives on independent parameters 68 from those on dependent ones. 69 70 :func:`ComputeDepESD` Use ComputeDepESD to compute uncertainties on dependent variables. 71 72 :func:`VarRemapShow` Use this to show a summary of the parameter remapping. 73 Call after :func:`GenerateConstraints`. 74 ============================= =================================================================== 75 76 Types of constraints 77 -------------------- 78 79 There are four ways to specify constraints, as listed below. 80 Note that constraints are initially stored in the 81 main section of the GSAS-II data tree under heading ``Constraints``. 82 This dict has four keys, 'Hist', 'HAP', 'Global', and 'Phase', 83 each containing a list of constraints. An additional set of constraints 84 are generated for each phase based on symmetry considerations by calling 85 :func:`GSASIIstrIO.GetPhaseData`. 86 87 Note that in the constraints, as stored in the GSAS-II data tree, parameters 88 are stored as :class:`GSASIIobj.G2VarObj` objects, as these objects allow for 89 changes in numbering of phases, histograms and atoms since :class:`GSASIIobj.G2VarObj` objects 90 use random Id's for references. 91 When constraints are interpreted (in :func:`ProcessConstraints`), 92 these references are resolved to the numbered objects by looking up random Id's 93 so that the parameter object is converted to a string of form ``ph:hst:VARNAM:at``. 94 95 Constraints are initially stored as described in the 96 :ref:`constraint definitions <Constraint_definitions_table>`, where the last value in the 97 list determines which type of constraint is defined. 98 99 Alternate parameters (New Var) 100 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 101 102 Parameter redefinition ("New Var" constraints) 103 is done by creating an expression that relates several 104 parameters: :: 105 106 Mx1 * Px + My1 * Py +... = ::newvar1 107 Mx2 * Px + Mz2 * Pz + ... = ::newvar2 108 109 where Pj is a GSAS-II parameter name and Mjk is a constant (float) multiplier. 110 Alternately, multipliers Mjk can contain a formula (str) that will be evaluated prior 111 to the start of the refinement. In a formula, GSAS-II parameters will be replaced by the 112 value of the parameter before the formula is evaluated, so ``'np.cos(0::Ax:2)'`` is a valid 113 multiplier. At present, only phase (atom/cell) parameters are available for use in 114 a formula, from the GUI but this can be expanded if needed. 115 116 This type of constraint describes an alternate 117 degree of freedom where parameter Px and Py, etc. are varied to keep 118 their ratio 119 fixed according the expression. A new variable parameter is assigned to each degree of 120 freedom when refined. An example where this can be valuable is when 121 two parameters, P1 and P2, have similar values and are highly correlated. It is often better to create a new variable, Ps = P1 + P2, and refine Ps. 122 In the later stages of refinement, a second 123 variable, Pd = P1 - P2, can be defined and it can be seen if refining Pd is 124 supported by the data. Another use will be to define parameters that 125 express "irrep modes" in terms of the fundamental structural parameters. 126 127 The "New Var" constraints are stored as a type "f" 128 :ref:`constraint (see definitions)<Constraint_definitions_table>`. 129 130 Constrained parameters (Const) 131 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 132 133 A constraint on a set of variables can be supplied in the form of a 134 linear algebraic equation: :: 135 136 Nx1 * Px + Ny1 * Py +... = C1 137 138 where Cn is a constant (float), where Pj is a GSAS-II parameter name, 139 and where Njk is a constant multiplier (float) or a formula (str) that will be evaluated prior 140 to the start of the refinement. In a formula, GSAS-II parameters will be replaced by the 141 value of the parameter before the formula is evaluated, so ``'np.cos(0::Ax:2)'`` is a valid 142 multiplier. At present, only phase (atom/cell) parameters are available for use in 143 a formula, but this can be expanded if needed. 144 145 These equations set an interdependence between parameters. 146 Common uses of parameter constraints are to set rules that decrease the number of parameters, 147 such as restricting the sum of fractional occupancies for atoms that share 148 a site to sum to unity, thus reducing the effective number of variables by one. 149 Likewise, the Uiso value for a H atom "riding" on a C, N or O atom 150 can be related by a fixed offset (the so called B+1 "rule"). 151 152 The "Const" constraints are stored as a type "c" 153 :ref:`constraint (see definitions)<Constraint_definitions_table>`. 154 155 Equivalenced parameters (Equiv) 156 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 157 158 A simplifed way to set up a constraint equation is to define an equivalence, 159 which can be of form: :: 160 161 C1 * P1 = C2 * Py 162 163 or:: 164 165 C1 * P1 = C2 * P2 = C3 * P3 = ... 166 167 where Cn is a constant (float), where Pj is a GSAS-II parameter name. This 168 means that parameters Py (or P2 and P3) are determined from (or "slaved" to) 169 parameter P1. Alternately, equivalences can be created with :func:`StoreEquivalence` 170 where the multipliers can be a formula (str) that will be evaluated prior to the start of 171 the refinement. In a formula, GSAS-II parameters will be replaced by the value of the 172 parameter before the formula is evaluated, so a multiplier can be specifed as ``'2*np.cos(0::Ax:2)'``. 173 At present, only phase (atom/cell) parameters are available for use in 174 such a formula, but this can be expanded if needed. 175 176 The first parameter (P1 above) 177 is considered the independent variable 178 and the remaining parameters are dependent variables. The dependent variables 179 are then set from the independent variable. 180 181 Note that a constraint expression is conceptually identical to 182 defining constraint equations. 183 The previous set of equalities could also be written as a set of constraint 184 equations in this way: :: 185 186 C1 * P1 - C2 * P2 = 0 187 C1 * P1 - C3 * P3 = 0 188 ... 189 190 In practice, however, 191 equivalenced parameters are processed in a 192 different and more direct manner than constraint equations. 193 194 A parameter can be used in multiple 195 equivalences where it is an independent variable, 196 but if a parameter were used both as a dependent and independent variable then the order that 197 shifts are applied becomes potentially significant. As an example, in this case these two 198 equivalences are "chained":: 199 200 C1 * P1 = C2 * P2 201 C2 * P2 = C3 * P3 202 203 where P2 is both a dependent and independent variable. Likewise, if a parameter is used both in equivalences 204 and in "New Var" or "Const" constraints, it also becomes unclear how this should be processed. It is 205 possible to specify equivalences that conflict with constraints. 206 Should parameter be used as both a dependent and an independent variable or if a parameter is used both in 207 an the equivalence and in a "New Var" or "Const" constraints, the equivalence 208 is converted to a constraint (Const) to 209 avoid conflicts. The equivalences that require this are addressed in ::func:`GenerateConstraints` where 210 :func:`CheckEquivalences` is used to locate problematic variables in equivalences 211 and then change these equivalences to "Const" equations. Also, unneeded equivalences are removed. 212 213 For an example of how equivalences may be used, consider 214 a material that has **N** O atoms in the asymmetric unit, all in fairly similar bonding environments 215 and where the diffraction data are sparse. One may wish to reduce the complexity of the model fit to 216 these data by defining Uiso for all O atoms to be the same. This is done by selecting Uiso for any one O atom 217 as an independent variable in a equivalence and setting the remaining **N-1** other O atom Uiso 218 variables as dependent parameters with multipliers of 1. This will require that all O atom Uiso values 219 be identical. 220 The results of this refinement will be simpler to understand than if a set of 221 constraint equations is used, because the refined parameter (named as ``ph::Uiso:n``) will be the 222 independent variable, corresponding to the first O atom and all other variables would be 223 expressed in terms of that variable with a single Equivalence expression. 224 The alternate would require **N-1** constraint equations, leaving one degree of freedom with a 225 variable would that is likely only indirectly related to the Uiso values. 226 227 Equivalenced parameters ("EQUIV" constraints), when defined by users, 228 or when created to relate phases, are stored as a type "e" 229 :ref:`constraint (see definitions)<Constraint_definitions_table>`. 230 Symmetry-generated equivalences are generated prior 231 to display or refinement in :func:`GSASIIstrIO.GetPhaseData`. 232 These are not stored in the data tree. 233 234 Hold parameters (Fixed) 235 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 236 237 When parameters are refined where a single refinement flag determines that several variables 238 are refined at the same time (examples are: cell parameters, atom positions, anisotropic 239 displacement parameters, magnetic moments,...) it can be useful to specify that a 240 specific parameter should not be varied. These will most commonly be generated due to symmetry, 241 but under specific conditions, there may be other good reasons to constrain a parameter. 242 243 The "Hold" constraints are stored as a type "h" 244 :ref:`constraint (see definitions)<Constraint_definitions_table>`. 245 246 .. _Constraints_processing: 247 248 Constraint Processing 249 --------------------- 250 251 When constraints will be used or edited, they are processed using a series of 252 calls. This is done in GSAS-II from several locations: 253 254 * For error checking from the tree in :mod:`GSASIIconstrGUI`, 255 :func:`GSASIIconstrGUI.CheckConstraints` loads constraints from 256 the data tree. 257 258 * When the table of refined parameters is shown, constraints are also 259 processed in function :func:`GSASIIdataGUI.GSASII.OnShowLSParms` using 260 :func:`GSASIIconstrGUI.CheckConstraints` 261 262 * To write parameters in the Export sections of the program, 263 :func:`GSASIIIO.loadParmDict` loads results as well as constraints 264 from the tree. This works a bit differently from the above, so it 265 makes direct calls to the constraints routines. 266 267 * For error checking from a GPX file 268 :func:`GSASIIstrIO.ReadCheckConstraints` loads constraints 269 (called in :mod:`GSASIIdataGUI` and :mod:`GSASIIscriptable`), 270 which is similar to :func:`GSASIIconstrGUI.CheckConstraints`. 271 :func:`~GSASIIstrIO.ReadCheckConstraints` is called by 272 :meth:`GSASIIdataGUI.GSASII.OnRefine` and 273 :meth:`GSASIIdataGUI.GSASII.OnSeqRefine` 274 before constraints are generated for use in refinements so they can 275 be shown in the GUI. This is also called to check for errors in 276 :class:`GSASIIscriptable.G2Project`. 277 278 * To create the constraints for use in a refinement, in 279 :mod:`GSASIIstrMain`, functions :func:`GSASIIstrMain.Refine` and 280 :func:`GSASIIstrMain.SeqRefine` load and process the constraints again. 281 This is repeated here because :func:`~GSASIIstrMain.Refine` and 282 :func:`~GSASIIstrMain.SeqRefine` are intended to operate as stand-alone 283 routines that may be called directly. 284 285 * After sequential fits have been completed, the previously processed 286 constraint info is read from the sequential results section of the 287 data tree. Function 288 :func:`GSASIIseqGUI.UpdateSeqResults` displays the sequential results 289 table also processes constraints. 290 291 TODO: Note that G2stIO.makeTwinFrConstr is called only in one place. It probably needs to be included in all of the above. 292 293 When constraints are processed, the following steps are used: 294 295 #. Constraints are stored in separate lists in the data tree to 296 simplify their creation and their GUI display. 297 In the initial processing, all of the stored constraints are appended 298 into a single list. 299 300 #. Then :func:`InitVars` is used to initialize the global variables in 301 this module (:mod:`GSASIImapvars`). This may be done before the previous 302 step. 303 304 #. Then :func:`ProcessConstraints` is used to initially process the 305 constraints user-supplied constraints (from the data tree), 306 as described in :ref:`Constraint Reorganization <ProcessConstraints>`. 307 When constraints are read from a GPX file, rather than the data tree, use 308 :func:`GSASIIstrIO.ReadConstraints` (which calls :func:`ProcessConstraints`). 309 310 #. Symmetry-generated equivalences are then created in 311 :func:`GSASIIstrIO.GetPhaseData`, which also calls 312 :func:`GSASIIstrIO.cellVary` and for Pawley refinements 313 :func:`GSASIIstrIO.GetPawleyConstr`. These are entered directly into this 314 module's globals using :func:`StoreEquivalence`. 315 316 #. Constraints/equivalences are then checked for possible conflicts with 317 :func:`GenerateConstraints`, this requires grouping the constraints, 318 as described below. 319 320 #. :func:`GenerateConstraints` is then called to 321 create the constraints that will be used, 322 :ref:`see below <GenerateConstraints>` for more details. 323 324 #. For debugging constraints, :func:`VarRemapShow` can be called after 325 :func:`GenerateConstraints` to display the generated constraints. 326 327 .. _ProcessConstraints: 328 329 Constraint Reorganization (:func:`ProcessConstraints`) 330 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 331 332 :func:`ProcessConstraints` is used to initially process the 333 constraints from the list of dict entries. The "Const" and "New Var" are placed into two 334 lists (:data:`constrDict` and :data:`fixedList`) that are later used for parameter 335 grouping (in :func:`GenerateConstraints`). "Hold" and "Equivalence" constraints are 336 separated into separate storage. 337 338 For "**Const**" entries, 339 a dict with multiple entries is placed in :data:`constrDict` where 340 each dict key is the parameter name and the value is the multiplier for the parameter, 341 while :data:`fixedList` gets a string value corresponding to the constant value for 342 the expression. 343 344 For "**New Var**" entries, 345 a dict with multiple entries defined identically to 346 to that used in "Const" entries. The differences between "New Var" and "Const" entries is 347 that for "Const" entries, a constant value (as a string) is placed in :data:`fixedList` while 348 for "New Var" entries corresponding entry in :data:`fixedList` is None. 349 Also, one or two additional entries are created in the dict for "New Var" constraints: 350 an entry with key "_vary" is given the value of True or False 351 depending on the refinement flag setting; 352 an entry with key "_name" will be created if the "New Var" parameter has a supplied name. 353 354 For "**Hold**" entries, 355 User-supplied âHoldâ constraints are stored in global variable :data:`holdParmList`. 356 Initialized in :func:`InitVars`; set in :func:`StoreHold`. Type of hold is stored in 357 :data:`holdParmType`. 358 359 **Equivalences** are stored using :func:`StoreEquivalence` into this module's globals 360 (:data:`dependentParmList`, :data:`arrayList`, :data:`invarrayList`, :data:`indParmList`, 361 and :data:`symGenList`). 362 For each equivalence: 363 364 * a list with one entry, the name of the independent parameter is placed in :data:`indParmList`; 365 * a list with one or more parameter name is placed in :data:`dependentParmList`; 366 * the value None is added to :data:`arrayList`; 367 * a list of multipliers for each dependent variable is placed in :data:`invarrayList` 368 * an entry of either True or False is placed in :data:`symGenList`, where True indicates that the entry has been generated from symmetry. 369 370 The output from :func:`ProcessConstraints` will have the form as below, 371 where the first entry is a "Const" and the second is a "New Var". 372 373 .. code-block:: python 374 375 constrDict = [ 376 {'0:12:Scale': 2.0, '0:14:Scale': 4.0, '0:13:Scale': 3.0, '0:0:Scale': 0.5}, 377 {'2::C(10,6,1)': 1.0, '1::C(10,6,1)': 1.0, '_vary':True}] 378 fixedList = ['5.0', None] 379 380 .. _GenerateConstraints: 381 382 Constraint Checking and Grouping (:func:`GenerateConstraints`) 383 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 384 385 Function :func:`GenerateConstraints` is used to 386 process the parameter equivalences and constraint lists created in 387 :func:`ProcessConstraints` (``constrDict`` and ``fixedList``). :func:`GenerateConstraints` 388 is used to generate error/warning messages, to set up lists that are used to show this 389 information for the GUI (using :func:`getConstrError`) and to 390 generate the information stored in :ref:`global arrays <GlobalVariables>` that are used later to 391 apply the constraints. 392 393 When a sequential refinement is in progress, the constraints are scanned for parameters 394 that have a wildcard (*) for the histogram number, such as 1:*:Scale which would refer 395 to the phase fraction for Phase ` in every histogram. The "*" will be replaced with 396 the number of the current histogram. 397 398 Equivalences are checked with :func:`CheckEquivalences` (described in detail 399 :ref:`below <CheckEquivalences>`). This may result in the creation of additional "Hold" 400 and "Constr" constraints being added to the ``constrDict`` and ``fixedList`` lists. 401 402 The "Const" and "New Var" constraint expressions are then scanned for problems: 403 404 Constraints cannot be processed without changes if any of the terms within have the following: 405 406 * **Undefined parameters** or **Multiplier of zero** 407 408 If any parameters in a constraint are undefined or have a parameter multiplier of zero 409 the constraint group is not used. 410 411 If some, but not all, parameters in a constraint are undefined or have a parameter 412 multiplier of zero and remaining valid parameters will be set as "Hold". 413 One exception: atom position constraints (p::dA[xyz]:#) will be assumed as zero. 414 415 * **Hold (Fixed) parameters** and **Unvaried parameters**: New Var constraints 416 417 If any parameters in a new var constraint are either not refined, or are marked as "Hold" 418 the constraint can not be varied. Any parameters in that group will be set as "Hold" 419 420 * **Hold (Fixed) parameters** and **Unvaried parameters**: Constraint Equations 421 422 If any parameters in a constraint equation are either not refined, or are marked as "Hold" 423 those parameters can be removed from the constraint, with an adjustment of the equation 424 sum. 425 426 Constraint expressions ("Const" and "New Var") are sorted by routine :func:`GroupConstraints` into 427 groups so that each group contains the minimum number of entries that 428 ensures each parameter is referenced in only one group. 429 This is done by scanning the 430 list of dicts in :data:`constrDict` one by one and making a list 431 of parameters used in that constraint expression. Any expression that contains 432 a parameter in that list is added to the current group and those 433 parameters are added to this list of parameters. The list of ungrouped 434 expressions is then scanned again until no more expressions are added to the 435 current group. This process is repeated until every expression has been 436 placed in a group. Function :func:`GroupConstraints` returns two lists of lists. 437 The first has, for each group, a list of the indices in :data:`constrDict` 438 that comprise the group (there can be only one). The second list contains, 439 for each group, the unique parameter names in that group. 440 441 Each constraint group is then processed. First, wildcard parameters are 442 renamed (in a sequential refinement). Any held parameters that are used 443 in constraints are noted as errors. The number of refined parameters and 444 the number of parameters that are not defined in the current refinement are 445 also noted. It is fine if all parameters in a group are not defined or all are 446 not varied, but if some are defined and others not or some are varied and 447 others not, this constitutes an error. 448 449 The contents of each group is then examined. Groups with a single 450 parameter (holds) are ignored. Then for each group, the number 451 of parameters in the group (Np) and the number of expressions in the 452 group (Nc) are counted and for each expression. If Nc > Np, then the constraint 453 is overdetermined, which also constitutes an error. 454 455 The parameter multipliers for each expression are then assembled: 456 457 :: 458 459 M1a * P1 + M2a * P2 +... Mka * Pk 460 M1b * P1 + M2b * P2 +... Mkb * Pk 461 ... 462 M1j * P1 + M2j * P2 +... Mkj * Pk 463 464 465 From this it becomes possible to create a Nc x Np matrix, which is 466 called the constraint matrix: 467 468 .. math:: 469 470 \left( \begin{matrix} 471 M_{1a} & M_{2a} &... & M_{ka} \\ 472 M_{1b} & M_{2b} &... & M_{kb} \\ 473 ... \\ 474 M_{1j} & M_{2j} &... & M_{kj} 475 \end{matrix}\right) 476 477 When Nc<Np, then additional rows need to be added to the matrix and to 478 the vector that contains the value for each row (:data:`fixedList`) where 479 values are ``None`` for New Vars and a constant for fixed values. 480 This then can describe a system of Np simultaneous equations: 481 482 .. math:: 483 484 \left( \begin{matrix} 485 M_{1a} & M_{2a} &... & M_{ka} \\ 486 M_{1b} & M_{2b} &... & M_{kb} \\ 487 ... \\ 488 M_{1j} & M_{2j} &... & M_{kj} 489 \end{matrix}\right) 490 \left( \begin{matrix} 491 P_{1} \\ 492 P_{2} \\ 493 ... \\ 494 P_{k} 495 \end{matrix}\right) 496 = 497 \left( \begin{matrix} 498 C_{1} & C_{2} & ... & C_{k} 499 \end{matrix}\right) 500 501 This is done by creating a square matrix from the group using 502 :func:`_FillArray`. The top Nc rows in the matrix are filled 503 as described above. Then :func:`_RowEchelon` is used to see if 504 those entries in the matrix can be coverted to row-echelon form. This 505 will raise an Exception there is linear dependence between the initial Nc rows 506 (which means that no matter what values are used for any remaining rows, that the matrix 507 will be singular). If that is not the case and Nc<Np then any remaining rows that 508 were not specified are filled in. For each of these rows, first only the 509 diagonal element in that row of the matrix is set to 1 510 and the upper portion of the matrix is again tested with :func:`_RowEchelon` 511 to check for linear independence. This is likely to be non-singular, 512 but should :func:`_RowEchelon` fail, 513 :func:`_FillArray` will then try setting each other element in that row to either 514 1 or -1. One of those options should be linearly independent from every other 515 row of the matrix. 516 517 The 518 `Gram-Schmidt process <http://en.wikipedia.org/wiki/Gram-Schmidt>`_, 519 implemented in :func:`GramSchmidtOrtho`, is used to find orthonormal unit 520 vectors which are used to replace the remaining Np-Nc rows of the matrix. This will fail with 521 a ``ConstraintException`` if this is not possible (singular matrix), but that would be 522 unexpected since the matrix could be converted to row-echelon form. The 523 Gram-Schmidt result is placed in :data:`constrArr` as a numpy array. 524 525 Rows in the matrix corresponding to "New Var" constraints and those that 526 were generated by the Gram-Schmidt process are provided with parameter names. 527 These names are generated using :data:`paramPrefix`, which is set to ``"::constr"``, 528 plus a number to make the new parameter name unique, 529 unless a name was specified for the 530 "New Var" entry by using a ``"_name"`` element in the constraint dict. 531 532 Finally the parameters used as input to the constraint are placed in 533 this module's globals 534 :data:`dependentParmList` and the constraint matrix is 535 placed in into :data:`arrayList`. This can be used to compute 536 the initial values for "New Var" parameters. The inverse of the 537 constraint matrix is placed in :data:`invarrayList` and a list 538 of the "New Var" parameters and a list of the fixed values (as str's) 539 is placed in :data:`indParmList`. 540 Finally the appropriate entry in :data:`symGenList` is set to 541 False to indicate that this is not a symmetry generated constraint. 542 543 .. _CheckEquivalences: 544 545 Equivalence Checking and Reorganization (:func:`CheckEquivalences`) 546 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 547 548 Equivalences need to be checked for usages that could be internally conflicted 549 or have possible conflicts with other constraints. 550 551 **Mixed parameter use:** 552 553 **Note** that cycling through the equivalences may be needed to find all mixed-use 554 parameters, see below. 555 556 * A parameter should not show up as a dependent variable in two equivalence expressions, 557 such as:: 558 559 ::x1 -> ::x3 560 ::x2 -> ::x3 561 562 This will be processed by turning the equivalences into two constraint equations:: 563 564 ::x1 - ::x3 = 0 565 ::x2 - ::x3 = 0 566 567 which can be satisfied when ``::x1 = ::x2 = ::x3``. If ``::x1`` and ``::x2`` had been 568 intended to be independent parameters, then the above equivalences would be conflict and 569 cannot be statisfied. 570 571 * If a parameter is used both as an independent and as a dependent variable (*chaining*), 572 as is in these two equivalence expressions:: 573 574 ::x1 -> ::x2 & ::x4 575 ::x2 -> ::x3 576 577 This can also be addressed by turning these equivalences into three constraint equations:: 578 579 ::x1 - ::x2 = 0 580 ::x1 - ::x4 = 0 581 ::x2 - ::x3 = 0 582 583 which can be satisfied when ``::x1 = ::x2 = ::x3 = ::x4`` 584 585 * Use of parameters in both equivalences and "Const" or "New Var" constraint expressions makes 586 logical sense:: 587 588 ::x1 -> ::x2 & ::x4 589 ::x2 + ::x3 = 0 590 591 This can also be addressed by turning the equivalence into two constraint equations:: 592 593 ::x1 - ::x2 = 0 594 ::x1 - ::x4 = 0 595 596 With the addition of the "Const" equation (``::x2 + ::x3 = 0``), the solution will require 597 ``::x1 = ::x2 = -1.0*::x3 = ::x4`` 598 599 * Cycling is needed to find all equivalences that must be converted. 600 Consider this set of constraints:: 601 602 ::x2 + ::x3 = 0 603 ::x1 -> ::x2 604 ::x1 -> ::x4 605 606 In the first pass the equivalence with ``::x2`` would be converted to a "Const" constraint 607 and in the second pass 608 the other equivalence with ``::x1`` would be converted. 609 610 611 **Mixing Hold (Fixed) parameters in equivalences** 612 613 * If one parameter (or more) is designated as a "Hold" in an equivalence, then all parameters in that 614 equivalence cannot be varied. Considering this equivalence:: 615 616 ::x1 -> ::x2 & ::x4 617 618 If any of the three parameters (``::x1``, ``::x2``, or `::x4`) are marked as Hold, then 619 the other two parameters may not be varied and will also be set with a "Hold". 620 621 622 **Unvaried parameters in equivalences** 623 624 * If no parameters in an equivalence are varied, then the equivalence is ignored. 625 626 * If only some parameters are marked as varied then 627 *none of the parameters can be varied*; any varied parameters will be set with a "Hold". 628 629 630 **Undefined parameters in equivalences** 631 632 Parameters may be placed in equivalences that are not actually defined in a project. 633 This can occur in two ways. If an equivalence is created in the GUI for a parameter that 634 is later supplanted with a different model (for example, changing from isotropic size 635 broadening to uniaxial broadening replaces the isotropic broadening term with two different 636 uniaxial terms) or symmetry may require restrictions on anisotropic ADPs that are not 637 in use). 638 639 * If the independent parameter is undefined, then any dependent parameters that are defined 640 are set as "Hold" and the equivalence is ignored. 641 642 * If all dependent parameters are undefined, then the equivalence is ignored. 643 644 * If a dependent parameter is undefined, then that parameter is dropped from the equivalence. 645 646 647 **Multiplier of zero in equivalences** 648 649 Any dependent parameter that has a multiplier of zero will be dropped from the equivalence. 650 If no terms remain, then the equivalence is ignored. (Independent parameters do not 651 have a multiplier). 652 653 654 .. _GlobalVariables: 655 656 *Global Variables* 657 ------------------ 658 659 This module uses a number of global variables. One set is used to store the 660 constraints and equivalences after processing by :func:`StoreEquivalence` and 661 :func:`GenerateConstraints`. 662 These globals are expected to be used only by this module's (:mod:`GSASIImapvars`) internal routines. 663 664 Lists with information from Constraint Equation and New Var constraints. Each entry 665 in these variables is related to a group of constraints. 666 667 .. tabularcolumns:: |l|p{4.5in}| 668 669 ============================= =================================================================== 670 variable explanation 671 ============================= =================================================================== 672 :data:`dependentParmList` a list containing group of lists of 673 parameters used in the group. 674 The columns of the matrices in :data:`arrayList` match 675 the order of parameters here. 676 Note that parameters listed in 677 dependentParmList will not be included in the Hessian as their 678 derivatives will not affect the model 679 680 :data:`indParmList` a list containing groups of variables or constants matching 681 the columns of the matrices in :data:`invarrayList`. 682 683 :data:`arrayList` a list containing group of relationship matrices to relate 684 parameters in dependentParmList to those in indParmList. 685 686 :data:`invarrayList` a list containing group of relationship matrices to relate 687 parameters in indParmList to those in dependentParmList. 688 Unlikely to be used externally. 689 690 :data:`symGenList` a list of boolean values that will be True to indicate 691 that an equivalence was generated internally GSAS-II 692 meaning it is generated based on symmetry, twining 693 or Pawley overlap. 694 695 ============================= =================================================================== 696 697 Lists with information from Hold and Equivalence constraints. Each entry 698 in these variables is related to a group of constraints. 699 700 .. tabularcolumns:: |l|p{4.5in}| 701 702 ============================= =================================================================== 703 variable explanation 704 ============================= =================================================================== 705 :data:`holdParmList` a list of parameters that have been marked as "Hold". 706 Unlikely to be accessed outside this module. 707 Initialized in :func:`InitVars`; set in :func:`StoreHold`. 708 709 :data:`holdParmType` The reason why a parameter has been marked as "Hold". 710 Unlikely to be accessed outside this module. 711 Initialized in :func:`InitVars`; set in :func:`StoreHold`. 712 713 :data:`constrParms` dict with lists of variables in equivalences, 714 constraint equations and new var expressions. 715 Used within :func:`GetIndependentVars`, 716 and :func:`GetDependentVars`. 717 Best if not referenced outside this module. 718 Contains elements: 719 720 * 'dep-equiv': dependent parameters set by equivalences 721 * 'dep-constr': dependent parameters set by 722 constraint equations or new var expressions 723 * 'indep-equiv': dependent parameters used in equivalences 724 * 'indep-constr': dependent parameters created from 725 constraint equations or new var expressions 726 727 :data:`saveVaryList` a list of the varied parameters used when constraints 728 were last processed. 729 ============================= =================================================================== 730 731 732 A second set of global variables are set in :func:`GenerateConstraints` with lists of parameter 733 names from equivalences and constraints. Used in :func:`CheckEquivalences` and 734 :func:`getConstrError`. 735 736 .. tabularcolumns:: |l|p{4.5in}| 737 738 ============================= =================================================================== 739 variable explanation 740 ============================= =================================================================== 741 :data:`depVarList` a list of the parameters used in equivalences as dependent 742 parameters for all equivalences initially specified (including 743 those to be reclassified as "Constr" constraints.) 744 745 :data:`indepVarList` a list of the parameters used in equivalences as independent 746 parameters for all equivalences initially specified (including 747 those to be reclassified as "Constr" constraints.) 748 749 :data:`constrVarList` a list of the parameters that are used in "Constr" or 750 "New Var" constraints. Does not include those in equivalences 751 to be reclassified as "Constr" constraints.) 752 ============================= =================================================================== 753 754 755 A third set of global variables to store equivalence warning information. 756 Set in :func:`CheckEquivalences` and :func:`GenerateConstraints`. 757 Used in :func:`getConstrError` to display warning messages. 758 759 .. tabularcolumns:: |l|p{4.5in}| 760 761 ============================= =================================================================== 762 variable explanation 763 ============================= =================================================================== 764 :data:`convVarList` parameters in equivalences that were converted to "Const" 765 constraints 766 767 :data:`multdepVarList` parameters used as dependent parameters in equivalences 768 multiple times 769 770 :data:`unvariedParmsList` parameters used in equivalences and constraints 771 that are not varied 772 773 :data:`undefinedVars` parameters used in equivalences 774 that are not defined in the parameter dict (parmDict) 775 776 :data:`groupErrors` parameters in constraints that cause grouping errors 777 ============================= =================================================================== 778 779 780 781 *GSASIImapvars Routines/variables* 782 --------------------------------------- 783 1 784 .. automodule:: GSASIImapvars 2 785 :members: 786 :private-members: 787 :special-members: -
trunk/docs/source/GSASIImath.rst
r2027 r5572 1 *GSASIImath: computation module* 2 ================================ 3 4 *Summary/Contents* 5 ---------------------------- 6 7 Least-squares minimization and misc. computation routines. 8 9 .. contents:: Section Contents 10 11 *GSASIImath Classes and routines* 12 ------------------------------------ 13 1 14 .. automodule:: GSASIImath 2 15 :members: 16 :private-members: 17 :special-members: -
trunk/docs/source/GSASIIobj.rst
r2027 r5572 1 *GSASIIobj: Data objects & Docs* 2 ================================================= 3 4 *Summary/Contents* 5 ---------------------------- 6 7 This module defines and/or documents the data structures used in GSAS-II, as well 8 as provides misc. support routines. 9 10 11 .. contents:: Section Contents 12 13 14 .. _VarNames_table: 15 16 .. index:: 17 single: Parameter names 18 single: GSAS-II variable naming 19 20 Variable names in GSAS-II 21 ---------------------------- 22 23 Parameter are named using the following pattern, 24 ``p:h:<var>:n``, where ``<var>`` is a variable name, as shown in the following table. Also, 25 ``p`` is the phase number, ``h`` is the histogram number, 26 and ``n`` is the atom parameter number 27 If a parameter does not depend on a histogram, phase or atom, ``h``, ``p`` and/or ``n`` will be omitted, 28 so ``p::<var>:n``, ``:h:<var>`` and ``p:h:<var>`` are all valid names. 29 30 .. include:: vars.rst 31 32 .. _Constraints_table: 33 34 .. index:: 35 single: Constraints object description 36 single: Data object descriptions; Constraints 37 38 Constraints Tree Item 39 ---------------------- 40 41 Constraints are stored in a dict, separated into groups. 42 Note that parameter are named in the following pattern, 43 p:h:<var>:n, where p is the phase number, h is the histogram number 44 <var> is a variable name and n is the parameter number. 45 If a parameter does not depend on a histogram or phase or is unnumbered, that 46 number is omitted. 47 Note that the contents of each dict item is a List where each element in the 48 list is a :ref:`constraint definition objects <Constraint_definitions_table>`. 49 The constraints in this form are converted in 50 :func:`GSASIImapvars.ProcessConstraints` to the form used in :mod:`GSASIImapvars` 51 52 The keys in the Constraints dict are: 53 54 .. tabularcolumns:: |l|p{4.5in}| 55 56 ========== ==================================================== 57 key explanation 58 ========== ==================================================== 59 Hist This specifies a list of constraints on 60 histogram-related parameters, 61 which will be of form :h:<var>:n. 62 HAP This specifies a list of constraints on parameters 63 that are defined for every histogram in each phase 64 and are of form p:h:<var>:n. 65 Phase This specifies a list of constraints on phase 66 parameters, 67 which will be of form p::<var>:n. 68 Global This specifies a list of constraints on parameters 69 that are not tied to a histogram or phase and 70 are of form ::<var>:n 71 ========== ==================================================== 72 73 .. _Constraint_definitions_table: 74 75 .. index:: 76 single: Constraint definition object description 77 single: Data object descriptions; Constraint Definition 78 79 Each constraint is defined as an item in a list. Each constraint is of form:: 80 81 [[<mult1>, <var1>], [<mult2>, <var2>],..., <fixedval>, <varyflag>, <constype>] 82 83 Where the variable pair list item containing two values [<mult>, <var>], where: 84 85 * <mult> is a multiplier for the constraint (float) 86 * <var> a :class:`G2VarObj` object. (Note that in very old .gpx files this might be a str with a variable name of form 'p:h:name[:at]') 87 88 Note that the last three items in the list play a special role: 89 90 * <fixedval> is the fixed value for a `constant equation` (``constype=c``) 91 constraint or is None. For a `New variable` (``constype=f``) constraint, 92 a variable name can be specified as a str (used for externally 93 generated constraints) 94 * <varyflag> is True or False for `New variable` (``constype=f``) constraints 95 or is None. This indicates if this variable should be refined. 96 * <constype> is one of four letters, 'e', 'c', 'h', 'f' that determines the type of constraint: 97 98 * 'e' defines a set of equivalent variables. Only the first variable is refined (if the 99 appropriate refine flag is set) and and all other equivalent variables in the list 100 are generated from that variable, using the appropriate multipliers. 101 * 'c' defines a constraint equation of form, 102 :math:`m_1 \times var_1 + m_2 \times var_2 + ... = c` 103 * 'h' defines a variable to hold (not vary). Any variable on this list is not varied, 104 even if its refinement flag is set. Only one [mult,var] pair is allowed in a hold 105 constraint and the mult value is ignored. 106 This is of particular value when needing to hold one or more variables where a 107 single flag controls a set of variables such as, coordinates, 108 the reciprocal metric tensor or anisotropic displacement parameter. 109 * 'f' defines a new variable (function) according to relationship 110 :math:`newvar = m_1 \times var_1 + m_2 \times var_2 + ...` 111 112 .. _Covariance_table: 113 114 .. index:: 115 single: Covariance description 116 single: Data object descriptions; Covariance 117 118 Covariance Tree Item 119 -------------------- 120 121 The Covariance tree item has results from the last least-squares run. They 122 are stored in a dict with these keys: 123 124 .. tabularcolumns:: |l|l|p{4in}|