GSAS-II is a powerful software for analyzing the crystallographic structure from diffraction data. It is written in Python, with some underlying routines in Fortran and C++. Conveniently, it provides the scriptable interface so that we can perform the refinement in a programming way. This is pretty handy when some batch processing is in need.

The scriptable way of running GSAS-II refinement is basically about writing a Python script, which involves setting up the fitting recipe and conduct the refinement. Detailed documentation can be found in Ref. [1]. To run the scriptable refinement, we need to first install GSAS-II on the machine. Typical installation instructions can be found in Ref. [2]. For Windows and MacOS, there shouldn’t be that much issue in the installation. For Linux, due to the wild variations of Linux flavors (Ubuntu, Centos, OpenSUSE, Arch, Manjaro, Debian, Fedora, you name it…), it is very difficult to come up with a uniform installation solution suitable for all platforms. Though, it is possible to build the codes from the source which is probably the most generic solution. Detailed instructions can be found in Ref. [3].

Once GSAS-II is successfully installed, we want to find out where the codes are installed. For example, on my Linux machine, GSAS-II was installed following Ref. [3] and the installation location is /home/y8z/Dev/gsasii/GSAS-II. Inside the directory, I could see the following file tree,

.
β”œβ”€β”€ backcompat
β”œβ”€β”€ docs
β”œβ”€β”€ GSASII
β”œβ”€β”€ GSASII-bin
β”œβ”€β”€ LICENSE
β”œβ”€β”€ meson.build
β”œβ”€β”€ noxfile.py
β”œβ”€β”€ pixi
β”œβ”€β”€ pyproject.toml
β”œβ”€β”€ README.md
β”œβ”€β”€ sources
└── tests

Now, we can create a conda environment (mamba can be used as well, to replace all conda instances in the following commands) and install some modules (not all of them will be needed but it is safe to install them all),

conda create -n gsasii_dev
conda activate gsasii_dev
conda install python numpy matplotlib wxpython pyopengl scipy git gitpython PyCifRW pillow conda requests hdf5 h5py imageio zarr xmltodict pybaselines seekpath pywin32 -c conda-forge -y

Next, we prepare the Python script for running the GSAS-II refinement, and with the conda environment active from previous step, we should be able to run the script. In the script, we need to provide the full path to where the GSAS-II scriptable file is located – see the example below.

N.B. In my case, my path inserting line would be sys.path.insert(0, '/home/y8z/Dev/gsasii/GSAS-II/GSASII').

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import os
import sys
import numpy as np
sys.path.insert(0, '/full/path/to/GSAS-II/GSASII')
import GSASIIscriptable as G2sc  # noqa: E402

# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# Input parameters
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
gpx_loc = "/full/path/to/where/gsasii/project/file/will/be/saved/"
structure_fn = "/full/path/to/structure.cif"
gsa_fn = "/full/path/to/gsa/data/file"
prm_fn = "/full/path/to/instrument/parameter/file"
output_stem_fn = "output_stem"
stype = "N"
bank = 5
xmin = 300
xmax = 16667
num_banks = 4
xmin_all = [300, 1500, 2000, 3500]
xmax_all = [9000, 10000, 12000, 16667]
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+


def run_gsas2_fit(
        structure_fn, gsa_fn, prm_fn, output_stem_fn,
        stype, bank, xmin, xmax):
    '''
    Parameters
    ----------
    structure_fn: str
        input structure cif filename.
    gsa_fn: str
        input gsa filename.
    instprm_fn: str
        input instrument profile filename.
    output_stem_fn: str
        output stem filename.
    banks: str
        bank 1-6.

    Returns
    -------
    gsas2_poj : str
        gsas2 .gpx project file
    '''
    def HistStats(gpx):
        '''prints profile rfactors for all histograms'''
        print(u"*** profile Rwp, " + os.path.split(gpx.filename)[1])
        for hist in gpx.histograms():
            print("\t{:20s}: {:.2f}".format(hist.name, hist.get_wR()))
        print("")

    print("INFO: Build GSAS-II Project File.")
    print("******************************")

    # start GSAS-II refinement
    # create a project file
    init_gpx = os.path.join(
        gpx_loc, output_stem_fn + "_initial.gpx"
    )
    if os.path.exists(init_gpx):
        os.remove(init_gpx)
    gpx = G2sc.G2Project(newgpx=init_gpx)

    # add a bank histogram to the project
    hists = []
    if stype == "N":
        hist1 = gpx.add_powder_histogram(
            gsa_fn, prm_fn, fmthint="GSAS powder",
            databank=bank, instbank=bank
        )
        hist1.set_refinements({'Limits': [xmin, xmax]})
    if stype == "X":
        hist1 = gpx.add_powder_histogram(
            gsa_fn,
            prm_fn,
            fmthint="GSAS powder"
        )
        hist1.set_refinements({'Limits': [xmin, xmax]})

    hists.append(hist1)

    # step 2: add a phase and link it to the previous histograms
    _ = gpx.add_phase(
        structure_fn,
        phasename='structure',
        fmthint='CIF',
        histograms=hists
    )

    cell_i = gpx.phase('structure').get_cell()

    # step 3: increase # of cycles to improve convergence
    gpx.data['Controls']['data']['max cyc'] = 5

    # step 4: start refinement
    # refinement step 1: turn on  Histogram Scale factor
    refdict1 = {
        "set": {
            "Sample Parameters": ["Scale"]
        },
        "call": HistStats,
    }
    # refinement step 2: turn on background refinement (Hist)
    refdict2 = {
        "set": {
            "Background": {
                "type": "chebyschev",
                "no. coeffs": 6,
                "refine": True
            }
        },
        "call": HistStats,
    }
    # refinement step 3: refine lattice parameter and Uiso refinement (Phase)
    refdict3 = {
        "set": {
            "Atoms": {"all": "U"},
            "Cell": True
        },
        "call": HistStats,
    }

    dictList = [refdict1, refdict2, refdict3]

    # before fit, save project file first. Then in the future,
    # the refined project file will update this one.
    ref_gpx = os.path.join(
        gpx_loc, output_stem_fn + "_refined.gpx"
    )
    gpx.save(ref_gpx)

    gpx.do_refinements(dictList)
    print("================")

    # save results data

    rw = gpx.histogram(0).get_wR() * 0.01
    x = np.array(gpx.histogram(0).getdata('X'))
    y = np.array(gpx.histogram(0).getdata('Yobs'))
    ycalc = np.array(gpx.histogram(0).getdata('Ycalc'))
    dy = np.array(gpx.histogram(0).getdata('Residual'))
    bkg = np.array(gpx.histogram(0).getdata('Background'))

    output_cif_fn = os.path.join(
        gpx_loc,
        output_stem_fn + "_refined.cif")

    gpx.phase('structure').export_CIF(output_cif_fn)
    cell_r = gpx.phase('structure').get_cell()

    return rw, x, y, ycalc, dy, bkg, cell_i, cell_r


