NCAR / ctsm_python_gallery

A place to put sample workflows and tools that use ctsm model output
Apache License 2.0
18 stars 28 forks source link

import_case time slot issues for CLM and CESM #47

Open RuXu-geo opened 6 months ago

RuXu-geo commented 6 months ago

Hi, all I used the below code to read output from CLM and CESM, but I found sth wired. ds_exp = import_case(exp, myVars=variables, timeSlice=time_slice, alter_lons=True)

for CESM, the time slot seems correct image

for CLM, the time slot sees has 1 month misalignment image

wwieder commented 6 months ago

You're right this is an issue with how CLM timestamps are read by xarray. I'm fuzzy on the details, but something like this will overwrite your time array correctly. You can put this in a preprocess function so data are read in correctly.

    # quick fix to adjust time vector for monthly data        
    if freq=='monthly':
        nmonths = len(ds.time)
        yr0 = ds['time.year'][0].values
        ds['time'] =xr.cftime_range(str(yr0),periods=nmonths,freq='MS')

    return ds.sel(time=slice(str(firstyear),str(lastyear)))
RuXu-geo commented 6 months ago

You're right this is an issue with how CLM timestamps are read by xarray. I'm fuzzy on the details, but something like this will overwrite your time array correctly. You can put this in a preprocess function so data are read in correctly.

    # quick fix to adjust time vector for monthly data        
    if freq=='monthly':
        nmonths = len(ds.time)
        yr0 = ds['time.year'][0].values
        ds['time'] =xr.cftime_range(str(yr0),periods=nmonths,freq='MS')

    return ds.sel(time=slice(str(firstyear),str(lastyear)))

may be the same result as

attrs, encoding = ds.time.attrs.copy(), ds.time.encoding.copy()

time_bounds = ds.cf.get_bounds('time')

time_bounds_dim_name = ds.cf.get_bounds_dim_name('time')

ds = ds.assign_coords(time=time_bounds.mean(time_bounds_dim_name))

ds.time.attrs, ds.time.encoding = attrs, encoding

this code is also used to process CLM time slot issues