Changeset 3209
- Timestamp:
- Dec 28, 2017 12:50:40 PM (5 years ago)
- Files:
-
- 1 added
- 5 edited
Legend:
- Unmodified
- Added
- Removed
-
Tutorials/PythonScript/Scripting.htm
r3207 r3209 8 8 To demonstrate the use of the 9 9 <A href="http://gsas-ii.readthedocs.io/en/latest/GSASIIscripts.html" target="_blank"> 10 GSASIIscriptable module</A>, we create a Python script to duplicate the 11 refinement in the 12 <A 13 href="https://subversion.xray.aps.anl.gov/pyGSAS/Tutorials/CWCombined/Combined%20refinement.htm" 14 target="_blank">GSAS-II CW Combined Refinement</A> 15 tutorial. This uses a Python script 16 to perform the same refinements steps as in that tutorial, but without use of the GSAS-II 10 GSASIIscriptable module</A>. This uses a Python script 11 to perform a refinement or computation, but without use of the GSAS-II 17 12 graphical user interface. Note that the 18 13 <A href="http://gsas-ii.readthedocs.io/en/latest/GSASIIscripts.html" target="_blank"> … … 22 17 by Jackson O'Donnell, as a summer undergraduate visitor under 23 18 supervisor Dr. Maria Chan. Other programming contributions are welcome. 19 <P> 20 This tutorial has three sections: 21 <OL type="A"> 22 <LI><a href="#multistep"> Create a Multi-step Script</A></LI> 23 <LI><a href="#SingleStep">Single-Step Refinement</a></LI> 24 <LI><a href="#Simulate">Powder Pattern Simulation</a></LI> 25 </OL> 26 The first section duplicates the refinement in the 27 <A 28 href="https://subversion.xray.aps.anl.gov/pyGSAS/Tutorials/CWCombined/Combined%20refinement.htm" 29 target="_blank">GSAS-II CW Combined Refinement</A> 30 tutorial as a multi-step process. The second section repeats the previous 31 refinement, but demonstrates how a complex process can be entered into 32 a single Python dict and the refinement executed with a single 33 function call. The third section shows how a pattern simulation, 34 rather than refinement can be executed from a script. 35 24 36 25 37 <h2>Prerequisites</h2> … … 45 57 <P> 46 58 The exercise can be performed by placing all of the Python commands 47 into a script, (which is supplied for 48 <A href="https://subversion.xray.aps.anl.gov/trac/pyGSAS/browser/Tutorials/PythonScript/data/example.py?format=txt"> 49 download here</A>), 59 into a script, 50 60 but a more pedagogical approach will be to enter the 51 61 commands into a Python interpreter. Use of IPython or Jupyter to run 52 62 Python will make this a more pleasant experience. 53 63 54 <h2>Multi-step Script Approach</h2> 64 <a name="multistep"> 65 <h2>A. Create a Multi-step Script</h2></a> 66 67 Note that the script in this section is supplied for 68 <A href="https://subversion.xray.aps.anl.gov/trac/pyGSAS/browser/Tutorials/PythonScript/data/example.py?format=txt"> 69 download here</A>, but some editing will be needed to match where files 70 are found on your computer. 55 71 56 72 <h4>0: Load the GSASIIscriptable module</H4> … … 450 466 451 467 </blockquote> 452 <a name="SingleStep"><h2>Single Step Approach</h2></a> 468 <a name="SingleStep"> 469 <h2>B. Single-Step Refinement</h2></a> 453 470 <blockquote> 454 471 … … 457 474 GSASIIscriptable module documentation</A>, 458 475 the <I>project</i><tt>.do_refinements()</tt> method can be used to 459 perform multiple refinement steps. To duplicate the above steps into a 476 perform multiple refinement steps. 477 Note that this version of the exercise can be 478 <A href="https://subversion.xray.aps.anl.gov/trac/pyGSAS/browser/Tutorials/PythonScript/data/SingleStep.py?format=txt"> 479 downloaded here</A>. 480 To duplicate the above steps into a 460 481 single call, a more complex set of dicts must be created, as shown 461 482 below: 462 483 463 <blockquote><textarea rows="3 9" cols="75" readonly>484 <blockquote><textarea rows="38" cols="75" readonly> 464 485 # tutorial step 4: turn on background refinement (Hist) 465 486 refdict0 = {"set": {"Background": { "no. coeffs": 3, "refine": True }}, … … 515 536 dictList = [refdict0,refdict1,refdict2,refdict3, 516 537 refdict4a,refdict4b, 517 refdict5a,refdict5b,refdict5c] 518 </textarea></blockquote> 538 refdict5a,refdict5b,refdict5c]</textarea></blockquote> 539 519 540 Steps 4 through 10, above then can be performed with these few commands: 520 541 <blockquote><textarea rows="4" cols="75" readonly> … … 522 543 gpx.data['Controls']['data']['max cyc'] = 8 # not in API 523 544 hist2.data['Sample Parameters']['Gonio. radius'] = 650. # not in API 524 gpx.do_refinements(dictList) 525 </textarea></blockquote> 526 Note that this version of the exercise can be 527 <A href="https://subversion.xray.aps.anl.gov/trac/pyGSAS/browser/Tutorials/PythonScript/data/SingleStep.py?format=txt"> 528 downloaded here</A>). 545 gpx.do_refinements(dictList)</textarea></blockquote> 546 547 </blockquote> 548 <a name="Simulate"> 549 <h2>C. Powder Pattern Simulation</h2></a> 550 <blockquote> 551 Use of the 552 <A href="http://gsas-ii.readthedocs.io/en/latest/GSASIIscripts.html" target="_blank"> 553 GSASIIscriptable module</A> makes it very simple to simulate a powder 554 diffraction pattern using GSAS-II. This is demonstrated in this 555 section. 556 557 Note that the Python commands can be 558 <A 559 href="https://subversion.xray.aps.anl.gov/trac/pyGSAS/browser/Tutorials/PythonScript/data/sim.py?format=txt">downloaded here</A>. 560 <P> 561 As before, the location of the GSASIIscripts Python module must be 562 defined and the module must be loaded: 563 564 <blockquote><textarea rows="3" cols="60" readonly> 565 import os,sys 566 sys.path.insert(0,os.path.expanduser("~/g2conda/GSASII/")) 567 import GSASIIscriptable as G2sc</textarea></blockquote> 568 569 To simplify this example, as before we will define the location where files will 570 be read from and written (as <tt>datadir</tt> and 571 <tt>workdir</tt>). Note that files "inst_d1a.prm" and 572 "PbSO4-Wyckoff.cif" from <A 573 href="https://subversion.xray.aps.anl.gov/pyGSAS/Tutorials/PythonScript/data/">here</A> 574 are needed. 575 576 <blockquote><textarea rows="2" cols="70" readonly> 577 workdir = "/Users/toby/Scratch/PythonScript" 578 datadir = "/Users/toby/software/G2/Tutorials/PythonScript/data"</textarea></blockquote> 579 580 We then need to create a project and for this example we choose to 581 define the phase first. (It would work equally well to create the 582 histogram first and then define the phase.) 583 584 <blockquote><textarea rows="4" cols="70" readonly> 585 gpx = G2sc.G2Project(filename='PbSO4sim.gpx') # create a project 586 # setup step 1: add a phase to the project 587 phase0 = gpx.add_phase(os.path.join(datadir,"PbSO4-Wyckoff.cif"), 588 phasename="PbSO4",fmthint='CIF') </textarea></blockquote> 589 590 We then add a "dummy" histogram to the project. Note that an 591 instrument parameter file is specified, but not a data file. The range 592 of data to be used and the step size must be specified. The phases 593 parameter is specified as ``gpx.phases()`` which creates a list of all 594 the previously read phases, which in this case is equivalent to 595 ``[phase0]``. 596 597 <blockquote><textarea rows="6" cols="70" readonly> 598 # setup step 2: add a simulated histogram and link it to the previous phase(s) 599 hist1 = gpx.add_simulated_powder_histogram("PbSO4 simulation", 600 os.path.join(datadir,"inst_d1a.prm"), 601 5.,120.,0.01, 602 phases=gpx.phases())</textarea></blockquote> 603 604 Finally, to perform the simulation computation, a refinement is 605 needed: 606 607 <blockquote><textarea rows="3" cols="70" readonly> 608 gpx.data['Controls']['data']['max cyc'] = 0 # refinement not needed 609 gpx.do_refinements([{}]) 610 gpx.save()</textarea></blockquote> 611 612 However, there is no need to actually optimize any variables, 613 so the number of refinement cycles is set to zero. Refinement is 614 initiated then with <I>proj</i>.<tt>do_refinements</tt>. Finally, the 615 project is saved. 529 616 530 617 </blockquote> … … 532 619 <hr> 533 620 <address></address> 534 <!-- hhmts start -->Last modified: T ue Dec 26 17:03:22CST 2017 <!-- hhmts end -->621 <!-- hhmts start -->Last modified: Thu Dec 28 12:18:27 CST 2017 <!-- hhmts end --> 535 622 </body> </html> -
Tutorials/PythonScript/data/SingleStep.py
r3207 r3209 10 10 sys.path.insert(0,'/Users/toby/software/G2/GSASII') 11 11 import GSASIIscriptable as G2sc 12 13 import GSASIIpath14 GSASIIpath.LoadConfigFile('config.py')15 12 16 13 workdir = "/Users/toby/Scratch/PythonScript" -
trunk/GSASIIctrlGUI.py
r3207 r3209 12 12 --------------------------------------------- 13 13 14 A library of GUI controls for reuse throughout GSAS-II 14 A library of GUI controls for reuse throughout GSAS-II, as indexed below 15 16 ================================ ================================================================= 17 Class or function name Description 18 ================================ ================================================================= 19 :class:`ValidatedTxtCtrl` A text control with a built-in call back routine to set dict 20 or list elements. Optionally validates input as float, int or 21 for strings non-blank. Value is set when focus changes 22 :class:`EnumSelector` A combo box with a built-in call back routine that 23 automatically sets a dict or list entry. 24 :class:`G2ChoiceButton` A customized wx.Choice that automatically initializes to 25 the initial value and saves the choice directly into a dict 26 or list value. Optionally calls function when a 27 choice is selected 28 :class:`G2CheckBox` A customized wx.CheckBox that automatically initializes to 29 the initial value and saves the choice directly into a dict 30 or list value. Optionally calls function when a 31 choice is selected 32 :func:`CallScrolledMultiEditor` Routine for editing many dict- or list-contained items. 33 using the :class:`ScrolledMultiEditor` dialog 34 :class:`ScrolledMultiEditor` wx.Dialog for editing many dict- or list-contained items. 35 with validation. Results are placed in dict or list. 36 :class:`G2MultiChoiceDialog` Dialog similar to wx.MultiChoiceDialog, but provides 37 a filter to select choices and buttons to make selection 38 of multiple items more simple. 39 :class:`G2SingleChoiceDialog` Dialog similar to wx.SingleChoiceDialog, but provides 40 a filter to help search through choices. 41 :class:`FlagSetDialog` Dialog that provides a table of items along with a 42 checkbox for each. 43 :class:`SingleFloatDialog` Dialog to obtain a single float value from user, with 44 optional range validation. 45 :class:`MultiFloatDialog` Dialog to obtain multiple float values from user, 46 with optional range validation. 47 :class:`SingleStringDialog` Dialog to obtain a single string value from user, 48 with optional an optional default value. 49 :class:`MultiStringDialog` Dialog to obtain multiple string values from user, 50 with a description for each value and optional 51 defaults. 52 :class:`SingleIntDialog` Dialog to obtain a single integer value from user, 53 with optional range validation. 54 :class:`MultiIntegerDialog` Dialog to obtain multiple integer values from user, 55 with a description for each value and optional 56 defaults. 57 :class:`G2ColumnIDDialog` A dialog for matching column data to desired items; some 58 columns may be ignored. 59 :class:`G2HistoDataDialog` A dialog for global edits to histogram data globally 60 :class:`OrderBox` Creates a wx.Panel with scrollbars where items can be 61 ordered into columns. 62 :class:`HelpButton` Creates a button labeled with a "?" that when pressed 63 displays help text in a modal message window. 64 :func:`G2MessageBox` Displays text typically used for errors or warnings. 65 :func:`HorizontalLine` Places a line in a Frame or Dialog to separate sections. 66 :func:`SelectEdit1Var` Select a variable from a list, then edit it and select 67 histograms to copy it to. 68 :func:`ItemSelector` Select a single item or multiple items from list of choices. 69 Creates and then destroys a wx.Dialog and returns the 70 selections(s). 71 :func:`GetItemOrder` Creates a dialog for ordering items into columns 72 :func:`GetImportFile` Gets one ore more file from the appropriate import 73 directory, which can be overridden. Arguments follow those 74 of :func:`wx.FileDialog` 75 :func:`Define_wxId` Create a unique wx.Id symbol that is global to this 76 module (:mod:`GSASIIctrlGUI`). Such symbols are needed 77 when the menu item is defined in a different location 78 from the wx.Bind that links the menu item to a function. 79 This function allows menu Ids to be 80 defined where they are first used rather than be placed 81 yet a third location somewhere in this module. 82 ================================ ================================================================= 83 84 Other miscellaneous routines that may be of use: 85 86 ================================ ================================================================= 87 Function name Description 88 ================================ ================================================================= 89 :func:`StripIndents` Regularizes the intentation from a string with multiple 90 newline characters by removing spaces at the beginning 91 of each line. 92 :func:`StripUnicode` Removes unicode characters from strings 93 :func:`GetImportPath` Determines the default location to use for importing files. 94 Tries sequentially :attr:`G2frame.TutorialImportDir`, 95 config var ``Import_directory`` and 96 :attr:`G2frame.LastImportDir`. 97 :func:`GetExportPath` Determines the default location to use for writing files. 98 Tries sequentially :attr:`G2frame.LastExportDir` and 99 :attr:`G2frame.LastGPXdir` 100 ================================ ================================================================= 101 102 Documentation for all the routines in module :mod:`GSASIIctrlGUI`. 15 103 16 104 ''' … … 1067 1155 self.onChoice() 1068 1156 1069 ############################################################### Custom checkbox that saves values into dict/list as used 1157 ############################################################## 1158 # Custom checkbox that saves values into dict/list as used 1070 1159 class G2CheckBox(wx.CheckBox): 1071 1160 '''A customized version of a CheckBox that automatically initializes … … 2613 2702 ######################################################### Column-order selection dialog 2614 2703 def GetItemOrder(parent,keylist,vallookup,posdict): 2615 '''Creates a panelwhere items can be ordered into columns2704 '''Creates a dialog where items can be ordered into columns 2616 2705 2617 2706 :param list keylist: is a list of keys for column assignments -
trunk/GSASIIscriptable.py
r3208 r3209 563 563 file.close() 564 564 565 def ImportPowder(reader,filename):566 '''Use a reader to import a powder diffraction data file567 568 :param str reader: a scriptable reader569 :param str filename: full name of powder data file; can be "multi-Bank" data570 571 :returns: list rdlist: list of reader objects containing powder data, one for each572 "Bank" of data encountered in file. Items in reader object of interest are:573 574 * rd.comments: list of str: comments found on powder file575 * rd.dnames: list of str: data nammes suitable for use in GSASII data tree NB: duplicated in all rd entries in rdlist576 * rd.powderdata: list of numpy arrays: pos,int,wt,zeros,zeros,zeros as needed for a PWDR entry in GSASII data tree.577 '''578 rdfile,rdpath,descr = imp.find_module(reader)579 rdclass = imp.load_module(reader,rdfile,rdpath,descr)580 rd = rdclass.GSAS_ReaderClass()581 if not rd.scriptable:582 print(u'**** ERROR: '+reader+u' is not a scriptable reader')583 return None584 rdlist = []585 if rd.ContentsValidator(filename):586 repeat = True587 rdbuffer = {} # create temporary storage for file reader588 block = 0589 while repeat: # loop if the reader asks for another pass on the file590 block += 1591 repeat = False592 rd.objname = ospath.basename(filename)593 flag = rd.Reader(filename,None,buffer=rdbuffer,blocknum=block,)594 if flag:595 rdlist.append(copy.deepcopy(rd)) # save the result before it is written over596 if rd.repeat:597 repeat = True598 return rdlist599 print(rd.errors)600 return None565 # def ImportPowder(reader,filename): 566 # '''Use a reader to import a powder diffraction data file 567 568 # :param str reader: a scriptable reader 569 # :param str filename: full name of powder data file; can be "multi-Bank" data 570 571 # :returns: list rdlist: list of reader objects containing powder data, one for each 572 # "Bank" of data encountered in file. Items in reader object of interest are: 573 574 # * rd.comments: list of str: comments found on powder file 575 # * rd.dnames: list of str: data nammes suitable for use in GSASII data tree NB: duplicated in all rd entries in rdlist 576 # * rd.powderdata: list of numpy arrays: pos,int,wt,zeros,zeros,zeros as needed for a PWDR entry in GSASII data tree. 577 # ''' 578 # rdfile,rdpath,descr = imp.find_module(reader) 579 # rdclass = imp.load_module(reader,rdfile,rdpath,descr) 580 # rd = rdclass.GSAS_ReaderClass() 581 # if not rd.scriptable: 582 # print(u'**** ERROR: '+reader+u' is not a scriptable reader') 583 # return None 584 # rdlist = [] 585 # if rd.ContentsValidator(filename): 586 # repeat = True 587 # rdbuffer = {} # create temporary storage for file reader 588 # block = 0 589 # while repeat: # loop if the reader asks for another pass on the file 590 # block += 1 591 # repeat = False 592 # rd.objname = ospath.basename(filename) 593 # flag = rd.Reader(filename,None,buffer=rdbuffer,blocknum=block,) 594 # if flag: 595 # rdlist.append(copy.deepcopy(rd)) # save the result before it is written over 596 # if rd.repeat: 597 # repeat = True 598 # return rdlist 599 # print(rd.errors) 600 # return None 601 601 602 602 def SetDefaultDData(dType,histoName,NShkl=0,NDij=0): … … 1166 1166 :param list phases: Phases to link to the new histogram 1167 1167 :param str fmthint: If specified, only importers where the format name 1168 (reader.formatName, as shown in Import menu) contain ingthe1168 (reader.formatName, as shown in Import menu) contains the 1169 1169 supplied string will be tried as importers. If not specified, all 1170 1170 importers consistent with the file extension will be tried … … 1196 1196 return self.histogram(histname) 1197 1197 1198 def add_simulated_powder_histogram(self, histname, iparams, Tmin, Tmax, Tstep, 1199 wavelength=None, scale=None, phases=[]): 1200 """Loads a powder data histogram into the project. 1201 1202 Requires an instrument parameter file. 1203 Note that in unix fashion, "~" can be used to indicate the 1204 home directory (e.g. ~/G2data/data.prm). The instrument parameter file 1205 will determine if the histogram is x-ray, CW neutron, TOF, etc. as well 1206 as the instrument type. 1207 1208 :param str histname: A name for the histogram to be created. 1209 :param str iparams: The instrument parameters file, a filename. 1210 :param float Tmin: Minimum 2theta or TOF (ms) for dataset to be simulated 1211 :param float Tmax: Maximum 2theta or TOF (ms) for dataset to be simulated 1212 :param float Tstep: Step size in 2theta or TOF (ms) for dataset to be simulated 1213 :param float wavelength: Wavelength for CW instruments, overriding the value 1214 in the instrument parameters file if specified. 1215 :param float scale: Histogram scale factor which multiplies the pattern. Note that 1216 simulated noise is added to the pattern, so that if the maximum intensity is 1217 small, the noise will mask the computed pattern. The scale 1218 needs to be a large number for CW neutrons. 1219 The default, None, provides a scale of 1 for x-rays and TOF; 10,000 for CW neutrons. 1220 :param list phases: Phases to link to the new histogram. Use proj.phases() to link to 1221 all defined phases. 1222 1223 :returns: A :class:`G2PwdrData` object representing the histogram 1224 """ 1225 LoadG2fil() 1226 iparams = os.path.abspath(os.path.expanduser(iparams)) 1227 if not os.path.exists(iparams): 1228 raise G2ScriptException("File does not exist:"+iparams) 1229 rd = G2obj.ImportPowderData( # Initialize a base class reader 1230 extensionlist=tuple(), 1231 strictExtension=False, 1232 formatName = 'Simulate dataset', 1233 longFormatName = 'Compute a simulated pattern') 1234 rd.powderentry[0] = '' # no filename 1235 rd.powderentry[2] = 1 # only one bank 1236 rd.comments.append('This is a dummy dataset for powder pattern simulation') 1237 #Iparm1, Iparm2 = load_iprms(iparams, rd) 1238 if Tmax < Tmin: 1239 Tmin,Tmax = Tmax,Tmin 1240 Tstep = abs(Tstep) 1241 if 'TOF' in rd.idstring: 1242 N = (np.log(Tmax)-np.log(Tmin))/Tstep 1243 x = np.exp((np.arange(0,N))*Tstep+np.log(Tmin*1000.)) 1244 N = len(x) 1245 else: 1246 N = int((Tmax-Tmin)/Tstep)+1 1247 x = np.linspace(Tmin,Tmax,N,True) 1248 N = len(x) 1249 if N < 3: 1250 raise G2ScriptException("Error: Range is too small or step is too large, <3 points") 1251 rd.powderdata = [ 1252 np.array(x), # x-axis values 1253 np.zeros_like(x), # powder pattern intensities 1254 np.ones_like(x), # 1/sig(intensity)^2 values (weights) 1255 np.zeros_like(x), # calc. intensities (zero) 1256 np.zeros_like(x), # calc. background (zero) 1257 np.zeros_like(x), # obs-calc profiles 1258 ] 1259 Tmin = rd.powderdata[0][0] 1260 Tmax = rd.powderdata[0][-1] 1261 rd.idstring = histname 1262 histname, new_names, pwdrdata = load_pwd_from_reader(rd, iparams, 1263 [h.name for h in self.histograms()]) 1264 if histname in self.data: 1265 print("Warning - redefining histogram", histname) 1266 elif self.names[-1][0] == 'Phases': 1267 self.names.insert(-1, new_names) 1268 else: 1269 self.names.append(new_names) 1270 if scale is not None: 1271 pwdrdata['Sample Parameters']['Scale'][0] = scale 1272 elif pwdrdata['Instrument Parameters'][0]['Type'][0].startswith('PNC'): 1273 pwdrdata['Sample Parameters']['Scale'][0] = 10000. 1274 self.data[histname] = pwdrdata 1275 self.update_ids() 1276 1277 for phase in phases: 1278 phase = self.phase(phase) 1279 self.link_histogram_phase(histname, phase) 1280 1281 return self.histogram(histname) 1282 1198 1283 def add_phase(self, phasefile, phasename=None, histograms=[], fmthint=None): 1199 1284 """Loads a phase into the project from a .cif file … … 1202 1287 :param str phasename: The name of the new phase, or None for the default 1203 1288 :param list histograms: The names of the histograms to associate with 1204 this phase 1289 this phase. Use proj.Histograms() to add to all histograms. 1205 1290 :param str fmthint: If specified, only importers where the format name 1206 (reader.formatName, as shown in Import menu) contain ingthe1291 (reader.formatName, as shown in Import menu) contains the 1207 1292 supplied string will be tried as importers. If not specified, all 1208 1293 importers consistent with the file extension will be tried … … 1369 1454 Gives an object representing the specified phase in this project. 1370 1455 1371 :param str phasename: The name of the desired phase. Either the name 1372 (str), the phase's ranId, or the phase's index 1456 :param str phasename: A reference to the desired phase. Either the phase 1457 name (str), the phase's ranId, the phase's index (both int) or 1458 a phase object (:class:`G2Phase`) 1373 1459 :returns: A :class:`G2Phase` object 1374 1460 :raises: KeyError … … 1379 1465 :meth:`G2Project.phases` 1380 1466 """ 1467 if isinstance(phasename, G2Phase): 1468 if phasename.proj == self: 1469 return phasename 1381 1470 phases = self.data['Phases'] 1382 1471 if phasename in phases: -
trunk/makeBat.py
r3204 r3209 67 67 if ' ' in G2s: G2s = '"'+G2script+'"' 68 68 # is mingw-w64\bin present? If so add it to path. 69 d = os.path.split(pexe)[0]70 mdir = os.path.join(d,'Library','mingw-w64','bin')71 if os.path.exists(mdir):72 fp.write('@path={};%path%\n'.format(mdir))69 #d = os.path.split(pexe)[0] 70 #mdir = os.path.join(d,'Library','mingw-w64','bin') 71 #if os.path.exists(mdir): 72 # fp.write('@path={};%path%\n'.format(mdir)) 73 73 fp.write(Script.format(pexe,G2s)) 74 74 fp.close()
Note: See TracChangeset
for help on using the changeset viewer.