Changeset 3205
- Timestamp:
- Dec 25, 2017 1:25:21 PM (5 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/GSASIIscriptable.py
r3202 r3205 16 16 They all inherit from :class:`G2ObjectWrapper`. The chief class is :class:`G2Project`, 17 17 which 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 18 phases, powder histograms, and execute Rietveld refinements. These routines are 19 typically called by using the :ref:`CommandlineInterface` to access a number of features or 20 the :ref:`API`, which allows much more versatile access. 27 21 28 22 .. _Refinement_parameters_kinds: … … 58 52 been provided. 59 53 60 There are several ways to set parameters using different objects, as described below ,54 There are several ways to set parameters using different objects, as described below. 61 55 62 56 ------------------------ … … 120 114 .. _Project_objects: 121 115 122 ------------------------ 123 Project objects124 ------------------------ 116 ----------------------------- 117 Project-level Parameter Dict 118 ----------------------------- 125 119 It is also possible to create a composite dictionary 126 that reference all three of the above types of refinement parameters.120 that references all three of the above types of refinement parameters. 127 121 In this case dictionaries are nested with keys at the outer level, such as 128 122 "set" and "clear" which determine function is used with function … … 151 145 Refinement recipe 152 146 ------------------------ 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`. 147 Finally, it is possible to specify a sequence of refinement actions as a list of 148 dicts that contain :ref:`Project_objects` objects. This list is 149 supplied as an argument to :meth:`G2Project.do_refinements`. 155 150 These dicts in this list are each like those described in the 156 151 :ref:`Project_objects` section, … … 351 346 ============= ========== ============================================================ 352 347 353 354 ============================ 355 Scriptable API 356 ============================ 348 .. _CommandlineInterface: 349 350 ======================================= 351 GSASIIscriptable Command-line Interface 352 ======================================= 353 354 One way to access these routines is by calling this script 355 via 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 369 Run:: 370 371 python GSASIIscriptable.py --help 372 373 to 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 ------------------------- 379 Parameters in JSON files 380 ------------------------- 381 382 The refine command requires two inputs: an existing GSAS-II project (.gpx) file and 383 a JSON format file 384 (see `Introducing JSON <http://json.org/>`_) that contains a single dict. 385 This dict may have two keys: 386 387 refinements: 388 This defines the a set of refinement steps in a JSON representation of a 389 :ref:`Refinement_recipe` list. 390 391 code: 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 398 JSON website: `Introducing JSON <http://json.org/>`_. 399 400 .. _API: 401 402 =================================== 403 GSASIIscriptable Application Layer 404 =================================== 405 406 This module provides a large number of classes and modules, as described below. 407 Most commonly a script will create a G2Project object using :class:`G2Project` and then 408 perform actions such as 409 adding a histogram (method :meth:`G2Project.add_powder_histogram`), 410 adding a phase (method :meth:`G2Project.add_phase`), 411 or setting parameters and performing a refinement 412 (method :meth:`G2Project.do_refinements`). 413 414 In some cases, it may be easier or more options may be available by direct access to 415 methods inside :class:`G2PwdrData` or :class:`G2Phase` 416 417 --------------------------------------- 418 GSASIIscriptable Classes and functions 419 --------------------------------------- 357 420 """ 358 from __future__ import division, print_function # needed?421 from __future__ import division, print_function 359 422 import argparse 360 423 import os.path as ospath … … 694 757 if badList[key] > 1: 695 758 msg += ' (' + str(badList[key]) + ' times)' 696 raise Exception("Phase error:\n" + msg)759 raise G2ScriptException("Phase error:\n" + msg) 697 760 # wx.MessageBox(msg,caption='Element symbol error') 698 761 F000X = 0. … … 753 816 pass 754 817 818 class G2ScriptException(Exception): 819 pass 755 820 756 821 def import_generic(filename, readerlist, fmthint=None): … … 1441 1506 self.set_refinement(temp, hist, ph) 1442 1507 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)) 1444 1515 1445 1516 def set_refinement(self, refinement, histogram='all', phase='all'): … … 2155 2226 # self._WriteAtomsNuclear(fp, parmDict, sigDict) 2156 2227 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") 2158 2229 # report cell contents 2159 2230 cif.WriteComposition(fp, self.data, self.name, parmDict) … … 2422 2493 # below) 2423 2494 2424 2495 commandhelp={} 2496 commandhelp["create"] = "creates a GSAS-II project, optionally adding histograms and/or phases" 2425 2497 def 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 2505 positional arguments:: 2506 2507 filename the project file to create. should end in .gpx 2508 2509 optional 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 """ 2427 2522 proj = G2Project(filename=args.filename) 2428 2523 2429 2524 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) 2435 2537 2436 2538 proj.save() 2437 2539 2438 2540 commandhelp["add"] = "adds histograms and/or phases to GSAS-II project" 2541 def 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 2551 positional arguments:: 2552 2553 filename the project file to open. Should end in .gpx 2554 2555 optional 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 2605 commandhelp["dump"] = "Shows the contents of a GSAS-II project" 2439 2606 def 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 2611 positional arguments:: 2612 2613 files 2614 2615 optional 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 2444 2622 """ 2445 2623 if not args.histograms and not args.phases: … … 2468 2646 2469 2647 2648 commandhelp["browse"] = "Load a GSAS-II project and then open a IPython shell to browse it" 2470 2649 def 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 2654 positional arguments:: 2655 2656 files list of files to browse 2657 2658 optional arguments:: 2659 2660 -h, --help show this help message and exit 2661 2472 2662 """ 2473 2663 for fname in args.files: … … 2478 2668 2479 2669 2670 commandhelp["refine"] = ''' 2671 Conducts refinements on GSAS-II projects according to a list of refinement 2672 steps in a JSON dict 2673 ''' 2480 2674 def 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 2679 positional 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 2685 optional arguments:: 2686 2687 -h, --help show this help message and exit 2688 2689 """ 2482 2690 proj = G2Project(args.gpxfile) 2483 2691 if args.refinements is None: … … 2487 2695 with open(args.refinements) as refs: 2488 2696 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'])) 2489 2702 proj.do_refinements(refs['refinements']) 2490 2703 2491 2704 2705 commandhelp["seqrefine"] = "Not implemented. Placeholder for eventual sequential refinement implementation" 2492 2706 def seqrefine(args): 2493 2707 """The seqrefine subcommand""" … … 2495 2709 2496 2710 2711 commandhelp["export"] = "Export phase as CIF" 2497 2712 def 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 2717 positional 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 2723 optional arguments:: 2724 2725 -h, --help show this help message and exit 2726 2727 """ 2500 2728 proj = G2Project(args.gpxfile) 2501 2729 phase = proj.phase(args.phase) … … 2510 2738 # The arguments are passed directly to the add_argument() method 2511 2739 # of an argparse.ArgumentParser 2740 2512 2741 subcommands = {"create": 2513 2742 (create, [_args_kwargs('filename', 2514 2743 help='the project file to create. should end in .gpx'), 2515 2744 2516 _args_kwargs('-i', '--iparams',2517 help='instrument parameter file'),2518 2519 2745 _args_kwargs('-d', '--histograms', 2520 2746 nargs='+', 2521 2747 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 ), 2522 2754 2523 2755 _args_kwargs('-p', '--phases', … … 2526 2758 'automatically associated with all ' 2527 2759 '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 2529 2796 "dump": (dump, [_args_kwargs('-d', '--histograms', 2530 2797 action='store_true', … … 2543 2810 (refine, [_args_kwargs('gpxfile', help='the project file to refine'), 2544 2811 _args_kwargs('refinements', 2545 help=' jsonfile of refinements to apply. if not present'2812 help='JSON file of refinements to apply. if not present' 2546 2813 ' refines file as-is', 2547 2814 default=None, … … 2558 2825 2559 2826 def 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` 2576 2841 2577 2842 .. seealso:: 2578 2843 :func:`create` 2844 :func:`add` 2579 2845 :func:`dump` 2580 2846 :func:`refine` … … 2583 2849 :func:`IPyBrowse` 2584 2850 ''' 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 ) 2586 2854 subs = parser.add_subparsers() 2587 2855 2588 2856 # Create all of the specified subparsers 2589 2857 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)) 2591 2860 for listargs, kwds in args: 2592 2861 new_parser.add_argument(*listargs, **kwds)
Note: See TracChangeset
for help on using the changeset viewer.