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

6. GSAS-II GUI Components

These modules are used to create different parts of the GSAS-II graphical user interface (GUI).

6.1. GSASIIdataGUI: Main GUI for GSAS-II

Module that defines GUI routines and classes for the main GUI Frame (window) and the main routines that define the GSAS-II tree panel and much of the data editing panel.

6.1.1. GSASIIdataGUI Classes & Routines

Routines for main GUI wx.Frame follow.

GSASIIdataGUI.FindPhaseItem(G2frame)[source]

Finds the Phase item in the tree. If not present it adds one also adding ‘Hist/Phase’ if config var SeparateHistPhaseTreeItem is set as True.

class GSASIIdataGUI.G2DataWindow(parent)[source]

Create the data item window as well as the menu. Note that the same core menu items are used in all menus, but different items may be added depending on what data tree item (and for phases, the phase tab).

Note that while the menus are created here, the binding for the menus is done later in various GSASII*GUI modules, where the functions to be called are defined.

Use of the dataWindow scrolled panel:

dataWindow has a “master” vertical BoxSizer: find it with G2frame.dataWindow.GetSizer() and always use it. A call to dataWindow.SetSizer() should not be needed.

When placing a widget in the sizer that has its own scrolling (e.g. G2G.GSNoteBook, anything else?) that one widget should be placed in the sizer as

G2frame.dataWindow.GetSizer().Add(G2frame.<obj>,1,wx.ALL|wx.EXPAND)

[is wx.ALL superfluous here?] so that it consumes the full size of the panel and so that the NoteBook widget does the scrolling.

For other uses, one will likely place a bunch of widgets and (other [sub-]sizers) into the master sizer. In this case, DO NOT use wx.EXPAND, as this will result in the widget resizing/repositioning as the window resizes. Possible exceptions might be for widgets going into a fixed-size panel that is inside the dataWindow (probably not being done). A call to Sizer.Fit(dataWindow) will do bad things, though a call to SubSizer.Fit(dataWindow.subpanel) could make sense.

Initial GUI draws to dataWindow will go through GSASIIdataGUI.SelectDataTreeItem(), which is called after any changes to data tree selection. SelectDataTreeItem places items in dataWindow or calls that do that. Before it calls those routines, it calls

G2frame.dataWindow.ClearData()

which deletes the contents of the master sizer. After the contents are posted a call is made to

G2frame.dataWindow.SetDataSize()

which repaints the window. For routines [such as GSASIIpwdGUI.UpdatePeakGrid()] that are called repeatedly to update the entire contents of dataWindow themselves, it is important to add calls to

G2frame.dataWindow.ClearData()

and

G2frame.dataWindow.SetDataSize()

at the beginning and end respectively to clear and refresh. This is not needed for GSNoteBook repaints, which seem to be working mostly automatically. If there is a problem, a call like

wx.CallAfter(G2frame.phaseDisplay.SendSizeEvent)

might be needed. There are some calls to G2frame.dataWindow.SendSizeEvent() that may be doing the same thing.

ClearData()[source]

Initializes the contents of the dataWindow panel

OnResize(event)[source]

Used for grids to match ScrolledWindow size

PostfillDataMenu(empty=False)[source]

Add the help menu to the menus associated with data tree items.

PrefillDataMenu(menu, empty=False)[source]

Create the “standard” part of data frame menus & add the dataWindow menu headings This menu duplicates the tree menu, but adds an extra help command for the current data item and a separator.

SetDataSize()[source]

Sizes the contents of the dataWindow panel

class GSASIIdataGUI.GSASII(parent)[source]

Define the main GSAS-II frame and its associated menu items.

Parameters:

parent – reference to parent application

AddSimulatedPowder(ttArr, intArr, HistName, Lam1, Lam2)[source]

Create a PWDR entry for a computed powder pattern

AddToNotebook(text)[source]

Add entry to Notebook tree item

CheckNotebook()[source]

Make sure the data tree has the minimally expected controls.

class CopyDialog(parent, title, text, data)[source]

Creates a dialog for copying control settings between data tree items

DoSequentialProjExport(event)[source]

Export a sequential project

duplicates part of GSASIIseqGUI.DoSequentialExport

EditProxyInfo(event)[source]

Edit the proxy information used by subversion (svn only, not used with git)

EnableRefineCommand()[source]

Check that phases are connected to histograms - if so then Refine is enabled

ErrorDialog(title, message, parent=None, wtype=4)[source]

Display an error message

ExitMain(event)[source]

Called if exit selected or the main window is closed rescord last position of data & plot windows; saved to config.py file NB: not called if console window closed

ExpandAll(event)[source]

Expand all tree items or those of a single type

FillMainMenu(menubar, addhelp=True)[source]

Define contents of the main GSAS-II menu for the (main) data tree window. For the mac, this is also called for the data item windows as well so that the main menu items are data menu as well.

GetFileList(fileType, skip=None)[source]

Get list of file names containing a particular string; can skip one of known GSAS-II id param: fileType str: any string within a file name param: skip int:default=None, a GSAS-II assigned id of a data item to skip in collecting the names returns: list of file names from GSAS-II tree returns: str name of file optionally skipped Appears unused, but potentially useful. Note routine of same name in GSASIIpwdGUI; it does not have the skip option

GetHKLFdatafromTree(HKLFname)[source]

Returns single crystal data from GSASII tree

Parameters:

HKLFname (str) – a single crystal histogram name as obtained from GSASIIstruct.GetHistogramNames()

Returns:

HKLFdata = single crystal data list of reflections

GetHistogramNames(hType)[source]

Returns a list of histogram names found in the GSASII data tree Note routine GSASIIstrIO.GetHistogramNames() also exists to get same info from GPX file.

Parameters:

hType (str) – list of histogram types

Returns:

list of histogram names

GetHistogramNamesID(hType)[source]

Returns a list of histogram names found in the GSASII data tree and a lookup table of their Id values. Should replace GetHistogramNames since that will not be much faster (and there may be real speed gains from caching the Ids rather than keep searching for them).

N.B routine GSASIIstrIO.GetHistogramNames() also exists to get same info, but from GPX file.

Parameters:

hType (str) – list of histogram types

Returns:

list of histogram names and a dict of histogram Ids keyed by histogram name.

GetHistogramTypes()[source]

Returns a list of histogram types found in the GSASII data tree

Returns:

list of histogram types

GetPWDRdatafromTree(PWDRname)[source]

Returns powder data from GSASII tree

Parameters:

PWDRname (str) – a powder histogram name as obtained from GSASIIstruct.GetHistogramNames()

Returns:

PWDRdata = powder data dictionary with Powder data arrays, Limits, Instrument Parameters, Sample Parameters

GetPhaseData()[source]

Returns a dict with defined phases. Note routine GSASIIstrIO.GetPhaseData() also exists to get same kind of info from GPX file & put in a list of 9 items.

GetPhaseInfofromTree(Used=False)[source]

Get the phase names and their rId values, also the histograms referenced in each phase.

Parameters:

Used (bool) – if Used is True, only histograms that are referenced in the histogram are returned

Returns:

(phaseRIdList, usedHistograms) where

  • phaseRIdList is a list of random Id values for each phase

  • usedHistograms is a dict where the keys are the phase names and the values for each key are a list of the histogram names used in each phase.

GetPhaseNames()[source]

Returns a list of defined phases. Note routine GSASIIstrIO.GetPhaseNames() also exists to get same info from GPX file.

GetPowderIparm(rd, prevIparm, lastIparmfile, lastdatafile)[source]

Open and read an instrument parameter file for a data file Returns the list of parameters used in the data tree

Parameters:
  • rd (obj) – the raw data (histogram) data object.

  • prevIparm (str) – not used

  • lastIparmfile (str) – Name of last instrument parameter file that was read, or a empty string.

  • lastdatafile (str) – Name of last data file that was read.

Returns:

a list of two dicts, the first containing instrument parameters and the second used for TOF lookup tables for profile coeff.

GetTreeItemsList(item)[source]

returns a list of all GSAS-II tree items

GetUsedHistogramsAndPhasesfromTree()[source]

Returns all histograms that are found in any phase and any phase that uses a histogram. This also assigns numbers to used phases and histograms by the order they appear in the file. Note routine GSASIIstrIO.GetUsedHistogramsAndPhases() also exists to get same info from GPX file.

Returns:

(Histograms,Phases)

  • Histograms = dictionary of histograms as {name:data,…}

  • Phases = dictionary of phases that use histograms

MakeLSParmDict(seqHist=None)[source]

Load all parameters used for computation from the tree into a dict of paired values [value, refine flag]. Note that this is different than the parmDict used in the refinement, which only has values.

Note that similar things are done in GSASIIIO.ExportBaseclass.loadParmDict() (from the tree) and GSASIIstrMain.Refine() and GSASIIstrMain.SeqRefine() (from a GPX file).

Parameters:

seqHist (dict) – defines a specific histogram to be loaded for a sequential refinement, if None (default) all are loaded. Note: at present this parameter is not used anywhere.

Returns:

(parmDict,varyList) where:

  • parmDict is a dict with values and refinement flags for each parameter and

  • varyList is a list of variables (refined parameters).

