\(\renewcommand\AA{\text{Å}}\)
7. GSAS-II GUI Components
These modules are used to create different parts of the GSAS-II graphical user interface (GUI).
7.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.
7.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 GSAS-II data window as well as sets up the menus for each window. There will be one instance of this in the GSAS-II app named as
G2frame.dataWindow
.This creates two panels, where the inner one is the data object in this class, which is scrolled. The outer one (
G2frame.dataWindow.outer
) uses all space in the appropriate part of the window, but defines a sizer at the top and bottom of the window that can be used to place information that will not be scrolled. The inner one is theG2frame.dataWindow
object.Note that before any items are to be placed in either of these panels, one should call:
G2frame.dataWindow.ClearData()
This deletes the contents of the three main sizers used in the panels. Do not delete the sizers for the unscrolled regions at the top and bottom of the outer panel, as they cannot be [easily?] regenerated if deleted.
The sizer for the scrolled panel should be not be reused, though some earlier code may do that.
After the contents of the data window have been created, a call is made to:
G2frame.dataWindow.SetDataSize()
this ensures that the window’s scroll bars are placed properly. Initial GUI creation for the contents of dataWindow is done in :func:`SelectDataTreeItem`(), which is invoked when a selection is made in the data tree selection. This may places items into the dataWindow, but more commonly calls other routeins tht call that.
Routines that are called multiple times to redraw the contents of the data window should call
ClearData()
andSetDataSize()
at the beginning and end of the GUI code, respectively, to clear contents and complete the layout.When placing a widget in the sizer that has its own scrolling e.g.
GSASIIctrlGUI.GSNoteBook
(anything else?) that one widget should be placed in the scrolledpanel sizer using:mainSizer = wx.BoxSizer(wx.VERTICAL) G2frame.dataWindow.SetSizer(mainSizer) mainSizer.Add(G2frame.<obj>,1,wx.EXPAND)
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.
Use of the unscrolled top sizer:
G2DataWindow.topBox
provides access to a Horizontal wx.BoxSizer, where GUI objects can be placed. The parent for these objects should beG2DataWindow.topPanel
. For the unscrolled bottom region of the window, useG2DataWindow.bottomBox
andG2DataWindow.bottomPanel
as parent. Sample code:topSizer = G2frame.dataWindow.topBox parent = G2frame.dataWindow.topPanel topSizer.Add(wx.StaticText(parent,label='Indexing tools'),0,WACV) topSizer.Add((-1,-1),1,wx.EXPAND) topSizer.Add(G2G.HelpButton(parent,helpIndex=G2frame.dataWindow.helpKey))
Menus: The same core menu items are used in all menu bars (defined in
PrefillDataMenu()
andPostfillDataMenu, but different items may be added, depending on what data tree item and in some cases (phases +?) window tab. Menu definitions are performed in :meth:`_initMenus()
. Menus that are needed at all times in GSAS-II are created there with a call sich as:self.ConstraintMenu = wx.MenuBar()
but to reduce the time needed to start GSAS-II initially, most menus are created “on demand”. This is done by defining a routine (named here as
_makemenu()
) and the above definition is replaced with:self.ConstraintMenu = _makemenu
The code that causes a menubar to be displayed (
SetDataMenuBar()
) checks to see if the menubar has been already been created, if so it is displayed, if not the function (the appropriate one of many_makemenu()
routines) is called. This creates and displays the menu.Note, if there is a problem, a call like
wx.CallAfter(G2frame.phaseDisplay.SendSizeEvent)
might be needed. There are some calls to G2frame.dataWindow.SendSizeEvent() or G2frame.dataWindow.outer.SendSizeEvent() that may be doing the same thing.
- 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.
- 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
- 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
- EnableRefineCommand()[source]
Check that phases are connected to histograms - if so then Data/Remove Histogram is enabled
- 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
- 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.
- 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
GSASIIfiles.ExportBaseclass.loadParmDict()
(from the tree) andGSASIIstrMain.Refine()
andGSASIIstrMain.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).
- 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
- OnExportMTZ(event)[source]
exports MTZ file from macromoleculat Reflection Lists in multiple histograms
- OnExpressionCalc(event)[source]
Compute an arbitrary expression (supplied by user) as well as the (statistical) standard uncertainty on that expression.
Uses the
GSASIIexprGUI.ExpressionDialog
to obtain an expression which is evaluated using theGSASIIobj.ExpressionObj
capability. Then the derivative of the expression is computed numerically for every parameter in the covariance matrix. Finally the derivative list is used to find the s.u. on the expression using Ted Prince’s method.
- 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
- 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
- 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
orGSASIIobj.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
- 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
- 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.
- 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
- ReadPowderInstprm(instLines, bank, rd)[source]
Read contents of a GSAS-II (new) .instprm instrument parameter file similar to G2pwdGUI.OnLoad. Uses
GSASIIfiles.ReadInstprm()
to actually read the file. If instprm file has multiple banks (where each has header #Bank n: …, and bank is supplied as None here, this routine (in GUI) uses a dialog for selection. Note that multibank .instprm files are made by a “Save all profile” command in Instrument Parameters.- Parameters:
instLines (list) – contents of GSAS-II parameter file as a list of str; N.B. lines can be concatenated with ‘;’
bank (int) – bank number to use when instprm file has values for multiple banks (noted by headers of ‘#BANK n:…’.). This is ignored for instprm files without those headers. If bank is None with multiple banks, a selection window is shown.
rd (GSASIIobj.ImportPowder) – The reader object that will be read from. Sample parameters are placed here.
- Returns:
Either an instrument parameter dict if OK, or an Error message (str) if read 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).
- SetDataSize()[source]
this routine is a placeholder until all G2frame.SetDataSize calls are replaced by G2frame.dataWindow.SetDataSize
- 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
- init_vars()[source]
initialize default values for GSAS-II “global” variables (saved in main Frame, G2frame)
- 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 SelectDataTreeItemAlso Called in GSASIIphsGUI.UpdatePhaseData by OnTransform callback.
- GSASIIdataGUI.SetDataMenuBar(G2frame, menu=None)[source]
Attach the appropriate menu (a wx.MenuBar object) for the selected data tree item to the system’s menu bar.
To speed startup of the main window, most menu bars are not created at startup of the program, instead, the menu variable is instead initially defined with a reference to routine that is called to create the menu bar. This routine should overwrite the variable that points to the menu bar (so that the routine is called only once) and it should call
GSASII.SetMenuBar()
since the name of the created MenuBar object is not available here.Note that there are some data tree items that do not need their own customized menu bars, for these this routine can be called without a value for the menu argument. This causes the standard, uncustomized, menubar to be used.
- GSASIIdataGUI.TestOldVersions()[source]
Test the versions of required Python packages, etc. Returns a non-empty text string if there are problems.
- 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.3'}, '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 errorsversionDict['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 problemsversionDict['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.
7.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)
7.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’
7.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).
7.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 dictself.data
, which is accessed usingGetData()
.- 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
- GSASIIphsGUI.CheckAddHKLF(G2frame, data)[source]
GUI actions associated with linking a Phase to a HKLF histogram.
This gets called in two routines named OnHklfAdd (one inside
GSASIIphsGUI.UpdatePhaseData()
and the other insideGSASIIddataGUI.MakeHistPhaseWin()
).
- class GSASIIphsGUI.DIFFaXcontrols(parent, ctrls, parms=None)[source]
Solicit items needed to prepare DIFFaX control.dif file
- 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?
- GSASIIphsGUI.SetPhaseWindow(phasePage, mainSizer=None, Scroll=0)[source]
Finish off processing for all items going into a phase notebook page This connects the sizer to the Panel/ScrolledWindow that is assigned as the notebook’s page for a tab.
Note that a wx.ScrolledWindow is used for most tab pages, with the exception of Atoms, drawAtoms, G2frame.MapPeaks and G2frame.PawleyRefl, where a wx.Panel is used with a single Grid inside. This allows the grid to handle scrolling.
When a wx.ScrolledWindows is used, scrolling is turned on here. The optional Scroll parameter is used to restore the scroll position to the previous position so that the window can be redrawn without disruption.
- 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 fromGSASIIdataGUI.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.
- 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.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
7.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).
7.4.1. GSASIIddataGUI Classes & Routines
Routines for Data tab in Phase dataframe follows.
- GSASIIddataGUI.MakeHistPhaseWin(G2frame)[source]
Display Phase/Data (HAP) info from a Hist/Phase tree item. Used when the HAP info is shown as if a top-level entry in the data tree (see the SeparateHistPhaseTreeItem config option). This code is not used when the HAP info is shown in its original location, the Data tab in the Phase info.
- 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
7.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.
7.5.1. GSASIIElemGUI Classes & Routines
Routines for Periodic table wx.Frame follow.
- 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
7.6. GSASIIconstrGUI: Constraint GUI routines
GUI routines to define constraints and rigid bodies.
7.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.
- 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.
- Create(parent, id, evtHandler)[source]
Create the editing control (wx.CheckBox) when cell is opened for edit
- class GSASIIconstrGUI.RBDataTable(rb, onChange)[source]
A Table to support
DragableRBGrid
- 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]
7.7. GSASIIrestrGUI: Restraint GUI routines
GUI Routines used to define restraints.
7.7.1. GSASIIrestrGUI Classes & Routines
Restraint GUI routines follow.
7.8. GSASIIimgGUI: Image GUI
GUI Routines used to control image display and processing
7.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”).
- 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
- 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
- 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.
- 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.displayPhase(G2frame, phList, panel, gsizer, headers, RefreshPlot)[source]
Fills the scrolled panel with the potential phases to display and their plot options
- GSASIIimgGUI.initPhaseOpts(phases)[source]
Make sure that the options for display of partials are all defined
- GSASIIimgGUI.selectPhase(G2frame, calList, RefreshPlot)[source]
Display a dialog with a list of avaliable phases
- Parameters:
G2frame – main GSAS-II window
calList (list) – a list of phases and calibrants that can be selected
RefreshPlot (function) – a callable routine that will redisplay the image
- 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.
7.9. GSASIIpwdGUI: Powder Pattern GUI routines
Used to define GUI controls for the routines that interact with the powder histogram (PWDR) data tree items.
7.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.SetLattice(controls)[source]
impose constraints on lattice constaints and determine the Bravias lattice index (ibrav) as used in cellGUIlist
- 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, ifPick=False)[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.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 or HKLF Reflections data tree item by displaying a table of reflections in the data window.
Note that this is used for Single Xtal even though in pwdGUI.
- 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, callSeaResSelected=False, New=False, showUse=False)[source]
respond to selection of PWDR Unit Cells data tree item.
- Parameters:
G2frame (wx.Frame) – Main GSAS-II window
data (dict) – contents of “Unit Cells List” data tree item
callSeaResSelected (bool) – when True, selects first entry in UnitCellsTable search results table
New (bool)
showUse (bool) – when showUse is False (default) the Show flag is cleared in all search tables. When True, and there is a True value for Show, the flag is set for that in the grid and the row is scrolled into view. This is currently implemented for indexing (Cell Search Results) only.
- 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
7.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()
.
7.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
- 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
- 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, useShow()
to run it and obtain aGSASIIobj.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
- 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.
- OnValidate(event)[source]
Respond to a press of the Validate button or when a variable is associated with a label (in
OnChoice()
)
- 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.
- 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
7.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.
7.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
byXferFPAsettings()
- 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
7.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.)
7.12.1. fprime Classes & Routines
main Fprime routines Copyright: 2008, Robert B. Von Dreele (Argonne National Laboratory)
7.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.)
7.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