Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeError: Invalid value for attr 'freq’ When I save SPI-6 to nc files #1537

Closed
CGL5230 opened this issue Nov 24, 2023 · 2 comments
Closed
Assignees

Comments

@CGL5230
Copy link

CGL5230 commented Nov 24, 2023

Generic Issue

  • xclim version:0.46.0
  • Python version:3.11.0
  • Operating System:Linux

Description

I got thoes error When I try to save the SPI-6. By the way, I want to calculate the SPI-6 by the command, It's correct?
pr_AWI_CM_ssp585 is a daily dataset for Cmip6 model output including the 'pr' variable.

What I Did

AWI_CM_ssp585_SPI = xclim.indicators.atmos.standardized_precipitation_index(pr='pr',freq='MS',ds=pr_AWI_CM_ssp585,window=6)
AWI_CM_ssp585_SPI.to_netcdf('/home/cgl/workdir/AWI_CM_ssp585_SPI.nc')

What I Received

TypeError: Invalid value for attr 'freq': None. For serialization to netCDF files, its value must be of one of the following types: str, Number, ndarray, number, list, tuple
@coxipi coxipi self-assigned this Nov 24, 2023
@coxipi
Copy link
Contributor

coxipi commented Nov 24, 2023

Hi @CGL5230,

Thanks for reporting this. I confirm this bug, some attributes have values that are problematic when saving to netcdf. In the case of freq, it should not have been None in the first place, even if netcdf accepted this, so it's good to know, it's also a bookkeeping error. In the meantime, you can just replace all problematic values with an empty string. You can add this code between your two lines:

for k in AWI_CM_ssp585_SPI.attrs.keys():
    if AWI_CM_ssp585_SPI.attrs[k] is None or AWI_CM_ssp585_SPI.attrs[k] == {}:
        AWI_CM_ssp585_SPI.attrs[k] = ""

Specifically for freq, you can add back the value you used if that's useful for you, that is what the SPI function will do when it's repaired

AWI_CM_ssp585_SPI.attrs["freq"] = "MS"

Alternatively, if you save to zarr, there is no problem like this.

And yes, you have the correct code for SPI-6!

@CGL5230
Copy link
Author

CGL5230 commented Nov 25, 2023

Hi@coxipi ,
Thanks for quick reply. The solution is I save the value of the SPI-6 dataset to new variable. The suggestion you offer is great!

@CGL5230 CGL5230 closed this as completed Nov 25, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants