Exemplo n.º 1
0
def main():
    from warnings import warn
    from .pncparse import pncparse
    from PseudoNetCDF.core._functions import pncfunc, pncbfunc
    from PseudoNetCDF.pncparse import getparser, pncparse

    parser = getparser(has_ofile = False, plot_options = False, interactive = True)
    parser.add_argument('--funcs', default = __all__, type = lambda x: x.split(','), help='Functions to evaluate split by , (default: %s)' % ','.join(__all__))

    import numpy as np
    np.seterr(divide = 'ignore', invalid = 'ignore')
    ifiles, options = pncparse(has_ofile = False, interactive = True, parser = parser)
    if options.variables is None:
        options.variables = set(ifiles[0].variables.keys()).difference(options.coordkeys)
    console = createconsole(ifiles, options)
    warn("Assumes input order is obs model")
    ifile1, ifile2 = ifiles
    for k in options.funcs:
        console.locals[k] = func = eval(k)
        console.locals[k+'_f'] = ofile = pncbfunc(func, ifile1, ifile2)
        times = ifile1.variables['time']
        tstart = times[:].min()
        tstop = times[:].max()
        dt = tstop - tstart
        for vk in options.variables:
            if vk in ('time', 'TFLAG'): continue
            print('%.2f,%.2f,%.2f,%s,%s,%s,%f' % (tstart, tstop, dt, vk, func.__doc__.strip(), k, ofile.variables[vk].ravel()[0]))
    np.seterr(divide = 'warn', invalid = 'warn')
    if options.interactive:
        console.interact()
Exemplo n.º 2
0
                pl.sca(ax)
        
        llabels = [l[0].get_label() for l in llines]
        pl.legend(llines, llabels, bbox_to_anchor = (.1, 1), loc = 'upper left', bbox_transform = fig.transFigure, ncol = 6)
        if edges:
            fig.text(0.95, 0.975, title, horizontalalignment = 'right', verticalalignment = "top", fontsize = 16)
        else:
            fig.text(0.95, 0.025, title, horizontalalignment = 'right', verticalalignment = "bottom", fontsize = 16)
        fig.savefig('%s_%s.%s' % (args.outpath, var_name, args.figformat))
        pl.close(fig)
    return fig

if __name__ == '__main__':
    from PseudoNetCDF.pncparse import getparser, pncparse
    
    parser = getparser(has_ofile = True, plot_options = True, interactive = False)

    parser.add_argument("--sigma", dest = "sigma", action = "store_true", default = False,
                        help = "Plot on sigma coordinate instead of pressure")

    parser.add_argument("--scale", dest = "scale", type = str, default = 'log',
                        help = "Defaults to log, but linear and semilog are also options.")

    parser.add_argument("--minmax", dest = "minmax", type = str, default = "None,None",
                        help = "Use values to set range (xmin, xmax); defaults None,None.")

    parser.add_argument("--mask-zeros", dest = "maskzeros", action = "store_true", default = False,
                        help = "Defaults False.")

    parser.add_argument("--minmaxq", dest = "minmaxq", type = str, default = '0,100',
                        help = "Use quartiles to set range (xmin, xmax); defaults 0,100.")
Exemplo n.º 3
0
               bbox_to_anchor=(.5, 0.025),
               loc='lower center')
    ticks = np.linspace(0, args.maxpct, 6)[1:]
    labels = ['%s%%' % i for i in ticks]
    plt.yticks(ticks, labels)
    ax.set_rmax(args.maxpct)
    ax.set_clip_on(False)
    figpath = args.outpath
    fig.savefig(figpath)
    if args.verbose > 0: print('Saved fig', figpath)
    plt.close(fig)


