Exemplo n.º 1
0
            output_name = arg
        if opt in ("-v", "--variables"):
            variables = arg.split(',')
        if opt in ("-e", "--exclude"):
            exclude = arg.split(',')
    if len(args) != 1:
        print "ERROR! Please specify one input file. Exiting..."
        exit(-1)
    input_name = args[0]
    if output_name == "":
        output_name = splitext(input_name)[0] + '.mat'
except GetoptError:
    print_options_and_exit(-1)

try:
    input_file = NC(input_name, "r")
except Exception, message:
    print "ERROR: ", message
    print "Can't open %s. Exiting..." % (input_name)
    exit(-1)

print "Reading data from %s..." % (input_name)

# if no variables were specified, assume that we need to dump them all
if variables == []:
    variables = input_file.variables.keys()

print "Loading variables...",
mdict = {}
missing = []
for each in variables:
Exemplo n.º 2
0
    'select minimum: if -c is used then above this value (of -s var) the points will not be plotted'
)

parser.add_argument('-wmin',
                    type=float,
                    default=None,
                    help='lower limit on W axis')
parser.add_argument('-wmax',
                    type=float,
                    default=None,
                    help='upper limit on W axis')

args = parser.parse_args()

try:
    nc = NC(args.filename, 'r')
except:
    print "ERROR: can't read from file ..."
    sys.exit(1)

print "  reading 'bwprel' field from file %s ..." % (args.filename)
try:
    bwprel = nc.variables["bwprel"]
except:
    print "ERROR: variable 'bwprel' not found ..."
    sys.exit(2)

print "  reading 'bwat' field from file %s ..." % (args.filename)
try:
    bwat = nc.variables["bwat"]
except:
Exemplo n.º 3
0
                        default="age")

    options = parser.parse_args()
    fill_value = -2e9
    variables = options.variables.split(",")
    n_levels = options.n_levels
    age_iso = np.fromstring(options.age_iso, dtype=float, sep=",")
    n_age_iso = len(age_iso)

    print("-----------------------------------------------------------------")
    print(("Running script %s ..." % __file__.split("/")[-1]))
    print("-----------------------------------------------------------------")
    print(("Opening NetCDF file %s ..." % options.INPUTFILE[0]))
    try:
        # open netCDF file in 'read' mode
        nc_in = NC(options.INPUTFILE[0], "r")
    except:
        print((
            "ERROR:  file '%s' not found or not NetCDF format ... ending ..." %
            options.INPUTFILE[0]))
        import sys

        sys.exit()

    # get file format
    format = nc_in.file_format
    # get the dimensions
    xdim, ydim, zdim, tdim = ppt.get_dims(nc_in)
    # read projection information
    projection = ppt.get_projection_from_file(nc_in)
    # new sigma coordinate with n_levels
Exemplo n.º 4
0
                    nargs="+",
                    dest="tests_to_plot",
                    default=None,
                    help="Test results to plot (space-delimited list)")
parser.add_argument("--save_figures",
                    dest="save_figures",
                    action="store_true",
                    help="Save figures to .png files")
parser.add_argument("--file_format",
                    dest="file_format",
                    default="png",
                    help="File format for --save_figures (png, pdf, jpg, ...)")

options = parser.parse_args()

input_file = NC(options.filename, 'r')
available_tests = unique(array(list(map(chr,
                                        input_file.variables['test'][:]))))
tests_to_plot = options.tests_to_plot

if len(available_tests) == 1:
    if tests_to_plot == None:
        tests_to_plot = available_tests
else:
    if (tests_to_plot == None):
        print("""Please choose tests to plot using the -t option.
(Input file %s has reports for tests %s available.)""" %
              (input, str(available_tests)))
        sys.exit(0)

if (tests_to_plot[0] == "all"):
Exemplo n.º 5
0
options = parser.parse_args()
args = options.FILE
start = 0
end = 1000
step = 1. / 12.
amplitude = options.amplitude
t_max = options.t_max
T_max = options.T_max
bnds_interval_since_refdate = np.linspace(start, end, end * 12 + 1)
time_interval_since_refdate = (bnds_interval_since_refdate[0:-1] +
                               np.diff(bnds_interval_since_refdate) / 2)

infile = args[0]

nc = NC(infile, 'w')


def def_var(nc, name, units):
    var = nc.createVariable(name, 'f', dimensions=('time'))
    var.units = units
    return var


# create a new dimension for bounds only if it does not yet exist
time_dim = "time"
if time_dim not in list(nc.dimensions.keys()):
    nc.createDimension(time_dim)

