5. GSAS-II GUI Utility Modules

5.1. GSASIIctrlGUI: Custom GUI controls

A library of GUI controls for reuse throughout GSAS-II, as indexed below

Class or function name Description
EnumSelector A combo box with a built-in call back routine that automatically sets a dict or list entry.
DisAglDialog Distance/Angle Controls input dialog.
FlagSetDialog Dialog that provides a table of items along with a checkbox for each.
G2ChoiceButton A customized wx.Choice that automatically initializes to the initial value and saves the choice directly into a dict or list value. Optionally calls function when a choice is selected
G2CheckBox A customized wx.CheckBox that automatically initializes to the initial value and saves the choice directly into a dict or list value. Optionally calls function when a choice is selected
G2SliderWidget A customized combination of a wx.Slider and a validated wx.TextCtrl (see ValidatedTxtCtrl).
G2ColumnIDDialog A dialog for matching column data to desired items; some columns may be ignored.
G2HistoDataDialog A dialog for global edits to histogram data globally
G2MultiChoiceDialog Dialog similar to wx.MultiChoiceDialog, but provides a filter to select choices and buttons to make selection of multiple items more simple.
G2MultiChoiceWindow Similar to G2MultiChoiceDialog but provides a sizer that can be placed in a frame or panel.
G2SingleChoiceDialog Dialog similar to wx.SingleChoiceDialog, but provides a filter to help search through choices.
HelpButton Creates a button labeled with a “?” that when pressed displays help text in a modal message window or web browser.
MultiColumnSelection A dialog that builds a multicolumn table, word wrapping is used for the 2nd, 3rd,… columns.
MultiDataDialog Dialog to obtain multiple data values from user, with optional range validation; items can be float, str or bool
MultiIntegerDialog Dialog to obtain multiple integer values from user, with a description for each value and optional defaults.
MultiStringDialog Dialog to obtain multiple string values from user, with a description for each value and optional defaults.
OrderBox Creates a wx.Panel with scrollbars where items can be ordered into columns.
SortableLstCtrl Creates a wx.Panel for a table of data that can be sorted by clicking on a column label.
ScrolledMultiEditor wx.Dialog for editing many dict- or list-contained items. with validation. Results are placed in dict or list.
SGMagSpinBox Special version of MessageBox that displays magnetic spin text
SGMessageBox Special version of MessageBox that displays space group & super space group text in two blocks
SingleFloatDialog Dialog to obtain a single float value from user, with optional range validation.
SingleIntDialog Dialog to obtain a single integer value from user, with optional range validation.
SingleStringDialog Dialog to obtain a single string value from user, with optional an optional default value.
ValidatedTxtCtrl A text control with a built-in call back routine to set dict or list elements. Optionally validates input as float, int or for strings non-blank. Value is set when focus changes
CallScrolledMultiEditor() Routine for editing many dict- or list-contained items. using the ScrolledMultiEditor dialog
Define_wxId() Create a unique wx.Id symbol in _initMenus in GSASIIdataGUI. Such symbols are needed when the menu item is defined in a different location from the wx.Bind that links the menu item to a function. This function allows all the menu Ids to be defined as the menus are created in one place and then can be used in Bind elsewhere in the code.
G2MessageBox() Displays text typically used for errors or warnings.
ShowScrolledInfo() Displays longer text where scrolling is possibly needed
GetItemOrder() Creates a dialog for ordering items into columns
GetImportFile() Gets one ore more file from the appropriate import directory, which can be overridden. Arguments follow those of wx.FileDialog()
HorizontalLine() Places a line in a Frame or Dialog to separate sections.
ItemSelector() Select a single item or multiple items from list of choices. Creates and then destroys a wx.Dialog and returns the selections(s).
SelectEdit1Var() Select a variable from a list, then edit it and select histograms to copy it to.
askSaveFile() Get a file name from user
askSaveDirectory() Get a directory name from user
BlockSelector() Select a single block for instrument parameters
MultipleBlockSelector() Select one or more blocks of data, used for CIF powder histogram imports only
MultipleChoicesSelector() Dialog for displaying fairly complex choices, used for CIF powder histogram imports only
PhaseSelector() Select a phase from a list (used for phase importers)

Other miscellaneous routines that may be of use:

Function name Description
StripIndents() Regularizes the intentation from a string with multiple newline characters by removing spaces at the beginning of each line.
StripUnicode() Removes unicode characters from strings
GetImportPath() Determines the default location to use for importing files. Tries sequentially G2frame.TutorialImportDir, config var Import_directory and G2frame.LastImportDir.
GetExportPath() Determines the default location to use for writing files. Tries sequentially G2frame.LastExportDir and G2frame.LastGPXdir

Documentation for all the routines in module GSASIIctrlGUI.

class GSASIIctrlGUI.ASCIIValidator(result=None, key=None)[source]

A validator to be used with a TextCtrl to prevent entering characters other than ASCII characters.

The value is checked for validity after every keystroke
If an invalid number is entered, the box is highlighted. If the number is valid, it is saved in result[key]
Parameters:
  • result (dict/list) – List or dict where value should be placed when valid
  • key (any) – key to use for result (int for list)
Clone()[source]

Create a copy of the validator, a strange, but required component

OnChar(event)[source]

Called each type a key is pressed ignores keys that are not allowed for int and float types

TestValid(tc)[source]

Check if the value is valid by casting the input string into ASCII.

Save it in the dict/list where the initial value was stored

Parameters:tc (wx.TextCtrl) – A reference to the TextCtrl that the validator is associated with.
TransferFromWindow()[source]

Needed by validator, strange, but required component

TransferToWindow()[source]

Needed by validator, strange, but required component

GSASIIctrlGUI.BlockSelector(ChoiceList, ParentFrame=None, title='Select a block', size=None, header='Block Selector', useCancel=True)[source]

Provide a wx dialog to select a single block where one must be selected. Used for selecting for banks for instrument parameters if the file contains more than one set.

GSASIIctrlGUI.CallScrolledMultiEditor(parent, dictlst, elemlst, prelbl=[], postlbl=[], title='Edit items', header='', size=(300, 250), CopyButton=False, ASCIIonly=False, **kw)[source]

Shell routine to call a ScrolledMultiEditor dialog. See ScrolledMultiEditor for parameter definitions.

Returns:True if the OK button is pressed; False if the window is closed with the system menu or the Cancel button.
GSASIIctrlGUI.Define_wxId(*args)[source]

routine to create unique global wx Id symbols in this module.

class GSASIIctrlGUI.DisAglDialog(parent, data, default, Reset=True, Angle=True)[source]

Distance/Angle Controls input dialog. After ShowModal() returns, the results are found in dict self.data, which is accessed using GetData().

Parameters:
  • parent (wx.Frame) – reference to parent frame (or None)
  • data (dict) – a dict containing the current search ranges or an empty dict, which causes default values to be used. Will be used to set element DisAglCtls in Phase Tree Item
  • default (dict) – A dict containing the default search ranges for each element.
  • Reset (bool) – if True (default), show Reset button
  • Angle (bool) – if True (default), show angle radii
Draw(data)[source]

Creates the contents of the dialog. Normally called by __init__().

GetData()[source]

Returns the values from the dialog

OnOk(event)[source]

Called when the OK button is pressed

OnReset(event)[source]

Called when the Reset button is pressed

class GSASIIctrlGUI.EnumSelector(parent, dct, item, choices, values=None, OnChange=None, **kw)[source]

A customized wxpython.ComboBox that selects items from a list of choices, but sets a dict (list) entry to the corresponding entry from the input list of values.

Parameters:
  • parent (wx.Panel) – the parent to the ComboBox (usually a frame or panel)
  • dct – a dict or list to contain the value set for the ComboBox.
  • item – the dict key (or list index) where dct[item] will be set to the value selected in the ComboBox. Also, dct[item] contains the starting value shown in the widget. If the value does not match an entry in values, the first value in choices is used as the default, but dct[item] is not changed.
  • choices (list) –

    a list of choices to be displayed to the user such as

    ["default","option 1","option 2",]
    

    Note that these options will correspond to the entries in values (if specified) item by item.

  • values (list) –

    a list of values that correspond to the options in choices, such as

    [0,1,2]
    

    The default for values is to use the same list as specified for choices.

  • onChange (function) – an optional routine that will be called when the ComboBox can be specified.
  • (other) – additional keyword arguments accepted by ComboBox can be specified.
class GSASIIctrlGUI.FlagSetDialog(parent, title, colnames, rownames, flags)[source]

Creates popup with table of variables to be checked for e.g. refinement flags

class GSASIIctrlGUI.G2CheckBox(parent, label, loc, key, OnChange=None)[source]

A customized version of a CheckBox that automatically initializes the control to a supplied list or dict entry and updates that entry as the widget is used.

Parameters:
  • parent (wx.Panel) – name of panel or frame that will be the parent to the widget. Can be None.
  • label (str) – text to put on check button
  • loc (dict/list) – the dict or list with the initial value to be placed in the CheckBox.
  • key (int/str) – the dict key or the list index for the value to be edited by the CheckBox. The loc[key] element must exist. The CheckBox will be initialized from this value. If the value is anything other that True (or 1), it will be taken as False.
  • OnChange (function) – specifies a function or method that will be called when the CheckBox is changed (Default is None). The called function is supplied with one argument, the calling event.
class GSASIIctrlGUI.G2ChoiceButton(parent, choiceList, indLoc=None, indKey=None, strLoc=None, strKey=None, onChoice=None, **kwargs)[source]

A customized version of a wx.Choice that automatically initializes the control to match a supplied value and saves the choice directly into an array or list. Optionally a function can be called each time a choice is selected. The widget can be used with an array item that is set to to the choice by number (indLoc[indKey]) or by string value (strLoc[strKey]) or both. The initial value is taken from indLoc[indKey] if not None or strLoc[strKey] if not None.

Parameters:
  • parent (wx.Panel) – name of panel or frame that will be the parent to the widget. Can be None.
  • choiceList (list) – a list or tuple of choices to offer the user.
  • indLoc (dict/list) – a dict or list with the initial value to be placed in the Choice button. If this is None, this is ignored.
  • indKey (int/str) – the dict key or the list index for the value to be edited by the Choice button. If indLoc is not None then this must be specified and the indLoc[indKey] will be set. If the value for indLoc[indKey] is not None, it should be an integer in range(len(choiceList)). The Choice button will be initialized to the choice corresponding to the value in this element if not None.
  • strLoc (dict/list) – a dict or list with the string value corresponding to indLoc/indKey. Default (None) means that this is not used.
  • strKey (int/str) – the dict key or the list index for the string value The strLoc[strKey] element must exist or strLoc must be None (default).
  • onChoice (function) – name of a function to call when the choice is made.
setByString(string)[source]

Find an entry matching string and select it

class GSASIIctrlGUI.G2ColumnIDDialog(parent, title, header, Comments, ChoiceList, ColumnData, monoFont=False, **kw)[source]

A dialog for matching column data to desired items; some columns may be ignored.

