\(\renewcommand\AA{\text{Å}}\)

5. GSAS-II GUI Support Modules

The modules documented here provide GUI or graphics capabilities that are used in multiple sections of the GSAS-II GUI or graphics.

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

G2CheckBoxFrontLbl()

A version of G2CheckBox that places the label for the check box in front. Otherwise works the same.

G2RadioButtons()

Creates a series of grouped radio buttons.

G2SliderWidget

A customized combination of a wx.Slider and a validated wx.TextCtrl (see ValidatedTxtCtrl).

G2Slider

A wrapped version of wx.Slider that implements scaling

G2SpinWidget

A customized combination of a wx.SpinButton 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

G2ScrolledGrid()

Displays a multicolumn table of information with possible scroll bars

ShowScrolledColText()

Displays tabular text with scrolling where 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)

gpxFileSelector

File browser dialog for opening existing .gpx files

ScrolledStaticText

A wx.StaticText widget that fits a large string into a small space by scrolling it

ReadOnlyTextCtrl()

A wx.TextCtrl widget to be used wx.StaticText (no edits allowed) text appears in a box.

setColorButton()

A button for color selection as a replacement for wx.ColourSelect

openInNewTerm()

opens a Python routine (usually GSASII.py) in a new terminal window (works on all platforms)

Other miscellaneous non-GUI routines that may be of use for GUI-related actions:

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

5.1.1. GSASIIctrlGUI Classes & Routines

Documentation for all the routines in module GSASIIctrlGUI follows.

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.