# create a new dimension for bounds only if it does not yet exist
bnds_dim = "nb2"
Exemplo n.º 6
0
def plot_basin_mass():

    fig = plt.figure()
    offset = transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans)
    ax = fig.add_subplot(111)

    mass_var_vals_positive_cum = 0
    mass_var_vals_negative_cum = 0
    for k, ifile in enumerate(ifiles):
        basin = basin_list[k]
        print('reading {}'.format(ifile))
        nc = NC(ifile, 'r')
        t = nc.variables["time"][:]

        date = np.arange(start_year + step,
                         start_year + (len(t[:]) + 1) * step, step)

        idx = np.where(np.array(date) == time_bounds[-1])[0][0]
        mvar = 'ice_mass'
        mass_var_vals = -np.squeeze(nc.variables[mvar][:] -
                                    nc.variables[mvar][0]) * gt2mSLE
        iunits = nc.variables[mvar].units
        mass_var_vals = unit_converter(mass_var_vals, iunits, mass_ounits)
        if mass_var_vals[idx] > 0:
            ax.fill_between(date[:],
                            mass_var_vals_positive_cum,
                            mass_var_vals_positive_cum + mass_var_vals[:],
                            color=basin_col_dict[basin],
                            linewidth=0,
                            label=basin)
        else:
            print mass_var_vals[idx]
            ax.fill_between(date[:],
                            mass_var_vals_negative_cum,
                            mass_var_vals_negative_cum + mass_var_vals[:],
                            color=basin_col_dict[basin],
                            linewidth=0,
                            label=basin)
            plt.rcParams['hatch.color'] = basin_col_dict[basin]
            plt.rcParams['hatch.linewidth'] = 0.1
            ax.fill_between(date[:],
                            mass_var_vals_negative_cum,
                            mass_var_vals_negative_cum + mass_var_vals[:],
                            facecolor="none",
                            hatch="XXXXX",
                            edgecolor="k",
                            linewidth=0.0)

        if mass_var_vals[idx] > 0:
            ax.plot(date[:],
                    mass_var_vals_positive_cum + mass_var_vals[:],
                    color='k',
                    linewidth=0.1)
        else:
            ax.plot(date[:],
                    mass_var_vals_negative_cum + mass_var_vals[:],
                    color='k',
                    linewidth=0.1)

        offset = 0
        if mass_var_vals[idx] > 0:
            try:
                x_sle, y_sle = date[idx] + offset, mass_var_vals_positive_cum[
                    idx]
            except:  # first iteratio
                x_sle, y_sle = date[idx] + offset, mass_var_vals_positive_cum
        else:
            try:
                x_sle, y_sle = date[idx] + offset, mass_var_vals_negative_cum[
                    idx] + mass_var_vals[idx]
            except:  # first iteration
                x_sle, y_sle = date[
                    idx] + offset, mass_var_vals_negative_cum + mass_var_vals[
                        idx]
        nc.close()
        if mass_var_vals[idx] > 0:
            mass_var_vals_positive_cum += mass_var_vals
        else:
            mass_var_vals_negative_cum += mass_var_vals

    ax.hlines(0, time_bounds[0], time_bounds[-1], lw=0.25)

    legend = ax.legend(loc="upper right",
                       edgecolor='0',
                       bbox_to_anchor=(0, 0, 1.15, 1),
                       bbox_transform=plt.gcf().transFigure)
    legend.get_frame().set_linewidth(0.2)

    ax.set_xlabel('Year (CE)')
    ax.set_ylabel('$\Delta$(GMSL) (m)')

    if time_bounds:
        ax.set_xlim(time_bounds[0], time_bounds[1])

    if bounds:
        ax.set_ylim(bounds[0], bounds[-1])

    if rotate_xticks:
        ticklabels = ax.get_xticklabels()
        for tick in ticklabels:
            tick.set_rotation(30)
    else:
        ticklabels = ax.get_xticklabels()
        for tick in ticklabels:
            tick.set_rotation(0)

    if title is not None:
        plt.title(title)

    for out_format in out_formats:
        out_file = outfile + '_' + mvar + '.' + out_format
        print "  - writing image %s ..." % out_file
        fig.savefig(out_file, bbox_inches='tight', dpi=out_res)
Exemplo n.º 7
0
                    help="Maximum backpressure fraction",
                    default=0.3)
parser.add_argument("-n",
                    dest="n",
                    type=float,
                    help="power-law exponent",
                    default=2)

options = parser.parse_args()
args = options.FILE
n = options.n
backpressure_max = options.backpressure_max

infile = args[0]

nc = NC(infile, "a")

temp = nc.variables["delta_T"][:]


def def_var(nc, name, units):
    var = nc.createVariable(name, "f", dimensions=("time"))
    var.units = units
    return var


T_max = 0
T_min = -10
psi_min = 0.01
psi_max = 1.0
Exemplo n.º 8
0
xExtent = 500  # in km
standard_gravity = 9.81  # g
B0 = 1.9e8  # ice hardness
rho_ice = 910.0  # in kg/m^3
rho_ocean = 1028.0  # in kg/m^3

# create config overwrite file as used in T. Albrecht, M. A. Martin, R. Winkelmann, M. Haseloff, A. Levermann; Parameterization for subgrid-scale motion of ice-shelf calving fronts; (2011), The Cryosphere 5, 35-44, DOI:10.5194/tc-5-35-2011.
'''Generates a config file containing flags and parameters
for a particular experiment and step.

This takes care of flags and parameters that *cannot* be set using
command-line options. (We try to use command-line options whenever we can.)
'''

filename = "flowline_config.nc"
nc = NC(filename, 'w', format="NETCDF3_CLASSIC")
var = nc.createVariable("pism_overrides", 'i')
attrs = {
    "ocean.always_grounded": "no",
    "geometry.update.use_basal_melt_rate": "no",
    "stress_balance.ssa.compute_surface_gradient_inward": "no",
    "flow_law.isothermal_Glen.ice_softness": (B0)**-3,
    "constants.ice.density": rho_ice,
    "constants.sea_water.density": rho_ocean,
    "bootstrapping.defaults.geothermal_flux": 0.0,
    "stress_balance.ssa.Glen_exponent": 3.0,
    "constants.standard_gravity": standard_gravity,
    "ocean.sub_shelf_heat_flux_into_ice": 0.0,
    "stress_balance.sia.bed_smoother.range": 0.0,
}
Exemplo n.º 9
0
    exit(2)

# read specmap.017
print "reading data from ", SPEC_FILE
try:
    years_sea, d18Osea = loadtxt(SPEC_FILE, skiprows=2, unpack=True)
