def create_output_file(filename, grid_size, start_year): "create the output file and set up the grid" zero = zeros((grid_size,grid_size)) try: nc = NC(filename, 'a') return nc, zero except: pass nc = NC(filename, 'w') Lx = 750000 Ly = 750000 dx = 2 * Lx / grid_size dy = 2 * Ly / grid_size x_min = -Lx + 0.5 * dx x_max = Lx - 0.5 * dx y_min = -Ly + 0.5 * dy y_max = Ly - 0.5 * dy x = linspace(x_min, x_max, grid_size) y = linspace(y_min, y_max, grid_size) nc.create_dimensions(x, y, time_dependent = True, use_time_bounds = True) nc.variables['time'].units = "days since %d-1-1" % (start_year) nc.variables['time'].calendar = "gregorian" return nc, zero
def generate_config(): """Generates the config file with custom ice softness and hydraulic conductivity.""" stderr.write("generating testPconfig.nc ...\n") nc = PISMDataset("testPconfig.nc", 'w') pism_overrides = nc.createVariable("pism_overrides", 'b') attrs = { "flow_law.isothermal_Glen.ice_softness": 3.1689e-24, "flow_law.isothermal_Glen.ice_softness_doc": "Pa-3 s-1; ice softness; NOT DEFAULT", "hydrology.hydraulic_conductivity": 1.0e-2 / (1000.0 * 9.81), "hydrology.hydraulic_conductivity_doc": "= k; NOT DEFAULT", "hydrology.regularizing_porosity": 0.01, "hydrology.regularizing_porosity_doc": "[pure]; phi_0 in notes", "hydrology.tillwat_max": 0.0, "hydrology.tillwat_max_doc": "m; turn off till water mechanism", "hydrology.thickness_power_in_flux": 1.0, "hydrology.thickness_power_in_flux_doc": "; = alpha in notes", "hydrology.gradient_power_in_flux": 2.0, "hydrology.gradient_power_in_flux_doc": "; = beta in notes", "hydrology.roughness_scale": 1.0, "hydrology.roughness_scale_doc": "m; W_r in notes; roughness scale", "basal_yield_stress.model": "constant", "basal_yield_stress.model_doc": "only the constant yield stress model works without till", "basal_yield_stress.constant.value": 1e6, "basal_yield_stress.constant.value_doc": "set default to 'high tauc'", } keys = list(attrs.keys()) keys.sort() for k in keys: pism_overrides.setncattr(k, attrs[k]) nc.close()
def generate_config(): """Generates the config file with custom ice softness and hydraulic conductivity.""" stderr.write("generating testPconfig.nc ...\n") nc = PISMDataset("testPconfig.nc", 'w') pism_overrides = nc.createVariable("pism_overrides", 'b') attrs = { "flow_law.isothermal_Glen.ice_softness": 3.1689e-24, "flow_law.isothermal_Glen.ice_softness_doc": "Pa-3 s-1; ice softness; NOT DEFAULT", "hydrology.hydraulic_conductivity": 1.0e-2 / (1000.0 * 9.81), "hydrology.hydraulic_conductivity_doc": "= k; NOT DEFAULT", "hydrology.regularizing_porosity": 0.01, "hydrology.regularizing_porosity_doc": "[pure]; phi_0 in notes", "hydrology.tillwat_max": 0.0, "hydrology.tillwat_max_doc": "m; turn off till water mechanism", "hydrology.thickness_power_in_flux": 1.0, "hydrology.thickness_power_in_flux_doc": "; = alpha in notes", "hydrology.gradient_power_in_flux": 2.0, "hydrology.gradient_power_in_flux_doc": "; = beta in notes", "hydrology.roughness_scale": 1.0, "hydrology.roughness_scale_doc": "m; W_r in notes; roughness scale", "basal_yield_stress.model": "constant", "basal_yield_stress.model_doc": "only the constant yield stress model works without till", "basal_yield_stress.constant.value": 1e6, "basal_yield_stress.constant.value_doc": "set default to 'high tauc'", } keys = list(attrs.keys()) keys.sort() for k in keys: pism_overrides.setncattr(k, attrs[k]) nc.close()
def report_drift(name, file1, file2, xx, yy, doshow=False): "Report on the difference between two files." nc1 = PISMDataset(file1) nc2 = PISMDataset(file2) var1 = nc1.variables[name] var2 = nc2.variables[name] diff = np.abs(np.squeeze(var1[:]) - np.squeeze(var2[:])) rr = np.sqrt(xx ** 2 + yy ** 2) diff[rr >= 0.89 * 25000.0] = 0.0 if (doshow): import matplotlib.pyplot as plt plt.pcolormesh(xx, yy, diff) plt.axis('equal') plt.axis('tight') plt.colorbar() plt.show() #stderr.write("Drift in %s: average = %f, max = %f [%s]" % (name, np.average(diff), np.max(diff), var1.units) + "\n") return np.average(diff), np.max(diff)
def generate_config(): """Generates the config file with custom ice softness and hydraulic conductivity.""" stderr.write("generating testPconfig.nc ...\n") nc = PISMDataset("testPconfig.nc", 'w') pism_overrides = nc.createVariable("pism_overrides", 'b') pism_overrides.ice_softness = 3.1689e-24 pism_overrides.ice_softness_doc = "Pa-3 s-1; ice softness; NOT DEFAULT" pism_overrides.hydrology_hydraulic_conductivity = 1.0e-2 / (1000.0 * 9.81) pism_overrides.hydrology_hydraulic_conductivity_doc = "= k; NOT DEFAULT" pism_overrides.hydrology_regularizing_porosity = 0.01 pism_overrides.hydrology_regularizing_porosity_doc = "[pure]; phi_0 in notes" pism_overrides.hydrology_tillwat_max = 0.0 pism_overrides.hydrology_tillwat_max_doc = "m; turn off till water mechanism" pism_overrides.hydrology_thickness_power_in_flux = 1.0 pism_overrides.hydrology_thickness_power_in_flux_doc = "; = alpha in notes" pism_overrides.hydrology_gradient_power_in_flux = 2.0 pism_overrides.hydrology_gradient_power_in_flux_doc = "; = beta in notes" pism_overrides.hydrology_roughness_scale = 1.0 pism_overrides.hydrology_roughness_scale_doc = "m; W_r in notes; roughness scale" pism_overrides.yield_stress_model = "constant" pism_overrides.yield_stress_model_doc = "only the constant yield stress model works without till" pism_overrides.default_tauc = 1e6 pism_overrides.default_tauc_doc = "set default to 'high tauc'" nc.close()
xx, yy = np.meshgrid(x, y) z = np.zeros_like(xx) thk = np.zeros_like(z) for phi in np.linspace(0, 2 * np.pi, 4): R = 0.5 * L r = 0.2 * L center_x = R * np.cos(phi) center_y = R * np.sin(phi) T = phi / (2.0 * np.pi) * 1500.0 thk += (T / r) * np.sqrt( np.maximum(r**2 - (xx - center_x)**2 - (yy - center_y)**2, 0)) try: nc = NC(options.output, 'w') except: nc = NC(options.output, 'a') try: nc.create_dimensions(x, y, time_dependent=False) nc.define_2d_field("topg", attrs={ "units": "m", "long_name": "bedrock topography" }) nc.define_2d_field("thk", attrs={ "units": "m", "long_name": "ice thickness"
if nearest.size > 6: return nearest.sum() / nearest.size return fill_value for j in xrange(1,shape[0]-1): for i in xrange(1,shape[1]-1): if data[j,i] == fill_value: data[j,i] = fix_a_hole(i, j) fill_holes(usurf) x = np.linspace(-890500., 1720500., shape[1]) y = np.linspace(-628500., -3410500., shape[0]) nc = NC("NSIDC_Greenland_1km.nc", 'w') nc.create_dimensions(x, y) nc.define_2d_field("usurf", time_dependent = False, nc_type='i', attrs = {"long_name" : "upper surface elevation DEM", "comment" : "Downloaded from %s" % (ftp_url), "units" : "cm", "valid_min" : 0.0, "mapping" : "mapping", "_FillValue" : -1}) nc.write_2d_field("usurf", usurf) nc.define_2d_field("dist", time_dependent = False, nc_type='i', attrs = {"long_name" : "Mean distance from contributing GLAS data for each grid cell", "comment" : "Downloaded from %s" % (ftp_url), "units" : "mm", "valid_min" : 0.0,
parser.add_argument("--weather_station", dest="weather_station", action="store_true") parser.add_argument("output", nargs=1) options = parser.parse_args() start_time = 0 end_time = options.length N = options.N time = np.linspace(start_time, end_time, N) time_bounds = np.zeros((N-1, 2)) for i in range(N-1): time_bounds[i,:] = [time[i], time[i+1]] nc = PISMDataset(options.output[0], 'w') nc.create_time(True, N-1, units="years since 1-1-1") nc.variables['time'][:] = time_bounds[:,0] nc.variables['time_bounds'][:] = time_bounds if options.precip: delta = nc.write("delta_P", -0.5 + 0.5 * time_bounds[:,0]) delta.units = "kg m-2 year-1" delta.long_name = "precipitation offset" elif options.precip_scaling: delta = nc.write("frac_P", 0.5 + 0.5 * np.sin(time_bounds[:,0] / options.length * 4 * np.pi + 0.5*np.pi)) delta.units = "1" delta.long_name = "precipitation scaling" elif options.frac_SMB:
fname = arthern_bin + '/arthern_accumulation_bedmap2_grid.flt' accum = np.flipud( np.ma.masked_equal( np.reshape(np.fromfile(fname, dtype=np.float32), (N3b, N3a)), -9999.0)) #fname = arthern_bin + '/arthern_accumulation_rms_bedmap2_grid.flt' print " range of accum = [%.2f, %.2f]" % (accum.min(), accum.max()) accum_bm2 = np.zeros([N, N]) accum_bm2 = accum[x0:x0 + N, y0:y0 + N] accum_bm2 = np.ma.masked_array(accum_bm2, mask=(accum_bm2 == -9999.)) ### Write nc-file print "\nWriting NetCDF file '%s' ...\n" % ncbm2_name try: #nc = PNC(ncbm2_name, 'w', format='NETCDF3_CLASSIC') nc = PNC(ncbm2_name, 'w', format='NETCDF4_CLASSIC') except: print("can't open file %s for writing" % ncbm2_name) exit(1) dx = 1000.0 #m dy = 1000.0 #m x = np.linspace(0.0, (N - 1) * dx, N) y = np.linspace(0.0, (N - 1) * dy, N) nc.create_dimensions(x, y, time_dependent=False) print " writing topg ..." nc.define_2d_field("topg", time_dependent=False, attrs={ "long_name": "elevation of bedrock",
xx, yy = np.meshgrid(x, y) z = np.zeros_like(xx) thk = np.zeros_like(z) for phi in np.linspace(0, 2 * np.pi, 4): R = 0.5 * L r = 0.2 * L center_x = R * np.cos(phi) center_y = R * np.sin(phi) T = phi / (2.0 * np.pi) * 1500.0 thk += (T / r) * np.sqrt(np.maximum(r ** 2 - (xx - center_x) ** 2 - (yy - center_y) ** 2, 0)) try: nc = NC(options.output, 'w') except: nc = NC(options.output, 'a') try: nc.create_dimensions(x, y, time_dependent=False) nc.define_2d_field("topg", attrs={"units": "m", "long_name": "bedrock topography"}) nc.define_2d_field("thk", attrs={"units": "m", "long_name": "ice thickness"}) nc.define_2d_field("climatic_mass_balance", attrs={"units": "kg m-2 year-1"}) nc.define_2d_field("ice_surface_temp", attrs={"units": "Kelvin"}) except: pass
def generate_input(N): """Generate a PISM bootstrapping file for a neighborhood number N.""" output_filename = options.output_file_prefix + "_%08d.nc" % N pism_output_filename = options.output_file_prefix + "_o_%08d.nc" % N nc = NC(output_filename, 'w') format_string = "{0:0%db}" % (M * M) string = format_string.format(N) x = np.linspace(-options.L * 1000, options.L * 1000, M) zeros = np.zeros((M, M)) thk = np.zeros(M * M) topg = zeros.copy() - 0.1 * options.H topg[1, 1] = -options.H for j in range(M * M): if string[j] == '1': thk[j] = options.H nc.create_dimensions(x, x) nc.write("topg", topg, attrs={"units": "m", "long_name": "bed_topography"}) nc.write("climatic_mass_balance", zeros, attrs={"units": "kg m-2 year-1"}) nc.write("ice_surface_temp", zeros, attrs={"units": "Celsius"}) nc.write("thk", thk.reshape(M, M), attrs={ "units": "m", "long_name": "land_ice_thickness" }) nc.close() return output_filename, pism_output_filename
bc_mask = np.zeros_like(thk) bc_mask[thk > 0] = 1 # make the bed deep everywhere except in icy areas, where it is barely # grounded z = np.zeros_like(xx) - 1000.0 z[thk > 0] = -(910.0 / 1028.0) * 100.0 + 1 # Velocity Dirichlet B.C.: ubar = np.zeros_like(thk) vbar = np.zeros_like(thk) vbar[bc_mask == 1] = 100.0 try: nc = NC(options.output, 'w') nc.create_dimensions(x, y, time_dependent=False) nc.define_2d_field("topg", attrs={"units": "m", "long_name": "bedrock topography"}) nc.define_2d_field("thk", attrs={"units": "m", "long_name": "ice thickness"}) nc.define_2d_field("climatic_mass_balance", attrs={"units": "kg m-2 year-1"}) nc.define_2d_field("ice_surface_temp", attrs={"units": "Celsius"}) nc.define_2d_field("u_ssa_bc", attrs={"units": "m/year"}) nc.define_2d_field("v_ssa_bc", attrs={"units": "m/year"}) except: nc = NC(options.output, 'a')
type=float, help="domain length, meters") parser.add_option("-M", dest="Mx", default=101, type=int, help="number of grid points in the flow direction") (options, args) = parser.parse_args() My = 3 bed_slope = 0.02 ice_thickness = 1000.0 U = 100.0 nc = NC(options.output_file_name, 'w') x = np.linspace(0, options.length, options.Mx) y = x[0:3] - x[1] xx, yy = np.meshgrid(x, y) zeros = np.zeros((My, options.Mx)) topg = (0.5 * options.length - xx) * bed_slope thk = zeros.copy() thk[topg > 200] = ice_thickness v = zeros.copy() u = zeros.copy() + U
vy_filename = "%smosaicOffsets.vy" % output_dir grid = np.loadtxt(vx_filename + ".geodat", skiprows=1, comments="&") shape = (int(grid[0,1]), int(grid[0,0])) x0 = grid[2,0] * 1e3 y0 = grid[2,1] * 1e3 dx = grid[1,0] dy = grid[1,1] x1 = x0 + (shape[1] - 1) * dx y1 = y0 + (shape[0] - 1) * dx x = np.linspace(x0, x1, shape[1]) y = np.linspace(y0, y1, shape[0]) nc = NC("%Greenland_Average_%s.nc" % (output_dir,years), 'w') nc.create_dimensions(x, y) for (filename, short_name, long_name) in [(vx_filename, "vx", "ice surface velocity in the X direction"), (vy_filename, "vy", "ice surface velocity in the Y direction"), ]: nc.define_2d_field(short_name, time_dependent = False, nc_type='f4', attrs = {"long_name" : long_name, "comment" : "Data directly received from Ian Joughin stored on marmaduke.gi.alaska.edu", "units" : "m / year", "mapping" : "mapping", "_FillValue" : -2e+9}) var = np.fromfile(filename, dtype=">f4", count=-1)
subprocess.call(["wget", "-nc", http_url + filename]) mask = np.fromfile(filename, dtype="f4", count=-1) shape = (1740, 1860) x0 = -2443456.992 y0 = -2493592.067 dx = 1250.0 dy = 1250.0 x1 = x0 + (shape[1] - 1) * dx y1 = y0 + (shape[0] - 1) * dx x = np.linspace(x0, x1, shape[1]) y = np.linspace(y1, y0, shape[0]) nc = NC("Greenland_Land_Surface_Mask.nc", 'w') nc.create_dimensions(x, y) nc.define_2d_field("mask", time_dependent = False, nc_type='f', attrs = {"long_name" : "land surface classification mask", "comment" : "Downloaded from %s" % (http_url + filename), "mapping" : "mapping"}) nc.write_2d_field("mask", mask) mapping = nc.createVariable("mapping", 'c') mapping.grid_mapping_name = "lambert_azimuthal_equal_area" mapping.longitude_of_projection_origin = 0.0 mapping.latitude_of_projection_origin = 90.0 mapping.false_easting = 0.0 mapping.false_northing = 0.0 mapping.ellipsoid = "sphere"
fig = plt.figure(3) ax = plt.imshow(thk) fig.colorbar(ax) plt.show() sys.exit(0) #err = abs(bed[msk<0.5] + thk[msk<0.5] - srf[msk<0.5]) # print err.max() outname = 'ant1kmgeom.nc' print("writing NetCDF file '%s' ..." % outname) try: nc = PNC(outname, 'w', format='NETCDF3_CLASSIC') except: print("can't open file %s for writing" % outname) exit(1) print(" writing x,y ...") dx = 1000.0 dy = 1000.0 x = np.linspace(0.0, (N - 1) * dx, N) y = np.linspace(0.0, (N - 1) * dy, N) nc.create_dimensions(x, y, time_dependent=False) print(" writing topg ...") nc.define_2d_field("topg", time_dependent=False, attrs={"long_name": "elevation of bedrock", "valid_range": (-9000.0, 9000.0),
parser.description = "Fills missing values in variables selected using -v in the file given by -f." parser.add_option("-o", dest="output_file_name", default="advance_test.nc", help="output file name") parser.add_option("-L", dest="length", default=100e3, type=float, help="domain length, meters") parser.add_option("-M", dest="Mx", default=101, type=int, help="number of grid points in the flow direction") (options, args) = parser.parse_args() My = 3 bed_slope = 0.02 ice_thickness = 1000.0 U = 100.0 nc = NC(options.output_file_name, 'w') x = np.linspace(0, options.length, options.Mx) y = x[0:3] - x[1] xx, yy = np.meshgrid(x, y) zeros = np.zeros((My, options.Mx)) topg = (0.5 * options.length - xx) * bed_slope thk = zeros.copy() thk[topg > 200] = ice_thickness v = zeros.copy() u = zeros.copy() + U
import netCDF4 as NC except: print("netCDF4 is not installed!") sys.exit(1) inname = "pismnbreen.nc" outname = "fakesummerevent.nc" try: innc = NC.Dataset(inname, 'r') except: print("file %s not found" % inname) exit(1) try: nc = PNC(outname, 'w', format='NETCDF3_CLASSIC') except: print("can't open file %s for writing" % outname) exit(1) def get(name): global innc return np.squeeze(innc.variables[name][:]) x = get('x') y = get('y') bmelt = get('basal_melt_rate_grounded') Mx = len(x) My = len(y)
from PISMNC import PISMDataset as NC import numpy as np Mx = 201 My = 201 Lx = 20e4 Ly = 20e4 x = np.linspace(-Lx, Lx, Mx) y = np.linspace(-Ly, Ly, My) z = np.zeros((My, Mx)) nc = NC("dem.nc", 'w') nc.create_dimensions(x, y) for i in range(Mx): xx = x[i] for j in range(My): yy = y[j] r = np.sqrt(xx*xx + yy*yy) if r < 15e4: z[j, i] = np.sqrt(15e4*15e4 - xx*xx - yy*yy)/150.0 nc.write_2d_field("usurf", z) nc.write_2d_field("thk", z) nc.close()
import netCDF4 as NC except: print("netCDF4 is not installed!") sys.exit(1) inname = "pismnbreen.nc" outname = "fakesummerevent.nc" try: innc = NC.Dataset(inname, 'r') except: print("file %s not found" % inname) exit(1) try: nc = PNC(outname, 'w', format='NETCDF3_CLASSIC') except: print("can't open file %s for writing" % outname) exit(1) def get(name): global innc return np.squeeze(innc.variables[name][:]) x = get('x') y = get('y') bmelt = get('basal_melt_rate_grounded') Mx = len(x) My = len(y)
from PISMNC import PISMDataset as NC from numpy import fromfile, int32, r_ shape = (2782, 2611) x = r_[0:shape[1]:1] y = r_[0:shape[0]:1] #download data from http://nsidc.org/data/docs/daac/nsidc0304_0305_glas_dems.gd.html dem = fromfile("../data/NSIDC_Grn1km_wgs84_elev_cm.dat", dtype=">i", count=-1) dem = dem.reshape(shape) / 100.0 # convert to meters nc = NC("NSIDC_Greenland.nc", 'w') nc.create_dimensions(x, y) nc.write_2d_field("usurf", dem) nc.write_2d_field("thk", dem) nc.close() err_distance = fromfile("../data/NSIDC_Grn1km_dist_mm.dat", dtype=">i", count=-1) err_distance = err_distance.reshape(shape) / 100.0 # convert to meters nc = NC("NSIDC_Greenland_err_distance.nc", 'w') nc.create_dimensions(x, y) nc.write_2d_field("err_distance", err_distance) nc.close() # char polar_stereographic ; # polar_stereographic:Northernmost_Northing = -628500. ; # polar_stereographic:Southernmost_Northing = -3410500. ; # polar_stereographic:Easternmost_Easting = 1720500. ; # polar_stereographic:Westernmost_Easting = -890500. ;
fig = plt.figure(3) ax = plt.imshow(thk) fig.colorbar(ax) plt.show() sys.exit(0) #err = abs(bed[msk<0.5] + thk[msk<0.5] - srf[msk<0.5]) # print err.max() outname = 'ant1kmgeom.nc' print("writing NetCDF file '%s' ..." % outname) try: nc = PNC(outname, 'w', format='NETCDF3_CLASSIC') except: print("can't open file %s for writing" % outname) exit(1) print(" writing x,y ...") dx = 1000.0 dy = 1000.0 x = np.linspace(0.0, (N - 1) * dx, N) y = np.linspace(0.0, (N - 1) * dy, N) nc.create_dimensions(x, y, time_dependent=False) print(" writing topg ...") nc.define_2d_field("topg", time_dependent=False, attrs={
#!/usr/bin/env python import dbg from PISMNC import PISMDataset as NC nc = NC("mask.nc") mask = nc.variables["mask"][:] usurf = nc.variables["usurf"][:] x = nc.variables["x"][:] y = nc.variables["y"][:] thk = mask.copy() thk[mask == 0] = 100 thk[mask == 255] = 0 mask = dbg.initialize_mask(thk) nc = NC("flow.nc", "w") nc.create_dimensions(x, y) nc.write_2d_field("mask", mask) nc.write_2d_field("thk", thk) nc.close()
bc_mask = np.zeros_like(thk) bc_mask[thk > 0] = 1 # make the bed deep everywhere except in icy areas, where it is barely # grounded z = np.zeros_like(xx) - 1000.0 z[thk > 0] = -(910.0 / 1028.0) * 100.0 + 1 # Velocity Dirichlet B.C.: ubar = np.zeros_like(thk) vbar = np.zeros_like(thk) vbar[bc_mask == 1] = 100.0 try: nc = NC(options.output, 'w') nc.create_dimensions(x, y, time_dependent=False) nc.define_2d_field("topg", attrs={ "units": "m", "long_name": "bedrock topography" }) nc.define_2d_field("thk", attrs={ "units": "m", "long_name": "ice thickness" }) nc.define_2d_field("climatic_mass_balance",
def generate_input(N): """Generate a PISM bootstrapping file for a neighborhood number N.""" output_filename = options.output_file_prefix + "_%08d.nc" % N pism_output_filename = options.output_file_prefix + "_o_%08d.nc" % N nc = NC(output_filename, 'w') format_string = "{0:0%db}" % (M * M) string = format_string.format(N) x = np.linspace(-options.L * 1000, options.L * 1000, M) zeros = np.zeros((M, M)) thk = np.zeros(M * M) topg = zeros.copy() - 0.1 * options.H topg[1, 1] = -options.H for j in range(M * M): if string[j] == '1': thk[j] = options.H nc.create_dimensions(x, x) nc.write("topg", topg, attrs={"units": "m", "long_name": "bed_topography"}) nc.write("climatic_mass_balance", zeros, attrs={"units": "kg m-2 year-1"}) nc.write("ice_surface_temp", zeros, attrs={"units": "Celsius"}) nc.write("thk", thk.reshape(M, M), attrs={"units": "m", "long_name": "land_ice_thickness"}) nc.close() return output_filename, pism_output_filename
def generate_pism_input(x, y, xx, yy): stderr.write("calling exactP_list() ...\n") EPS_ABS = 1.0e-12 EPS_REL = 1.0e-15 # Wrapping r[:]['r'] in np.array() forces NumPy to make a C-contiguous copy. h_r, magvb_r, _, W_r, P_r = exactP_list(np.array(r[:]['r']), EPS_ABS, EPS_REL, 1) stderr.write("creating gridded variables ...\n") # put on grid h = np.zeros_like(xx) W = np.zeros_like(xx) P = np.zeros_like(xx) magvb = np.zeros_like(xx) ussa = np.zeros_like(xx) vssa = np.zeros_like(xx) for n, pt in enumerate(r): j = pt['j'] k = pt['k'] h[j, k] = h_r[n] # ice thickness in m magvb[j, k] = magvb_r[n] # sliding speed in m s-1 ussa[j, k], vssa[j, k] = radially_outward(magvb[j, k], xx[j, k], yy[j, k]) W[j, k] = W_r[n] # water thickness in m P[j, k] = P_r[n] # water pressure in Pa stderr.write("creating inputforP.nc ...\n") nc = PISMDataset("inputforP.nc", 'w') nc.create_dimensions(x, y, time_dependent=True, use_time_bounds=True) nc.define_2d_field("thk", time_dependent=False, attrs={"long_name": "ice thickness", "units": "m", "valid_min": 0.0, "standard_name": "land_ice_thickness"}) nc.define_2d_field("topg", time_dependent=False, attrs={"long_name": "bedrock topography", "units": "m", "standard_name": "bedrock_altitude"}) nc.define_2d_field("climatic_mass_balance", time_dependent=False, attrs={"long_name": "climatic mass balance for -surface given", "units": "kg m-2 year-1", "standard_name": "land_ice_surface_specific_mass_balance"}) nc.define_2d_field("ice_surface_temp", time_dependent=False, attrs={"long_name": "ice surface temp (K) for -surface given", "units": "Kelvin", "valid_min": 0.0}) nc.define_2d_field("bmelt", time_dependent=False, attrs={"long_name": "basal melt rate", "units": "m year-1", "standard_name": "land_ice_basal_melt_rate"}) nc.define_2d_field("bwat", time_dependent=False, attrs={"long_name": "thickness of basal water layer", "units": "m", "valid_min": 0.0}) nc.define_2d_field("bwp", time_dependent=False, attrs={"long_name": "water pressure in basal water layer", "units": "Pa", "valid_min": 0.0}) nc.define_2d_field("bc_mask", time_dependent=False, attrs={"long_name": "if =1, apply u_ssa_bc and v_ssa_bc as sliding velocity"}) nc.define_2d_field("u_ssa_bc", time_dependent=False, attrs={"long_name": "x-component of prescribed sliding velocity", "units": "m s-1"}) nc.define_2d_field("v_ssa_bc", time_dependent=False, attrs={"long_name": "y-component of prescribed sliding velocity", "units": "m s-1"}) Phi0 = 0.20 # 20 cm/year basal melt rate T_surface = 260 # ice surface temperature, K variables = {"topg": np.zeros_like(xx), "climatic_mass_balance": np.zeros_like(xx), "ice_surface_temp": np.ones_like(xx) + T_surface, "bmelt": np.zeros_like(xx) + Phi0, "thk": h, "bwat": W, "bwp": P, "bc_mask": np.ones_like(xx), "u_ssa_bc": ussa, "v_ssa_bc": vssa} for name in variables.keys(): nc.write(name, variables[name]) nc.history = subprocess.list2cmdline(argv) nc.close() stderr.write("NetCDF file %s written\n" % "inputforP.nc")
def vel_mosaic2netcdf(filename_base, output_filename): files = [] for (short_name, long_name) in [("vx", "ice surface velocity in the X direction"), ("vy", "ice surface velocity in the Y direction"), ("ex", "error estimates for the X-component of the ice surface velocity"), ("ey", "error estimates for the Y-component of the ice surface velocity"), ]: try: os.stat(filename_base + "." + short_name) entry = ("%s.%s" %(filename_base,short_name), short_name, long_name) files.append(entry) except: print "Missing %s.%s. If this file ends with ex or ey the script will work just fine" %(filename_base, short_name) grid = np.loadtxt(filename_base + ".vx.geodat", skiprows=1, comments="&") shape = (int(grid[0,1]), int(grid[0,0])) x0 = grid[2,0] * 1e3 y0 = grid[2,1] * 1e3 dx = grid[1,0] dy = grid[1,1] x1 = x0 + (shape[1] - 1) * dx y1 = y0 + (shape[0] - 1) * dx x = np.linspace(x0, x1, shape[1]) y = np.linspace(y0, y1, shape[0]) nc = NC("%s.nc" % output_filename, 'w') nc.create_dimensions(x, y) for (filename, short_name, long_name) in files: nc.define_2d_field(short_name, time_dependent = False, nc_type='f4', attrs = {"long_name" : long_name, "comment" : "Downloaded from %s" % (ftp_url + filename), "units" : "m / year", "mapping" : "mapping", "_FillValue" : -2e+9}) var = np.fromfile(filename, dtype=">f4", count=-1) nc.write_2d_field(short_name, var) # Add a mask that shows where observations are present if options.add_mask == True: nc.define_2d_field("vel_surface_mask", time_dependent = False, nc_type='i', attrs = {"long_name" : "Mask observations; 1 where surface vel. available", "comment" : "Used as vel_misfit_weight in inversion for tauc", "units" : "", "mapping" : "mapping", "_FillValue" : 0}) var = np.fromfile(filename_base + ".vx", dtype=">f4", count=-1) mask = var/var mask[var == -2e9] = 0. nc.write_2d_field("vel_surface_mask", mask) mapping = nc.createVariable("mapping", 'c') mapping.grid_mapping_name = "polar_stereographic" mapping.standard_parallel = 70.0 mapping.latitude_of_projection_origin = 90.0 mapping.straight_vertical_longitude_from_pole = -45.0 mapping.ellipsoid = "WGS84" nc.Conventions = "CF-1.4" nc.projection = "+proj=stere +ellps=WGS84 +datum=WGS84 +lon_0=-45 +lat_0=90 +lat_ts=70 +units=m" nc.reference = "Joughin, I., B. Smith, I. Howat, and T. Scambos. 2010. MEaSUREs Greenland Ice Velocity Map from InSAR Data. Boulder, Colorado, USA: National Snow and Ice Data Center. Digital media." nc.title = "MEaSUREs Greenland Ice Velocity Map from InSAR Data" from time import asctime import sys separator = ' ' historystr = "%s: %s\n" % (asctime(), separator.join(sys.argv)) nc.history = historystr nc.close()
elif options.antarctica: projection = "+lon_0=0.0 +ellps=WGS84 +datum=WGS84 +lat_ts=-71.0 +proj=stere +x_0=0.0 +units=m +y_0=0.0 +lat_0=-90.0" x = np.linspace(-2800000, 3195000, 41) y = np.linspace(-2800000, 3195000, 41) else: print "Please select --antarctica or --greenland." import sys sys.exit(1) p = Proj(projection) ee,nn = np.meshgrid(x,y) lon,lat = p(ee, nn, inverse=True) nc = NC(options.output[0], 'w') nc.create_dimensions(x, y, time_dependent = False) nc.define_2d_field("lon", attrs={"long_name" : "longitude", "standard_name" : "longitude", "units" : "degreesE"}) nc.define_2d_field("lat", attrs={"long_name" : "latitude", "standard_name" : "latitude", "units" : "degreesN"}) nc.write("lon", lon) nc.write("lat", lat)
def grid2netcdf(filename_base, output_filename): print "Reading txt files with data ..." x, y, topg, fill_value = readComposite("%sbottom.txt" % filename_base) x, y, thk, fill_value = readComposite("%sthickness.txt" % filename_base) x, y, usurf, fill_value = readComposite("%ssurface.txt" % filename_base) nc = NC("%s.nc" % output_filename, "w") nc.create_dimensions(x, y) names = [] for (short_name, long_name) in [ ("topg", "bedrock surface elevation"), ("thk", "land ice thickness"), ("usurf", "ice upper surface elevation"), ]: entry = (short_name, long_name) names.append(entry) var = [topg, thk, usurf] for i, (short_name, long_name) in enumerate(names): nc.define_2d_field( short_name, time_dependent=False, nc_type="f4", attrs={ "long_name": long_name, "comment": "Downloaded from ftp://data.cresis.ku.edu/data/grids/Jakobshavn_2006_2012_Composite.zip", "units": "m", "mapping": "mapping", "_FillValue": fill_value, }, ) nc.write_2d_field(short_name, var[i]) # Add a mask that shows where observations are present nc.define_2d_field( "obs_mask", time_dependent=False, nc_type="i", attrs={ "long_name": "Mask observations; 1 where observations available", "units": "", "mapping": "mapping", "_FillValue": 0, }, ) mask = np.ones(thk.shape) mask[thk == fill_value] = 0.0 nc.write_2d_field("obs_mask", mask) mapping = nc.createVariable("mapping", "c") mapping.grid_mapping_name = "polar_stereographic" mapping.standard_parallel = 70.0 mapping.latitude_of_projection_origin = 90.0 mapping.straight_vertical_longitude_from_pole = -45.0 mapping.ellipsoid = "WGS84" nc.Conventions = "CF-1.4" nc.projection = "+proj=stere +ellps=WGS84 +datum=WGS84 +lon_0=-45 +lat_0=90 +lat_ts=70 +units=m" nc.reference = "Gogineni, Prasad. 2012. CReSIS Radar Depth Sounder Data, Lawrence, Kansas, USA. Digital Media. http://data.cresis.ku.edu" nc.title = "CReSIS Gridded Depth Sounder Data for Jakobshavn, Greenland" nc.acknowledgement = "We acknowledge the use of data and/or data products from CReSIS generated with support from NSF grant ANT-0424589 and NASA grant NNX10AT68G" from time import asctime import sys separator = " " historystr = "%s: %s\n" % (asctime(), separator.join(sys.argv)) nc.history = historystr print "Done writing %s.nc ..." % output_filename nc.close() # Run nc2cdo to add lat/lon print "Adding lat/lon by running nc2cdo.py ..." os.system("nc2cdo.py %s.nc" % output_filename)