### Install packages using pip Source: https://gsas-ii.readthedocs.io/en/latest/GSASIIutil.html Examples of passing a list of package names or file paths to the pipInstall function. ```python 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'] ``` -------------------------------- ### Configure SelectEdit1Var parameters Source: https://gsas-ii.readthedocs.io/en/latest/GSASIIGUIr.html Example setup for the SelectEdit1Var function, demonstrating how to map data arrays to labels and refinement flags. ```python array = data labelLst = ['v1','v2'] elemKeysLst = [['v1'], ['v2',0]] refFlgElem = [None, ['v2',1]] * The value for v1 will be in data['v1'] and this cannot be refined while, * The value for v2 will be in data['v2'][0] and its refinement flag is data['v2'][1] ``` -------------------------------- ### Install packages with condaInstall Source: https://gsas-ii.readthedocs.io/en/latest/GSASIIutil.html Examples of passing package lists and optional conda flags to the condaInstall function. ```python packageList=['gsl'] packageList=['-c','conda-forge','wxpython'] packageList=['numpy','scipy','matplotlib'] ``` -------------------------------- ### Initialize and Start GSAS-II GUI Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIGUI.html The main routine handles platform-specific wxPython application setup and invokes the GSAS-II data GUI. ```python #!/usr/bin/env python # -*- coding: utf-8 -*- #GSASIIGUI ''' GSASIIGUI provides a short file that is used to start the GSAS-II GUI. It is usually called from `G2.py` but this routine can also be invoked directly when GSAS-II has been installed into Python. On MacOS, a class, :class:`G2App`, is defined inside :func:`main` that creates a wxPython application. For other platforms ``wx.App()`` is called directly. ''' import sys from . import GSASIIpath __version__ = '5.0.0' gv = GSASIIpath.getSavedVersionInfo() if gv is not None: if len(gv.git_versiontag): __version__ = gv.git_versiontag[1:] elif len(gv.git_tags): __version__ = gv.git_tags[0] elif len(gv.git_prevtags): __version__ = gv.git_prevtags[0] [docs] def main(): '''This routine is called to start the GSAS-II GUI ''' import scipy.optimize # loading here addresses problem with build for wx on Pi import wx # the next line removes the need for pythonw. Thanks to Matt Newville! # appears unneeded from wx 4.2.1 on if sys.platform.lower() == 'darwin': wx.PyApp.IsDisplayAvailable = lambda _: True # importing the following wx modules at the same time as wx seems to # eliminate the "Debug: Adding duplicate image handler for 'Windows bitmap # file'" error message import wx.grid as wg import wx.aui import wx.lib.scrolledpanel as wxscroll import wx.lib.mixins.listctrl as listmix import wx.richtext as wxrt import wx.lib.filebrowsebutton as wxfilebrowse wg,wx.aui,wxscroll,listmix,wxrt,wxfilebrowse,scipy.optimize # avoid unused warning if sys.platform == "darwin": class G2App(wx.App): '''Used to create a wx python application for the GUI for Mac. Customized to implement drop of GPX files onto app. ''' startupMode = True def ClearStartup(self): '''Call this after app startup complete because a Drop event is posted when GSAS-II is initially started. ''' self.startupMode = False def MacOpenFiles(self, filenames): if self.startupMode: return from . import GSASIIfiles for project in filenames: #print("Start GSAS-II with project file "+str(project)) #GSASIIpath.MacStartGSASII(__file__,project) GSASIIfiles.openInNewTerm(project) application = G2App(0) # create the GUI framework else: application = wx.App(0) # create the GUI framework try: GSASIIpath.SetBinaryPath(True) except Exception as msg: print( '''Unable to run with current installation due to lack of binary (compiled) files, please reset or reinstall''') print('\nError:') print(msg) # if GSASIIpath.HowIsG2Installed().startswith('git'): # print('use this command w/gitstrap') sys.exit() # print('Unable to run with current setup, do you want to update to the') # try: # ans = input("latest GSAS-II version? Update ([Yes]/no): ") # except: # ans = 'no' # if ans.strip().lower() == "no": # import sys # print('Exiting') # sys.exit() # print('Updating...') # import GSASIIctrlGUI as G2G # if GSASIIpath.HowIsG2Installed().startswith('git'): # gitCheckUpdates(None) from . import GSASIIdataGUI as G2gd GSASIIpath.InvokeDebugOpts() # debug capability. If a Python file is on the command-line import it if GSASIIpath.GetConfigValue('debug') and len(sys.argv) == 2: import os if os.path.splitext(sys.argv[1])[1] == '.py': print (f'{60*"="}\n"Importing" file {sys.argv[1]}\n{60*"="}') import importlib.util spec = importlib.util.spec_from_file_location('test_module', sys.argv[1]) module = importlib.util.module_from_spec(spec) sys.modules['test_module'] = module spec.loader.exec_module(module) #test_module = module sys.exit() G2gd.GSASIImain(application) # start the GUI if sys.platform == "darwin": wx.CallLater(50,application.ClearStartup) application.MainLoop() if __name__ == '__main__': main() ``` -------------------------------- ### Start GSAS-II GUI via Command Line Source: https://gsas-ii.readthedocs.io/en/latest/GSASII.html Use this command to launch the GSAS-II GUI when the installation directory is already in the Python path. ```bash python -c “from GSASII.GSASIIGUI import main; main()” ``` -------------------------------- ### main(application) Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/G2compare.html Initializes and starts the GSAS-II Compare GUI application. ```APIDOC ## main(application) ### Description Starts up the GSAS-II Compare GUI. It validates the Python environment version and initializes the main window. ### Parameters - **application** (object) - The application instance to be initialized. ### Returns - (wx.Frame) The main top-level window of the application. ``` -------------------------------- ### Install Miniconda and Dependencies Source: https://gsas-ii.readthedocs.io/en/latest/packages.html Commands to install Miniconda, activate the environment, and install required Python packages. ```bash bash ~/Downloads/Miniconda3-latest--x86_64.sh -b -p /loc/pyg2script source /loc/pyg2script/bin/activate conda install numpy scipy pycifrw matplotlib-base pillow h5py hdf5 ``` -------------------------------- ### GSASII.GSASIIpath.pipInstall() Source: https://gsas-ii.readthedocs.io/en/latest/GSASIIutil.html Installs one or more packages using the pip package installer. ```APIDOC ## GSASII.GSASIIpath.pipInstall(packageList) ### Description Installs one or more packages using the pip package installer. Use of this should be avoided if conda can be used. ### Parameters - **packageList** (list) - Required. A list of strings with name(s) of packages to install. ### Returns - **None/string** - None if the command ran normally, or an error message if it did not. ``` -------------------------------- ### Verify GSASIIscriptable installation Source: https://gsas-ii.readthedocs.io/en/latest/GSASIIscriptable.html Test the configuration by importing G2script and displaying version information. ```python import G2script as G2sc print(G2sc.ShowVersions()) ``` -------------------------------- ### GSASII.GSASIIElem.SetupGeneral Source: https://gsas-ii.readthedocs.io/en/latest/GSASIIutil.html Initializes the General sections of the Phase tree. ```APIDOC ## GSASII.GSASIIElem.SetupGeneral(data, dirname) ### Description Initializes the General sections of the Phase tree contents. Should be executed after changes to the Atoms array. ``` -------------------------------- ### Get Repository Updates in Background Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIpath.html Checks if GSAS-II is installed via Git and triggers a background update process. ```python def GetRepoUpdatesInBackground(): '''Get the latest GSAS-II version info. This serves to make sure that :func:`gitGetUpdate` is called only if git has been used to install GSAS-II. :returns: returns a Popen object (see subprocess) ''' if HowIsG2Installed().startswith('git'): return gitGetUpdate(mode='Background') else: return saveGitHubVersion() ``` -------------------------------- ### Initialize Origin Instance and Data Folders Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIpwdplot.html Sets up the Origin application instance and creates a dedicated folder for the refinement data. ```python # Start Origin instance if op and op.oext: sys.excepthook = origin_shutdown_exception_hook # Set Origin instance visibility if op.oext: op.set_show(True) op.new() # Create folder to hold data and graph refinementName = G2frame.Label refinementName = refinementName[17:-4] fldr = op.po.RootFolder.Folders.Add(refinementName) fldr.Activate() ``` -------------------------------- ### Setup sequential refinement Source: https://gsas-ii.readthedocs.io/en/latest/GSASIIscriptable.html Initializes paths and helper functions for setting up a sequential refinement workflow. ```python import os,glob datadir = os.path.expanduser("~/Scratch/SeqTut2019Mar") PathWrap = lambda fil: os.path.join(datadir,fil) ``` -------------------------------- ### Get Current Git Branch Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIpath.html Retrieves the name of the active Git branch for the GSAS-II installation, returning '?' if in a detached head state. ```python [docs] def getG2Branch(): '''Get name of current branch, as named on local computer ''' if HowIsG2Installed().startswith('git'): g2repo = openGitRepo(path2GSAS2) try: return g2repo.active_branch.name except TypeError: # likely on a detached head return '?' ``` -------------------------------- ### Initialize GUI Layout Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIIntPDFtool.html Sets up the bottom button sizer, core count spin control, and initial window configuration. ```python # buttons on bottom sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add((20,-1)) self.btnstart = wx.Button(mnpnl, wx.ID_ANY, "Start") self.btnstart.Bind(wx.EVT_BUTTON, OnStart) sizer.Add(self.btnstart) self.btnreset = wx.Button(mnpnl, wx.ID_ANY, "Reset") self.btnreset.Bind(wx.EVT_BUTTON, OnReset) sizer.Add(self.btnreset) sizer.Add((20,-1),wx.EXPAND,1) sizer.Add(wx.StaticText(mnpnl, wx.ID_ANY,' cores:')) spin = wx.SpinCtrl(mnpnl, wx.ID_ANY,size=(50,-1)) spin.SetRange(1, mp.cpu_count()) # spin.SetRange(0, mp.cpu_count()) # debug spin.SetValue(self.ncores) def _onSpin(event): if event: event.Skip() self.ncores = spin.GetValue() spin.Bind(wx.EVT_SPINCTRL, _onSpin) spin.Bind(wx.EVT_KILL_FOCUS, _onSpin) sizer.Add(spin) sizer.Add((20,-1),wx.EXPAND,1) self.btnclose = wx.Button(mnpnl, wx.ID_ANY, "Exit") self.btnclose.Bind(wx.EVT_BUTTON, OnQuit) self.EnableIntButtons(False) sizer.Add(self.btnclose) sizer.Add((20,-1)) mnsizer.Add(sizer,0,wx.EXPAND|wx.BOTTOM|wx.TOP,5) # finish up window mnpnl.SetSizer(mnsizer) #OnRadioSelect(None) # disable widgets mnsizer.Fit(self) ShowbyMode() if len(sys.argv) > 1: fil = os.path.splitext(sys.argv[1])[0]+'.gpx' if os.path.exists(fil): self.gpxin[3] = fil SetGPXInputFile() showPDFctrls(None) ``` -------------------------------- ### Initialize Integration Output GUI Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIIntPDFtool.html Sets up the static box and sizers for integration output, including directory selection and format checkboxes. ```python # box for output selections mnsizer.Add((-1,15)) lbl = wx.StaticBox(mnpnl, wx.ID_ANY, "Integration output") lblsizr = wx.StaticBoxSizer(lbl, wx.VERTICAL) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(wx.StaticText(mnpnl, wx.ID_ANY,'Write to: '),0,wx.ALIGN_CENTER_VERTICAL) fInp3 = G2G.ValidatedTxtCtrl(mnpnl,self.params,'outdir',notBlank=False,size=(300,-1)) sizer.Add(fInp3,1,wx.EXPAND) btn3 = wx.Button(mnpnl, wx.ID_ANY, "Browse") btn3.Bind(wx.EVT_BUTTON, OnBrowse) sizer.Add(btn3,0,wx.ALIGN_CENTER_VERTICAL) lblsizr.Add(sizer,0,wx.EXPAND) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(wx.StaticText(mnpnl, wx.ID_ANY,'Select format(s):')) for dfmt in sorted(self.fmtlist): sizer.Add((6,2)) # add a bit of extra space fmt = dfmt[1:] if fmt not in self.params['outsel']: self.params['outsel'][fmt] = False btn = G2G.G2CheckBox(mnpnl,dfmt,self.params['outsel'],fmt, OnChange=TestInput) sizer.Add(btn) lblsizr.Add(sizer) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(wx.StaticText(mnpnl, wx.ID_ANY,'Separate dir for each format: ')) self.params['SeparateDir'] = False sizer.Add(G2G.G2CheckBox(mnpnl,'',self.params,'SeparateDir')) lblsizr.Add(sizer) mnsizer.Add(lblsizr,0,wx.EXPAND,1) ``` -------------------------------- ### G2Image Usage Example Source: https://gsas-ii.readthedocs.io/en/latest/GSASIIscriptable.html Demonstrates initializing a project, adding an image, and performing common image processing tasks like calibration and integration. ```python >>> gpx = G2sc.G2Project(newgpx='itest.gpx') >>> imlst = gpx.add_image(idata,fmthint="TIF") >>> imlst[0].loadControls('stdSettings.imctrl') >>> imlst[0].setCalibrant('Si SRM640c') >>> imlst[0].loadMasks('stdMasks.immask') >>> imlst[0].Recalibrate() >>> imlst[0].setControl('outAzimuths',3) >>> pwdrList = imlst[0].Integrate() ``` -------------------------------- ### Configure Tutorial Location Source: https://gsas-ii.readthedocs.io/en/latest/GSASIIutil.html Sets the directory path for tutorial files. ```python Tutorial_location = GSASIIpath.path2GSAS2 ``` ```python Tutorial_location = '~/.G2tutorials' ``` -------------------------------- ### Install packages using pip Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIpath.html Installs packages using the pip installer. It automatically converts conda-style package specifiers to pip-compatible format. ```python def pipInstall(packageList): '''Installs one or more packages using the pip package installer. Use of this should be avoided if conda can be used (see :func:`condaTest` to test for conda). Can be used to install multiple packages together. One can use pip options, but this is probably not needed. :param list packageList: 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. ''' # update conda package specs (pkg=1.2.3) to pip package specs (pkg==1.2.3) # at present no other specifiers are used. for i,val in enumerate(packageList): if '=' in val and '==' not in val: packageList[i] = packageList[i].replace('=','==') try: subprocess.check_call([sys.executable, '-m', 'pip', 'install']+packageList) except Exception as msg: return msg return None ``` -------------------------------- ### Initialize testSytSym GUI Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/testSytSym.html Setup script for the testSytSym module, including environment path configuration and wxPython frame initialization. ```python #testMagSym import sys import os import wx import numpy as np import importlib.util try: importlib.util.find_spec('GSASII.GSASIIGUI') except ModuleNotFoundError: print('GSAS-II not installed in Python; Hacking sys.path') sys.path.insert(0,os.path.dirname(os.path.dirname(__file__))) from GSASII import GSASIIpath GSASIIpath.SetBinaryPath() from GSASII import GSASIIspc as G2spc from GSASII import GSASIIlattice as G2lat from GSASII import GSASIIctrlGUI as G2G from GSASII import GSASIIphsGUI as G2phsGUI try: wx.NewId except AttributeError: wx.NewId = wx.NewIdRef [wxID_FILEEXIT, ] = [wx.NewId() for _init_coll_File_Items in range(1)] WACV = wx.ALIGN_CENTER_VERTICAL [docs] class testSytSym(wx.Frame): def _init_ctrls(self, parent): wx.Frame.__init__(self, name='testSytSym', parent=parent, size=[800,300],style=wx.DEFAULT_FRAME_STYLE, title='Test space group site symmetry') self.testSSMenu = wx.MenuBar() self.File = wx.Menu(title='') self.File.Append(wxID_FILEEXIT,'Exit') self.Bind(wx.EVT_MENU, self.OnFileExit, id=wxID_FILEEXIT) self.testSSMenu.Append(menu=self.File, title='Run') self.SetMenuBar(self.testSSMenu) self.testSSPanel = wx.Window(self) def __init__(self, parent): self._init_ctrls(parent) self.Bind(wx.EVT_CLOSE, self.ExitMain) self.dataFrame = None Data = {'SGData':G2spc.SpcGroup('P 1')[1],} self.RBsym = '1' self.propVec = '0,0,0' self.XYZ = '0,0,0' self.UpdateData(Data) ``` -------------------------------- ### Initialize Tool State Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIIntPDFtool.html Sets up initial parameters, timers, and file format lists for the tool instance. ```python ################################################## # beginning of __init__ processing ################################################## self.G2frame = G2frame self.ImgTblParms = None self.IMfileList = None self.params = {} self.Reset = False self.Pause = False self.PreventReEntryShowMatch = False self.PreventTimerReEntry = False self.params['ControlsTable'] = {} self.params['MaskTable'] = {} G2sc.LoadG2fil() self.fmtlist = G2sc.exportersByExtension.get('powder',{}) self.fmtlist['.gpx'] = None self.timer = wx.Timer() self.timer.Bind(wx.EVT_TIMER,self.OnTimerLoop) self.imageBase = G2frame.Image self.params['ComputePDF'] = False self.params['pdfDmax'] = 0.0 ``` -------------------------------- ### Equivalence Definition Example Source: https://gsas-ii.readthedocs.io/en/latest/GSASIImapvars.html Example syntax for defining parameter equivalences. ```text ::x1 -> ::x2 & ::x4 ``` -------------------------------- ### pipInstall(packageList) Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIpath.html Installs one or more packages using the pip package installer. ```APIDOC ## pipInstall(packageList) ### Description Installs one or more packages using the pip package installer. It automatically converts conda-style package specifiers (e.g., pkg=1.2.3) to pip-style (pkg==1.2.3). ### Parameters - **packageList** (list) - A list of strings containing the names of packages to install. ### Returns - **None** - If the command ran normally. - **str/Exception** - An error message or exception if the installation failed. ``` -------------------------------- ### Initialize G2Project Source: https://gsas-ii.readthedocs.io/en/latest/GSASIIscriptable.html Demonstrates how to initialize a G2Project object by either loading an existing file or creating a new one. ```python >>> # Load an existing project file >>> proj = G2Project('filename.gpx') ``` ```python >>> # Create a new project >>> proj = G2Project(newgpx='new_file.gpx') ``` -------------------------------- ### HowIsG2Installed() Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIpath.html Determines if GSAS-II was installed via git and returns the installation type. ```APIDOC ## HowIsG2Installed ### Description Determines if GSAS-II was installed with git. The result is cached to optimize performance for multiple calls. ### Returns - **str** - Returns 'github' (with optional '-rev' suffix) if installed from the GSAS-II GitHub repository, or 'noVCS' if installed without a version control system. ``` -------------------------------- ### GSASII.GSASIIctrlGUI.GSGrid.setupPopup Source: https://gsas-ii.readthedocs.io/en/latest/GSASIIGUIr.html Defines a callback that creates a popup menu for the grid. ```APIDOC ## setupPopup(lblList, callList) ### Description Creates a popup menu where selecting an item triggers a corresponding function call. ### Parameters - **lblList** (list) - Required - List of string items for the popup menu. - **callList** (list) - Required - List of functions to be called when a menu item is selected. ### Returns - **callback** (function) - A callback that can be used to create the menu. ``` -------------------------------- ### Install GSAS-II binary files Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIpath.html Installs GSAS-II binary files into a specified directory. ```python [docs] def InstallGitBinary(tarURL, instDir, nameByVersion=False, verbose=True): '''Install the GSAS-II binary files into the location specified. ``` -------------------------------- ### Setup Parameter Dictionary Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIrestrGUI.html Creates a dictionary mapping variable names to their current numerical values. ```python def SetupParmDict(G2frame): '''Creates a parameter dict with variable names as keys and numerical values (only) ''' G2cnstG.CheckAllScalePhaseFractions(G2frame,refine=False) try: parmDict,varyList = G2frame.MakeLSParmDict() except: print('Error retrieving parameters') return {} return {i:parmDict[i][0] for i in parmDict} ``` -------------------------------- ### Export installed packages from environment Source: https://gsas-ii.readthedocs.io/en/latest/packages.html Lists packages explicitly installed in a specific Conda environment. ```bash conda env export --from-history -n ``` -------------------------------- ### Initialize Frame Controls Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/Absorb.html Sets up the main frame, menu bar, and initial panel drawing. ```python def _init_ctrls(self, parent): wx.Frame.__init__(self, parent=parent, size=wx.Size(500, 400),style=wx.DEFAULT_FRAME_STYLE ^ wx.CLOSE_BOX, title='Absorb') self._init_utils() self.SetMenuBar(self.menuBar1) self.DrawPanel() ``` -------------------------------- ### Chained Equivalence Example Source: https://gsas-ii.readthedocs.io/en/latest/GSASIImapvars.html Example of chained equivalences where a parameter acts as both a dependent and independent variable. ```text C1 * P1 = C2 * P2 C2 * P2 = C3 * P3 ``` -------------------------------- ### Example of a single calibrant entry Source: https://gsas-ii.readthedocs.io/en/latest/GSASIIdata.html A standard example of a single material entry in the ImageCalibrants dictionary. ```python 'LaB6 SRM660a':([2,],['',][(4.1569162,4.1569162,4.1569162,90,90,90),],0,(1.0,10,10.)), ``` -------------------------------- ### Initialize Fprime Utilities Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/fprime.html Sets up the menu bar and individual menus for the Fprime utility. ```python def _init_utils(self): self.FPRIME = wx.Menu(title='') self.KALPHA = wx.Menu(title='') self.KALPHA.SetEvtHandlerEnabled(True) self.ABOUT = wx.Menu(title='') self.menuBar1 = wx.MenuBar() self._init_coll_FPRIME_Items(self.FPRIME) self._init_coll_KALPHA_Items(self.KALPHA) self._init_coll_ABOUT_Items(self.ABOUT) self._init_coll_menuBar1_Menus(self.menuBar1) ``` -------------------------------- ### Install Conda Package Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIpath.html Installs the conda API into the current environment using command line tools. ```python def addCondaPkg(): '''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. ''' if not any([(i in os.environ) for i in ('CONDA_DEFAULT_ENV','CONDA_EXE', 'CONDA_PREFIX', 'CONDA_PYTHON_EXE')]): return None #condaexe = os.environ['CONDA_EXE'] currenv = os.environ['CONDA_DEFAULT_ENV'] if sys.platform == "win32": cmd = [os.environ['CONDA_EXE'],'install','conda','-n',currenv,'-y'] with subprocess.Popen(cmd, #stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='UTF-8') as p: out,err = p.communicate() else: script = 'source ' + os.path.join( os.path.dirname(os.environ['CONDA_PYTHON_EXE']), 'activate') + ' base; ' script += 'conda install conda -n '+currenv+' -y' with subprocess.Popen(script,shell=True,env={}, #stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='UTF-8') as p: out,err = p.communicate() if out is not None and GetConfigValue('debug'): print('Output from adding conda:\n',out) if err and err is not None: print('Note error/warning from running conda:\n',err) if currenv == "base": print('\nUnexpected action: adding conda to base environment???') ``` -------------------------------- ### Initialize Help Dialog Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIpwdplot.html Sets up a help button with context-specific information for plot export options. ```python helpinfo = '''---- Help on creating hard copy ---- Select options such as the size of text and colors for plot contents here. Tricks: * Use a color of pure white to remove an element from the plot (light gray is plotted) * LaTeX-like coding can be used for phase labels such as $\rm FeO_2$ (for a subscript 2) or $\gamma$-Ti for a Greek "gamma" Note that the dpi value is ignored for svg and pdf files, which are drawn with vector graphics (infinite resolution). Likewise, the agr and itx options create input files for programs Grace (QtGrace) and Igor Pro, that largely duplicate the displayed plot. Once read into Grace or Igor the graphs can then be customized. ''' if sys.platform == "win32": helpinfo += ''' Note that the OriginPro connection export requires Origin 2021 or later.''' hlp = G2G.HelpButton(dlg,helpinfo) sizebox.Add(hlp,0,wx.ALL) vbox.Add(sizebox,0,wx.ALL|wx.EXPAND) ``` -------------------------------- ### GSASII.GSASIIimgGUI.initPhaseOpts Source: https://gsas-ii.readthedocs.io/en/latest/GSASIIGUI.html Ensures that the options for display of partials are all defined. ```APIDOC ## GSASII.GSASIIimgGUI.initPhaseOpts(_phases_) ### Description Make sure that the options for display of partials are all defined. ``` -------------------------------- ### Define Excluded Regions Examples Source: https://gsas-ii.readthedocs.io/en/latest/GSASIIscriptable.html Examples of defining excluded regions for histograms using lists of pairs. ```python [[4.5, 5.5], [8.0, 9.0]] ``` ```python [[130000.0, 140000.0], [160000.0, 170000.0]] ``` ```python [] ``` -------------------------------- ### Initialize MakeTopWindow Class Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/G2compare.html The constructor sets up the main frame, plot window, menu bar, and the split-window interface for the comparison tool. ```python class MakeTopWindow(wx.Frame): '''Define the main frame and its associated menu items ''' def __init__(self, parent): size = wx.Size(700,450) wx.Frame.__init__(self, name='dComp', parent=parent, size=size,style=wx.DEFAULT_FRAME_STYLE, title='GSAS-II data/model comparison') # misc vars self.VcovColor = 'RdYlGn' # plot window try: size = GSASIIpath.GetConfigValue('Plot_Size') if type(size) is tuple: pass elif type(size) is str: size = eval(size) else: raise Exception except: size = wx.Size(700,600) self.plotFrame = wx.Frame(None,-1,'dComp Plots',size=size, style=wx.DEFAULT_FRAME_STYLE ^ wx.CLOSE_BOX) self.G2plotNB = G2plt.G2PlotNoteBook(self.plotFrame,G2frame=self) #self.plotFrame.Show() self.plotFrame.Show(False) # until we have some graphics, hide the plot window # menus Frame = self.GetTopLevelParent() # same as self self.MenuBar = wx.MenuBar() File = wx.Menu(title='') self.MenuBar.Append(menu=File, title='&File') item = File.Append(wx.ID_ANY,'&Import single project...\tCtrl+O','Open a GSAS-II project file (*.gpx)') self.Bind(wx.EVT_MENU, self.onLoadGPX, id=item.GetId()) item = File.Append(wx.ID_ANY,'&Import multiple projects...\tCtrl+U','Open a GSAS-II project file (*.gpx)') self.Bind(wx.EVT_MENU, self.onLoadMultGPX, id=item.GetId()) item = File.Append(wx.ID_ANY,'&Wildcard import of projects...\tCtrl+W','Open a GSAS-II project file (*.gpx)') self.Bind(wx.EVT_MENU, self.onLoadWildGPX, id=item.GetId()) # item = File.Append(wx.ID_ANY,'&Import selected...','Open a GSAS-II project file (*.gpx)') # self.Bind(wx.EVT_MENU, self.onLoadSel, id=item.GetId()) self.Mode = wx.Menu(title='') self.MenuBar.Append(menu=self.Mode, title='&Mode') self.wxID_Mode = {} for i,m in enumerate(("Histogram","Phase","Project")): self.wxID_Mode[m] = i+1 item = self.Mode.AppendRadioItem(i+1,m+'\tCtrl+{}'.format(i+1), 'Display {}s'.format(m)) self.Bind(wx.EVT_MENU, self.onRefresh, id=item.GetId()) self.hFilter = self.Mode.Append(wx.ID_ANY,'Filter by histogram\tCtrl+F','Only show selected histograms') self.Bind(wx.EVT_MENU, self.onHistFilter, id=self.hFilter.GetId()) modeMenu = wx.Menu(title='') self.MenuBar.Append(menu=modeMenu, title='TBD') self.modeMenuPos = self.MenuBar.FindMenu('TBD') Frame.SetMenuBar(self.MenuBar) # status bar self.Status = self.CreateStatusBar() self.Status.SetFieldsCount(2) # split the frame and add the tree self.mainPanel = wx.SplitterWindow(self, wx.ID_ANY, style=wx.SP_LIVE_UPDATE|wx.SP_3D) self.mainPanel.SetMinimumPaneSize(100) self.treePanel = wx.Panel(self.mainPanel, wx.ID_ANY, style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER) # self.dataWindow = G2DataWindow(self.mainPanel) self.dataWindow = wx.ScrolledWindow(self.mainPanel) dataSizer = wx.BoxSizer(wx.VERTICAL) self.dataWindow.SetSizer(dataSizer) self.mainPanel.SplitVertically(self.treePanel, self.dataWindow, 200) self.Status.SetStatusWidths([200,-1]) # make these match? treeSizer = wx.BoxSizer(wx.VERTICAL) self.treePanel.SetSizer(treeSizer) self.GPXtree = G2G.G2TreeCtrl(id=wx.ID_ANY, parent=self.treePanel, size=self.treePanel.GetClientSize(),style=wx.TR_DEFAULT_STYLE ) #TreeId = self.GPXtree.Id treeSizer.Add(self.GPXtree,1,wx.EXPAND|wx.ALL,0) #self.GPXtree.Bind(wx.EVT_TREE_SEL_CHANGED,self.OnDataTreeSelChanged) self.GPXtree.Bind(wx.EVT_TREE_SEL_CHANGED,self.OnDataTreeSelChanged) # self.GPXtree.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK,self.OnDataTreeSelChanged) # self.GPXtree.Bind(wx.EVT_TREE_ITEM_COLLAPSED, # self.OnGPXtreeItemCollapsed, id=TreeId) #self.GPXtree.Bind(wx.EVT_TREE_ITEM_EXPANDED, # self.OnGPXtreeItemExpanded, id=TreeId) # self.GPXtree.Bind(wx.EVT_TREE_DELETE_ITEM, # self.OnGPXtreeItemDelete, id=TreeId) # self.GPXtree.Bind(wx.EVT_TREE_KEY_DOWN, # self.OnGPXtreeKeyDown, id=TreeId) # self.GPXtree.Bind(wx.EVT_TREE_BEGIN_RDRAG, # self.OnGPXtreeBeginRDrag, id=TreeId) # self.GPXtree.Bind(wx.EVT_TREE_END_DRAG, # self.OnGPXtreeEndDrag, id=TreeId) self.root = self.GPXtree.root self.Bind(wx.EVT_CLOSE, lambda event: sys.exit()) ``` -------------------------------- ### Example of a calibrant with absent reflections Source: https://gsas-ii.readthedocs.io/en/latest/GSASIIdata.html An example showing how to specify indices of lines that have no intensity despite being allowed. ```python 'Si':([0,],['F d 3 m'],[(5.4311946,5.4311946,5.4311946,90,90,90),],0,(1.,10,10.),(3,10,13,20,23,26,33,35,40,43)), ``` -------------------------------- ### Atom Modulation Wave GUI Setup Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIphsGUI2.html This code snippet handles the initialization of the atom selection interface and the dynamic generation of sizers for modulation wave parameters. ```python iatm = atNames.index(G2frame.atmSel) atm = atomData[iatm] G2elem.AddWave2atm(atm) xyz = atm[cx:cx+3] atomSizer = wx.BoxSizer(wx.VERTICAL) G2G.HorizontalLine(atomSizer,waveData) atomSizer.Add(AtomSizer(atm)) for Stype in ['Sfrac','Spos','Sadp','Smag']: if atm[cia] != 'A' and Stype == 'Sadp': #Uiso can't have modulations! (why not?) continue if generalData['Type'] != 'magnetic' and Stype == 'Smag': break try: atomSizer.Add(WaveSizer(iatm,atm[-1]['SS1'][Stype],Stype,typeNames[Stype],Labels[Stype])) except TypeError: # not expected anymore atomSizer.Add(wx.StaticText(waveData,label=' Error: could not process SS info for this atom')) break return atomSizer generalData = data['General'] cx,ct,cs,cia = generalData['AtomPtrs'] typeNames = {'Sfrac':' Site fraction','Spos':' Position','Sadp':' Thermal motion','Smag':' Magnetic moment'} numVals = {'Sfrac':2,'Spos':6,'Sadp':12,'Smag':6,'ZigZag':5,'Block':5,'Crenel':2} posNames = ['Xsin','Ysin','Zsin','Xcos','Ycos','Zcos','Tmin','Tmax','Xmax','Ymax','Zmax'] adpNames = ['U11sin','U22sin','U33sin','U12sin','U13sin','U23sin', 'U11cos','U22cos','U33cos','U12cos','U13cos','U23cos'] magNames = ['MXsin','MYsin','MZsin','MXcos','MYcos','MZcos'] fracNames = ['Fsin','Fcos','Fzero','Fwid'] waveTypes = {'Sfrac':['Fourier','Crenel'],'Spos':['Fourier','ZigZag','Block',],'Sadp':['Fourier',],'Smag':['Fourier',]} Labels = {'Spos':posNames,'Sfrac':fracNames,'Sadp':adpNames,'Smag':magNames} Indx = {} waveData = G2frame.waveData G2frame.GetStatusBar().SetStatusText('',1) generalData = data['General'] SGData = generalData['SGData'] SSGData = generalData['SSGData'] cx,ct,cs,cia = generalData['AtomPtrs'] atomData = data['Atoms'] D4Map = generalData.get('4DmapData',{'rho':[]}) if waveData.GetSizer(): waveData.GetSizer().Clear(True) mainSizer = wx.BoxSizer(wx.VERTICAL) mainSizer.Add(wx.StaticText(waveData,label=' Incommensurate propagation wave data')) atNames = [] for atm in atomData: atNames.append(atm[ct-1]) if not atNames: mainSizer.Add(wx.StaticText(waveData,label=' (no atoms in phase)')) G2phsG.SetPhaseWindow(G2frame.waveData,mainSizer,Scroll=Scroll) return if G2frame.atmSel not in atNames: G2frame.atmSel = atNames[0] topSizer = wx.BoxSizer(wx.HORIZONTAL) mainSizer.Add(topSizer,0) topSizer.Add(wx.StaticText(waveData,label=' Select atom to edit: '),0,WACV) atms = wx.ComboBox(waveData,value=G2frame.atmSel,choices=atNames, style=wx.CB_READONLY|wx.CB_DROPDOWN) atms.Bind(wx.EVT_COMBOBOX,OnAtmSel) topSizer.Add(atms,0) G2frame.bottomSizer = ShowAtomInfo() mainSizer.Add(G2frame.bottomSizer) G2phsG.SetPhaseWindow(G2frame.waveData,mainSizer,Scroll=Scroll) ``` -------------------------------- ### Import GSASIIscriptable when installed in Python Source: https://gsas-ii.readthedocs.io/en/latest/GSASIIscriptable.html Use this import statement when GSAS-II is already installed within the Python environment. ```python from GSASII import GSASIIscriptable as G2sc ``` -------------------------------- ### findConda() Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIpath.html Determines if GSAS-II has been installed as g2conda or gsas2full by locating the conda executable and activation script relative to the installation path. ```APIDOC ## findConda() ### Description Determines if GSAS-II has been installed as g2conda or gsas2full with conda located relative to the file path. It returns the paths to the conda executable and the activation script if found, otherwise returns None. ### Returns - **tuple** (conda_path, activate_path) - The paths to the conda executable and activation script. - **None** - If the paths cannot be determined. ``` -------------------------------- ### Configure and Initialize Image Integration Script Source: https://gsas-ii.readthedocs.io/en/latest/_sources/GSASIIscriptable.rst.txt Sets up the environment, tuning parameters, and file paths for processing image data. Includes a helper function to wait for metadata files before processing. ```python import os,glob,time,shutil G2sc.blkSize = 2**8 # computer-dependent tuning parameter G2sc.SetPrintLevel('warn') # reduces output cache = {} # place to save intermediate computations # define location & names of files dataLoc = os.path.abspath(os.path.split(__file__)[0]) # data in location of this file PathWrap = lambda fil: os.path.join(dataLoc,fil) # convenience function for file paths imgctrl = PathWrap('Si_ch3_d700-00000.imctrl') imgmask = PathWrap('Si_ch3_d700-00000.immask') globPattern = PathWrap("*_d700-*.tif") def wait_for_metadata(tifname): '''A .tif file is created before it can be read. Wait for the metadata file to be created before trying to read both. ''' while not os.path.exists(tifname + '.metadata'): time.sleep(0.05) # make a subfolder to store integrated images & integrated patterns pathImg = os.path.join(dataLoc,'img') if not os.path.exists(pathImg): os.mkdir(pathImg) pathxye = os.path.join(dataLoc,'xye') if not os.path.exists(pathxye): os.mkdir(pathxye) ``` -------------------------------- ### Initialize Rigid Body GUI Page 1 Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIconstrGUI.html Sets up the first stage of the rigid body GUI, allowing atom selection and visualization. ```python def Page1(): '''Show the GUI for first stage of the rigid body with all atoms in phase in crystal coordinates. Select the atoms to go onto the next stage ''' def ShowSelection(selections): 'respond to change in atom selections' ct,cs = [1,8] generalData = rd.Phase['General'] for i,atom in enumerate(rd.Phase['Drawing']['Atoms']): if i in selections: factor = 1 else: factor = 2.5 atNum = generalData['AtomTypes'].index(atom[ct]) atom[cs] = list(np.array(generalData['Color'][atNum])//factor) draw(*drawArgs) def onPage1OK(event): '1st section has been completed, move onto next' G2frame.G2plotNB.Delete(rd.Phase['General']['Name']) GetCoords(atmsel) Page2() if 'macromolecular' == rd.Phase['General']['Type']: # for PDB imports, lets see if a quick reformat of atoms list will work rd.Phase['Atoms'] = [a[3:] for a in rd.Phase['Atoms']] rd.Phase['General']['AtomPtrs'] = [i-3 for i in rd.Phase['General']['AtomPtrs']] rd.Phase['General']['Type'] = 'nuclear' SetupDrawing(rd.Phase) # add information to reader object to allow plotting atomlist = [atom[0] for atom in rd.Phase['Atoms']] atmsel = list(range(len(rd.Phase['Atoms']))) # broken -- # why no bonds? #for atm in rd.Phase['Drawing']['Atoms']: # atm[6] = 'balls & sticks' draw,drawArgs = G2plt.PlotStructure(G2frame,rd.Phase,True) ShowSelection(atmsel) if G2frame.rbBook.FindPage(pagename) is not None: G2frame.rbBook.DeletePage(G2frame.rbBook.FindPage(pagename)) ``` -------------------------------- ### Determine GSAS-II installation method Source: https://gsas-ii.readthedocs.io/en/latest/_modules/GSASII/GSASIIpath.html Checks if GSAS-II was installed via git and caches the result to optimize subsequent calls. ```python def HowIsG2Installed(): '''Determines if GSAS-II was installed with git. 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 'noVCS' if installed without a connection to a version control system ''' global G2_installed_result if G2_installed_result is not None: return G2_installed_result try: g2repo = openGitRepo(path2GSAS2) if os.path.samefile(os.path.dirname(g2repo.common_dir),path2GSAS2): rev = '' else: rev = '-rev' if g2URL in g2repo.remote().urls: return 'github'+rev elif g2URL.replace('https://github.com/', 'git@github.com:') in g2repo.remote().urls: return 'github'+rev G2_installed_result = 'git'+rev return G2_installed_result except: pass G2_installed_result = 'noVCS' return G2_installed_result ``` -------------------------------- ### Example of a mixture calibrant entry Source: https://gsas-ii.readthedocs.io/en/latest/GSASIIdata.html An example showing how to define a mixture of materials by repeating Bravais numbers and lattice parameters. ```python 'LaB6 & CeO2':([2,0],['',''] [(4.1569,4.1569,4.1569,90,90,90),(5.4117,5.4117,5.4117,90,90,90)], 0, (1.0,2,1.)), ```