except IOError:
    print 'ERROR: File: ' + SPEC_FILE + ' could not be found.'
    exit(2)
years_sea *= 1000.0
# compute sea level from \delta 18^O; see C. Ritz, 1997. "EISMINT
#   intercomparison experiment comparison of existing Greenland models"
dSea = -34.83 * (d18Osea + 1.93)

# open the nc for delta Sea Level file to write to
ncfile = NC(DSL_FILE, 'w', format='NETCDF3_CLASSIC')

# set global attributes
historysep = ' '
historystr = asctime() + ': ' + historysep.join(argv) + '\n'
setattr(ncfile, 'history', historystr)

# define time dimension, then time variable
Stdim = ncfile.createDimension('t', None)
Stvar = ncfile.createVariable('t', 'f4', ('t', ))
setattr(Stvar, 'units', 'years since 1-1-1')

# define climate data variables and attributes
d18Oseavar = ncfile.createVariable('delta_18_O', 'f4', ('t', ))
setattr(d18Oseavar, 'units', 'normalized O-18')  # see specmap_readme.txt
setattr(d18Oseavar, 'long_name',
Exemplo n.º 10
0
        Bcount = Bcount + 1
    else:  # accumulation (m/a -> m/s)
        acc[Acccount / int(dim[1]), Acccount % int(dim[1])] = float(line)
        Acccount = Acccount + 1
    x = x + 1

# done reading from data file
input.close()
print "Total Values Read: " + str(x)

# replace zero (used to represent missing values in the input file) with a
# value outside the valid range
putmask(B, B == 0, topg_fill_value)

# ready to write NetCDF file
ncfile = NC(WRIT_FILE, 'w', format='NETCDF3_CLASSIC')

# set global attributes
ncfile.Conventions = 'CF-1.4'
historysep = ' '
historystr = time.asctime() + ': ' + historysep.join(sys.argv) + '\n'
ncfile.history = historystr

# define the dimensions
xdim = ncfile.createDimension('x', int(dim[1]))
ydim = ncfile.createDimension('y', int(dim[0]))

# define the variables
polarVar = ncfile.createVariable('mapping', 'i4')
xvar = ncfile.createVariable('x', 'f8', dimensions=('x', ))
yvar = ncfile.createVariable('y', 'f8', dimensions=('y', ))
Exemplo n.º 11
0
# set up the option parser
parser = ArgumentParser()
parser.description = "Pasting 3d fields from subset domain into large domain."
parser.add_argument("FILE",
                    nargs=2,
                    help="Small and large domain files with 3d fields",
                    default=None)

options = parser.parse_args()

file_sm = options.FILE[0]
file_lg = options.FILE[1]

print(("Pasting regrid fields from {} to {}".format(file_sm, file_lg)))

nc_sm = NC(file_sm, "r")
nc_lg = NC(file_lg, "a")

x_sm = nc_sm.variables["x"][:]
y_sm = nc_sm.variables["y"][:]

x_lg = nc_lg.variables["x"][:]
y_lg = nc_lg.variables["y"][:]

# latitude lower and upper index
y_li = np.argmin(np.abs(y_lg - y_sm[0]))
y_ui = np.argmin(np.abs(y_lg - y_sm[-1]))

# longitude lower and upper index
x_li = np.argmin(np.abs(x_lg - x_sm[0]))
x_ui = np.argmin(np.abs(x_lg - x_sm[-1]))
Exemplo n.º 12
0
time = zeros([datalength - datastart])
slev = zeros([datalength - datastart])

for linecount, line in enumerate(f.readlines()):
    for entrycount, entry in enumerate(line.split("\t")):
        if linecount >= datastart and linecount < datalength:
            if entrycount == 0:
                time[linecount - datastart] = float(entry) * (-1.0e3)
            elif entrycount == 1:
                slev[linecount - datastart] = float(entry)
f.close()
#
#########################################################################

timeseries = 'timeseries_spratt16_sl.nc'
ncf = NC(timeseries, 'w', format='NETCDF3_CLASSIC')

# define time dimension, then time variable, then attributes
timedim = ncf.createDimension('time', None)
yearvar = ncf.createVariable('time', 'f4', dimensions=('time', ))
setattr(yearvar, 'units', 'years since 1950-01-01')
#os.system("chmod 775 " + timeseries + " 2> /dev/null")

sealevel = ncf.createVariable('delta_SL', 'f4', dimensions=('time', ))
setattr(sealevel, 'units', 'meters')
setattr(sealevel, 'interpolation', 'linear')
sealevel.long_name = 'Relative Sea Level (variation from present)'
setattr(sealevel, 'standard_name', 'global_average_sea_level_change')

yearvar[:] = time[:]  #+50.0
sealevel[:] = slev[:] - slev[0]
Exemplo n.º 13
0
    if e != 0:
        exit(1)

    e = system(
        "ncks -O -v temp -d z,0 foo-temp-continuity.nc temp-temp-continuity.nc"
    )
    if e != 0:
        exit(1)

    e = system(
        "ncks -O -v litho_temp -d zb,10 foo-temp-continuity.nc litho_temp-temp-continuity.nc"
    )
    if e != 0:
        exit(1)

    nc1 = NC("temp-temp-continuity.nc")
    nc2 = NC("litho_temp-temp-continuity.nc")

    temp = squeeze(nc1.variables['temp'][:])
    litho_temp = squeeze(nc2.variables['litho_temp'][:])

    deltas.append(abs(temp - litho_temp).max())

# these deltas are observed to decrease O(dt^1) approximately, which is expected from theory
for (dt, delta) in zip(dts, deltas):
    stderr.write("dt = %f, delta = %f\n" % (dt, delta))

# the only test is whether they decrease; no rate measured
if any(diff(deltas) > 0):
    print(diff(deltas))
    exit(1)
Exemplo n.º 14
0
#!/usr/bin/env python

from numpy import *
try:
    from netCDF4 import Dataset as NC
except:
    from netCDF3 import Dataset as NC
from pylab import *

nc_no = NC("ts_no_force.nc", "r")
nc_with = NC("ts_with_force.nc", "r")
nc_weak = NC("ts_weak_force.nc", "r")

t = nc_no.variables["t"][:]

ivol_no = nc_no.variables["ivol"][:]
ivol_with = nc_with.variables["ivol"][:]
ivol_weak = nc_weak.variables["ivol"][:]

plot(t, ivol_no * 1.0e-15, '-o',
     t, ivol_with * 1.0e-15, '-o',
     t, ivol_weak * 1.0e-15, '-o',
     t, 2.82528 * ones(shape(t)),'--k')
legend( ('no forcing',
         'alpha = 0.002 (default)',
         'alpha = 0.0002',
         'target volume'),
         loc='right')
xlabel("t (years)", size=16)
ylabel("ice volume (10^6 km^3)", size=16)
grid(True)
Exemplo n.º 15
0
def adjust_timeline(
    filename,
    start_date="2015-1-1",
    interval=1,
    interval_type="mid",
    bounds=True,
    periodicity="yearly".upper(),
    ref_date="2008-1-1",
    ref_unit="days",
    calendar="standard",
):
    nc = NC(filename, "a")
    nt = len(nc.variables["time"])

    time_units = "%s since %s" % (ref_unit, ref_date)
    time_calendar = calendar

    cdftime = utime(time_units, time_calendar)

    # create a dictionary so that we can supply the periodicity as a
    # command-line argument.
    pdict = {}
    pdict["SECONDLY"] = rrule.SECONDLY
    pdict["MINUTELY"] = rrule.MINUTELY
    pdict["HOURLY"] = rrule.HOURLY
    pdict["DAILY"] = rrule.DAILY
    pdict["WEEKLY"] = rrule.WEEKLY
    pdict["MONTHLY"] = rrule.MONTHLY
    pdict["YEARLY"] = rrule.YEARLY
    prule = pdict[periodicity]

    # reference date from command-line argument
    r = time_units.split(" ")[2].split("-")
    refdate = datetime(int(r[0]), int(r[1]), int(r[2]))

    # create list with dates from start_date for nt counts
    # periodicity prule.
    bnds_datelist = list(
        rrule.rrule(freq=prule,
                    dtstart=parse(start_date),
                    count=nt + 1,
                    interval=interval))

    # calculate the days since refdate, including refdate, with time being the
    bnds_interval_since_refdate = cdftime.date2num(bnds_datelist)
    if interval_type == "mid":
        # mid-point value:
        # time[n] = (bnds[n] + bnds[n+1]) / 2
        time_interval_since_refdate = bnds_interval_since_refdate[
            0:-1] + np.diff(bnds_interval_since_refdate) / 2
    elif interval_type == "start":
        time_interval_since_refdate = bnds_interval_since_refdate[:-1]
    else:
        time_interval_since_refdate = bnds_interval_since_refdate[1:]

    # create a new dimension for bounds only if it does not yet exist
    time_dim = "time"
    if time_dim not in list(nc.dimensions.keys()):
        nc.createDimension(time_dim)

    # variable names consistent with PISM
    time_var_name = "time"
    bnds_var_name = "time_bnds"

    # create time variable
    if time_var_name not in nc.variables:
        time_var = nc.createVariable(time_var_name, "d", dimensions=(time_dim))
    else:
        time_var = nc.variables[time_var_name]
    time_var[:] = time_interval_since_refdate
    time_var.units = time_units
    time_var.calendar = time_calendar
    time_var.standard_name = time_var_name
    time_var.axis = "T"

    if bounds:
        # create a new dimension for bounds only if it does not yet exist
        bnds_dim = "nb2"
        if bnds_dim not in list(nc.dimensions.keys()):
            nc.createDimension(bnds_dim, 2)

        # create time bounds variable
        if bnds_var_name not in nc.variables:
            time_bnds_var = nc.createVariable(bnds_var_name,
                                              "d",
                                              dimensions=(time_dim, bnds_dim))
        else:
            time_bnds_var = nc.variables[bnds_var_name]
        time_bnds_var[:, 0] = bnds_interval_since_refdate[0:-1]
        time_bnds_var[:, 1] = bnds_interval_since_refdate[1::]
        time_var.bounds = bnds_var_name
    else:
        delattr(time_var, "bounds")

    nc.close()
Exemplo n.º 16
0
    parser.description = "Fill missing values by solving the Laplace equation in on the missing values and using present values as Dirichlet B.C."

    parser.add_argument("INPUT", nargs=1, help="Input file name.")
    parser.add_argument("OUTPUT", nargs=1, help="Output file name.")
    parser.add_argument("-a", "--all", dest="all", action="store_true",
                        help="Process all variables.")
    parser.add_argument("-v", "--vars", dest="variables",
                        help="comma-separated list of variables to process")

    options, _ = parser.parse_known_args()

    input_filename = options.INPUT[0]
    output_filename = options.OUTPUT[0]

    if options.all:
        nc = NC(input_filename)
        variables = list(nc.variables.keys())
        nc.close()
    else:
        try:
            variables = (options.variables).split(',')
        except:
            PETSc.Sys.Print("Please specify variables using the -v option.")
            sys.exit(-1)

    # Done processing command-line options.

    comm = PETSc.COMM_WORLD
    rank = comm.getRank()

    t0 = time()
Exemplo n.º 17
0
xcu, ycu = 50e3, y1

CL = (X - xcl) ** 2 + (Y - ycl) ** 2 < radius ** 2
CU = (X - xcu) ** 2 + (Y - ycu) ** 2 < radius ** 2

wall_elevation = 1000.0
if has_sidewalls:
    Zpi[np.logical_or(CL, CU)] = wall_elevation
    Zpi[np.logical_and((X < xcl), (Y < ycl + radius))] = wall_elevation
    Zpi[np.logical_and((X < xcu), (Y > ycu - radius))] = wall_elevation

thk = Zspi - Zpi
thk[X < x_s] = 0.0
thk[thk < 0] = 0.0

nc = NC(nc_outfile, "w", format=fileformat)

nc.createDimension("x", size=x.shape[0])
nc.createDimension("y", size=y.shape[0])

var = "x"
var_out = nc.createVariable(var, "d", dimensions=("x"))
var_out.axis = "X"
var_out.long_name = "X-coordinate in Cartesian system"
var_out.standard_name = "projection_x_coordinate"
var_out.units = "meters"
var_out[:] = x

var = "y"
var_out = nc.createVariable(var, "d", dimensions=("y"))
var_out.axis = "Y"
Exemplo n.º 18
0
# load RIGGS data FROM D. MACAYEAL TO ELB ON 19 DEC 2006.
try:
    print "Loading RIGGS data from '%s'..." % (riggs_file),
    RIGGS = loadtxt(riggs_file)  # pylab now suggests numpy.loadtxt instead of
    #    pylab's "load"
    print "done."
except IOError:
    print """ERROR!\nMake sure that '%s' is in the expected location
     and try again.  Exiting...""" % (riggs_file)
    exit(-1)

# load the PISM output
try:
    print "Loading PISM output from '%s'..." % (pism_output),
    infile = NC(pism_output, 'r')
except Exception:
    print """ERROR!\nSpecify NetCDF file from PISM run with -p.
    See ross_plot.py --help and User's Manual.  Exiting..."""
    exit(-1)


def get_var(nc, name):
    """Get a 2D field from a NetCDF file, transposing if necessary. The
    returned array will always have the (y,x) variable order."""

    var = nc.variables[name]
    dims = var.dimensions
    if dims.index('x') < dims.index('y'):
        # transpose
        return squeeze(var[:]).T
Exemplo n.º 19
0
def plot_rcp_traj_mass(plot_var=mass_plot_vars):

    jet = cm = plt.get_cmap('jet')

    for k, rcp in enumerate(rcp_list):

        rcp_files = [f for f in ifiles if 'rcp_{}'.format(rcp) in f]

        if len(rcp_files) < 3:

            print('Less than 3 files found for {}, skipping'.format(
                rcp_dict[rcp]))

        else:

            print('Reading files for {}'.format(rcp_dict[rcp]))

            cdf_mass_enspctl16 = cdo.enspctl('16',
                                             input=rcp_files,
                                             returnCdf=True,
                                             options=pthreads)
            cdf_mass_enspctl84 = cdo.enspctl('84',
                                             input=rcp_files,
                                             returnCdf=True,
                                             options=pthreads)
            cdf_mass_ensmedian = cdo.enspctl('50',
                                             input=rcp_files,
                                             returnCdf=True,
                                             options=pthreads)
            t = cdf_mass_ensmedian.variables['time'][:]

            mass_enspctl16_vals = cdf_mass_enspctl16.variables[
                plot_var][:] - cdf_mass_enspctl16.variables[plot_var][0]
            iunits = cdf_mass_enspctl16[plot_var].units
            mass_enspctl16_vals = -unit_converter(mass_enspctl16_vals, iunits,
                                                  mass_ounits) * gt2mSLE

            mass_enspctl84_vals = cdf_mass_enspctl84.variables[
                plot_var][:] - cdf_mass_enspctl84.variables[plot_var][0]
            iunits = cdf_mass_enspctl84[plot_var].units
            mass_enspctl84_vals = -unit_converter(mass_enspctl84_vals, iunits,
                                                  mass_ounits) * gt2mSLE

            mass_ensmedian_vals = cdf_mass_ensmedian.variables[
                plot_var][:] - cdf_mass_ensmedian.variables[plot_var][0]
            iunits = cdf_mass_ensmedian[plot_var].units
            mass_ensmedian_vals = -unit_converter(mass_ensmedian_vals, iunits,
                                                  mass_ounits) * gt2mSLE

            date = np.arange(start_year + step,
                             start_year + (len(t[:]) + 1) * step, step)

            for lhs_param in lhs_params_dict:
                param = lhs_params_dict[lhs_param]
                param_name = param['param_name']
                param_scale_factor = param['scale_factor']
                norm = mpl.colors.Normalize(vmin=param['vmin'],
                                            vmax=param['vmax'])
                scalarMap = cmx.ScalarMappable(norm=norm, cmap=jet)

                fig = plt.figure()
                offset = transforms.ScaledTranslation(dx, dy,
                                                      fig.dpi_scale_trans)
                ax = fig.add_subplot(111)

                for rcp_file in rcp_files:
                    nc = NC(rcp_file, 'r')
                    pism_config = nc.variables['pism_config']
                    param_value = getattr(pism_config,
                                          param_name) * param_scale_factor
                    colorVal = scalarMap.to_rgba(param_value)

                    cdf_rcp_mass_file = nc.variables[plot_var]
                    mass_vals = nc.variables[plot_var][:] - nc.variables[
                        plot_var][0]
                    iunits = cdf_rcp_mass_file.units
                    mass_vals = -unit_converter(mass_vals, iunits,
                                                mass_ounits) * gt2mSLE
                    ax.plot(date[:],
                            mass_vals,
                            alpha=0.3,
                            linewidth=0.2,
                            color=colorVal)
                    nc.close()

                    ax.plot(date[:],
                            mass_ensmedian_vals,
                            color='k',
                            linewidth=0.5)

                    ax.plot(date[:],
                            mass_enspctl16_vals,
                            color='k',
                            linestyle='dashed',
                            linewidth=0.25)

                    ax.plot(date[:],
                            mass_enspctl84_vals,
                            color='k',
                            linestyle='dashed',
                            linewidth=0.25)

                    idx = np.where(np.array(date) == time_bounds[-1])[0][0]
                    m_median = mass_ensmedian_vals[idx]
                    m_pctl16 = mass_enspctl16_vals[idx]
                    m_pctl84 = mass_enspctl84_vals[idx]

                    # x_sle, y_sle = time_bounds[-1], m_median
                    # plt.text( x_sle, y_sle, '{: 1.2f}$\pm${:1.2f}'.format(m_median, m_diff),
                    #           color='k')

                    # if do_legend:
                    #     legend = ax.legend(loc="upper right",
                    #                        edgecolor='0',
                    #                        bbox_to_anchor=(0, 0, .35, 0.88),
                    #                        bbox_transform=plt.gcf().transFigure)
                    #     legend.get_frame().set_linewidth(0.0)

                    ax.set_xlabel('Year (CE)')
                    ax.set_ylabel('$\Delta$(GMSL) (m)')

                    if time_bounds:
                        ax.set_xlim(time_bounds[0], time_bounds[1])

                    if bounds:
                        ax.set_ylim(bounds[0], bounds[1])

                    ymin, ymax = ax.get_ylim()

                    ax.yaxis.set_major_formatter(FormatStrFormatter('%1.2f'))

                    if rotate_xticks:
                        ticklabels = ax.get_xticklabels()
                        for tick in ticklabels:
                            tick.set_rotation(30)
                    else:
                        ticklabels = ax.get_xticklabels()
                        for tick in ticklabels:
                            tick.set_rotation(0)

                    title = '{} {}'.format(rcp_dict[rcp],
                                           lhs_params_dict[lhs_param]['symb'])
                    if title is not None:
                        plt.title(title)

                for out_format in out_formats:
                    out_file = outfile + '_rcp' + '_' + rcp + '_' + lhs_param.lower(
                    ) + '_' + plot_var + '.' + out_format
                    print "  - writing image %s ..." % out_file
                    fig.savefig(out_file, bbox_inches='tight', dpi=out_res)
Exemplo n.º 20
0
######## geometry setup (moritz.huetten@pik) #########

### CONSTANTS ###

secpera = 31556926.
ice_density = 910.0

yExtent = 2 * 50  # in km
xExtent = 2 * 800  # in km

# load data from Stnd-experiment

try:
    name = inpath  # + '.nc'
    infile = NC(name, 'r')
except Exception:
    print("file '%s' not found" % name)
    sys.exit(2)
    # exit(-1)

x = squeeze(infile.variables["x"][:])
nx = len(x)

boxWidth = x[nx - 1] / ((nx - 1) / 2) / 1e3

# grid size: # of boxes

ny = int(np.floor(yExtent / boxWidth / 2) * 2 + 1)  # make it an odd number

# grid size: extent in km's, origin (0,0) in the center of the domain
Exemplo n.º 21
0
                    default="interface.shp")