Parameters:
  • ParentFrame (wx.Frame) – reference to parent frame
  • title (str) – heading above list of choices
  • header (str) – Title to place on window frame
  • ChoiceList (list) – a list of possible choices for the columns
  • ColumnData (list) – lists of column data to be matched with ChoiceList
  • monoFont (bool) – If False (default), use a variable-spaced font; if True use a equally-spaced font.
  • kw – optional keyword parameters for the wx.Dialog may be included such as size [which defaults to (320,310)] and style (which defaults to wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.CENTRE | wx.OK | wx.CANCEL); note that wx.OK and wx.CANCEL controls the presence of the eponymous buttons in the dialog.
Returns:

the name of the created dialog

GetSelection()[source]

Returns the selected sample parm for each column

class GSASIIctrlGUI.G2HistoDataDialog(parent, title, header, ParmList, ParmFmt, HistoList, ParmData, monoFont=False, **kw)[source]

A dialog for editing histogram data globally.

Parameters:
  • ParentFrame (wx.Frame) – reference to parent frame
  • title (str) – heading above list of choices
  • header (str) – Title to place on window frame
  • ParmList (list) – a list of names for the columns
  • ParmFmt (list) – a list of formatting strings for the columns
  • list – HistoList: a list of histogram names
  • ParmData (list) – a list of lists of data matched to ParmList; one for each item in HistoList
  • monoFont (bool) – If False (default), use a variable-spaced font; if True use a equally-spaced font.
  • kw – optional keyword parameters for the wx.Dialog may be included such as size [which defaults to (320,310)] and style (which defaults to wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.CENTRE | wx.OK | wx.CANCEL); note that wx.OK and wx.CANCEL controls the presence of the eponymous buttons in the dialog.
Returns:

the modified ParmData

GetData()[source]

Returns the modified ParmData

class GSASIIctrlGUI.G2HtmlWindow(parent, *args, **kwargs)[source]

Displays help information in a primitive HTML browser type window

class GSASIIctrlGUI.G2LoggedButton(parent, id=<sphinx.ext.autodoc.importer._MockObject object>, label='', locationcode='', handler=None, *args, **kwargs)[source]

A version of wx.Button that creates logging events. Bindings are saved in the object, and are looked up rather than directly set with a bind. An index to these buttons is saved as log.ButtonBindingLookup :param wx.Panel parent: parent widget :param int id: Id for button :param str label: label for button :param str locationcode: a label used internally to uniquely indentify the button :param function handler: a routine to call when the button is pressed

onPress(event)[source]

create log event and call handler

class GSASIIctrlGUI.G2LstCtrl(*args, **kwargs)[source]

Creates a custom ListCtrl with support for images in column labels

GSASIIctrlGUI.G2MessageBox(parent, msg, title='Error')[source]

Simple code to display a error or warning message

class GSASIIctrlGUI.G2MultiChoiceDialog(parent, title, header, ChoiceList, toggle=True, monoFont=False, filterBox=True, extraOpts={}, selected=[], **kw)[source]

A dialog similar to wx.MultiChoiceDialog except that buttons are added to set all choices and to toggle all choices and a filter is available to select from available entries. Note that if multiple entries are placed in the filter box separated by spaces, all of the strings must be present for an item to be shown.

Parameters:
  • ParentFrame (wx.Frame) – reference to parent frame
  • title (str) – heading above list of choices
  • header (str) – Title to place on window frame
  • ChoiceList (list) – a list of choices where one more will be selected
  • toggle (bool) – If True (default) the toggle and select all buttons are displayed
  • monoFont (bool) – If False (default), use a variable-spaced font; if True use a equally-spaced font.
  • filterBox (bool) – If True (default) an input widget is placed on the window and only entries matching the entered text are shown.
  • extraOpts (dict) – a dict containing a entries of form label_i and value_i with extra options to present to the user, where value_i is the default value. Options are listed ordered by the value_i values.
  • selected (list) – list of indicies for items that should be
  • kw – optional keyword parameters for the wx.Dialog may be included such as size [which defaults to (320,310)] and style (which defaults to wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.CENTRE| wx.OK | wx.CANCEL); note that wx.OK and wx.CANCEL style items control the presence of the eponymous buttons in the dialog.
Returns:

the name of the created dialog

Filter(event)[source]

Read text from filter control and select entries that match. Called by Timer after a delay with no input or if Enter is pressed.

GetSelections()[source]

Returns a list of the indices for the selected choices

OnCheck(event)[source]

for CheckListBox events; if Set Range is in use, this sets/clears all entries in range between start and end according to the value in start. Repeated clicks on the start change the checkbox state, but do not trigger the range copy. The caption next to the button is updated on the first button press.

SetRange(event)[source]

Respond to a press of the Set Range button. Set the range flag and the caption next to the button

SetSelections(selList)[source]

Sets the selection indices in selList as selected. Resets any previous selections for compatibility with wx.MultiChoiceDialog. Note that the state for only the filtered items is shown.

Parameters:selList (list) – indices of items to be selected. These indices are referenced to the order in self.ChoiceList
onChar(event)[source]

Respond to keyboard events in the Filter box

class GSASIIctrlGUI.G2MultiChoiceWindow(parent, title, ChoiceList, SelectList, toggle=True, monoFont=False, filterBox=True, OnChange=None, OnChangeArgs=[], helpText=None)[source]

Creates a sizer similar to G2MultiChoiceDialog except that buttons are added to set all choices and to toggle all choices. This is placed in a sizer, so that it can be used in a frame or panel.

Parameters:
  • parent – reference to parent frame/panel
  • title (str) – heading above list of choices
  • ChoiceList (list) – a list of choices where one more will be selected
  • SelectList (list) – a list of selected choices
  • toggle (bool) – If True (default) the toggle and select all buttons are displayed
  • monoFont (bool) – If False (default), use a variable-spaced font; if True use a equally-spaced font.
  • filterBox (bool) – If True (default) an input widget is placed on the window and only entries matching the entered text are shown.
  • OnChange (function) – a reference to a callable object, that is called each time any a choice is changed. Default is None which will not be called.
  • OnChangeArgs (list) – a list of arguments to be supplied to function OnChange. The default is a null list.
Returns:

the name of the created sizer

Filter(event)[source]

Read text from filter control and select entries that match. Called by Timer after a delay with no input or if Enter is pressed.

GetSelections()[source]

Returns a list of the indices for the selected choices

OnCheck(event)[source]

for CheckListBox events; if Set Range is in use, this sets/clears all entries in range between start and end according to the value in start. Repeated clicks on the start change the checkbox state, but do not trigger the range copy. The caption next to the button is updated on the first button press.

SetRange(event)[source]

Respond to a press of the Set Range button. Set the range flag and the caption next to the button

SetSelections(selList)[source]

Sets the selection indices in selList as selected. Resets any previous selections for compatibility with wx.MultiChoiceDialog. Note that the state for only the filtered items is shown.

Parameters:selList (list) – indices of items to be selected. These indices are referenced to the order in self.ChoiceList
onChar(event)[source]

Respond to keyboard events in the Filter box

class GSASIIctrlGUI.G2SingleChoiceDialog(parent, title, header, ChoiceList, monoFont=False, filterBox=True, **kw)[source]

A dialog similar to wx.SingleChoiceDialog except that a filter can be added.

Parameters:
  • ParentFrame (wx.Frame) – reference to parent frame
  • title (str) – heading above list of choices
  • header (str) – Title to place on window frame
  • ChoiceList (list) – a list of choices where one will be selected
  • monoFont (bool) – If False (default), use a variable-spaced font; if True use a equally-spaced font.
  • filterBox (bool) – If True (default) an input widget is placed on the window and only entries matching the entered text are shown.
  • kw – optional keyword parameters for the wx.Dialog may be included such as size [which defaults to (320,310)] and style (which defaults to wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.CENTRE | wx.OK | wx.CANCEL); note that wx.OK and wx.CANCEL controls the presence of the eponymous buttons in the dialog.
Returns:

the name of the created dialog

GetSelection()[source]

Returns the index of the selected choice

GSASIIctrlGUI.G2SliderWidget(parent, loc, key, label, xmin, xmax, iscale, onChange=None, onChangeArgs=[])[source]

A customized combination of a wx.Slider and a validated wx.TextCtrl (see ValidatedTxtCtrl) that allows either a slider or text entry to set a value within a range.

Parameters:
  • parent (wx.Panel) – name of panel or frame that will be the parent to the TextCtrl. Can be None.
  • loc (dict/list) – the dict or list with the initial value to be placed in the TextCtrl.
  • key (int/str) – the dict key or the list index for the value to be edited by the TextCtrl. The loc[key] element must exist and should have a float value. It will be forced to an initial value between xmin and xmax.
  • label (str) – A label to be placed to the left of the slider.
  • xmin (float) – the minimum allowed valid value.
  • xmax (float) – the maximum allowed valid value.
  • iscale (float) – number to scale values to integers which is what the Scale widget uses. If the xmin=1 and xmax=4 and iscale=1 then values only the values 1,2,3 and 4 can be set with the slider.
  • onChange (callable) – function to call when value is changed. Default is None where nothing will be called.
  • onChangeArgs (list) – arguments to be passed to onChange function when called.
Returns:

returns a wx.BoxSizer containing the widgets

class GSASIIctrlGUI.G2TreeCtrl(parent=None, *args, **kwargs)[source]

Create a wrapper around the standard TreeCtrl so we can “wrap” various events.

This logs when a tree item is selected (in onSelectionChanged())

This also wraps lists and dicts pulled out of the tree to track where they were retrieved from.

ConvertRelativeHistNum(histtype, histnum)[source]

Converts a histogram type and relative histogram number to a histogram name in the current project

ConvertRelativePhaseNum(phasenum)[source]

Converts relative phase number to a phase name in the current project

GetImageLoc(TreeId)[source]

Get Image data from the Tree. Handles cases where the image name is specified, as well as where the image file name is a tuple containing the image file and an image number

GetRelativeHistNum(histname)[source]

Returns list with a histogram type and a relative number for that histogram, or the original string if not a histogram

GetRelativePhaseNum(phasename)[source]

Returns a phase number if the string matches a phase name or else returns the original string

RestoreExposedItems()[source]

Traverse the top level tree items and restore exposed (expanded) tree items back to their previous state (done after a reload of the tree after a refinement)

SaveExposedItems()[source]

Traverse the top level tree items and save names of exposed (expanded) tree items. Done before a refinement.

UpdateImageLoc(TreeId, imagefile)[source]

Saves a new imagefile name in the Tree. Handles cases where the image name is specified, as well as where the image file name is a tuple containing the image file and an image number

class GSASIIctrlGUI.GSGrid(parent, name='')[source]

Basic wx.Grid implementation

InstallGridToolTip(rowcolhintcallback, colLblCallback=None, rowLblCallback=None)[source]

