Changeset 3202 for trunk/GSASIIscriptable.py
- Timestamp:
- Dec 22, 2017 7:56:50 PM (5 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/GSASIIscriptable.py
r3187 r3202 118 118 Note that the parameters must match the object type and method (phase vs. histogram vs. HAP). 119 119 120 .. _Project_objects: 121 120 122 ------------------------ 121 123 Project objects 122 124 ------------------------ 123 It is also possible to create a composite dictionary containing parameters of any type. 124 In this case dictionaries are nested with keys at the outer level of "set" and "clear" 125 to specify which function is used with function :meth:`G2Project.set_refinement`. Note 126 that optionally a list of histograms and/or phases can be supplied to 127 :meth:`G2Project.set_refinement`, where the default is to use all phases and histograms. 125 It is also possible to create a composite dictionary 126 that reference all three of the above types of refinement parameters. 127 In this case dictionaries are nested with keys at the outer level, such as 128 "set" and "clear" which determine function is used with function 129 :meth:`G2Project.set_refinement`. 130 131 Note that optionally a list of histograms and/or phases can be supplied to 132 :meth:`G2Project.set_refinement` or :meth:`G2Project.do_refinements`, 133 where the default is to use all phases and histograms, but more commonly for 134 :meth:`G2Project.do_refinements` will be to define the "histograms" and "phases" 135 items within individual dictionaries and these will override the call arguments. 136 137 128 138 As an example: 129 139 … … 136 146 my_project.set_refinement(pardict) 137 147 148 .. _Refinement_recipe: 149 138 150 ------------------------ 139 151 Refinement recipe 140 152 ------------------------ 141 Finally, it is possible to specify a sequence of refinement actions as a list of dicts. 142 Note in the following example, the list contains a set of dicts, each defined as before. 143 It is not possible to specify different actions for differing phases or histograms 144 with this method. Note that a 145 separate refinement step will be performed for each element in the list. 153 Finally, it is possible to specify a sequence of refinement actions as a list of dicts 154 that will be supplied as an argument to :meth:`G2Project.do_refinements`. 155 These dicts in this list are each like those described in the 156 :ref:`Project_objects` section, 157 except that additional keys, as are described in the table below may be used. 158 159 ========== ============================================================================ 160 key explanation 161 ========== ============================================================================ 162 set Specifies a dict with keys and subkeys as described in the 163 :ref:`Refinement_parameters_fmt` section. Items listed here 164 will be set to be refined. 165 clear Specifies a dict as above for set, except that parameters are 166 cleared and thus will not be refined. 167 once Specifies a dict as above for set, except that parameters are 168 set for the next cycle of refinement and are cleared once the 169 refinement step is completed. 170 skip Normally, once parameters are processed with a set/clear/once 171 action(s), a refinement is started. If skip is defined as True 172 (or any other value) the refinement step is not performed. 173 output If a file name is specified for output is will be used for 174 the current refinement. 175 histograms Should contain a list of histogram(s) to be used for the 176 set/clear/once action(s) on :ref:`Histogram_parameters_table` or 177 :ref:`HAP_parameters_table`. Note that this will be 178 ignored for :ref:`Phase_parameters_table`. Histograms may be 179 specified as a list of strings [('PWDR ...'),...], indices 180 [0,1,2] or as list of objects [hist1, hist2]. 181 phases Should contain a list of phase(s) to be used for the 182 set/clear/once action(s) on :ref:`Phase_parameters_table` or 183 :ref:`HAP_parameters_table`. Note that this will be 184 ignored for :ref:`Histogram_parameters_table`. 185 Phases may be specified as a list of strings 186 [('Phase name'),...], indices [0,1,2] or as list of objects 187 [phase0, phase2]. 188 call Specifies a function to call after a refinement is completed. 189 No function is called if this is not specified. 190 callargs Provides a list of arguments that will be passed to the function 191 in call (if any). If call is defined and callargs is not, the 192 current <tt>G2Project</tt> is passed as a single argument. 193 ========== ============================================================================ 194 146 195 An example follows: 147 196 … … 166 215 my_project.do_refinements(reflist) 167 216 168 Note that in the second from last refinement step (``reflist[6]``), parameters are both set and cleared. To perform a single refinement without changing any parameters, use this 169 call: 170 171 .. code-block:: python 172 173 my_project.do_refinements([]) 174 175 217 218 In this example, the list contains a set of dicts, each defined as before. 219 A separate refinement step will be performed for each element in the list unless 220 "skip" is included. 221 Note that in the second from last refinement step, parameters are both set and cleared. 222 223 .. _Refinement_parameters_fmt: 176 224 177 225 ============================ … … 240 288 .. tabularcolumns:: |l|p{4.5in}| 241 289 242 ======= ==========================================================290 ======= ========================================================== 243 291 key explanation 244 ======= ==========================================================292 ======= ========================================================== 245 293 Cell Whether or not to refine the unit cell. 246 294 Atoms Dictionary of atoms and refinement flags. … … 252 300 and 'U' for Debye-Waller factor 253 301 LeBail Enables LeBail intensity extraction. 254 ===================== ============================================ 302 ======= ========================================================== 303 255 304 256 305 .. _HAP_parameters_table: … … 265 314 .. tabularcolumns:: |l|l|p{3.5in}| 266 315 267 ============= ======== =====================================================================268 key 269 ============= ======== =====================================================================270 Babinet 271 272 273 \ 274 \ 275 Extinction 276 HStrain 277 316 ============= ========== ============================================================ 317 key subkey explanation 318 ============= ========== ============================================================ 319 Babinet Should be a **list** of the following 320 subkeys. If not, assumes both 321 BabA and BabU 322 \ BabA 323 \ BabU 324 Extinction Boolean, True to refine. 325 HStrain Boolean, True to refine all appropriate 326 $D_ij$ terms. 278 327 Mustrain 279 \ 280 281 282 \ directionFor uniaxial only. A list of three283 284 285 \ 286 287 288 289 290 Size Not implemented291 \ 292 293 294 \ directionFor uniaxial only. A list of three295 296 297 \ 298 Pref.Ori. 299 Show 300 Use 301 Scale 302 ============= ======== =====================================================================328 \ type Mustrain model. One of 'isotropic', 329 'uniaxial', or 'generalized'. Should always 330 be specified. 331 \ direction For uniaxial only. A list of three 332 integers, 333 the [hkl] direction of the axis. 334 \ refine Usually boolean, set to True to refine. 335 When in doubt, set it to true. 336 For uniaxial model, can specify list 337 of 'axial' or 'equatorial' or a single 338 boolean sets both axial and equatorial. 339 Size Not yet implemented 340 \ type Size broadening model. One of 'isotropic', 341 'uniaxial', or 'ellipsoid'. Should always 342 be specified. 343 \ direction For uniaxial only. A list of three 344 integers, 345 the [hkl] direction of the axis. 346 \ refine A boolean, True to refine. 347 Pref.Ori. Boolean, True to refine 348 Show Boolean, True to refine 349 Use Boolean, True to refine 350 Scale Phase fraction; Boolean, True to refine 351 ============= ========== ============================================================ 303 352 304 353 … … 315 364 if '2' in platform.python_version_tuple()[0]: 316 365 import cPickle 366 strtypes = (str,unicode) 317 367 else: 318 368 import _pickle as cPickle 369 strtypes = (str,bytes) 319 370 import imp 320 371 import copy … … 334 385 import GSASIIspc as G2spc 335 386 import GSASIIElem as G2elem 387 336 388 337 389 # Delay imports to not slow down small scripts … … 668 720 """ 669 721 if not filename: 670 filename = os.path.join(os.getcwd(), 'test_output.gpx') 671 else: 672 filename = os.path.abspath(filename) 722 filename = 'test_output.gpx' 723 filename = os.path.abspath(filename) 673 724 gsasii_version = str(GSASIIpath.GetVersionNumber()) 674 725 LoadG2fil() … … 677 728 678 729 controls_data = dict(G2obj.DefaultControls) 679 controls_data['LastSavedAs'] = unicode(filename)730 controls_data['LastSavedAs'] = filename 680 731 controls_data['LastSavedUsing'] = gsasii_version 681 732 controls_data['PythonVersions'] = python_library_versions … … 703 754 704 755 705 def import_generic(filename, readerlist ):756 def import_generic(filename, readerlist, fmthint=None): 706 757 """Attempt to import a filename, using a list of reader objects. 707 758 … … 710 761 primaryReaders, secondaryReaders = [], [] 711 762 for reader in readerlist: 763 if fmthint is not None and fmthint not in reader.formatName: continue 712 764 flag = reader.ExtensionValidator(filename) 713 765 if flag is None: … … 812 864 """ 813 865 HistName = 'PWDR ' + G2obj.StripUnicode(reader.idstring, '_') 814 HistName = unicode(G2obj.MakeUniqueLabel(HistName, existingnames))866 HistName = G2obj.MakeUniqueLabel(HistName, existingnames) 815 867 816 868 try: … … 1035 1087 SaveDictToProjFile(self.data, self.names, self.filename) 1036 1088 1037 def add_powder_histogram(self, datafile, iparams, phases=[] ):1089 def add_powder_histogram(self, datafile, iparams, phases=[], fmthint=None): 1038 1090 """Loads a powder data histogram into the project. 1039 1091 … … 1045 1097 :param str iparams: The instrument parameters file, a filename. 1046 1098 :param list phases: Phases to link to the new histogram 1099 :param str fmthint: If specified, only importers where the format name 1100 (reader.formatName, as shown in Import menu) containing the 1101 supplied string will be tried as importers. If not specified, all 1102 importers consistent with the file extension will be tried 1103 (equivalent to "guess format" in menu). 1047 1104 1048 1105 :returns: A :class:`G2PwdrData` object representing … … 1052 1109 datafile = os.path.abspath(os.path.expanduser(datafile)) 1053 1110 iparams = os.path.abspath(os.path.expanduser(iparams)) 1054 pwdrreaders = import_generic(datafile, PwdrDataReaders )1111 pwdrreaders = import_generic(datafile, PwdrDataReaders,fmthint=fmthint) 1055 1112 histname, new_names, pwdrdata = load_pwd_from_reader( 1056 1113 pwdrreaders[0], iparams, … … 1071 1128 return self.histogram(histname) 1072 1129 1073 def add_phase(self, phasefile, phasename=None, histograms=[] ):1130 def add_phase(self, phasefile, phasename=None, histograms=[], fmthint=None): 1074 1131 """Loads a phase into the project from a .cif file 1075 1132 … … 1078 1135 :param list histograms: The names of the histograms to associate with 1079 1136 this phase 1137 :param str fmthint: If specified, only importers where the format name 1138 (reader.formatName, as shown in Import menu) containing the 1139 supplied string will be tried as importers. If not specified, all 1140 importers consistent with the file extension will be tried 1141 (equivalent to "guess format" in menu). 1080 1142 1081 1143 :returns: A :class:`G2Phase` object representing the … … 1087 1149 1088 1150 # TODO handle multiple phases in a file 1089 phasereaders = import_generic(phasefile, PhaseReaders )1151 phasereaders = import_generic(phasefile, PhaseReaders, fmthint=fmthint) 1090 1152 phasereader = phasereaders[0] 1091 1153 … … 1132 1194 phasenames = [u'Phases'] 1133 1195 self.names.append(phasenames) 1134 phasenames.append( unicode(phasename))1196 phasenames.append(phasename) 1135 1197 1136 1198 # TODO should it be self.filename, not phasefile? … … 1290 1352 def do_refinements(self, refinements, histogram='all', phase='all', 1291 1353 outputnames=None, makeBack=False): 1292 """Conducts a series of refinements. Wrapper around iter_refinements 1293 1294 :param list refinements: A list of dictionaries defining refinements 1354 """Conducts one or a series of refinements according to the 1355 input provided in parameter refinements. This is a wrapper 1356 around :meth:`iter_refinements` 1357 1358 :param list refinements: A list of dictionaries specifiying changes to be made to 1359 parameters before refinements are conducted. 1360 See the :ref:`Refinement_recipe` section for how this is defined. 1295 1361 :param str histogram: Name of histogram for refinements to be applied 1296 to, or 'all' 1362 to, or 'all'; note that this can be overridden for each refinement 1363 step via a "histograms" entry in the dict. 1297 1364 :param str phase: Name of phase for refinements to be applied to, or 1298 'all' 1365 'all'; note that this can be overridden for each refinement 1366 step via a "phases" entry in the dict. 1367 :param list outputnames: Provides a list of project (.gpx) file names 1368 to use for each refinement step (specifying None skips the save step). 1369 See :meth:`save`. 1370 Note that this can be overridden using an "output" entry in the dict. 1371 :param bool makeBack: determines if a backup ).bckX.gpx) file is made 1372 before a refinement is performed. The default is False. 1373 1374 To perform a single refinement without changing any parameters, use this 1375 call: 1376 1377 .. code-block:: python 1378 1379 my_project.do_refinements([]) 1299 1380 """ 1381 1300 1382 for proj in self.iter_refinements(refinements, histogram, phase, 1301 1383 outputnames, makeBack): … … 1307 1389 """Conducts a series of refinements, iteratively. Stops after every 1308 1390 refinement and yields this project, to allow error checking or 1309 logging of intermediate results. 1310 1311 :param list refinements: A list of dictionaries defining refinements 1312 :param str histogram: Name of histogram for refinements to be applied 1313 to, a list of histograms or 'all'. 1314 See :func:`set_refinement` for more details 1315 :param str phase: Name of phase for refinements to be applied to, a 1316 list of phases or 'all'. 1317 See :func:`set_refinement` for more details 1318 1391 logging of intermediate results. Parameter use is the same as for 1392 :meth:`do_refinements` (which calls this method). 1393 1319 1394 >>> def checked_refinements(proj): 1320 1395 ... for p in proj.iter_refinements(refs): … … 1335 1410 outputnames = [None for r in refinements] 1336 1411 1337 for output, refinement in zip(outputnames, refinements): 1338 self.set_refinement(refinement, histogram) 1412 for output, refinedict in zip(outputnames, refinements): 1413 if 'histograms' in refinedict: 1414 hist = refinedict['histograms'] 1415 else: 1416 hist = histogram 1417 if 'phases' in refinedict: 1418 ph = refinedict['phases'] 1419 else: 1420 ph = phase 1421 if 'output' in refinedict: 1422 output = refinedict['output'] 1423 self.set_refinement(refinedict, hist, ph) 1339 1424 # Handle 'once' args - refinements that are disabled after this 1340 1425 # refinement 1341 if 'once' in refine ment:1342 temp = {'set': refine ment['once']}1343 self.set_refinement(temp, hist ogram, phase)1426 if 'once' in refinedict: 1427 temp = {'set': refinedict['once']} 1428 self.set_refinement(temp, hist, ph) 1344 1429 1345 1430 if output: 1346 1431 self.save(output) 1347 1432 1348 self.refine(makeBack=makeBack) 1433 if 'skip' not in refinedict: 1434 self.refine(makeBack=makeBack) 1349 1435 yield self 1350 1436 1351 1437 # Handle 'once' args - refinements that are disabled after this 1352 1438 # refinement 1353 if 'once' in refinement: 1354 temp = {'clear': refinement['once']} 1355 self.set_refinement(temp, histogram, phase) 1439 if 'once' in refinedict: 1440 temp = {'clear': refinedict['once']} 1441 self.set_refinement(temp, hist, ph) 1442 if 'call' in refinedict: 1443 refinedict['call'](*refinedict.get('callargs',[self])) 1356 1444 1357 1445 def set_refinement(self, refinement, histogram='all', phase='all'): … … 1588 1676 if c not in ' FXU': 1589 1677 raise ValueError("Invalid atom refinement: ", other) 1590 self.data[self.ct+1] = unicode(other)1678 self.data[self.ct+1] = other 1591 1679 1592 1680 @property … … 2176 2264 newType = None 2177 2265 direction = None 2178 if isinstance(val, (unicode, str)):2266 if isinstance(val, strtypes): 2179 2267 if val in ['isotropic', 'uniaxial', 'generalized']: 2180 2268 newType = val … … 2193 2281 if 'refine' in val: 2194 2282 types = val['refine'] 2195 if isinstance(types, (unicode, str)):2283 if isinstance(types, strtypes): 2196 2284 types = [types] 2197 2285 elif isinstance(types, bool): … … 2226 2314 newType = None 2227 2315 direction = None 2228 if isinstance(val, (unicode, str)):2316 if isinstance(val, strtypes): 2229 2317 if val in ['isotropic', 'uniaxial', 'ellipsoidal']: 2230 2318 newType = val
Note: See TracChangeset
for help on using the changeset viewer.