def run_gsas2_fit_all(
        structure_fn, gsa_fn, prm_fn, output_stem_fn,
        stype, num_banks, xmin_all, xmax_all):
    '''
    Parameters
    ----------
    structure_fn: str
        input structure cif filename.
    gsa_fn: str
        input gsa filename.
    instprm_fn: str
        input instrument profile filename.
    output_stem_fn: str
        output stem filename.
    banks: str
        bank 1-6.

    Returns
    -------
    gsas2_poj : str
        gsas2 .gpx project file
    '''
    def HistStats(gpx):
        '''prints profile rfactors for all histograms'''
        print(u"*** profile Rwp, " + os.path.split(gpx.filename)[1])
        for hist in gpx.histograms():
            print("\t{:20s}: {:.2f}".format(hist.name, hist.get_wR()))
        print("")

    print("INFO: Build GSAS-II Project File.")
    print("******************************")

    # start GSAS-II refinement
    # create a project file
    init_gpx = os.path.join(
        gpx_loc, output_stem_fn + "_initial.gpx"
    )
    if os.path.exists(init_gpx):
        os.remove(init_gpx)
    gpx = G2sc.G2Project(newgpx=init_gpx)

    hists = []
    if stype == "N":
        for bank in range(num_banks):
            hist_tmp = gpx.add_powder_histogram(
                gsa_fn, prm_fn,
                fmthint="GSAS powder",
                databank=bank + 1,
                instbank=bank + 1
            )
            hist_tmp.set_refinements({'Limits': [xmin_all[bank + 1], xmax_all[bank + 1]]})
            hists.append(hist_tmp)

    # step 2: add a phase and link it to the previous histograms
    _ = gpx.add_phase(
        structure_fn,
        phasename='structure',
        fmthint='CIF',
        histograms=hists
    )

    cell_i = gpx.phase('structure').get_cell()

    # step 3: increase # of cycles to improve convergence
    gpx.data['Controls']['data']['max cyc'] = 5

    # step 4: start refinement
    # refinement step 1: turn on  Histogram Scale factor
    refdict1 = {
        "set": {
            "Sample Parameters": ["Scale"]
        },
        "call": HistStats,
        "histograms": hists
    }
    # refinement step 2: turn on background refinement (Hist)
    refdict2 = {
        "set": {
            "Background": {
                "type": "chebyschev",
                "no. coeffs": 6,
                "refine": True
            }
        },
        "call": HistStats,
        "histograms": hists
    }
    # refinement step 3: refine lattice parameter and Uiso refinement (Phase)
    refdict3 = {
        "set": {
            "Atoms": {
                "all": "U"
            },
            "Cell": True
        },
        "call": HistStats,
        "histograms": hists
    }

    dictList = [refdict1, refdict2, refdict3]

    # before fit, save project file first. Then in the future,
    # the refined project file will update this one.
    ref_gpx = os.path.join(
        gpx_loc, output_stem_fn + "_refined.gpx"
    )
    gpx.save(ref_gpx)

    gpx.do_refinements(dictList)
    print("================")

    # save results data

    rw = list()
    x = list()
    y = list()
    ycalc = list()
    dy = list()
    bkg = list()
    for bank in range(num_banks):
        rw.append(gpx.histogram(bank).get_wR() * 0.01)
        x.append(np.array(gpx.histogram(bank).getdata('X')))
        y.append(np.array(gpx.histogram(bank).getdata('Yobs')))
        ycalc.append(np.array(gpx.histogram(bank).getdata('Ycalc')))
        dy.append(np.array(gpx.histogram(bank).getdata('Residual')))
        bkg.append(np.array(gpx.histogram(bank).getdata('Background')))

    output_cif_fn = os.path.join(
        gpx_loc,
        output_stem_fn + "_refined.cif"
    )

    gpx.phase('structure').export_CIF(output_cif_fn)
    cell_r = gpx.phase('structure').get_cell()

    return rw, x, y, ycalc, dy, bkg, cell_i, cell_r


if __name__ == "__main__":
    run_gsas2_fit(
        structure_fn, gsa_fn, prm_fn, output_stem_fn,
        stype, bank, xmin, xmax
    )

    run_gsas2_fit_all(
        structure_fn, gsa_fn, prm_fn, output_stem_fn,
        stype, num_banks, xmin_all, xmax_all
    )

References

[1] https://gsas-ii.readthedocs.io/en/latest/GSASIIscriptable.html

[2] https://advancedphotonsource.github.io/GSAS-II-tutorials/install.html

[3] https://iris2020.net/2025-08-01-gsasii_on_linux/