from __future__ import print_function import os import sys import numpy as np import datetime as dt from netCDF4 import Dataset,chartostring ########################################### ## ## input file specified on the command line ## load the data into the numpy array ## if len(sys.argv) == 3: # Read the input file as the first argument input_file = os.path.expandvars(sys.argv[1]) var_name = sys.argv[2] try: # Print some output to verify that this script ran print("Input File: " + repr(input_file)) print("Variable: " + repr(var_name)) # Read input file f = Dataset(input_file, 'r') data = np.float64(f.variables[var_name][0,:,:]) met_data = data[::-1].copy() print("Data Shape: " + repr(met_data.shape)) print("Data Type: " + repr(met_data.dtype)) except NameError: print("Trouble reading data from input file") else: print("Must specify exactly one input file and variable name.") sys.exit(1) ########################################### ## ## create the metadata dictionary ## init = dt.datetime.strptime(getattr(f, "START_DATE"), "%Y-%m-%d_%H:%M:%S") valid_ref = dt.datetime.strptime(getattr(f.variables["time"], "units"), "hours since %Y-%m-%d %H:%M:%S") add_hours = float(f.variables["time"][:]) valid = valid_ref + dt.timedelta(hours=add_hours) lead, rem = divmod((valid-init).total_seconds(), 3600) if var_name == "PREC": accum = "01" else: accum = "00" Nx = len(f.dimensions["rlon"]) Ny = len(f.dimensions["rlat"]) if getattr(f, "POLE_LAT") > 0: hemi = 'N' else: hemi = 'S' attrs = { 'valid': valid.strftime("%Y%m%d_%H%M%S"), 'init': init.strftime("%Y%m%d_%H%M%S"), 'lead': str(int(lead)), 'accum': accum, 'name': var_name, 'long_name': str(getattr(f.variables[var_name], "long_name")), 'level': "SURFACE", 'units': str(getattr(f.variables[var_name], "units")), 'grid': { 'type' : "Lambert Conformal", 'name' : "WRF Domain", 'hemisphere' : hemi, 'scale_lat_1' : float(getattr(f, "TRUELAT1")), 'scale_lat_2' : float(getattr(f, "TRUELAT2")), 'lat_pin' : float(getattr(f, "CEN_LAT")), 'lon_pin' : float(getattr(f, "CEN_LON")), 'x_pin' : float(Nx/2), 'y_pin' : float(Ny/2), 'lon_orient' : float(getattr(f, "STAND_LON")), 'd_km' : getattr(f, "DX")/1000.0, 'r_km' : 6371.2, 'nx' : Nx, 'ny' : Ny, } } print("Attributes: " + repr(attrs))