source: Tutorials/PythonScript/Scripting.htm

Last change on this file was 4457, checked in by toby, 18 months ago

add data link to tutorials

  • Property svn:mime-type set to text/html
File size: 29.0 KB
Line 
1<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
2<html> <head>
3<title>Scripting GSAS-II</title>
4</head>
5
6<body>
7<h1>Running a GSAS-II Refinement From a Python Script</h1>
8
9<P><BL>
10  <LI>Exercise files are found <A href="./data/" target="_blank">here</a>
11</BL></P><P></P>
12
13 To demonstrate the use of the
14<A href="http://gsas-ii.readthedocs.io/en/latest/GSASIIscripts.html" target="_blank">
15GSASIIscriptable module</A>. This uses a Python script
16to perform a refinement or computation, but without use of the GSAS-II
17graphical user interface. Note that the
18<A href="http://gsas-ii.readthedocs.io/en/latest/GSASIIscripts.html" target="_blank">
19GSASIIscriptable module</A> does not offer access to all of the
20features within GSAS-II, but over time it is expected to grow in
21capabilities. Much of the initial development for this module was done
22by Jackson O'Donnell, as a summer undergraduate visitor under
23supervisor Dr. Maria Chan. Other programming contributions are welcome.
24<P>
25This tutorial has three sections:
26<OL type="A">
27<LI><a href="#multistep"> Create a Multi-step Script</A></LI>
28<LI><a href="#SingleStep">Single-Step Refinement</a></LI>
29<LI><a href="#Simulate">Powder Pattern Simulation</a></LI>
30</OL>
31The first section duplicates the refinement in the
32<A
33href="https://subversion.xray.aps.anl.gov/pyGSAS/Tutorials/CWCombined/Combined%20refinement.htm"
34target="_blank">GSAS-II CW Combined Refinement</A>
35tutorial as a multi-step process. The second section repeats the previous
36refinement, but demonstrates how a complex process can be entered into
37a single Python dict and the refinement executed with a single
38function call. The third section shows how a pattern simulation,
39rather than refinement can be executed from a script.
40
41
42<h2>Prerequisites</h2>
43This exercise assumes that the reader has reasonable familiarity with
44the Python language.
45Also, the documentation on the
46<A href="http://gsas-ii.readthedocs.io/en/latest/GSASIIscripts.html"
47target="_blank">
48Scripting Tools in the GSAS-II GSASIIscriptable module</A> should be
49read from here: <A href="http://gsas-ii.readthedocs.io/en/latest/GSASIIscripts.html"
50target="_blank">http://gsas-ii.readthedocs.io/en/latest/GSASIIscripts.html</A>. It
51is also wise to read the <A href="https://subversion.xray.aps.anl.gov/pyGSAS/Tutorials/CWCombined/Combined%20refinement.htm"
52target="_blank">GSAS-II CW Combined Refinement</A> tutorial that this
53exercise is modeled upon, which explains why each refinement step is
54being used.
55The exercise will require downloading of the same files needed for the
56Combined Refinement tutorial: "PBSO4.XRA", "INST_XRY.PRM", "PBSO4.CWN",
57"inst_d1a.prm" and "PbSO4-Wyckoff.cif",
58which can be downloaded from
59<A href="https://subversion.xray.aps.anl.gov/pyGSAS/Tutorials/PythonScript/data/">
60https://subversion.xray.aps.anl.gov/pyGSAS/Tutorials/PythonScript/data/</A>)
61or will be downloaded with this tutorial if that is requested.
62<P>
63The exercise can be performed by placing all of the Python commands
64into a script,
65but a more pedagogical approach will be to enter the
66commands into a Python interpreter. Use of IPython or Jupyter to run
67Python will make this a more pleasant experience.
68
69<a name="multistep">
70<h2>A. Create a Multi-step Script</h2></a>
71
72Note that the script in this section is supplied for
73<A href="https://subversion.xray.aps.anl.gov/trac/pyGSAS/browser/Tutorials/PythonScript/data/example.py?format=txt">
74download here</A>, but some editing will be needed to match where files
75are found on your computer.
76
77<h4>0: Load the GSASIIscriptable module</H4>
78<blockquote>
79The first step in writing any Python module is to load the modules
80that will be needed. Here we will need the <tt>os</tt> and
81<tt>sys</tt> modules from the Python standard library and the
82GSASIIscriptable from the GSAS-II code. The location where the
83GSAS-II source code is installed must usually be hard-coded into the
84script as is done in the example below. Note that a common location
85for this will be
86<TT>os.path.expanduser("~/g2conda/GSASII/")</TT> or
87<tt>'/Users/toby/software/GSASII'</tt>, etc.
88Thus the script will begin with something like this:
89
90<blockquote><textarea rows="3" cols="60" readonly>
91import os,sys
92sys.path.insert(0,os.path.expanduser("~/g2conda/GSASII/"))
93import GSASIIscriptable as G2sc</textarea></blockquote>
94
95If a <tt>ImportError: No module named GSASIIscriptable</tt> error
96occurs, then the wrong directory location has been supplied for the
97GSAS-II files.
98</blockquote>
99
100<h4>1: Define some other prerequisite code</H4>
101<blockquote>
102To simplify this example, we will define the location where files will
103be written as <tt>workdir</tt> (this directory must exist, but it may
104be empty) and the location where the input files for this exercise
105("PBSO4.XRA", "INST_XRY.PRM", "PBSO4.CWN",
106"inst_d1a.prm" and "PbSO4-Wyckoff.cif") will
107be found as <tt>datadir</tt>. (As discussed previously,
108these files can be
109<A href="https://subversion.xray.aps.anl.gov/pyGSAS/Tutorials/PythonScript/data/">
110downloaded from here. </A>)
111<P>
112We also define here a short function to display the weighted profile R
113factor for every histogram in a project, <tt>HistStats</tt>. This will
114be <A href="#HistStats">discussed later</A>.
115
116<blockquote><textarea rows="10" cols="70" readonly>
117workdir = "/Users/toby/Scratch/PythonScript"
118datadir = "/Users/toby/software/G2/Tutorials/PythonScript/data"
119
120def HistStats(gpx):
121    '''prints profile rfactors for all histograms'''
122    print(u"*** profile Rwp, "+os.path.split(gpx.filename)[1])
123    for hist in gpx.histograms():
124        print("\t{:20s}: {:.2f}".format(hist.name,hist.get_wR()))
125    print("")
126    gpx.save()</textarea></blockquote>
127
128</blockquote>
129
130<h4>2: Create a GSAS-II project</H4>
131<blockquote>
132The first step in creating a GSASIIscriptable script to to create or
133access a GSAS-II project, which is done with a call to
134<TT>GSASIIscriptable.G2Project()</tt>. This can be done in one of two
135ways: a call with <tt>G2sc.G2Project(newgpx=</tt><I>file</I><tt>)</tt> creates a new
136(empty) project, while a call with
137<tt>G2sc.G2Project(gpxfile=</tt><I>file</I><tt>)</tt> opens and
138reads an existing project (.gpx) file. Both return a <tt>G2Project</tt> wrapper
139object that is used to access a number of methods and variables.
140Note that <TT>GSASIIscriptable.G2Project()</tt> can read .gpx files
141written by both previous <TT>GSASIIscriptable.G2Project()</tt> runs or
142the GSAS-II GUI.
143<P>
144In this example, we create a new project by using the
145<tt>newgpx=</tt><I>file</I> argument with this code:
146   
147<blockquote><textarea rows="3" cols="70" readonly>
148# create a project with a default project name
149gpx = G2sc.G2Project(newgpx='PbSO4.gpx')</textarea></blockquote>
150
151Note that the file will not actually be created until an operation
152that saves the project is called.
153</blockquote>
154
155<h4>3: Add Histograms and Phase to the GSAS-II project</H4>
156<blockquote>
157To add two powder diffraction datasets (histograms) and a phase to the
158project using this code:
159
160<blockquote><textarea rows="10" cols="70" readonly>
161# setup step 1: add two histograms to the project
162hist1 = gpx.add_powder_histogram(os.path.join(datadir,"PBSO4.XRA"),
163                          os.path.join(datadir,"INST_XRY.PRM"))
164hist2 = gpx.add_powder_histogram(os.path.join(datadir,"PBSO4.CWN"),
165                          os.path.join(datadir,"inst_d1a.prm"))
166# setup step 2: add a phase and link it to the previous histograms
167phase0 = gpx.add_phase(os.path.join(datadir,"PbSO4-Wyckoff.cif"),
168                      phasename="PbSO4",
169                      histograms=[hist1,hist2])</textarea></blockquote>
170
171 
172We use the <I>project</I><tt>.add_powder_histogram()</tt> method in
173the <TT>GSASIIscriptable</tt> class to read in the powder data.
174The two arguments to
175<tt>.add_powder_histogram()</tt> are the powder dataset and the
176  instrument parameter file. Note that these files are both "GSAS
177  powder data" files and the importer for this format (and many
178  others) allows files with arbitrary extensions to be read.
179All importers that allow for extensions .XRA and .CWN will be
180used to attempt to read the file, producing a number of warning
181messages. To specify that only the GSAS powder data importer be
182used, include a third argument, <tt>fmthint="GSAS powder"</tt> or
183something similar (<tt>fmthint="GSAS"</tt> is also fine, but will
184cause both the "GSAS powder data" and the "GSAS-II .gpx" importer to be considered.)
185<UL><LI>
186  Note that <I>project</I><tt>.add_powder_histogram()</tt> returns a
187  powder histogram objects, which here are saved for later reference. It is
188  also possible to obtain these using <tt>gpx.histograms()</tt>, which
189  returns a list of defined histograms.
190</UL>
191<P>
192Then we add a phase to the project using
193  <I>project</I><tt>.add_phase()</tt>. This specifies a CIF containing the
194  structural information, a name for the phase and specifies that the
195  two histograms are "added" (linked) to the phase. The
196<tt>fmthint="CIF"</tt> parameter can also optionally be specified to limit the
197importers that will be tried.
198
199  <UL><LI>
200  Note that <I>project</I><tt>.add_phase()</tt>
201  returns a phase object</li>
202  <LI>Also, the previously saved histogram objects are used in the
203  <I>project</I><tt>.add_phase()</tt> call. Note that it is
204  also possible to reference the two histgrams by their numbers in the
205  project (here <tt>histograms=[0,1]</tt>) or by the histogram names
206  (here <BR><TT>histograms=['PWDR PBSO4.XRA Bank 1', 'PWDR PBSO4.CWN
207  Bank 1']</TT>).
208  These three ways to use the <tt>histograms</tt> parameter produce
209  the same result.
210</blockquote>
211   
212<A name="ChangeCycles">
213<h4>4: Change the number of refinement cycles</H4>
214</A><blockquote>
215While this is not noted in the original tutorial, this exercise will
216  not complete properly if more variables are added to the refinement
217  without converging the refinement (or at least coming close to
218  convergence) at each refinement step. This is best accomplished by
219  increasing the number of least-squares cycles. No supplied method (at
220  present) allows this parameter to be set straightforwardly, but this
221  code will do this:
222 
223 <blockquote><textarea rows="3" cols="70" readonly>
224# not in tutorial: increase # of cycles to improve convergence
225gpx.data['Controls']['data']['max cyc'] = 8 # not in API </textarea></blockquote>
226
227<P>
228  To find this parameter in the GSAS-II data structure, I followed
229  these steps: In the GUI, Controls is the tree item
230  corresponding to the section where Least Squares cycles are
231  set. Executing the command <tt>gpx.data.keys()</tt> shows the names of the
232  entries in the dictionary corresponding to the GSAS-II tree and
233  indeed one entry is 'Controls'.
234  Command <tt>gpx.data['Controls'].keys()</tt> shows that all
235  values are located in an entry labeled 'data' and
236  <tt>gpx.data['Controls']['data'].keys()</tt> shows the entries in
237this section. Examination of
238<tt>gpx.data['Controls']['data']['max cyc']</tt> shows the value 3,
239which is default number of cycles. Thus,
240the number of cycles is changed with the Python command above.
241
242</blockquote>
243
244<h4>5: Set initial variables and refine</H4>
245<blockquote>
246
247In Step 4 of the original tutorial, the refinement is performed with
248the variables that are on by default. These variables are the two
249histogram scale factors and three background parameters for each
250histogram (8 in total). With GSASIIscriptable, the background
251refinement flags are not turned on by default, so a dictionary must be
252created to set these histogram variables. This code:
253<blockquote><textarea rows="5" cols="75" readonly>
254# tutorial step 4: turn on background refinement (Hist)
255refdict0 = {"set": {"Background": { "no. coeffs": 3, "refine": True }}}
256gpx.save('step4.gpx')
257gpx.do_refinements([refdict0])
258HistStats(gpx)</textarea></blockquote>
259<UL>
260<LI>defines a dictionary (refdict0) that will be used to set the number of background coefficients (not really
261needed, since the default is 3) and sets the background refinement
262flag "on".</li>
263<LI>The project is saved under a new name, so that we can later look at
264the results from each step separately.</li>
265<LI>The parameters in refdict0 are set using
266<I>project</i><tt>.do_refinements()</tt> for both histograms in the
267project and the a refinement is run.
268<LI>The weighted profile R-factor values for all histograms in the project
269are printed using the previously defined <tt>HistStats()</tt> function.
270</UL>
271
272<A name="HistStats">
273Function <tt>HistStats()</tt> works by using <tt>gpx.histograms()</tt>
274to iterate over all histograms in the project, setting <tt>hist</tt> to each histogram
275object. Class member <tt>hist.name</tt> provides the histogram name
276and method <tt>hist.get_wR()</tt> looks up the profile R-factor and
277prints them. The function also writes the final refinement results
278into the current project file. </A>
279
280The output from this will be:<blockquote><pre>
281 Hessian Levenburg-Marquardt SVD refinement on 8 variables:
282initial chi^2 9.6912e+06
283 Cycle: 0, Time: 1.88s, Chi**2: 6.7609e+05, Lambda: 0.001,  Delta: 0.93
284initial chi^2 6.7609e+05
285 Cycle: 1, Time: 1.84s, Chi**2: 6.7602e+05, Lambda: 0.001,  Delta: 0.000104
286converged
287Found 0 SVD zeros
288Read from file: /Users/toby/software/G2/Tutorials/PythonScript/step4.bak0.gpx
289Save to file  : /Users/toby/software/G2/Tutorials/PythonScript/step4.gpx
290GPX file save successful
291 Refinement results are in file: /Users/toby/software/G2/Tutorials/PythonScript/step4.lst
292 ***** Refinement successful *****
293*** profile Rwp, step4.gpx
294        PWDR PBSO4.XRA Bank 1: 40.88
295        PWDR PBSO4.CWN Bank 1: 18.65
296</pre></blockquote>Note that the Rwp values agree with what is
297 expected from the original tutorial.
298<P>
299<B>Note:</B> that there are several equivalent ways to set the histogram
300parameters using
301<tt>G2PwdrData.set_refinements()</tt>,
302<tt>G2Project.set_refinement()</tt> or
303<tt>my_project.do_refinements()</tt>, as
304<A href="http://gsas-ii.readthedocs.io/en/latest/GSASIIscripts.html#refinement-parameters">
305described here</A>. Thus, the <tt>gpx.do_refinements([refdict0])</tt>
306statement above could be replaced with:
307<blockquote><pre>
308gpx.set_refinement({"Background": { "no. coeffs": 3, "refine": True }})
309gpx.do_refinements([{}])
310</pre></blockquote>
311or
312<blockquote><pre> 
313for hist in gpx.histograms():
314    hist.set_refinements({"Background": { "no. coeffs": 3, "refine": True }})
315gpx.do_refinements([{}])
316</pre></blockquote>
317
318</blockquote>
319<h4>6: Add unit cell parameters to refinement</h4>
320<blockquote>
321
322In Step 5 of the original tutorial, the refinement is performed again,
323but the unit cell is refined in the phase.
324
325<blockquote><textarea rows="6" cols="75" readonly>
326# tutorial step 5: add unit cell refinement (Phase)
327gpx.save('step5.gpx')
328refdict1 = {"set": {"Cell": True}} # set the cell flag (for all phases)
329gpx.set_refinement(refdict1)
330gpx.do_refinements([{}])
331HistStats(gpx)</textarea></blockquote>
332
333In this case the <tt>gpx.set_refinement(refdict1)</tt> statement can
334be replaced with:<blockquote><pre>
335phase0.set_refinements({"Cell": True})
336</pre></blockquote>
337
338Note that it is also possible to combine the refinement in the current
339and previous section using
340<blockquote><pre>
341gpx.do_refinements([refdict0,refdict1])
342</pre></blockquote>
343but then the results are not saved in separate project files and it is
344not possible to see the Rwp values after each refinement.
345
346</blockquote>
347<h4>7: Add hydrostatic strain for just one histogram</h4>
348<blockquote>
349
350In Step 6 of the original tutorial, the refinement is performed again
351after adding Histogram/Phase (HAP) parameters so that the lattice
352constants for the first histogram (only) can vary. This is done with
353this code:
354
355<blockquote><textarea rows="6" cols="75" readonly>
356# tutorial step 6: add Dij terms (HAP) for histogram 1 only
357gpx.save('step6.gpx')
358refdict2 = {"set": {"HStrain": True}} # set HAP parameters
359gpx.set_refinement(refdict2,phase=phase0,histogram=[hist1])
360gpx.do_refinements([{}]) # refine after setting
361HistStats(gpx)</textarea></blockquote>
362
363Here we cannot use <tt>gpx.do_refinements([refdict2])</tt> with
364<tt>refdict2</tt> defined as above because
365that would turn on refinement of the Hstrain terms for all histograms
366and all phases. There are several ways to restrict the parameter
367changes to specified histogram(s) and phase(s). One is to call a
368method in the phase object(s) directly, such as
369replacing the <tt>gpx.set_refinement(...)</tt>
370statement with this:
371<blockquote><pre>
372phase0.set_HAP_refinements({"HStrain": True},histograms=[hist1])
373</pre></blockquote>
374
375It is also possible to add "histograms" and/or "phases" values into
376the <tt>refdict2</tt> dict, as will be <a href="#SingeStep">described below.</a>
377</blockquote>
378
379<h4>8: Add X-ray Sample broadening terms</h4>
380<blockquote>
381The next step in the original tutorial is to treat sample broadening
382by turning on refinement of the "Mustrain" (microstrain) and
383"Size" (Scherrer broadening) terms using an isotropic (single-term)
384model. As described in the
385<A
386href="http://gsas-ii.readthedocs.io/en/latest/GSASIIscripts.html#histogram-and-phase-parameters">
387documentation for Histogram/Phase parameters</A>, type must always be
388specfied even as in this case where it is not being changed from the
389existing default. Again, since these parameters are being set only for
390one histogram, either <tt>phase0.set_HAP_refinements()</tt> or
391<tt>gpx.set_refinement()</tt> must be called or to use
392<tt>gpx.do_refinements([refdict3])</tt> the "histograms" element must be
393included inside <tt>refdict3</tt>.
394
395<blockquote><textarea rows="8" cols="75" readonly>
396# tutorial step 7: add size & strain broadening (HAP) for histogram 1 only
397gpx.save('step7.gpx')
398refdict3 = {"set": {"Mustrain": {"type":"isotropic","refine":True},
399                    "Size":{"type":"isotropic","refine":True},
400                    }}
401gpx.set_refinement(refdict3,phase=phase0,histogram=[hist1])
402gpx.do_refinements([{}]) # refine after setting
403HistStats(gpx)</textarea></blockquote>
404
405</blockquote>
406<h4>9: Add Structural and Sample Displacement Parameters</h4>
407<blockquote>
408The step 8 in the original tutorial is to treat sample displacement
409for each histogram/phase. These parameters are different because of
410the differing diffractometer geometries. We also add refinement of
411sample parameters using <tt>phase0.set_refinements()</tt> to set the
412"X" (coordinate) and "U" (displacement) refinement flags for all
413atoms. This is done with this code:
414
415<blockquote><textarea rows="9" cols="75" readonly>
416# tutorial step 8: add sample parameters & set radius (Hist); refine atom parameters (phase)
417gpx.save('step8.gpx')
418hist1.set_refinements({'Sample Parameters': ['Shift']})
419hist2.set_refinements({'Sample Parameters': ['DisplaceX', 'DisplaceY']})
420hist2.data['Sample Parameters']['Gonio. radius'] = 650. # not in API
421phase0.set_refinements({"Atoms":{"all":"XU"}})
422gpx.do_refinements([{}]) # refine after setting
423HistStats(gpx)</textarea></blockquote>
424
425Note that the original tutorial
426calls for the diffractometer radius to be changed to the correct value
427so that the displacement value is in the correct units. This parameter
428cannot be set from any GSASIIscriptable routines, but following a
429similar process,
430<A href="#ChangeCycles">as before</A>, the location for this
431setting can be located in the histogram's 'Sample Parameters' section
432(as <tt>hist2.data['Sample Parameters']['Gonio. radius']</tt>).
433
434Also note that the settings provided in the
435<tt>phase0.set_refinements()</tt> and statements
436<tt>gpx.do_refinements()</tt> could have
437been combined into this single statement:
438<blockquote><pre>
439gpx.do_refinements({"set":{"Atoms":{"all":"XU"}})
440</pre></blockquote>
441
442</blockquote>
443<h4>10: Change Data Limits; Vary Gaussian Profile Terms</h4>
444<blockquote>
445The final step in the original tutorial is to trim the range of data
446used in the refinement to exclude data where no reflections occur and
447where the peaks are cut off at high angle. Also, additional parameters
448are refined here because the supplied instrumental profile parameters
449are not very accurate descriptions for the datasets that are used
450here. It is not possible to refine the Lorentzian x-ray instrumental
451broadening terms, since this broadening is treated as sample
452broadening. The Lorentzian neutron broadening is negligible.
453
454<blockquote><textarea rows="6" cols="75" readonly>
455# tutorial step 9: change data limits & inst. parm refinements (Hist)
456gpx.save('step9.gpx')
457hist1.set_refinements({'Limits': [16.,158.4]})
458hist2.set_refinements({'Limits': [19.,153.]})
459gpx.do_refinements([{"set": {'Instrument Parameters': ['U', 'V', 'W']}}])
460HistStats(gpx)</textarea></blockquote>
461
462Note that the final <tt>gpx.do_refinements()</tt> statement can be
463replaced with calls to
464<tt>hist</tt><I>X</I><tt>.set_refinements()</tt> or
465<tt>gpx.set_refinement()</tt>, such as
466<blockquote><pre>
467hist1.set_refinements({'Instrument Parameters': ['U', 'V', 'W']})
468hist2.set_refinements({'Instrument Parameters': ['U', 'V', 'W']})
469gpx.do_refinements([{}])
470</pre></blockquote>
471
472</blockquote>
473<a name="SingleStep">
474<h2>B. Single-Step Refinement</h2></a>
475<blockquote>
476
477As is noted in the
478<A href="http://gsas-ii.readthedocs.io/en/latest/GSASIIscripts.html" target="_blank">
479GSASIIscriptable module documentation</A>,
480the <I>project</i><tt>.do_refinements()</tt> method can be used to
481perform multiple refinement steps.
482Note that this version of the exercise can be
483<A href="https://subversion.xray.aps.anl.gov/trac/pyGSAS/browser/Tutorials/PythonScript/data/SingleStep.py?format=txt">
484downloaded here</A>.
485To duplicate the above steps into a
486single call, a more complex set of dicts must be created, as shown
487below:
488
489<blockquote><textarea rows="38" cols="75" readonly>
490# tutorial step 4: turn on background refinement (Hist)
491refdict0 = {"set": {"Background": { "no. coeffs": 3, "refine": True }},
492            "output":'step4.gpx',
493            "call":HistStats,"callargs":[gpx]} # callargs actually unneeded
494                                               # as [gpx] is the default
495# tutorial step 5: add unit cell refinement (Phase)
496refdict1 = {"set": {"Cell": True},    # set the cell flag (for all phases)
497            "output":'step5.gpx', "call":HistStats}
498# tutorial step 6: add Dij terms (HAP) for phase 1 only
499refdict2 = {"set": {"HStrain": True},  # set HAP parameters
500            "histograms":[hist1],      # histogram 1 only
501            "phases":[phase0],         # unneeded (default is all
502                                       # phases) included as a example
503            "output":'step6.gpx', "call":HistStats}
504# tutorial step 7: add size & strain broadening (HAP) for histogram 1 only
505refdict3 = {"set": {"Mustrain": {"type":"isotropic","refine":True},
506                    "Size":{"type":"isotropic","refine":True},},
507            "histograms":[hist1],      # histogram 1 only
508            "output":'step7.gpx', "call":HistStats}
509# tutorial step 8: add sample parameters & set radius (Hist); refine
510#                  atom parameters (phase)
511refdict4a = {"set": {'Sample Parameters': ['Shift']},
512            "histograms":[hist1],      # histogram 1 only
513             "skip": True}
514refdict4b = {"set": {"Atoms":{"all":"XU"}, # not affected by histograms
515             'Sample Parameters': ['DisplaceX', 'DisplaceY']},
516            "histograms":[hist2],      # histogram 2 only
517            "output":'step8.gpx', "call":HistStats}
518# tutorial step 9: change data limits & inst. parm refinements (Hist)
519refdict5a = {"set": {'Limits': [16.,158.4]},
520            "histograms":[hist1],      # histogram 1 only
521             "skip": True,}
522refdict5b = {"set": {'Limits': [19.,153.]},
523            "histograms":[hist2],      # histogram 2 only
524             "skip": True}
525refdict5c = {"set": {'Instrument Parameters': ['U', 'V', 'W']},
526            "output":'step9.gpx', "call":HistStats}
527</textarea></blockquote>
528
529Note that above the "call" and "callargs" dict entries are
530defined to run <tt>HistStats</tt> and "output" is used to designate
531the .gpx file that will be needed. When parameters should be changed
532in specific histograms, the entries <tt>"histograms":[hist1]</tt> and
533<tt>"histograms":[hist2]</tt> are used
534(equivalent would be <tt>"histograms":[0]</tt> and
535<tt>"histograms":[1]</tt>).
536Since there is only one phase present, use of <tt>"phase":[0]</tt> is
537superfluous, but in a more complex refinement, this could be needed.
538<p>
539A list of dicts is then prepared here:
540<blockquote><textarea rows="3" cols="75" readonly>
541dictList = [refdict0,refdict1,refdict2,refdict3,
542            refdict4a,refdict4b,
543            refdict5a,refdict5b,refdict5c]</textarea></blockquote>
544
545Steps 4 through 10, above then can be performed with these few commands:
546<blockquote><textarea rows="4" cols="75" readonly>
547# Change number of cycles and radius
548gpx.data['Controls']['data']['max cyc'] = 8 # not in API
549hist2.data['Sample Parameters']['Gonio. radius'] = 650. # not in API
550gpx.do_refinements(dictList)</textarea></blockquote>
551
552</blockquote>
553<a name="Simulate">
554<h2>C. Powder Pattern Simulation</h2></a>
555<blockquote>
556Use of the
557<A href="http://gsas-ii.readthedocs.io/en/latest/GSASIIscripts.html" target="_blank">
558GSASIIscriptable module</A> makes it very simple to simulate a powder
559diffraction pattern using GSAS-II. This is demonstrated in this
560section.
561
562Note that the Python commands can be
563<A
564href="https://subversion.xray.aps.anl.gov/trac/pyGSAS/browser/Tutorials/PythonScript/data/sim.py?format=txt">downloaded here</A>.
565<P>
566As before, the location of the GSASIIscripts Python module must be
567defined and the module must be loaded:
568
569<blockquote><textarea rows="3" cols="60" readonly>
570import os,sys
571sys.path.insert(0,os.path.expanduser("~/g2conda/GSASII/"))
572import GSASIIscriptable as G2sc</textarea></blockquote>
573
574To simplify this example, as before we will define the location where files will
575be read from and written (as <tt>datadir</tt> and
576<tt>workdir</tt>). Note that files "inst_d1a.prm" and
577"PbSO4-Wyckoff.cif" from <A
578href="https://subversion.xray.aps.anl.gov/pyGSAS/Tutorials/PythonScript/data/">here</A>
579are needed.
580
581<blockquote><textarea rows="2" cols="70" readonly>
582workdir = "/Users/toby/Scratch/PythonScript"
583datadir = "/Users/toby/software/G2/Tutorials/PythonScript/data"</textarea></blockquote>
584
585We then need to create a project and for this example we choose to
586define the phase first. (It would work equally well to create the
587histogram first and then define the phase.)
588
589<blockquote><textarea rows="4" cols="70" readonly>
590gpx = G2sc.G2Project(newgpx='PbSO4sim.gpx') # create a project
591# step 1, setup: add a phase to the project
592phase0 = gpx.add_phase(os.path.join(datadir,"PbSO4-Wyckoff.cif"),
593                      phasename="PbSO4",fmthint='CIF') </textarea></blockquote>
594
595We then add a "dummy" histogram to the project. Note that an
596instrument parameter file is specified, but not a data file. The range
597of data to be used and the step size must be specified. The phases
598parameter is specified as ``gpx.phases()`` which creates a list of all
599the previously read phases, which in this case is equivalent to
600``[phase0]``.
601
602<blockquote><textarea rows="6" cols="80" readonly>
603# step 2, setup: add a simulated histogram and link it to the previous phase(s)
604hist1 = gpx.add_simulated_powder_histogram("PbSO4 simulation",
605                          os.path.join(datadir,"inst_d1a.prm"),
606                          5.,120.,0.01,
607                          phases=gpx.phases())</textarea></blockquote>
608
609Note that the computed pattern cannot be seen above "simulated noise"
610unless the intensities are large enough. We can change the pattern
611scale factor using the Scale factor (parameter
612<tt>hist1.data['Sample Parameters']['Scale'][0]</tt>), as shown below.
613
614<blockquote><textarea rows="3" cols="70" readonly>
615# Step 3: Set the scale factor to adjust the y scale
616hist1.SampleParameters['Scale'][0] = 1000000.
617</textarea></blockquote>
618
619Next, to perform the simulation computation, a refinement is
620needed:
621
622<blockquote><textarea rows="4" cols="80" readonly>
623# step 4, compute: turn off parameter optimization and calculate pattern
624gpx.data['Controls']['data']['max cyc'] = 0 # refinement not needed
625gpx.do_refinements([{}])
626gpx.save()</textarea></blockquote>
627
628However, there is no need to actually optimize any variables,
629so the number of refinement cycles is set to zero. Refinement is
630initiated then with <I>proj</i>.<tt>do_refinements</tt>. To keep the
631results in a .gpx file, the
632project is saved.
633
634<P>
635Finally, we want to do something with the results. The histogram could
636be written to a file with the <A href=
637"http://gsas-ii.readthedocs.io/en/latest/GSASIIscriptable.html#GSASIIscriptable.G2PwdrData.Export">
638<i>histogram.</i><tt>Export()</tt></A> command. Note that the first time
639a refinement computation is done with a dummy histogram the "observed"
640pattern is set from the calculated intensities. Here an alternate option is
641used, where the values are retrieved and plotted.
642
643<blockquote><textarea rows="6" cols="70" readonly>
644# step 5, retrieve results & plot
645x = gpx.histogram(0).getdata('x')
646y = gpx.histogram(0).getdata('ycalc')
647import matplotlib.pyplot as plt
648plt.plot(x,y)
649plt.savefig('PbSO4.png') # to show on screen use: plt.show()</textarea></blockquote>
650
651Note that in the above, <tt>gpx.histogram(0)</tt> is used to show how
652to reference <tt>hist1</tt> when the histogram object is not
653known. The generated two-theta values and computed intensity values
654are retrieved and the remaining lines generate a very simple plot
655which is saved to a file, as shown below.
656</blockquote>
657
658<img src="PbSO4.png">
659
660<hr>
661<address></address>
662<!-- hhmts start -->Last modified: Mon Jun  1 15:09:36 CDT 2020 <!-- hhmts end -->
663</body> </html>
Note: See TracBrowser for help on using the repository browser.