Changeset 3012


Ignore:
Timestamp:
Aug 17, 2017 10:21:17 AM (6 years ago)
Author:
odonnell
Message:

Switch GSASIIscriptable.py to argparse, fixed bug with .instprm files

Location:
trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIfiles.py

    r3000 r3012  
    237237             str: Error message if failed
    238238   
    239     (transliterated from GSASII.py:1012, function of the same name)
     239    (transliterated from GSASIIdataGUI.py:1235 (rev 3008), function of the same name)
    240240     '''
    241241    if 'GSAS-II' not in instLines[0]:
     
    251251            if S[0] == '#' and 'Bank' in S:
    252252                banklist.add(int(S.split(':')[0].split()[1]))
    253         bank = sorted(banklist[1])
     253        # Picks the first bank by default
     254        if len(banklist) > 1:
     255            bank = sorted(banklist)[0]
     256        else:
     257            bank = 1
    254258        rd.powderentry[2] = bank
    255259    while il < len(instLines):
  • trunk/GSASIIscriptable.py

    r3011 r3012  
    3232"""
    3333from __future__ import division, print_function # needed?
     34import argparse
    3435import os.path as ospath
    3536import datetime as dt
     
    771772        """
    772773        LoadG2fil()
     774        histograms = [self.histogram(h).name for h in histograms]
    773775        phasefile = os.path.abspath(os.path.expanduser(phasefile))
    774776
     
    869871            :func:`~GSASIIscriptable.G2Project.phases`
    870872            """
     873        if isinstance(histname, G2PwdrData):
     874            if histname.proj == self:
     875                return histname
    871876        if histname in self.data:
    872877            return G2PwdrData(self.data[histname], self)
     
    17761781
    17771782
    1778 # TODO SUBPARSERS
    1779 
    1780 def create(*args):
    1781     """The create subcommand.
    1782 
    1783     Should be passed all the command-line arguments after `create`"""
    1784     import argparse
    1785     parser = argparse.ArgumentParser(prog=' '.join([sys.argv[0], sys.argv[1]]))
    1786     parser.add_argument('filename',
    1787                         help='the project file to create. should end in .gpx')
    1788     parser.add_argument('-g', '--histograms', nargs='+',
    1789                         help='list of histograms to add')
    1790     parser.add_argument('-p', '--phases', nargs='+',
    1791                         help='list of phases to add')
    1792     results = parser.parse_args(args)
    1793 
    1794     proj = G2Project(filename=filename)
    1795 
    1796     isPhase = False
    1797     isPowderData = False
    1798     isInstPrms = False
    1799     instPrms = None
    1800 
    1801     # TODO how to associate phase with histogram?
    1802     for arg in args[1:]:
    1803         if arg == '--phases':
    1804             isPhase = True
    1805             isPowderData = False
    1806             isInstPrms = False
    1807         elif arg == '--powder':
    1808             isPhase = False
    1809             isPowderData = True
    1810             isInstPrms = False
    1811         # Instrument parameters must be specified before
    1812         # any powder data files are passed
    1813         elif arg == '--iparams':
    1814             isPhase = False
    1815             isPowderData = False
    1816             isInstPrms = True
    1817         elif isPhase:
    1818             proj.add_phase(arg)
    1819         elif isPowderData:
    1820             proj.add_powder_histogram(arg, instPrms)
    1821         elif isInstPrms:
    1822             instPrms = arg
    1823             isInstPrms = False
    1824         else:
    1825             print("Not sure what to do with: {}".format(arg))
     1783def create(args):
     1784    """The create subcommand."""
     1785    proj = G2Project(filename=args.filename)
     1786
     1787    hist_objs = []
     1788    for h in args.histograms:
     1789        hist_objs.append(proj.add_powder_histogram(h, args.iparams))
     1790
     1791    for p in args.phases:
     1792        proj.add_phase(p, histograms=hist_objs)
    18261793
    18271794    proj.save()
    18281795
    18291796
    1830 def dump(*args):
     1797def dump(args):
    18311798    """The dump subcommand"""
    1832     import argparse
    1833     parser = argparse.ArgumentParser(prog=' '.join([sys.argv[0], sys.argv[1]]))
    1834     parser.add_argument('-g', '--histograms', action='store_true',
    1835                         help='list histograms in files, overrides --raw')
    1836     parser.add_argument('-p', '--phases', action='store_true',
    1837                         help='list phases in files, overrides --raw')
    1838     parser.add_argument('-r', '--raw', action='store_true',
    1839                         help='dump raw file contents')
    1840     parser.add_argument('files', nargs='*')
    1841     results = parser.parse_args(args)
    1842 
    1843     if not results.histograms and not results.phases:
    1844         results.raw = True
    1845     if results.raw:
     1799    if not args.histograms and not args.phases:
     1800        args.raw = True
     1801    if args.raw:
    18461802        import IPython.lib.pretty as pretty
    18471803
    1848     for fname in results.files:
    1849         if results.raw:
     1804    for fname in args.files:
     1805        if args.raw:
    18501806            proj, nameList = LoadDictFromProjFile(fname)
    18511807            print("file:", fname)
     
    18561812        else:
    18571813            proj = G2Project(fname)
    1858             if results.histograms:
     1814            if args.histograms:
    18591815                hists = proj.histograms()
    18601816                for h in hists:
    18611817                    print(fname, "hist", h.id, h.name)
    1862             if results.phases:
     1818            if args.phases:
    18631819                phase_list = proj.phases()
    18641820                for p in phase_list:
     
    18661822
    18671823
    1868 def IPyBrowse(*args):
     1824def IPyBrowse(args):
    18691825    """Load a .gpx file and then open a IPython shell to browse it
    18701826    """
    1871     filename = []
    1872     for arg in args:
    1873         fname = arg
     1827    for fname in args.files:
    18741828        proj, nameList = LoadDictFromProjFile(fname)
    1875         msg = "\nfile {} loaded into proj (dict) with names in nameList".format(fname)
     1829        msg = "\nfname {} loaded into proj (dict) with names in nameList".format(fname)
    18761830        GSASIIpath.IPyBreak_base(msg)
    18771831        break
    18781832
    18791833
    1880 def refine(*args):
     1834def refine(args):
    18811835    """The refine subcommand"""
    1882     proj = G2Project(args[0])
    1883     if len(args) == 1:
     1836    proj = G2Project(args.gpxfile)
     1837    if args.refinements is None:
    18841838        proj.refine()
    1885     elif len(args) == 2:
     1839    else:
    18861840        import json
    1887         with open(args[1]) as refs:
     1841        with open(args.refinements) as refs:
    18881842            refs = json.load(refs)
    18891843        proj.do_refinements(refs['refinements'])
    1890     else:
    1891         print("Refine not sure what to do with args:", args)
    1892 
    1893 
    1894 def seqrefine(*args):
     1844
     1845
     1846def seqrefine(args):
    18951847    """The seqrefine subcommand"""
    18961848    raise NotImplementedError("seqrefine is not yet implemented")
    18971849
    18981850
    1899 def export(*args):
     1851def export(args):
    19001852    """The export subcommand"""
    1901     # Export CIF or Structure or ...
    1902     gpxfile, phase, exportfile = args
    1903     proj = G2Project(gpxfile)
    1904     phase = proj.phase(phase)
    1905     phase.export_CIF(exportfile)
    1906 
    1907 
    1908 subcommands = {"create": create,
    1909                "dump": dump,
    1910                "refine": refine,
    1911                "seqrefine": seqrefine,
    1912                "export": export,
    1913                "browse": IPyBrowse}
     1853    # Export phase as CIF to args.exportfile
     1854    proj = G2Project(args.gpxfile)
     1855    phase = proj.phase(args.phase)
     1856    phase.export_CIF(args.exportfile)
     1857
     1858
     1859def _args_kwargs(*args, **kwargs):
     1860    return args, kwargs
     1861
     1862# A dictionary of the name of each subcommand, and a tuple
     1863# of its associated function and a list of its arguments
     1864# The arguments are passed directly to the add_argument() method
     1865# of an argparse.ArgumentParser
     1866subcommands = {"create":
     1867               (create, [_args_kwargs('filename',
     1868                                      help='the project file to create. should end in .gpx'),
     1869
     1870                         _args_kwargs('-i', '--iparams',
     1871                                      help='instrument parameter file'),
     1872
     1873                         _args_kwargs('-d', '--histograms',
     1874                                      nargs='+',
     1875                                      help='list of datafiles to add as histograms'),
     1876
     1877                         _args_kwargs('-p', '--phases',
     1878                                      nargs='+',
     1879                                      help='list of phases to add. phases are '
     1880                                           'automatically associated with all '
     1881                                           'histograms given.')]),
     1882
     1883               "dump": (dump, [_args_kwargs('-d', '--histograms',
     1884                                     action='store_true',
     1885                                     help='list histograms in files, overrides --raw'),
     1886
     1887                               _args_kwargs('-p', '--phases',
     1888                                            action='store_true',
     1889                                            help='list phases in files, overrides --raw'),
     1890
     1891                               _args_kwargs('-r', '--raw',
     1892                                      action='store_true', help='dump raw file contents, default'),
     1893
     1894                               _args_kwargs('files', nargs='+')]),
     1895
     1896               "refine":
     1897               (refine, [_args_kwargs('gpxfile', help='the project file to refine'),
     1898                         _args_kwargs('refinements',
     1899                                      help='json file of refinements to apply. if not present'
     1900                                           ' refines file as-is',
     1901                                      default=None,
     1902                                      nargs='?')]),
     1903
     1904               "seqrefine": (seqrefine, []),
     1905               "export": (export, [_args_kwargs('gpxfile',
     1906                                                help='the project file from which to export'),
     1907                                   _args_kwargs('phase', help='identifier of phase to export'),
     1908                                   _args_kwargs('exportfile', help='the .cif file to export to')]),
     1909               "browse": (IPyBrowse, [_args_kwargs('files', nargs='+',
     1910                                                   help='list of files to browse')])}
    19141911
    19151912
     
    19341931        :func:`browse`
    19351932    '''
    1936     import argparse
    19371933    parser = argparse.ArgumentParser()
    1938     parser.add_argument('subcommand', choices=sorted(subcommands.keys()),
    1939                         help='The subcommand to be executed')
    1940 
    1941     result = parser.parse_args(sys.argv[1:2])
    1942     sub = result.subcommand
    1943     subcommands[sub](*sys.argv[2:])
     1934    subs = parser.add_subparsers()
     1935
     1936    # Create all of the specified subparsers
     1937    for name, (func, args) in subcommands.items():
     1938        new_parser = subs.add_parser(name)
     1939        for listargs, kwds in args:
     1940            new_parser.add_argument(*listargs, **kwds)
     1941        new_parser.set_defaults(func=func)
     1942
     1943    # Parse and trigger subcommand
     1944    result = parser.parse_args()
     1945    result.func(result)
    19441946
    19451947    # argv = sys.argv
     
    19581960    # sys.exit(0)
    19591961
    1960     # arg = sys.argv
    1961     # print(arg)
    1962     # if len(arg) > 1:
    1963     #     GPXfile = arg[1]
    1964     #     if not ospath.exists(GPXfile):
    1965     #         print(u'ERROR - '+GPXfile+u" doesn't exist!")
    1966     #         exit()
    1967     #     Project,nameList = LoadDictFromProjFile(GPXfile)
    1968     #     SaveDictToProjFile(Project,nameList,'testout.gpx')
    1969     # else:
    1970     #     print('ERROR - missing filename')
    1971     #     exit()
    1972     # print("Done")
    1973 
    19741962if __name__ == '__main__':
    19751963    main()
    1976 
    1977     # from gpx_manipulatons.py
    1978     # try:
    1979     #     filename, authorname = sys.argv[1:3]
    1980     #     proj, names = make_empty_project(authorname, filename)
    1981     #     SaveDictToProjFile(proj, names, os.path.abspath(filename))
    1982     # except ValueError:
    1983     #     print("Usage: {} <filename> <author>".format(sys.argv[0]))
    1984     #     sys.exit(-1)
    19851964
    19861965
Note: See TracChangeset for help on using the changeset viewer.