Extract Data from OpenDAP Dataset for multi dimensional variables

155 Views Asked by At

I am creating an API that would extract data from an ocean dataset

I am using netCDF4 python module to work with this data. There is a multi dimensional variable vozocrtx with input params time_counter, deptht, y, x.

As per the documentation if I want to extract data from the dataset for this particular variable I can do

import netCDF4
url = 'http://navigator.oceansdata.ca/thredds/dodsC/giops/daily/201806/giops_2018061300_024.nc'
dataset = netCDF4.Dataset(url)
variable = dataset.variables['vozocrtx']
extracted_data = variable[0:1:1,0:50:1,0:10:1,0:10:1]

However, what I want is to have a variable that contains the extraction and slicing indexes, something like

data_indexes = 0:1:1,0:50:1,0:10:1,0:10:1
extracted_data = variable[data_indexes]

The reason why I want to do is to create a generic function that would extract the data based on the input (start, end, and stride) * no. of dimensions.

I tried a few things and also read the document, but couldn't find anything helpful. Any hint or direction would be appreciated.

1

There are 1 best solutions below

0
On
#Step 1 - create a list of all the slices

list = []
list.append(np.s_[0:1:1])
list.append(np.s_[0:50:1])
list.append(np.s_[0:10:1])
list.append(np.s_[0:10:1])    

#Step 2 - convert the list to a tuple
tuple_slice = tuple(list)    

#Step 3 - use the tuple as the index input to extract the data
variable[tuple_slice]

Thanks to questions How can I create a slice object for Numpy array? and Store Numpy array index in variable I figured a solution to my problem.