I’m currently working on a script that was given to my company to work with NetCDF files but I’m lost on a few parts that I’m unable to clear up with the original writer of the script as they are no longer around. I’m fairly new to both Python and NetCDF so this is a learning experience but I’m starting to hit a road block.
Here is the script I’m currently using:
#!/user/bin/env ipython
# -*- coding: UTF-8 -*-
# This script is used to adapt LIS-NOAHMP-HYMAP model data for use in Visual Weather.
# Use it as a processing program in a appropriate input channel. No extra arguments are required.
# A sample of NetCDF configuration is attached at the end.
import shutil
import numpy as np
import netCDF4
import sys
if len(sys.argv) != 3:
print("Converter for LIS-NOAHMP-HYMAP model datan Args: input.nc output.nc")
exit(131)
infilename = sys.argv[1]
outfilename = sys.argv[2]
shutil.copy(infilename,outfilename)
ds= netCDF4.Dataset(outfilename,'r+')
print("Dataset: ", str(ds))
# Check variables and attributes?
for name, variable in ds.variables.items():
print("Name: {} --- Var: {}".format(name, variable)
for attrname in variable.ncattrs():
print("Var: {} --- Attr: {}".format(attrname, getattr(variable, attrname)))
cval= ds.SOIL_LAYER_THICKNESS
print("CVal: ", str(cval))
for coord in ['SoilMoist_profiles','SoilTemp_profiles','SmLiqFrac_profiles','RelSMC_profiles']: #these are dimensions in the file
# Create the vertical coordinate variable
print("Coord: ", str(coord))
cvar= ds.createVariable(coord, np.float32, (coord,) )
print("cvar: ", str(cvar))
assert( len(cvar) == len(cval) )
cvar[:]=cval
cvar.units='cm' #Thicknesses are in cm.
cvar.positive='down'
print("cvar post: ", str(cvar))
ds.close()
exit(0)
The print statements are mine checking the data through each step to understand what is happening. The issue I’m running into is the line
cval = ds.SOIL_LAYER_THICKNESS
It always returns and attribute error for one not existing. That is somewhat expected as this was an example script and needs to be worked to our needs, but I cannot seem to understand what I should be placing here instead of SOIL_LAYER_THICKNESS. When I look at the dataset print statement, I do see that SOIL_LAYER_THICKNESS is inside of the dataset but can’t be accessed or something? Or do I need to use a different method from netCDF4 to pull this in. It seems to only exist to assert and then to be used to assign but beyond that I don’t know what it exists for.
I can put in the dataset and variable outputs from the print statements if that would help.
I have been scouring through netCDF4 api documentation as well as other answers on here but can’t seem to figure anything out. I have tried using Qs_tavg instead as I know that variable exists within the file I’m using currently but it also returns an error at the same line.