code to display a tooltip for each item on a grid from http://wiki.wxpython.org/wxGrid%20ToolTips (buggy!), expanded to column and row labels using hints from https://groups.google.com/forum/#!topic/wxPython-users/bm8OARRVDCs

Parameters:
  • rowcolhintcallback (function) – a routine that returns a text string depending on the selected row and column, to be used in explaining grid entries.
  • colLblCallback (function) – a routine that returns a text string depending on the selected column, to be used in explaining grid columns (if None, the default), column labels do not get a tooltip.
  • rowLblCallback (function) – a routine that returns a text string depending on the selected row, to be used in explaining grid rows (if None, the default), row labels do not get a tooltip.
SetTable(table, *args, **kwargs)[source]

Overrides the standard SetTable method with one that uses GridFractionEditor for all numeric columns (unless useFracEdit is false)

completeEdits()[source]

complete any outstanding edits

setupPopup(lblList, callList)[source]

define a callback that creates a popup menu. The rows associated with the items selected items are selected in the table and if an item is called from the menu, the corresponding function is called to perform an action on the

Parameters:
  • lblList (list) – list of str items that will be placed in the popup menu
  • callList (list) – list of functions to be called when a
Returns:

a callback that can be used to create the menu

Sample usage:

lblList = ('Delete','Set atom style','Set atom label',
               'Set atom color','Set view point','Generate copy',
               'Generate surrounding sphere','Transform atoms',
               'Generate bonded')
callList = (DrawAtomsDelete,DrawAtomStyle, DrawAtomLabel,
                DrawAtomColor,SetViewPoint,AddSymEquiv,
                AddSphere,TransformSymEquiv,
                FillCoordSphere)
onRightClick = drawAtoms.setupPopup(lblList,callList)
drawAtoms.Bind(wg.EVT_GRID_CELL_RIGHT_CLICK, onRightClick)
drawAtoms.Bind(wg.EVT_GRID_LABEL_RIGHT_CLICK, onRightClick)
class GSASIIctrlGUI.GSNoteBook(parent, name='', size=None, style=None)[source]

Notebook used in various locations; implemented with wx.aui extension

GSASIIctrlGUI.GetConfigValsDocs()[source]

Reads the module referenced in fname (often <module>.__file__) and return a dict with names of global variables as keys. For each global variable, the value contains four items:

Returns:a dict where keys are names defined in module config_example.py where the value is a list of four items, as follows:
  • item 0: the default value
  • item 1: the current value
  • item 2: the initial value (starts same as item 1)
  • item 3: the “docstring” that follows variable definition
GSASIIctrlGUI.GetExportPath(G2frame)[source]

Determines the default location to use for writing files. Tries sequentially G2frame.LastExportDir and G2frame.LastGPXdir.

Returns:a string containing the path to be used when writing files or ‘.’ if none of the above are specified.
GSASIIctrlGUI.GetImportFile(G2frame, message, defaultDir='', defaultFile='', style=<sphinx.ext.autodoc.importer._MockObject object>, parent=None, *args, **kwargs)[source]

Uses a customized dialog that gets files from the appropriate import directory. Arguments are used the same as in wx.FileDialog(). Selection of multiple files is allowed if argument style includes wx.FD_MULTIPLE.

The default initial directory (unless overridden with argument defaultDir) is found in G2frame.TutorialImportDir, config setting Import_directory or G2frame.LastImportDir, see GetImportPath().

The path of the first file entered is used to set G2frame.LastImportDir and optionally config setting Import_directory.

Returns:a list of files or an empty list
GSASIIctrlGUI.GetImportPath(G2frame)[source]

Determines the default location to use for importing files. Tries sequentially G2frame.TutorialImportDir, config var Import_directory, G2frame.LastImportDir and G2frame.LastGPXdir

Returns:a string containing the path to be used when reading files or ‘.’ if none of the above are specified.
GSASIIctrlGUI.GetItemOrder(parent, keylist, vallookup, posdict)[source]

Creates a dialog where items can be ordered into columns

Parameters:
  • keylist (list) – is a list of keys for column assignments
  • vallookup (dict) – is a dict keyed by names in keylist where each item is a dict. Each inner dict contains variable names as keys and their associated values
  • posdict (dict) – is a dict keyed by names in keylist where each item is a dict. Each inner dict contains column numbers as keys and their associated variable name as a value. This is used for both input and output.
class GSASIIctrlGUI.GridFractionEditor(grid)[source]

A grid cell editor class that allows entry of values as fractions as well as sine and cosine values [as s() and c(), sin() or sind(), etc]. Any valid Python expression will be evaluated.

The current value can be incremented, multiplied or divided by prefixing an expression by +, * or / respectively.

ApplyEdit(row, col, grid)[source]

Called only in wx >= 2.9 Save the value of the control into the grid if EndEdit() returns as True

class GSASIIctrlGUI.HelpButton(parent, msg='', helpIndex='', wrap=None)[source]

Create a help button that displays help information. The text can be displayed in a modal message window or it can be a reference to a location in the gsasII.html (etc.) help web page, in which case that page is opened in a web browser.

TODO: it might be nice if it were non-modal: e.g. it stays around until the parent is deleted or the user closes it, but this did not work for me.

Parameters:
  • parent – the panel/frame where the button will be placed
  • msg (str) – the help text to be displayed. Indentation on multiline help text is stripped (see StripIndents()). If wrap is set as non-zero, all new lines are
  • helpIndex (str) – location of the help information in the gsasII.html help file in the form of an anchor string. The URL will be constructed from: location + gsasII.html + “#” + helpIndex
  • wrap (int) – if specified, the text displayed is reformatted by wrapping it to fit in wrap pixels. Default is None which prevents wrapping.
GSASIIctrlGUI.HorizontalLine(sizer, parent)[source]

Draws a horizontal line as wide as the window.

GSASIIctrlGUI.ItemSelector(ChoiceList, ParentFrame=None, title='Select an item', size=None, header='Item Selector', useCancel=True, multiple=False)[source]

Provide a wx dialog to select a single item or multiple items from list of choices

Parameters:
  • ChoiceList (list) – a list of choices where one will be selected
  • ParentFrame (wx.Frame) – Name of parent frame (default None)
  • title (str) – heading above list of choices (default ‘Select an item’)
  • size (wx.Size) – Size for dialog to be created (default None – size as needed)
  • header (str) – Title to place on window frame (default ‘Item Selector’)
  • useCancel (bool) – If True (default) both the OK and Cancel buttons are offered
  • multiple (bool) – If True then multiple items can be selected (default False)
Returns:

the selection index or None or a selection list if multiple is true

Called by GSASIIdataGUI.OnReOrgSelSeq() Which is not fully implemented.

class GSASIIctrlGUI.MultiColumnSelection(parent, title, colLabels, choices, colWidths, checkLbl='', height=400, centerCols=False, *args, **kw)[source]

Defines a Dialog widget that can be used to select an item from a multicolumn list. The first column should be short, but remaining columns are word-wrapped if the length of the information extends beyond the column.

When created, the dialog will be shown and <dlg>.Selection will be set to the index of the selected row, or -1. Be sure to use <dlg>.Destroy() to remove the window after reading the selection. If the dialog cannot be shown because a very old version of wxPython is in use, <dlg>.Selection will be None.

If checkLbl is provided with a value, then a set of check buttons starts the table and <dlg>.Selections has the checked rows.

Parameters:
  • parent (wx.Frame) – the parent frame (or None)
  • title (str) – A title for the dialog window
  • colLabels (list) – labels for each column
  • choices (list) – a nested list with a value for each row in the table. Within each value should be a list of values for each column. There must be at least one value, but it is OK to have more or fewer values than there are column labels (colLabels). Extra are ignored and unspecified columns are left blank.
  • colWidths (list) – a list of int values specifying the column width for each column in the table (pixels). There must be a value for every column label (colLabels).
  • checkLbl (str) – A label for a row of checkboxes added at the beginning of the table
  • height (int) – an optional height (pixels) for the table (defaults to 400)
  • centerCols (bool) – if True, items in each column are centered. Default is False

Example use:

lbls = ('col 1','col 2','col 3')
choices=(['test1','explanation of test 1'],
         ['b', 'a really really long line that will be word-wrapped'],
         ['test3','more explanation text','optional 3rd column text'])
colWidths=[200,400,100]
dlg = MultiColumnSelection(frm,'select tutorial',lbls,choices,colWidths)
value = choices[dlg.Selection][0]
dlg.Destroy()
class GSASIIctrlGUI.MultiDataDialog(parent, title, prompts, values, limits=[[0.0, 1.0]], formats=['%.5g'])[source]

Dialog to obtain multiple values from user

class GSASIIctrlGUI.MultiIntegerDialog(parent, title, prompts, values)[source]

Input a series of integers based on prompts

class GSASIIctrlGUI.MultiStringDialog(parent, title, prompts, values=[], size=-1, addRows=False, hlp=None, lbl=None)[source]

Dialog to obtain a multi string values from user

Parameters:
  • parent (wx.Frame) – name of parent frame
  • title (str) – title string for dialog
  • prompts (list) – list of strings to tell user what they are inputting
  • values (list) – list of str default input values, if any
  • size (int) – length of the input box in pixels
  • addRows (bool) – if True, users can add rows to the table (default is False)
  • hlp (str) – if supplied, a help button is added to the dialog that can be used to display the supplied help text in this variable.
  • lbl (str) – label placed at top of dialog
Returns:

a wx.Dialog instance

GetValues()[source]

Use this method to get the value(s) entered by the user

Returns:a list of strings entered by user
Show()[source]

Use this method after creating the dialog to post it

Returns:True if the user pressed OK; False if the User pressed Cancel
GSASIIctrlGUI.MultipleBlockSelector(ChoiceList, ParentFrame=None, title='Select a block', size=None, header='Block Selector')[source]

Provide a wx dialog to select a block of data if the file contains more than one set of data and one must be selected. Used in G2pwd_CIF only.

Returns:a list of the selected blocks
class GSASIIctrlGUI.MultipleChoicesDialog(choicelist, headinglist, head='Select options', title='Please select from options below', parent=None)[source]

A dialog that offers a series of choices, each with a title and a wx.Choice widget. Intended to be used Modally. typical input:

  • choicelist=[ (‘a’,’b’,’c’), (‘test1’,’test2’),(‘no choice’,)]
  • headinglist = [ ‘select a, b or c’, ‘select 1 of 2’, ‘No option here’]

selections are placed in self.chosen when OK is pressed

Also see GSASIIctrlGUI

GSASIIctrlGUI.MultipleChoicesSelector(choicelist, headinglist, ParentFrame=None, **kwargs)[source]

A modal dialog that offers a series of choices, each with a title and a wx.Choice widget. Used in G2pwd_CIF only.

Typical input:

  • choicelist=[ (‘a’,’b’,’c’), (‘test1’,’test2’),(‘no choice’,)]
  • headinglist = [ ‘select a, b or c’, ‘select 1 of 2’, ‘No option here’]

optional keyword parameters are: head (window title) and title returns a list of selected indicies for each choice (or None)