GSASIIctrlGUI.G2CheckBoxFrontLbl(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. Same as G2CheckBox except the label is placed before the CheckBox and returns a sizer rather than the G2CheckBox.

If the CheckBox is needed, reference Sizer.myCheckBox.

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

HistoryBack() bool[source]

Moves back to the previous page.

LoadPage(location) bool[source]

Unlike SetPage() this function first loads the HTML page from location and then displays it.

OnLinkClicked(link)[source]

Called when user clicks on hypertext link.

class GSASIIctrlGUI.G2LoggedButton(parent, id=-1, 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(parent, ID=-1, pos=wx.Point(-1, -1), size=wx.Size(-1, -1), style=0)[source]

Creates a custom ListCtrl with support for images in column labels

GetSortImages()[source]

Returns a tuple of image list indexesthe indexes in the image list for an image to be put on the column header when sorting in descending order.

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

Simple code to display a error or warning message

TODO: replace wx.MessageDialog with one derived from wx.Dialog because on most platforms wx.MessageDialog is a native widget and CentreOnParent will not function.

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

GSASIIctrlGUI.G2RadioButtons(parent, loc, key, choices, values=None, OnChange=None)[source]

A customized version of wx.RadioButton that returns a list of coupled RadioButtons

Parameters:
  • parent (wx.Panel) – name of panel or frame that will be the parent to the widgets. Can be None.

  • 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 CheckButton will be initialized from this value.

  • choices (list)

  • values (list)

  • 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.G2RefinementProgress(title='Refinement progress', message='All data Rw =', maximum=101, parent=None, trialMode=False, seqLen=0, seqShow=3, style=None)[source]

Defines an replacement for wx.ProgressDialog to be used for showing refinement progress.

Parameters:
  • title (str) – string to place on border of window (default is ‘Refinement progress’).

  • message (str) – initial string to place on top line of window.

  • maximum (int) – maximum value for progress gauge bar on bottom of window.

  • parent (wx.Frame) – parent window for creation of this dialog

  • trialMode (bool) – Set to True for Levenberg-Marquardt fitting where Rw may be computed several times for a single cycle. Call AdvanceCycle() when trialMode is True to indicate that a cycle has been completed. Default is False.

  • seqLen (int) – Number of histograms in sequential fit. A value of zero (default) means that the fit is not a sequential fit.

  • seqShow (int) – Number of histograms to shown in a sequential fit (default 3)

  • style (int) – optional parameters that determine how the dialog is is displayed.

AdvanceCycle(cycle=None)[source]

Call this directly with Levenberg-Marquardt fitting after a cycle completes. Plots the results.

Destroy()[source]

Destroy the window, but allow events to clear before doing so

SetHistogram(nextHist, histLbl)[source]

Set this before beginning processing of each histogram

SetMaxCycle(value)[source]

Set the maximum number of cycles or histograms (sequential fit). Used to scale settings so the gauge bar completes close to 100%. Ignored for sequential refinements.

Update(value=None, newmsg='')[source]

designed to work with calls intended for wx.ProgressDialog.Update the value is assumed to be the current wR value for the histogram selected with SetHistogram and newmsg goes into the 2nd status line.

GSASIIctrlGUI.G2ScrolledGrid(G2frame, lbl, title, tbl, colLbls, colTypes, maxSize=(600, 300), comment='')[source]

Display a scrolled table of information in a dialog window

Parameters:
  • G2frame (wx.Frame) – parent for dialog

  • lbl (str) – label for window

  • title (str) – window title

  • tbl (list) – list of lists where inner list is each row

  • colLbls (list) – list of str with labels for each column

  • colTypes (list) – Data types for each column (such as wg.GRID_VALUE_STRING,wg.GRID_VALUE_FLOAT)

  • maxSize (list) – Maximum size for the table in points. Defaults to (600,300) :param str comment: optional text that appears below table

Example:

row = ['item1',1.234,'description of item']
colTypes = [wg.GRID_VALUE_STRING,wg.GRID_VALUE_FLOAT+':8,4',wg.GRID_VALUE_STRING]
colLbls = ['item name','value','Description']
G2ScrolledGrid(frm,'window label','title',20*[row],colLbls,colTypes)
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

class GSASIIctrlGUI.G2Slider(parent, id=-1, value=0, minValue=0, maxValue=100, *arg, **kwarg)[source]

Wrapper around wx.Slider widget that implements scaling Also casts floats as integers to avoid py3.10+ errors

SetMax(maxValue)[source]

Sets the maximum slider value.

SetMin(minValue)[source]

Sets the minimum slider value.

SetValue(value)[source]

Sets the slider position.

GSASIIctrlGUI.G2SliderWidget(parent, loc, key, label, xmin, xmax, iscale, onChange=None, onChangeArgs=[], sizer=None, nDig=None, size=(50, 20))[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. However, if iscale=2 then the values 1, 1.5, 2, 2.5, 3, 3.5 and 4 are all allowed.

  • 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

GSASIIctrlGUI.G2SpinWidget(parent, loc, key, label, xmin=None, xmax=None, onChange=None, onChangeArgs=[], hsize=35)[source]

A customized combination of a wx.SpinButton and a validated wx.TextCtrl (see ValidatedTxtCtrl) that allows either a the spin button 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 or int value. It will be forced to an integer initial value between xmin and xmax.

  • label (str) – A label to be placed to the left of the entry widget.

  • xmin (int) – the minimum allowed valid value. If None it is ignored.

  • xmax (int) – the maximum allowed valid value. If None it is ignored.

  • 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.

  • hsize (int) – length of TextCtrl in pixels. Defaults to 35.

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

GetItemPyData(treeId)[source]

GetItemData(item) -> TreeItemData

Returns the tree item data associated with the item.

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.

SetItemPyData(treeId, data)[source]

SetItemData(item, data)

Sets the item client data.

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=257)[source]

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

ChangeSelection(n) int[source]

Changes the selection for the given page, returning the previous selection.

FindPage(page) int[source]

Returns the index of the specified tab window or wxNOT_FOUND if not found.

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=1, 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

BeginEdit(row, col, grid)[source]

Fetch the value from the table and prepare the edit control to begin editing.

Clone() GridCellEditor[source]

Create a new object which is the copy of this one.

Create(parent, id, evtHandler)[source]

Creates the actual edit control.

EndEdit(row, col, grid, oldval)[source]

End editing the cell.

This function must check if the current value of the editing cell is valid and different from the original value in its string form. If not then simply return None. If it has changed then this method should save the new value so that ApplyEdit can apply it later and the string representation of the new value should be returned.

Notice that this method shoiuld not modify the grid as the change could still be vetoed.

Reset()[source]

Reset the value in the control back to its starting value.

SetSize(rect)[source]

Size and position the edit control.

StartingKey(event)[source]

If the editor is enabled by pressing keys on the grid, this will be called to let the editor do something about that first key if desired.

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.

GSASIIctrlGUI.Load2Cells(G2frame, phase)[source]

Accept two unit cells and use NIST*LATTICE to search for a relationship that relates them.

The first unit cell is initialized as the currently selected phase and the second unit cell is set to the first different phase from the tree. The user can initialize the cell parameters to select a different phase for either cell or can type in the values themselves.

Parameters:
  • G2frame (wx.Frame) – The main GSAS-II window

  • phase (dict) – the currently selected frame

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'], header=None)[source]

Dialog to obtain multiple values from user

Parameters:
  • parent (wx.Frame) – parent frame for dialog to be created

  • title (str) – title to place on top of window

  • prompts (list) – a string to describe each item

  • values (list) – a set of initial values for each item

  • limits (list) – A nested list with an upper and lower value for each item

  • format (list) – an “old-style” format string used to display each item value

  • header (str) – a string to be placed at the top of the window, if specified

example:

dlg = G2G.MultiDataDialog(G2frame,title='ISOCIF search',
        prompts=['lattice constants tolerance',
                 'coordinate tolerance',
                 'occupancy tolerance'],
        values=[0.001,0.01,0.1],
        limits=3*[[0.,2.]],formats=3*['%.5g'],
        header=isoCite)
dlg.ShowModal()
latTol,coordTol,occTol = dlg.GetValues()
dlg.Destroy()
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.OpenGitTutorial(parent)[source]

Open a tutorial web page from the git repository, optionally copying the tutorial’s exercise data file(s) to the local disk.

ChooseTutorial2(choices)[source]

Select tutorials from a two-column table, when possible

SelectAndDownload(event)[source]

Shows a list of all tutorials so user can select one to view. The data files associated with that directory are then downloaded.

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

onWebBrowse(event)[source]

Shows a list of all tutorials so user can select one to view.

Returns:

the name of the directory where the tutorial is located, which is used if called from SelectAndDownload().

class GSASIIctrlGUI.OpenSvnTutorial(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

GSASIIctrlGUI.ReadOnlyTextCtrl(*args, **kwargs)[source]

Create a read-only TextCtrl for display of constants This is probably not ideal as it mixes visual cues, but it does look nice. Addresses 4.2 bug where TextCtrl has no default size

class GSASIIctrlGUI.RefinementProgress(title='Residual', message='All data Rw =', maximum=101, parent=None, trialMode=False, seqLen=0, style=None)[source]

Defines a wrapper to place around wx.ProgressDialog to be used for showing refinement progress. At some point a better progress window should be created that keeps useful info on the screen such as some starting and current fit metrics, but for now all this adds is window defaults and a wx.Yield call during progress update calls.

Update(value, newmsg=EmptyString)[source]

Updates the dialog, setting the progress bar to the new value and updating the message if new one is specified.

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.ScrolledStaticText(parent, label='', delay=100, lbllen=15, dots=True, **kwargs)[source]

Fits a long string into a small space by scrolling it. Inspired by ActiveText.py from J Healey <rolfofsaxony@gmx.com> https://discuss.wxpython.org/t/activetext-rather-than-statictext/36370

Use examples:

frm = wx.Frame(None) # create a frame
ms = wx.BoxSizer(wx.VERTICAL)
text = 'this is a long string that will be scrolled'
ms.Add(G2G.ScrolledStaticText(frm,label=text))
txt = G2G.ScrolledStaticText(frm,label=text, lbllen=20)
smallfont = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT)
smallfont.SetPointSize(10)
txt.SetFont(smallfont)
ms.Add(txt)
ms.Add(G2G.ScrolledStaticText(frm,label=text,dots=False,delay=250,lbllen=20))
frm.SetSizer(ms)
Parameters:
  • parent (w.Frame) – Frame or Panel where widget will be placed

  • label (str) – string to be displayed

  • delay (int) – time between updates in ms (default is 100)

  • lbllen (int) – number of characters to show (default is 15)

  • dots (bool) – If True (default) ellipsis (…) are placed at the beginning and end of the string when any characters in the string are not shown. The displayed string length will thus be lbllen+6 most of the time

  • (other) – other optional keyword parameters for the wx.StaticText widget such as size or style may be specified.

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.ShowScrolledColText(parent, txt, width=600, height=400, header='Warning info', col1len=999)[source]

Simple code to display tabular information in a scrolled wx.Dialog window.

Lines ending with a colon (:) are centered across all columns and have a grey background. Lines beginning and ending with ‘**’ are also are centered across all columns and are given a yellow background All other lines have columns split by tab (t) characters.

Parameters:
  • parent (wx.Frame) – parent window

  • 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) – title to be placed on window

GSASIIctrlGUI.ShowScrolledInfo(parent, txt, width=600, height=400, header='Warning info', buttonlist=None)[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) – title to be placed on window

  • buttonlist (list) – list of button Ids to show. The default is None which places a single “Close” button and returns wx.ID_CANCEL

Returns:

the wx Id for the selected button

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

AppendRows(numRows=1) bool[source]

Append additional rows at the end of the table.

CanGetValueAs(row, col, typeName) bool[source]

Returns true if the value of the given cell can be accessed as if it were of the specified type.

CanSetValueAs(row, col, typeName) bool[source]

Returns true if the value of the given cell can be set as if it were of the specified type.

GetColLabelValue(col) String[source]

Return the label of the specified column.

GetNumberCols() int[source]

Must be overridden to return the number of columns in the table.

GetNumberRows() int[source]

Must be overridden to return the number of rows in the table.

GetRowLabelValue(row) String[source]

Return the label of the specified row.

GetTypeName(row, col) String[source]

Returns the type of the value in the given cell.

GetValue(row, col) PyObject[source]

Must be overridden to implement accessing the table values as text.

InsertRows(pos=0, numRows=1) bool[source]

Insert additional rows into the table.

IsEmptyCell(row, col) bool[source]

May be overridden to implement testing for empty cells.

SetColLabelValue(col, label)[source]

Exactly the same as SetRowLabelValue() but for columns.

SetRowLabelValue(row, label)[source]

Set the given label for the specified row.

SetValue(row, col, value)[source]

Must be overridden to implement setting the table values as text.

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

SetValue(value)[source]

Sets the new text control value.

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]
OnGetItemAttr(item) ItemAttr[source]