parser.add_argument("-v",
                    "--variable",
                    dest="dst_fieldname",
                    help="Name of variable to use",
                    default="usurf")

options = parser.parse_args()
filename = options.FILE[0]
epsg = options.epsg
levels = np.array(options.levels.split(","), dtype=float)
shp_filename = options.out_file
ts_fieldname = "timestamp"
dst_fieldname = options.dst_fieldname

nc = NC(filename, "r")
xdim, ydim, zdim, tdim = ppt.get_dims(nc)

if tdim:
    time = nc.variables[tdim]
    time_units = time.units
    time_calendar = time.calendar
    cdftime = utime(time_units, time_calendar)
    timestamps = cdftime.num2date(time[:])
    has_time = True
else:
    tdim = None
nc.close()

src_ds = gdal.Open("NETCDF:{}:{}".format(filename, dst_fieldname))
Exemplo n.º 22
0
def evalcase(stddev, cp, fn, deletencfiles):
    """evaluates one pclimate run against smb target in a file"""
    # input cp is of type Case()
    # input fn is of type Filenames()

    cp.stddev = stddev

    try:
        from netCDF4 import Dataset as NC
    except:
        from netCDF3 import Dataset as NC

    from objective import computeobjective

    configopt = " -config_override " + fn.configfile(cp)
    print "  creating -config_override file %s ..." % fn.configfile(cp)
    try:
        nc_config = NC(fn.configfile(cp), 'w')
    except:
        usagefailure("ERROR: NETCDF FILE '%s' CANNOT BE OPENED FOR WRITING" \
                     % fn.configfile(cp) )
    cp.put_pism_overrides(nc_config)
    nc_config.close()

    # change this to "mpiexec -n 8" or similar to run on multiple processes
    mpido = ""
    # coupler settings: Fausto 2m air temp parameterization, but default PDD
    #   (w/o Greve/Fausto settings of PDD parameters)
    coupleropts = " -atmosphere searise_greenland -surface pdd"
    if cp.annualizepdd:
        coupleropts += " -pdd_annualize"
    timeopts = " -times 1990:1.0:1991"
    #dt = 0.0833333333 # monthly = (1/12) of year

    if len(fn.diffsfile) > 0:
        print "  will add lines of text to " + fn.diffsfile + " ..."
    if deletencfiles:
        print "  will delete NetCDF files %s and %s when no longer needed ..." % \
                (fn.configfile(cp), fn.climatefile(cp))

    # run PISM:
    command = mpido + " pclimate -i " + fn.startfile + coupleropts + configopt \
                + timeopts + " -o " + fn.climatefile(cp)
    print "  doing:"
    print "    " + command
    try:
        (status, output) = commands.getstatusoutput(command)
    except KeyboardInterrupt:
        exit(2)
    if status:
        #exit(status)
        print status
        print output

    countvalid, avdiff, avL2, av2kL2 = computeobjective(
        fn.startfile, fn.climatefile(cp), fn.targetfile, "acab", "smb")
    print "  result: "
    print "    %d locations for valid (thk>0) comparison:" % countvalid
    print "    average of signed differences (whole sheet) is  %12.7f" % avdiff
    print "    average of squared differences (whole sheet) is %12.7f" % avL2
    print "    average of squared differences (H < 2000) is    %12.7f" % av2kL2

    # FIXME:  allow choice of weights
    weighted = 1.0 * avL2 + 3.0 * av2kL2
    print "    weighted average of above quantities is         %12.7f" % weighted

    # write results to file if a file name was given, otherwise stdout
    lineoftxt = "%s %12.7f %12.7f %12.7f %12.7f\n" % \
                  (fn.climatefile(cp), avdiff, avL2, av2kL2, weighted)
    if len(fn.diffsfile) > 0:
        diffs = file(fn.diffsfile, 'a')
        diffs.write(lineoftxt)
        diffs.close()
    else:
        print "  result in one line:"
        print lineoftxt

    # finalize: if option was given, clean up generated NetCDF file
    if deletencfiles:
        command = "rm -rf " + fn.configfile(cp) + " " + fn.climatefile(cp)
        print "  doing:"
        print "    " + command
        try:
            (status, output) = commands.getstatusoutput(command)
        except KeyboardInterrupt:
            exit(2)
        if status:
            #exit(status)
            print status
            print output

    print ""
    return avdiff
