### Install and configure Ollama Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/gsas_query/README.md Install Ollama, start the local server, and pull the llama3 model (~5 GB). ```bash brew install ollama # macOS; see https://ollama.com for other platforms ollama serve & # start the local server ollama pull llama3 # ~5 GB one-time download ``` -------------------------------- ### Start GSAS-II GUI with python -m Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIGUI.rst Alternative command to start the GSAS-II GUI when GSAS-II is installed on the default Python path or the current working directory contains the GSASII directory. ```bash python -m GSASII ``` -------------------------------- ### Start GSAS-II GUI with python -c Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIGUI.rst Use this command to start the GSAS-II GUI when GSAS-II is installed on the default Python path or the current working directory contains the GSASII directory. ```bash python -c "from GSASII.GSASIIGUI import main; main()" ``` -------------------------------- ### Install gsas2-query from source Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/gsas_query/README.md Install directly from the GitHub repository. ```bash pip install git+https://github.com/AdvancedPhotonSource/Query-GSAS-II.git ``` -------------------------------- ### Development / editable install Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/gsas_query/README.md Clone the repository and install in editable mode with development dependencies. ```bash git clone https://github.com/AdvancedPhotonSource/Query-GSAS-II.git cd Query-GSAS-II pip install -e ".[dev]" ``` -------------------------------- ### Start GSAS-II GUI with python -c or python -m Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASII.rst Two equivalent commands to start the GSAS-II GUI when GSAS-II is installed inside Python. The first uses the -c flag to import and call the main() function from GSASII.GSASIIGUI, while the second uses the module execution flag. ```python python -c "from GSASII.GSASIIGUI import main; main()" ``` ```python python -m GSASII ``` -------------------------------- ### Install GSAS-II with conda (minimal environment) Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/packages.rst Installs the core GSAS-II dependencies into the current conda environment. Use this for a minimal setup to run GSAS-II. ```bash conda install python=3.13 numpy=2.2 wxpython scipy matplotlib-base pyopengl pillow h5py imageio requests git gitpython pycifrw pybaselines -c conda-forge ``` -------------------------------- ### Install GSAS-II via git clone and initialize scriptable Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/packages.rst Install GSAS-II after Python is installed and in the path. The first command downloads the GSAS-II software to /loc/GSASII (you can select a different location). The second command invokes GSAS-II scriptable for the first time, which is needed to load the binary files from the server. ```bash git clone https://github.com/AdvancedPhotonSource/GSAS-II.git /loc/GSAS-II python /loc/GSAS-II/GSASII/GSASIIscriptable.py ``` -------------------------------- ### Install gsas2-query via pip Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/gsas_query/README.md Install the package from PyPI using pip. ```bash pip install gsas2-query ``` -------------------------------- ### Interactive REPL with gsas2-query Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/gsas_query/README.md Start an interactive REPL session that remembers previous questions. The displayed output shows the welcome banner and an example exchange. Inside the REPL, 'clear' resets history and 'quit' or 'exit' exits. ```bash gsas2-query ``` ```text GSAS-II Documentation Assistant ════════════════════════════════════════════════════════════════════════════════ Knowledge base: 3,847 indexed chunks. LLM backend: ollama Type your question and press Enter. 'clear' resets history, 'quit' exits. ──────────────────────────────────────────────────────────────────────────────── You: How do I constrain lattice parameters? Thinking… Assistant: To constrain lattice parameters in GSAS-II, open the Constraints tab in the Phase panel [1]… Sources: [94%] Help: Phase General › Constraints https://advancedphotonsource.github.io/GSAS-II-tutorials/help/phasegeneral.html ``` -------------------------------- ### installScriptingShortcut Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Installs GSASIIscriptable within Python as G2script. ```APIDOC ## Function: installScriptingShortcut ### Description Installs GSASIIscriptable within Python as G2script. ### Method N/A (Function) ### Endpoint N/A ### Parameters None ### Request Example None ### Response None ``` -------------------------------- ### Install scripting shortcut via Python script Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Run once to install a scripting shortcut for GSASIIscriptable. After running, remove or comment out the G2sc.installScriptingShortcut() line. This is an alternative to the GUI menu command. ```python import sys sys.path.insert(0,'/Users/toby/gsas2main/GSAS-II') # needed to find GSASII package from GSASII import GSASIIscriptable as G2sc G2sc.installScriptingShortcut() ``` -------------------------------- ### Index documentation with gsas2-query --setup Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/gsas_query/README.md Run once to index the documentation. Fetches ~130 web pages and 2 PDFs, embeds everything locally, and takes ~10–20 minutes. By default the index is stored in ~/.GSASII/gsas_query/chroma_db. Use --html-only to skip PDFs (faster, ~5 min) or --reset to drop the index and rebuild from scratch. ```bash gsas2-query --setup # all sources (HTML + PDFs) gsas2-query --setup --html-only # skip PDFs, faster (~5 min) gsas2-query --setup --reset # drop index and rebuild from scratch ``` -------------------------------- ### Install llama-cpp-python Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/gsas_query/README.md Install llama-cpp-python via conda-forge or pip with the llama_cpp extra. ```bash conda install -c conda-forge llama-cpp-python # recommended # or: pip install "gsas2-query[llama_cpp]" ``` -------------------------------- ### Install gsas2-query via conda Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/gsas_query/README.md Install the package from conda-forge. ```bash conda install -c conda-forge gsas2-query ``` -------------------------------- ### Test GSASIIscriptable shortcut with ShowVersions Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Test that GSASIIscriptable is working after installing the shortcut. Prints version information. ```python import G2script as G2sc print(G2sc.ShowVersions()) ``` -------------------------------- ### Run web UI with gsas2-query-web Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/gsas_query/README.md Start the web UI. By default it serves on 0.0.0.0:8000; you can override HOST and PORT. Then open http://localhost:8000 in a browser. The web UI shows inline citations as clickable superscript links and source chips below each answer. ```bash gsas2-query-web # serves on 0.0.0.0:8000 HOST=127.0.0.1 PORT=8765 gsas2-query-web ``` -------------------------------- ### Install Python with Miniconda and required packages Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/packages.rst Install a minimal Python environment using the Miniconda installer. The first command assumes the appropriate Miniconda version has been downloaded from https://docs.conda.io/en/latest/miniconda.html and installs Python to /loc/pyg2script (you might use ~/pyg2script). The second command activates the environment, and the third installs all packages that might be used by scripting; matplotlib, pillow, h5py and hdf5 are not commonly needed and could be omitted. ```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 ``` -------------------------------- ### Multicore integration setup with command-line core count Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Sets up a multicore image integration script: parses the number of cores from the command line (0 means run directly), tunes G2sc.blkSize, and defines file locations and glob patterns. Expects a .imctrl and .immask calibration file in the script's directory. ```python import os,sys,glob,time,shutil scriptstart = time.time() if len(sys.argv) >= 2: nodes = int(sys.argv[1]) else: nodes = 4 if nodes == 0: print('no multiprocessing') else: print(f'multiprocessing with {nodes} cores') G2sc.blkSize = 2**8 # computer-dependent tuning parameter #G2sc.SetPrintLevel('warn') cache = {} # place to save intermediate computations # define location & names of files dataLoc = '/dataserv/inttest' # images found here globPattern = os.path.join(dataLoc,"*_d700-*.tif") calibLoc = os.path.abspath(os.path.split(__file__)[0]) # calib in location of this file imgctrl = os.path.join(calibLoc,'Si_ch3_d700-00000.imctrl') imgmask = os.path.join(calibLoc,'Si_ch3_d700-00000.immask') # locations to put processed files pathImg = os.path.join(dataLoc,'img') pathxye = os.path.join(dataLoc,'xye') ``` -------------------------------- ### Install gsas2-query into existing GSAS-II environment Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/gsas_query/README.md Activate the GSAS-II conda environment first, then install with pip. ```bash # Activate the GSAS-II conda environment first, then: pip install gsas2-query ``` -------------------------------- ### Refinement recipe with do_refinements Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Shows how to perform multiple refinement steps by passing a list of parameter dicts to do_refinements. The example performs two refinement steps using pardict and pardict1. ```python my_project.do_refinements([pardict,pardict1]) ``` -------------------------------- ### Install scripting shortcut via command line (Windows) Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Run in a cmd.exe window on Windows to install the scripting shortcut. Assumes the intended Python interpreter is already in the path; otherwise use a conda activate command. The directory used is the parent of the GSASII directory. ```bash >cd \Users\toby\gsas2main\GSAS-II >python -c "import GSASII.GSASIIscriptable as G2sc; G2sc.installScriptingShortcut()" ``` -------------------------------- ### Run refinements with do_refinements Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Example of using G2Project.do_refinements with a list containing a dict with 'set' key and 'histograms' key to apply refinements to specific histograms. The 'set' dict contains the same parameters as the set_refinements example. ```python gsas_proj.do_refinements([ {'set': { 'Background': {'no. coeffs': 3, 'refine': True}, 'Sample Parameters': ['Scale'], 'Limits': [10000, 40000]}, 'histograms': [1,2]} ]) ``` -------------------------------- ### Install scripting shortcut via command line (MacOS/Linux) Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Run in a terminal on MacOS/Linux to install the scripting shortcut. Assumes the intended Python interpreter is already in the path; otherwise use a conda activate command. The directory used is the parent of the GSASII directory. ```bash % cd /Users/toby/gsas2main/GSAS-II % python -c "import GSASII.GSASIIscriptable as G2sc; G2sc.installScriptingShortcut()" ``` -------------------------------- ### Windows fc command output comparing before and after Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Example output from the fc command on Windows, showing differences between before.txt and after.txt. The diff reveals an extra 'PWDR Co_PCP_Act_d900-00030.fxye Bank 1' entry in the after file. ```text Z:\>fc before.txt after.txt Comparing files before.txt and after.txt ***** before.txt fill_value = 1e+20) , 'PWDR Co_PCP_Act_d900-00030.fxye Bank 1', 'PWDR Co_PCP_Act_d900-00030.fxye Ban k 1'] (['Comments'], , ['Co_PCP_Act_d900-00030.tif #0001 Azm= 180.00']) ***** AFTER.TXT fill_value = 1e+20) , 'PWDR Co_PCP_Act_d900-00030.fxye Bank 1', 'PWDR Co_PCP_Act_d900-00030.fxye Ban k 1', 'PWDR Co_PCP_Act_d900-00030.fxye Bank 1'] (['Comments'], , ['Co_PCP_Act_d900-00030.tif #0001 Azm= 180.00']) ***** ``` -------------------------------- ### Set sys.path for GSAS-II on Windows Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Place at the start of a script when GSAS-II is installed in C:\Users\toby\gsas2main on Windows. Uses forward slashes deliberately; backslashes must be doubled or placed in a raw string. The path must be the parent of the GSASII directory. ```python import sys sys.path.insert(0,'/Users/toby/gsas2main/GSAS-II') # needed to find GSASII package from GSASII import GSASIIscriptable as G2sc ``` -------------------------------- ### Import GSASIIscriptable when installed inside Python Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Use when GSAS-II is installed inside Python; no path modification is needed. This import should work without any of the previous setup steps. ```python from GSASII import GSASIIscriptable as G2sc ``` -------------------------------- ### Set sys.path for GSAS-II on MacOS/Linux Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Place at the start of a script when GSAS-II is installed in /Users/toby/g2main/GSAS-II on MacOS/Linux. Adds the parent directory of the GSASII package to sys.path so GSASIIscriptable can be imported. ```python import sys sys.path.insert(0,'/Users/toby/g2main/GSAS-II') # needed to find GSASII package from GSASII import GSASIIscriptable as G2sc ``` -------------------------------- ### Project-level parameter dict example Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Defines a pardict dictionary with 'set' and 'clear' keys to configure refinement parameters such as limits, sample parameters, background, and instrument parameters. This dict is passed to set_refinement to apply the settings. ```python pardict = {'set': { 'Limits': [0.8, 12.0], 'Sample Parameters': ['Absorption', 'Contrast', 'DisplaceX'], 'Background': {'type': 'chebyschev-1', 'refine': True, 'peaks':[[0,1,1],[1,1,1]] }}, 'clear': {'Instrument Parameters': ['U', 'V', 'W']}} my_project.set_refinement(pardict) ``` -------------------------------- ### Python Script Example: Using G2script to Read and Transform CIF Files Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Example Python script using G2script to read CIF files, call strtidy, and export transformed coordinates. ```APIDOC ## Python Script Example: Using G2script to Read and Transform CIF Files ### Description Example script that reads CIF files, calls the Bilbao strtidy service if needed, and writes transformed coordinates. Requires BCS_API_KEY environment variable. ### Prerequisites - BCS_API_KEY must be set (see tutorial for obtaining it). - Do not run on a very large number of files over a short time to avoid overloading the BCS server. ### Code Example ```python import os import G2script as G2sc os.environ.update({"BCS_API_KEY":"BCS_API_KEY_..."}) PathWrap = lambda fil: os.path.join('/Users/toby/Scratch/CIF_problems',fil) files = [ 'data_104906-ICSD_original.cif', 'data_260095-ICSD_original.cif', ] for f in files: gpx = G2sc.G2Project(newgpx='Junk.gpx') # create a new project newname = f.replace('.cif','_rev.cif') phase0 = gpx.add_phase(PathWrap(f), phasename=os.path.split(f)[1],fmthint='CIF', useNet=True, ) phase0.export_CIF(newname) print(f'file {newname} written') del gpx # gets written anyway, alas ``` ``` -------------------------------- ### Optimized image integration setup with GSAS-II Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Optimized image integration script for GSAS-II. Sets the blkSize tuning parameter (power of two, default 128) and reduces output with SetPrintLevel('warn'). Defines file paths, a wait_for_metadata helper for .tif files that are created before they can be read, and creates output subfolders for integrated images and patterns. ```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) ``` -------------------------------- ### Show GSAS-II version information with G2sc.ShowVersions() Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Call G2sc.ShowVersions() to print Python, package, and GSAS-II version details. The output shows the GSAS-II location and binary location, useful for verifying the installation. ```python print(f'Version information:\n{G2sc.ShowVersions()}') ``` ```text setting up GSASIIscriptable from /Users/toby/G2/git/g2full/GSAS-II/GSASII Version information: Python 3.11.9: from /Users/toby/py/mf3/envs/py311/bin/python numpy 1.26.4: scipy 1.13.0: IPython 8.22.2: GSAS-II: 641a65, 24-May-2024 10:16 (0.5 days old). Last tag: #5789 GSAS-II location: /Users/toby/G2/git/g2full/GSAS-II/GSASII Binary location: /Users/toby/G2/git/g2full/GSAS-II/GSASII-bin/mac_arm_p3.11_n1.26 ``` -------------------------------- ### Override ChromaDB data directory with GSAS_QUERY_DATA_DIR Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/gsas_query/README.md Sets the GSAS_QUERY_DATA_DIR environment variable to /data/gsas_query and runs the gsas2-query --setup command to initialize the index in the custom location. ```bash GSAS_QUERY_DATA_DIR=/data/gsas_query gsas2-query --setup ``` -------------------------------- ### Save version information with save-versions.py Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/versioning.rst For non-git installs, this script saves version information to the git_verinfo.py file. ```bash .../GSASII/install/save-versions.py ``` -------------------------------- ### GSAS-II .instparm CorrectionCode example for powder data corrections Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/help/others.html Shows how to add a CorrectionCode parameter to a GSAS-II .instparm file to apply systematic changes to powder data (e.g., 2theta positions). The active example uses a numpy array correction for speed; a commented-out alternate loop version is also included. ```text #GSAS-II instrument parameter file; manually edited by B.H.Toby to show how to use CorrectionCode Lam:0.72768 SH/L:0.002 ... Polariz.:0.99 Type:PXC Bank:1 CorrectionCode:'''# Example 2theta correction (applied via numpy array correction; fast!) print('2theta before', rd.powderdata[0][:3],'...',rd.powderdata[0][-2:]) TT = rd.powderdata[0] rd.powderdata[0] += 0.06038972 - 0.001500277 * TT + 7.389e-06 * TT**2 print('2theta after', rd.powderdata[0][:3],'...',rd.powderdata[0][-2:]) ''' # # alternate example. This applies a correction point-by-point in a loop # #CorrectionCode:'''#apply 2theta correction in a loop #print '2T before', rd.powderdata[0][:3],'...',rd.powderdata[0][-3:] #for i,TT in enumerate(rd.powderdata[0]): # rd.powderdata[0][i] += 0.06038972 - 0.001500277 * TT + 7.389e-06 * TT**2 #print('2T after', rd.powderdata[0][:3],'...',rd.powderdata[0][-3:]) #''' ``` -------------------------------- ### Run gsas2-query with backend and model overrides Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/gsas_query/README.md Shows how to override the LLM backend and model via CLI flags. The retrieval backend returns raw matched chunks without an LLM, useful offline or for testing. The ollama and llama_cpp examples demonstrate model overrides with --model. ```bash gsas2-query --backend retrieval "What is Le Bail extraction?" gsas2-query --backend ollama --model mistral "How do I index peaks?" gsas2-query --backend llama_cpp --model /path/to/model.gguf "How do I refine a structure?" ``` -------------------------------- ### Simulate TOF neutron powder pattern from CIF Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Simulates a powder pattern from the same CIF as the CW example but uses bank #2 from a TOF neutron instrument parameter file (POWGEN_1066.instprm). The pattern is computed over a TOF range of 14 to 35 milliseconds with the default 2500 points. The instrument file is from the TOF-CW Joint Refinement tutorial. ```python import os cifdir = "/Users/toby/software/G2/Tutorials/PythonScript/data" datadir = "/Users/toby/software/G2/Tutorials/TOF-CW Joint Refinement/data" gpx = G2sc.G2Project(newgpx='/tmp/PbSO4simT.gpx') # create a project phase0 = gpx.add_phase(os.path.join(cifdir,"PbSO4-Wyckoff.cif"), phasename="PbSO4",fmthint='CIF') # add a phase to the project hist1 = gpx.add_simulated_powder_histogram("PbSO4 simulation", os.path.join(datadir,"POWGEN_1066.instprm"),14.,35., phases=gpx.phases(),ibank=2) gpx.do_refinements([{}]) gpx.save() ``` -------------------------------- ### ProcessConstraints output example Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIImapvars.rst Shows the structure of the output from ProcessConstraints: constrDict is a list of dicts, each representing a constraint expression (first is a 'Const', second is a 'New Var'), and fixedList holds the fixed values for each constraint (a string or None). ```python constrDict = [ {'0:12:Scale': 2.0, '0:14:Scale': 4.0, '0:13:Scale': 3.0, '0:0:Scale': 0.5}, {'2::C(10,6,1)': 1.0, '1::C(10,6,1)': 1.0, '_vary':True}] fixedList = ['5.0', None] ``` -------------------------------- ### Set up simple refinement with background peak Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Sets up a simple refinement by reading an existing project (.gpx) file, adding a background peak, and changing refinement flags for sample parameters and background. The refinement is not run in this snippet; it only configures the project. ```python datadir = "/Users/Scratch/" gpx = G2sc.G2Project(os.path.join(datadir,'test2.gpx')) gpx.histogram(0).add_back_peak(4.5,30000,5000,0) pardict = {'set': {'Sample Parameters': ['Absorption', 'Contrast', 'DisplaceX'], 'Background': {'type': 'chebyschev-1', 'refine': True, 'peaks':[[0,True]]}}} gpx.set_refinement(pardict) ``` -------------------------------- ### Set up and run sequential refinement Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Sets up and runs a sequential refinement: loads a single-dataset fit, adjusts refinement flags, adds additional .fxye histograms, copies parameters, and launches the sequential fit with 10 cycles. This script is used at the end of Step 1 of the Sequential Refinement tutorial. ```python import os,glob datadir = os.path.expanduser("~/Scratch/SeqTut2019Mar") PathWrap = lambda fil: os.path.join(datadir,fil) # load and rename project gpx = G2sc.G2Project(PathWrap('7Konly.gpx')) gpx.save(PathWrap('SeqRef.gpx')) # turn off some variables; turn on Dijs for p in gpx.phases(): p.set_refinements({"Cell": False}) gpx.phase(0).set_HAP_refinements( {'Scale': False, "Size": {'type':'isotropic', 'refine': False}, "Mustrain": {'type':'uniaxial', 'refine': False}, "HStrain":True,}) gpx.phase(1).set_HAP_refinements({'Scale': False}) gpx.histogram(0).clear_refinements({'Background':False, 'Sample Parameters':['DisplaceX'],}) gpx.histogram(0).ref_back_peak(0,[]) gpx.phase(1).set_HAP_refinements({"HStrain":(1,1,1,0)}) for fil in sorted(glob.glob(PathWrap('*.fxye'))): # load in remaining fxye files if '00' in fil: continue gpx.add_powder_histogram(fil, PathWrap('OH_00.prm'), fmthint="GSAS powder",phases='all') # copy HAP values, background, instrument params. & limits, not sample params. gpx.copyHistParms(0,'all',['b','i','l']) for p in gpx.phases(): p.copyHAPvalues(0,'all') # setup and launch sequential fit gpx.set_Controls('sequential',gpx.histograms()) gpx.set_Controls('cycles',10) gpx.set_Controls('seqCopy',True) gpx.refine() ``` -------------------------------- ### Integrate an image with calibration values Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Reads an image, loads calibration values from a control file, integrates the image, and saves the project. The data files are available in the Scripting Tutorial. ```python import os datadir = "/tmp" PathWrap = lambda fil: os.path.join(datadir,fil) gpx = G2sc.G2Project(newgpx=PathWrap('inttest.gpx')) imlst = gpx.add_image(PathWrap('Si_free_dc800_1-00000.tif'),fmthint="TIF") imlst[0].loadControls(PathWrap('Si_free_dc800_1-00000.imctrl')) pwdrList = imlst[0].Integrate() gpx.save() ``` -------------------------------- ### Display GSASIIscriptable.py help Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Shows the available subcommands for the GSASIIscriptable command-line interface. Use 'python GSASIIscriptable.py --help' to inspect each subcommand. ```text python GSASIIscriptable.py --help ``` -------------------------------- ### G2AtomRecord.type Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Get or set the atom type. ```APIDOC ## G2AtomRecord.type ### Description Get or set the atom type. ### Property type ### Usage .G2AtomRecord.type ### Parameters None documented. ### Returns Atom type. ``` -------------------------------- ### G2AtomRecord.element Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Get the element symbol associated with an atom. ```APIDOC ## G2AtomRecord.element ### Description Get the element symbol associated with an atom. Change with .G2AtomRecord.type. ### Property element ### Usage .G2AtomRecord.element ### Parameters None documented. ### Returns Element symbol associated with the atom. ``` -------------------------------- ### G2AtomRecord.label Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Get or set the label value for an atom. ```APIDOC ## G2AtomRecord.label ### Description Get or set the label value for an atom. ### Property label ### Usage .label ### Parameters None documented. ### Returns Label value for the atom. ``` -------------------------------- ### G2AtomRecord.occupancy Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Get or set the site occupancy associated with an atom. ```APIDOC ## G2AtomRecord.occupancy ### Description Get or set the site occupancy associated with an atom. ### Property occupancy ### Usage .G2AtomRecord.occupancy ### Parameters None documented. ### Returns Site occupancy associated with the atom. ``` -------------------------------- ### Launch desktop GUI with gsas2-query --gui Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/gsas_query/README.md Opens a standalone floating dialog that stays open while you work in GSAS-II. ```bash gsas2-query --gui ``` -------------------------------- ### G2AtomRecord.coordinates Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Get or set the three coordinates associated with an atom. ```APIDOC ## G2AtomRecord.coordinates ### Description Get or set the three coordinates associated with an atom. ### Property coordinates ### Usage .G2AtomRecord.coordinates ### Parameters None documented. ### Returns Three coordinates associated with the atom. ``` -------------------------------- ### G2AtomRecord.refinement_flags Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Get or set the refinement flags associated with an atom. ```APIDOC ## G2AtomRecord.refinement_flags ### Description Get or set the refinement flags associated with an atom. ### Property refinement_flags ### Usage .G2AtomRecord.refinement_flags ### Parameters None documented. ### Returns Refinement flags associated with the atom. ``` -------------------------------- ### VarRemapShow Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIImapvars.rst Shows a summary of the parameter remapping. Call after GenerateConstraints. ```APIDOC ## VarRemapShow ### Description Use this to show a summary of the parameter remapping. Call after GenerateConstraints. ### Method Function call ### Endpoint VarRemapShow() ### Parameters None documented in source. ### Response No return value documented. ``` -------------------------------- ### G2Project.do_refinements Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst This is passed a list of dictionaries, where each dict defines a refinement step. Passing a list with a single empty dict initiates a refinement with the current parameters and flags. ```APIDOC ## G2Project.do_refinements ### Description This is passed a list of dictionaries, where each dict defines a refinement step. Passing a list with a single empty dict initiates a refinement with the current parameters and flags. ### Method do_refinements ### Parameters - **refinement_list** (list of dict) - Required - A list of dictionaries, each defining a refinement step. ### Returns None documented. ``` -------------------------------- ### G2AtomRecord.mult Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Get an atom site multiplicity (value cannot be changed in script). ```APIDOC ## G2AtomRecord.mult ### Description Get an atom site multiplicity (value cannot be changed in script). ### Property mult ### Usage .G2AtomRecord.mult ### Parameters None documented. ### Returns Atom site multiplicity. ``` -------------------------------- ### G2AtomRecord.ranId Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Get an atom random Id number (value cannot be changed in script). ```APIDOC ## G2AtomRecord.ranId ### Description Get an atom random Id number (value cannot be changed in script). ### Property ranId ### Usage .G2AtomRecord.ranId ### Parameters None documented. ### Returns Atom random Id number. ``` -------------------------------- ### Invoke GSASIIscriptable.py from the command line Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Command-line invocation of the GSASIIscriptable.py script. Subcommands include create, add, dump, refine, export, and browse. This mode is no longer being developed. ```text python GSASIIscriptable.py ``` -------------------------------- ### G2AtomRecord.adp_flag Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Get either 'U' or 'I' specifying that an atom is set as anisotropic or isotropic (value cannot be changed in script). ```APIDOC ## G2AtomRecord.adp_flag ### Description Get either 'U' or 'I' specifying that an atom is set as anisotropic or isotropic (value cannot be changed in script). ### Property adp_flag ### Usage .G2AtomRecord.adp_flag ### Parameters None documented. ### Returns Either 'U' or 'I' indicating anisotropic or isotropic. ``` -------------------------------- ### Specify instrument parameters directly with add_powder_histogram Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Creates a project and adds a powder histogram using instrument parameters supplied directly as a list of dictionaries instead of reading from a file. The first dictionary defines the instrument; the second is empty. See CWPowder_table and TOFPowder_table for parameter details. ```python import G2script as G2sc import os datadir = os.path.expanduser("~/Scratch/peakfit") PathWrap = lambda fil: os.path.join(datadir,fil) gpx = G2sc.G2Project(newgpx=PathWrap('pkfit.gpx')) # specify instrmental parameters dictionaries inst_params = [ { "Type": ["PXC", "PXC", 0], "Lam": [1.5405, 1.5405, 0], "Zero": [0.0, 0.0, 0], "Polariz.": [0.7, 0.7, 0], "U": [2.0, 2.0, 0], "V": [-2.0, -2.0, 0], "W": [5.0, 5.0, 0], "X": [0.0, 0.0, 0], "Y": [0.0, 0.0, 0], "Z": [0.0, 0.0, 0], "SH/L": [0.002, 0.002, 0], "Azimuth": [0.0, 0.0, 0], "Bank": [1, 1, 0], }, {}, ] hist = gpx.add_powder_histogram(PathWrap('FAP.XRA'), fmthint='GSAS powder', iparams=inst_params) ``` -------------------------------- ### Export conda environment history Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/packages.rst Lists packages directly installed in a conda environment, excluding dependencies. Replace with the environment name. ```bash conda env export --from-history -n ``` -------------------------------- ### Automatic background fitting with calc_autobkg and fit_fixed_points Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Computes an approximate background with calc_autobkg, sets fixed background points, and refines Chebyschev terms and background peaks via fit_fixed_points. Scripting cannot read files from zip archives or use defaulted instrument parameters. ```python import os,glob PathWrap = lambda fil: os.path.join('/tmp',fil) gpx = G2sc.G2Project(newgpx=PathWrap('autobkg.gpx')) for i in glob.glob(PathWrap('test_RampDown-*.xye')): hist = gpx.add_powder_histogram(i,PathWrap('testData.instprm')) for hist in gpx.histograms('PWDR'): hist.calc_autobkg(logLam=3.5) hist.set_refinements({"Background": {"no. coeffs": 3, "refine": True}}) for pk in [2.4,3.1,4.75]: hist.add_back_peak(pk,1000,1000,0,[False,True,False,False]) hist.fit_fixed_points() for i in [0,1,2]: hist.ref_back_peak(i,[False,True,True,False]) hist.fit_fixed_points() hist.ref_back_peak(2,[True,True,True,False]) hist.fit_fixed_points() hist.set_refinements({"Background": {"no. coeffs": 6, "refine": True}}) hist.fit_fixed_points() gpx.save() ``` -------------------------------- ### Set histogram refinements with set_refinements Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Example of using G2PwdrData.set_refinements to set background coefficients, sample parameters, and limits for a histogram. The dictionary keys are 'Background', 'Sample Parameters', and 'Limits'. ```python hist.set_refinements({"Background": {"no. coeffs": 3, "refine": True}, "Sample Parameters": ["Scale"], "Limits": [10000, 40000]}) ``` -------------------------------- ### Download a GGUF model Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/gsas_query/README.md Download a GGUF-format model from Hugging Face, e.g., Llama 3.1 8B Q4_K_M. ```bash # Llama 3.1 8B (Q4_K_M quantisation, ~5 GB): wget https://huggingface.co/bartowski/Meta-Llama-3.1-8B-Instruct-GGUF/resolve/main/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf ``` -------------------------------- ### Re-index documentation with gsas2-query CLI Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/gsas_query/README.md Run this command to reset and re-index the documentation sources. Useful after documentation updates. ```bash gsas2-query --setup --reset ``` -------------------------------- ### Run script to capture after.txt Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Reruns the script after changing the diffractometer type in the GUI, capturing output to after.txt. ```bash python test.py > after.txt ``` -------------------------------- ### Add keyboard shortcut to menu command with wxPython Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASII.rst Adds a menu command with a keyboard shortcut by including '\tCtrl+' in the menu item label. This example assigns Control-R (Command+R on macOS) to the 'Refine' menu command. ```python item = parent.Append(wx.ID_ANY,'&Refine\tCtrl+R','Perform a refinement') ``` -------------------------------- ### Perform a series of refinement steps with do_refinements Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Defines a list of refinement steps, each dict specifying parameters to set or clear, and passes it to do_refinements. Each dict triggers a separate refinement unless 'skip' is used. The second-to-last step both clears and sets parameters. ```python reflist = [ {"set": { "Limits": { "low": 0.7 }, "Background": { "no. coeffs": 3, "refine": True }}}, {"set": { "LeBail": True, "Cell": True }}, {"set": { "Sample Parameters": ["DisplaceX"]}}, {"set": { "Instrument Parameters": ["U", "V", "W", "X", "Y"]}}, {"set": { "Mustrain": { "type": "uniaxial", "refine": "equatorial", "direction": [0, 0, 1]}}}, {"set": { "Mustrain": { "type": "uniaxial", "refine": "axial"}}}, {"clear": { "LeBail": True}, "set": { "Atoms": { "Mn": "X" }}}, {"set": { "Atoms": { "O1": "X", "O2": "X" }}},] my_project.do_refinements(reflist) ``` -------------------------------- ### Run script to capture before.txt Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Runs the script that displays histogram settings and redirects output to before.txt. ```bash python test.py > before.txt ``` -------------------------------- ### ShowVersions Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Shows Python and GSAS-II version information. ```APIDOC ## Function: ShowVersions ### Description Shows Python and GSAS-II version information. ### Method N/A (Function) ### Endpoint N/A ### Parameters None ### Request Example None ### Response None ``` -------------------------------- ### Embed assistant in GSAS-II Help menu with show_assistant() Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/gsas_query/README.md Add this call to the GSAS-II menu handler (e.g. in GSASIIctrl.py) to embed the assistant in the Help menu. show_assistant() is idempotent — calling it a second time raises the existing window rather than opening a duplicate. ```python def OnDocAssistant(self, event): try: from gsas_query.gui import show_assistant show_assistant(self) # self = GSAS-II main frame except ImportError: wx.MessageBox( "GSAS-II Assistant not installed.\n" "Run: pip install gsas2-query", "Not available" ) ``` -------------------------------- ### Ask a single question with gsas2-query Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/GSASII/gsas_query/README.md Ask a single question from the command line. Each command returns an answer with sources. ```bash gsas2-query "How do I set up a sequential refinement?" gsas2-query "What parameters control the background in Rietveld?" gsas2-query "How do I export a CIF for publication?" ``` -------------------------------- ### GSASIIscriptable Command-Line Interface Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Command-line interface for GSASIIscriptable.py, listing subcommands and usage. ```APIDOC ## GSASIIscriptable Command-Line Interface ### Description Invoke the GSASIIscriptable.py script from the command line to access GSAS-II scripting functionality. This mode is no longer being developed. ### Usage ``` python GSASIIscriptable.py ``` ### Subcommands - **create** - See `~GSASIIscriptable.create` - **add** - See `~GSASIIscriptable.add` - **dump** - See `~GSASIIscriptable.dump` - **refine** - See `~GSASIIscriptable.refine` - **export** - See `~GSASIIscriptable.export` - **browse** - See `~GSASIIscriptable.IPyBrowse` ### Help Run `python GSASIIscriptable.py --help` to show available subcommands. Inspect each subcommand with `python GSASIIscriptable.py --help`. ``` -------------------------------- ### G2Project.do_refinements Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Documentation for the G2Project.do_refinements method, which accepts a list of parameter dicts to perform one or more refinement steps. ```APIDOC ## G2Project.do_refinements(recipe) ### Description Performs a sequence of refinement actions. The recipe is a list of project-level parameter dicts, each of which sets parameters and then performs a refinement. Multiple refinement steps can be performed by including more than one dict in the list. ### Method do_refinements ### Parameters - **recipe** (list of dict) - Required - A list of parameter dicts, each with keys "set" and "clear" (and optionally "histograms" and "phases" to limit actions to specific sets of parameters). ### Request Example ```python pardict = {'set': { 'Limits': [0.8, 12.0], 'Sample Parameters': ['Absorption', 'Contrast', 'DisplaceX'], 'Background': {'type': 'chebyschev-1', 'refine': True}}, 'clear': {'Instrument Parameters': ['U', 'V', 'W']}} my_project.do_refinements([pardict]) ``` ### Response No return value is documented. ``` -------------------------------- ### refine Command JSON Input Source: https://github.com/advancedphotonsource/gsas-ii/blob/main/docs/source/GSASIIscriptable.rst Documentation for the JSON input file used by the refine command. ```APIDOC ## refine Command JSON Input ### Description The refine command requires two inputs: an existing GSAS-II project (.gpx) file and a JSON format file containing a single dict. ### JSON File Structure The JSON file may have two keys: - **refinements** (list) - Defines a set of refinement steps in a JSON representation of a Refinement_recipe list. - **code** (string) - Optional Python code executed after the project is loaded, before refinement starts. The project object is accessed with variable `proj`. ```