This function may be overridden in the derived class for a control with wxLC_VIRTUAL style.

OnGetItemText(item, column) String[source]

This function must be overridden in the derived class for a control with wxLC_VIRTUAL style.

OnRowSelected(event, row=None)[source]

Creates an edit window when a parameter is selected

GSASIIctrlGUI.XformMatrix(panel, Trans, Uvec, Vvec, OnLeave=None, OnLeaveArgs={})[source]

Display a transformation matrix and two vectors

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; used for svn

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 svn version

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.gitCheckUpdates(G2frame)[source]

Used to update to the latest GSAS-II version, but checks for a variety of repository conditions that could make this process more complex. If there are uncommitted local changes, these changes must be cached or deleted first. If there are local changes that have been committed or a new branch has been created, the user (how obstensibly must know use of git) will probably need to do this manually. If GSAS-II has previously been regressed (using gitSelectVersion()), then this is noted as well.

When all is done, function GSASIIpath.gitStartUpdate() is called to actually perform the update.

GSASIIctrlGUI.gitSelectVersion(G2frame)[source]

Used to regress to a previous GSAS-II version, checking first for a variety of repository conditions that could make this process more complex. If there are uncommitted local changes, these changes must be cached or deleted before a different version can be installed. If there are local changes that have been committed or a new branch has been created, the user (how obstensibly must know use of git) will probably need to do this manually. If GSAS-II has previously been regressed (using gitSelectVersion()), then this is noted as well.