Exemplo n.º 23
0
nco = Nco()

# Set up the option parser
parser = ArgumentParser()
parser.description = "Extract basal enthalpy."
parser.add_argument("INFILE", nargs=1)
parser.add_argument("OUTFILE", nargs=1)

options = parser.parse_args()
infile = options.INFILE[0]
outfile = options.OUTFILE[0]
fill_value = -9999

nco.ncks(input=infile, output=outfile, variable='thk', overwrite=True)

nc_in = NC(infile, 'r')
nc_out = NC(outfile, 'a')

z = nc_in.variables['z'][:]
thk = nc_in.variables['thk'][:]
basal_layer_thickness = 200
enthalpy = nc_in.variables['enthalpy'][:, :, :, z <= basal_layer_thickness]
eb_values = np.sum(enthalpy, axis=3)
eb_values[thk < 10] = fill_value
eb_var = nc_out.createVariable('basal_enthalpy',
                               'f',
                               dimensions=('time', 'y', 'x'),
                               fill_value=fill_value)
eb_var.comment = 'enthalpy in the lowermost {}m'.format(basal_layer_thickness)
eb_var.units = 'J kg-1'
eb_var.long_name = 'enthalpy in the lowermost {}m'.format(
Exemplo n.º 24
0
import numpy as np
from netCDF4 import Dataset as NC
import os
import re
from glob import glob
import pandas as pd

infiles = glob(os.path.join("2018_09_les/scalar_clean", "ts_*.nc"))
start_year = 2008

dfs = []
for infile in infiles:
    print(f"Processing {infile}")
    if os.path.isfile(infile):
        nc = NC(infile)
        m_id = int(re.search("id_(.+?)_", infile).group(1))
        m_dx = int(re.search("gris_g(.+?)m", infile).group(1))
        m_rcp = int(re.search("rcp_(.+?)_", infile).group(1))
        m_m = np.squeeze(nc.variables["limnsw"][:]) / 1e12
        m_m -= m_m[0]
        m_dm = np.squeeze(nc.variables["tendency_of_ice_mass_glacierized"][:]) / 1e12
        m_dm -= m_dm[0]
        m_smb = np.squeeze(nc.variables["tendency_of_ice_mass_due_to_surface_mass_balance"][:]) / 1e12
        m_d = np.squeeze(nc.variables["tendency_of_ice_mass_due_to_discharge"][:]) / 1e12
        n = len(m_m)
        m_years = start_year + np.linspace(0, n - 1, n)

        dfs.append(
            pd.DataFrame(
                data=np.hstack(
Exemplo n.º 25
0
  sys.exit(0)


################## NetCDF write option #################
#### write a PISM-readable file with thickness only ####

try:
    from netCDF4 import Dataset as NC
except:
    from netCDF3 import Dataset as NC

My = 3
dy = (2. * LL) / (float(Mx-1))
Lx = (dy * float(My)) / 2.  # truely periodic in x direction

ncfile = NC(ncfilename, 'w',format='NETCDF3_CLASSIC')

# set global attributes
historysep = ' '
historystr = time.asctime() + ': ' + historysep.join(sys.argv) + '\n'
setattr(ncfile, 'history', historystr)
setattr(ncfile, 'source', "PISM: examples/mismip/solverMS.py")

# define the dimensions & variables
xdim = ncfile.createDimension('x', Mx)
ydim = ncfile.createDimension('y', My)
xvar = ncfile.createVariable('x', 'f8', dimensions=('x',))
yvar = ncfile.createVariable('y', 'f8', dimensions=('y',))
Hvar = ncfile.createVariable('thk', 'f4', dimensions=('y', 'x'))

# attributes of the variables
Exemplo n.º 26
0
        '85': '#31a354'
    },
    'NorESM1': {
        '45': '#bcbddc',
        '85': '#756bb1'
    }
}

fig, ax = plt.subplots()

rus = []
tass = []
p_ols = []
for k, ifile in enumerate(options.FILE):
    print(ifile, k)
    nc = NC(ifile, 'r')
    forcing = nc.forcing
    gcm, rcp = forcing.split('-')
    rcp = rcp.split('rcp')[-1]
    tas = np.squeeze(nc.variables['ST'][:])
    ru = np.squeeze(nc.variables['RU'][:])
    tas -= tas.min()
    ru /= ru.min()

    rus.append(ru)
    tass.append(tas)
    print(gcm, rcp)
    ax.scatter(tas,
               ru,
               s=2.5,
               facecolors='none',
Exemplo n.º 27
0
# Copyright (C) 2012, 2014, 2016, 2018 Moritz Huetten and Torsten Albrecht

# create MISMIP config override file

try:
    from netCDF4 import Dataset as NC
except:
    print("netCDF4 is not installed!")
    sys.exit(1)

filename = "MISMIP3D_conf.nc"

print(
    '  creating MISMIP3D_conf.nc for configuration parameters (overrides) ...')

nc = NC(filename, 'w', format="NETCDF3_CLASSIC")

var = nc.createVariable("pism_overrides", 'i')

attrs = {
    "ocean.always_grounded": "no",
    "geometry.update.use_basal_melt_rate": "no",
    "stress_balance.ssa.compute_surface_gradient_inward": "no",
    "flow_law.isothermal_Glen.ice_softness": 1.0e-25,
    "constants.ice.density": 900.,
    "constants.sea_water.density": 1000.,
    "bootstrapping.defaults.geothermal_flux": 0.0,
    "stress_balance.ssa.Glen_exponent": 3.,
    "constants.standard_gravity": 9.81,
    "ocean.sub_shelf_heat_flux_into_ice": 0.0,
    "stress_balance.sia.bed_smoother.range": 0.0,
Exemplo n.º 28
0
        "altitude",
        "altitude",
        "ice thickness",
        "ice thickness",
        "ice thickness",
    )
    var_name_dict = dict(list(zip(var_long, var_short)))

    flow_types = {0: "isbr{\\ae}", 1: "ice-stream", 2: "undefined"}
    glacier_types = {0: "ffmt", 1: "lvmt", 2: "ist", 3: "lt"}

    # Open first file
    filename = args[0]
    print(("  opening NetCDF file %s ..." % filename))
    try:
        nc0 = NC(filename, "r")
    except:
        print(("ERROR:  file '%s' not found or not NetCDF format ... ending ..." % filename))
        import sys

        sys.exit(1)

    # Get profiles from first file
    # All experiments have to contain the same profiles
    # Create flux gates
    profile_names = nc0.variables["profile_name"][:]
    flux_gates = []
    for pos_id, profile_name in enumerate(profile_names):
        profile_axis = nc0.variables["profile_axis"][pos_id]
        profile_axis_units = nc0.variables["profile_axis"].units
        profile_axis_name = nc0.variables["profile_axis"].long_name
Exemplo n.º 29
0
    output_filename = options.output_filename

    eps = float(options.eps)

    # Done processing command-line options.

    print("Creating the temporary file...")
    try:
        (handle, tmp_filename) = mkstemp()
        close(handle)  # mkstemp returns a file handle (which we don't need)
        copy(input_filename, tmp_filename)
    except IOError:
        print("ERROR: Can't create %s, Exiting..." % tmp_filename)

    try:
        nc = NC(tmp_filename, 'a')
    except Exception as message:
        print(message)
        print("Note: %s was not modified." % output_filename)
        exit(-1)

    # add history global attribute (after checking if present)
    historysep = ' '
    historystr = asctime() + ': ' + historysep.join(argv) + '\n'
    if 'history' in nc.ncattrs():
        nc.history = historystr + nc.history  # prepend to history string
    else:
        nc.history = historystr

    t_zero = time()
    for name in variables:
Exemplo n.º 30
0
    """ 
    w, h: width, height in inches
    """

    if not ax:
        ax = plt.gca()
    l = ax.figure.subplotpars.left
    r = ax.figure.subplotpars.right
    t = ax.figure.subplotpars.top
    b = ax.figure.subplotpars.bottom
    figw = float(w) / (r - l)
    figh = float(h) / (t - b)
    ax.figure.set_size_inches(figw, figh)


nc = NC("fldsum_synth_jib_runoff_g1000m.nc", "r")
water_input_rate = np.squeeze(nc.variables["water_input_rate"][:])
nc.close()

nc_r = NC("2019_12_routing/spatial/fldmax_ex_synth_jib_g1000m_id_ROUTING_0_10.nc", "r")
nc_s = NC("2019_12_steady/spatial/fldmax_ex_synth_jib_g1000m_id_STEADY_0_10.nc", "r")

calving_r = np.squeeze(nc_r.variables["vonmises_calving_rate"][:])
fm_r = np.squeeze(nc_r.variables["frontal_melt_rate"][:])
fm_s = np.squeeze(nc_s.variables["frontal_melt_rate"][:])

time = range(0, 365)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(time, water_input_rate)