Changeset 3202


Ignore:
Timestamp:
Dec 22, 2017 7:56:50 PM (4 years ago)
Author:
toby
Message:

make scriptable Py3 ready and add new features; minor fix for new G2 installation

Files:
3 edited

Legend:

Unmodified
Added
Removed
  • Tutorials/PythonScript/Scripting.htm

    r3132 r3202  
    2020This exercise assumes that the reader has reasonable familiarity with
    2121the Python language.
    22 Before beginning this exercise, the documentation on the
     22Also, the documentation on the
    2323<A href="http://gsas-ii.readthedocs.io/en/latest/GSASIIscripts.html"
    2424target="_blank">
     
    3939Python will make this a more pleasant experience.
    4040
     41<h2>Multi-step Script Approach</h2>
     42
    4143<h4>0: Load the GSASIIscriptable module</H4>
    4244<blockquote>
     
    4850script as is done in the example below. Note that a common location
    4951for this will be
    50 <TT>os.path.expanduser("~/g2conda/GSASII/")</TT>. Thus the script will
    51 begin with:
     52<TT>os.path.expanduser("~/g2conda/GSASII/")</TT> or
     53<tt>'/Users/toby/software/GSASII'</tt>, etc.
     54Thus the script will begin with something like this:
    5255
    5356<blockquote><textarea rows="3" cols="60" readonly>
    5457import os,sys
    55 sys.path.insert(0,'/Users/toby/software/G2/GSASII')
     58sys.path.insert(0,os.path.expanduser("~/g2conda/GSASII/"))
    5659import GSASIIscriptable as G2sc</textarea></blockquote>
    5760
     
    9699access a GSAS-II project, which is done with a call to
    97100<TT>GSASIIscriptable.G2Project()</tt>. This can be done in one of two
    98 ways, a call with <tt>G2sc.G2Project(filename=</tt><I>file</I><tt>)</tt> creates a new
     101ways: a call with <tt>G2sc.G2Project(filename=</tt><I>file</I><tt>)</tt> creates a new
    99102(empty) project, while a call with
    100103<tt>G2sc.G2Project(gpxfile=</tt><I>file</I><tt>)</tt> opens and
    101 reads an existing project (.gpx) file. Both return a Project wrapper
     104reads an existing project (.gpx) file. Both return a <tt>G2Project</tt> wrapper
    102105object that is used to access a number of methods and variables.
    103106Note that <TT>GSASIIscriptable.G2Project()</tt> can read .gpx files
     
    106109<P>
    107110In this example, we create a new project by using the
    108 <tt>filename=</tt><I>file</I> argument. Note that this will not
    109 actually create a file until a save operation is done.
     111<tt>filename=</tt><I>file</I> argument with this code:
    110112   
    111113<blockquote><textarea rows="3" cols="70" readonly>
     
    113115gpx = G2sc.G2Project(filename='PbSO4.gpx')</textarea></blockquote>
    114116
    115 </blockquote>
     117Note that the file will not actually be created until an operation
     118that saves the project is called.
     119</blockquote>
     120
    116121<h4>3: Add Histograms and Phase to the GSAS-II project</H4>
    117122<blockquote>
    118 To add two powder diffraction datasets (histograms) to the
    119 project we use the <I>project</I><tt>.add_powder_histogram()</tt> method in
    120 the <TT>GSASIIscriptable</tt> class. The two arguments to
     123To add two powder diffraction datasets (histograms) and a phase to the
     124project using this code:
     125
     126<blockquote><textarea rows="10" cols="70" readonly>
     127# setup step 1: add two histograms to the project
     128hist1 = gpx.add_powder_histogram(os.path.join(datadir,"PBSO4.XRA"),
     129                          os.path.join(datadir,"INST_XRY.PRM"))
     130hist2 = gpx.add_powder_histogram(os.path.join(datadir,"PBSO4.CWN"),
     131                          os.path.join(datadir,"inst_d1a.prm"))
     132# setup step 2: add a phase and link it to the previous histograms
     133phase0 = gpx.add_phase(os.path.join(datadir,"PbSO4-Wyckoff.cif"),
     134                      phasename="PbSO4",
     135                      histograms=[hist1,hist2])</textarea></blockquote>
     136
     137 
     138We use the <I>project</I><tt>.add_powder_histogram()</tt> method in
     139the <TT>GSASIIscriptable</tt> class to read in the powder data.
     140The two arguments to
    121141<tt>.add_powder_histogram()</tt> are the powder dataset and the
    122   instrument parameter file. While neither powder data file uses a
    123   standard extension, the importer is able to determine the file
    124   format anyway. This will not be true for all file formats.
     142  instrument parameter file. Note that these files are both "GSAS
     143  powder data" files and the importer for this format (and many
     144  others) allows files with arbitrary extensions to be read.
     145All importers that allow for extensions .XRA and .CWN will be
     146used to attempt to read the file, producing a number of warning
     147messages. To specify that only the GSAS powder data importer be
     148used, include a third argument, <tt>fmthint="GSAS powder"</tt> or
     149something similar (<tt>fmthint="GSAS"</tt> is also fine, but will
     150cause both the "GSAS powder data" and the "GSAS-II .gpx" importer to be considered.)
    125151<UL><LI>
    126152  Note that <I>project</I><tt>.add_powder_histogram()</tt> returns a
    127   powder histogram objects which are saved for later reference. It is
     153  powder histogram objects, which here are saved for later reference. It is
    128154  also possible to obtain these using <tt>gpx.histograms()</tt>, which
    129155  returns a list of defined histograms.
     
    133159  <I>project</I><tt>.add_phase()</tt>. This specifies a CIF containing the
    134160  structural information, a name for the phase and specifies that the
    135   two histograms are "added" (linked) to the phase.
     161  two histograms are "added" (linked) to the phase. The
     162<tt>fmthint="CIF"</tt> parameter can also optionally be specified to limit the
     163importers that will be tried.
     164
    136165  <UL><LI>
    137166  Note that <I>project</I><tt>.add_phase()</tt>
     
    145174  These three ways to use the <tt>histograms</tt> parameter produce
    146175  the same result.
     176</blockquote>
    147177   
    148 <blockquote><textarea rows="10" cols="70" readonly>
    149 # setup step 1: add two histograms to the project
    150 hist1 = gpx.add_powder_histogram(os.path.join(datadir,"PBSO4.XRA"),
    151                           os.path.join(datadir,"INST_XRY.PRM"))
    152 hist2 = gpx.add_powder_histogram(os.path.join(datadir,"PBSO4.CWN"),
    153                           os.path.join(datadir,"inst_d1a.prm"))
    154 # setup step 2: add a phase and link it to the previous histograms
    155 phase0 = gpx.add_phase(os.path.join(datadir,"PbSO4-Wyckoff.cif"),
    156                       phasename="PbSO4",
    157                       histograms=[hist1,hist2])</textarea></blockquote>
    158 
    159  
    160 </blockquote>
    161178<A name="ChangeCycles">
    162179<h4>4: Change the number of refinement cycles</H4>
     
    166183  without converging the refinement (or at least coming close to
    167184  convergence) at each refinement step. This is best accomplished by
    168   increasing the number of least-squares cycles. There at present is
    169   no method in the project object that allows this parameter to be
    170   set, so this must be done by finding appropriate parameter
    171   dictionary entry.
     185  increasing the number of least-squares cycles. No supplied method (at
     186  present) allows this parameter to be set straightforwardly, but this
     187  code will do this:
     188 
     189 <blockquote><textarea rows="3" cols="70" readonly>
     190# not in tutorial: increase # of cycles to improve convergence
     191gpx.data['Controls']['data']['max cyc'] = 8 # not in API </textarea></blockquote>
     192
    172193<P>
    173   At this point, the Python command <tt>gpx.data.keys()</tt> shows the names of the
    174   entries in the GSAS-II tree; 'Controls' is the tree item
     194  To find this parameter in the GSAS-II data structure, I followed
     195  these steps: In the GUI, Controls is the tree item
    175196  corresponding to the section where Least Squares cycles are
    176   set. Command <tt>gpx.data['Controls'].keys()</tt> shows that all
     197  set. Executing the command <tt>gpx.data.keys()</tt> shows the names of the
     198  entries in the dictionary corresponding to the GSAS-II tree and
     199  indeed one entry is 'Controls'.
     200  Command <tt>gpx.data['Controls'].keys()</tt> shows that all
    177201  values are located in an entry labeled 'data' and
    178202  <tt>gpx.data['Controls']['data'].keys()</tt> shows the entries in
    179203this section. Examination of
    180 <BR><tt>gpx.data['Controls']['data']['max cyc']</tt>shows the value 3,
     204<tt>gpx.data['Controls']['data']['max cyc']</tt> shows the value 3,
    181205which is default number of cycles. Thus,
    182 the number of cycles is changed with this Python command:
    183 
    184 <blockquote><textarea rows="3" cols="70" readonly>
    185 # not in tutorial: increase # of cycles to improve convergence
    186 gpx.data['Controls']['data']['max cyc'] = 8 # not in API </textarea></blockquote>
    187 
    188 </blockquote>
     206the number of cycles is changed with the Python command above.
     207
     208</blockquote>
     209
    189210<h4>5: Set initial variables and refine</H4>
    190211<blockquote>
     
    196217refinement flags are not turned on by default, so a dictionary must be
    197218created to set these histogram variables. This code:
     219<blockquote><textarea rows="5" cols="75" readonly>
     220# tutorial step 4: turn on background refinement (Hist)
     221refdict0 = {"set": {"Background": { "no. coeffs": 3, "refine": True }}}
     222gpx.save('step4.gpx')
     223gpx.do_refinements([refdict0])
     224HistStats(gpx)</textarea></blockquote>
    198225<UL>
    199226<LI>defines a dictionary (refdict0) that will be used to set the number of background coefficients (not really
     
    216243prints them. The function also writes the final refinement results
    217244into the current project file. </A>
    218 
    219 <blockquote><textarea rows="5" cols="75" readonly>
    220 # tutorial step 4: turn on background refinement (Hist)
    221 refdict0 = {"set": {"Background": { "no. coeffs": 3, "refine": True }}}
    222 gpx.save('step4.gpx')
    223 gpx.do_refinements([refdict0])
    224 HistStats(gpx)</textarea></blockquote>
    225245
    226246The output from this will be:<blockquote><pre>
     
    249269<tt>my_project.do_refinements()</tt>, as
    250270<A href="http://gsas-ii.readthedocs.io/en/latest/GSASIIscripts.html#refinement-parameters">
    251 described here</A>. The <tt>gpx.do_refinements([refdict0])</tt>
     271described here</A>. Thus, the <tt>gpx.do_refinements([refdict0])</tt>
    252272statement above could be replaced with:
    253273<blockquote><pre>
     
    295315
    296316In Step 6 of the original tutorial, the refinement is performed again
    297 after adding Histogram/Phase (HAP) parameters that allow different
    298 lattice constants for the first histogram only.
     317after adding Histogram/Phase (HAP) parameters so that the lattice
     318constants for the first histogram (only) can vary. This is done with
     319this code:
    299320
    300321<blockquote><textarea rows="6" cols="75" readonly>
     
    306327HistStats(gpx)</textarea></blockquote>
    307328
    308 Here we cannot use <tt>gpx.do_refinements([refdict2])</tt> because
    309 that would turn on refinement of the Hstrain terms for both histograms
    310 (if there were more than one phase, it would be all phases and all
    311 histograms), but in the above the <tt>gpx.set_refinement(...)</tt>
    312 statement alternately can be replaced with this:
     329Here we cannot use <tt>gpx.do_refinements([refdict2])</tt> with
     330<tt>refdict2</tt> defined as above because
     331that would turn on refinement of the Hstrain terms for all histograms
     332and all phases. There are several ways to restrict the parameter
     333changes to specified histogram(s) and phase(s). One is to call a
     334method in the phase object(s) directly, such as
     335replacing the <tt>gpx.set_refinement(...)</tt>
     336statement with this:
    313337<blockquote><pre>
    314338phase0.set_HAP_refinements({"HStrain": True},histograms=[hist1])
    315339</pre></blockquote>
    316340
    317 </blockquote>
     341It is also possible to add "histograms" and/or "phases" values into
     342the <tt>refdict2</tt> dict, as will be <a href="#SingeStep">described below.</a>
     343</blockquote>
     344
    318345<h4>8: Add X-ray Sample broadening terms</h4>
    319346<blockquote>
     
    328355existing default. Again, since these parameters are being set only for
    329356one histogram, either <tt>phase0.set_HAP_refinements()</tt> or
    330 <tt>gpx.set_refinement()</tt> must be used.
     357<tt>gpx.set_refinement()</tt> must be called or to use
     358<tt>gpx.do_refinements([refdict3])</tt> the "histograms" element must be
     359included inside <tt>refdict3</tt>.
    331360
    332361<blockquote><textarea rows="8" cols="75" readonly>
    333362# tutorial step 7: add size & strain broadening (HAP) for histogram 1 only
    334363gpx.save('step7.gpx')
    335 refdict2 = {"set": {"Mustrain": {"type":"isotropic","refine":True},
     364refdict3 = {"set": {"Mustrain": {"type":"isotropic","refine":True},
    336365                    "Size":{"type":"isotropic","refine":True},
    337366                    }}
    338 gpx.set_refinement(refdict2,phase=phase0,histogram=[hist1])
     367gpx.set_refinement(refdict3,phase=phase0,histogram=[hist1])
    339368gpx.do_refinements([{}]) # refine after setting
    340369HistStats(gpx)</textarea></blockquote>
     
    348377sample parameters using <tt>phase0.set_refinements()</tt> to set the
    349378"X" (coordinate) and "U" (displacement) refinement flags for all
    350 atoms. The original tutorial
    351 calls for the diffractometer radius to be changed. This parameter
    352 cannot be set from any GSASIIscriptable routines, but following a
    353 similar
    354 <A href="#ChangeCycles">process, as before</A>, the location for this
    355 setting can be located in the histogram's 'Sample Parameters' section
    356 (<tt>hist2.data['Sample Parameters']['Gonio. radius']</tt>).
     379atoms. This is done with this code:
    357380
    358381<blockquote><textarea rows="9" cols="75" readonly>
     
    366389HistStats(gpx)</textarea></blockquote>
    367390
    368 Note that the settings provided in the
    369 <tt>phase0.set_refinements()</tt> statement could have been done using
    370 the <tt>gpx.do_refinements()</tt> call, but not those in the
    371 <tt>hist</tt><I>X</I><tt>.set_refinements()</tt> calls, since they
    372 must be different for each histogram.
     391Note that the original tutorial
     392calls for the diffractometer radius to be changed to the correct value
     393so that the displacement value is in the correct units. This parameter
     394cannot be set from any GSASIIscriptable routines, but following a
     395similar process,
     396<A href="#ChangeCycles">as before</A>, the location for this
     397setting can be located in the histogram's 'Sample Parameters' section
     398(as <tt>hist2.data['Sample Parameters']['Gonio. radius']</tt>).
     399
     400Also note that the settings provided in the
     401<tt>phase0.set_refinements()</tt> and statements
     402<tt>gpx.do_refinements()</tt> could have
     403been combined into this single statement:
     404<blockquote><pre>
     405gpx.do_refinements({"set":{"Atoms":{"all":"XU"}})
     406</pre></blockquote>
    373407
    374408</blockquote>
     
    402436</pre></blockquote>
    403437
    404 
    405 </blockquote><hr>
     438</blockquote>
     439<a name="SingeStep"><h2>Single Step Approach</h2></a>
     440<blockquote>
     441
     442As is noted in the
     443<A href="http://gsas-ii.readthedocs.io/en/latest/GSASIIscripts.html" target="_blank">
     444GSASIIscriptable module documentation</A>,
     445the <I>project</i><tt>.do_refinements()</tt> method can be used to
     446perform multiple refinement steps. To duplicate the above steps into a
     447single call a more complex set of dicts must be created, as shown
     448below:
     449
     450<blockquote><textarea rows="39" cols="75" readonly>
     451# tutorial step 4: turn on background refinement (Hist)
     452refdict0 = {"set": {"Background": { "no. coeffs": 3, "refine": True }},
     453            "output":'step4.gpx',
     454            "call":HistStats,"callargs":[gpx]} # callargs actually unneeded
     455                                               # as [gpx] is the default
     456# tutorial step 5: add unit cell refinement (Phase)
     457refdict1 = {"set": {"Cell": True},    # set the cell flag (for all phases)
     458            "output":'step5.gpx', "call":HistStats}
     459# tutorial step 6: add Dij terms (HAP) for phase 1 only
     460refdict2 = {"set": {"HStrain": True},  # set HAP parameters
     461            "histograms":[hist1],      # histogram 1 only
     462            "phases":[phase0],         # unneeded (default is all
     463                                       # phases) included as a example
     464            "output":'step6.gpx', "call":HistStats}
     465# tutorial step 7: add size & strain broadening (HAP) for histogram 1 only
     466refdict3 = {"set": {"Mustrain": {"type":"isotropic","refine":True},
     467                    "Size":{"type":"isotropic","refine":True},},
     468            "histograms":[hist1],      # histogram 1 only
     469            "output":'step7.gpx', "call":HistStats}
     470# tutorial step 8: add sample parameters & set radius (Hist); refine
     471#                  atom parameters (phase)
     472refdict4a = {"set": {'Sample Parameters': ['Shift']},
     473            "histograms":[hist1],      # histogram 1 only
     474             "skip": True}
     475refdict4b = {"set": {"Atoms":{"all":"XU"}, # not affected by histograms
     476             'Sample Parameters': ['DisplaceX', 'DisplaceY']},
     477            "histograms":[hist2],      # histogram 2 only
     478            "output":'step8.gpx', "call":HistStats}
     479# tutorial step 9: change data limits & inst. parm refinements (Hist)
     480refdict5a = {"set": {'Limits': [16.,158.4]},
     481            "histograms":[hist1],      # histogram 1 only
     482             "skip": True,}
     483refdict5b = {"set": {'Limits': [19.,153.]},
     484            "histograms":[hist2],      # histogram 2 only
     485             "skip": True}
     486refdict5c = {"set": {'Instrument Parameters': ['U', 'V', 'W']},
     487            "output":'step9.gpx', "call":HistStats}
     488</textarea></blockquote>
     489
     490Note that above the "call" and "callargs" dict entries are
     491defined to run <tt>HistStats</tt> and "output" is used to designate
     492the .gpx file that will be needed. When parameters should be changed
     493in specific histograms, the entries <tt>"histograms":[hist1]</tt> and
     494<tt>"histograms":[hist2]</tt> are used
     495(equivalent would be <tt>"histograms":[0]</tt> and
     496<tt>"histograms":[1]</tt>).
     497Since there is only one phase present, use of <tt>"phase":[0]</tt> is
     498superfluous, but in a more complex refinement, this could be needed.
     499<p>
     500A list of dicts is then prepared here:
     501<blockquote><textarea rows="3" cols="75" readonly>
     502dictList = [refdict0,refdict1,refdict2,refdict3,
     503            refdict4a,refdict4b,
     504            refdict5a,refdict5b,refdict5c]
     505</textarea></blockquote>
     506Steps 4 through 10, above then can be performed with these few commands:
     507<blockquote><textarea rows="4" cols="75" readonly>
     508# Change number of cycles and radius
     509gpx.data['Controls']['data']['max cyc'] = 8 # not in API
     510hist2.data['Sample Parameters']['Gonio. radius'] = 650. # not in API
     511gpx.do_refinements(dictList)
     512</textarea></blockquote>
     513
     514</blockquote>
     515
     516<hr>
    406517<address></address>
    407 <!-- hhmts start -->Last modified: Thu Oct 12 10:45:51 CDT 2017 <!-- hhmts end -->
     518<!-- hhmts start -->Last modified: Fri Dec 22 16:24:53 CST 2017 <!-- hhmts end -->
    408519</body> </html>
  • trunk/GSASIIdataGUI.py

    r3195 r3202  
    25852585            size = GSASIIpath.GetConfigValue('Main_Size')
    25862586            if type(size) is str:
    2587                 if size == 'None':
    2588                     size = wx.Size(700,450)
    2589                 else:
    2590                     size = eval(size)
     2587                size = eval(size)
     2588            else:
     2589                raise Exception
    25912590        except:
    25922591            size = wx.Size(700,450)
     
    26492648        try:
    26502649            size = GSASIIpath.GetConfigValue('Plot_Size')
    2651             if type(size) is str:
    2652                 if size == 'None':
    2653                     size = wx.Size(700,600)
    2654                 else:
    2655                     size = eval(size)
     2650            if type(size) is str:
     2651                size = eval(size)
     2652            else:
     2653                raise Exception
    26562654        except:
    26572655            size = wx.Size(700,600)               
  • trunk/GSASIIscriptable.py

    r3187 r3202  
    118118Note that the parameters must match the object type and method (phase vs. histogram vs. HAP).
    119119
     120.. _Project_objects:
     121
    120122------------------------
    121123Project objects
    122124------------------------
    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.
     125It is also possible to create a composite dictionary
     126that reference all three of the above types of refinement parameters.
     127In 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
     131Note that optionally a list of histograms and/or phases can be supplied to
     132:meth:`G2Project.set_refinement` or :meth:`G2Project.do_refinements`,
     133where 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"
     135items within individual dictionaries and these will override the call arguments.
     136
     137
    128138As an example:
    129139
     
    136146    my_project.set_refinement(pardict)
    137147
     148.. _Refinement_recipe:
     149   
    138150------------------------
    139151Refinement recipe
    140152------------------------
    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.
     153Finally, it is possible to specify a sequence of refinement actions as a list of dicts
     154that will be supplied as an argument to :meth:`G2Project.do_refinements`.
     155These dicts in this list are each like those described in the
     156:ref:`Project_objects` section,
     157except that additional keys, as are described in the table below may be used.
     158
     159========== ============================================================================
     160key         explanation
     161========== ============================================================================
     162set                    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.
     165clear                  Specifies a dict as above for set, except that parameters are
     166                       cleared and thus will not be refined.
     167once                   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.
     170skip                   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.
     173output                 If a file name is specified for output is will be used for
     174                       the current refinement.
     175histograms             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].
     181phases                 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].
     188call                   Specifies a function to call after a refinement is completed.
     189                       No function is called if this is not specified.
     190callargs               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
    146195An example follows:
    147196
     
    166215    my_project.do_refinements(reflist)
    167216   
    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
     218In this example, the list contains a set of dicts, each defined as before.
     219A separate refinement step will be performed for each element in the list unless
     220"skip" is included.
     221Note that in the second from last refinement step, parameters are both set and cleared.
     222
     223.. _Refinement_parameters_fmt:
    176224
    177225============================
     
    240288.. tabularcolumns:: |l|p{4.5in}|
    241289
    242 ===================== ============================================
     290======= ==========================================================
    243291key                   explanation
    244 ===================== ============================================
     292======= ==========================================================
    245293Cell                  Whether or not to refine the unit cell.
    246294Atoms                 Dictionary of atoms and refinement flags.
     
    252300                      and 'U' for Debye-Waller factor
    253301LeBail                Enables LeBail intensity extraction.
    254 ===================== ============================================
     302======= ==========================================================
     303
    255304
    256305.. _HAP_parameters_table:
     
    265314.. tabularcolumns:: |l|l|p{3.5in}|
    266315
    267 ===================== ====================  =================================================
    268 key                   subkey                 explanation
    269 ===================== ====================  =================================================
    270 Babinet                                      Should be a **list** of the following
    271                                              subkeys. If not, assumes both
    272                                              BabA and BabU
    273 \                     BabA
    274 \                     BabU
    275 Extinction                                   Boolean, True to refine.
    276 HStrain                                      Boolean, True to refine all appropriate
    277                                              $D_ij$ terms.
     316=============  ==========  ============================================================
     317key             subkey                 explanation
     318=============  ==========  ============================================================
     319Babinet                                Should be a **list** of the following
     320                                       subkeys. If not, assumes both
     321                                       BabA and BabU
     322\               BabA
     323\               BabU
     324Extinction                             Boolean, True to refine.
     325HStrain                                Boolean, True to refine all appropriate
     326                                       $D_ij$ terms.
    278327Mustrain
    279 \                     type                   Mustrain model. One of 'isotropic',
    280                                              'uniaxial', or 'generalized'. Should always
    281                                              be specified.
    282 \                     direction              For uniaxial only. A list of three
    283                                              integers,
    284                                              the [hkl] direction of the axis.
    285 \                     refine                 Usually boolean, set to True to refine.
    286                                              When in doubt, set it to true.
    287                                              For uniaxial model, can specify list
    288                                              of 'axial' or 'equatorial' or a single
    289                                              boolean sets both axial and equatorial.
    290 Size                                         Not implemented
    291 \                     type                   Size broadening model. One of 'isotropic',
    292                                              'uniaxial', or 'ellipsoid'. Should always
    293                                              be specified.
    294 \                     direction              For uniaxial only. A list of three
    295                                              integers,
    296                                              the [hkl] direction of the axis.
    297 \                     refine                 A boolean, True to refine.
    298 Pref.Ori.                                    Boolean, True to refine
    299 Show                                         Boolean, True to refine
    300 Use                                          Boolean, True to refine
    301 Scale                                        Phase fraction; Boolean, True to refine
    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.
     339Size                                   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.
     347Pref.Ori.                              Boolean, True to refine
     348Show                                   Boolean, True to refine
     349Use                                    Boolean, True to refine
     350Scale                                  Phase fraction; Boolean, True to refine
     351=============  ==========  ============================================================
    303352
    304353
     
    315364if '2' in platform.python_version_tuple()[0]:
    316365    import cPickle
     366    strtypes = (str,unicode)
    317367else:
    318368    import _pickle as cPickle
     369    strtypes = (str,bytes)
    319370import imp
    320371import copy
     
    334385import GSASIIspc as G2spc
    335386import GSASIIElem as G2elem
     387
    336388
    337389# Delay imports to not slow down small scripts
     
    668720    """
    669721    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)
    673724    gsasii_version = str(GSASIIpath.GetVersionNumber())
    674725    LoadG2fil()
     
    677728
    678729    controls_data = dict(G2obj.DefaultControls)
    679     controls_data['LastSavedAs'] = unicode(filename)
     730    controls_data['LastSavedAs'] = filename
    680731    controls_data['LastSavedUsing'] = gsasii_version
    681732    controls_data['PythonVersions'] = python_library_versions
     
    703754
    704755
    705 def import_generic(filename, readerlist):
     756def import_generic(filename, readerlist, fmthint=None):
    706757    """Attempt to import a filename, using a list of reader objects.
    707758
     
    710761    primaryReaders, secondaryReaders = [], []
    711762    for reader in readerlist:
     763        if fmthint is not None and fmthint not in reader.formatName: continue
    712764        flag = reader.ExtensionValidator(filename)
    713765        if flag is None:
     
    812864    """
    813865    HistName = 'PWDR ' + G2obj.StripUnicode(reader.idstring, '_')
    814     HistName = unicode(G2obj.MakeUniqueLabel(HistName, existingnames))
     866    HistName = G2obj.MakeUniqueLabel(HistName, existingnames)
    815867
    816868    try:
     
    10351087        SaveDictToProjFile(self.data, self.names, self.filename)
    10361088
    1037     def add_powder_histogram(self, datafile, iparams, phases=[]):
     1089    def add_powder_histogram(self, datafile, iparams, phases=[], fmthint=None):
    10381090        """Loads a powder data histogram into the project.
    10391091
     
    10451097        :param str iparams: The instrument parameters file, a filename.
    10461098        :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).
    10471104
    10481105        :returns: A :class:`G2PwdrData` object representing
     
    10521109        datafile = os.path.abspath(os.path.expanduser(datafile))
    10531110        iparams = os.path.abspath(os.path.expanduser(iparams))
    1054         pwdrreaders = import_generic(datafile, PwdrDataReaders)
     1111        pwdrreaders = import_generic(datafile, PwdrDataReaders,fmthint=fmthint)
    10551112        histname, new_names, pwdrdata = load_pwd_from_reader(
    10561113                                          pwdrreaders[0], iparams,
     
    10711128        return self.histogram(histname)
    10721129
    1073     def add_phase(self, phasefile, phasename=None, histograms=[]):
     1130    def add_phase(self, phasefile, phasename=None, histograms=[], fmthint=None):
    10741131        """Loads a phase into the project from a .cif file
    10751132
     
    10781135        :param list histograms: The names of the histograms to associate with
    10791136            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).
    10801142
    10811143        :returns: A :class:`G2Phase` object representing the
     
    10871149
    10881150        # TODO handle multiple phases in a file
    1089         phasereaders = import_generic(phasefile, PhaseReaders)
     1151        phasereaders = import_generic(phasefile, PhaseReaders, fmthint=fmthint)
    10901152        phasereader = phasereaders[0]
    10911153       
     
    11321194            phasenames = [u'Phases']
    11331195            self.names.append(phasenames)
    1134         phasenames.append(unicode(phasename))
     1196        phasenames.append(phasename)
    11351197
    11361198        # TODO should it be self.filename, not phasefile?
     
    12901352    def do_refinements(self, refinements, histogram='all', phase='all',
    12911353                       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.
    12951361        :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.
    12971364        :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([])
    12991380        """
     1381       
    13001382        for proj in self.iter_refinements(refinements, histogram, phase,
    13011383                                          outputnames, makeBack):
     
    13071389        """Conducts a series of refinements, iteratively. Stops after every
    13081390        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
    13191394        >>> def checked_refinements(proj):
    13201395        ...     for p in proj.iter_refinements(refs):
     
    13351410            outputnames = [None for r in refinements]
    13361411
    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)
    13391424            # Handle 'once' args - refinements that are disabled after this
    13401425            # refinement
    1341             if 'once' in refinement:
    1342                 temp = {'set': refinement['once']}
    1343                 self.set_refinement(temp, histogram, phase)
     1426            if 'once' in refinedict:
     1427                temp = {'set': refinedict['once']}
     1428                self.set_refinement(temp, hist, ph)
    13441429
    13451430            if output:
    13461431                self.save(output)
    13471432
    1348             self.refine(makeBack=makeBack)
     1433            if 'skip' not in refinedict:
     1434                self.refine(makeBack=makeBack)
    13491435            yield self
    13501436
    13511437            # Handle 'once' args - refinements that are disabled after this
    13521438            # 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]))
    13561444
    13571445    def set_refinement(self, refinement, histogram='all', phase='all'):
     
    15881676            if c not in ' FXU':
    15891677                raise ValueError("Invalid atom refinement: ", other)
    1590         self.data[self.ct+1] = unicode(other)
     1678        self.data[self.ct+1] = other
    15911679
    15921680    @property
     
    21762264                        newType = None
    21772265                        direction = None
    2178                         if isinstance(val, (unicode, str)):
     2266                        if isinstance(val, strtypes):
    21792267                            if val in ['isotropic', 'uniaxial', 'generalized']:
    21802268                                newType = val
     
    21932281                                if 'refine' in val:
    21942282                                    types = val['refine']
    2195                                     if isinstance(types, (unicode, str)):
     2283                                    if isinstance(types, strtypes):
    21962284                                        types = [types]
    21972285                                    elif isinstance(types, bool):
     
    22262314                        newType = None
    22272315                        direction = None
    2228                         if isinstance(val, (unicode, str)):
     2316                        if isinstance(val, strtypes):
    22292317                            if val in ['isotropic', 'uniaxial', 'ellipsoidal']:
    22302318                                newType = val
Note: See TracChangeset for help on using the changeset viewer.