MenuBinding(event)[source]

Called when a menu is clicked upon; looks up the binding in table

MoveTreeItems(event)[source]

Move tree items of a single type to the end of the tree

OnAddPhase(event)[source]

Add a new, empty phase to the tree. Called by Data/Add Phase menu

OnClusterAnalysis(event)[source]

Setsup cluster analysis & make tree entry

OnColMetaTest(event)[source]

Test the .par/.*lbls pair for contents

OnDataDelete(event)[source]

Delete one or more histograms from data tree. Called by the Data/DeleteData menu

OnDataTreeSelChanged(event)[source]

Called when a data tree item is selected. May be called on item deletion as well.

OnDeletePhase(event)[source]

Delete one or more phases from the tree. Called by Data/Delete Phase menu. Also delete this phase from Reflection Lists for each PWDR histogram; removes the phase from restraints and deletes any constraints with variables from the phase. If any deleted phase is marked as Used in a histogram, a more rigorous “deep clean” is done and histogram refinement results are cleared, as well as the covariance information and all plots are deleted

OnDeleteSequential(event)[source]

Delete any sequential results table. Called by the Data/Delete sequential results menu

OnDummyPowder(event)[source]

Called in response to Import/Powder Data/Simulate menu item to create a Dummy powder diffraction data set.

Reads an instrument parameter file and then gets input from the user

OnExportHKL(event)[source]

Exports a PWDR reflection list as a text file

OnExportMTZ(event)[source]

exports MTZ file from macromoleculat Reflection Lists in multiple histograms

OnExportPDF(event)[source]

Save S(Q), G(R),… as selected by user

OnExportPeakList(event)[source]

Exports a PWDR peak list as a text file

OnFileBrowse(event)[source]

Gets a GSAS-II .gpx project using the GPX browser, in response to the File/”Open Project browser” menu button

OnFileClose(event)[source]

Clears the data tree in response to the File/New Project menu button. User is given option to save the project.

OnFileOpen(event, filename=None, askSave=True)[source]

Gets a GSAS-II .gpx project file in response to the File/Open Project menu button

OnFileReopen(event)[source]

Creates a dialog box showing previously opened GSAS-II projects & offers to open one called by File/Reopen recent… menu item

OnFileReread(event)[source]

reread the current GPX file; no questions asked – no save for development purposes.

OnFileSave(event)[source]

Save the current project in response to the File/Save Project menu button

OnFileSaveas(event)[source]

Save the current project with a new name in response to the File/Save as menu button. The current project then has this new name

OnGPXtreeItemActivated(event)[source]

Called when a tree item is activated

OnGPXtreeItemCollapsed(event)[source]

Called when a tree item is collapsed - all children will be collapsed

OnGPXtreeItemDelete(event)[source]

Called when a tree item is deleted, inhibit the next tree item selection action

OnGPXtreeItemExpanded(event)[source]

Called when a tree item is expanded

OnGPXtreeKeyDown(event)[source]

Allows stepping through the tree with the up/down arrow keys

OnImageSum(event)[source]

Sum together image data

OnImportGeneric(reader, readerlist, label, multiple=False, usedRanIdList=[], Preview=True, load2Tree=False)[source]

Used for all imports, including Phases, datasets, images…