class GSASIIctrlGUI.MyHelp(frame, includeTree=False, morehelpitems=[])[source]

A class that creates the contents of a help menu. The menu will start with two entries:

  • ‘Help on <helpType>’: where helpType is a reference to an HTML page to be opened
  • About: opens an About dialog using OnHelpAbout. N.B. on the Mac this gets moved to the App menu to be consistent with Apple style.

NOTE: for this to work properly with respect to system menus, the title for the menu must be &Help, or it will not be processed properly:

menu.Append(menu=MyHelp(self,...),title="&Help")
OnCheckUpdates(event)[source]

Check if the GSAS-II repository has an update for the current source files and perform that update if requested.

OnHelpAbout(event)[source]

Display an ‘About GSAS-II’ box

OnHelpById(event)[source]

Called when Help on… is pressed in a menu. Brings up a web page for documentation. Uses the helpKey value from the dataWindow window unless a special help key value has been defined for this menu id in self.HelpById

Note that self should now (2frame) be child of the main window (G2frame)

OnSelectVersion(event)[source]

Allow the user to select a specific version of GSAS-II

class GSASIIctrlGUI.MyHtmlPanel(frame, newId)[source]

Defines a panel to display HTML help information, as an alternative to displaying help information in a web browser.

class GSASIIctrlGUI.NumberValidator(typ, positiveonly=False, xmin=None, xmax=None, exclLim=[False, False], result=None, key=None, OKcontrol=None, CIFinput=False)[source]

A validator to be used with a TextCtrl to prevent entering characters other than digits, signs, and for float input, a period and exponents.

The value is checked for validity after every keystroke
If an invalid number is entered, the box is highlighted. If the number is valid, it is saved in result[key]
Parameters:
  • typ (type) – the base data type. Must be int or float.
  • positiveonly (bool) – If True, negative integers are not allowed (default False). This prevents the + or - keys from being pressed. Used with typ=int; ignored for typ=float.
  • xmin (number) – Minimum allowed value. If None (default) the lower limit is unbounded
  • xmax (number) – Maximum allowed value. If None (default) the upper limit is unbounded
  • exclLim (list) – if True exclude xmin/xmax value ([exclMin,exclMax]); (Default=[False,False])
  • result (dict/list) – List or dict where value should be placed when valid
  • key (any) – key to use for result (int for list)
  • OKcontrol (function) – function or class method to control an OK button for a window. Ignored if None (default)
  • CIFinput (bool) – allows use of a single ‘?’ or ‘.’ character as valid input.
CheckInput(previousInvalid)[source]

called to test every change to the TextCtrl for validity and to change the appearance of the TextCtrl

Anytime the input is invalid, call self.OKcontrol (if defined) because it is fast. If valid, check for any other invalid entries only when changing from invalid to valid, since that is slower.

Parameters:previousInvalid (bool) – True if the TextCtrl contents were invalid prior to the current change.
Clone()[source]

Create a copy of the validator, a strange, but required component

OnChar(event)[source]

Called each type a key is pressed ignores keys that are not allowed for int and float types

ShowValidity(tc)[source]

Set the control colors to show invalid input

Parameters:tc (wx.TextCtrl) – A reference to the TextCtrl that the validator is associated with.
TestValid(tc)[source]

Check if the value is valid by casting the input string into the current type.

Set the invalid variable in the TextCtrl object accordingly.

If the value is valid, save it in the dict/list where the initial value was stored, if appropriate.

Parameters:tc (wx.TextCtrl) – A reference to the TextCtrl that the validator is associated with.
TransferFromWindow()[source]

Needed by validator, strange, but required component

TransferToWindow()[source]

Needed by validator, strange, but required component

class GSASIIctrlGUI.OpenTutorial(parent)[source]

Open a tutorial web page, optionally copying the web page, screen images and data file(s) to the local disk.

ChooseTutorial(choices)[source]

