0

I have downloaded imd yearly rainfall data, min temperature data and max temperature data of 1.0*1.0 resolution in NetCDF format from 2007 to 2018, and saved to a folder in my local drive. Directory path: "E:\\Lipsa(MTech)\\Final year project\\dataset\\imd gridded", folder names:"rain_netcdf", "max_temp_netcdf", "min_temp_netcdf", files names: "2007_rain.nc","2008_rain.nc", and so on, "2007_tmax.nc", "2008_tmax.nc", and so on, and "2007_tmin.nc", "2008_tmin.nc" and so on respectively. I also have the shapefile of india saved in directory: "E:\\Lipsa_data\\India_studyarea", with file names as: "India_Boundary.shp", "India_Boundary.prj" and other.

Now how can I use these data to calculate spei-1, spei-3, spei-6 and spei-12 for india using spei 0.3.3 package using python in spyder and save the spei values as both .csv and .nc format.

import os
import numpy as np
import pandas as pd
import xarray as xr
from spei import spei
from netCDF4 import Dataset
import shapefile as shp

os.chdir("E:\\Lipsa(MTech)\\Final year project\\dataset\\imd gridded")

rain_path = "rain_netcdf"
max_temp_path = "max_temp_netcdf"
min_temp_path = "min_temp_netcdf"
india_shape_path = "E:\\Lipsa_data\\India_studyarea\\India_Boundary.shp"

sf = shp.Reader(india_shape_path)

# Extract the boundary coordinates
shapes = sf.shapes()
boundary = shapes[0].bbox
min_lon, min_lat, max_lon, max_lat = boundary

# Define the coordinates for India
lon = np.arange(min_lon, max_lon + 1.0, 1.0)
lat = np.arange(max_lat, min_lat - 1.0, -1.0)


periods = [1, 2, 3, 6, 12] # Time periods for SPEI calculation

for year in range(2007, 2019):
    # Load the rainfall data
    rain_file = os.path.join(rain_path, str(year) + "_rain.nc")
    rain_data = Dataset(rain_file)
    rain = rain_data.variables['RAINFALL'][:]

    # Load the maximum temperature data
    max_temp_file = os.path.join(max_temp_path, str(year) + "_tmax.nc")
    max_temp_data = Dataset(max_temp_file)
    max_temp = max_temp_data.variables['tmax'][:]

    # Load the minimum temperature data
    min_temp_file = os.path.join(min_temp_path, str(year) + "_tmin.nc")
    min_temp_data = Dataset(min_temp_file)
    min_temp = min_temp_data.variables['tmin'][:]

    # Calculate the SPEI for each time period
    for p in periods:
        spei_values = spei(rain=rain, tmax=max_temp, tmin=min_temp, time_dim=None, 
        calibration_year_initial= None, calibration_year_final= None, fitting_params=None, 
        periodicity='monthly', distribution='Gamma', verbose=False)

        # Save the SPEI values as a CSV file
        spei_df = pd.DataFrame(spei_values, columns=['SPEI'])
        spei_df.to_csv(f'SPEI_{p}_{year}.csv', index=False)

        # Save the SPEI values as a netCDF file
        ds = xr.Dataset({'SPEI': (('lat', 'lon'), spei_values)},
                        coords={'lon': lon, 'lat': lat})
        ds.to_netcdf(f'SPEI_{p}_{year}.nc')
spei_values = spei(rain=rain, tmax=max_temp, tmin=min_temp, time_dim=None, calibration_year_initial= None, calibration_year_final= None, fitting_params=None, periodicity='monthly', distribution='Gamma', verbose=False)

Traceback (most recent call last):

Cell In[7], line 1
spei_values = spei(rain=rain, tmax=max_temp, tmin=min_temp, time_dim=None, calibration_year_initial= None, calibration_year_final= None, fitting_params=None, periodicity='monthly', distribution='Gamma', verbose=False)

TypeError: spei() got an unexpected keyword argument 'rain'

Can someone help me with the correct code for this?

1 Answer 1

2

Have you checked the function's documentation?

"""Method to compute the Standardized Precipitation Evaporation Index
[spei_2010]_.
Parameters
----------
series: pandas.Series
    Pandas time series of the precipitation. Time series index
    should be a pandas DatetimeIndex.
dist: scipy.stats.rv_continuous
    Can be any continuous distribution from the scipy.stats library.
    However, for the SPEI generally the log-logistic (fisk) probability
    density function is recommended. Other appropriate choices could be
    the lognormal or PearsonIII distribution.
Returns
-------
pandas.Series
References
----------
.. [spei_2010] Vicente-Serrano S.M., Beguería S., López-Moreno J.I.:
   A Multi-scalar drought index sensitive to global warming: The
   Standardized Precipitation Evapotranspiration Index.
   Journal of Climate, 23, 1696-1718, 2010.
"""

The error message is clear: 'rain' is not an argument, 'series', and 'dist' are. Looks like this SPI function is for weather stations while you are using gridded data. I suspect you called the wrong library

1
  • Thank you so much for the help. Mar 29, 2023 at 4:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.