Esempio 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()
Esempio n. 2
0
def main():
    from PseudoNetCDF.pncparse import pncparse, getparser
    from PseudoNetCDF.plotutil.pnc2d import make2ds
    parser = getparser(has_ofile=True, plot_options=True, interactive=True)
    parser.add_argument('--swapaxes',
                        action='store_true',
                        help='Swap x-y axes')
    ifiles, args = pncparse(has_ofile=True,
                            plot_options=True,
                            interactive=True,
                            parser=parser)
    make2ds(args)
Esempio n. 3
0
def main():
    from PseudoNetCDF.pncparse import getparser, pncparse
    from PseudoNetCDF.plotutil.pncts import plotts
    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)
Esempio n. 4
0
def main():
    from PseudoNetCDF.pncparse import getparser, pncparse
    from PseudoNetCDF.plotutil.pncmap import makemaps
    parser = getparser(has_ofile=True,
                       map_options=True,
                       plot_options=True,
                       interactive=True)
    ifiles, args = pncparse(has_ofile=True,
                            plot_options=True,
                            interactive=True,
                            parser=parser)
    args.ifiles = ifiles
    makemaps(args)
Esempio n. 5
0
def main():
    from PseudoNetCDF.pncparse import pncparse, getparser
    from PseudoNetCDF.plotutil.pnc2d import make2ds
    parser = getparser(has_ofile=True, plot_options=True, interactive=True)
    #parser.add_argument('--no-squeeze', dest = 'squeeze', default = True, action = 'store_false', help = 'Squeeze automatically removes singleton dimensions; disabling requires user to remove singleton dimensions with --remove-singleton option')
    parser.add_argument('--swapaxes',
                        action='store_true',
                        help='Swap x-y axes')
    ifiles, args = pncparse(has_ofile=True,
                            plot_options=True,
                            interactive=True,
                            parser=parser)
    make2ds(args)
Esempio n. 6
0
def read_bpch(filename, varname_list, latlon_flag=True,
        verbose=True, squeeze=False):
    """ read data from GEOS-Chem bpch file

    Paratemters
    -----------
    filename : str
        bpch file
    varname_list : list
        A list of variable names.
    latlon_flag : bool
        Whether latitude and longitude is returned
    squeeze : logical
        Remove single-dimensional entries from the shape
        of an array.

    Returns
    -------

    """

    out_dict = {}



    # read file
    if verbose:
        print('reading ' + filename)
    infiles, argcs = pncparse(args = [filename, '-f bpch'])
    infile = infiles[0]

    # get variables
    for varname in varname_list:
        out_dict[varname] = np.array(infile.variables[varname])

    if latlon_flag:
        out_dict['latitude']  = np.array(infile.variables['latitude'])
        out_dict['longitude'] = np.array(infile.variables['longitude'])
        lat_e = np.array(infile.variables['latitude_bounds'])
        lon_e = np.array(infile.variables['longitude_bounds'])
        out_dict['latitude_e']  = np.append(lat_e[:,0], lat_e[-1,1])
        out_dict['longitude_e'] = np.append(lon_e[:,0], lon_e[-1,1])

    # Remove single-dimensional entries from the shape
    # of an array
    if squeeze:
        for varn in out_dict:
            out_dict[varn] = np.squeeze(out_dict[varn])

    return out_dict
Esempio n. 7
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()
Esempio n. 8
0
                        help = "Use quartiles to set range (xmin, xmax); defaults 0,100.")

    parser.add_argument("--out-unit", dest = "outunit", type = str, default = 'ppb',
                        help = "Defaults ppb.")

    parser.add_argument("--tes-paths", dest = "tespaths", type = str, default = [], action = "append",
                        help = "Plot tes on top of boundary from paths; defaults to []")

    parser.add_argument("--omi-paths", dest = "omipaths", type = str, default = [], action = "append",
                        help = "Plot omi on top of boundary from paths; defaults to []")

    parser.add_argument("--itertime", dest = "itertime", default = False, action = 'store_true',
                        help = "Iterate over times and plot each one.")
                        
    parser.add_argument("--edges", dest = "edges", default = False, action = "store_true",
                        help = "Plot S,E,N,W edges instead of a single plot.")
    parser.epilog = """
Example:
    $ pncvertprofile.py outputs/ts20120301.bpch.BCON.nc test_profile -v O3  --edges --minmaxq .5,99.5 --tes-paths=~/Data/test/*
"""
    
    ifiles, args = pncparse(has_ofile = True, parser = parser)
    if args.variables is None:
        raise ValueError('User must specify variable(s) to plot:\n%s' % '\n\t'.join(ifiles[0].variables.keys()))
    if len(args.tespaths) > 0:
        args.tespaths = reduce(list.__add__, [tp.split(',') for tp in args.tespaths])
        
    if len(args.omipaths) > 0:
        args.omipaths = reduce(list.__add__, [op.split(',') for op in args.omipaths])
    plot(ifiles, args)