choose a tutorial from a list (will eventually only be used with very old wxPython

ChooseTutorial2(choices)[source]

Select tutorials from a two-column table, when possible

DownloadAll(event)[source]

Download or update all tutorials

SelectAndDownload(event)[source]

Make a list of all tutorials on web and allow user to choose one to download and then view

SelectDownloadLoc(event)[source]

Select a download location, Cancel resets to the default

SetTutorialPath()[source]

Get the tutorial location if set; if not pick a default directory in a logical place

UpdateDownloaded(event)[source]

Find the downloaded tutorials and run an svn update on them

onSelectDownloaded(event)[source]

Select a previously downloaded tutorial

onWebBrowse(event)[source]

Make a list of all tutorials on web and allow user to view one.

class GSASIIctrlGUI.OrderBox(parent, keylist, vallookup, posdict, *arg, **kw)[source]

Creates a panel with scrollbars where items can be ordered into columns

Parameters:
  • keylist (list) – is a list of keys for column assignments
  • vallookup (dict) – is a dict keyed by names in keylist where each item is a dict. Each inner dict contains variable names as keys and their associated values
  • posdict (dict) – is a dict keyed by names in keylist where each item is a dict. Each inner dict contains column numbers as keys and their associated variable name as a value. This is used for both input and output.
OnChoice(event)[source]

Called when a column is assigned to a variable

GSASIIctrlGUI.PhaseSelector(ChoiceList, ParentFrame=None, title='Select a phase', size=None, header='Phase Selector')[source]

Provide a wx dialog to select a phase, used in importers if a file contains more than one phase

class GSASIIctrlGUI.PickTwoDialog(parent, title, prompt, names, choices)[source]

This does not seem to be in use

class GSASIIctrlGUI.SGMagSpinBox(parent, title, text, table, Cents, names, spins, ifGray)[source]

Special version of MessageBox that displays magnetic spin text

Show()[source]

Use this method after creating the dialog to post it

class GSASIIctrlGUI.SGMessageBox(parent, title, text, table, spins=[])[source]

Special version of MessageBox that displays space group & super space group text in two blocks

Show()[source]

Use this method after creating the dialog to post it

GSASIIctrlGUI.SaveConfigVars(vars, parent=None)[source]

Write the current config variable values to config.py

Params dict vars:
 a dictionary of variable settings and meanings as created in GetConfigValsDocs().
Parameters:parent – wx.Frame object or None (default) for parent of error message if no file can be written.
Returns:True if unable to write the file, None otherwise
class GSASIIctrlGUI.ScrolledMultiEditor(parent, dictlst, elemlst, prelbl=[], postlbl=[], title='Edit items', header='', size=(300, 250), CopyButton=False, ASCIIonly=False, minvals=[], maxvals=[], sizevals=[], checkdictlst=[], checkelemlst=[], checklabel='')[source]

Define a window for editing a potentially large number of dict- or list-contained values with validation for each item. Edited values are automatically placed in their source location. If invalid entries are provided, the TextCtrl is turned yellow and the OK button is disabled.

The type for each TextCtrl validation is determined by the initial value of the entry (int, float or string). Float values can be entered in the TextCtrl as numbers or also as algebraic expressions using operators + - / * () and **, in addition pi, sind(), cosd(), tand(), and sqrt() can be used, as well as appreviations s(), sin(), c(), cos(), t(), tan() and sq().

Parameters:
  • parent (wx.Frame) – name of parent window, or may be None
  • dictlst (tuple) – a list of dicts or lists containing values to edit
  • elemlst (tuple) – a list of keys/indices for items in dictlst. Note that elemlst must have the same length as dictlst, where each item in elemlst will will match an entry for an entry for successive dicts/lists in dictlst.
  • prelbl (tuple) – a list of labels placed before the TextCtrl for each item (optional)
  • postlbl (tuple) – a list of labels placed after the TextCtrl for each item (optional)
  • title (str) – a title to place in the frame of the dialog
  • header (str) – text to place at the top of the window. May contain new line characters.
  • size (wx.Size) – a size parameter that dictates the size for the scrolled region of the dialog. The default is (300,250).
  • CopyButton (bool) – if True adds a small button that copies the value for the current row to all fields below (default is False)
  • ASCIIonly (bool) – if set as True will remove unicode characters from strings
  • minvals (list) – optional list of minimum values for validation of float or int values. Ignored if value is None.
  • maxvals (list) – optional list of maximum values for validation of float or int values. Ignored if value is None.
  • sizevals (list) – optional list of wx.Size values for each input widget. Ignored if value is None.
  • checkdictlst (tuple) – an optional list of dicts or lists containing bool values (similar to dictlst).
  • checkelemlst (tuple) – an optional list of dicts or lists containing bool key values (similar to elemlst). Must be used with checkdictlst.
  • checklabel (string) – a string to use for each checkbutton
Returns:

the wx.Dialog created here. Use method .ShowModal() to display it.

Example for use of ScrolledMultiEditor:

dlg = <pkg>.ScrolledMultiEditor(frame,dictlst,elemlst,prelbl,postlbl,
                                header=header)
if dlg.ShowModal() == wx.ID_OK:
     for d,k in zip(dictlst,elemlst):
         print d[k]

Example definitions for dictlst and elemlst:

    dictlst = (dict1,list1,dict1,list1)
    elemlst = ('a', 1, 2, 3)

This causes items dict1['a'], list1[1], dict1[2] and list1[3] to be edited.

Note that these items must have int, float or str values assigned to them. The dialog will force these types to be retained. String values that are blank are marked as invalid.

ControlOKButton(setvalue)[source]

Enable or Disable the OK button for the dialog. Note that this is passed into the ValidatedTxtCtrl for use by validators.

Parameters:setvalue (bool) – if True, all entries in the dialog are checked for validity. if False then the OK button is disabled.
class GSASIIctrlGUI.SelectConfigSetting(parent=None)[source]

Dialog to select configuration variables and set associated values.

OnApplyChanges(event=None)[source]

Set config variables to match the current settings

OnBoolSelect(event)[source]

Respond to a change in a True/False variable

OnChange(event=None)[source]

Check if anything been changed. Turn the save button on/off.

OnSave(event)[source]

Write the config variables to config.py and then set them as the current settings

OnSelection()[source]

show a selected variable and allow it to be changed

onSelDir(event)[source]

Select a directory from a menu

onSelExec(event)[source]

Select an executable file from a menu

GSASIIctrlGUI.SelectEdit1Var(G2frame, array, labelLst, elemKeysLst, dspLst, refFlgElem)[source]

Select a variable from a list, then edit it and select histograms to copy it to.

Parameters:
  • G2frame (wx.Frame) – main GSAS-II frame
  • array (dict) – the array (dict or list) where values to be edited are kept
  • labelLst (list) – labels for each data item
  • elemKeysLst (list) – a list of lists of keys needed to be applied (see below) to obtain the value of each parameter
  • dspLst (list) – list list of digits to be displayed (10,4) is 10 digits with 4 decimal places. Can be None.
  • refFlgElem (list) – a list of lists of keys needed to be applied (see below) to obtain the refine flag for each parameter or None if the parameter does not have refine flag.
Example::
array = data labelLst = [‘v1’,’v2’] elemKeysLst = [[‘v1’], [‘v2’,0]] refFlgElem = [None, [‘v2’,1]]
  • The value for v1 will be in data[‘v1’] and this cannot be refined while,
  • The value for v2 will be in data[‘v2’][0] and its refinement flag is data[‘v2’][1]
GSASIIctrlGUI.ShowHelp(helpType, frame)[source]

Called to bring up a web page for documentation.

class GSASIIctrlGUI.ShowLSParms(G2frame, title, parmDict, varyList, fullVaryList, Controls, size=(650, 430))[source]

Create frame to show least-squares parameters

DrawPanel()[source]

Draws the contents of the entire dialog. Called initially & when radio buttons are pressed

repaintScrollTbl()[source]

Shows the selected variables in a ListCtrl

GSASIIctrlGUI.ShowScrolledInfo(parent, txt, width=600, height=400, header='Warning info')[source]

Simple code to display possibly extensive error or warning text in a scrolled window.

Parameters:
  • parent (wx.Frame) – parent window for
  • txt (str) – text to be displayed
  • width (int) – lateral of window in pixels (defaults to 600)
  • height (int) – vertical dimension of window in pixels (defaults to 400)
  • header (str) – width of window in pixels (defaults to 600)
GSASIIctrlGUI.ShowWebPage(URL, frame)[source]

Called to show a tutorial web page.

class GSASIIctrlGUI.SingleFloatDialog(parent, title, prompt, value, limits=[0.0, 1.0], fmt='%.5g')[source]

Dialog to obtain a single float value from user

Parameters:
  • parent (wx.Frame) – name of parent frame
  • title (str) – title string for dialog
  • prompt (str) – string to tell user what they are inputing
  • value (str) – default input value, if any
  • limits (list) – upper and lower value used to set bounds for entry, use [None,None] for no bounds checking, [None,val] for only upper bounds, etc. Default is [0,1]. Values outside of limits will be ignored.
  • format (str) – string to format numbers. Defaults to ‘%.5g’. Use ‘%d’ to have integer input (but dlg.GetValue will still return a float).

Typical usage:

limits = (0,1)
dlg = G2G.SingleFloatDialog(G2frame,'New value','Enter new value for...',default,limits)
if dlg.ShowModal() == wx.ID_OK:
    parm = dlg.GetValue()
dlg.Destroy()    
ControlOKButton(setvalue)[source]

Enable or Disable the OK button for the dialog. Note that this is passed into the ValidatedTxtCtrl for use by validators.

Parameters:setvalue (bool) – if True, all entries in the dialog are checked for validity. if False then the OK button is disabled.
class GSASIIctrlGUI.SingleIntDialog(parent, title, prompt, value, limits=[None, None])[source]

Dialog to obtain a single int value from user

Parameters:
  • parent (wx.Frame) – name of parent frame
  • title (str) – title string for dialog
  • prompt (str) – string to tell user what they are inputing
  • value (str) – default input value, if any
  • limits (list) – upper and lower value used to set bounds for entries. Default is [None,None] – for no bounds checking; use [None,val] for only upper bounds, etc. Default is [0,1]. Values outside of limits will be ignored.

Typical usage:

limits = (0,None)  # allows zero or positive values only
dlg = G2G.SingleIntDialog(G2frame,'New value','Enter new value for...',default,limits)
if dlg.ShowModal() == wx.ID_OK:
    parm = dlg.GetValue()
dlg.Destroy()    
class GSASIIctrlGUI.SingleStringDialog(parent, title, prompt, value='', size=(200, -1), help='', choices=None)[source]

Dialog to obtain a single string value from user

Parameters:
  • parent (wx.Frame) – name of parent frame
  • title (str) – title string for dialog
  • prompt (str) – string to tell use what they are inputting
  • value (str) – default input value, if any
  • size (tuple) – specifies default size and width for dialog [default (200,-1)]
  • help (str) – if supplied, a help button is added to the dialog that can be used to display the supplied help text/URL for setting this variable. (Default is ‘’, which is ignored.)
  • choices (list) – a set of strings that provide optional values that can be selected from; these can be edited if desired.
GetValue()[source]

Use this method to get the value entered by the user :returns: string entered by user

Show()[source]

Use this method after creating the dialog to post it :returns: True if the user pressed OK; False if the User pressed Cancel

class GSASIIctrlGUI.SortableLstCtrl(parent)[source]

Creates a read-only table with sortable columns. Sorting is done by clicking on a column label. A triangle facing up or down is added to indicate the column is sorted.

To use, the header is labeled using PopulateHeader(), then PopulateLine() is called for every row in table and finally SetColWidth() is called to set the column widths.

Parameters:parent (wx.Frame) – parent object for control
PopulateHeader(header, justify)[source]

Defines the column labels

Parameters:
  • header (list) – a list of strings with header labels
  • justify (list) – a list of int values where 0 causes left justification, 1 causes right justification, and -1 causes centering
PopulateLine(key, data)[source]

Enters each row into the table

Parameters:
  • key (int) – a unique int value for each line, probably should be sequential
  • data (list) – a list of strings for each column in that row
SetColWidth(col, width=None, auto=True, minwidth=0, maxwidth=None)[source]

Sets the column width.

Parameters:
  • width (int) – the column width in pixels
  • auto (bool) – if True (default) and width is None (default) the width is set by the maximum width entry in the column
  • minwidth (int) – used when auto is True, sets a minimum column width
  • maxwidth (int) – used when auto is True, sets a maximum column width. Do not use with minwidth
GSASIIctrlGUI.StripIndents(msg, singleLine=False)[source]

Strip unintended indentation from multiline strings. When singleLine is True, all newline are removed, but inserting “%%” into the string will cause a blank line to be inserted at that point and %t% will generate a new line and tab (to indent a line)

Parameters:
  • msg (str) – a string containing one or more lines of text. spaces or tabs following a newline are removed.
  • singleLine (bool) – removes all newlines from the msg so that the text may be wrapped.
Returns:

the string but reformatted

GSASIIctrlGUI.StripUnicode(string, subs='.')[source]

Strip non-ASCII characters from strings

Parameters:
  • string (str) – string to strip Unicode characters from
  • subs (str) – character(s) to place into string in place of each Unicode character. Defaults to ‘.’
Returns:

a new string with only ASCII characters

class GSASIIctrlGUI.Table(data=[], rowLabels=None, colLabels=None, types=None)[source]

Basic data table for use with GSgrid

class GSASIIctrlGUI.ValidatedTxtCtrl(parent, loc, key, nDig=None, notBlank=True, xmin=None, xmax=None, OKcontrol=None, OnLeave=None, typeHint=None, CIFinput=False, exclLim=[False, False], OnLeaveArgs={}, ASCIIonly=False, min=None, max=None, **kw)[source]

Create a TextCtrl widget that uses a validator to prevent the entry of inappropriate characters and changes color to highlight when invalid input is supplied. As valid values are typed, they are placed into the dict or list where the initial value came from. The type of the initial value must be int, float or str or None (see key and typeHint); this type (or the one in typeHint) is preserved.

Float values can be entered in the TextCtrl as numbers or also as algebraic expressions using operators + - / * () and **, in addition pi, sind(), cosd(), tand(), and sqrt() can be used, as well as appreviations s, sin, c, cos, t, tan and sq.

Parameters:
  • parent (wx.Panel) – name of panel or frame that will be the parent to the TextCtrl. Can be None.
  • loc (dict/list) – the dict or list with the initial value to be placed in the TextCtrl.
  • key (int/str) –

    the dict key or the list index for the value to be edited by the TextCtrl. The loc[key] element must exist, but may have value None. If None, the type for the element is taken from typeHint and the value for the control is set initially blank (and thus invalid.) This is a way to specify a field without a default value: a user must set a valid value.

    If the value is not None, it must have a base type of int, float, str or unicode; the TextCrtl will be initialized from this value.

  • nDig (list) – number of digits, places and optionally the format ([nDig,nPlc,fmt]) after decimal to use for display of float. The format is either ‘f’ (default) or ‘g’. Alternately, None can be specified which causes numbers to be displayed with approximately 5 significant figures for floats. If this is specified, then typeHint = float becomes the default. (Default=None).
  • notBlank (bool) – if True (default) blank values are invalid for str inputs.
  • xmin (number) – minimum allowed valid value. If None (default) the lower limit is unbounded. NB: test in NumberValidator is val >= xmin not val > xmin
  • xmax (number) – maximum allowed valid value. If None (default) the upper limit is unbounded NB: test in NumberValidator is val <= xmax not val < xmax
  • exclLim (list) – if True exclude min/max value ([exclMin,exclMax]); (Default=[False,False])
  • OKcontrol (function) – specifies a function or method that will be called when the input is validated. The called function is supplied with one argument which is False if the TextCtrl contains an invalid value and True if the value is valid. Note that this function should check all values in the dialog when True, since other entries might be invalid. The default for this is None, which indicates no function should be called.
  • OnLeave (function) –

    specifies a function or method that will be called when the focus for the control is lost. The called function is supplied with (at present) three keyword arguments:

    • invalid: (bool) True if the value for the TextCtrl is invalid
    • value: (int/float/str) the value contained in the TextCtrl
    • tc: (wx.TextCtrl) the TextCtrl object

    The number of keyword arguments may be increased in the future should needs arise, so it is best to code these functions with a **kwargs argument so they will continue to run without errors

    The default for OnLeave is None, which indicates no function should be called.

  • typeHint (type) – the value of typeHint should be int, float or str (or None). The value for this will override the initial type taken from value for the dict/list element loc[key] if not None and thus specifies the type for input to the TextCtrl. Defaults as None, which is ignored, unless nDig is specified in which case the default is float.
  • CIFinput (bool) – for str input, indicates that only printable ASCII characters may be entered into the TextCtrl. Forces output to be ASCII rather than Unicode. For float and int input, allows use of a single ‘?’ or ‘.’ character as valid input.
  • OnLeaveArgs (dict) – a dict with keyword args that are passed to the OnLeave function. Defaults to {}
  • ASCIIonly (bool) – if set as True will remove unicode characters from strings
  • (other) – other optional keyword parameters for the wx.TextCtrl widget such as size or style may be specified.
OnKeyDown(event)[source]

Special callback for wx 2.9+ on Mac where backspace is not processed by validator

ShowStringValidity(previousInvalid=True)[source]

Check if input is valid. Anytime the input is invalid, call self.OKcontrol (if defined) because it is fast. If valid, check for any other invalid entries only when changing from invalid to valid, since that is slower.

Parameters:previousInvalid (bool) – True if the TextCtrl contents were invalid prior to the current change.
class GSASIIctrlGUI.VirtualVarBox(parent)[source]
OnRowSelected(event, row=None)[source]

Creates an edit window when a parameter is selected

GSASIIctrlGUI.askSaveDirectory(G2frame)[source]

Ask the user to supply a directory name. Path name is used as the starting point for the next export path search.

Returns:a directory name (str) or None if Cancel is pressed
GSASIIctrlGUI.askSaveFile(G2frame, defnam, extension, longFormatName, parent=None)[source]

Ask the user to supply a file name

Parameters:
  • G2frame (wx.Frame) – The main GSAS-II window
  • defnam (str) – a default file name
  • extension (str) – the default file extension beginning with a ‘.’
  • longFormatName (str) – a description of the type of file
  • parent (wx.Frame) – the parent window for the dialog. Defaults to G2frame.
Returns:

a file name (str) or None if Cancel is pressed

class GSASIIctrlGUI.downdate(parent=None)[source]

Dialog to allow a user to select a version of GSAS-II to install

getVersion()[source]

Get the version number in the dialog

GSASIIctrlGUI.getTextSize(txt)[source]

Get the size of the text string txt in points, returns (x,y)

GSASIIctrlGUI.tutorialIndex = (['Getting started'], ['StartingGSASII', 'Starting GSAS.htm', 'Starting GSAS-II', 'An introduction to GSAS-II with starting instructions and a brief description of the displays.'], ['Rietveld refinement'], ['CWNeutron', 'Neutron CW Powder Data.htm', 'CW Neutron Powder fit for Yttrium-Iron Garnet', 'This shows a simple Rietveld refinement with constraints from CW neutron powder diffraction data.'], ['LabData', 'Laboratory X.htm', 'Fitting laboratory X-ray powder data for fluoroapatite', 'This shows a simple Rietveld refinement with CuKa lab Bragg-Brentano powder data.'], ['CWCombined', 'Combined refinement.htm', 'Combined X-ray/CW-neutron refinement of PbSO4', 'This shows Rietveld refinement of a structure with room temperature lab CuKa data and low temperature CW neutron data; \n use is made of the lattice parameter offsets to account for thermal expansion.'], ['TOF-CW Joint Refinement', 'TOF combined XN Rietveld refinement in GSAS.htm', 'Combined X-ray/TOF-neutron Rietveld refinement', 'This shows Rietveld refinement with high resolution synchrotron powder data and neutron TOF data'], ['Simulation', 'SimTutorial.htm', 'Simulating Powder Diffraction with GSAS-II', 'This show how to create a simulated powder pattern from a lab diffractometer.'], ['Advanced Rietveld'], ['BkgFit', 'FitBkgTut.htm', 'Fitting the Starting Background using Fixed Points', 'This shows how to get an initial estimate of background parameters from a suite of fixed points \n before beginning Rietveld refinement.'], ['LeBail', 'LeBailSucrose.htm', 'Le Bail Intensity Extraction in GSAS-II - Sucrose', 'Shows the process of setting up a Le Bail fit, where reflection \n intensities are treated as arbitrary, and how to converge the Le Bail\n intensities before a combined Le Bail/Least-Squares fit that \n optimizes lattice, peak shape and background parameters.'], ['CIFtutorial', 'CIFtutorial.html', 'Create a CIF for Publication', 'Shows how to create a full CIF for a project that includes the structure(s),\n bond distances/angles/ the observed and computed data, etc as well as documentary \n information about the sample(s), instrument(s) and the project in a way that allows\n for updating the CIF without having to reenter any of that information. The tutorial \n also explains how creation of template file can allow for reuse of that information.'], ['RietPlot', 'PublicationPlot.htm', 'Create a Publication-Ready Rietveld Plot', 'Shows how to create a customized version of a plot from a fit, \n with enlarged letters, different colors or symbols which can be written \n as a bitmap file, a pdf file or be exported to the Grace or Igor Pro \n plotting programs.'], ['ParameterLimits', 'ParameterLimitsUse.html', 'Use of Parameter Limits', 'Shows how to set lower and upper limits on selected parameters to keep refinements from refining unreasonably.'], ['RigidBody', 'RigidBodyRef.html', 'Rietveld Fitting with Rigid Bodies', 'Shows how to set up and refine with rigid bodies to simplify and improve the crystal structure model.'], ['Magnetic Structure Analysis'], ['SimpleMagnetic', 'SimpleMagnetic.htm', 'Simple Magnetic Structure Analysis', 'Analysis of a simple antiferromagnet and a simple ferromagnet from CW neutron powder data'], ['Magnetic-I', 'Magnetic Structures-I.htm', 'Magnetic Structure Analysis-I', 'Analysis of a simple antiferromagnet using Bilbao k-SUBGROUPSMAG from CW neutron powder data'], ['Magnetic-II', 'Magnetic-II.htm', 'Magnetic Structure Analysis-II', 'Analysis of a antiferromagnet with change of space group using Bilbao k-SUBGROUPSMAG from CW neutron powder data'], ['Magnetic-III', 'Magnetic-III.htm', 'Magnetic Structure Analysis-III', 'Analysis of a Type IV antiferromagnet with a cell axis doubling using Bilbao k-SUBGROUPSMAG from CW neutron powder data'], ['Magnetic-IV', 'Magnetic-IV.htm', 'Magnetic Structure Analysis-IV', 'Analysis of a Type IV antiferromagnet with a lattice centering change using Bilbao k-SUBGROUPSMAG from CW neutron powder data'], ['Magnetic-V', 'Magnetic-V.htm', 'Magnetic Structure Analysis-V', 'Analysis of a complex Type IV antiferromagnet with two propagation vectorse using Bilbao k-SUBGROUPSMAG from TOF neutron powder data'], ['Parametric sequential fitting'], ['SeqRefine', 'SequentialTutorial.htm', 'Sequential refinement of multiple datasets', 'This shows the fitting of a structural model to multiple data sets collected as a function of temperature (7-300K). \n This tutorial is the prerequisite for the next one.'], ['SeqParametric', 'ParametricFitting.htm', ' Parametric Fitting and Pseudo Variables for Sequential Fits', 'This explores the results of the sequential refinement obtained in the previous tutorial; includes \n plotting of variables and fitting the changes with simple equations.'], ['TOF Sequential Single Peak Fit', 'TOF Sequential Single Peak Fit.htm', 'Sequential fitting of single peaks and strain analysis of result', 'This shows the fitting of single peaks in a sequence of TOF powder patterns from a sample under load; includes\n fitting of the result to get Hookes Law coefficients for elastic deformations.'], ['Structure solution'], ['FitPeaks', 'Fit Peaks.htm', 'Fitting individual peaks & autoindexing', 'This covers two examples of selecting individual powder diffraction peaks, fitting them and then \n indexing to determine the crystal lattice and possible space group. This is the prerequisite for the next two tutorials.'], ['CFjadarite', 'Charge Flipping in GSAS.htm', ' Charge Flipping structure solution for jadarite', 'Solving the structure of jadarite (HLiNaSiB3O8) by charge flipping from Pawley extracted intensities\n from a high resolution synchrotron powder pattern.'], ['CFsucrose', 'Charge Flipping - sucrose.htm', ' Charge Flipping structure solution for sucrose', 'Solving the structure of sucrose (C12H22O11) by charge flipping from Pawley extracted intensities\n from a high resolution synchrotron powder pattern.'], ['CFXraySingleCrystal', 'CFSingleCrystal.htm', 'Charge Flipping structure solution with Xray single crystal data', 'Solving the structure of dipyridyl disulfate by charge flipping and then refine the structure by least-squares.'], ['TOF Charge Flipping', 'Charge Flipping with TOF single crystal data in GSASII.htm', 'Charge flipping with neutron TOF single crystal data', 'Solving the crystal structure or rubrene (C42H28) from single crystal neutron data \n via charge flipping and then refine the structure by least squares.'], ['MCsimanneal', 'MCSA in GSAS.htm', 'Monte-Carlo simulated annealing structure determination', 'Solving the structures of 3-aminoquinoline and α-d-lactose monohydrate from powder diffraction data \n via Monte Carlo/Simulated Annealing (MC/SA).'], ['Reverse Monte-Carlo Modeling'], ['RMCProfile-I', 'RMCProfile-I.htm', 'RMC Modeling with RMCProfile-I', 'Big box modelling for real and reciprocal space diffraction data for SF6'], ['RMCProfile-II', 'RMCProfile-II.htm', 'RMC Modeling with RMCProfile-II', 'Big box modelling for real and reciprocal space diffraction data for SrTiO3'], ['RMCProfile-III', 'RMCProfile-III.htm', 'RMC Modeling with RMCProfile-III', 'Combined x-ray/neutron big box modelling for real and reciprocal space diffraction data for GaPO4'], ['RMCProfile-IV', 'RMCProfile-IV.htm', 'RMC Modeling with RMCProfile-IV', 'x-ray big box modelling with potential energy restraints for real and reciprocal space diffraction data for GaPO4'], ['Stacking Fault Modeling'], ['StackingFaults-I', 'Stacking Faults-I.htm', 'Stacking fault simulations for diamond', 'This shows how to simulate the diffraction patterns from faulted diamond.'], ['StackingFaults-II', 'Stacking Faults II.htm', 'Stacking fault simulations for Keokuk kaolinite', 'This shows how to simulate some diffraction patterns from well ordered Keokuk kaolinite (Al2Si2O5(OH)4) clay.'], ['StackingFaults-III', 'Stacking Faults-III.htm', 'Stacking fault simulations for Georgia kaolinite', 'This shows how to simulate some diffraction patterns from poorly ordered Georgia kaolinite (Al2Si2O5(OH)4) clay.'], ['Powder diffractometer calibration'], ['CWInstDemo', 'FindProfParamCW.htm', 'Determining Starting Profile Parameters from a Standard', 'This shows how to determine profile parameters by fitting individual peaks\n with data collected on a standard using a lab diffractometer.'], ['FPAfit', 'FPAfit.htm', 'Determining Profile Parameters with Fundamental Parameters', 'This shows how to determine profile parameters by fitting \n peaks that are computed using the NIST Fundamental Parameters Python\n code. \n Input is formulated to use FPA values similar to those in Topas.'], ['TOF Calibration', 'Calibration of a TOF powder diffractometer.htm', 'Calibration of a Neutron TOF diffractometer', 'This uses the fitted positions of all visible peaks in a pattern of NIST SRM 660b La11B6 \n (a=4.15689Å) obtained in a multiple single peak fit. The positions are compared to those expected from the \n known lattice parameters to establish the diffractometer constants (difC, difA, difB and Zero) used for \n calculating TOF peak positions from d-spacings. In addition, the peak fitting includes the various profile \n coefficients thus fully describing the instrument contribution to the peak profiles.'], ['2D Image Processing'], ['2DCalibration', 'Calibration of an area detector in GSAS.htm', 'Calibration of an area detector', 'A demonstration of calibrating a Perkin-Elmer area detector, where the detector was intentionally tilted at 45 degrees.\n This exercise is the prerequisite for the next one.'], ['2DIntegration', 'Integration of area detector data in GSAS.htm', ' Integration of area detector data', 'Integration of the image from a Perkin-Elmer area detector, where the detector was intentionally tilted at 45 degrees.'], ['2DStrain', 'Strain fitting of 2D data in GSAS-II.htm', 'Strain fitting of 2D data', 'This show how to determine 3 strain tensor values using the method of He & Smith (Adv. in X-ray Anal. 41, 501, 1997) \n directly froom a sequence of 2D imges from a loaded sample.'], ['2DTexture', 'Texture analysis of 2D data in GSAS-II.htm', 'Texture analysis of 2D data', 'This shows 3 different methods for determining texture via spherical harmonics from 2D x-ray diffraction images. '], ['DeterminingWavelength', 'DeterminingWavelength.html', 'Area Detector Calibration with Multiple Distances: Determine Wavelength', 'To get an accurate wavelength, without knowing the sample-to-detector distance accurately, images recorded with\n several different distances can be used. This exercise shows how to determine the wavelength from such a series. \n This exercise is the prerequisite for the next one.'], ['CalibrationTutorial', 'CalibrationTutorial.html', ' Area Detector Calibration with Multiple Distances: Calibrate Detector Distances', 'To get an accurate wavelength, without knowing the sample-to-detector distance accurately, images recorded with\n several different distances can be used. After using the previous exercise to determine the wavelength,\n this exercise calibrates the detector distances and shows examples of how to mask, integrate, and save those parameters\n for future reuse.'], ['Small-Angle Scattering'], ['SAsize', 'Small Angle Size Distribution.htm', 'Small angle x-ray data size distribution (alumina powder)', 'This shows how to determine the size distribution of particles using data from a constant \n wavelength synchrotron X-ray USAXS instrument. This is the prerequisite for the next tutorial'], ['SAfit', 'Fitting Small Angle Scattering Data.htm', ' Fitting small angle x-ray data (alumina powder)', 'This shows how to fit small angle scattering data using data from a constant wavelength synchrotron X-ray USAXS instrument. '], ['SAimages', 'Small Angle Image Processing.htm', 'Image Processing of small angle x-ray data', 'This shows how to reduce 2D SAXS data to create 1D absolute scaled data. '], ['SAseqref', 'Sequential Refinement of Small Angle Scattering Data.htm', 'Sequential refinement with small angle scattering data', 'This shows how to fit USAXS small angle scattering data for a suite of samples to demonstrate the \n sequential refinement technique in GSAS-II for SASD and demonstrates fitting with a hard sphere structure \n factor for non-dilute systems. '], ['Other'], ['MerohedralTwins', 'Merohedral twin refinement in GSAS.htm', 'Merohedral twin refinements', 'This shows how to use GSAS-II to refine the structure of a few single crystal structures where there is merohedral twinning. '], ['TOF Single Crystal Refinement', 'TOF single crystal refinement in GSAS.htm', 'Single crystal refinement from TOF data', 'This shows how to refine the structure of sapphire (really corundum, Al2O3) from single crystal diffraction data \n collected at the SNS on the TOPAZ instrument at room temperature. '], ['PythonScript', 'Scripting.htm', 'Scripting a GSAS-II Refinement from Python', 'This demonstrates the use of the GSASIIscriptable module. This uses a Python script to perform a refinement or \n computation, but without use of the GSAS-II graphical user interface. This is a prerequisite for the next tutorial.'], ['PythonScript', 'CommandLine.htm', ' Running a GSAS-II Refinement from the Command Line', 'This shows a unix script that duplicates the previous Python Scripting GSAS-II tutorial. '])

A catalog of GSAS-II tutorials with headings. This is the master list of GSAS-II tutorials and must be updated when tutorials are added. Each item has either one or three items. Titles are single item in a list or tuple. Tutorials have four items: (a) the name of the directory, (b) the name of the web page, (c) a title for the tutorial and (d) a short text description (optional). Tutorials that depend on a previous tutorial being completed should have the title for the tutorial indented by five spaces.

Note that tutorialCatalog is generated from this tuple. Also see makeTutorial which is used to read this and create a web page.

GSASIIctrlGUI.updateNoticeDict = {4919: True}

A dict with versions that should be noted. The value associated with the tag is if all older projects should show the warning, or only the first to be opened. Version info is found in file versioninfo.txt.

GSASIIctrlGUI.updateNotifier(G2frame, fileVersion)[source]

Posts an update notice when a a specially tagged GSAS-II version is seen for the first time. Versions to be tagged are set in global updateNoticeDict; version info is found in file versioninfo.txt.

Parameters:
  • G2frame (wx.Frame) – GSAS-II main window
  • fileVersion (int) – version of GSAS-II used to create the current .gpx file

5.2. GSASIIIO: Misc I/O routines

Module with miscellaneous routines for input and output. Many are GUI routines to interact with user.

Includes support for image reading.

Also includes base class for data export routines (TODO: should move)

TODO: This module needs some work to separate wx from non-wx routines. GUI routines should probably move to GSASIIctrlGUI.

class GSASIIIO.ExportBaseclass(G2frame, formatName, extension, longFormatName=None)[source]

Defines a base class for the exporting of GSAS-II results.

This class is subclassed in the various exports/G2export_*.py files. Those files are imported in GSASIIdataGUI.GSASII._init_Exports() which defines the appropriate menu items for each one and the .Exporter method is called directly from the menu item.

Routines may also define a .Writer method, which is used to write a single file without invoking any GUI objects.

CloseFile(fp=None)[source]

Close a file opened in OpenFile

Parameters:fp (file) – the file object to be closed. If None (default) file object self.fp is closed.
ExportSelect(AskFile='ask')[source]

Selects histograms or phases when needed. Sets a default file name when requested into self.filename; always sets a default directory in self.dirname.

Parameters:AskFile (bool) –

Determines how this routine processes getting a location to store the current export(s).

  • if AskFile is ‘ask’ (default option), get the name of the file to be written; self.filename and self.dirname are always set. In the case where multiple files must be generated, the export routine should do this based on self.filename as a template.
  • if AskFile is ‘dir’, get the name of the directory to be used; self.filename is not used, but self.dirname is always set. The export routine will always generate the file name.
  • if AskFile is ‘single’, get only the name of the directory to be used when multiple items will be written (as multiple files) are used or a complete file name is requested when a single file name is selected. self.dirname is always set and self.filename used only when a single file is selected.
  • if AskFile is ‘default’, creates a name of the file to be used from the name of the project (.gpx) file. If the project has not been saved, then the name of file is requested. self.filename and self.dirname are always set. In the case where multiple file names must be generated, the export routine should do this based on self.filename.
  • if AskFile is ‘default-dir’, sets self.dirname from the project (.gpx) file. If the project has not been saved, then a directory is requested. self.filename is not used.
Returns:True in case of an error
GetAtoms(phasenam)[source]

Gets the atoms associated with a phase. Can be used with standard or macromolecular phases

Parameters:phasenam (str) – the name for the selected phase
Returns:a list of items for eac atom where each item is a list containing: label, typ, mult, xyz, and td, where
  • label and typ are the atom label and the scattering factor type (str)
  • mult is the site multiplicity (int)
  • xyz is contains a list with four pairs of numbers: x, y, z and fractional occupancy and their standard uncertainty (or a negative value)
  • td is contains a list with either one or six pairs of numbers: if one number it is Uiso and with six numbers it is U11, U22, U33, U12, U13 & U23 paired with their standard uncertainty (or a negative value)
GetCell(phasenam)[source]

Gets the unit cell parameters and their s.u.’s for a selected phase

Parameters:phasenam (str) – the name for the selected phase
Returns:cellList,cellSig where each is a 7 element list corresponding to a, b, c, alpha, beta, gamma, volume where cellList has the cell values and cellSig has their uncertainties.
GetSeqCell(phasenam, data_name)[source]

Gets the unit cell parameters and their s.u.’s for a selected phase and histogram in a sequential fit

Parameters:
  • phasenam (str) – the name for the selected phase
  • data_name (dict) – the sequential refinement parameters for the selected histogram
Returns:

cellList,cellSig where each is a 7 element list corresponding to a, b, c, alpha, beta, gamma, volume where cellList has the cell values and cellSig has their uncertainties.

InitExport(event)[source]

Determines the type of menu that called the Exporter and misc initialization.

MakePWDRfilename(hist)[source]

Make a filename root (no extension) from a PWDR histogram name

Parameters:hist (str) – the histogram name in data tree (starts with “PWDR “)
OpenFile(fil=None, mode='w')[source]

Open the output file

Parameters:fil (str) – The name of the file to open. If None (default) the name defaults to self.dirname + self.filename. If an extension is supplied, it is not overridded, but if not, the default extension is used.
Returns:the file object opened by the routine which is also saved as self.fp
SetSeqRef(data, hist)[source]

Set the exporter to retrieve results from a sequential refinement rather than the main tree

Write(line)[source]

write a line of output, attaching a line-end character

Parameters:line (str) – the text to be written.
askSaveDirectory()[source]

Ask the user to supply a directory name. Path name is used as the starting point for the next export path search.

Returns:a directory name (str) or None if Cancel is pressed

TODO: Can this be replaced with G2G.askSaveDirectory?

askSaveFile()[source]

Ask the user to supply a file name

Returns:a file name (str) or None if Cancel is pressed
dumpTree(mode='type')[source]

Print out information on the data tree dicts loaded in loadTree. Used for testing only.

loadParmDict()[source]

Load the GSAS-II refinable parameters from the tree into a dict (self.parmDict). Update refined values to those from the last cycle and set the uncertainties for the refined parameters in another dict (self.sigDict).

Expands the parm & sig dicts to include values derived from constraints.

This could be made faster for sequential fits by reducing the histogram list to only the active histogram being exported.

loadTree()[source]

Load the contents of the data tree into a set of dicts (self.OverallParms, self.Phases and self.Histogram as well as self.powderDict & self.xtalDict)

  • The childrenless data tree items are overall parameters/controls for the entire project and are placed in self.OverallParms
  • Phase items are placed in self.Phases
  • Data items are placed in self.Histogram. The key for these data items begin with a keyword, such as PWDR, IMG, HKLF,… that identifies the data type.
GSASIIIO.ExportPowder(G2frame, TreeName, fileroot, extension, hint='')[source]

Writes a single powder histogram using the Export routines. This is used in GSASIIimgGUI.AutoIntFrame() only.

Parameters:
  • G2frame (wx.Frame) – the GSAS-II main data tree window
  • TreeName (str) – the name of the histogram (PWDR …) in the data tree
  • fileroot (str) – name for file to be written, extension ignored
  • extension (str) – extension for file to be written (start with ‘.’). Must match a powder export routine that has a Writer object.
  • hint (str) – a string that must match the export’s format
GSASIIIO.ExportPowderList(G2frame)[source]

Returns a list of extensions supported by GSASIIIO:ExportPowder() along with their descriptions (note that a extension may be repeated but descriptions are unique). This is used in GSASIIimgGUI.AutoIntFrame() only.

Parameters:G2frame (wx.Frame) – the GSAS-II main data tree window
GSASIIIO.ExportSequential(G2frame, data, obj, exporttype)[source]

Used to export from every phase/dataset in a sequential refinement using a .Writer method for either projects or phases. Prompts to select histograms and for phase exports, which phase(s).

Parameters:
  • G2frame (wx.Frame) – the GSAS-II main data tree window
  • data (dict) – the sequential refinement data object
  • exporttype (str) – indicates the type of export (‘project’ or ‘phase’)
GSASIIIO.ExtractFileFromZip(filename, selection=None, confirmread=True, confirmoverwrite=True, parent=None, multipleselect=False)[source]

If the filename is a zip file, extract a file from that archive.

Parameters:
  • Selection (list) – used to predefine the name of the file to be extracted. Filename case and zip directory name are ignored in selection; the first matching file is used.
  • confirmread (bool) – if True asks the user to confirm before expanding the only file in a zip
  • confirmoverwrite (bool) – if True asks the user to confirm before overwriting if the extracted file already exists
  • multipleselect (bool) – if True allows more than one zip file to be extracted, a list of file(s) is returned. If only one file is present, do not ask which one, otherwise offer a list of choices (unless selection is used).
Returns:

the name of the file that has been created or a list of files (see multipleselect)

If the file is not a zipfile, return the name of the input file. If the zipfile is empty or no file has been selected, return None

GSASIIIO.FileDlgFixExt(dlg, file)[source]

this is needed to fix a problem in linux wx.FileDialog

GSASIIIO.GetCheckImageFile(G2frame, treeId)[source]

Try to locate an image file if the project and image have been moved together. If the image file cannot be found, request the location from the user.

Parameters:
  • G2frame (wx.Frame) – main GSAS-II Frame and data object
  • treeId (wx.Id) – Id for the main tree item for the image
Returns:

Npix,imagefile,imagetag with (Npix) number of pixels, imagefile, if it exists, or the name of a file that does exist or False if the user presses Cancel and (imagetag) an optional image number

GSASIIIO.GetImageData(G2frame, imagefile, imageOnly=False, ImageTag=None, FormatName='')[source]

Read a single image with an image importer. This is called to reread an image after it has already been imported with GSASIIdataGUI.GSASII.OnImportGeneric() (or ReadImages() in Auto Integration) so it is not necessary to reload metadata.

Parameters:
  • G2frame (wx.Frame) – main GSAS-II Frame and data object.
  • imagefile (str) – name of image file
  • imageOnly (bool) – If True return only the image, otherwise (default) return more (see below)
  • ImageTag (int/str) – specifies a particular image to be read from a file. First image is read if None (default).
  • formatName (str) – the image reader formatName
Returns:

an image as a numpy array or a list of four items: Comments, Data, Npix and the Image, as selected by imageOnly

GSASIIIO.GetPowderPeaks(fileName)[source]

Read powder peaks from a file

GSASIIIO.IndexPeakListSave(G2frame, peaks)[source]

Save powder peaks from the indexing list

GSASIIIO.LoadImage2Tree(imagefile, G2frame, Comments, Data, Npix, Image)[source]

Load an image into the tree. Saves the location of the image, as well as the ImageTag (where there is more than one image in the file), if defined.

GSASIIIO.PeakListSave(G2frame, file, peaks)[source]

Save powder peaks to a data file

GSASIIIO.ProjFileOpen(G2frame, showProvenance=True)[source]

Read a GSAS-II project file and load into the G2 data tree

GSASIIIO.ProjFileSave(G2frame)[source]

Save a GSAS-II project file

GSASIIIO.PutG2Image(filename, Comments, Data, Npix, image)[source]

Write an image as a python pickle - might be better as an .edf file?

GSASIIIO.ReadImages(G2frame, imagefile)[source]

Read one or more images from a file and put them into the Tree using image importers. Called only in AutoIntFrame.OnTimerLoop().

ToDo: Images are most commonly read in GSASIIdataGUI.GSASII.OnImportGeneric() which is called from GSASIIdataGUI.GSASII.OnImportImage() it would be good if these routines used a common code core so that changes need to be made in only one place.

Parameters:
  • G2frame (wx.Frame) – main GSAS-II Frame and data object.
  • imagefile (str) – name of image file
Returns:

a list of the id’s of the IMG tree items created

GSASIIIO.SaveIntegration(G2frame, PickId, data, Overwrite=False)[source]

Save image integration results as powder pattern(s)

GSASIIIO.XYsave(G2frame, XY, labelX='X', labelY='Y', names=[])[source]

Save XY table data

GSASIIIO.objectScan(data, tag, indexStack=[])[source]

Recursively scan an object looking for unexpected data types. This is used in debug mode to scan .gpx files for objects we did not intend to be there.

GSASIIIO.postURL(URL, postdict)[source]

Posts a set of values as from a web form. If access fails to an https site the access is retried with http.

Parameters:
  • URL (str) – the URL to post; typically something like ‘http://www…/dir/page?’
  • postdict (dict) – contains keywords and values, such as {‘centrosymmetry’: ‘0’, ‘crystalsystem’: ‘0’, …}
Returns:

a string with the response from the web server or None if access fails.

GSASIIIO.sfloat(S)[source]

Convert a string to float. An empty field or a unconvertable value is treated as zero

GSASIIIO.sint(S)[source]

Convert a string to int. An empty field is treated as zero

GSASIIIO.striphist(var, insChar='')[source]

strip a histogram number from a var name

GSASIIIO.trim(val)[source]

Simplify a string containing leading and trailing spaces as well as newlines, tabs, repeated spaces etc. into a shorter and more simple string, by replacing all ranges of whitespace characters with a single space.

Parameters:val (str) – the string to be simplified
Returns:the (usually) shortened version of the string

5.3. GSASIIpy3: Python 3.x Routines

Module to hold python 3-compatible code, to keep it separate from code that will break with __future__ options.

GSASIIpy3.FormatPadValue(val, maxdigits=None)[source]

Format a float to fit in maxdigits[0] spaces with maxdigits[1] after decimal.

Parameters:
  • val (float) – number to be formatted.
  • maxdigits (list) – the number of digits & places after decimal to be used for display of the number (defaults to [10,2]).
Returns:

a string with exactly maxdigits[0] characters (except under error conditions), but last character will always be a space

GSASIIpy3.FormatSigFigs(val, maxdigits=10, sigfigs=5, treatAsZero=1e-20)[source]

Format a float to use maxdigits or fewer digits with sigfigs significant digits showing (if room allows).

Parameters:
  • val (float) – number to be formatted.
  • maxdigits (int) – the number of digits to be used for display of the number (defaults to 10).
  • sigfigs (int) – the number of significant figures to use, if room allows
  • treatAsZero (float) – numbers that are less than this in magnitude are treated as zero. Defaults to 1.0e-20, but this can be disabled if set to None.
Returns:

a string with <= maxdigits characters (I hope).

GSASIIpy3.FormatValue(val, maxdigits=None)[source]

Format a float to fit in at most maxdigits[0] spaces with maxdigits[1] after decimal. Note that this code has been hacked from FormatSigFigs and may have unused sections.

Parameters:
  • val (float) – number to be formatted.
  • maxdigits (list) – the number of digits, places after decimal and ‘f’ or ‘g’ to be used for display of the number (defaults to [10,2,’f’]).
Returns:

a string with <= maxdigits characters (usually).

GSASIIpy3.FormulaEval(string)[source]

Evaluates a algebraic formula into a float, if possible. Works properly on fractions e.g. 2/3 only with python 3.0+ division.

Expressions such as 2/3, 3*pi, sin(45)/2, 2*sqrt(2), 2**10 can all be evaluated.

Parameters:string (str) – Character string containing a Python expression to be evaluated.
Returns:the value for the expression as a float or None if the expression does not evaluate to a valid number.

5.4. gltext: draw OpenGL text

Routines that render text on OpenGL without use of GLUT.

Code written by Christian Brugger & Stefan Hacker and distributed under GNU General Public License.

class gltext.Text(text='Text', font=None, font_size=8, foreground=<sphinx.ext.autodoc.importer._MockObject object>, centered=False)[source]

A simple class for using System Fonts to display text in an OpenGL scene. The Text adds a global Cache of already created text elements to TextElement’s base functionality so you can save some memory and increase speed

centered

Display the text centered

draw_text(position=<sphinx.ext.autodoc.importer._MockObject object>, scale=1.0, rotation=0)[source]

position (wx.RealPoint) - x/y Position to draw in scene scale (float) - Scale rotation (int) - Rotation in degree

Draws the text to the scene

font

Font of the object

font_size

Font size

foreground

Color/Overlay bitmap of the text

getTextElement()[source]

Returns the text element bound to the Text class

getTexture()[source]

Returns the texture of the bound TextElement

getTexture_size()[source]

Returns a texture size tuple

setCentered(value, reinit=True)[source]

value (bool) - New centered value reinit (bool) - Create a new texture

Sets a new value for ‘centered’

setFont(value, reinit=True)[source]

value (bool) - New Font reinit (bool) - Create a new texture

Sets a new font

setFont_size(value, reinit=True)[source]

value (bool) - New font size reinit (bool) - Create a new texture

Sets a new font size

setForeground(value, reinit=True)[source]

value (bool) - New centered value reinit (bool) - Create a new texture

Sets a new value for ‘centered’

setText(value, reinit=True)[source]

value (bool) - New Text reinit (bool) - Create a new texture

Sets a new text

text

Text of the object

text_element

TextElement bound to this class

texture

Texture of bound TextElement

texture_size

Size of the used texture

class gltext.TextElement(text='', font=None, foreground=<sphinx.ext.autodoc.importer._MockObject object>, centered=False)[source]

A simple class for using system Fonts to display text in an OpenGL scene

bind()[source]

Increase refcount

centered

Is text centered

createTexture()[source]

Creates a texture from the settings saved in TextElement, to be able to use normal system fonts conviently a wx.MemoryDC is used to draw on a wx.Bitmap. As wxwidgets device contexts don’t support alpha at all it is necessary to apply a little hack to preserve antialiasing without sticking to a fixed background color:

We draw the bmp in b/w mode so we can use its data as a alpha channel for a solid color bitmap which after GL_ALPHA_TEST and GL_BLEND will show a nicely antialiased text on any surface.

To access the raw pixel data the bmp gets converted to a wx.Image. Now we just have to merge our foreground color with the alpha data we just created and push it all into a OpenGL texture and we are DONE inhalesdelpy

DRAWBACK of the whole conversion thing is a really long time for creating the texture. If you see any optimizations that could save time PLEASE CREATE A PATCH!!!

deleteTexture()[source]

Deletes the OpenGL texture object

draw_text(position=<sphinx.ext.autodoc.importer._MockObject object>, scale=1.0, rotation=0)[source]

position (wx.RealPoint) - x/y Position to draw in scene scale (float) - Scale rotation (int) - Rotation in degree

Draws the text to the scene

font

Font of the object

foreground

Color of the text

isBound()[source]

Return refcount

owner_cnt

Owner count

release()[source]

Decrease refcount

text

Text of the object

texture

Used texture

texture_size

Size of the used texture