When all is done, function GSASIIpath.gitStartUpdate() is called to actually perform the update.

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

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

docCommit(commit)[source]

Provides a string with information about a specific git commit.

Returns:

a multi-line string

getVersion()[source]

Gets the selected version that should be installed

Returns:

returns one of three values:

  • 0: if the newest version is selected, so that the installation should be updated rather than regressed

  • None: if the currently installed version is selected, so that nothing need be done

  • A hexsha string: the regressed version that should be selected.

class GSASIIctrlGUI.gpxFileSelector(parent, startdir='.', multiple=False, *args, **kwargs)[source]

Create a file selection widget for locating .gpx files as a modal dialog. Displays status information on selected files. After creating this use dlg.ShowModal() to wait for selection of a file. If dlg.ShowModal() returns wx.ID_OK, use dlg.Selection (multiple=False) to obtain the selected file or dlg.Selections (multiple=True) to obtain a list of multiple files.

Parameters:
  • parent (wx.Frame) – name of panel or frame that will be the parent to the dialog. Can be None.

  • startdir (path) – Specifies the initial directory that is opened when the window is initially opened. Default is ‘.’

  • multiple (bool) – if True, checkboxes are used to allow selection of multiple files. Default is False

DirSelected(event=None, *args, **kwargs)[source]

Respond to a directory being selected. List files found in fileBox and clear any selections. Also clear any reference to a timer.

FileSelected(event)[source]

Respond to a file being selected (or checked in multiple mode)

