\(\renewcommand\AA{\text{Å}}\)
5. GSAS-II Utility Modules
5.1. GSASIIpath: locations & updates
Routines for dealing with file locations, etc.
Determines the location of the compiled (.pyd or .so) libraries.
Interfaces with subversion (svn):
Determine the subversion release number by determining the highest version number
where SetVersionNumber()
is called (best done in every GSASII file).
Other routines will update GSASII from the subversion server if svn can be
found.
Accesses configuration options, as defined in config.py
5.1.1. GSASIIpath Classes & Routines
GSASIIpath
Classes & routines follow
- GSASIIpath.DoNothing()[source]
A routine that does nothing. This is called in place of IPyBreak and pdbBreak except when the debug option is set True in config.py
- GSASIIpath.DownloadG2Binaries(g2home, verbose=True)[source]
Download GSAS-II binaries from appropriate section of the GSAS-II svn repository based on the platform, numpy and Python version
- GSASIIpath.GetBinaryPrefix(pyver=None)[source]
Creates the first part of the binary directory name such as linux_64_p3.9 (where the full name will be linux_64_p3.9_n1.21).
Note that any change made here is also needed in GetBinaryDir in fsource/SConstruct
- GSASIIpath.GetConfigDefault(key)[source]
Return the default value for a config value
- Parameters:
key (str) – a value to be found in the configuration (config_example.py) file
- Returns:
the default value or None
- GSASIIpath.GetConfigValue(key, default=None, getDefault=False)[source]
Return the configuration file value for key or a default value if not present
- Parameters:
key (str) – a value to be found in the configuration (config.py) file
default – a value to be supplied if none is in the config file or the config file is not found. Defaults to None
- Returns:
the value found or the default.
- GSASIIpath.GetRepoUpdatesInBackground()[source]
Wrapper to make sure that
gitGetUpdate()
is called only if git has been used to install GSAS-II.- Returns:
returns a Popen object (see subprocess)
- GSASIIpath.GetVersionNumber()[source]
Obtain a version number for GSAS-II from git, svn or from the files themselves, if no other choice.
This routine was used to get the GSAS-II version from strings placed in files by svn with the version number being the latest number found, gathered by
SetVersionNumber()
(not 100% accurate as the latest version might have files changed that are not tagged by svn or with a call to SetVersionNumber. Post-svn this info will not be reliable, and this mechanism is replaced by a something created with a git hook, file git_verinfo.py (see the git_filters.py file).Before resorting to the approaches above, try to ask git or svn directly.
- Returns:
an int value usually, but a value of ‘unknown’ might occur
- GSASIIpath.HowIsG2Installed()[source]
Determines if GSAS-II was installed with git, svn or none of the above. Result is cached to avoid time needed for multiple calls of this.
- Returns:
a string starting with ‘git’ from git, if installed from the GSAS-II GitHub repository (defined in g2URL), the string is ‘github’, if the post-3/2024 directory structure is in use ‘-rev’ is appended.
or ‘svn’ is installed from an svn repository (assumed as defined in g2home)
or ‘noVCS’ if installed without a connection to a version control system
- GSASIIpath.IPyBreak()
A routine that does nothing. This is called in place of IPyBreak and pdbBreak except when the debug option is set True in config.py
- GSASIIpath.IPyBreak_base(userMsg=None)[source]
A routine that invokes an IPython session at the calling location This routine is only used when debug=True is set in config.py
- GSASIIpath.InstallGitBinary(tarURL, instDir, nameByVersion=False, verbose=True)[source]
Install the GSAS-II binary files into the location specified.
- Parameters:
tarURL (str) – a URL for the tar file.
instDir (str) – location directory to install files. This directory may not exist and will be created if needed.
nameByVersion (bool) – if True, files are put into a subdirectory of instDir, named to match the tar file (with plaform, Python & numpy versions). Default is False, where the binary files are put directly into instDir.
verbose (bool) – if True (default), status messages are printed.
- Returns:
None
- GSASIIpath.LoadConfigFile(filename)[source]
Read a GSAS-II configuration file. Comments (starting with “%”) are removed, as are empty lines
- Parameters:
filename (str) – base file name (such as ‘file.dat’). Files with this name are located from the path and the contents of each are concatenated.
- Returns:
a list containing each non-empty (after removal of comments) line found in every matching config file.
- GSASIIpath.MacRunScript(script)[source]
Start a bash script in a new terminal window. Used on Mac OS X only.
- Parameters:
script (str) – file name for a bash script
- GSASIIpath.MakeByte2str(arg)[source]
Convert output from subprocess pipes (bytes) to str (unicode) in Python 3. In Python 2: Leaves output alone (already str). Leaves stuff of other types alone (including unicode in Py2) Works recursively for string-like stuff in nested loops and tuples.
typical use:
out = MakeByte2str(out)
or:
out,err = MakeByte2str(s.communicate())
- GSASIIpath.SetBinaryPath(printInfo=False, loadBinary=False)[source]
Add location of GSAS-II shared libraries (binaries: .so or .pyd files) to path
This routine must be executed after GSASIIpath is imported and before any other GSAS-II imports are done, since they assume binary files are in path
- Parameters:
printInfo (bool) – When True, information is printed to show has happened (default is False)
loadBinary (bool) – no longer in use. This is now done in
GSASIIdataGUI.ShowVersions()
.
- GSASIIpath.SetConfigValue(parmdict)[source]
Set configuration variables from a dictionary where elements are lists First item in list is the default value and second is the value to use.
- GSASIIpath.SetVersionNumber(RevString)[source]
Set the subversion (svn) version number. No longer in use.
- Parameters:
RevString (str) – something like “$Revision: 5796 $” that is set by subversion when the file is retrieved from subversion.
Place
GSASIIpath.SetVersionNumber("$Revision: 5796 $")
in every python file.
- GSASIIpath.addCondaPkg()[source]
Install the conda API into the current conda environment using the command line, so that the API can be used in the current Python interpreter
Attempts to do this without a shell failed on the Mac because it seems that the environment was inherited; seems to work w/o shell on Windows.
- GSASIIpath.addPrevGPX(fil, cDict)[source]
Add a GPX file to the list of previous files. Move previous names to start of list. Keep most recent five files
- GSASIIpath.commonPath(dir1, dir2)[source]
Check if two directories share a path. Note that paths are considered the same if either directory is a subdirectory of the other, but not if they are in different subdirectories /a/b/c shares a path with /a/b/c/d but /a/b/c/d and /a/b/c/e do not.
- Returns:
True if the paths are common
- GSASIIpath.condaEnvCreate(envname, packageList, force=False)[source]
Create a Python interpreter in a new conda environment. Use this when there is a potential conflict between packages and it would be better to keep the packages separate (which is one of the reasons conda supports environments). Note that conda should be run from the base environment; this attempts to deal with issues if it is not.
Currently, this is used only to install diffpy.PDFfit2.
- Parameters:
envname (str) – the name of the environment to be created. If the environment exists, it will be overwritten only if force is True.
packageList (list) –
a list of conda install create command options, such as:
['python=3.7', 'conda', 'gsl', 'diffpy.pdffit2', '-c', 'conda-forge', '-c', 'diffpy']
force (bool) – if False (default) an error will be generated if an environment exists
- Returns:
(status,msg) where status is True if an error occurs and msg is a string with error information if status is True or the location of the newly-created Python interpreter.
- GSASIIpath.condaInstall(packageList)[source]
Installs one or more packages using the anaconda conda package manager. Can be used to install multiple packages and optionally use channels.
- Parameters:
packageList (list) –
a list of strings with name(s) of packages and optionally conda options. Examples:
packageList=['gsl'] packageList=['-c','conda-forge','wxpython'] packageList=['numpy','scipy','matplotlib']
- Returns:
None if the the command ran normally, or an error message if it did not.
- GSASIIpath.condaTest(requireAPI=False)[source]
Returns True if it appears that Python is being run under Anaconda Python with conda present. Tests for conda environment vars and that the conda package is installed in the current environment.
- Returns:
True, if running under Conda
- GSASIIpath.countDetachedCommits(g2repo=None)[source]
Count the number of commits that have been made since a commit that is containined in the master branch
returns the count and the commit object for the parent commit that connects the current stranded branch to the master branch.
None is returned if no connection is found
- GSASIIpath.dirGitHub(dirlist, orgName='AdvancedPhotonSource', repoName='GSAS-II-Tutorials')[source]
Obtain a the contents of a GitHub repository directory using the GitHub REST API.
- Parameters:
dirlist (str) – a list of sub-directories [‘parent’,’child’,sub’] for parent/child/sub or [] for a file in the top-level directory.
orgName (str) – the name of the GitHub organization
repoName (str) – the name of the GitHub repository
- Returns:
a list of file names or None if the dirlist info does not reference a directory
examples:
dirGitHub([], 'GSASII', 'TutorialTest') dirGitHub(['TOF Sequential Single Peak Fit', 'data'])
The first example will get the contents of the top-level directory for the specified repository
The second example will provide the contents of the “TOF Sequential Single Peak Fit”/data directory.
- GSASIIpath.downloadDirContents(dirlist, targetDir, orgName='AdvancedPhotonSource', repoName='GSAS-II-Tutorials')[source]
Download the entire contents of a directory from a repository on GitHub. Used to download data for a tutorial.
- GSASIIpath.exceptHook(*args)[source]
A routine to be called when an exception occurs. It prints the traceback with fancy formatting and then calls an IPython shell with the environment of the exception location.
This routine is only used when debug=True is set in config.py
- GSASIIpath.findConda()[source]
Determines if GSAS-II has been installed as g2conda or gsas2full with conda located relative to this file. We could also look for conda relative to the python (sys.executable) image, but I don’t want to muck around with python that someone else installed.
- GSASIIpath.fullsplit(fil, prev=None)[source]
recursive routine to split all levels of directory names
- GSASIIpath.getGitBinaryLoc(npver=None, pyver=None, verbose=True)[source]
Identify the best GSAS-II binary download location from the distributions in the latest release section of the github repository on the CPU platform, and Python & numpy versions. The CPU & Python versions must match, but the numpy version may only be close.
- Parameters:
npver (str) – Version number to use for numpy, if None (default) the version is taken from numpy in the current Python interpreter.
pyver (str) – Version number to use for Python, if None (default) the version is taken from the current Python interpreter.
verbose (bool) – if True (default), status messages are printed
- Returns:
a URL for the tar file (success) or None (failure)
- GSASIIpath.getGitBinaryReleases(cache=False)[source]
Retrieves the binaries and download urls of the latest release
- Parameters:
cache (bool) – when cache is True and the binaries file names are retrieved (does not always succeed when done via GitHub Actions), the results are saved in a file for reuse should the retrieval fail. Default is False so the file is not changed.
- Returns:
a URL dict for GSAS-II binary distributions found in the newest release in a GitHub repository. The repo location is defined in global G2binURL.
The dict keys are references to binary distributions, which are named as f”{platform}_p{pver}_n{npver}” where platform is determined in
GSASIIpath.GetBinaryPrefix()
(linux_64, mac_arm, win_64,…) and where pver is the Python version (such as “3.10”) and npver is the numpy version (such as “1.26”).The value associated with each key contains the full URL to download a tar containing that binary distribution.
- GSASIIpath.getIconFile(imgfile)[source]
Looks in either the main GSAS-II install location (old) or subdirectory icons (after reorg) for an icon
- Returns:
the full path for the icon file
- GSASIIpath.getsvnProxy()[source]
Loads a proxy for subversion from the proxyinfo.txt file created by bootstrap.py or File => Edit Proxy…; If not found, then the standard http_proxy and https_proxy environment variables are scanned (see https://docs.python.org/3/library/urllib.request.html#urllib.request.getproxies) with case ignored and that is used.
- GSASIIpath.gitCheckForUpdates(fetch=True, g2repo=None)[source]
Provides a list of the commits made locally and those in the local copy of the repo that have not been applied. Does not provide useful information in the case of a detached Head (see
countDetachedCommits()
for that.)- Parameters:
fetch (bool) – if True (default), updates are copied over from the remote repository (git fetch), before checking for changes.
g2repo (str) – git.Rwpo connecton to GSAS-II installation. If None (default) it will be opened.
- Returns:
a list containing (remotecommits, localcommits, fetched) where
remotecommits is a list of hex hash numbers of remote commits and
localcommits is a list of hex hash numbers of local commits and
fetched is a bool that will be True if the update (fetch) step ran successfully
Note that if the head is detached (GSAS-II has been reverted to an older version) or the branch has been changed, the values for each of the three items above will be None.
- GSASIIpath.gitCountRegressions(g2repo=None)[source]
Count the number of new check ins on the master branch since the head was detached as well as any checkins made on the detached head.
- Returns:
mastercount,detachedcount, where
mastercount is the number of check ins made on the master branch remote repository since the reverted check in was first made.
detachedcount is the number of check ins made locally starting from the detached head (hopefully 0)
If the connection between the current head and the master branch cannot be established, None is returned for both. If the connection from the reverted check in to the newest version (I don’t see how this could happen) then only mastercount will be None.
- GSASIIpath.gitGetUpdate(mode='Background')[source]
Download the latest updates into the local copy of the GSAS-II repository from the remote master, but don’t actually update the GSAS-II files being used. This can be done immediately or in background.
In ‘Background’ mode, a background process is launched. The results from the process are recorded in file in ~/GSASII_bkgUpdate.log (located in %HOME% on Windows). A pointer to the created process is returned.
In ‘immediate’ mode, the update is performed immediately. The function does not return until after the update is downloaded.
- Returns:
In ‘Background’ mode, returns a Popen object (see subprocess). In ‘immediate’ mode nothing is returned.
- GSASIIpath.gitHash2Tags(githash=None, g2repo=None)[source]
Find tags associated with a particular git commit. Note that if githash cannot be located because it does not exist or is not unique, a git.BadName exception is raised.
- Parameters:
githash (str) – hex hash code (abbreviated to as few characters as needed to keep it unique). If None (default), the HEAD is used.
g2repo (str) – git.Rwpo connecton to GSAS-II installation. If None (default) it will be opened.
- Returns:
a list of tags (each a string)
- GSASIIpath.gitHistory(values='tag', g2repo=None, maxdepth=100)[source]
Provides the history of commits to the master, either as tags or hash values
- Parameters:
values (str) – specifies what type of values are returned. If values==’hash’, then hash values or for values==’tag’, a list of list of tag(s).
g2repo (str) – git.Rwpo connecton to GSAS-II installation. If None (default) it will be opened.
- Returns:
a list of str values where each value is a hash for a commit (values==’hash’), for values==’tag’, a list of lists, where a list of tags is provided for each commit. When tags are provided, for any commit that does not have any associated tag(s), that entry is omitted from the list. for values==’both’, a list of lists, where a hash is followed by a list of tags (if any) is provided
- GSASIIpath.gitLookup(repo_path, gittag=None, githash=None)[source]
Return information on a particular checked-in version of GSAS-II.
- Parameters:
repo_path (str) – location where GSAS-II has been installed
gittag (str) – a tag value.
githash (str) – hex hash code (abbreviated to as few characters as needed to keep it unique). If None (default), a tag must be supplied.
- Returns:
either None if the tag/hash is not found or a tuple with four values (hash, tag-list, message,date_time) where
hash (str) is the git checking hash code;
tag-list is a list of tags (typically there will be one or two);
message is the check-in message (str)
date_time is the check-in date as a datetime object
- GSASIIpath.gitStartUpdate(cmdopts)[source]
Update GSAS-II in a separate process, by running this script with the options supplied in the call to this function and then exiting GSAS-II.
- GSASIIpath.gitTag2Hash(gittag, g2repo=None)[source]
Provides the hash number for a git tag. Note that if gittag cannot be located because it does not exist or is too old and is beyond the depth of the local repository, a ValueError exception is raised.
- Parameters:
repo_path (str) – location where GSAS-II has been installed.
gittag (str) – a tag value.
g2repo (str) – git.Rwpo connecton to GSAS-II installation. If None (default) it will be opened.
- Returns:
a str value with the hex hash for the commit.
- GSASIIpath.gitTestGSASII(verbose=True, g2repo=None)[source]
Test a the status of a GSAS-II installation
- Parameters:
verbose (bool) – if True (default), status messages are printed
g2repo (str) – git.Rwpo connecton to GSAS-II installation. If None (default) it will be opened.
- Returns:
istat, with the status of the repository, with one of the following values:
-1: path is not found
-2: no git repository at path
-3: unable to access repository
value&1==1: repository has local changes (uncommitted/stashed)
value&2==2: repository has been regressed (detached head)
value&4==4: repository has staged files
value&8==8: repository has has been switched to non-master branch
value==0: no problems noted
- GSASIIpath.makeScriptShortcut()[source]
Creates a shortcut to GSAS-II in the current Python installation so that “import G2script” (or “import G2script as GSASIIscripting”) can be used without having to add GSASII to the path.
The new shortcut is then tested.
- Returns:
returns the name of the created file if successful. None indicates an error.
- GSASIIpath.pdbBreak()
A routine that does nothing. This is called in place of IPyBreak and pdbBreak except when the debug option is set True in config.py
- GSASIIpath.pipInstall(packageList)[source]
Installs one or more packages using the pip package installer. Use of this should be avoided if conda can be used (see
condaTest()
to test for conda). Can be used to install multiple packages together. One can use pip options, but this is probably not needed.- Parameters:
packageList (list) –
a list of strings with name(s) of packages Examples:
packageList=['gsl'] packageList=['wxpython','matplotlib','scipy'] packageList=[r'\Mac\Home\Scratch\wheels\pygsl-2.3.3-py3-none-any.whl'] packageList=['z:/Scratch/wheels/pygsl-2.3.3-py3-none-any.whl']
- Returns:
None if the the command ran normally, or an error message if it did not.
- GSASIIpath.postURL(URL, postdict, getcookie=None, usecookie=None, timeout=None, retry=2, mode='get')[source]
Posts a set of values as from a web form using the “get” or “post” protocols. If access fails to an https site, the access is retried with http.
- Parameters:
URL (str) – the URL to post; typically something like ‘http://www…/dir/page?’
postdict (dict) – contains keywords and values, such as {‘centrosymmetry’: ‘0’, ‘crystalsystem’: ‘0’, …}
getcookie (dict) – dict to save cookies created in call, or None (default) if not needed.
usecookie (dict) – dict containing cookies to be used in call, or None (default) if not needed.
timeout (int) – specifies a timeout period for the get or post (default is None, which means the timeout period is set by the server). The value when specified is the time in seconds to wait before giving up on the request.
retry (int) – the number of times to retry the request, if it times out. This is only used if timeout is specified. The default is 2. Note that if retry is left at the default value (2), The timeout is increased by 25% for the second try.
mode (str) – either ‘get’ (default) or ‘post’. Determines how the request will be submitted.
- Returns:
a string with the response from the web server or None if access fails.
- GSASIIpath.rawGitHubURL(dirlist, filename, orgName='AdvancedPhotonSource', repoName='GSAS-II-Tutorials', branchname='master')[source]
Create a URL that can be used to view/downlaod the raw version of file in a GitHub repository.
- Parameters:
dirlist (str) – a list of sub-directories [‘parent’,’child’,sub’] for parent/child/sub or [] for a file in the top-level directory.
filename (str) – the name of the file
orgName (str) – the name of the GitHub organization
repoName (str) – the name of the GitHub repository
branchname (str) – the name of the GitHub branch. Defaults to “master”.
- Returns:
a URL-encoded URL
- GSASIIpath.runScript(cmds=[], wait=False, G2frame=None)[source]
run a shell script of commands in an external process
- Parameters:
cmds (list) – a list of str’s, each ietm containing a shell (cmd.exe or bash) command
wait (bool) – if True indicates the commands should be run and then the script should return. If False, then the currently running Python will exit. Default is False
G2frame (wx.Frame) – provides the location of the current .gpx file to be used to restart GSAS-II after running the commands, if wait is False. Default is None which prevents restarting GSAS-II regardless of the value of wait.
- GSASIIpath.svnChecksumPatch(svn, fpath, verstr)[source]
This performs a fix when svn cannot finish an update because of a Checksum mismatch error. This seems to be happening on OS X for unclear reasons.
- GSASIIpath.svnCleanup(fpath='/home/docs/checkouts/readthedocs.org/user_builds/gsas-ii/checkouts/latest/GSASII', verbose=True)[source]
This runs svn cleanup on a selected local directory.
- Parameters:
fpath (str) – path to repository dictionary, defaults to directory where the current file is located
- GSASIIpath.svnFindLocalChanges(fpath='/home/docs/checkouts/readthedocs.org/user_builds/gsas-ii/checkouts/latest/GSASII')[source]
- Returns a list of files that were changed locally. If no files are changed,
the list has length 0
- Parameters:
fpath – path to repository dictionary, defaults to directory where the current file is located
- Returns:
None if there is a subversion error (likely because the path is not a repository or svn is not found)
- GSASIIpath.svnGetFileStatus(fpath='/home/docs/checkouts/readthedocs.org/user_builds/gsas-ii/checkouts/latest/GSASII', version=None)[source]
Compare file status to repository (svn status -u)
- Returns:
updatecount,modcount,locked where updatecount is the number of files waiting to be updated from repository modcount is the number of files that have been modified locally locked is the number of files tagged as locked
- GSASIIpath.svnGetLog(fpath='/home/docs/checkouts/readthedocs.org/user_builds/gsas-ii/checkouts/latest/GSASII', version=None)[source]
Get the revision log information for a specific version of the specified package
- Parameters:
fpath (str) – path to repository dictionary, defaults to directory where the current file is located.
version (int) – the version number to be looked up or None (default) for the latest version.
- Returns:
a dictionary with keys (one hopes) ‘author’, ‘date’, ‘msg’, and ‘revision’
- GSASIIpath.svnGetRev(fpath='/home/docs/checkouts/readthedocs.org/user_builds/gsas-ii/checkouts/latest/GSASII', local=True, verbose=True)[source]
Obtain the version number for the either the last update of the local version or contacts the subversion server to get the latest update version (# of Head).
- Parameters:
fpath (str) – path to repository dictionary, defaults to directory where the current file is located
local (bool) – determines the type of version number, where True (default): returns the latest installed update False: returns the version number of Head on the server
- Returns:
the version number as an str or None if there is a subversion error (likely because the path is not a repository or svn is not found). The error message is placed in global variable svnLastError
- GSASIIpath.svnInstallDir(URL, loadpath)[source]
Load a subversion tree into a specified directory
- Parameters:
URL (str) – the repository URL
loadpath (str) – path to locate files
- GSASIIpath.svnSwitch2branch(branch=None, loc=None, svnHome=None)[source]
Switch to a subversion branch if specified. Switches to trunk otherwise.
- GSASIIpath.svnSwitchDir(rpath, filename, baseURL, loadpath=None, verbose=True)[source]
This performs a switch command to move files between subversion trees. Note that if the files were previously downloaded, the switch command will update the files to the newest version.
- Parameters:
rpath (str) – path to locate files, relative to the GSAS-II installation path (defaults to path2GSAS2)
URL (str) – the repository URL
loadpath (str) – the prefix for the path, if specified. Defaults to path2GSAS2
verbose (bool) – if True (default) diagnostics are printed
- GSASIIpath.svnUpdateDir(fpath='/home/docs/checkouts/readthedocs.org/user_builds/gsas-ii/checkouts/latest/GSASII', version=None, verbose=True)[source]
This performs an update of the files in a local directory from a server.
- Parameters:
fpath (str) – path to repository dictionary, defaults to directory where the current file is located
version – the number of the version to be loaded. Used only cast as a string, but should be an integer or something that corresponds to a string representation of an integer value when cast. A value of None (default) causes the latest version on the server to be used.
- GSASIIpath.svnUpdateProcess(version=None, projectfile=None, branch=None)[source]
perform an update of GSAS-II in a separate python process
- GSASIIpath.svnUpgrade(fpath='/home/docs/checkouts/readthedocs.org/user_builds/gsas-ii/checkouts/latest/GSASII')[source]
This reformats subversion files, which may be needed if an upgrade of subversion is done.
- Parameters:
fpath (str) – path to repository dictionary, defaults to directory where the current file is located
- GSASIIpath.svnVersion(svn=None)[source]
Get the version number of the current subversion executable. The result is cached, as this takes a bit of time to run and is done a fair number of times.
- Returns:
a string with a version number such as “1.6.6” or None if subversion is not found.
5.2. config_example.py: Configuration options
5.2.1. Configuration variables
This file contains optional configuration options for GSAS-II. The variables
in this file can be copied to file config.py, which is imported if present.
Access these variables using GSASIIpath.GetConfigValue()
, which returns
None if the variable is not set. Note that a config.py file need not
be present, but if in use it will typically be found with the GSAS-II source
directory (GSASIIpath.Path2GSAS2) or a directory for local GSAS-II
modifications (~/.G2local/ or /Documents and Settings/<User>/.G2local/).
Note that the contents of config.py is usually changed
using GSASIIctrlGUI.SelectConfigSetting()
.
When defining new config variables for GSAS-II, define them here with a default value: use None or a string for strings, or use integers or real values as defaults to ensure that only values of that type are allowed. Include a doc string after each variable is defined to explain what it does.
If a name ends with a particular keyword, then specialized edit routines are used.
Names ending in _location or _directory are for items
Names ending in _exec for executable files (.exe on windows).
Names ending in _color for colors, to be specified as RGBA values (note that Contour_color is restricted to color maps).
For example:
int_config = 0
float_config = 0.0
string_config = None (or)
string_config = 'value'
- config_example.Arc_mask_azimuth = 10.0
Specifies the default azimuthal range for creation of arc masks. Default is 10.0 degrees 2-theta.
- config_example.Autoint_PollTime = 30.0
Specifies the frequency, in seconds that AutoInt checks for new files. Default is 30 seconds
- config_example.Autoscale_ParmNames = ['userComment2', 'extraInputs\\1\\extraInputs', 'Ion_Chamber_I0']
Gives the possible selection of incident monitor names as found in an image metadata file. Used in AutoIntegration
- config_example.Bkg_color = 'ff0000ff'
The color for plotting the background powder diffraction pattern. Colors are specified as hex RGBA values, as used in Matplotlib (without preceding #). The default is ff0000ff, which sets the color to red.
- config_example.Calc_color = '008000ff'
The color for plotting the computed powder diffraction pattern. Colors are specified as hex RGBA values, as used in Matplotlib (without preceding #). The default is 00ff00ff, which sets the color to green.
- config_example.Clip_on = True
if True then line plots willl be clipped at plot border; if False line plots extend nto white space around plot frme
- config_example.Column_Metadata_directory = None
When specified and when images are read, GSAS-II will read metadata from a 1-ID style .par and a .EXT_lbls (EXT = image extension) or .lbls file. See
GSASIIfiles.readColMetadata()
for information on how this is done.
- config_example.Contour_color = 'GSPaired'
Specifies the color map to be used for contour plots (images, pole figures, etc.) will be applied for new images and if Saved for a new start of GSAS-II
- config_example.DefaultAutoScale = 'userComment2'
DefaultAutoScale selects one of the AutoScale_ParmNames. Used in AutoIntegration
- config_example.Diff_color = '00bfbfff'
The color for plotting the obs-calc powder diffraction pattern. Colors are specified as hex RGBA values, as used in Matplotlib (without preceding #). The default is 00ffffff, which sets the color to cyan.
- config_example.DrawAtoms_default = ''
Allows selection of the default plotting mode for structures in Draw Atoms. The only valid values are: ‘lines’, ‘vdW balls’, ‘sticks’, ‘balls & sticks’, ‘ellipsoids’. %% If a non-valid choice is used (the default) ‘vdW balls’ is used.
- config_example.Enable_logging = False
Set to True to enable use of command logging (under development.)
- config_example.G2RefinementWindow = False
When True a custom progress window is displayed to track the progress of refinements. When False a generic wxpython supplied progress dialog is used.
- config_example.Help_mode = 'browser'
Set to “internal” to use a Python-based web viewer to display help documentation and tutorials. If set to the default (“browser”) the default web browser is used.
- config_example.Image_2theta_max = 50.0
Specifies a default 2-theta maximum used for calibration and integration as the Outer 2-theta value. Will be applied for newly-read images, but if changed the new value will be saved.
- config_example.Image_2theta_min = 5.0
Specifies a default 2-theta minimum used for calibration and integration as the Inner 2-theta value. Will be applied for newly-read images, but if changed the new value will be saved.
- config_example.Image_calibrant = ''
Specifies a default calibrant material for images. Will be applied for newly-read images, but if changed the specified material will be saved.
- config_example.Import_directory = None
Specifies a default location for importing (reading) input files. Will be updated if Save_paths is True. Note that os.path.expanduser is run on this before it is used, so the user’s home directory can be specified with a ‘~’.
- config_example.Instprm_default = False
when True, GSAS-II instprm file are shown as default; when False, old GSAS stype prm, etc files are default
- config_example.Main_Pos = '(100,100)'
Main window location - will be updated & saved when user moves it. If position is outside screen then it will be repositioned to default
- config_example.Main_Size = '(700,450)'
Main window size (width, height) - initially uses wx.DefaultSize but will updated and saved as the user changes the window
- config_example.Movie_fps = 10
Specifies movie frames-per-second; larger number will make smoother modulation movies but larger files.
- config_example.Movie_time = 5
Specifices time in sec for one modulation loop; larger number will give more frames for same fps’
- config_example.Multiprocessing_cores = 0
Specifies the number of cores to use when performing multicore computing. A number less than zero causes the recommended number of cores [using multiprocessing.cpu_count()/2] to be used. Setting this number to 0 or 1 avoids use of the multiprocessing module: all computations are performed in-line.
- config_example.Obs_color = '0000ffff'
The color for plotting the observed powder diffraction pattern. Colors are specified as hex RGBA values, as used in Matplotlib (without preceding #). The default is 0000ffff, which sets the color to blue.
- config_example.PDF_Rmax = 100.0
Maximum radius for G(r) calculations: range is from 10-200A; default is 100A
- config_example.Plot_Pos = '(200,200)'
Plot window location - will be updated & saved when user moves it these widows. If position is outside screen then it will be repositioned to default
- config_example.Plot_Size = '(700,600)'
Plot window size (width, height) - initially uses wx.DefaultSize but will updated and saved as the user changes the window
- config_example.Ref_Colors = 'b r c g m k'
The colors for reflection tick marks by phase. Use one of ‘k’-black, ‘r’-red, ‘b’-blue, ‘g’-green, ‘m’-magenta, ‘c’-cyan for the line colors, or any other valid matplotlib color name or hex code.
- config_example.Ring_mask_thickness = 0.1
Specifies the default thickness for creation of ring and arc masks. Default is 0.1 degrees 2-theta.
- config_example.Save_paths = False
When set to True, the last-used path for saving of .gpx and for importing of input files is saved in the configuration file. Note that since this causes the config.py file to be updated whenever files are saved/imported, any temporary config settings can be saved to disk at that point.
- config_example.SeparateHistPhaseTreeItem = False
When this is set to True, the parameters specific to each histogram and phase together (such as peak shapes & phase fractions) are shown as a 1st-level tree item rather than inside each Phase’s Data tab. After changing this, GSAS-II needs to be restarted for the change to take effect. Default is False.
- config_example.Show_timing = False
If True, shows various timing results.
- config_example.Spot_mask_diameter = 1.0
Specifies the default diameter for creation of spot masks. Default is 1.0 mm
- config_example.Starting_directory = None
Specifies a default location for starting GSAS-II and where .gpx files should be read from. Will be updated if Save_paths is True. Note that os.path.expanduser is run on this before it is used, so the user’s home directory can be specified with a ‘~’.
- config_example.Tick_length = 8.0
Specifies the length of phase tick marks in pixels. Default is 8.
- config_example.Tick_width = 1.0
Specifies the width of phase tick marks in pixels. Fractional values do seem to produce an effect. Default is 1.
- config_example.Transpose = False
Set to True to cause images to be Transposed when read (for code development)
- config_example.Tutorial_location = None
Change this to place tutorials by in a different spot. If None, this defaults to <user>/My Documents/G2tutorials (on windows) or <user>/G2tutorials. If you want to use a different location, this can be set here. To install into the location where GSAS-II is installed, use this:
Tutorial_location = GSASIIpath.path2GSAS2
As another example, to use ~/.G2tutorials do this:
Tutorial_location = '~/.G2tutorials'
Note that os.path.expanduser is run on Tutorial_location before it is used. Also note that GSASIIpath is imported inside config.py; other imports should be avoided.
- config_example.debug = False
Set to True to turn on debugging mode. This enables use of IPython on exceptions and on calls to
GSASIIpath.IPyBreak()
or breakpoint(). Calls toGSASIIpath.pdbBreak()
will invoke pdb at that location. %% If debug is False, calls toGSASIIpath.IPyBreak()
, breakpoint() andGSASIIpath.pdbBreak()
are ignored. %% From inside Spyder, calls to breakpoint() invoke the Spyder debugger, independent of the setting of debug. %% Restart GSAS-II for the setting of debug to take effect.
- config_example.enum_DrawAtoms_default = ['', 'lines', 'vdW balls', 'sticks', 'balls & sticks', 'ellipsoids']
choices for DrawAtoms_default
- config_example.fullIntegrate = True
If True then full image integration is default; False otherwise
- config_example.fullrmc_exec = None
Defines the full path to a Python executable that has been configured with the fullrmc package. If None (the default), GSAS-II will see if fullrmc can be imported into the current Python (which is unlikely to ever work). If that does not work, GSAS-II will search for an executable named fullrmc* (or fullrmc*.exe on Windows) in the Python
sys.path
search path, which includes the GSAS-II binary directory.
- config_example.lastUpdateNotice = 0
Defines the version number for the last update notice that has been shown. This should not need to be changed manually.
- config_example.logging_debug = False
Set to True to enable debug for logging (under development.)
- config_example.pdffit2_exec = None
Defines the full path to a Python executable that has been configured with the PDFfit2 (diffpy) package. If None (the default), GSAS-II will see if PDFfit2 can be imported into the current Python.
- config_example.previous_GPX_files = []
A list of previously used .gpx files
- config_example.show_gpxSize = False
When True, the sizes of the sections of the GPX file are listed when the GPX file is opened. Default is False.
- config_example.svn_exec = None
Defines the full path to a subversion executable. If None (the default), GSAS-II will search for a svn or svn.exe file in the current path or in the location where the current Python is located.
- config_example.wxInspector = False
If set to True, the wxInspector widget is displayed when GSAS-II is started.
5.3. GSASIIElem: functions for element types
5.3.1. GSASIIElem Routines
Routines used to define element settings follow.
- GSASIIElem.BlenResCW(Els, BLtables, wave)[source]
Computes resonant scattering lengths - single wavelength version (CW) returns bo+b’ and b”’
- GSASIIElem.BlenResTOF(Els, BLtables, wave)[source]
Computes resonant scattering lengths - multiple wavelength version (TOF) returns bo+b’ and b”’
- GSASIIElem.CheckElement(El)[source]
Check if element El is in the periodic table
- Parameters:
El (str) – One or two letter element symbol, capitaliztion ignored
- Returns:
True if the element is found
- GSASIIElem.ClosedFormFF(Z, SQ, k, N)[source]
Closed form expressions for FT Slater fxns. IT B Table 1.2.7.4 (not used at present - doesn’t make sense yet)
- Parameters:
Z – element zeta factor
SQ – (sin-theta/lambda)**2
k – int principal Bessel fxn order as in <jk>
N – int power
return: form factor
- GSASIIElem.ComptonFac(El, SQ)[source]
compute Compton scattering factor
- Parameters:
El – element dictionary
SQ – (sin-theta/lambda)**2
- Returns:
compton scattering factor
- GSASIIElem.FPcalc(Orbs, KEv)[source]
Compute real & imaginary resonant X-ray scattering factors
- Parameters:
Orbs – list of orbital dictionaries as defined in GetXsectionCoeff
KEv – x-ray energy in keV
- Returns:
C: (f’,f”,mu): real, imaginary parts of resonant scattering & atomic absorption coeff.
- GSASIIElem.GetBLtable(General)[source]
returns a dictionary of neutron scattering length data for atom types & isotopes found in General
- Parameters:
General (dict) – dictionary of phase info.; includes AtomTypes & Isotopes
- Returns:
BLtable, dictionary of scattering length data; key is atom type
- GSASIIElem.GetEFFtable(atomTypes)[source]
returns a dictionary of electron form factor data for atom types found in atomTypes might not be needed?
- Parameters:
atomTypes (list) – list of atom types
- Returns:
FFtable, dictionary of form factor data; key is atom type
- GSASIIElem.GetEFormFactorCoeff(El)[source]
Read electron form factor coefficients from atomdata.py file
- Parameters:
El (str) – element 1-2 character symbol, case irrevelant
- Returns:
FormFactors: list of form factor dictionaries
Each electrn form factor dictionary is:
Symbol: 4 character element symbol (no valence)
Z: atomic number
fa: 5 A coefficients
fb: 5 B coefficients
- GSASIIElem.GetFFC5(ElSym)[source]
Get 5 term form factor and Compton scattering data
- Parameters:
ElSym – str(1-2 character element symbol with proper case);
- Return El:
dictionary with 5 term form factor & compton coefficients
- GSASIIElem.GetFFtable(atomTypes)[source]
returns a dictionary of form factor data for atom types found in atomTypes
- Parameters:
atomTypes (list) – list of atom types
- Returns:
FFtable, dictionary of form factor data; key is atom type
- GSASIIElem.GetFormFactorCoeff(El)[source]
Read X-ray form factor coefficients from atomdata.py file
- Parameters:
El (str) – element 1-2 character symbol, case irrevelant
- Returns:
FormFactors: list of form factor dictionaries
Each X-ray form factor dictionary is:
Symbol: 4 character element symbol with valence (e.g. ‘NI+2’)
Z: atomic number
fa: 4 A coefficients
fb: 4 B coefficients
fc: C coefficient
- GSASIIElem.GetMFtable(atomTypes, Landeg)[source]
returns a dictionary of magnetic form factor data for atom types found in atomTypes
- Parameters:
atomTypes (list) – list of atom types
Landeg (list) – Lande g factors for atomTypes
- Returns:
FFtable, dictionary of form factor data; key is atom type
- GSASIIElem.GetMagFormFacCoeff(El)[source]
Read magnetic form factor data from atmdata.py
- Parameters:
El – 2 character element symbol
- Returns:
MagFormFactors: list of all magnetic form factors dictionaries for element El.
each dictionary contains:
‘Symbol’:Symbol
‘Z’:Z
‘mfa’: 4 MA coefficients
‘nfa’: 4 NA coefficients
‘mfb’: 4 MB coefficients
‘nfb’: 4 NB coefficients
‘mfc’: MC coefficient
‘nfc’: NC coefficient
- GSASIIElem.GetORBtable(atomTypes)[source]
returns a dictionary of orbital form factor data for atom types found in atomTypes
- Parameters:
atomTypes (list) – list of atom types
- Returns:
ORBtable, dictionary of orbital form factor data; key is atom type
- GSASIIElem.GetXsectionCoeff(El)[source]
Read atom orbital scattering cross sections for fprime calculations via Cromer-Lieberman algorithm
- Parameters:
El – 2 character element symbol
- Returns:
Orbs: list of orbitals each a dictionary with detailed orbital information used by FPcalc
each dictionary is:
‘OrbName’: Orbital name read from file
‘IfBe’ 0/2 depending on orbital
‘BindEn’: binding energy
‘BB’: BindEn/0.02721
‘XSectIP’: 5 cross section inflection points
‘ElEterm’: energy correction term
‘SEdge’: absorption edge for orbital
‘Nval’: 10/11 depending on IfBe
‘LEner’: 10/11 values of log(energy)
‘LXSect’: 10/11 values of log(cross section)
- GSASIIElem.MagScatFac(El, SQ)[source]
compute value of form factor
- Parameters:
El – element dictionary defined in GetFormFactorCoeff
SQ – (sin-theta/lambda)**2
gfac – Lande g factor (normally = 2.0)
- Returns:
real part of form factor
- GSASIIElem.ScatFac(El, SQ)[source]
compute value of form factor
- Parameters:
El – element dictionary defined in GetFormFactorCoeff
SQ – (sin-theta/lambda)**2
- Returns:
real part of form factor
- GSASIIElem.ScatFacDer(El, SQ)[source]
compute derivative of form factor wrt SQ
- Parameters:
El – element dictionary defined in GetFormFactorCoeff
SQ – (sin-theta/lambda)**2
- Returns:
real part of form factor
- GSASIIElem.SetupGeneral(data, dirname)[source]
Initialize the General sections of the Phase tree contents. Should be done after changes to the Atoms array.
Called by routine SetupGeneral (in
GSASIIphsGUI.UpdatePhaseData()
),GSASIIphsGUI.makeIsoNewPhase()
,GSASIImiscGUI.saveNewPhase()
, and inGSASIIscriptable.SetupGeneral()
.
5.4. GSASIIlattice: Unit Cell Computations
Performs lattice-related computations
Note that as used here G is the reciprocal lattice tensor, and g is its inverse, \(G = g^{-1}\), where
\[\begin{split}g = \left( \begin{matrix} a^2 & a b\cos\gamma & a c\cos\beta \\ a b\cos\gamma & b^2 & b c \cos\alpha \\ a c\cos\beta & b c \cos\alpha & c^2 \end{matrix}\right)\end{split}\]
The “A tensor” terms are defined as
\(A = (\begin{matrix} G_{11} & G_{22} & G_{33} & 2G_{12} & 2G_{13} & 2G_{23}\end{matrix})\) and A can be used in this fashion:
\(d^* = \sqrt {A_0 h^2 + A_1 k^2 + A_2 l^2 + A_3 hk + A_4 hl + A_5 kl}\), where
d is the d-spacing, and \(d^*\) is the reciprocal lattice spacing,
\(Q = 2 \pi d^* = 2 \pi / d\).
Note that GSAS-II variables p::Ai
(i = 0, 1,… 5) and p
is a phase number are
used for the Ai values. See A2cell()
, cell2A()
for interconversion between A and
unit cell parameters; cell2Gmat()
Gmat2cell()
for G and cell parameters.
When the hydrostatic/elastic strain coefficients (Dij, \(D_{ij}\)) are used, they are added to the
A tensor terms (Ai, \(A_{i}\)) so that A is redefined
\(A = (\begin{matrix} A_{0} + D_{11} & A_{1} + D_{22} & A_{2} + D_{33} & A_{3} + D_{12} & A_{4} + D_{13} & A_{5} + D_{23}\end{matrix})\). See cellDijFill()
.
Note that GSAS-II variables p:h:Dij
(i,j = 1, 2, 3) and p
is a phase number
and h
a histogram number are used for the Dij values.
5.4.1. GSASIIlattice Classes & Routines
GSASIIlattice
Classes & routines follow
- GSASIIlattice.A2Gmat(A, inverse=True)[source]
Fill real & reciprocal metric tensor (G) from A.
- Parameters:
A – reciprocal metric tensor elements as [G11,G22,G33,2*G12,2*G13,2*G23]
inverse (bool) – if True return both G and g; else just G
- Returns:
reciprocal (G) & real (g) metric tensors (list of two numpy 3x3 arrays)
- GSASIIlattice.A2cell(A)[source]
Compute unit cell constants from A
- Parameters:
A – [G11,G22,G33,2*G12,2*G13,2*G23] G - reciprocal metric tensor
- Returns:
a,b,c,alpha, beta, gamma (degrees) - lattice parameters
- GSASIIlattice.A2invcell(A)[source]
Compute reciprocal unit cell constants from A returns tuple with a*,b*,c*,alpha*, beta*, gamma* (degrees)
- GSASIIlattice.AplusDij(A, Dij, SGData)[source]
returns the A corrected by Dij
- Parameters:
A (list) – reciprocal metric terms A0-A5
Dij (array) – unique Dij values as stored in Hstrain
SGdata (dict) – a symmetry object
- Returns list newA:
A corrected by Dij
- GSASIIlattice.CellAbsorption(ElList, Volume)[source]
Compute unit cell absorption
- Parameters:
ElList (dict) – dictionary of element contents including mu and number of atoms be cell
Volume (float) – unit cell volume
- Returns:
mu-total/Volume
- GSASIIlattice.CellBlock(nCells)[source]
Generate block of unit cells n*n*n on a side; [0,0,0] centered, n = 2*nCells+1 currently only works for nCells = 0 or 1 (not >1)
- GSASIIlattice.CellDijCorr(Cell, SGData, Data, hist)[source]
Returns the cell corrected for Dij values.
- Parameters:
Cell (list) – lattice parameters
SGdata (dict) – a symmetry object
Data (dict) – phase data structure; contains set of Dij values
hist (str) – histogram name
- Returns:
cell corrected for Dij values
- GSASIIlattice.CosAngle(U, V, G)[source]
calculate cos of angle between U & V in generalized coordinates defined by metric tensor G
- Parameters:
U – 3-vectors assume numpy arrays, can be multiple reflections as (N,3) array
V – 3-vectors assume numpy arrays, only as (3) vector
G – metric tensor for U & V defined space assume numpy array
- Returns:
cos(phi)
- GSASIIlattice.CosSinAngle(U, V, G)[source]
calculate sin & cos of angle between U & V in generalized coordinates defined by metric tensor G
- Parameters:
U – 3-vectors assume numpy arrays
V – 3-vectors assume numpy arrays
G – metric tensor for U & V defined space assume numpy array
- Returns:
cos(phi) & sin(phi)
- GSASIIlattice.CrsAng(H, cell, SGData)[source]
Convert HKL to polar coordinates with proper orientation WRT space group point group :param array H: hkls :param list cell: lattice parameters :param dict SGData: space group data :returns arrays phi,beta: polar, azimuthal angles for HKL
- GSASIIlattice.CubicSHarm(L, M, Th, Ph)[source]
Calculation of the cubic harmonics given in Table 3 in M.Kara & K. Kurki-Suonio, Acta Cryt. A37, 201 (1981). For L = 14,20 only for m3m from F.M. Mueller and M.G. Priestley, Phys Rev 148, 638 (1966)
- Parameters:
L (int) – degree of the harmonic (L >= 0)
M (int) – order number [|M| <= L]
Th (float/array) – Azimuthal coordinate 0 <= Th <= 360
Ph (float/array) – Polar coordinate 0<= Ph <= 180
- Returns klm value/array:
cubic harmonics
- GSASIIlattice.Dsp2pos(Inst, dsp)[source]
convert d-spacing to powder pattern position (2-theta or TOF, musec)
- GSASIIlattice.FindNonstandard(controls, Phase)[source]
Find nonstandard setting of magnetic cell that aligns with parent nuclear cell
- Parameters:
controls – list unit cell indexing controls
Phase – dict new magnetic phase data (NB:not G2 phase construction); modified here
- Returns:
None
- GSASIIlattice.GenCellConstraints(Trans, origPhase, newPhase, origA, oSGLaue, nSGLaue, debug=False)[source]
Generate the constraints between two unit cells constants for a phase transformed by matrix Trans.
- Parameters:
Trans (np.array) – a 3x3 direct cell transformation matrix where, Trans = np.array([ [2/3, 4/3, 1/3], [-1, 0, 0], [-1/3, -2/3, 1/3] ]) (for a’ = 2/3a + 4/3b + 1/3c; b’ = -a; c’ = -1/3, -2/3, 1/3)
origPhase (int) – phase id (pId) for original phase
newPhase (int) – phase id for the transformed phase to be constrained from original phase
origA (list) – reciprocal cell (“A*”) tensor (used for debug only)
oSGLaue (dict) – space group info for original phase
nSGLaue (dict) – space group info for transformed phase
debug (bool) – If true, the constraint input is used to compute and print A* and from that the direct cell for the transformed phase.
- GSASIIlattice.GenHBravais(dmin, Bravais, A, cctbx_args=None)[source]
Generate the positionally unique powder diffraction reflections
- Parameters:
dmin – minimum d-spacing in A
Bravais –
lattice type (see GetBraviasNum). Bravais is one of:
0 F cubic
1 I cubic
2 P cubic
3 R hexagonal (trigonal not rhombohedral)
4 P hexagonal
5 I tetragonal
6 P tetragonal
7 F orthorhombic
8 I orthorhombic
9 A orthorhombic
10 B orthorhombic
11 C orthorhombic
12 P orthorhombic
13 I monoclinic
14 A monoclinic
15 C monoclinic
16 P monoclinic
17 P triclinic
A – reciprocal metric tensor elements as [G11,G22,G33,2*G12,2*G13,2*G23]
cctbx_args (dict) –
items defined in CCTBX:
’sg_type’: value from cctbx.sgtbx.space_group_type(symmorphic_sgs[ibrav])
’uctbx_unit_cell’: pointer to
cctbx.uctbx.unit_cell()
’miller_index_generator’: pointer to
cctbx.miller.index_generator()
- Returns:
HKL unique d list of [h,k,l,d,-1] sorted with largest d first
- GSASIIlattice.GenHLaue(dmin, SGData, A)[source]
Generate the crystallographically unique powder diffraction reflections for a lattice and Bravais type
- Parameters:
dmin – minimum d-spacing
SGData –
space group dictionary with at least
’SGLaue’: Laue group symbol: one of ‘-1’,’2/m’,’mmm’,’4/m’,’6/m’,’4/mmm’,’6/mmm’, ‘3m1’, ‘31m’, ‘3’, ‘3R’, ‘3mR’, ‘m3’, ‘m3m’
’SGLatt’: lattice centering: one of ‘P’,’A’,’B’,’C’,’I’,’F’
’SGUniq’: code for unique monoclinic axis one of ‘a’,’b’,’c’ (only if ‘SGLaue’ is ‘2/m’) otherwise an empty string
A – reciprocal metric tensor elements as [G11,G22,G33,2*G12,2*G13,2*G23]
- Returns:
HKL = list of [h,k,l,d] sorted with largest d first and is unique part of reciprocal space ignoring anomalous dispersion
- GSASIIlattice.GenPfHKLs(nMax, SGData, A)[source]
Generate the unique pole figure reflections for a lattice and Bravais type. Min d-spacing=1.0A & no more than nMax returned
- Parameters:
nMax – maximum number of hkls returned
SGData –
space group dictionary with at least
’SGLaue’: Laue group symbol: one of ‘-1’,’2/m’,’mmm’,’4/m’,’6/m’,’4/mmm’,’6/mmm’, ‘3m1’, ‘31m’, ‘3’, ‘3R’, ‘3mR’, ‘m3’, ‘m3m’
’SGLatt’: lattice centering: one of ‘P’,’A’,’B’,’C’,’I’,’F’
’SGUniq’: code for unique monoclinic axis one of ‘a’,’b’,’c’ (only if ‘SGLaue’ is ‘2/m’) otherwise an empty string
A – reciprocal metric tensor elements as [G11,G22,G33,2*G12,2*G13,2*G23]
- Returns:
HKL = list of ‘h k l’ strings sorted with largest d first; no duplicate zones
- GSASIIlattice.GenRBCoeff(sytsym, RBsym, L)[source]
imposes rigid body symmetry on spherical harmonics terms Key problem is noncubic RB symmetries in cubic site symmetries & vice versa. :param str sytsym: atom position site symmetry symbol :param str RBsym: molecular point symmetry symbol :param int L: spherical harmonic order no. :returns list newNames: spherical harmonic term of order L as either C(L,M) or C(L,M)c for cubic terms :returns list newSgns: matching coefficient signs as +/- 1.0
- GSASIIlattice.GenSHCoeff(SGLaue, SamSym, L, IfLMN=True)[source]
Generate spherical harmonics coefficient names for texture :param str SGLaue: Laue symbol :param str SamSym: sample symmetry symbol :param int L: spherical harmonic order no. :param bool IfLMN: if TRUE return sp.harm. name as C(L,M,N); else return C(L,N) :returns coefficient name as C(L,M,N) or C(L,N)
- GSASIIlattice.GenShCoeff(sytsym, L)[source]
Generate spherical harmonic coefficient names for atom site symmetry :param str sytsym: site symmetry or perhaps molecular symmetry :param int L:spherical harmonic order no. :returns list newNames: spherical harmonic term of order L as either C(L,M) or C(L,M)c for cubic terms :returns list newSgns: matching coefficient signs as +/- 1.0
- GSASIIlattice.GenerateCellConstraints()[source]
Generate unit cell constraints for transforming one set of A tensor values to another using symbolic math (requires the sympy package)
Note that this is only used to do the symbolic math needed to generate cell relationships. It is not used normally in GSAS-II.
- GSASIIlattice.GetBraviasNum(center, system)[source]
Determine the Bravais lattice number, as used in GenHBravais
- Parameters:
center – one of: ‘P’, ‘C’, ‘I’, ‘F’, ‘R’ (see SGLatt from GSASIIspc.SpcGroup)
system – one of ‘cubic’, ‘hexagonal’, ‘tetragonal’, ‘orthorhombic’, ‘trigonal’ (for R) ‘monoclinic’, ‘triclinic’ (see SGSys from GSASIIspc.SpcGroup)
- Returns:
a number between 0 and 13 or throws a ValueError exception if the combination of center, system is not found (i.e. non-standard)
- GSASIIlattice.GetKclKsl(L, N, SGLaue, psi, phi, beta)[source]
- This is used for spherical harmonics description of preferred orientation;
cylindrical symmetry only (M=0) and no sample angle derivatives returned
- GSASIIlattice.Gmat2A(G)[source]
Extract A from reciprocal metric tensor (G)
- Parameters:
G – reciprocal metric tensor (3x3 numpy array)
- Returns:
A = [G11,G22,G33,2*G12,2*G13,2*G23]
- GSASIIlattice.Gmat2AB(G)[source]
Computes orthogonalization matrix from reciprocal metric tensor G
- Returns:
tuple of two 3x3 numpy arrays (A,B)
A for crystal to Cartesian transformations (A*x = np.inner(A,x) = X)
B (= inverse of A) for Cartesian to crystal transformation (B*X = np.inner(B,X) = x)
- GSASIIlattice.Gmat2cell(g)[source]
Compute real/reciprocal lattice parameters from real/reciprocal metric tensor (g/G) The math works the same either way.
- Parameters:
G) (g (or) – real (or reciprocal) metric tensor 3x3 array
- Returns:
a,b,c,alpha, beta, gamma (degrees) (or a*,b*,c*,alpha*,beta*,gamma* degrees)
- GSASIIlattice.H2ThPh(H, Bmat, Q)[source]
Convert HKL to spherical polar & azimuth angles
- Parameters:
H (array) – array of hkl as [n,3]
Bmat ([3,3] array) – inv crystal to Cartesian transformation
Q (array) – quaternion for rotation of HKL to new polar axis
- Returns array Th:
HKL azimuth angles
- Returns array Ph:
HKL polar angles
- GSASIIlattice.HKL2SpAng(H, cell, SGData)[source]
Computes spherical coords for hkls; view along 001
- Parameters:
H (array) – arrays of hkl
cell (tuple) – a,b,c, alpha, beta, gamma (degrees)
SGData (dict) – space group dictionary
- Returns:
arrays of r,phi,psi (radius,inclination,azimuth) about 001
- GSASIIlattice.KslCalc(trm, psi, gam)[source]
Compute one angular part term in spherical harmonics :param str trm:sp. harm term name in the form of ‘C(l,m)’ or ‘C(l,m)c’ for cubic :param float/array psi: Azimuthal coordinate 0 <= Th <= 360 :param float/array gam: Polar coordinate 0<= Ph <= 180
- Returns array Ksl:
spherical harmonics angular part for psi,gam pairs
- GSASIIlattice.LaueUnique(Laue, HKLF)[source]
Impose Laue symmetry on hkl
- Parameters:
Laue (str) –
Laue symbol, as below
centrosymmetric Laue groups:
['-1','2/m','112/m','2/m11','mmm','-42m','-4m2','4/mmm','-3','-3m', '-31m','-3m1','6/m','6/mmm','m3','m3m']
noncentrosymmetric Laue groups:
['1','2','211','112','m','m11','11m','222','mm2','m2m','2mm', '4','-4','422','4mm','3','312','321','3m','31m','3m1','6','-6', '622','6mm','-62m','-6m2','23','432','-43m']
HKLF – np.array([[h,k,l,…]]) reflection set to be converted
- Returns:
HKLF new reflection array with imposed Laue symmetry
- GSASIIlattice.LaueUnique2(SGData, refList)[source]
Impose Laue symmetry on hkl
- Parameters:
SGData – space group data from ‘P ‘+Laue
HKLF – np.array([[h,k,l,…]]) reflection set to be converted
- Returns:
HKLF new reflection array with imposed Laue symmetry
- GSASIIlattice.OdfChk(SGLaue, L, M)[source]
finds symmetry rules for spherical harmonic coefficients for Laue groups :param str SGLaue: Laue symbol :param int L: principal harmonic term; only evens are used :param int M: second harmonic term; can be -L <= M <= L :returns True if allowed
- GSASIIlattice.PlaneIntercepts(Amat, H, phase, stack)[source]
find unit cell intercepts for a stack of hkl planes
- GSASIIlattice.Pos2dsp(Inst, pos)[source]
convert powder pattern position (2-theta or TOF, musec) to d-spacing is currently only approximate for EDX data; accurate for others.
- GSASIIlattice.RBChk(sytsym, L, M)[source]
finds symmetry rules for spherical harmonic coefficients for site symmetries :param str sytsym: atom site symmetry symbol :param int L: principal harmonic term L>0 :param int M: second harmonic term; can be -L <= M <= L :returns True if allowed and sign for term NB: not complete for all possible site symmetries! Many are missing Based on Tables 2 & 4 of M. Kara & K. Kurki-Suonio, Acta Cryst. A37, 201-210 (1981).
- GSASIIlattice.RBsymCheck(Atoms, ct, cx, cs, AtLookUp, Amat, RBObjIds, SGData)[source]
Checks members of a rigid body to see if one is a symmetry equivalent of another. If so the atom site frac is set to zero.
- Parameters:
Atoms – atom array as defined in GSAS-II; modified here
ct – int location of atom type in Atoms item
cx – int location of x,y,z,frac in Atoms item
AtLookUp (dict) – atom lookup by Id table
Amat (np.array) – crystal-to-Cartesian transformation matrix
RBObjIds (list) – atom Id belonging to rigid body being tested
SGData (dict) – GSAS-II space group info.
- Returns:
Atoms with modified atom frac entries
- GSASIIlattice.RBsymChk(RBsym, cubic, coefNames, L=18)[source]
imposes rigid body symmetry on spherical harmonics terms Key problem is noncubic RB symmetries in cubic site symmetries & vice versa. :param str RBsym: molecular point symmetry symbol :param bool cubic: True if atom site symmetry is cubic :param list coefNames: sp. harm coefficient names to be checked/converted :param int L: maximum spherical harmonic order no. for cubic generation if needed
- GSASIIlattice.SHarmcal(SytSym, SHFln, psi, gam)[source]
Perform a surface spherical harmonics computation. Presently only used for plotting Note that the the number of gam values must either be 1 or must match psi
- Parameters:
SytSym (str) – sit symmetry - only looking for cubics - remove this
SHFln (dict) – spherical harmonics coefficients; key has L & M
psi (float/array) – Azimuthal coordinate 0 <= Th <= 360
gam (float/array) – Polar coordinate 0<= Ph <= 180
- Returns array SHVal:
spherical harmonics array for psi,gam values
- GSASIIlattice.SamAng(Tth, Gangls, Sangl, IFCoup)[source]
Compute sample orientation angles vs laboratory coord. system
- Parameters:
Tth – Signed theta
Gangls – Sample goniometer angles phi,chi,omega,azmuth
Sangl – Sample angle zeros om-0, chi-0, phi-0
IFCoup – True if omega & 2-theta coupled in CW scan
- Returns:
psi,gam: Sample odf angles dPSdA,dGMdA: Angle zero derivatives
- GSASIIlattice.SphHarmAng(L, M, P, Th, Ph)[source]
Compute spherical harmonics values using scipy.special.sph_harm
- Parameters:
L (int) – degree of the harmonic (L >= 0)
M (int) – order number (|M| <= L)
P (int) – sign flag = -1 or 1
Th (float/array) – Azimuthal coordinate 0 <= Th <= 360
Ph (float/array) – Polar coordinate 0<= Ph <= 180
- Returns ylmp value/array:
as reals
- GSASIIlattice.TOF2dsp(Inst, Pos)[source]
convert powder pattern TOF, musec to d-spacing by successive approximation Pos can be numpy array
- GSASIIlattice.TransformCell(cell, Trans)[source]
Transform lattice parameters by matrix
- Parameters:
cell – list a,b,c,alpha,beta,gamma,(volume)
Trans – array transformation matrix
- Returns:
array transformed a,b,c,alpha,beta,gamma,volume
- GSASIIlattice.TransformPhase(oldPhase, newPhase, Trans, Uvec, Vvec, ifMag, Force=True)[source]
Transform atoms from oldPhase to newPhase M’ is inv(M) does X’ = M(X-U)+V transformation for coordinates and U’ = MUM/det(M) for anisotropic thermal parameters
- Parameters:
oldPhase – dict G2 phase info for old phase
newPhase – dict G2 phase info for new phase; with new cell & space group atoms are from oldPhase & will be transformed
Trans – lattice transformation matrix M
Uvec – array parent coordinates transformation vector U
Vvec – array child coordinate transformation vector V
ifMag – bool True if convert to magnetic phase; if True all nonmagnetic atoms will be removed
- Returns:
newPhase dict modified G2 phase info
- Returns:
atCodes list atom transformation codes
- GSASIIlattice.U6toUij(U6)[source]
Fill matrix (Uij) from U6 = [U11,U22,U33,U12,U13,U23] NB: there is a non numpy version in GSASIIspc: U2Uij
- Parameters:
U6 (list) – 6 terms of u11,u22,…
- Returns:
Uij - numpy [3][3] array of uij
- GSASIIlattice.Uij2Ueqv(Uij, GS, Amat)[source]
returns 1/3 trace of diagonalized U matrix :param Uij: numpy array [Uij] :param GS: Uij too betaij conversion matrix :param Amat: crystal to Cartesian transformation matrix :returns: 1/3 trace of diagonalized U matrix :returns: True if nonpositive-definite; False otherwise
- GSASIIlattice.Uij2betaij(Uij, G)[source]
Convert Uij to beta-ij tensors – stub for eventual completion
- Parameters:
Uij – numpy array [Uij]
G – reciprocal metric tensor
- Returns:
beta-ij - numpy array [beta-ij]
- GSASIIlattice.UijtoU6(U)[source]
Fill vector [U11,U22,U33,U12,U13,U23] from Uij NB: there is a non numpy version in GSASIIspc: Uij2U
- GSASIIlattice.UniqueCellByLaue = [[['m3', 'm3m'], (0,)], [['3R', '3mR'], (0, 3)], [['3', '3m1', '31m', '6/m', '6/mmm', '4/m', '4/mmm'], (0, 2)], [['mmm'], (0, 1, 2)], [['2/ma'], (0, 1, 2, 3)], [['2/mb'], (0, 1, 2, 4)], [['2/mc'], (0, 1, 2, 5)], [['-1'], (0, 1, 2, 3, 4, 5)]]
List the unique cell terms by index for each Laue class
- GSASIIlattice.betaij2Uij(betaij, G)[source]
Convert beta-ij to Uij tensors
:param beta-ij - numpy array [beta-ij] :param G: reciprocal metric tensor :returns: Uij: numpy array [Uij]
- GSASIIlattice.calc_rDsqSS(H, A, vec)[source]
computes 1/d^2 from hklm, reciprocal metric tensor A & k-vector
- GSASIIlattice.calc_rDsqT(H, A, Z, tof, difC)[source]
computes 1/d^2 from hkl & reciprocal metric tensor A with TOF ZERO shift
- GSASIIlattice.calc_rDsqTSS(H, A, vec, Z, tof, difC)[source]
computes 1/d^2 from hklm, reciprocal metric tensor A & k-vector with TOF Z shift
- GSASIIlattice.calc_rDsqZ(H, A, Z, tth, lam)[source]
computes 1/d^2 from hkl & reciprocal metric tensor A with CW ZERO shift
- GSASIIlattice.calc_rDsqZSS(H, A, vec, Z, tth, lam)[source]
computes 1/d^2 from hklm, reciprocal metric tensor A & k-vector with CW Z shift
- GSASIIlattice.calc_rVsq(A)[source]
Compute the square of the reciprocal lattice volume (1/V**2) from A’
- GSASIIlattice.cell2A(cell)[source]
Obtain A = [G11,G22,G33,2*G12,2*G13,2*G23] from lattice parameters
- Parameters:
cell – [a,b,c,alpha,beta,gamma] (degrees)
- Returns:
G reciprocal metric tensor as 3x3 numpy array
- GSASIIlattice.cell2AB(cell, alt=False)[source]
Computes orthogonalization matrix from unit cell constants
- Parameters:
cell (tuple) – a,b,c, alpha, beta, gamma (degrees)
- Returns:
tuple of two 3x3 numpy arrays (A,B) A for crystal to Cartesian transformations A*x = np.inner(A,x) = X B (= inverse of A) for Cartesian to crystal transformation B*X = np.inner(B,X) = x both rounded to 12 places (typically zero terms = +/-10e-6 otherwise)
- GSASIIlattice.cell2Gmat(cell)[source]
Compute real and reciprocal lattice metric tensor from unit cell constants
- Parameters:
cell – tuple with a,b,c,alpha, beta, gamma (degrees)
- Returns:
reciprocal (G) & real (g) metric tensors (list of two numpy 3x3 arrays)
- GSASIIlattice.cellAlbl = ('a', 'b', 'c', 'alpha', 'beta', 'gamma')
ASCII labels for a, b, c, alpha, beta, gamma
- GSASIIlattice.cellDijFill(pfx, phfx, SGData, parmDict)[source]
Returns the filled-out reciprocal cell (A) terms from the parameter dictionaries corrected for Dij.
- Parameters:
pfx (str) – parameter prefix (“n::”, where n is a phase number)
SGdata (dict) – a symmetry object
parmDict (dict) – a dictionary of parameters
- Returns:
A,sigA where each is a list of six terms with the A terms
- GSASIIlattice.cellUlbl = ('a', 'b', 'c', 'α', 'β', 'γ')
unicode labels for a, b, c, alpha, beta, gamma
- GSASIIlattice.cellUnique(SGData)[source]
Returns the indices for the unique A tensor terms based on the Laue class. Any terms that are determined from others or are zero are not included.
- Parameters:
SGdata (dict) – a symmetry object
- Returns:
a list of 0 to 6 terms with indices of the unique A terms
- GSASIIlattice.cellXformRelations = {0: ['1.0*A0*T[0,0]**2', '1.0*A1*T[0,1]**2', '1.0*A2*T[0,2]**2', '1.0*A3*T[0,0]*T[0,1]', '1.0*A4*T[0,0]*T[0,2]', '1.0*A5*T[0,1]*T[0,2]'], 1: ['1.0*A0*T[1,0]**2', '1.0*A1*T[1,1]**2', '1.0*A2*T[1,2]**2', '1.0*A3*T[1,0]*T[1,1]', '1.0*A4*T[1,0]*T[1,2]', '1.0*A5*T[1,1]*T[1,2]'], 2: ['1.0*A0*T[2,0]**2', '1.0*A1*T[2,1]**2', '1.0*A2*T[2,2]**2', '1.0*A3*T[2,0]*T[2,1]', '1.0*A4*T[2,0]*T[2,2]', '1.0*A5*T[2,1]*T[2,2]'], 3: ['2.0*A0*T[0,0]*T[1,0]', '2.0*A1*T[0,1]*T[1,1]', '2.0*A2*T[0,2]*T[1,2]', '1.0*A3*(T[0,0]*T[1,1] + T[1,0]*T[0,1])', '1.0*A4*(T[0,0]*T[1,2] + T[1,0]*T[0,2])', '1.0*A5*(T[0,1]*T[1,2] + T[1,1]*T[0,2])'], 4: ['2.0*A0*T[0,0]*T[2,0]', '2.0*A1*T[0,1]*T[2,1]', '2.0*A2*T[0,2]*T[2,2]', '1.0*A3*(T[0,0]*T[2,1] + T[2,0]*T[0,1])', '1.0*A4*(T[0,0]*T[2,2] + T[2,0]*T[0,2])', '1.0*A5*(T[0,1]*T[2,2] + T[2,1]*T[0,2])'], 5: ['2.0*A0*T[1,0]*T[2,0]', '2.0*A1*T[1,1]*T[2,1]', '2.0*A2*T[1,2]*T[2,2]', '1.0*A3*(T[1,0]*T[2,1] + T[2,0]*T[1,1])', '1.0*A4*(T[1,0]*T[2,2] + T[2,0]*T[1,2])', '1.0*A5*(T[1,1]*T[2,2] + T[2,1]*T[1,2])']}
cellXformRelations provide the constraints on newA[i] values for a new cell generated from oldA[i] values.
- GSASIIlattice.cellZeros(SGData)[source]
Returns a list with the A terms required to be zero based on Laue symmetry
- Parameters:
SGdata (dict) – a symmetry object
- Returns:
A list of six terms where the values are True if the A term must be zero, False otherwise.
- GSASIIlattice.criticalEllipse(prob)[source]
Calculate critical values for probability ellipsoids from probability
- GSASIIlattice.fillgmat(cell)[source]
Compute lattice metric tensor from unit cell constants
- Parameters:
cell – tuple with a,b,c,alpha, beta, gamma (degrees)
- Returns:
3x3 numpy array
- GSASIIlattice.fmtCellConstraints(cellConstr)[source]
Format the cell relationships created in
GenerateCellConstraints()
in a format that can be used to generate constraints.Use:
cXforms = G2lat.fmtCellConstraints(G2lat.GenerateCellConstraints())
Note that this is only used to do the symbolic math needed to generate cell relationships. It is not used normally in GSAS-II.
- GSASIIlattice.getPeakPos(dataType, parmdict, dsp)[source]
convert d-spacing to powder pattern position (2-theta, E or TOF, musec)
- GSASIIlattice.invcell2Gmat(invcell)[source]
- Compute real and reciprocal lattice metric tensor from reciprocal
unit cell constants
- Parameters:
invcell – [a*,b*,c*,alpha*, beta*, gamma*] (degrees)
- Returns:
reciprocal (G) & real (g) metric tensors (list of two 3x3 arrays)
- GSASIIlattice.polfcal(ODFln, SamSym, psi, gam)[source]
Perform a pole figure computation. Note that the the number of gam values must either be 1 or must match psi. Updated for numpy 1.8.0
- GSASIIlattice.prodMGMT(G, Mat)[source]
Transform metric tensor by matrix
- Parameters:
G – array metric tensor
Mat – array transformation matrix
- Returns:
array new metric tensor
- GSASIIlattice.rotdMat(angle, axis=0)[source]
Prepare rotation matrix for angle in degrees about axis(=0,1,2)
- Parameters:
angle – angle in degrees
axis – axis (0,1,2 = x,y,z) about which for the rotation
- Returns:
rotation matrix - 3x3 numpy array
- GSASIIlattice.rotdMat4(angle, axis=0)[source]
Prepare rotation matrix for angle in degrees about axis(=0,1,2) with scaling for OpenGL
- Parameters:
angle – angle in degrees
axis – axis (0,1,2 = x,y,z) about which for the rotation
- Returns:
rotation matrix - 4x4 numpy array (last row/column for openGL scaling)
- GSASIIlattice.sec2HMS(sec)[source]
Convert time in sec to H:M:S string
- Parameters:
sec – time in seconds
- Returns:
H:M:S string (to nearest 100th second)
- GSASIIlattice.selftestlist = []
Defines a list of self-tests
- GSASIIlattice.sortHKLd(HKLd, ifreverse, ifdup, ifSS=False)[source]
sort reflection list on d-spacing; can sort in either order
- Parameters:
HKLd – a list of [h,k,l,d,…];
ifreverse – True for largest d first
ifdup – True if duplicate d-spacings allowed
- Returns:
sorted reflection list
- GSASIIlattice.subVals(expr, A, T)[source]
Evaluate the symbolic expressions by substituting for A0-A5 & Tij
This can be used on the cell relationships created in
GenerateCellConstraints()
like this:Trans = np.array([ [2/3, 4/3, 1/3], [-1, 0, 0], [-1/3, -2/3, 1/3] ]) T = np.linalg.inv(Trans).T print([subVals(i,Aold,T) for i in GenerateCellConstraints()])
- Parameters:
expr (list) – a list of sympy expressions.
A (list) – This is the A* tensor as defined above.
T (np.array) – a 3x3 transformation matrix where, Trans = np.array([ [2/3, 4/3, 1/3], [-1, 0, 0], [-1/3, -2/3, 1/3] ]) (for a’ = 2/3a + 4/3b + 1/3c; b’ = -a; c’ = -1/3, -2/3, 1/3) then T = np.linalg.inv(Trans).T
Note that this is only used to do the symbolic math needed to generate cell relationships. It is not used normally in GSAS-II.
- GSASIIlattice.symInner(M1, M2)[source]
Compute inner product of two square matrices with symbolic processing Use dot product because sympy does not define an inner product primitive
This requires that M1 & M2 be two sympy objects, as created in GenerateCellConstraints().
Note that this is only used to do the symbolic math needed to generate cell relationships. It is not used normally in GSAS-II.
5.5. GSASIIspc: Space Group Computations
Space group interpretation routines. Note that space group information is stored in a Space Group (SGData) object.
5.5.1. GSASIIspc Classes & Routines
GSASIIspc
Classes & routines follow
- GSASIIspc.AllOps(SGData)[source]
Returns a list of all operators for a space group, including those for centering and a center of symmetry
- Parameters:
SGData – from
SpcGroup()
- Returns:
(SGTextList,offsetList,symOpList,G2oprList) where
SGTextList: a list of strings with formatted and normalized symmetry operators.
offsetList: a tuple of (dx,dy,dz) offsets that relate the GSAS-II symmetry operation to the operator in SGTextList and symOpList. these dx (etc.) values are added to the GSAS-II generated positions to provide the positions that are generated by the normalized symmetry operators.
symOpList: a list of tuples with the normalized symmetry operations as (M,T) values (see
SGOps
in the Space Group object)G2oprList: a list with the GSAS-II operations for each symmetry operation as a tuple with (center,mult,opnum,opcode), where center is (0,0,0), (0.5,0,0), (0.5,0.5,0.5),…; where mult is 1 or -1 for the center of symmetry where opnum is the number for the symmetry operation, in
SGOps
(starting with 0) and opcode is mult*(100*icen+j+1).G2opcodes: a list with the name that GSAS-II uses for each symmetry operation (same as opcode, above)
- GSASIIspc.ApplyStringOpsMom(A, SGData, SSGData, Mom)[source]
Applies string operations to modulated magnetic moment components used in drawing Drawing matches Bilbao MVISUALIZE
- GSASIIspc.AtomDxSymFix(Dx, SytSym, CSIX)[source]
Applies site symmetry restrictions to atom position shifts. 1st parameter value of each kind encountered is assumed to be the independent one. Needed for ISODISTORT mode shifts.
- GSASIIspc.CompareSym(symList, sgName=None, SGData=None)[source]
Compare symmetry generated by GSAS-II from a space group name with a list of operators from some other source.
- Parameters:
symList (list) – a list of symmetry operations (such as ‘x,y,z’ or ‘-Y,X,Z’). The code is fairly forgiving in that 1/2-X or X-1/2 or even -X+0.5 can all be accepted. This is typically read from a CIF.
sgName (str) – a space group name. Need not follow GSAS-II convention for spaces, etc (see
GSASIIspc.StandardizeSpcName()
)SGData – a GSAS-II symmetry objectspace group name. Need not follow GSAS-II convention for spaces, etc (see
GSASIIspc.StandardizeSpcName()
)
- GSASIIspc.ElemPosition(SGData)[source]
Under development. Object here is to return a list of symmetry element types and locations suitable for say drawing them. So far I have the element type… getting all possible locations without lookup may be impossible!
- GSASIIspc.GenAtom(XYZ, SGData, All=False, Uij=[], Move=True)[source]
Generates the equivalent positions for a specified coordinate and space group
- Parameters:
XYZ – an array, tuple or list containing 3 elements: x, y & z
SGData – from
SpcGroup()
All – True return all equivalent positions including duplicates; False return only unique positions
Uij – [U11,U22,U33,U12,U13,U23] or [] if no Uij
Move – True move generated atom positions to be inside cell False do not move atoms
- Returns:
[[XYZEquiv],Idup,[UijEquiv],spnflp]
[XYZEquiv] is list of equivalent positions (XYZ is first entry)
Idup = [-][C]SS where SS is the symmetry operator number (1-24), C (if not 0,0,0)
is centering operator number (1-4) and - is for inversion Cell = unit cell translations needed to put new positions inside cell [UijEquiv] - equivalent Uij; absent if no Uij given
+1/-1 for spin inversion of operator - empty if not magnetic
- GSASIIspc.GenHKL(HKL, SGData)[source]
Generates all equivlent reflections including Friedel pairs :param HKL: [h,k,l] must be integral values :param SGData: space group data obtained from SpcGroup :returns: array Uniq: equivalent reflections
- GSASIIspc.GenHKLf(HKL, SGData)[source]
Uses old GSAS Fortran routine genhkl.for
- Parameters:
HKL – [h,k,l] must be integral values for genhkl.for to work
SGData – space group data obtained from SpcGroup
- Returns:
iabsnt,mulp,Uniq,phi
iabsnt = True if reflection is forbidden by symmetry
mulp = reflection multiplicity including Friedel pairs
Uniq = numpy array of equivalent hkl in descending order of h,k,l
phi = phase offset for each equivalent h,k,l
- GSASIIspc.GetCSuinel(siteSym)[source]
returns Uij terms, multipliers, GUI flags & Uiso2Uij multipliers
- GSASIIspc.GetGenSym(SGData)[source]
Get the space group generator symbols :param SGData: from
SpcGroup()
LaueSym = (‘-1’,’2/m’,’mmm’,’4/m’,’4/mmm’,’3R’,’3mR’,’3’,’3m1’,’31m’,’6/m’,’6/mmm’,’m3’,’m3m’) LattSym = (‘P’,’A’,’B’,’C’,’I’,’F’,’R’)
- GSASIIspc.GetHallSpaceGroup(SGData)[source]
Determine the Hall space group symbol for a GSAS-II space group object, if it exists (it will not if non-standard centering is used, perhaps also for other cases). Will return None if not found.
- GSASIIspc.GetLittleGrpOps(SGData, vec)[source]
Find rotation part of operators that leave vec unchanged
- Parameters:
SGData – space group data structure as defined in SpcGroup above.
vec – a numpy array of fractional vector coordinates
- Returns:
Little - list of operators [M,T] that form the little gropu
- GSASIIspc.GetNXUPQsym(siteSym)[source]
The codes XUPQ are for lookup of symmetry constraints for position(X), thermal parm(U) & magnetic moments (P & Q)
- GSASIIspc.Latt2text(Cen)[source]
From lattice centering vectors returns ‘;’ delimited cell centering vectors
- GSASIIspc.MT2text(Opr, reverse=False)[source]
From space group matrix/translation operator returns text version
- GSASIIspc.MagSSText2MTS(Opr, G2=False)[source]
From magnetic super space group cif text returns matrix/translation + spin flip
- GSASIIspc.MagSytSym(SytSym, dupDir, SGData)[source]
site sym operations: 1,-1,2,3,-3,4,-4,6,-6,m need to be marked if spin inversion
- GSASIIspc.MagText2MTS(mcifOpr, CIF=True)[source]
From magnetic space group cif text returns matrix/translation + spin flip
- GSASIIspc.MoveToUnitCell(xyz)[source]
Translates a set of coordinates so that all values are >=0 and < 1
- Parameters:
xyz – a list or numpy array of fractional coordinates
- Returns:
XYZ - numpy array of new coordinates now 0 or greater and less than 1
- GSASIIspc.Muiso2Shkl(muiso, SGData, cell)[source]
this is to convert isotropic mustrain to generalized Shkls
- GSASIIspc.Opposite(XYZ, toler=0.0002)[source]
- Gives opposite corner, edge or face of unit cell for position within tolerance.
Result may be just outside the cell within tolerance
- Parameters:
XYZ – 0 >= np.array[x,y,z] > 1 as by MoveToUnitCell
toler – unit cell fraction tolerance making opposite
- Returns:
XYZ: dict of opposite positions; key=unit cell & always contains XYZ
- GSASIIspc.ParseXYZ(sym)[source]
Parse a set of space group operations, such as ‘-x,-y,-z’ or ‘x-y,z,-x’ etc. into an algebraic form returning a 3x3 matrix, M, and a length 3 vector, O, where the symmetry operation can be applied as
M . (x,y,z) + O
where M is a 3x3 matrix and O is a displacement vector. This is the same form generated by
SpcGroup()
.Note that this code will process offsets either before the coordinate multipliers or after, so that either of these
1/2-y,1/2+x,z or -y+1/2,x-0.5,z
will both be parsed properly. Returns None if a symbol cannot be parsed.
- GSASIIspc.SGErrors(IErr)[source]
Interprets the error message code from SpcGroup. Used in SpaceGroup.
- Parameters:
IErr – see SGError in
SpcGroup()
- Returns:
ErrString - a string with the error message or “Unknown error”
- GSASIIspc.SGPrint(SGData, AddInv=False)[source]
Print the output of SpcGroup in a nicely formatted way. Used in SpaceGroup
- Parameters:
SGData – from
SpcGroup()
- Returns:
SGText - list of strings with the space group details SGTable - list of strings for each of the operations
- GSASIIspc.SGProd(OpA, OpB)[source]
- Form space group operator product. OpA & OpB are [M,V] pairs;
both must be of same dimension (3 or 4). Returns [M,V] pair
- GSASIIspc.SGPtGroup(SGData)[source]
Determine point group of the space group - done after space group symbol has been evaluated by SpcGroup. Only short symbols are allowed
- Parameters:
SGData – from
SpcGroup()
- Returns:
SSGPtGrp & SSGKl (only defaults for Mono & Ortho)
- GSASIIspc.SSChoice(SGData)[source]
Gets the unique set of possible super space groups for a given space group
- GSASIIspc.SSGModCheck(Vec, modSymb, newMod=True)[source]
Checks modulation vector compatibility with supersymmetry space group symbol. if newMod: Superspace group symbol takes precidence & the vector will be modified accordingly
- GSASIIspc.SSGPrint(SGData, SSGData, AddInv=False)[source]
Print the output of SSpcGroup in a nicely formatted way. Used in SSpaceGroup
- Parameters:
SGData – space group data structure as defined in SpcGroup above.
SSGData – from
SSpcGroup()
- Returns:
SSGText - list of strings with the superspace group details SGTable - list of strings for each of the operations
- GSASIIspc.SSMT2text(Opr)[source]
From superspace group matrix/translation operator returns text version
- GSASIIspc.SSpaceGroup(SGSymbol, SSymbol)[source]
Print the output of SSpcGroup in a nicely formatted way.
- Parameters:
SGSymbol – space group symbol with spaces between axial fields.
SSymbol – superspace group symbol extension (string).
- Returns:
nothing
- GSASIIspc.SSpcGroup(SGData, SSymbol)[source]
Determines supersymmetry information from superspace group name; currently only for (3+1) superlattices
- Parameters:
SGData – space group data structure as defined in SpcGroup above (see SGData).
SSymbol – superspace group symbol extension (string) defining modulation direction & generator info.
- Returns:
(SSGError,SSGData)
SGError = 0 for no errors; >0 for errors (see SGErrors below for details)
SSGData - is a dict (see Superspace Group object) with entries:
’SSpGrp’: full superspace group symbol, accidental spaces removed; for display only
’SSGCen’: 4D cell centering vectors [0,0,0,0] at least
’SSGOps’: 4D symmetry operations as [M,T] so that M*x+T = x’
- GSASIIspc.SpaceGroup(SGSymbol)[source]
Print the output of SpcGroup in a nicely formatted way.
- Parameters:
SGSymbol – space group symbol (string) with spaces between axial fields
- Returns:
nothing
- GSASIIspc.SpaceGroupNumber(spcgroup)[source]
Determine the space group number for a space group from H-M name. Will work for non-standard groups insofar as we can normalize – far from perfect.
- GSASIIspc.SpcGroup(SGSymbol)[source]
Determines cell and symmetry information from a short H-M space group name
- Parameters:
SGSymbol – space group symbol (string) with spaces between axial fields
- Returns:
(SGError,SGData)
SGError = 0 for no errors; >0 for errors (see
SGErrors()
for details)SGData - is a dict (see Space Group object) with entries:
’SpGrp’: space group symbol, slightly cleaned up
’SGFixed’: True if space group data can not be changed, e.g. from magnetic cif; otherwise False
’SGGray’: True if 1’ in symbol - gray group for mag. incommensurate phases
’SGLaue’: one of ‘-1’, ‘2/m’, ‘mmm’, ‘4/m’, ‘4/mmm’, ‘3R’, ‘3mR’, ‘3’, ‘3m1’, ‘31m’, ‘6/m’, ‘6/mmm’, ‘m3’, ‘m3m’
’SGInv’: boolean; True if centrosymmetric, False if not
’SGLatt’: one of ‘P’, ‘A’, ‘B’, ‘C’, ‘I’, ‘F’, ‘R’
’SGUniq’: one of ‘a’, ‘b’, ‘c’ if monoclinic, ‘’ otherwise
’SGCen’: cell centering vectors [0,0,0] at least
’SGOps’: symmetry operations as [M,T] so that M*x+T = x’
’SGSys’: one of ‘triclinic’, ‘monoclinic’, ‘orthorhombic’, ‘tetragonal’, ‘rhombohedral’, ‘trigonal’, ‘hexagonal’, ‘cubic’
’SGPolax’: one of ‘ ‘, ‘x’, ‘y’, ‘x y’, ‘z’, ‘x z’, ‘y z’, ‘xyz’, ‘111’ for arbitrary axes
’SGPtGrp’: one of 32 point group symbols (with some permutations), which is filled by SGPtGroup, is external (KE) part of supersymmetry point group
’SSGKl’: default internal (Kl) part of supersymmetry point group; modified in supersymmetry stuff depending on chosen modulation vector for Mono & Ortho
’BNSlattsym’: BNS lattice symbol & cenering op - used for magnetic structures
- GSASIIspc.StandardizeSpcName(spcgroup)[source]
Accept a spacegroup name where spaces may have not been used in the names according to the GSAS convention (spaces between symmetry for each axis) and return the space group name as used in GSAS
- GSASIIspc.StringOpsProd(A, B, SGData)[source]
Find A*B where A & B are in strings ‘-’ + ‘100*c+n’ + ‘+ijk’ where ‘-’ indicates inversion, c(>0) is the cell centering operator, n is operator number from SgOps and ijk are unit cell translations (each may be <0). Should return resultant string - C. SGData - dictionary using entries:
‘SGCen’: cell centering vectors [0,0,0] at least
‘SGOps’: symmetry operations as [M,T] so that M*x+T = x’
- GSASIIspc.SytSym(XYZ, SGData)[source]
Generates the number of equivalent positions and a site symmetry code for a specified coordinate and space group
- Parameters:
XYZ – an array, tuple or list containing 3 elements: x, y & z
SGData – from SpcGroup
- Returns:
a four element tuple:
The 1st element is a code for the site symmetry (see GetKNsym)
The 2nd element is the site multiplicity
Ndup number of overlapping operators
dupDir Dict - dictionary of overlapping operators
- GSASIIspc.TextOps(text, table, reverse=False)[source]
Makes formatted operator list :param text,table: arrays of text made by SGPrint :param reverse: True for x+1/2 form; False for 1/2+x form :returns: OpText: full list of symmetry operators; one operation per line generally printed to console for use via cut/paste in other programs, but could be used for direct input
- GSASIIspc.UpdateSytSym(Phase)[source]
Update site symmetry/site multiplicity after space group/BNS lattice change
- GSASIIspc.altSettingOrtho = {}
A dictionary of alternate settings for orthorhombic unit cells
- GSASIIspc.checkHKLextc(HKL, SGData)[source]
Checks if reflection extinct - does not check centering
- Parameters:
HKL – [h,k,l]
SGData – space group data obtained from SpcGroup
- Returns:
True if extinct; False if allowed
- GSASIIspc.checkMagextc(HKL, SGData)[source]
Checks if reflection magnetically extinct; does fullcheck (centering, too) uses algorthm from Gallego, et al., J. Appl. Cryst. 45, 1236-1247 (2012)
- Parameters:
HKL – [h,k,l]
SGData – space group data obtained from SpcGroup; must have magnetic symmetry SpnFlp data
- Returns:
True if magnetically extinct; False if allowed (to match GenHKLf)
- GSASIIspc.fullHM2shortHM(SpcGp)[source]
Accepts a full H-M space group symbol and returns a short H-M symbol that the space group interpreter can translate
- GSASIIspc.offsetNorm(x)[source]
Translate a coordinate (or vector of symmetry offsets) into the range -1/6 < x <= 5/6, matching GSAS-II use.
- GSASIIspc.selftestlist = [<function test0>, <function test1>, <function test2>, <function test3>]
Defines a list of self-tests
- GSASIIspc.sgequiv_2002_orthorhombic = {}
A dictionary of orthorhombic space groups that were renamed in the 2002 Volume A, along with the pre-2002 name. The e designates a double glide-plane
- GSASIIspc.spg2origins = {}
A dictionary of all spacegroups that have 2nd settings; the value is the 1st –> 2nd setting transformation vector as X(2nd) = X(1st)-V, nonstandard ones are included.
- GSASIIspc.spgHall = []
Hall space group symbols indexed by GSAS-II space group name. This is indexed by a key which is generated from the name used in GSAS-II with spaces removed and all letters in lowercase. The value associated with the key consists of a list of two values: the first is the Hall name and the second is a Hermann-Mauguin name. Note that there may be several names used by GSAS-II that map to the same symmetry operators and the same Hall symbol (for example “P 21” and “P 1 21 1” and “P 63/m” and “P 63/m H”). There are also space group names that GSAS-II will accept that do not have Hall symbols (such as “I -1” or “F 21 21 21”).
- GSASIIspc.spgbyNum = []
Space groups indexed by number
- GSASIIspc.spglist = {}
A dictionary of space groups as ordered and named in the pre-2002 International Tables Volume A, except that spaces are used following the GSAS convention to separate the different crystallographic directions. Note that the symmetry codes here will recognize many non-standard space group symbols with different settings. They are ordered by Laue group
5.6. GSASIIfiles: data (non-GUI) I/O routines
Module with miscellaneous routines for input and output from files.
5.6.1. GSASIIfiles Classes & Routines
Code for accessing files, including support for reading and writing instrument parameter files and exporting various types of data files.
This module has some routines that require wxPython, but imports for wx and GSAS-II GUI routines is done on a per-function basis so that this module can be imported for GSASIIscriptable use when wx is not installed.
- GSASIIfiles.CleanupFromZip(label, cleanupList)[source]
Delete files extracted from a zip archive, typically created with
GSASIIctrl.ExtractFileFromZip()
during the data import process.Note that image files should not be deleted as they will be reused every time the image is displayed, but everything else will be saved in the data tree and the file copy is not needed.
- Parameters:
label (str) – for imports, this is the type of file being read
cleanupList (list) – a list of files that have been extracted from the zip archive and can be deleted.
- class GSASIIfiles.ExportBaseclass(G2frame, formatName, extension, longFormatName=None)[source]
Defines a base class for the exporting of GSAS-II results.
This class is subclassed in the various exports/G2export_*.py files. Those files are imported in
GSASIIdataGUI.GSASII._init_Exports()
which defines the appropriate menu items for each one and the .Exporter method is called directly from the menu item.Routines may also define a .Writer method, which is used to write a single file without invoking any GUI objects.
- CloseFile(fp=None)[source]
Close a file opened in OpenFile
- Parameters:
fp (file) – the file object to be closed. If None (default) file object self.fp is closed.
- ExportSelect(AskFile='ask')[source]
Selects histograms or phases when needed. Sets a default file name when requested into self.filename; always sets a default directory in self.dirname.
- Parameters:
AskFile (bool) –
Determines how this routine processes getting a location to store the current export(s).
if AskFile is ‘ask’ (default option), get the name of the file to be written; self.filename and self.dirname are always set. In the case where multiple files must be generated, the export routine should do this based on self.filename as a template.
if AskFile is ‘dir’, get the name of the directory to be used; self.filename is not used, but self.dirname is always set. The export routine will always generate the file name.
if AskFile is ‘single’, get only the name of the directory to be used when multiple items will be written (as multiple files) are used or a complete file name is requested when a single file name is selected. self.dirname is always set and self.filename used only when a single file is selected.
if AskFile is ‘default’, creates a name of the file to be used from the name of the project (.gpx) file. If the project has not been saved, then the name of file is requested. self.filename and self.dirname are always set. In the case where multiple file names must be generated, the export routine should do this based on self.filename.
if AskFile is ‘default-dir’, sets self.dirname from the project (.gpx) file. If the project has not been saved, then a directory is requested. self.filename is not used.
- Returns:
True in case of an error
- GetAtoms(phasenam)[source]
Gets the atoms associated with a phase. Can be used with standard or macromolecular phases
- Parameters:
phasenam (str) – the name for the selected phase
- Returns:
a list of items for eac atom where each item is a list containing: label, typ, mult, xyz, and td, where
label and typ are the atom label and the scattering factor type (str)
mult is the site multiplicity (int)
xyz is contains a list with four pairs of numbers: x, y, z and fractional occupancy and their standard uncertainty (or a negative value)
td is contains a list with either one or six pairs of numbers: if one number it is Uiso and with six numbers it is U11, U22, U33, U12, U13 & U23 paired with their standard uncertainty (or a negative value)
- GetCell(phasenam, unique=False)[source]
Gets the unit cell parameters and their s.u.’s for a selected phase
- Parameters:
phasenam (str) – the name for the selected phase
unique (bool) – when True, only directly refined parameters (a in cubic, a & alpha in rhombohedral cells) are assigned positive s.u. values. Used as True for CIF generation.
- Returns:
cellList,cellSig where each is a 7 element list corresponding to a, b, c, alpha, beta, gamma, volume where cellList has the cell values and cellSig has their uncertainties.
- GetSeqCell(phasenam, data_name)[source]
Gets the unit cell parameters and their s.u.’s for a selected phase and histogram in a sequential fit
- Parameters:
phasenam (str) – the name for the selected phase
data_name (dict) – the sequential refinement parameters for the selected histogram
- Returns:
cellList,cellSig where each is a 7 element list corresponding to a, b, c, alpha, beta, gamma, volume where cellList has the cell values and cellSig has their uncertainties.
- InitExport(event)[source]
Determines the type of menu that called the Exporter and misc initialization.
- MakePWDRfilename(hist)[source]
Make a filename root (no extension) from a PWDR histogram name
- Parameters:
hist (str) – the histogram name in data tree (starts with “PWDR “)
- OpenFile(fil=None, mode='w', delayOpen=False)[source]
Open the output file
- Parameters:
fil (str) – The name of the file to open. If None (default) the name defaults to self.dirname + self.filename. If an extension is supplied, it is not overridded, but if not, the default extension is used.
mode (str) – The mode can ‘w’ to write a file, or ‘a’ to append to it. If the mode is ‘d’ (for debug), output is displayed on the console.
- Returns:
the file object opened by the routine which is also saved as self.fp
- SetSeqRef(data, hist)[source]
Set the exporter to retrieve results from a sequential refinement rather than the main tree
- Write(line)[source]
write a line of output, attaching a line-end character
- Parameters:
line (str) – the text to be written.
- askSaveDirectory()[source]
Ask the user to supply a directory name. Path name is used as the starting point for the next export path search.
- Returns:
a directory name (str) or None if Cancel is pressed
TODO: Can this be replaced with G2G.askSaveDirectory?
- askSaveFile()[source]
Ask the user to supply a file name
- Returns:
a file name (str) or None if Cancel is pressed
- dumpTree(mode='type')[source]
Print out information on the data tree dicts loaded in loadTree. Used for testing only.
- loadParmDict(computeSU=False)[source]
Load the GSAS-II refinable parameters from the tree into a dict (self.parmDict). Update refined values to those from the last cycle and set the uncertainties for the refined parameters in another dict (self.sigDict).
Expands the parm & sig dicts to include values derived from constraints.
This could be made faster for sequential fits as info for each histogram is loaded later when iterating over histograms.
- loadTree()[source]
Load the contents of the data tree into a set of dicts (self.OverallParms, self.Phases and self.Histogram as well as self.powderDict & self.xtalDict)
The childrenless data tree items are overall parameters/controls for the entire project and are placed in self.OverallParms
Phase items are placed in self.Phases
Data items are placed in self.Histogram. The key for these data items begin with a keyword, such as PWDR, IMG, HKLF,… that identifies the data type.
- GSASIIfiles.FormatPadValue(val, maxdigits=None)[source]
Format a float to fit in
maxdigits[0]
spaces with maxdigits[1] after decimal.- Parameters:
val (float) – number to be formatted.
maxdigits (list) – the number of digits & places after decimal to be used for display of the number (defaults to [10,2]).
- Returns:
a string with exactly maxdigits[0] characters (except under error conditions), but last character will always be a space
- GSASIIfiles.FormatSigFigs(val, maxdigits=10, sigfigs=5, treatAsZero=1e-20)[source]
Format a float to use
maxdigits
or fewer digits withsigfigs
significant digits showing (if room allows).- Parameters:
val (float) – number to be formatted.
maxdigits (int) – the number of digits to be used for display of the number (defaults to 10).
sigfigs (int) – the number of significant figures to use, if room allows
treatAsZero (float) – numbers that are less than this in magnitude are treated as zero. Defaults to 1.0e-20, but this can be disabled if set to None.
- Returns:
a string with <= maxdigits characters (I hope).
- GSASIIfiles.FormatValue(val, maxdigits=None)[source]
Format a float to fit in at most
maxdigits[0]
spaces with maxdigits[1] after decimal. Note that this code has been hacked from FormatSigFigs and may have unused sections.- Parameters:
val (float) – number to be formatted.
maxdigits (list) – the number of digits, places after decimal and ‘f’ or ‘g’ to be used for display of the number (defaults to [10,2,’f’]).
- Returns:
a string with <= maxdigits characters (usually).
- GSASIIfiles.FormulaEval(string)[source]
Evaluates a algebraic formula into a float, if possible. Works properly on fractions e.g. 2/3 only with python 3.0+ division.
Expressions such as 2/3, 3*pi, sin(45)/2, 2*sqrt(2), 2**10 can all be evaluated.
- Parameters:
string (str) – Character string containing a Python expression to be evaluated.
- Returns:
the value for the expression as a float or None if the expression does not evaluate to a valid number.
- GSASIIfiles.G2Print(*args, **kwargs)[source]
Print with filtering based level of output (see
G2SetPrintLevel()
). Use G2Print() as replacement for print().- Parameters:
mode (str) – if specified, this should contain the mode for printing (‘error’, ‘warn’ or anything else). If not specified, the first argument of the print command (args[0]) should contain the string ‘error’ for error messages and ‘warn’ for warning messages (capitalization and additional letters ignored.)
- GSASIIfiles.G2SetPrintLevel(level)[source]
Set the level of output from calls to
G2Print()
, which should be used in place of print() within GSASII. Settings for the mode are ‘all’, ‘warn’, ‘error’ or ‘none’- Parameters:
level (str) – a string used to set the print level, which may be ‘all’, ‘warn’, ‘error’ or ‘none’. Note that capitalization and extra letters in level are ignored, so ‘Warn’, ‘warnings’, etc. will all set the mode to ‘warn’
- GSASIIfiles.G2printLevel = 'all'
This defines the level of output from calls to
GSASIIfiles.G2Print()
, which should be used in place of print() within GSASII where possible. Settings for this are ‘all’, ‘warn’, ‘error’ or ‘none’. Best to change this withG2SetPrintLevel()
.See also
- GSASIIfiles.GetColumnMetadata(reader)[source]
Add metadata to an image from a column-type metadata file using
readColMetadata()
- Parameters:
reader – a reader object from reading an image
- GSASIIfiles.GetImageData(G2frame, imagefile, imageOnly=False, ImageTag=None, FormatName='')[source]
Read a single image with an image importer. This is called to reread an image after it has already been imported with
GSASIIdataGUI.GSASII.OnImportGeneric()
(orGSASIImiscGUI.ReadImages()
in Auto Integration) so it is not necessary to reload metadata.- Parameters:
G2frame (wx.Frame) – main GSAS-II Frame and data object.
imagefile (str) – name of image file
imageOnly (bool) – If True return only the image, otherwise (default) return more (see below)
ImageTag (int/str) – specifies a particular image to be read from a file. First image is read if None (default).
formatName (str) – the image reader formatName
- Returns:
an image as a numpy array or a list of four items: Comments, Data, Npix and the Image, as selected by imageOnly
- GSASIIfiles.ImportErrorMsg(errormsg=None, pkg={})[source]
Store error message(s) from loading importers (usually missing packages. Or, report back all messages, if called with no argument.
- Parameters:
errormsg (str) – a string containing the error message. If not supplied, the function returns the error message(s).
pkg (dict) – a dict where the key is the name of the importer and the value is a list containing the packages that need to be installed to allow the importer to be used.
- Returns:
the error messages as a list (an empty list if there are none), only if errormsg is None (the default).
- GSASIIfiles.LoadExportRoutines(parent, traceback=False)[source]
Routine to locate GSASII exporters. Warns if more than one file with the same name is in the path or if a file is found that is not in the main directory tree.
- GSASIIfiles.LoadImportRoutines(prefix, errprefix=None, traceback=False)[source]
Routine to locate GSASII importers matching a prefix string.
Warns if more than one file with the same name is in the path or if a file is found that is not in the main directory tree.
- GSASIIfiles.PDFWrite(PDFentry, fileroot, PDFsaves, PDFControls, Inst={}, Limits=[])[source]
Write PDF-related data (G(r), S(Q),…) into files, as selected.
- Parameters:
PDFentry (str) – name of the PDF entry in the tree. This is used for comments in the file specifying where it came from; it can be arbitrary
fileroot (str) – name of file(s) to be written. The extension will be ignored.
PDFsaves (list) – flags that determine what type of file will be written: PDFsaves[0], if True writes a I(Q) file with a .iq extension PDFsaves[1], if True writes a S(Q) file with a .sq extension PDFsaves[2], if True writes a F(Q) file with a .fq extension PDFsaves[3], if True writes a G(r) file with a .gr extension PDFsaves[4], if True writes G(r) in a pdfGUI input file with a .gr extension. Note that if PDFsaves[3] and PDFsaves[4] are both True, the pdfGUI overwrites the G(r) file. PDFsaves[5], if True writes F(Q) & g(R) with .fq & .gr extensions overwrites these if selected by option 2, 3 or 4
PDFControls (dict) – The PDF parameters and computed results
Inst (dict) – Instrument parameters from the PDWR entry used to compute the PDF. Needed only when PDFsaves[4] is True.
Limits (list) – Computation limits from the PDWR entry used to compute the PDF. Needed only when PDFsaves[4] is True.
- GSASIIfiles.ReadInstprm(instLines, bank, Sample={})[source]
Read contents of a GSAS-II (new) .instprm instrument parameter file
- 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, the first bank is used. Note that multibank .instprm files are made by a “Save all profile” command in Instrument Parameters.
Sample (dict) – A dict containing sample parameters, typically corresponding to rd.Sample, where rd is a reader object that is being read from. Sample parameters determined by instrument settings or information from the instprm file are placed here.
- Returns:
bank,instdict where bank is the sample parameter set number and instdict is the instrument parameter dict
Note if ‘Type’ is set as Debye-Scherrer or Bragg-Brentano this will be used and will set defaults in the sample parameters. Otherwise, a single-wavelength file will set Debye-Scherrer mode and dual wavelength will set Bragg-Brentano.
- GSASIIfiles.RereadImageData(ImageReaderlist, imagefile, ImageTag=None, FormatName='')[source]
Read a single image with an image importer. This is called to reread an image after it has already been imported, so it is not necessary to reload metadata.
Based on
GetImageData()
which this can replace where imageOnly=True- Parameters:
ImageReaderlist (list) – list of Reader objects for images
imagefile (str) – name of image file
ImageTag (int/str) – specifies a particular image to be read from a file. First image is read if None (default).
formatName (str) – the image reader formatName
- Returns:
an image as a numpy array
- GSASIIfiles.SetPowderInstParms(Iparm, rd)[source]
extracts values from instrument parameters in rd.instdict or in array Iparm. Create and return the contents of the instrument parameter tree entry.
- GSASIIfiles.WriteControls(filename, data)[source]
Write current values to a .imctrl (Image Controls) file
- GSASIIfiles.WriteInstprm(fp, InstPrm, Sample={}, bank=None)[source]
Write the contents of a GSAS-II (new) .instprm instrument parameter file ToDo: use this inside G2frame.OnSave and G2frame.OnSaveAll
- Parameters:
fp (file) – Pointer to open file to be written.
InstPrm (dict) – Instrument parameters
Sample (dict) – Sample parameters (optional)
bank (int) – Bank number. If not None (default), this causes a “#Bank” heading to be placed in the file before the parameters are written.
- GSASIIfiles.evalColMetadataDicts(items, labels, lbldict, keyCols, keyExp, ShowError=False)[source]
Evaluate the metadata for a line in the .par file
- GSASIIfiles.openInNewTerm(project=None, g2script=None, pythonapp='/home/docs/checkouts/readthedocs.org/user_builds/gsas-ii/conda/latest/bin/python')[source]
Open a new and independent GSAS-II session in separate terminal or console window and as a separate process that will continue even if the calling process exits. Intended to work on all platforms.
This could be used to run other scripts inside python other than GSAS-II
- Parameters:
project (str) – the name of an optional parameter to be passed to the script (usually a .gpx file to be opened in a new GSAS-II session)
g2script (str) – the script to be run. If None (default) the GSASII.py file in the same directory as this file will be used.
pythonapp (str) – the Python interpreter to be used. Defaults to sys.executable which is usually what is wanted.
terminal (str) – a name for a preferred terminal emulator
- GSASIIfiles.readColMetadata(imagefile)[source]
Reads image metadata from a column-oriented metadata table (1-ID style .par file). Called by
GetColumnMetadata()
The .par file has any number of columns separated by spaces. The directory for the file must be specified in Config variable
config_example.Column_Metadata_directory
. As an index to the .par file a second “label file” must be specified with the same file root name as the .par file but the extension must be .XXX_lbls (where .XXX is the extension of the image) or if that is not present extension .lbls.- Parameters:
imagefile (str) – the full name of the image file (with extension, directory optional)
- Returns:
a dict with parameter values. Named parameters will have the type based on the specified Python function, named columns will be character strings
The contents of the label file will look like this:
# define keywords filename:lambda x,y: "{}_{:0>6}".format(x,y)|33,34 distance: float | 75 wavelength:lambda keV: 12.398425/float(keV)|9 pixelSize:lambda x: [74.8, 74.8]|0 ISOlikeDate: lambda dow,m,d,t,y:"{}-{}-{}T{} ({})".format(y,m,d,t,dow)|0,1,2,3,4 Temperature: float|53 FreePrm2: int | 34 | Free Parm2 Label # define other variables 0:day 1:month 2:date 3:time 4:year 7:I_ring
- This file contains three types of lines in any order.
Named parameters are evaluated with user-supplied Python code (see subsequent information). Specific named parameters are used to determine values that are used for image interpretation (see table, below). Any others are copied to the Comments subsection of the Image tree item.
Column labels are defined with a column number (integer) followed by a colon (:) and a label to be assigned to that column. All labeled columns are copied to the Image’s Comments subsection.
Comments are any line that does not contain a colon.
Note that columns are numbered starting at zero.
Any named parameter may be defined provided it is not a valid integer, but the named parameters in the table have special meanings, as descibed. The parameter name is followed by a colon. After the colon, specify Python code that defines or specifies a function that will be called to generate a value for that parameter.
Note that several keywords, if defined in the Comments, will be found and placed in the appropriate section of the powder histogram(s)’s Sample Parameters after an integration:
Temperature
,Pressure
,Time
,FreePrm1
,FreePrm2
,FreePrm3
,Omega
,Chi
, andPhi
.After the Python code, supply a vertical bar (|) and then a list of one more more columns that will be supplied as arguments to that function.
Note that the labels for the three FreePrm items can be changed by including that label as a third item with an additional vertical bar. Labels will be ignored for any other named parameters.
The examples above are discussed here:
filename:lambda x,y: "{}_{:0>6}".format(x,y)|33,34
Here the function to be used is defined with a lambda statement:
lambda x,y: "{}_{:0>6}".format(x,y)
This function will use the format function to create a file name from the contents of columns 33 and 34. The first parameter (x, col. 33) is inserted directly into the file name, followed by a underscore (_), followed by the second parameter (y, col. 34), which will be left-padded with zeros to six characters (format directive
:0>6
).When there will be more than one image generated per line in the .par file, an alternate way to generate list of file names takes into account the number of images generated:
lambda x,y,z: ["{}_{:0>6}".format(x,int(y)+i) for i in range(int(z))]
Here a third parameter is used to specify the number of images generated, where the image number is incremented for each image.
distance: float | 75
Here the contents of column 75 will be converted to a floating point number by calling float on it. Note that the spaces here are ignored.
wavelength:lambda keV: 12.398425/float(keV)|9
Here we define an algebraic expression to convert an energy in keV to a wavelength and pass the contents of column 9 as that input energy
pixelSize:lambda x: [74.8, 74.8]|0
In this case the pixel size is a constant (a list of two numbers). The first column is passed as an argument as at least one argument is required, but that value is not used in the expression.
ISOlikeDate: lambda dow,m,d,t,y:"{}-{}-{}T{} ({})".format(y,m,d,t,dow)|0,1,2,3,4
This example defines a parameter that takes items in the first five columns and formats them in a different way. This parameter is not one of the pre-defined parameter names below. Some external code could be used to change the month string (argument
m
) to a integer from 1 to 12.FreePrm2: int | 34 | Free Parm2 Label
In this example, the contents of column 34 will be converted to an integer and placed as the second free-named parameter in the Sample Parameters after an integration. The label for this parameter will be changed to “Free Parm2 Label”.
Pre-defined parameter names
keyword
required
type
Description
filename
yes
str or list
generates the file name prefix for the matching image file (MyImage001 for file /tmp/MyImage001.tif) or a list of file names.
polarization
no
float
generates the polarization expected based on the monochromator angle, defaults to 0.99.
center
no
list of 2 floats
generates the approximate beam center on the detector in mm, such as [204.8, 204.8].
distance
yes
float
generates the distance from the sample to the detector in mm
pixelSize
no
list of 2 floats
generates the size of the pixels in microns such as [200.0, 200.0].
wavelength
yes
float
generates the wavelength in Angstroms
- GSASIIfiles.readColMetadataLabels(lblFil)[source]
Read the .*lbls file and setup for metadata assignments
- GSASIIfiles.sfloat(S)[source]
Convert a string to float. An empty field or a unconvertable value is treated as zero
- GSASIIfiles.trim(val)[source]
Simplify a string containing leading and trailing spaces as well as newlines, tabs, repeated spaces etc. into a shorter and more simple string, by replacing all ranges of whitespace characters with a single space.
- Parameters:
val (str) – the string to be simplified
- Returns:
the (usually) shortened version of the string
5.7. GSASIImpsubs: routines used in multiprocessing
5.7.1. GSASIImpsubs Classes & Routines
The routines here are called either directly when GSAS-II is used without multiprocessing or in separate cores when multiprocessing is used.
These routines are designed to be used in one of two ways:
when multiprocessing is enabled (see global variable useMP) the computational routines are called in separate Python interpreter that is created and then deleted after use.
when useMP is False, these routines are called directly from the main “thread”.
Note that GSASIImpsubs.InitMP()
should be called before any of the other routines
in this module are used.
- GSASIImpsubs.ComputePwdrProfCW(profList)[source]
Compute the peaks profile for a set of CW peaks and add into the yc array
- GSASIImpsubs.ComputePwdrProfCWA(profList)[source]
Compute the peaks profile for a set of TOF peaks and add into the yc array
- GSASIImpsubs.ComputePwdrProfCWB(profList)[source]
Compute the peaks profile for a set of TOF peaks and add into the yc array
- GSASIImpsubs.ComputePwdrProfED(profList)[source]
Compute the peaks profile for a set of TOF peaks and add into the yc array
- GSASIImpsubs.ComputePwdrProfTOF(profList)[source]
Compute the peaks profile for a set of TOF peaks and add into the yc array
- GSASIImpsubs.InitFobsSqGlobals(x1, ratio1, shl1, xB1, xF1, im1, lamRatio1, kRatio1, xMask1, Ka21)[source]
Initialize for the computation of Fobs Squared for powder histograms. Puts lots of junk into the global namespace in this module.
5.8. Module nistlat: NIST*LATTICE cell computations
5.8.1. nistlat Classes & Routines
This implements an interface to the NIST*LATTICE code using the Spring 1991 program version. NIST*LATTICE, “A Program to Analyze Lattice Relationships” was created by Vicky Lynn Karen and Alan D. Mighell (National Institute of Standards and Technology, Materials Science and Engineering Laboratory, Gaithersburg, Maryland 20899.) Minor code modifications made to provide more significant digits for cell reduction matrix terms.
Please cite V. L. Karen and A. D. Mighell, NIST Technical Note 1290 (1991), https://nvlpubs.nist.gov/nistpubs/Legacy/TN/nbstechnicalnote1290.pdf; and V. L. Karen & A. D. Mighell, U.S. Patent 5,235,523, https://patents.google.com/patent/US5235523A/en?oq=5235523 if this module is used.
- nistlat.CellSymSearch(cellin, center, tolerance=[0.2, 0.2, 0.2, 1, 1, 1], mode=0, deltaV=2, output=None)[source]
Search for a higher symmetry lattice related to an input unit cell, and optionally to the supercells and/or subcells with a specified volume ratio to the input cell.
- Parameters:
cellin (list) – six lattice constants as float values
center (str) – cell centering code; one of P/A/B/C/F/I/R Note that ‘R’ is used for rhombohedral lattices in either hexagonal or rhombohedral (primitive) cells
tolerance (list) – comparison tolerances for a, b, c, alpha, beta & gamma (defaults to [0.2,0.2,0.2,1.,1.,1.]
mode (int) –
0: use only input cell,
1: generate supercells,
2: generate subcells
3: generate sub- and supercells
deltaV (int) – volume ratios for sub/supercells if mode != 0 as ratio of original cell to smallest subcell or largest supercell to original cell. Ignored if mode=0. Otherwise should be 2, 3, 4 or 5
output (str) – name of file to write the NIST*LATTICE output. Default is None, which does not produce a file.
- Returns:
a list of processed cells (only one entry in list when mode=0) where for each cell the the following items are included:
conventional input cell;
reduced input cell;
symmetry-generated conventional cell;
symmetry-generated reduced cell;
matrix to convert sym-generated output cell to input conventional cell
- nistlat.CompareCell(cell1, center1, cell2, center2, tolerance=[0.2, 0.2, 0.2, 1, 1, 1], mode='I', vrange=8, output=None)[source]
Search for matrices that relate two unit cells
- Parameters:
cell1 (list) – six lattice constants as float values for 1st cell
center1 (str) – cell centering code for 1st cell; one of P/A/B/C/F/I/R Note that ‘R’ is used for rhombohedral lattices in either hexagonal or rhombohedral (primitive) cells
cell2 (list) – six lattice constants as float values for 2nd cell
center2 (str) – cell centering code for 2nd cell (see center1)
tolerance (list) – comparison tolerances for a, b, c, alpha, beta & gamma (defaults to [0.2,0.2,0.2,1.,1.,1.]
mode (str) – search mode, which should be either ‘I’ or ‘F’ ‘I’ provides searching with integral matrices or ‘F’ provides searching with integral and fractional matrices
vrange (int) – maximum matrix term range. Must be 1 <= vrange <= 10 for mode=’F’ or Must be 1 <= vrange <= 40 for mode=’I’
output (str) – name of file to write the NIST*LATTICE output. Default is None, which does not produce a file.
- Returns:
A list of matrices that match cell1 to cell2 where each entry contains (det, im, m, tol, one2two, two2one) where:
det is the determinant, giving the volume ratio between cells
im relates the reduced cell for cell1 to the reduced cell for cell2
m relates the reduced cell for cell2 to the reduced cell for cell1
- tol shows the quality of agreement, as six differences between the
two reduced cells
one2two: a numpy matrix that transforms cell1 to cell2
two2one: a numpy matrix that transforms cell2 to cell1
- nistlat.ConvCell(redcell)[source]
Converts a reduced cell to a conventional cell
- Parameters:
redcell (list) – unit cell parameters as 3 cell lengths and 3 angles (in degrees)
- Returns:
tuple (cell,center,setting,mat) where:
cell: has the six cell dimensions for the conventional cell;
center: is P/A/B/C/F/I/R;
setting: is ‘ ‘ except for rhombohedral symmetry (center=R), where it will always be H (for hexagonal cell choice);
mat: is the matrix that gives the conventional cell when the reduced cell is multiplied by mat.
- nistlat.ReduceCell(center, cellin, mode=0, deltaV=0, output=None)[source]
Compute reduced cell(s) with NIST*LATTICE
- Parameters:
center (str) – cell centering code; one of P/A/B/C/F/I/R Note that ‘R’ is used for rhombohedral lattices in either hexagonal or rhombohedral (primitive) cells
cellin (list) – six lattice constants as float values
mode (int) –
0: reduction,
1: generate supercells,
2: generate subcells
3: generate sub- and supercells
deltaV (int) – volume ratios for sub/supercells if mode != 0 as ratio of original cell to smallest subcell or largest supercell to original cell. Ignored if mode=0. Otherwise should be 2, 3, 4 or 5
output (str) – name of file to write the NIST*LATTICE output. Default is None, which does not produce a file.
- Returns:
a dict with two items, ‘input’ and ‘output’. The value for ‘input’ is the input cell as (cell,center,setting). The value for ‘output’ is a list of reduced cells of form (d,cell,vol,mat,center,setting). In these:
cell: a list with the six cell dimensions;
center: is as above (always ‘P’ on output);
setting: is ‘ ‘ except for rhombohedral symmetry where it may be R or H for the cell type;
d: is the volume ratio for new cell over input cell;
vol: is volume of output cell
mat: is the matrix that gives the output cell when the input cell is multiplied by mat.
- nistlat.showCell(cell, center='P', setting=' ', *ignored)[source]
show unit cell input or output nicely formatted.
- Parameters:
cell (list) – six lattice constants as float values; a 7th volume value is ignored if present.
center (str) – cell centering code; one of P/A/B/C/F/I/R Note that ‘R’ is used for rhombohedral lattices in either rhombohedral (primitive) or hexagonal cells.
setting (str) – is ‘ ‘ except for rhombohedral symmetry where it will be R or H for the cell type.
- Returns:
a formatted string
- nistlat.uniqCells(cellList)[source]
remove duplicated cells from a cell output list from
ReduceCell()
- Parameters:
cellList (list) – A list of reduced cells where each entry represents a reduced cell as (_,cell,_,_,center,…) where cell has six lattice constants and center is the cell centering code (P/A/B/C/F/I/R).
- Returns:
a list as above, but where each unique cell is listed only once
5.9. ReadMarCCDFrame: Read Mar Files
5.10. G2shapes: Compute SAS particle shapes
Program SHAPES from “A New Algroithm for the Reconstruction of Protein Molecular Envelopes from X-ray Solution Scattering Data”, John Badger, J. Appl. Cryst. (2019) 52, 937-944. (DOI: 10.1107/S1600576719009774) modified to run inside GSAS-II.
5.11. tutorialIndex: index to GSAS-II tutorials
5.11.1. tutorialIndex Contents
A catalog of GSAS-II tutorials with headings. This is the master list of GSAS-II tutorials and must be updated when tutorials are added. Each item has either one or three items. Titles are single item in a list or tuple. Tutorials have four items:
the name of the directory,
the name of the web page,
a title for the tutorial and
a short text description (optional).
Tutorials that depend on a previous tutorial being completed should have the title for the tutorial indented by five spaces.
Note that GSASIIpath.tutorialCatalog
is generated from this table using the
makeGitTutorial.py script (see
https://gsas-ii.readthedocs.io/en/latest/GSASIIscripts.html#other-scripts) in the
GSAS-II tutorials repo (https://github.com/AdvancedPhotonSource/GSAS-II-tutorials) and
which creates the tutorials.html file in that repo.