Esempio n. 9
0
def read_nd49_resample(file_list, varname_list):
    """ read data from GEOS-Chem ND49 file from resampling 
    according to satellite overpass time.

    Paratemters
    -----------
    file_list: list
        A list of ND49 filenames. It usually includes files
        of previous one day, current day, and next one day. 
    varname_list : list
        A list of variable names.

    Returns
    -------

    """

    out_dict = {}

    # 4-D variables
    for varname in varname_list:
        out_dict[varname] = []

    # other variables
    out_dict['time'] = []

    # read data
    latlon_flag = True
    for i in range(len(file_list)):

        filename = file_list[i]

        # Determine if file exists
        if not os.path.exists(filename):
            print(' - read_nd49_resample: WARNING! ' + filename + \
                    ' does not exist.')
            continue

        # read file
        print('reading ' + filename)
        infiles, argcs = pncparse(args = [filename, '-f bpch'])
        infile = infiles[0]

        # get variables
        for varname in varname_list:
            out_dict[varname].append(np.array(infile.variables[varname]))

        # other variables
        out_dict['time'].append(np.array(infile.variables['time']))

        if latlon_flag:
            out_dict['latitude']  = np.array(infile.variables['latitude'])
            out_dict['longitude'] = np.array(infile.variables['longitude'])
            lat_e = np.array(infile.variables['latitude_bounds'])
            lon_e = np.array(infile.variables['longitude_bounds'])
            out_dict['latitude_e']  = np.append(lat_e[:,0], lat_e[-1,1])
            out_dict['longitude_e'] = np.append(lon_e[:,0], lon_e[-1,1])

    # merge variables
    for varname in varname_list:

        # concatenate arrays
        out_dict[varname] = np.concatenate(out_dict[varname], axis=0)

        # move axis
        out_dict[varname] = np.moveaxis(out_dict[varname], 1, 3)

    # tau
    # 'time': hours since 1985-01-01T00:00:00
    # 'TAI93': seconds since 1993-01-01T00:00:00
    # 'Time' : datetime instance
    day_hours = 24.0
    hour_seconds = 3600.0
    day_seconds = day_hours * hour_seconds
    out_dict['time'] = np.hstack(out_dict['time'])
    diff_93_85 = datetime.datetime.strptime('1993-01-01', '%Y-%m-%d') \
            - datetime.datetime.strptime('1985-01-01', '%Y-%m-%d')
    diff_93_85_hours = diff_93_85.days * day_hours
    TAI93 = (out_dict['time'] - diff_93_85_hours) * hour_seconds
    out_dict['TAI93'] = TAI93
    out_dict['Time'] = []
    for i in range(len(out_dict['TAI93'])):
        out_dict['Time'].append( \
                datetime.datetime.strptime('1993-01-01', '%Y-%m-%d') \
                + datetime.timedelta(seconds=out_dict['TAI93'][i]) )

    return out_dict
Esempio n. 10
0
                        help='Direction bin widths in degrees.')
    parser.add_argument('--max-pct',
                        dest='maxpct',
                        type=float,
                        default=50.,
                        help='Maximum percent on plot')
    parser.add_argument(
        '--fromnorth',
        dest='fromnorth',
        action='store_true',
        default=False,
        help='Bins should start from north (i.e., not bound north)')
    parser.add_argument('--bounds',
                        dest='bounds',
                        type=lambda x: np.array(eval(x)),
                        default=np.array([1, 2, 3, 5, 10, np.inf]),
                        help='Boundaries for wind speed')
    parser.epilog = """
Example:
    $ pncwindrose.py -s time,600,None --max-pct=35 --wind-dir wd --wind-speed ws  --mask-var="ws[:].mask.all(0)[None,:].repeat(ws.shape[0], 0)" --bounds="[0.5,1,2,3.5,4.5,6.5,np.inf]"  --title obs  Bogota_2012_s12345.nc df.nc oct_obs

Description:
    Create windrose for timestep 600 and on where wind-direction is name wd, and windspeed is named ws. Masking is applied from df.nc file where all times for ws are masked (useful for ignoring monitors). Values less than 0.5 will be masked.
"""
    ifiles, args = pncparse(has_ofile=True,
                            plot_options=False,
                            interactive=False,
                            args=None,
                            parser=parser)
    out = pncwindrose(ifiles, args)