displayGPXrtc(result, fwp)[source]

Show info about selected file in a RichText display

GSASIIctrlGUI.makeContourSliders(G2frame, Ymax, PlotPatterns, newPlot, plottype)[source]

Create a non-modal dialog for sliders to set contour plot intensity thresholds.

GSASIIctrlGUI.openInNewTerm(project=None, g2script=None, pythonapp='/home/docs/checkouts/readthedocs.org/user_builds/gsas-ii/conda/latest/bin/python')[source]

Open a new and independent GSAS-II session in separate terminal or console window and as a separate process that will continue even if the calling process exits. Intended to work on all platforms.

This could be used to run other scripts inside python other than GSAS-II

Parameters:
  • project (str) – the name of an optional parameter to be passed to the script (usually a .gpx file to be opened in a new GSAS-II session)

  • g2script (str) – the script to be run. If None (default) the GSASII.py file in the same directory as this file will be used.

  • pythonapp (str) – the Python interpreter to be used. Defaults to sys.executable which is usually what is wanted.

  • terminal (str) – a name for a preferred terminal emulator

GSASIIctrlGUI.setColorButton(parent, array, key, callback=None, callbackArgs=[])[source]

Define a button for setting colors This bypasses the bug in wx4.1.x in ColourSelect

GSASIIctrlGUI.showUniqueCell(frame, cellSizer, row, cell, SGData=None, editAllowed=False, OnCellChange=None)[source]

function to put cell values into a GridBagSizer. First column (#0) is reserved for labels etc. if editAllowed is True, values are placed in a wx.TextCtrl and if needed two rows are used in the table.

GSASIIctrlGUI.skimGPX(fl)[source]

pull out fit information from a .gpx file quickly

Returns:

dict with status info

GSASIIctrlGUI.svnCheckUpdates(G2frame)[source]

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

GSASIIctrlGUI.svnSelectVersion(G2frame)[source]

Allow the user to select a specific version of GSAS-II from the APS svn server

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.

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)

5.2.1. GSASIIIO Classes & Routines

Misc routines for input and output, including image reading follow.

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, unique=False)[source]

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

Parameters:
  • phasenam (str) – the name for the selected phase

  • unique (bool) – when True, only directly refined parameters (a in cubic, a & alpha in rhombohedral cells) are assigned positive s.u. values. Used as True for CIF generation.

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', delayOpen=False)[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.

  • mode (str) – The mode can ‘w’ to write a file, or ‘a’ to append to it. If the mode is ‘d’ (for debug), output is displayed on the console.

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

  • obj (exporter) – an exporter object

  • exporttype (str) – indicates the type of export (‘project’ or ‘phase’)

GSASIIIO.ExportSequentialFullCIF(G2frame, seqData, Controls)[source]

Handles access to CIF exporter a bit differently for sequential fits, as this is not accessed via the usual export menus

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, getcookie=None, usecookie=None, timeout=None, retry=2, mode='get')[source]

Posts a set of values as from a web form using the “get” or “post” protocols. 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’, …}

  • getcookie (dict) – dict to save cookies created in call, or None (default) if not needed.

  • usecookie (dict) – dict containing cookies to be used in call, or None (default) if not needed.

  • timeout (int) – specifies a timeout period for the get or post (default is None, which means the timeout period is set by the server). The value when specified is the time in seconds to wait before giving up on the request.

  • retry (int) – the number of times to retry the request, if it times out. This is only used if timeout is specified. The default is 2. Note that if retry is left at the default value (2), The timeout is increased by 25% for the second try.

  • mode (str) – either ‘get’ (default) or ‘post’. Determines how the request will be submitted.

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. 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=wx.Colour(-1, -1, -1, 255), 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

property centered

Display the text centered

draw_text(position=wx.RealPoint(0.0, 0.0), 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

property font

Font of the object

property font_size

Font size

property 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

property text

Text of the object

property text_element

TextElement bound to this class

property texture

Texture of bound TextElement

property texture_size

Size of the used texture

class gltext.TextElement(text='', font=None, foreground=wx.Colour(-1, -1, -1, 255), centered=False)[source]

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

bind()[source]

Increase refcount

property 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=wx.RealPoint(0.0, 0.0), 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

property font

Font of the object

property foreground

Color of the text

isBound()[source]

Return refcount

property owner_cnt

Owner count

release()[source]

Decrease refcount

property text

Text of the object

property texture

Used texture

property texture_size

Size of the used texture