if __name__ == '__main__':
    from PseudoNetCDF.pncparse import getparser, pncparse
    parser = getparser(has_ofile=True, plot_options=False, interactive=False)
    parser.add_argument('--wind-speed',
                        dest='windspeed',
                        default='WS',
                        help='Wind speed variable')
    parser.add_argument('--mask-var',
                        dest='maskvar',
                        default='WS',
                        help='Variable from file two for masking')
    parser.add_argument('--wind-dir',
                        dest='winddir',
                        default='WD',
                        help='Wind direction variable')
    parser.add_argument('--title', default=None, help='Title for wind rose')
    parser.add_argument('--binwidth',
                        dest='binwidth',
Exemplo n.º 4
0
        po = np.arange(24) + 0.1 + varwidth / 2
        for vi, (time, var) in enumerate(zip(times, vars)):
            vals = var[:]
            if args.squeeze:
                vals = vals.squeeze()
            vardesc = getattr(var, 'description', None)
            varb = ax.plot(time, vals[:], label=vardesc)
        # plt.setp(ax.xaxis.get_ticklabels(),rotation = 45)
        plt.legend()
        figpath = args.outpath + target + '.' + args.figformat
        for pc in args.plotcommands:
            exec(pc, globals(), locals())
        fig.savefig(figpath)
        if args.verbose > 0:
            print('Saved fig', figpath)
        print(figpath)


if __name__ == '__main__':
    from PseudoNetCDF.pncparse import getparser, pncparse
    parser = getparser(plot_options=True, has_ofile=True)
    parser.epilog += """
    -----
box.py inobs inmod target [target ...]
inobs - path to obs
inmod - path to mod
target - variable name
"""
    ifiles, args = pncparse(plot_options=True, has_ofile=True, parser=parser)
    plotts(args)
Exemplo n.º 5
0
def parse_and_run():
    import os
    from argparse import ArgumentParser
    from warnings import warn
    from permm import mechanism_dict, Mechanism
    from permm.analyses import __all__ as all_analyses
    all_mechs = '|'.join(list(mechanism_dict.keys()))
    all_analyses = '|'.join(all_analyses)
    from PseudoNetCDF.pncparse import getparser, pncparse
    parser = ArgumentParser(
        description=
        "permm (Python Environment for Reaction Mechanism Mathematics)")
    parser.add_argument("--gui", dest="graphical", \
                        action="store_true", default=False, \
                        help="open a graphical user interactive environment")

    parser.add_argument("--mechanism", dest="mechanism", \
                      default="cb05_camx", help="Chemical mechanisms (e.g., a custom path|%s)" % all_mechs)

    parser.add_argument("--analysis", dest="analysis", \
                      default=None, help="Stock analysis to perform (i.e., %s)" % all_analyses)
    parser.add_argument("--scripts",
                        dest="scripts",
                        action='append',
                        default=[],
                        help="Provide scripts to run")
    parser.add_argument("-i",
                        "--interactive",
                        dest="interactive",
                        action='store_true',
                        default=False,
                        help="Run interactively")
    parser.add_argument(
        "--input-role",
        dest="inrole",
        action='append',
        default=[],
        help=
        "Is this a 'merge' file or a 'concentration' file or any other word indicating type?"
    )

    parser.add_argument("pseudonetcdf", nargs='*')
    options = parser.parse_args()
    if len(options.pseudonetcdf) > 0:
        pncparser = getparser(has_ofile=False, interactive=True)
        ifiles, pncoptions = pncparse(has_ofile=False,
                                      interactive=True,
                                      parser=pncparser,
                                      args=args.pseudonetcdf)
    else:
        ifiles = []
        pncoptions = {}

    from permm import netcdf
    from permm.Shell import load_environ
    try:
        mech = mechanism_dict[options.mechanism]
    except KeyError:
        mech = Mechanism(options.mechanism)

    start_script = 0
    options.inrole += ['merge'] * (len(ifiles) - len(options.inrole))
    for r, ifile in zip(options.inrole, ifiles):
        if r == 'merge':
            mech.set_mrg(ifile)
        else:
            vardict = dict([(k, v) for k, v in list(ifile.variables.items())
                            if k in mech.species_dict])
            mech.set_process(r, vardict)

    from permm.Shell import PERMConsole
    console = PERMConsole()
    load_environ(mech, console.locals)

    for script in options.scripts:
        if os.path.isfile(script):
            exec(compile(open(script).read(), script, 'exec'), globals(),
                 console.locals)
        else:
            exec(script, globals(), console.locals)

    if options.graphical:
        console.runsource("from permm.GUI import StartGUI")
        console.runsource("StartGUI(mech)")

    if options.analysis is not None:
        if len(args) < 1:
            parser.error(
                msg=
                "Requires a pyPA mrg file as an argument for analysis output.  You can enter an interactive environment (-i), but will not have access to \"netted\" reactions"
            )

        if options.analysis == "net_balance":
            console.runsource(
                "from permm.analyses.net_balance import net_balance")
            console.runsource("net_balance('%s', '%s', '%s')" %
                              (options.mechanism, args[0], options.output))
        elif options.analysis == "history":
            console.runsource("from permm.analyses.history import matrix")
            console.runsource(
                "history = matrix(mech, [C2O3], [HC+Radical-OH-HO2-O1D], [])")
            console.runsource("history.run()")
        else:
            raise "Unkown analysis"

    if options.interactive:
        load_environ(mech, console.locals)
        console.interact()