Skip to content

Instantly share code, notes, and snippets.

@MiCurry
Created May 18, 2021 00:50
Show Gist options
  • Save MiCurry/e5aaad6934c385ec08a4247d055adf2e to your computer and use it in GitHub Desktop.
Save MiCurry/e5aaad6934c385ec08a4247d055adf2e to your computer and use it in GitHub Desktop.
CAM-MPAS Topo Attributes
import os
import sys
import configparser
import argparse
from datetime import datetime
from netCDF4 import Dataset
# Add attributes to a topography file created by Peter's Topo Tool.
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('topo_file',
help='Topo file that needs attributes',
type=str)
parser.add_argument('-r', '--rename',
help="Rename 'ncols'to 'nCells'",
action='store_true',
default=False)
args = parser.parse_args()
topo_file = args.topo_file
rename = args.rename
mesh = Dataset(topo_file, 'r+')
if not os.path.isfile('./topoAtts.cfg'):
print("No topoAtts.cfg config file found - Please make one!")
sys.exit(-1)
if rename:
mesh.renameDimension('ncols', 'nCells')
# Read config file
config = configparser.ConfigParser()
config.read('./topoAtts.cfg')
# Determine the creation date of the file using the os
# NOTE: This may not work correctly on OSX
mod_time_s = os.stat(topo_file).st_mtime
# Convert to human readable datetime ... Thu Jun 25 hh:mm:ss MDT 2020
creation_date = datetime.fromtimestamp(mod_time_s).strftime("%a %b %d %H:%M:%S MDT %Y")
# From the config file, create a dictionary of attributes to be added to the NetCDF file using
# Dataset.setncatts()
atts = {
'data_title' : config['MetaData']['data_title'],
'data_summary' : config['MetaData']['data_summary'],
'data_creator' : config['MetaData']['data_creator'],
'creation_date' : creation_date,
'cesm_contact' : config['MetaData']['cesm_contact'],
'data_script' : config['MetaData']['data_script']
}
mesh.setncatts(atts)
mesh.close()
[MetaData]
data_title = CAM topography file
data_summary = Topography data (PHIS, SGH, SGH30, LANDFRAC) based on GMTED2020 elevation data and MOIDS land-water mask
data_creator = Peter Hjort Lauritzen, pel@ucar.edu
cesm_contact = Cecile Hanny
# The creation date will be created from the file's UNIX creation date
# creation_date = None
data_script = Makefile in https://github.com/NCAR/Topo.git
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment