Ignore:
Timestamp:
Dec 25, 2017 1:25:21 PM (4 years ago)
Author:
toby
Message:

expand scripting capabilities and documentation

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIscriptable.py

    r3202 r3205  
    1616They all inherit from :class:`G2ObjectWrapper`. The chief class is :class:`G2Project`,
    1717which represents an entire GSAS-II project and provides several methods to access
    18 phases, powder histograms, and execute Rietveld refinements.
    19 These routines can be accessed either by directly calling these routines
    20 or via a command line interface. Run::
    21 
    22    python GSASIIscriptable.py --help
    23 
    24 to show the available subcommands, and inspect each subcommand with
    25 `python GSASIIscriptable.py <subcommand> --help`.
    26 
     18phases, powder histograms, and execute Rietveld refinements. These routines are
     19typically called by using the :ref:`CommandlineInterface` to access a number of features or
     20the :ref:`API`, which allows much more versatile access.
    2721
    2822.. _Refinement_parameters_kinds:
     
    5852      been provided.
    5953
    60 There are several ways to set parameters using different objects, as described below,
     54There are several ways to set parameters using different objects, as described below.
    6155
    6256------------------------
     
    120114.. _Project_objects:
    121115
    122 ------------------------
    123 Project objects
    124 ------------------------
     116-----------------------------
     117Project-level Parameter Dict
     118-----------------------------
    125119It is also possible to create a composite dictionary
    126 that reference all three of the above types of refinement parameters.
     120that references all three of the above types of refinement parameters.
    127121In this case dictionaries are nested with keys at the outer level, such as
    128122"set" and "clear" which determine function is used with function
     
    151145Refinement recipe
    152146------------------------
    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`.
     147Finally, it is possible to specify a sequence of refinement actions as a list of
     148dicts that contain :ref:`Project_objects` objects. This list is
     149supplied as an argument to :meth:`G2Project.do_refinements`.
    155150These dicts in this list are each like those described in the
    156151:ref:`Project_objects` section,
     
    351346=============  ==========  ============================================================
    352347
    353 
    354 ============================
    355 Scriptable API
    356 ============================
     348.. _CommandlineInterface:
     349
     350=======================================
     351GSASIIscriptable Command-line Interface
     352=======================================
     353
     354One way to access these routines is by calling this script
     355via a command line interface as a shell command, where it is expected to be called as::
     356
     357       python GSASIIscriptable.py <subcommand> <file.gpx> <options>
     358
     359    The following subcommands are defined:
     360
     361        * create, see :func:`create`
     362        * add, see :func:`add`
     363        * dump, see :func:`dump`
     364        * refine, see :func:`refine`
     365        * seqrefine, see :func:`seqrefine`
     366        * export, :func:`export`
     367        * browse, see :func:`IPyBrowse`
     368       
     369Run::
     370
     371   python GSASIIscriptable.py --help
     372
     373to show the available subcommands, and inspect each subcommand with
     374`python GSASIIscriptable.py <subcommand> --help` or see the documentation for each of the above routines.
     375
     376.. _JsonFormat:
     377
     378-------------------------
     379Parameters in JSON files
     380-------------------------
     381
     382The refine command requires two inputs: an existing GSAS-II project (.gpx) file and
     383a JSON format file
     384(see `Introducing JSON <http://json.org/>`_) that contains a single dict.
     385This dict may have two keys:
     386
     387refinements:
     388  This defines the a set of refinement steps in a JSON representation of a
     389  :ref:`Refinement_recipe` list.
     390
     391code:
     392  This optionally defines Python code that will be executed after the project is loaded,
     393  but before the refinement is started. This can be used to execute Python code to change
     394  parameters that are not accessible via a :ref:`Refinement_recipe` dict (note that the
     395  project object is accessed with variable ``proj``) or to define code that will be called
     396  later (see key ``call`` in the :ref:`Refinement_recipe` section.)
     397   
     398JSON website: `Introducing JSON <http://json.org/>`_.
     399
     400.. _API:
     401
     402===================================
     403GSASIIscriptable Application Layer
     404===================================
     405
     406This module provides a large number of classes and modules, as described below.
     407Most commonly a script will create a G2Project object using :class:`G2Project` and then
     408perform actions such as
     409adding a histogram (method :meth:`G2Project.add_powder_histogram`),
     410adding a phase (method :meth:`G2Project.add_phase`),
     411or setting parameters and performing a refinement
     412(method :meth:`G2Project.do_refinements`).
     413
     414In some cases, it may be easier or more options may be available by direct access to
     415methods inside :class:`G2PwdrData` or :class:`G2Phase`
     416
     417---------------------------------------
     418GSASIIscriptable Classes and functions
     419---------------------------------------
    357420"""
    358 from __future__ import division, print_function # needed?
     421from __future__ import division, print_function
    359422import argparse
    360423import os.path as ospath
     
    694757            if badList[key] > 1:
    695758                msg += ' (' + str(badList[key]) + ' times)'
    696         raise Exception("Phase error:\n" + msg)
     759        raise G2ScriptException("Phase error:\n" + msg)
    697760        # wx.MessageBox(msg,caption='Element symbol error')
    698761    F000X = 0.
     
    753816    pass
    754817
     818class G2ScriptException(Exception):
     819    pass
    755820
    756821def import_generic(filename, readerlist, fmthint=None):
     
    14411506                self.set_refinement(temp, hist, ph)
    14421507            if 'call' in refinedict:
    1443                 refinedict['call'](*refinedict.get('callargs',[self]))
     1508                fxn = refinedict['call']
     1509                if callable(fxn):
     1510                    fxn(*refinedict.get('callargs',[self]))
     1511                elif callable(eval(fxn)):
     1512                    eval(fxn)(*refinedict.get('callargs',[self]))
     1513                else:
     1514                    raise G2ScriptException("Error: call value {} is not callable".format(fxn))
    14441515
    14451516    def set_refinement(self, refinement, histogram='all', phase='all'):
     
    21552226                # self._WriteAtomsNuclear(fp, parmDict, sigDict)
    21562227            else:
    2157                 raise Exception("no export for "+str(self.data['General']['Type'])+" coordinates implemented")
     2228                raise G2ScriptException("no export for "+str(self.data['General']['Type'])+" coordinates implemented")
    21582229            # report cell contents
    21592230            cif.WriteComposition(fp, self.data, self.name, parmDict)
     
    24222493# below)
    24232494
    2424 
     2495commandhelp={}
     2496commandhelp["create"] = "creates a GSAS-II project, optionally adding histograms and/or phases"
    24252497def create(args):
    2426     """The create subcommand."""
     2498    """The create subcommand. This creates a GSAS-II project, optionally adding histograms and/or phases::
     2499
     2500  usage: GSASIIscriptable.py create [-h] [-d HISTOGRAMS [HISTOGRAMS ...]]
     2501                                  [-i IPARAMS [IPARAMS ...]]
     2502                                  [-p PHASES [PHASES ...]]
     2503                                  filename
     2504                                 
     2505positional arguments::
     2506
     2507  filename              the project file to create. should end in .gpx
     2508
     2509optional arguments::
     2510
     2511  -h, --help            show this help message and exit
     2512  -d HISTOGRAMS [HISTOGRAMS ...], --histograms HISTOGRAMS [HISTOGRAMS ...]
     2513                        list of datafiles to add as histograms
     2514  -i IPARAMS [IPARAMS ...], --iparams IPARAMS [IPARAMS ...]
     2515                        instrument parameter file, must be one for every
     2516                        histogram
     2517  -p PHASES [PHASES ...], --phases PHASES [PHASES ...]
     2518                        list of phases to add. phases are automatically
     2519                        associated with all histograms given.
     2520
     2521    """
    24272522    proj = G2Project(filename=args.filename)
    24282523
    24292524    hist_objs = []
    2430     for h in args.histograms:
    2431         hist_objs.append(proj.add_powder_histogram(h, args.iparams))
    2432 
    2433     for p in args.phases:
    2434         proj.add_phase(p, histograms=hist_objs)
     2525    if args.histograms:
     2526        for h,i in zip(args.histograms,args.iparams):
     2527            print("Adding histogram from",h,"with instparm ",i)
     2528            hist_objs.append(proj.add_powder_histogram(h, i))
     2529
     2530    if args.phases:
     2531        for p in args.phases:
     2532            print("Adding phase from",p)
     2533            proj.add_phase(p, histograms=hist_objs)
     2534        print('Linking phase(s) to histogram(s):')
     2535        for h in hist_objs:
     2536            print ('   '+h.name)
    24352537
    24362538    proj.save()
    24372539
    2438 
     2540commandhelp["add"] = "adds histograms and/or phases to GSAS-II project"
     2541def add(args):
     2542    """The add subcommand. This adds histograms and/or phases to GSAS-II project::
     2543
     2544  usage: GSASIIscriptable.py add [-h] [-d HISTOGRAMS [HISTOGRAMS ...]]
     2545                               [-i IPARAMS [IPARAMS ...]]
     2546                               [-hf HISTOGRAMFORMAT] [-p PHASES [PHASES ...]]
     2547                               [-pf PHASEFORMAT] [-l HISTLIST [HISTLIST ...]]
     2548                               filename
     2549
     2550
     2551positional arguments::
     2552
     2553  filename              the project file to open. Should end in .gpx
     2554
     2555optional arguments::
     2556
     2557  -h, --help            show this help message and exit
     2558  -d HISTOGRAMS [HISTOGRAMS ...], --histograms HISTOGRAMS [HISTOGRAMS ...]
     2559                        list of datafiles to add as histograms
     2560  -i IPARAMS [IPARAMS ...], --iparams IPARAMS [IPARAMS ...]
     2561                        instrument parameter file, must be one for every
     2562                        histogram
     2563  -hf HISTOGRAMFORMAT, --histogramformat HISTOGRAMFORMAT
     2564                        format hint for histogram import. Applies to all
     2565                        histograms
     2566  -p PHASES [PHASES ...], --phases PHASES [PHASES ...]
     2567                        list of phases to add. phases are automatically
     2568                        associated with all histograms given.
     2569  -pf PHASEFORMAT, --phaseformat PHASEFORMAT
     2570                        format hint for phase import. Applies to all phases.
     2571                        Example: -pf CIF
     2572  -l HISTLIST [HISTLIST ...], --histlist HISTLIST [HISTLIST ...]
     2573                        list of histgram indices to associate with added
     2574                        phases. If not specified, phases are associated with
     2575                        all previously loaded histograms. Example: -l 2 3 4
     2576   
     2577    """
     2578    proj = G2Project(args.filename)
     2579
     2580    if args.histograms:
     2581        for h,i in zip(args.histograms,args.iparams):
     2582            print("Adding histogram from",h,"with instparm ",i)
     2583            proj.add_powder_histogram(h, i, fmthint=args.histogramformat)
     2584
     2585    if args.phases:
     2586        if not args.histlist:
     2587            histlist = proj.histograms()
     2588        else:
     2589            histlist = [proj.histogram(i) for i in args.histlist]
     2590
     2591        for p in args.phases:
     2592            print("Adding phase from",p)
     2593            proj.add_phase(p, histograms=histlist, fmthint=args.phaseformat)
     2594           
     2595        if not args.histlist:
     2596            print('Linking phase(s) to all histogram(s)')
     2597        else:
     2598            print('Linking phase(s) to histogram(s):')
     2599            for h in histlist:
     2600                print ('   '+h.name)
     2601
     2602    proj.save()
     2603
     2604
     2605commandhelp["dump"] = "Shows the contents of a GSAS-II project"
    24392606def dump(args):
    2440     """The dump subcommand. This is intended to be called by the :func:`main` routine.
    2441     This is typically called by invoking this script with a subcommand::
    2442 
    2443        python GSASIIscriptable.py dump <file.gpx>
     2607    """The dump subcommand shows the contents of a GSAS-II project::
     2608
     2609       usage: GSASIIscriptable.py dump [-h] [-d] [-p] [-r] files [files ...]
     2610
     2611positional arguments::
     2612
     2613  files
     2614
     2615optional arguments::
     2616
     2617  -h, --help        show this help message and exit
     2618  -d, --histograms  list histograms in files, overrides --raw
     2619  -p, --phases      list phases in files, overrides --raw
     2620  -r, --raw         dump raw file contents, default
     2621 
    24442622    """
    24452623    if not args.histograms and not args.phases:
     
    24682646
    24692647
     2648commandhelp["browse"] = "Load a GSAS-II project and then open a IPython shell to browse it"
    24702649def IPyBrowse(args):
    2471     """Load a .gpx file and then open a IPython shell to browse it
     2650    """Load a .gpx file and then open a IPython shell to browse it::
     2651
     2652  usage: GSASIIscriptable.py browse [-h] files [files ...]
     2653
     2654positional arguments::
     2655
     2656  files       list of files to browse
     2657
     2658optional arguments::
     2659
     2660  -h, --help  show this help message and exit
     2661
    24722662    """
    24732663    for fname in args.files:
     
    24782668
    24792669
     2670commandhelp["refine"] = '''
     2671Conducts refinements on GSAS-II projects according to a list of refinement
     2672steps in a JSON dict
     2673'''
    24802674def refine(args):
    2481     """The refine subcommand"""
     2675    """Conducts refinements on GSAS-II projects according to a JSON refinement dict::
     2676   
     2677  usage: GSASIIscriptable.py refine [-h] gpxfile [refinements]
     2678
     2679positional arguments::
     2680
     2681  gpxfile      the project file to refine
     2682  refinements  json file of refinements to apply. if not present refines file
     2683               as-is
     2684
     2685optional arguments::
     2686
     2687  -h, --help   show this help message and exit
     2688 
     2689    """
    24822690    proj = G2Project(args.gpxfile)
    24832691    if args.refinements is None:
     
    24872695        with open(args.refinements) as refs:
    24882696            refs = json.load(refs)
     2697        if type(refs) is not dict:
     2698            raise G2ScriptException("Error: JSON object must be a dict.")
     2699        if "code" in refs:
     2700            print("executing code:\n|  ",'\n|  '.join(refs['code']))
     2701            exec('\n'.join(refs['code']))
    24892702        proj.do_refinements(refs['refinements'])
    24902703
    24912704
     2705commandhelp["seqrefine"] = "Not implemented. Placeholder for eventual sequential refinement implementation"
    24922706def seqrefine(args):
    24932707    """The seqrefine subcommand"""
     
    24952709
    24962710
     2711commandhelp["export"] = "Export phase as CIF"
    24972712def export(args):
    2498     """The export subcommand"""
    2499     # Export phase as CIF to args.exportfile
     2713    """The export subcommand: Exports phase as CIF::
     2714
     2715      usage: GSASIIscriptable.py export [-h] gpxfile phase exportfile
     2716
     2717positional arguments::
     2718
     2719  gpxfile     the project file from which to export
     2720  phase       identifier of phase to export
     2721  exportfile  the .cif file to export to
     2722
     2723optional arguments::
     2724
     2725  -h, --help  show this help message and exit
     2726
     2727    """
    25002728    proj = G2Project(args.gpxfile)
    25012729    phase = proj.phase(args.phase)
     
    25102738# The arguments are passed directly to the add_argument() method
    25112739# of an argparse.ArgumentParser
     2740
    25122741subcommands = {"create":
    25132742               (create, [_args_kwargs('filename',
    25142743                                      help='the project file to create. should end in .gpx'),
    25152744
    2516                          _args_kwargs('-i', '--iparams',
    2517                                       help='instrument parameter file'),
    2518 
    25192745                         _args_kwargs('-d', '--histograms',
    25202746                                      nargs='+',
    25212747                                      help='list of datafiles to add as histograms'),
     2748                                     
     2749                         _args_kwargs('-i', '--iparams',
     2750                                      nargs='+',
     2751                                      help='instrument parameter file, must be one'
     2752                                           ' for every histogram'
     2753                                      ),
    25222754
    25232755                         _args_kwargs('-p', '--phases',
     
    25262758                                           'automatically associated with all '
    25272759                                           'histograms given.')]),
    2528 
     2760               "add": (add, [_args_kwargs('filename',
     2761                                      help='the project file to open. Should end in .gpx'),
     2762
     2763                         _args_kwargs('-d', '--histograms',
     2764                                      nargs='+',
     2765                                      help='list of datafiles to add as histograms'),
     2766                                     
     2767                         _args_kwargs('-i', '--iparams',
     2768                                      nargs='+',
     2769                                      help='instrument parameter file, must be one'
     2770                                           ' for every histogram'
     2771                                      ),
     2772                                     
     2773                         _args_kwargs('-hf', '--histogramformat',
     2774                                      help='format hint for histogram import. Applies to all'
     2775                                           ' histograms'
     2776                                      ),
     2777
     2778                         _args_kwargs('-p', '--phases',
     2779                                      nargs='+',
     2780                                      help='list of phases to add. phases are '
     2781                                           'automatically associated with all '
     2782                                           'histograms given.'),
     2783
     2784                         _args_kwargs('-pf', '--phaseformat',
     2785                                      help='format hint for phase import. Applies to all'
     2786                                           ' phases. Example: -pf CIF'
     2787                                      ),
     2788                                     
     2789                         _args_kwargs('-l', '--histlist',
     2790                                      nargs='+',
     2791                                      help='list of histgram indices to associate with added'
     2792                                           ' phases. If not specified, phases are'
     2793                                           ' associated with all previously loaded'
     2794                                           ' histograms. Example: -l 2 3 4')]),
     2795                                           
    25292796               "dump": (dump, [_args_kwargs('-d', '--histograms',
    25302797                                     action='store_true',
     
    25432810               (refine, [_args_kwargs('gpxfile', help='the project file to refine'),
    25442811                         _args_kwargs('refinements',
    2545                                       help='json file of refinements to apply. if not present'
     2812                                      help='JSON file of refinements to apply. if not present'
    25462813                                           ' refines file as-is',
    25472814                                      default=None,
     
    25582825
    25592826def main():
    2560     '''The command line interface for GSASIIscriptable.
    2561 
    2562     Executes one of the following subcommands:
    2563 
    2564         * :func:`create`
    2565         * :func:`dump`
    2566         * :func:`refine`
    2567         * :func:`seqrefine`
    2568         * :func:`export`
    2569         * browse (:func:`IPyBrowse`)
    2570 
    2571     These commands are typically called by invoking this script with a subcommand,
    2572     for example::
    2573 
    2574        python GSASIIscriptable.py dump <file.gpx>
    2575        
     2827    '''The command-line interface for calling GSASIIscriptable as a shell command,
     2828    where it is expected to be called as::
     2829
     2830       python GSASIIscriptable.py <subcommand> <file.gpx> <options>
     2831
     2832    The following subcommands are defined:
     2833
     2834        * create, see :func:`create`
     2835        * add, see :func:`add`
     2836        * dump, see :func:`dump`
     2837        * refine, see :func:`refine`
     2838        * seqrefine, see :func:`seqrefine`
     2839        * export, :func:`export`
     2840        * browse, see :func:`IPyBrowse`
    25762841
    25772842    .. seealso::
    25782843        :func:`create`
     2844        :func:`add`
    25792845        :func:`dump`
    25802846        :func:`refine`
     
    25832849        :func:`IPyBrowse`
    25842850    '''
    2585     parser = argparse.ArgumentParser()
     2851    parser = argparse.ArgumentParser(description=
     2852        "Use of "+os.path.split(__file__)[1]+" Allows GSAS-II actions from command line."
     2853        )
    25862854    subs = parser.add_subparsers()
    25872855
    25882856    # Create all of the specified subparsers
    25892857    for name, (func, args) in subcommands.items():
    2590         new_parser = subs.add_parser(name)
     2858        new_parser = subs.add_parser(name,help=commandhelp.get(name),
     2859                                     description='Command "'+name+'" '+commandhelp.get(name))
    25912860        for listargs, kwds in args:
    25922861            new_parser.add_argument(*listargs, **kwds)
Note: See TracChangeset for help on using the changeset viewer.