from __future__ import print_function from netCDF4 import Dataset import numpy as np import datetime as dt import os import sys import math ########################################### ## ## 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 Name : " + repr(var_name)) # Read input file f = Dataset(input_file, 'r') # Read the requested variable data = np.float64(f.variables[var_name][:]) # Expect that dimensions are ordered (lat, lon) # If (lon, lat), transpose the data if(f.variables[var_name].dimensions[0] == 'lon'): data = data.transpose() # Reset any negative values to missing data (-9999 in MET) data[data<0] = -9999 # Flip data along the equator data = data[::-1] # Store a deep copy of the data for MET met_data = data.copy() print("Data Shape: " + repr(met_data.shape)) print("Data Type: " + repr(met_data.dtype)) except NameError: print("Trouble reading input file: " . input_file) else: print("Must specify exactly one input file and the variable name.") sys.exit(1) ########################################### # Function to parse time strings with or without microseconds def parse_dtg(time_str): try: time_val = dt.datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S.%fZ") except: time_val = dt.datetime.strptime(time_str, "%Y-%m-%d %H:%M:%SZ") return time_val ########################################### # Determine timing information from global attributes beg_time = parse_dtg(f.getncattr('BeginDate') + ' ' + f.getncattr('BeginTime')) end_time = parse_dtg(f.getncattr('EndDate') + ' ' + f.getncattr('EndTime')) valid_time = end_time init_time = valid_time accum_sec = math.ceil((end_time - beg_time).total_seconds()) accum_time = "%02d%02d%02d" % ((accum_sec/3600), (accum_sec%3600)/60, (accum_sec%60)) print("Begin Time =", beg_time) print("End Time =", end_time) print("Accum Time =",accum_time) # Determine LatLon grid information lat = np.float64(f.variables['lat'][:]) lon = np.float64(f.variables['lon'][:]) ########################################### ## ## create the metadata dictionary ## attrs = { 'valid': valid_time.strftime("%Y%m%d_%H%M%S"), 'init': valid_time.strftime("%Y%m%d_%H%M%S"), 'lead': '00', 'accum': accum_time, 'name': var_name, 'long_name': var_name, 'level': 'Surface', 'units': 'mm', 'grid': { 'name': '3B42-Grid', 'type' : 'LatLon', 'lat_ll' : min(lat), 'lon_ll' : min(lon), 'delta_lat' : lat[1]-lat[0], 'delta_lon' : lon[1]-lon[0], 'Nlat' : len(lat), 'Nlon' : len(lon), } } print("Attributes: " + repr(attrs))