Called from GSASII.OnImportPhase(), GSASII.OnImportImage(), GSASII.OnImportSfact(), GSASII.OnImportPowder(), GSASII.OnImportSmallAngle() and :meth:’GSASII.OnImportReflectometry`

Uses reader_objects subclassed from GSASIIobj.ImportPhase, GSASIIobj.ImportStructFactor, GSASIIobj.ImportPowderData, GSASIIobj.ImportSmallAngleData GSASIIobj.ImportReflectometryData or GSASIIobj.ImportImage. If a specific reader is specified, only that method will be called, but if no reader is specified, every one that is potentially compatible (by file extension) will be tried on the file(s) selected in the Open File dialog.

Parameters:
  • reader (reader_object) – This will be a reference to a particular object to be used to read a file or None, if every appropriate reader should be used.

  • readerlist (list) – a list of reader objects appropriate for the current read attempt. At present, this will be either self.ImportPhaseReaderlist, self.ImportSfactReaderlist self.ImportPowderReaderlist or self.ImportImageReaderlist (defined in _init_Imports from the files found in the path), but in theory this list could be tailored. Used only when reader is None.

  • label (str) – string to place on the open file dialog: Open label input file

  • multiple (bool) – True if multiple files can be selected in the file dialog. False is default. At present True is used only for reading of powder data.

  • usedRanIdList (list) – an optional list of random Ids that have been used and should not be reused

  • Preview (bool) – indicates if a preview of the file should be shown. Default is True, but set to False for image files which are all binary.

  • load2Tree (bool) – indicates if the file should be loaded into the data tree immediately (used for images only). True only when called from OnImportImage(); causes return value to change to a list of True values rather than reader objects.

Returns:

a list of reader objects (rd_list) that were able to read the specified file(s). This list may be empty.

OnImportImage(event)[source]

Called in response to an Import/Image/… menu item to read an image from a file. Like all the other imports, dict self.ImportMenuId is used to look up the specific reader item associated with the menu item, which will be None for the last menu item, which is the “guess” option where all appropriate formats will be tried.

A reader object is filled each time an image is read.

OnImportPDF(event)[source]

Called in response to an Import/PDF G(R) Data/… menu item to read a PDF G(R) data set. dict self.ImportMenuId is used to look up the specific reader item associated with the menu item, which will be None for the last menu item, which is the “guess” option where all appropriate formats will be tried.

OnImportPhase(event)[source]

Called in response to an Import/Phase/… menu item to read phase information. dict self.ImportMenuId is used to look up the specific reader item associated with the menu item, which will be None for the last menu item, which is the “guess” option where all appropriate formats will be tried.

OnImportPowder(event)[source]

Called in response to an Import/Powder Data/… menu item to read a powder diffraction data set. dict self.ImportMenuId is used to look up the specific reader item associated with the menu item, which will be None for the last menu item, which is the “guess” option where all appropriate formats will be tried.

Also reads an instrument parameter file for each dataset.

OnImportReflectometry(event)[source]

Called in response to an Import/Reflectometry Data/… menu item to read a reflectometry data set. dict self.ImportMenuId is used to look up the specific reader item associated with the menu item, which will be None for the last menu item, which is the “guess” option where all appropriate formats will be tried. Reflectometry data is presumed to be in QIE form for x-rays of neutrons

OnImportSfact(event)[source]

Called in response to an Import/Structure Factor/… menu item to read single crystal datasets. dict self.ImportMenuId is used to look up the specific reader item associated with the menu item, which will be None for the last menu item, which is the “guess” option where all appropriate formats will be tried.

OnImportSmallAngle(event)[source]

Called in response to an Import/Small Angle Data/… menu item to read a small angle diffraction data set. dict self.ImportMenuId is used to look up the specific reader item associated with the menu item, which will be None for the last menu item, which is the “guess” option where all appropriate formats will be tried. Small angle data is presumed to be as QIE form for either x-rays or neutrons

OnLeBail(event)[source]

Do a 1 cycle LeBail refinement with no other variables; usually done upon initialization of a LeBail refinement either single or sequentially

OnMacroRecordStatus(event, setvalue=None)[source]

Called when the record macro menu item is used which toggles the value. Alternately a value to be set can be provided. Note that this routine is made more complex because on the Mac there are lots of menu items (listed in self.MacroStatusList) and this loops over all of them.

OnMakePDFs(event)[source]

Sets up PDF data structure filled with defaults; if found chemical formula is inserted so a default PDF can be made.

OnNewGSASII(event)[source]

Gets a GSAS-II .gpx project file in response to the File/Open new window menu button. Runs only on Mac.

OnPlotDelete(event)[source]

Delete one or more plots from plot window. Called by the Data/DeletePlots menu

OnPowderFPA(event)[source]

Perform FPA simulation/peak fitting

OnPreferences(event)[source]

Edit the GSAS-II configuration variables

OnPwdrSum(event)[source]

Sum or Average together powder data(?)

OnReadPowderPeaks(event)[source]

Bound to menu Data/Read Powder Peaks

OnRefine(event)[source]

Perform a single refinement or a sequential refinement (depending on controls setting) Called from the Calculate/Refine menu.

OnRefinePartials(event)[source]

Computes and saves the intensities from each phase for each powder histogram. Do a 0 cycle fit with no variables to pickle intensities for each phase into a file. Not for sequential fits. Sets Controls[‘PhasePartials’] to a file name to trigger save of info in GSASIIstrMath.getPowderProfile() and then clear that.

OnRenameData(event)[source]

Renames an existing histogram. Called by Data/Rename Phase menu. Must be used before a histogram is used in a phase.

OnRunAbsorb(event)[source]

Run Absorb

OnRunFprime(event)[source]

Run Fprime

OnRunPlotXNFF(evnt)[source]

Run PlotXNFF

OnSaveMultipleImg(event)[source]

Select and save multiple image parameter and mask files

OnSavePartials(event)[source]

Saves partials as a csv file

OnSeqRefine(event)[source]

Perform a sequential refinement. Called from self.OnRefine (Which is called from the Calculate/Refine menu)

OnShowLSParms(event)[source]

Displays a window showing all parameters in the refinement. Called from the Calculate/View LS Parms menu.

This could potentially be sped up by loading only the histogram that is needed for a sequential fit.

OpenPowderInstprm(instfile)[source]

Read a GSAS-II (new) instrument parameter file

Parameters:

instfile (str) – name of instrument parameter file

PreviewFile(filename)[source]

utility to confirm we have the right file

ReadPowderInstprm(instLines, bank, databanks, rd)[source]

Read lines from a GSAS-II (new) instrument parameter file similar to G2pwdGUI.OnLoad If instprm file has multiple banks each with header #Bank n: …, this finds matching bank no. to load - problem with nonmatches?

Note that this routine performs a similar role to GSASIIfiles.ReadPowderInstprm(), but this will call a GUI routine for selection when needed. TODO: refactor to combine

Parameters:
  • instLines (list) – strings from GSAS-II parameter file; can be concatenated with ‘;’

  • bank (int) – bank number to check when instprm file has ‘#BANK n:…’ strings when bank = n then use parameters; otherwise skip that set. Ignored if BANK n: not present. NB: this kind of instprm file made by a Save all profile command in Instrument Parameters

Return dict:

Inst instrument parameter dict if OK, or str: Error message if failed

ReadPowderIparm(instfile, bank, databanks, rd)[source]

Read a GSAS (old) instrument parameter file

Parameters:
  • instfile (str) – name of instrument parameter file

  • bank (int) – the bank number read in the raw data file

  • databanks (int) – the number of banks in the raw data file. If the number of banks in the data and instrument parameter files agree, then the sets of banks are assumed to match up and bank is used to select the instrument parameter file. If not and not TOF, the user is asked to make a selection.

  • rd (obj) – the raw data (histogram) data object. This sets rd.instbank.

ResetPlots()[source]

This reloads the current tree item, often drawing a plot. It also refreshes any plots that have registered a refresh routine (see G2plotNB.RegisterRedrawRoutine) and deletes all plots that have not been refreshed and require one (see G2plotNB.SetNoDelete).

SaveTreeSetting()[source]

Save the current selected tree item by name (since the id will change)

SetDataSize()[source]

this routine is a placeholder until all G2frame.SetDataSize calls are replaced by G2frame.dataWindow.SetDataSize

SetTitleByGPX()[source]

Set the title for the two window frames

StartProject()[source]

Opens a GSAS-II project file & selects the 1st available data set to display (PWDR, HKLF, REFD or SASD)

class SumDialog(parent, title, text, dataType, data, dataList, Limits=None)[source]

Allows user to supply scale factor(s) when summing data

OnFilter(event)[source]

Read text from filter control and select entries that match.

onChar(event)[source]

Respond to keyboard events in the Filter box

init_vars()[source]

initialize default values for GSAS-II “global” variables (saved in main Frame)

reloadFromGPX(rtext=None)[source]

Deletes current data tree & reloads it from GPX file (after a refinemnt.) Done after events are completed to avoid crashes. :param rtext str: string info from caller to be put in Notebook after reload

testSeqRefineMode()[source]

Returns the list of histograms included in a sequential refinement or an empty list if a standard (non-sequential) refinement. Also sets Menu item status depending on mode

GSASIIdataGUI.GSASIImain(application)[source]

Start up the GSAS-II GUI

GSASIIdataGUI.GUIpatches()[source]

Misc fixes that only needs to be done when running a GUI

GSASIIdataGUI.GetDisplay(pos)[source]

Gets display number (0=main display) for window position (pos). If pos outside all displays returns None

GSASIIdataGUI.GetGPXtreeDataNames(G2frame, dataTypes)[source]

Finds all items in tree that match a 4 character prefix

Parameters:
  • G2frame (wx.Frame) – Data tree frame object

  • dataTypes (list) – Contains one or more data tree item types to be matched such as [‘IMG ‘] or [‘PWDR’,’HKLF’]

Returns:

a list of tree item names for the matching items

GSASIIdataGUI.GetGPXtreeItemId(G2frame, parentId, itemText)[source]

Find the tree item that matches the text in itemText starting with parentId

Parameters:
  • G2frame (wx.Frame) – Data tree frame object

  • parentId (wx.TreeItemId) – tree item to start search with

  • itemText (str) – text for tree item

class GSASIIdataGUI.MergeDialog(parent, data)[source]

HKL transformation & merge dialog

Parameters:
  • parent (wx.Frame) – reference to parent frame (or None)

  • data – HKLF data

GSASIIdataGUI.SelectDataTreeItem(G2frame, item, oldFocus=None)[source]

Called from GSASIIdataGUI.GSASII.OnDataTreeSelChanged() when a item is selected on the tree. Also called from GSASII.OnGPXtreeEndDrag, OnAddPhase – might be better to select item, triggering the the bind to SelectDataTreeItem

Also Called in GSASIIphsGUI.UpdatePhaseData by OnTransform callback.

GSASIIdataGUI.SetDataMenuBar(G2frame, menu=None)[source]

Set the menu for the data frame.

Note that data frame items do not have menus, for these (menu=None) display the standard main menu for the data tree window.

GSASIIdataGUI.SetDefaultDData(dType, histoName, NShkl=0, NDij=0)[source]

Sets default values for various histogram parameters param: str dType: 3 letter histogram type, e.g. ‘PNT’ param: str histoName: histogram name as it aoears in tree param: NShkl int: number of generalized mustrain coefficients - depends on symmetry param: NDij int: number of hydrostatic strain coefficients - depends on symmetry

returns dict: default data for histogram - found in data tab for phase/histogram

GSASIIdataGUI.ShowVersions()[source]

Show the versions all of required Python packages, etc.

GSASIIdataGUI.TestOldVersions()[source]

Test the versions of required Python packages, etc. Returns a non-empty text string if there are problems.

GSASIIdataGUI.UpdateComments(G2frame, data)[source]

Place comments into the data window

GSASIIdataGUI.UpdateControls(G2frame, data)[source]

Edit overall GSAS-II controls in main Controls data tree entry

GSASIIdataGUI.UpdateNotebook(G2frame, data)[source]

Called when the data tree notebook entry is selected. Allows for editing of the text in that tree entry

GSASIIdataGUI.UpdatePWHKPlot(G2frame, kind, item)[source]

Called when the histogram main tree entry is called. Displays the histogram weight factor, refinement statistics for the histogram and the range of data for a simulation.

Also invokes a plot of the histogram.

GSASIIdataGUI.compareVersions(version1, version2)[source]

Compare two version strings (“x”, “x.y”, “x.y.z”) Note that ‘3.’ matches ‘3.1’, and ‘3.0’ matches ‘3.0.1’ but ‘3.0.0’ does not match ‘3.0.1’

Returns:

0 if the versions match, -1 if version1 < version2, or 1 if version1 > version2

GSASIIdataGUI.convVersion(version)[source]

Convert a version string (“x”, “x.y”, “x.y.z”) into a series of ints.

Returns:

[i0, i1, i2] where None is used if a value is not specified and 0 is used if a field cannot be parsed.

GSASIIdataGUI.versionDict = {'badVersionWarn': {'matplotlib': ['3.1', '3.2'], 'numpy': ['1.16.0'], 'wx': ['4.1']}, 'tooNewUntested': {'Python': '3.12', 'wx': '4.2.2'}, 'tooNewWarn': {}, 'tooOld': {'Python': '2.7', 'matplotlib': '2.'}, 'tooOldWarn': {'Python': '3.6', 'matplotlib': '3.2.99', 'wx': '3.99'}}

Variable versionDict is used to designate versions of packages that should generate warnings or error messages.

  • versionDict['tooOld'] is a dict with module versions that are too old and are known to cause serious errors

  • versionDict['tooOldWarn'] is a dict with module versions that are significantly out of date and should be updated, but will probably function OK.

  • versionDict['badVersionWarn'] is a dict of with lists of package versions that are known to have bugs. One should select an older or newer version of the package.

  • versionDict['tooNewUntested'] is a dict with module versions that have not been tested but there is no reason to expect problems

  • versionDict['tooNewWarn'] is a dict with module versions that have not been tested but there are concerns that problems may occur.

Packages/versions to be avoided

  • Python:

  • We are no longer supporting Python <=2.7 and <=3.6. Jan. 2023: We will soon start removing code that is specific to Python 2.7.

  • A problem has been noted with wx4.0.7.post2 with Python 3.10 that we can’t yet duplicate (2/4/22).

  • We anticipate that Python 3.10+ will flag code that previously worked fine, because it reports errors where we pass a floating point number to a wxpython routine that expects a int value. We are fixing these as we learn about them.

  • wxPython:

  • <=2.x.x: while most of GSAS-II has been written to be compatible with older versions of wxpython, we are now testing with version 4.0+ only.

  • wxpython 3.0 is pretty similar to 4.0, but we did see some issues with Python 3.x.

  • wxpython 4.1 has some serious internal bugs with Python 3.10+ so we recommend 4.2+ for compatibility with newer Python versions.

  • 4.2.0 has a problem on MacOS where buttons w/default size are not displayed properly. (see https://github.com/wxWidgets/Phoenix/issues/2319). Worked around (mostly?) in our code.

  • Matplotlib:

    • 1.x: there have been significant API changes since these versions and significant graphics errors will occur.

    • 3.1.x and 3.2.x: these versions have a known bug for plotting 3-D surfaces, such as microstrain vs crystal axes. The plots may appear distorted as the lengths of x, y & z will not be constrained as equal. Preferably use 3.0.x as 3.3.x is not fully tested.

    • between 3.3.x vs 3.6.x there seems to be a change in how 3d graphics are handled; we seem to have this fixed, but not sure how <3.3 will work. Since 3.1 & 3.2 have problems; warn w/mpl <3.3.0

  • numpy:

    • 1.16.0: produces .gpx files that are not compatible with older version numpy versions. This is a pretty outmoded version; upgrade.

6.2. GSASIIseqGUI: Sequential Results GUI

Module that defines GUI routines and classes for the various sequential result GUI Frames (window). Also defines GUI routines for Cluster Analysis results.

Note that there are seven types of sequential results that GSAS-II can produce and all are displayed/analyzed with the code in this module. They vary by title so that a project can hold one result of each type without a naming collision:

  • Rietveld (Title: Sequential results)

  • PDF (Title: Sequential PDFfit2 results)

  • Peak fit (Title: Sequential peak fit results)

  • Small angle (Title: Sequential SASD fit results)

  • Reflectometry (Title: Sequential REFD results)

  • Image (strain) (Title: Sequential strain fit results)

  • Image (calibration) (Title: Sequential image calibration results)

6.2.1. GSASIIseqGUI Classes & Routines

Routines for Sequential Results & Cluster Analysis dataframes follow.

GSASIIseqGUI.UpdateSeqResults(G2frame, data, prevSize=None)[source]

Called when any data tree entry is selected that has ‘Sequential’ in the name to show results from any sequential analysis.

Parameters:
  • G2frame (wx.Frame) – main GSAS-II data tree windows

  • data (dict) –

    a dictionary containing the following items:

    • ’histNames’ - list of histogram names in order as processed by Sequential Refinement

    • ’varyList’ - list of variables - identical over all refinements in sequence note that this is the original list of variables, prior to processing constraints.

    • ’variableLabels’ – a dict of labels to be applied to each parameter (this is created as an empty dict if not present in data).

    • keyed by histName - dictionaries for all data sets processed, which contains:

      • ’variables’- result[0] from leastsq call

      • ’varyList’ - list of variables passed to leastsq call (not same as above)

      • ’sig’ - esds for variables

      • ’covMatrix’ - covariance matrix from individual refinement

      • ’title’ - histogram name; same as dict item name

      • ’newAtomDict’ - new atom parameters after shifts applied

      • ’newCellDict’ - refined cell parameters after shifts to A0-A5 from Dij terms applied’

6.3. GSASIIphsGUI: Phase GUI

Module to create the GUI for display of phase information in the data display window when a phase is selected. Phase information is stored in one or more Phase Tree Item objects. Note that there are functions that respond to some tabs in the phase GUI in other modules (such as GSASIIddata).

6.3.1. GSASIIphsGUI Classes & Routines

Main routine here is UpdatePhaseData(), which displays the phase information (called from GSASIIdataGUI:SelectDataTreeItem()).

Other top-level routines are: GetSpGrpfromUser() (called locally only); FindBondsDraw() and FindBondsDrawCell() (called locally and in GSASIIplot); SetPhaseWindow() (called locally and in GSASIIddataGUI and GSASIIrestrGUI, multiple locations) to control scrolling.

Routines for Phase dataframes follow.

class GSASIIphsGUI.AddHatomDialog(parent, Neigh, phase)[source]

H atom addition 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)

  • Neigh (dict) – a dict of atom names with list of atom name, dist pairs for neighboring atoms

  • phase (dict) – a dict containing the phase as defined by Phase Tree Item

Draw(Neigh, phase)[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

class GSASIIphsGUI.DIFFaXcontrols(parent, ctrls, parms=None)[source]

Solicit items needed to prepare DIFFaX control.dif file

GSASIIphsGUI.FindBondsDraw(data)[source]

Generally used routine where cell is from data

GSASIIphsGUI.FindBondsDrawCell(data, cell)[source]

uses numpy & masks - very fast even for proteins! allows different cell as input from seq. refinements

GSASIIphsGUI.FindCoordination(ind, data, neighborArray, coordsArray, cmx=0, targets=None)[source]

Find atoms coordinating atom ind, speed-up version. This only searches to atoms already added to the Draw Array, though we might want to search to all atoms in the asymmetric unity (which would mean searching against atomsAll, but would also require a reformat of atom entry to match difference in format between atoms and drawatoms.

GSASIIphsGUI.FindCoordinationByLabel(data)[source]

Map out molecular connectivity by determining the atoms bonded to each atom, by label. The atoms bonded to each atom in the asymmetric unit is determined and returned in a dict. Works best

class GSASIIphsGUI.RotationDialog(parent)[source]

Get Rotate & translate matrix & vector - currently not used needs rethinking - possible use to rotate a group of atoms about some vector/origin + translation

GSASIIphsGUI.SetDrawingDefaults(drawingData)[source]

Add required items into data[‘drawing’] array if not present. This does not add all the items in SetupDrawingData, but it seems that this is not a problem. Perhaps the two routines could be combined?

class GSASIIphsGUI.SphereEnclosure(parent, general, drawing, indx)[source]

Add atoms within sphere of enclosure to drawing

Parameters:
  • parent (wx.Frame) – reference to parent frame (or None)

  • general – general data (includes drawing data)

  • atoms – drawing atoms data

  • indx – list of selected atoms (may be empty)

class GSASIIphsGUI.SymOpDialog(parent, SGData, New=True, ForceUnit=False)[source]

Class to select a symmetry operator

class GSASIIphsGUI.TransformDialog(parent, phase, Trans=array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]), Uvec=array([0., 0., 0.]), Vvec=array([0., 0., 0.]), ifMag=False, BNSlatt='')[source]

Phase transformation X’ = M*(X-U)+V

Parameters:
  • parent (wx.Frame) – reference to parent frame (or None)

  • phase – parent phase data

#NB: commonNames & commonTrans defined in GSASIIdataGUI = G2gd

GSASIIphsGUI.UpdatePhaseData(G2frame, Item, data)[source]

Create the data display window contents when a phase is clicked on in the main (data tree) window. Called only from GSASIIdataGUI.SelectDataTreeItem(), which in turn is called from GSASIIdataGUI.GSASII.OnDataTreeSelChanged() when a Phase tree item is selected. This creates all tabs on the page and fills their contents. Routine OnPageChanged is called each time a tab is pressed and updates the contents of the tab’s page.

Parameters:
  • G2frame (wx.frame) – the main GSAS-II frame object

  • Item (wx.TreeItemId) – the tree item that was selected

  • data (dict) – all the information on the phase in a dictionary

class GSASIIphsGUI.UseMagAtomDialog(parent, Name, Atoms, atCodes, atMxyz, ifMag=True, ifOK=False, ifDelete=False)[source]

Get user selected magnetic atoms after cell transformation

GSASIIphsGUI.VoidMap(data, aMax=1, bMax=1, cMax=1, gridspacing=0.25, probeRadius=0.5, aMin=0, bMin=0, cMin=0)[source]

Compute points where there are no atoms within probeRadius A. All atoms in the Atoms list are considered, provided their occupancy is non-zero.

Parameters:
  • data (dict) – Phase data array

  • aMax (float) – Maximum along the a direction (fractional units). Defaults to 1.

  • bMax (float) – Maximum along the b direction (fractional units). Defaults to 1.

  • cMax (float) – Maximum along the c direction (fractional units). Defaults to 1.

  • gridspacing=.25 (float) – Approximate spacing of points (fractional units). Defaults to 1.

  • ,probeRadius=.5 (float)

  • aMin (float) – Minimum along the a direction (fractional units). Defaults to 0.

  • bMin (float) – Minimum along the b direction (fractional units). Defaults to 0.

  • cMin (float) – Minimum along the c direction (fractional units). Defaults to 0.

GSASIIphsGUI.checkPDFfit(G2frame)[source]

Checks to see if PDFfit2 is available and can be imported. PDFfit2 can be installed in a separate Python interpreter (saved in the pdffit2_exec config variable). If this is defined, no attempt is made to check that it actually runs. Otherwise, if diffpy.PDFfit has been installed with conda/pip, it is checked if the install command. The fallback is to check if a .so/.pyd file has been supplied with GSAS-II. This requires that GSL (GNU Scientific Library) be installed. If the current Python is being run from conda, this will be loaded.

Returns:

False if PDFfit2 cannot be run/accessed. True if it appears it can be run.

GSASIIphsGUI.getAtomRadii(data)[source]

Get radii for atoms, using generalData[‘DisAglCtls’][‘BondRadii’] to override generalData[‘BondRadii’] when present. Fix to make sure that all elements in generalData are present in DisAglCtls.

GSASIIphsGUI.getAtomSelections(AtmTbl, cn=0, action='action', includeView=False, ask=True)[source]

get selected atoms from table or ask user if none are selected

Parameters:
  • AtmTbl (list) – atom or draw atom table

  • cn (int) – atom name position

  • action (str) – description for prompt, when needed

  • includeView (bool) – if True, the viewpoint is included as an option in the selection dialog

Returns:

indx (list) selected atoms from indices in table. If includeView is True, indx can contain index n (where there are n atoms in table). This is indicates the viewpoint.

GSASIIphsGUI.getPawleydRange(G2frame, data)[source]

find d-space range in used histograms

GSASIIphsGUI.makeIsoNewPhase(phData, cell, atomList, sglbl, sgnum)[source]

create a new phase from a supergroup structure generated by ISOCIF

GSASIIphsGUI.saveIsoNewPhase(G2frame, phData, newPhase, orgFilName)[source]

save the new phase generated by ISOCIF created in makeIsoNewPhase() into a GSAS-II project (.gpx) file

GSASIIphsGUI.updateAddRBorientText(G2frame, testRBObj, Bmat)[source]

Update all orientation text on the Add RB panel

6.4. GSASIIddataGUI: Phase Diffraction Data GUI

Module to create the GUI for display of HAP items (where there is an entry for each histogram & phase). This is shown when the Phase “Data” tab is selected or may appear as if in a separate data tree item (see SeparateHistPhaseTreeItem in config.py).

6.4.1. GSASIIddataGUI Classes & Routines

Routines for Data tab in Phase dataframe follows.

GSASIIddataGUI.MakeHistPhaseWin(G2frame)[source]

Display Phase/Data info from Hist/Phase tree item (not used with Phase/Data tab)

GSASIIddataGUI.UpdateDData(G2frame, DData, data, hist='', Scroll=0)[source]

Display the Diffraction Data associated with a phase (items where there is a value for each histogram and phase) Used in the Phase/Data tab or the Hist/Phase tree entry

Parameters:
  • G2frame (wx.frame) – the main GSAS-II frame object

  • DData (wx.ScrolledWindow) – notebook page to be used for the display

  • data (dict) – all the information on the phase in a dictionary

  • hist (str) – histogram name

  • Scroll (int) – previous scroll position

6.5. GSASIIElemGUI: GUI to select and delete element lists

Module to select elements from a periodic table and to delete an element from a list of selected elements.

6.5.1. GSASIIElemGUI Classes & Routines

Routines for Periodic table wx.Frame follow.

class GSASIIElemGUI.DeleteElement(parent, choice)[source]

Delete element from selected set widget

ElButton(name, pos)[source]

Needs a doc string

class GSASIIElemGUI.PickElement(parent, oneOnly=False, ifNone=False, ifMag=False, ifOrbs=False, multiple=False)[source]

Makes periodic table widget for picking element. Modes: oneOnly if True element symbols are provided, otherwise select valence ifNone if True show None button ifMag if True present magnetic scatters only ifOrbs if True present orbital form actors only multiple if True multiple elements can be selected

ElButton(name, pos, tip, color)[source]

Creates an element button widget

class GSASIIElemGUI.PickElements(parent, list)[source]

Makes periodic table widget for picking elements - caller maintains element list

6.6. GSASIIconstrGUI: Constraint GUI routines

GUI routines to define constraints and rigid bodies.

6.6.1. GSASIIconstrGUI Classes & Routines

Constraints and rigid bodies GUI routines follow.

GSASIIconstrGUI.CheckAllScalePhaseFractions(G2frame, refine=True)[source]

Check if scale factor and all phase fractions are refined without a constraint for all used histograms, if so, offer the user a chance to create a constraint on the sum of phase fractions

Returns:

False if refinement should be continued

GSASIIconstrGUI.CheckConstraints(G2frame, Phases, Histograms, data, newcons=[], reqVaryList=None, seqhst=None, seqmode='use-all')[source]

Load constraints & check them for errors.

N.B. Equivalences based on symmetry (etc.) are generated by running GSASIIstrIO.GetPhaseData().

When reqVaryList is included (see WarnConstraintLimit) then parameters with limits are checked against constraints and a warning is shown.

GSASIIconstrGUI.CheckScalePhaseFractions(G2frame, hist, histograms, phases, Constraints)[source]

Check if scale factor and all phase fractions are refined without a constraint for histogram hist, if so, offer the user a chance to create a constraint on the sum of phase fractions

class GSASIIconstrGUI.ConstraintDialog(parent, title, text, data, separator='*', varname='', varyflag=False)[source]

Window to edit Constraint values

class GSASIIconstrGUI.DragableRBGrid(parent, rb, onChange=None)[source]

Simple grid implentation for display of rigid body positions.

Parameters:
  • parent – frame or panel where grid will be placed

  • rb (dict) – dict with atom labels, types and positions

  • onChange (function) – a callback used every time a value in rb is changed.

OnRowMove(evt)[source]

called when a row move needs to take place

completeEdits()[source]

complete any outstanding edits

class GSASIIconstrGUI.G2BoolEditor[source]

Substitute for wx.grid.GridCellBoolEditor except toggles grid items immediately when opened, updates grid & table contents after every item change

ApplyEdit(row, col, grid)[source]

Save the value into the table, and create event. Called after EndEdit(), BeginEdit and onCheckSet.

BeginEdit(row, col, grid)[source]

Prepares the edit control by loading the initial value from the table (toggles it since you would not click on it if you were not planning to change it), buts saves the original, pre-change value. Makes change to table immediately. Saves the info needed to make updates in self.saveVals. Sets the focus.

Clone()[source]

required

Create(parent, id, evtHandler)[source]

Create the editing control (wx.CheckBox) when cell is opened for edit

Destroy()[source]

final cleanup

EndEdit(row, col, grid, oldVal=None)[source]

End editing the cell. This is supposed to return None if the value has not changed, but I am not sure that actually works.

Reset()[source]

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

SetSize(rect)[source]

Set position/size the edit control within the cell’s rectangle.

StartingClick()[source]

This seems to be needed for BeginEdit to work properly

onCheckSet(event)[source]

Callback used when checkbox is toggled. Makes change to table immediately (creating event)

class GSASIIconstrGUI.RBDataTable(rb, onChange)[source]

A Table to support DragableRBGrid

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.

GetValue(row, col) PyObject[source]

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

IsEmptyCell(row, col) bool[source]

May be overridden to implement testing for empty cells.

SetValue(row, col, value)[source]

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

GSASIIconstrGUI.ShowIsoDistortCalc(G2frame, phase=None)[source]

Compute the ISODISTORT mode values from the current coordinates. Called in response to the (Phase/Atoms tab) AtomCompute or Constraints/Edit Constr. “Show ISODISTORT modes” menu item, which should be enabled only when Phase[‘ISODISTORT’] is defined.

GSASIIconstrGUI.ShowIsoModes(G2frame, phase)[source]

Show details about the ISODISTORT mode and the displacements they translate to.

GSASIIconstrGUI.TransConstraints(G2frame, oldPhase, newPhase, Trans, Vec, atCodes)[source]

Add constraints for new magnetic phase created via transformation of old nuclear one NB: A = [G11,G22,G33,2*G12,2*G13,2*G23]

GSASIIconstrGUI.UpdateConstraints(G2frame, data, selectTab=None, Clear=False)[source]

Called when Constraints tree item is selected. Displays the constraints in the data window

GSASIIconstrGUI.UpdateRigidBodies(G2frame, data)[source]

Called when Rigid bodies tree item is selected. Displays the rigid bodies in the data window

6.7. GSASIIrestrGUI: Restraint GUI routines

GUI Routines used to define restraints.

6.7.1. GSASIIrestrGUI Classes & Routines

Restraint GUI routines follow.

GSASIIrestrGUI.GetSelectedRows(widget, lbl='edit', G2frame=None)[source]

Returns a list of selected rows. Rows can be selected, blocks of cells or individual cells can be selected. The column for selected cells is ignored.

GSASIIrestrGUI.UpdateRestraints(G2frame, data, phaseName)[source]

Respond to selection of the Restraints item on the data tree

6.8. GSASIIimgGUI: Image GUI

GUI Routines used to control image display and processing

6.8.1. GSASIIimgGUI Classes & Routines

Image GUI routines follow.

class GSASIIimgGUI.AutoIntFrame(G2frame, PollTime=30.0)[source]

Creates a wx.Frame window for the Image AutoIntegration. The intent is that this will be used as a non-modal dialog window.

Implements a Start button that morphs into a pause and resume button. This button starts a processing loop that is repeated every PollTime() seconds.

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

  • PollTime (float) – frequency in seconds to repeat calling the processing loop. (Default is 30.0 seconds.)

EnableButtons(flag)[source]

Relabels and enable/disables the buttons at window bottom when auto-integration is running

IntegrateImage(img, useTA=None, useMask=None)[source]

Integrates a single image. Ids for created PWDR entries (more than one is possible) are placed in G2frame.IntgOutList

OnPause()[source]

Respond to Pause, changes text on button/Status line, if needed Stops timer self.Pause should already be True

OnTimerLoop(event)[source]

A method that is called every PollTime() seconds that is used to check for new files and process them. Integrates new images. Also optionally sets up and computes PDF. This is called only after the “Start” button is pressed (then its label reads “Pause”).

ResetFromTable(dist)[source]

Sets integration parameters based on values from the lookup table

SetSourceDir(event)[source]

Use a dialog to get a directory for image files

ShowMatchingFiles(value, invalid=False, **kwargs)[source]

Find and show images in the tree and the image files matching the image file directory (self.params[‘readdir’]) and the image file filter (self.params[‘filter’]) and add this information to the GUI list box

StartLoop()[source]

Prepare to start autointegration timer loop. Save current Image params for use in future integrations also label the window so users understand what is being used

checkPDFprm(ShowContents=False)[source]

Read in the PDF (.pdfprm) parameter file and check for problems. If ShowContents is True, a formatted text version of some of the file contents is returned. If errors are found, the return string will contain the string “Error:” at least once.

GSASIIimgGUI.CleanupMasks(data)[source]

If a mask creation is not completed, an empty mask entry is created in the masks array. This cleans them out. It is called when the masks page is first loaded and before saving them or after reading them in. This should also probably be done before they are used for integration.

GSASIIimgGUI.DefineEvaluator(dlg)[source]

Creates a function that provides interpolated values for a given distance value

GSASIIimgGUI.GetImageZ(G2frame, data, newRange=False)[source]

Gets image & applies dark, background & flat background corrections.

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

  • data (dict) – Image Controls dictionary

Returns:

array sumImg: corrected image for background/dark/flat back

class GSASIIimgGUI.ImgIntLstCtrl(parent, ID, pos=wx.Point(-1, -1), size=(1000, 200), style=0)[source]

Creates a custom ListCtrl for editing Image Integration parameters

FillList(parms)[source]

Places the current parms into the table

OnDouble(evt)[source]

respond to a double-click

class GSASIIimgGUI.IntegParmTable(parent, parms=None, IMfileList=None, readFileList=None)[source]

Creates a dialog window with a table of integration parameters. ShowModal() will return wx.ID_OK if the process has been successful. In this case, DefineEvaluator() should be called to obtain a function that creates a dictionary with interpolated parameter values.

ReadFiles(files)[source]

Reads a list of .imctrl files or a single .imtbl file

ReadImageParmTable()[source]

Reads possibly edited values from the ListCtrl table and returns a list of values for each column.

GSASIIimgGUI.ReadControls(filename)[source]

read an image controls (.imctrl) file

GSASIIimgGUI.ReadMask(filename)[source]

Read a mask (.immask) file

GSASIIimgGUI.Read_imctrl(imctrl_file)[source]

Read an image control file and record control parms into a dict, with some simple type conversions

GSASIIimgGUI.UpdateImageControls(G2frame, data, masks, useTA=None, useMask=None, IntegrateOnly=False)[source]

Shows and handles the controls on the “Image Controls” data tree entry

GSASIIimgGUI.UpdateMasks(G2frame, data)[source]

Shows and handles the controls on the “Masks” data tree entry

GSASIIimgGUI.UpdateStressStrain(G2frame, data)[source]

Shows and handles the controls on the “Stress/Strain” data tree entry

GSASIIimgGUI.testColumnMetadata(G2frame)[source]

Test the column-oriented metadata parsing, as implemented at 1-ID, by showing results when using a .par and .lbls pair.

  • Select a .par file, if more than one in selected dir.

  • Select the .*lbls file, if more than one matching .par file.

  • Parse the .lbls file, showing errors if encountered; loop until errors are fixed.

  • Search for an image or a line in the .par file and show the results when interpreted

See GSASIIfiles.readColMetadata() for more details.

6.9. GSASIIpwdGUI: Powder Pattern GUI routines

Used to define GUI controls for the routines that interact with the powder histogram (PWDR) data tree items.

6.9.1. GSASIIpwdGUI Classes & Routines

GUI routines for PWDR datadree subitems follow.

GSASIIpwdGUI.CopyPlotCtrls(G2frame)[source]

Global copy: Copy plot controls from current histogram to others.

GSASIIpwdGUI.CopySelectedHistItems(G2frame)[source]

Global copy: Copy items from current histogram to others.

GSASIIpwdGUI.GetFileBackground(G2frame, xye, background, scale=True)[source]

Select a background file to subtract from PWDR pattern param: xye list [npts,6] of PWDR pattern param: background PWDR file to be used as background param: scale bool:=True if scale mult included in background & apply it returns: list background to subtract

GSASIIpwdGUI.GetFileList(G2frame, fileType)[source]

Get list of file names containing a particular string param: fileType str: any string within a file name returns: list of file names from GSAS-II tree Note routine of same name in GSASIIdataGUI; it has a skip option

GSASIIpwdGUI.GetHistsLikeSelected(G2frame)[source]

Get the histograms that match the current selected one: The histogram prefix and data type (PXC etc.), the number of wavelengths and the instrument geometry (Debye-Scherrer etc.) must all match. The current histogram is not included in the list.

Parameters:

G2frame (wx.Frame) – pointer to main GSAS-II data tree

GSASIIpwdGUI.GetPhasesforHistogram(G2frame, histoName)[source]

Returns phases (if any) associated with provided Histogram Returns a list of phase dicts

GSASIIpwdGUI.IsHistogramInAnyPhase(G2frame, histoName)[source]

Tests a Histogram to see if it is linked to any phases. Returns the name of the first phase where the histogram is used.

GSASIIpwdGUI.OptimizePDF(G2frame, data, showFit=True, maxCycles=5)[source]

Optimize the PDF to minimize the difference between G(r) and the expected value for low r (-4 pi r #density).

class GSASIIpwdGUI.RDFDialog(parent)[source]

Display controls for generating RDF plot in Background

GSASIIpwdGUI.SetCopyNames(histName, dataType, addNames=[])[source]

Determine the items in the sample parameters that should be copied, depending on the histogram type and the instrument type.

GSASIIpwdGUI.SetDefaultREFDModel()[source]

Fills in default items for the REFD Models dictionary which are defined as follows for each layer:

  • Name: name of substance

  • Thick: thickness of layer in Angstroms (not present for top & bottom layers)

  • Rough: upper surface roughness for layer (not present for toplayer)

  • Penetration: mixing of layer substance into layer above-is this needed?

  • DenMul: multiplier for layer scattering density (default = 1.0)

Top layer defaults to vacuum (or air/any gas); can be substituted for some other substance.

Bottom layer default: infinitely thisck Silicon; can be substituted for some other substance.

GSASIIpwdGUI.SetDefaultSASDModel()[source]

Fills in default items for the SASD Models dictionary

GSASIIpwdGUI.SetDefaultSubstances()[source]

Fills in default items for the SASD Substances dictionary

GSASIIpwdGUI.SetupSampleLabels(histName, dataType, histType)[source]

Setup a list of labels and number formatting for use in labeling sample parameters. :param str histName: Name of histogram, (“PWDR …”) :param str dataType:

class GSASIIpwdGUI.SubCellsDialog(parent, title, controls, SGData, items, phaseDict)[source]

Display magnetic subcell space group information from selection in Unit Cells table of results from k-SUBGROUPSMAG

GSASIIpwdGUI.TestAtoms(phase, magAtms, SGData, Uvec, Trans, maxequiv=100, maximal=False)[source]

Tests atoms for substructure equivalents param: phase GSAS-II phase object param: magAtms list: atom objects param: SGData dict: GSAS-II space group object param: Uvec array: Translation U vector param: Trans array: Transformation matrix params: maxequiv int:maximum number of atoms with moments to consider param: maximal bool:=True if maximal subgroups only are allowed returns: unique atoms (if any)

GSASIIpwdGUI.TestMagAtoms(phase, magAtms, SGData, Uvec, Trans, allmom, maxequiv=100, maximal=False)[source]

Tests substructure magnetic atoms for magnetic site symmetry param: phase GSAS-II phase object param: magAtms list:magnetic atom objects param: SGData dict: GSAS-II space group object param: Uvec array: Translation U vector param: Trans array: Transformation matrix param: allmom bool: =True if all atoms must have moments allowed params: maxequiv int:maximum number of atoms with moments to consider param: maximal bool:=True if maximal subgroups only are allowed returns: unique magnetic atoms (if any)

GSASIIpwdGUI.UpdateBackground(G2frame, data)[source]

respond to selection of PWDR background data tree item.

GSASIIpwdGUI.UpdateIndexPeaksGrid(G2frame, data)[source]

respond to selection of PWDR Index Peak List data tree item.

GSASIIpwdGUI.UpdateInstrumentGrid(G2frame, data)[source]

respond to selection of PWDR/SASD/REFD Instrument Parameters data tree item.

GSASIIpwdGUI.UpdateLimitsGrid(G2frame, data, datatype)[source]

respond to selection of PWDR Limits data tree item. Allows setting of limits and excluded regions in a PWDR data set

GSASIIpwdGUI.UpdateModelsGrid(G2frame, data)[source]

respond to selection of SASD Models data tree item.

GSASIIpwdGUI.UpdatePDFGrid(G2frame, data)[source]

respond to selection of PWDR PDF data tree item.

GSASIIpwdGUI.UpdatePeakGrid(G2frame, data)[source]

respond to selection of PWDR powder peaks data tree item.

GSASIIpwdGUI.UpdateREFDModelsGrid(G2frame, data)[source]

respond to selection of REFD Models data tree item.

GSASIIpwdGUI.UpdateReflectionGrid(G2frame, data, HKLF=False, Name='')[source]

respond to selection of PWDR Reflections data tree item by displaying a table of reflections in the data window.

GSASIIpwdGUI.UpdateSampleGrid(G2frame, data)[source]

respond to selection of PWDR/SASD Sample Parameters data tree item.

GSASIIpwdGUI.UpdateSubstanceGrid(G2frame, data)[source]

respond to selection of SASD/REFD Substance data tree item.

GSASIIpwdGUI.UpdateUnitCellsGrid(G2frame, data)[source]

respond to selection of PWDR Unit Cells data tree item.

GSASIIpwdGUI.addAutoBack(G2frame, data, xydata)[source]

Create a new histogram for the computed auto background and place as the fixed background histogram

class GSASIIpwdGUI.autoBackground(G2frame, *args, **kwargs)[source]

Create a file selection widget for setting background with pybaselines, as requested by James Feng.

Parameters:

G2frame (wx.Frame) – reference to the main GSAS-II frame.

GSASIIpwdGUI.computePDF(G2frame, data)[source]

Calls GSASIIpwd.CalcPDF() to compute the PDF and put into the data tree array. Called from OnComputePDF and OnComputeAllPDF and OnComputeAllPDF in GSASIIimgGUI.py

6.10. GSASIIexprGUI: Expression Handling

This module defines a class for defining an expression in terms of values in a parameter dictionary via a wx.Dialog. The dialog creates a GSASIIexprGUI.GSASII.ExpressionObj which is used to evaluate the expression against a supplied parameter dictionary.

The expression is parsed to find variables used in the expression and then the user is asked to assign parameters from the dictionary to each variable.

Default expressions are read from file DefaultExpressions.txt using GSASIIpath.LoadConfigFile().

6.10.1. GSASIIexprGUI Classes & Routines

Routines for users to input Python expressions used within GSAS-II computations follow.

class GSASIIexprGUI.AngleDialog(parent, Phases, parmDict, exprObj=None, header='Select an angle for table', wintitle='Select angle', VarLabel=None, depVarDict=None, ExtraButton=None, usedVars=[])[source]

A wx.Dialog that allows a user to select a bond angle to be evaluated. What needs to be done here? Need phase info for atom 0. Select phase 1. Select 1st atom from dialog 2. Find neighbors & select two from dialog 3. Set up angle equation & save it - has to look like result from Show in above ExpressionDialog Use existing angle & esd calculate routines

Draw()[source]

paints the angle dialog window

class GSASIIexprGUI.BondDialog(parent, Phases, parmDict, exprObj=None, header='Select a bond for table', wintitle='Select bond', VarLabel=None, depVarDict=None, ExtraButton=None, usedVars=[])[source]

A wx.Dialog that allows a user to select a bond length to be evaluated. What needs to be done here? Need phase info for atoms 0. Select phase 1. Select 1st atom from dialog 2. Find neighbors & select one from dialog 3. Set up distance equation & save it - has to look like result from Show in above ExpressionDialog Use existing bond & esd calculate routines

Draw()[source]

paints the distance dialog window

class GSASIIexprGUI.ExpressionDialog(parent, parmDict, exprObj=None, header='Enter restraint expression here', wintitle='Expression Editor', fit=True, VarLabel=None, depVarDict=None, ExtraButton=None, usedVars=[], wildCard=True)[source]

A wx.Dialog that allows a user to input an arbitrary expression to be evaluated and possibly minimized.

To do this, the user assigns a new (free) or existing GSAS-II parameter to each parameter label used in the expression. The free parameters can optionally be designated to be refined. For example, is an expression is used such as:

'A*np.exp(-B/C)'

then A, B and C can each be assigned as Free parameter with a user-selected value or to any existing GSAS-II variable in the parameter dictionary. As the expression is entered it is checked for validity.

After the ExpressionDialog object is created, use Show() to run it and obtain a GSASIIobj.ExpressionObj object with the user input.

Parameters:
  • parent (wx.Frame) – The parent of the Dialog. Can be None, but better is to provide the name of the Frame where the dialog is called.

  • parmDict (dict) – a dict with defined parameters and their values. Each value may be a list with parameter values and a refine flag or may just contain the parameter value (non-float/int values in dict are ignored)

  • exprObj – a GSASIIobj.ExpressionObj object with an expression and label assignments or None (default)

  • wintitle (str) – String placed on title bar of dialog; defaults to “Expression Editor”

  • header (str) – String placed at top of dialog to tell the user what they will do here; default is “Enter restraint expression here”

  • fit (bool) – determines if the expression will be used in fitting (default=True). If set to False, refinement flags are not shown and Free parameters are not offered as an assignment option.

  • VarLabel (str) – an optional variable label to include before the expression input. Ignored if None (default)

  • depVarDict (list) – a dict of choices for the dependent variable to be fitted to the expression and their values. Ignored if None (default).

  • ExtraButton (list) – a list with two terms that define [0]: the label for an extra button and [1] the callback routine to be used when the button is pressed. The button will only be enabled when the OK button can be used (meaning the equation/expression is valid). The default is None, meaning this will not be used.

  • usedVars (list) – defines a list of previously used variable names. These names will not be reused as defaults for new free variables. (The default is an empty list).

  • wildCard (bool) – If True (default), histogram names are converted to wildcard values, as is appropriate for the sequential refinement table

CheckVars()[source]

Check that appropriate variables are defined for each symbol used in self.expr

Returns:

a text error message or None if all needed input is present

GetDepVar()[source]

Returns the name of the dependent variable, when depVarDict is used.

OnChar(event)[source]

Called as each character is entered. Cancels any running timer and starts a new one. The timer causes a check of syntax after 2 seconds without input. Disables the OK button until a validity check is complete.

OnChoice(event)[source]

Respond to a selection of a variable type for a label in an expression

OnDepChoice(event)[source]

Respond to a selection of a variable type for a label in an expression

OnValidate(event)[source]

Respond to a press of the Validate button or when a variable is associated with a label (in OnChoice())

Repaint(exprObj)[source]

Redisplay the variables and continue the validation

RestartTimer()[source]

Cancels any running timer and starts a new one. The timer causes a check of syntax after 2 seconds unless there is further input. Disables the OK button until a validity check is complete.

SelectG2var(sel, var, parmList)[source]

Offer a selection of a GSAS-II variable.

Parameters:

sel (int) – Determines the type of variable to be selected. where 1 is used for Phase variables, and 2 for Histogram/Phase vars, 3 for Histogram vars and 4 for Global vars.

Returns:

a variable name or None (if Cancel is pressed)

Show(mode=True)[source]

Call to use the dialog after it is created.

Returns:

None (On Cancel) or a new ExpressionObj

depVarDict

dict for dependent variables

dependentVar

name for dependent variable selection, when depVarDict is specified

expr

Expression as a text string

exprVarLst

A list containing the variables utilized in the current expression. Placed into a GSASIIobj.ExpressionObj object when the dialog is closed with “OK”, saving any changes.

parmDict

A copy of the G2 parameter dict (parmDict) except only numerical values are included and only the value (not the vary flag, if present) is included.

setEvalResult(msg)[source]

Show a string in the expression result area

showError(msg1, msg2='', msg3='')[source]

Show an error message of 1 to 3 sections. The second section is shown in an equally-spaced font.

Parameters:
  • msg1 (str) – msg1 is shown in a the standard font

  • msg2 (str) – msg2 is shown in a equally-spaced (wx.MODERN) font

  • msg3 (str) – msg3 is shown in a the standard font

usedVars

variable names that have been used and should not be reused by default

varName

Name assigned to each variable

varRefflag

Refinement flag for a variable (Free parameters only)

varSelect

A dict that shows the variable type for each label found in the expression.

  • If the value is None or is not defined, the value is not assigned.

  • If the value is 0, then the varible is “free” – a new refineable parameter.

  • Values above 1 determine what variables will be shown when the option is selected.

varValue

Value for a variable (Free parameters only)

GSASIIexprGUI.IndexParmDict(parmDict, wildcard)[source]

Separate the parameters in parmDict into list of keys by parameter type.

Parameters:
  • parmDict (dict) – a dict with GSAS-II parameters

  • wildcard (bool) – True if wildcard versions of parameters should be generated and added to the lists

Returns:

a dict of lists where key 1 is a list of phase parameters, 2 is histogram/phase parms, 3 is histogram parms and 4 are global parameters

GSASIIexprGUI.LoadDefaultExpressions()[source]

Read a configuration file with default expressions from all files named DefaultExpressions.txt found in the path. Duplicates are removed and expressions are sorted alphabetically

6.11. GSASIIfpaGUI: Fundamental Parameters Routines

This module contains GUI routines to accept Fundamental Parameters Approach (FPA) input used to run the NIST XRD Fundamental Parameters Code, computes a set of peaks with that code and fits profile terms to the peaks. Also allows for plotting the convolutors generated by that code.

6.11.1. GSASIIfpaGUI Classes & Routines

NIST XRD Fundamental Parameters interface routines follow:

GSASIIfpaGUI.BBPSDDetector = [('SiPSD_th2_angular_range', 3.0, 'Angular range observed by PSD (degrees 2Theta)')]

Additional FPA dict entries used in FillParmSizer() needed for Bragg Brentano instruments with linear (1-D) Si PSD detectors.

GSASIIfpaGUI.BBPointDetector = [('receiving_slit_width', 0.2, 'Width of receiving slit (mm)')]

Additional FPA dict entries used in FillParmSizer() needed for Bragg Brentano instruments with point detectors.

GSASIIfpaGUI.BraggBrentanoParms = [('divergence', 0.5, 'Bragg-Brentano divergence angle (degrees)'), ('soller_angle', 2.0, 'Soller slit axial divergence (degrees)'), ('Rs', 220, 'Diffractometer radius (mm)'), ('filament_length', 12.0, 'X-ray tube line focus length (mm)'), ('sample_length', 12.0, 'Illuminated sample length in axial direction (mm)'), ('receiving_slit_length', 12.0, 'Length of receiving slit in axial direction (mm)'), ('LAC_cm', 0.0, 'Linear absorption coef. adjusted for packing density (cm-1)'), ('sample_thickness', 1.0, 'Depth of sample (mm)'), ('convolution_steps', 8, 'Number of Fourier-space bins per two-theta step'), ('source_width', 0.04, 'Tube filament width, in projection at takeoff angle (mm)'), ('tube-tails_L-tail', -1.0, 'Left-side tube tails width, in projection (mm)'), ('tube-tails_R-tail', 1.0, 'Right-side tube tails width, in projection (mm)'), ('tube-tails_rel-I', 0.001, 'Tube tails fractional intensity (no units)')]

FPA dict entries used in FillParmSizer(). Tuple contains a dict key, a default value and a description. These are the parameters needed for all Bragg Brentano instruments

GSASIIfpaGUI.DetMode = 'BBpoint'

The type of detector, either ‘BBpoint’ for Bragg-Brentano point detector or or ‘BBPSD’ (linear) position sensitive detector

GSASIIfpaGUI.FillParmSizer()[source]

Create a list of input items for the parameter section of the input window, sets default values when not set and displays them in the scrolledpanel prmPnl.

GSASIIfpaGUI.IBmono = False

set to True if an incident beam monochromator is in use

GSASIIfpaGUI.IBmonoParms = [('src_mono_mm', 119, 'Distance from xray line source to monochromator crystal (mm)'), ('focus_mono_mm', 217, 'Distance from monochromator crystal to focus slit (mm)'), ('passband_mistune', -0.145, 'Offset from the tuning of the IBM to the center of the reference line of the spectrum, in units of its bandwidth'), ('mono_src_proj_mn', 51, 'Projection width of line-focus xray source on the monochromator along beam direction (microns), sets bandwidth'), ('passband_shoulder', 0.087, 'Width of transition region from flat top to tails, in units of the bandwidth'), ('two_theta_mono', 27.27, 'The full diffraction angle of the IBM crystal, e.g. double 2theta-Bragg for the mono (deg)'), ('mono_slit_attenuation', 0.03, 'Attenuation of Cu K alpha2 lines due to focal slit')]

Additional FPA dict entries used in FillParmSizer(), needed for Incident Beam Monochromator

GSASIIfpaGUI.MakeSimSizer(G2frame, dlg)[source]

Create a GUI to get simulation with parameters for Fundamental Parameters fitting.

Parameters:

dlg (wx.Window) – Frame or Dialog where GUI will appear

Returns:

a sizer with the GUI controls

GSASIIfpaGUI.MakeTopasFPASizer(G2frame, FPdlg, SetButtonStatus)[source]

Create a GUI with parameters for the NIST XRD Fundamental Parameters Code. Parameter input is modeled after Topas input parameters.

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

  • FPdlg (wx.Window) – Frame or Dialog where GUI will appear

  • SetButtonStatus – a callback function to call to see what buttons in this windows can be enabled. Called with done=True to trigger closing the parent window as well.

Returns:

a sizer with the GUI controls

GSASIIfpaGUI.NISTparms = {}

Parameters in a nested dict, with an entry for each concolutor. Entries in those dicts have values in SI units (of course). NISTparms can be can be input directly or can be from created from parmDict by XferFPAsettings()

GSASIIfpaGUI.SetCu2Wave()[source]

Set the parameters to the two-line Cu K alpha 1+2 spectrum

GSASIIfpaGUI.SetCu6wave()[source]

Set the emission parameters to the NIST six-line Cu K alpha spectrum

GSASIIfpaGUI.SetMonoWave()[source]

Eliminates the short-wavelength line from the six-line Cu K alpha spectrum when incident beam mono; resets it to 6 if no mono

GSASIIfpaGUI.XferFPAsettings(InpParms)[source]

convert Topas-type parameters to SI units for NIST and place in a dict sorted according to use in each convoluter

Parameters:

InpParms (dict) – a dict with Topas-like parameters, as set in MakeTopasFPASizer()

Returns:

a nested dict with global parameters and those for each convolution

GSASIIfpaGUI.doFPAcalc(NISTpk, ttArr, twotheta, calcwid, step)[source]

Compute a single peak using a NIST profile object

Parameters:
  • NISTpk (object) – a peak profile computational object from the NIST XRD Fundamental Parameters Code, typically established from a call to SetupFPAcalc()

  • ttArr (np.Array) – an evenly-spaced grid of two-theta points (degrees)

  • twotheta (float) – nominal center of peak (degrees)

  • calcwid (float) – width to perform convolution (degrees)

  • step (float) – step size

GSASIIfpaGUI.parmDict = {'int': {0: 0.58384351, 1: 0.2284605, 2: 0.11258773, 3: 0.07077796, 4: 0.0043303, 5: 0.00208613}, 'lwidth': {0: 0.436, 1: 0.487, 2: 0.63, 3: 0.558, 4: 2.93, 5: 2.93}, 'wave': {0: 1.5405925, 1: 1.5443873, 2: 1.5446782, 3: 1.5410769, 4: 1.53471, 5: 1.53382}}

Parameter dict used for reading Topas-style values. These are converted to SI units and placed into NISTparms

GSASIIfpaGUI.setupFPAcalc()[source]

Create a peak profile object using the NIST XRD Fundamental Parameters Code.

Returns:

a profile object that can provide information on each convolution or compute the composite peak shape.

GSASIIfpaGUI.simParms = {}

Parameters to set range for pattern simulation

GSASIIfpaGUI.writeNIST(filename)[source]

Write the NIST FPA terms into a JSON-like file that can be reloaded in _onReadFPA

6.12. fprime: compute f’ & f”

This module contains GUI routines to calculate and plot real and resonant X-ray scattering factors to 250keV, based on Fortran program of Cromer & Liberman corrected for Kissel & Pratt energy term; Jensen term not included (D. T. Cromer and D. A. Liberman, Acta Cryst. (1981). A37, 267-268.)

6.12.1. fprime Classes & Routines

main Fprime routines Copyright: 2008, Robert B. Von Dreele (Argonne National Laboratory)

class fprime.Fprime(parent)[source]

Creates a frame where input for absorption calculation is supplied

CalcFPPS()[source]

generate set of f’ & f” curves for selected elements does constant delta-lambda/lambda steps over defined range

OnABOUTItems0Menu(event)[source]

Displays the About window

UpDateFPlot(Wave, rePlot=True)[source]

Plot f’ & f” vs wavelength 0.05-3.0A

6.13. Absorb: Compute X-ray Absorption

This module contains GUI routines to calculate X-ray absorption factors to 250keV for cylindrical powder samples with a specified chemical composition and density. Uses same approach as in fprime (D. T. Cromer and D. A. Liberman, Acta Cryst. (1981). A37, 267-268.)

6.13.1. Absorb Classes & Routines

main Absorb routines Copyright: 2009, Robert B. Von Dreele (Argonne National Laboratory)

class Absorb.Absorb(parent)[source]

Creates a frame where input for absorption calculation is supplied

CalcFPPS()[source]

generate f” curves for selected elements does constant delta-lambda/lambda steps over defined range

OnABOUTItems0Menu(event)[source]

Displays the About window

SetSize(x, y, width, height, sizeFlags=SIZE_AUTO)[source]
SetSize(rect) None
SetSize(size) None
SetSize(width, height) None

Sets the size of the window in pixels.

UpDateAbsPlot(Wave, rePlot=True)[source]

Plot mu vs wavelength 0.05-3.0A