Esempio n. 11
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)
Esempio n. 12
0
                extend = 'neither'
            cbar = fig.colorbar(patches, orientation = orientation, cax = cax, extend = extend, format = formatter)
            del cbar.ax.texts[:]
            cbar.set_label(varkey + ' (' + varunit + '; min=%.3g; max=%.3g)' % (var[:].min(), var[:].max()))
 #           if orientation == 'vertical':
 #               cbar.ax.text(.5, 1.05, '%.3g' % var[:].max(), horizontalalignment = 'center', verticalalignment = 'bottom')
#                cbar.ax.text(.5, -.06, '%.3g ' % var[:].min(), horizontalalignment = 'center', verticalalignment = 'top')
#            else:
#                cbar.ax.text(1.05, .5, ' %.3g' % var[:].max(), verticalalignment = 'center', horizontalalignment = 'left')
#                cbar.ax.text(-.06, .5, '%.3g ' % var[:].min(), verticalalignment = 'center', horizontalalignment = 'right')
            #cbar.update_ticks()
            fmt = 'png'
            outpath = options.outpath
            if len(ifiles) > 1:
                
                outpath += ('_%%0%dd' % len(str(len(ifiles)))) % fi
            figpath = os.path.join(outpath + varkey + '.' + fmt)
            if options.interactive:
                csl = PNCConsole(locals = globals())
                csl.interact()
            
            fig.savefig(figpath)
            print('Saved fig', figpath)
        
if __name__ == '__main__':
    from PseudoNetCDF.pncparse import pncparse, getparser
    parser = getparser(has_ofile = True, plot_options = True, interactive = True)
    parser.add_argument('--swapaxes', action = 'store_true', help = 'Swap x-y axes')
    ifiles, options = pncparse(has_ofile = True, plot_options = True, interactive = True, parser = parser)
    make2d(ifiles, options)
Esempio n. 13
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()
Esempio n. 14
0
    rectangles = [plt.Rectangle((0, 0), 1, 1, color = ubc) for ubc in ubcs]
    fig.legend(rectangles, labels, ncol = 3, 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)
    fig.savefig(args.outpath)
    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', type = float, default = 45., help = 'Direction bin widths in degrees.')
    parser.add_argument('--max-pct', dest = 'maxpct', type = float, default = 50., help = 'Maximum percent on plot')
    parser.add_argument('--fromnorth', dest = 'fromnorth', action = 'store_true', default = False, help = 'Bins should start from north (i.e., not bound north)')
    parser.add_argument('--bounds', dest = 'bounds', type = lambda x: np.array(eval(x)), default = np.array([1, 2, 3, 5, 10, np.inf]), help = 'Boundaries for wind speed')
    parser.epilog = """
Example:
    $ pncwindrose.py -s time,600,None --max-pct=35 --wind-dir wd --wind-speed ws  --mask-var="ws[:].mask.all(0)[None,:].repeat(ws.shape[0], 0)" --bounds="[0.5,1,2,3.5,4.5,6.5,np.inf]"  --title obs  Bogota_2012_s12345.nc df.nc oct_obs

Description:
    Create windrose for timestep 600 and on where wind-direction is name wd, and windspeed is named ws. Masking is applied from df.nc file where all times for ws are masked (useful for ignoring monitors). Values less than 0.5 will be masked.
"""
    ifiles, args = pncparse(has_ofile = True, plot_options = False, interactive = False, args = None, parser = parser)
    out = pncwindrose(ifiles, args)
    
Esempio n. 15
0
                csl = PNCConsole(locals=globals())
                csl.interact()

            pl.savefig(figpath)
            print('Saved fig', figpath)


if __name__ == '__main__':
    parser = getparser(has_ofile=True, plot_options=True, interactive=True)
    parser.add_argument(
        "--iter",
        dest="iter",
        action='append',
        default=[],
        help=
        "Create plots for each element of specified dimension (e.g., --iter=time)."
    )
    ifiles, options = pncparse(has_ofile=True,
                               plot_options=True,
                               interactive=True,
                               parser=parser)
    prepmap(ifiles, options)
    ifile, = ifiles
    if options.iter != []:
        ifiles = []
        for dimk in options.iter:
            ifiles += [
                slice_dim(getvarpnc(ifile, None), '%s,%d' % (dimk, i))
                for i in range(len(ifile.dimensions[dimk]))
            ]
    makemap(ifiles, options)