ocf-data-sampler 0.0.24__py3-none-any.whl → 0.0.25__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of ocf-data-sampler might be problematic. Click here for more details.

@@ -2,100 +2,20 @@
2
2
 
3
3
  import numpy as np
4
4
  import pandas as pd
5
+ import pkg_resources
5
6
  import xarray as xr
6
7
  from torch.utils.data import Dataset
7
- import pkg_resources
8
-
9
- from ocf_data_sampler.load.gsp import open_gsp
10
- from ocf_data_sampler.load.nwp import open_nwp
11
- from ocf_data_sampler.load.satellite import open_sat_data
12
-
13
- from ocf_data_sampler.select.find_contiguous_time_periods import (
14
- find_contiguous_t0_periods, find_contiguous_t0_periods_nwp,
15
- intersection_of_multiple_dataframes_of_periods,
16
- )
17
- from ocf_data_sampler.select.fill_time_periods import fill_time_periods
18
- from ocf_data_sampler.select.select_time_slice import select_time_slice, select_time_slice_nwp
19
- from ocf_data_sampler.select.dropout import draw_dropout_time, apply_dropout_time
20
- from ocf_data_sampler.select.select_spatial_slice import select_spatial_slice_pixels
21
-
22
- from ocf_data_sampler.numpy_batch import (
23
- convert_gsp_to_numpy_batch,
24
- convert_nwp_to_numpy_batch,
25
- convert_satellite_to_numpy_batch,
26
- make_sun_position_numpy_batch,
27
- NWPBatchKey,
28
- GSPBatchKey,
29
- )
30
-
31
8
 
32
9
  from ocf_data_sampler.config import Configuration, load_yaml_configuration
33
-
34
- from ocf_data_sampler.select.location import Location
35
- from ocf_data_sampler.select.geospatial import osgb_to_lon_lat
36
-
37
- from ocf_data_sampler.constants import NWP_MEANS, NWP_STDS
38
-
39
-
40
-
10
+ from ocf_data_sampler.load.load_dataset import get_dataset_dict
11
+ from ocf_data_sampler.select import fill_time_periods, Location, slice_datasets_by_space, slice_datasets_by_time
12
+ from ocf_data_sampler.time_functions import minutes
13
+ from ocf_data_sampler.torch_datasets.process_and_combine import process_and_combine_datasets, compute
14
+ from ocf_data_sampler.torch_datasets.valid_time_periods import find_valid_time_periods
41
15
 
42
16
  xr.set_options(keep_attrs=True)
43
17
 
44
18
 
45
-
46
- def minutes(minutes: list[float]):
47
- """Timedelta minutes
48
-
49
- Args:
50
- m: minutes
51
- """
52
- return pd.to_timedelta(minutes, unit="m")
53
-
54
-
55
- def get_dataset_dict(config: Configuration) -> dict[xr.DataArray, dict[xr.DataArray]]:
56
- """Construct dictionary of all of the input data sources
57
-
58
- Args:
59
- config: Configuration file
60
- """
61
-
62
- in_config = config.input_data
63
-
64
- datasets_dict = {}
65
-
66
- # Load GSP data unless the path is None
67
- if in_config.gsp.gsp_zarr_path:
68
- da_gsp = open_gsp(zarr_path=in_config.gsp.gsp_zarr_path).compute()
69
-
70
- # Remove national GSP
71
- datasets_dict["gsp"] = da_gsp.sel(gsp_id=slice(1, None))
72
-
73
- # Load NWP data if in config
74
- if in_config.nwp:
75
-
76
- datasets_dict["nwp"] = {}
77
- for nwp_source, nwp_config in in_config.nwp.items():
78
-
79
- da_nwp = open_nwp(nwp_config.nwp_zarr_path, provider=nwp_config.nwp_provider)
80
-
81
- da_nwp = da_nwp.sel(channel=list(nwp_config.nwp_channels))
82
-
83
- datasets_dict["nwp"][nwp_source] = da_nwp
84
-
85
- # Load satellite data if in config
86
- if in_config.satellite:
87
- sat_config = config.input_data.satellite
88
-
89
- da_sat = open_sat_data(sat_config.satellite_zarr_path)
90
-
91
- da_sat = da_sat.sel(channel=list(sat_config.satellite_channels))
92
-
93
- datasets_dict["sat"] = da_sat
94
-
95
- return datasets_dict
96
-
97
-
98
-
99
19
  def find_valid_t0_times(
100
20
  datasets_dict: dict,
101
21
  config: Configuration,
@@ -103,96 +23,11 @@ def find_valid_t0_times(
103
23
  """Find the t0 times where all of the requested input data is available
104
24
 
105
25
  Args:
106
- datasets_dict: A dictionary of input datasets
26
+ datasets_dict: A dictionary of input datasets
107
27
  config: Configuration file
108
28
  """
109
29
 
110
- assert set(datasets_dict.keys()).issubset({"nwp", "sat", "gsp"})
111
-
112
- contiguous_time_periods: dict[str: pd.DataFrame] = {} # Used to store contiguous time periods from each data source
113
-
114
- if "nwp" in datasets_dict:
115
- for nwp_key, nwp_config in config.input_data.nwp.items():
116
-
117
- da = datasets_dict["nwp"][nwp_key]
118
-
119
- if nwp_config.dropout_timedeltas_minutes is None:
120
- max_dropout = minutes(0)
121
- else:
122
- max_dropout = minutes(np.max(np.abs(nwp_config.dropout_timedeltas_minutes)))
123
-
124
- if nwp_config.max_staleness_minutes is None:
125
- max_staleness = None
126
- else:
127
- max_staleness = minutes(nwp_config.max_staleness_minutes)
128
-
129
- # The last step of the forecast is lost if we have to diff channels
130
- if len(nwp_config.nwp_accum_channels) > 0:
131
- end_buffer = minutes(nwp_config.time_resolution_minutes)
132
- else:
133
- end_buffer = minutes(0)
134
-
135
- # This is the max staleness we can use considering the max step of the input data
136
- max_possible_staleness = (
137
- pd.Timedelta(da["step"].max().item())
138
- - minutes(nwp_config.forecast_minutes)
139
- - end_buffer
140
- )
141
-
142
- # Default to use max possible staleness unless specified in config
143
- if max_staleness is None:
144
- max_staleness = max_possible_staleness
145
- else:
146
- # Make sure the max acceptable staleness isn't longer than the max possible
147
- assert max_staleness <= max_possible_staleness
148
-
149
- time_periods = find_contiguous_t0_periods_nwp(
150
- datetimes=pd.DatetimeIndex(da["init_time_utc"]),
151
- history_duration=minutes(nwp_config.history_minutes),
152
- max_staleness=max_staleness,
153
- max_dropout=max_dropout,
154
- )
155
-
156
- contiguous_time_periods[f'nwp_{nwp_key}'] = time_periods
157
-
158
- if "sat" in datasets_dict:
159
- sat_config = config.input_data.satellite
160
-
161
- time_periods = find_contiguous_t0_periods(
162
- pd.DatetimeIndex(datasets_dict["sat"]["time_utc"]),
163
- sample_period_duration=minutes(sat_config.time_resolution_minutes),
164
- history_duration=minutes(sat_config.history_minutes),
165
- forecast_duration=minutes(sat_config.forecast_minutes),
166
- )
167
-
168
- contiguous_time_periods['sat'] = time_periods
169
-
170
- if "gsp" in datasets_dict:
171
- gsp_config = config.input_data.gsp
172
-
173
- time_periods = find_contiguous_t0_periods(
174
- pd.DatetimeIndex(datasets_dict["gsp"]["time_utc"]),
175
- sample_period_duration=minutes(gsp_config.time_resolution_minutes),
176
- history_duration=minutes(gsp_config.history_minutes),
177
- forecast_duration=minutes(gsp_config.forecast_minutes),
178
- )
179
-
180
- contiguous_time_periods['gsp'] = time_periods
181
-
182
- # just get the values (not the keys)
183
- contiguous_time_periods_values = list(contiguous_time_periods.values())
184
-
185
- # Find joint overlapping contiguous time periods
186
- if len(contiguous_time_periods_values) > 1:
187
- valid_time_periods = intersection_of_multiple_dataframes_of_periods(
188
- contiguous_time_periods_values
189
- )
190
- else:
191
- valid_time_periods = contiguous_time_periods_values[0]
192
-
193
- # check there are some valid time periods
194
- if len(valid_time_periods) == 0:
195
- raise ValueError(f"No valid time periods found, {contiguous_time_periods=}")
30
+ valid_time_periods = find_valid_time_periods(datasets_dict, config)
196
31
 
197
32
  # Fill out the contiguous time periods to get the t0 times
198
33
  valid_t0_times = fill_time_periods(
@@ -203,250 +38,6 @@ def find_valid_t0_times(
203
38
  return valid_t0_times
204
39
 
205
40
 
206
- def slice_datasets_by_space(
207
- datasets_dict: dict,
208
- location: Location,
209
- config: Configuration,
210
- ) -> dict:
211
- """Slice a dictionaries of input data sources around a given location
212
-
213
- Args:
214
- datasets_dict: Dictionary of the input data sources
215
- location: The location to sample around
216
- config: Configuration object.
217
- """
218
-
219
- assert set(datasets_dict.keys()).issubset({"nwp", "sat", "gsp"})
220
-
221
- sliced_datasets_dict = {}
222
-
223
- if "nwp" in datasets_dict:
224
-
225
- sliced_datasets_dict["nwp"] = {}
226
-
227
- for nwp_key, nwp_config in config.input_data.nwp.items():
228
-
229
- sliced_datasets_dict["nwp"][nwp_key] = select_spatial_slice_pixels(
230
- datasets_dict["nwp"][nwp_key],
231
- location,
232
- height_pixels=nwp_config.nwp_image_size_pixels_height,
233
- width_pixels=nwp_config.nwp_image_size_pixels_width,
234
- )
235
-
236
- if "sat" in datasets_dict:
237
- sat_config = config.input_data.satellite
238
-
239
- sliced_datasets_dict["sat"] = select_spatial_slice_pixels(
240
- datasets_dict["sat"],
241
- location,
242
- height_pixels=sat_config.satellite_image_size_pixels_height,
243
- width_pixels=sat_config.satellite_image_size_pixels_width,
244
- )
245
-
246
- if "gsp" in datasets_dict:
247
- sliced_datasets_dict["gsp"] = datasets_dict["gsp"].sel(gsp_id=location.id)
248
-
249
- return sliced_datasets_dict
250
-
251
-
252
- def slice_datasets_by_time(
253
- datasets_dict: dict,
254
- t0: pd.Timedelta,
255
- config: Configuration,
256
- ) -> dict:
257
- """Slice a dictionaries of input data sources around a given t0 time
258
-
259
- Args:
260
- datasets_dict: Dictionary of the input data sources
261
- t0: The init-time
262
- config: Configuration object.
263
- """
264
-
265
- sliced_datasets_dict = {}
266
-
267
- if "nwp" in datasets_dict:
268
-
269
- sliced_datasets_dict["nwp"] = {}
270
-
271
- for nwp_key, da_nwp in datasets_dict["nwp"].items():
272
-
273
- nwp_config = config.input_data.nwp[nwp_key]
274
-
275
- sliced_datasets_dict["nwp"][nwp_key] = select_time_slice_nwp(
276
- da_nwp,
277
- t0,
278
- sample_period_duration=minutes(nwp_config.time_resolution_minutes),
279
- history_duration=minutes(nwp_config.history_minutes),
280
- forecast_duration=minutes(nwp_config.forecast_minutes),
281
- dropout_timedeltas=minutes(nwp_config.dropout_timedeltas_minutes),
282
- dropout_frac=nwp_config.dropout_fraction,
283
- accum_channels=nwp_config.nwp_accum_channels,
284
- )
285
-
286
- if "sat" in datasets_dict:
287
-
288
- sat_config = config.input_data.satellite
289
-
290
- sliced_datasets_dict["sat"] = select_time_slice(
291
- datasets_dict["sat"],
292
- t0,
293
- sample_period_duration=minutes(sat_config.time_resolution_minutes),
294
- interval_start=minutes(-sat_config.history_minutes),
295
- interval_end=minutes(-sat_config.live_delay_minutes),
296
- max_steps_gap=2,
297
- )
298
-
299
- # Randomly sample dropout
300
- sat_dropout_time = draw_dropout_time(
301
- t0,
302
- dropout_timedeltas=minutes(sat_config.dropout_timedeltas_minutes),
303
- dropout_frac=sat_config.dropout_fraction,
304
- )
305
-
306
- # Apply the dropout
307
- sliced_datasets_dict["sat"] = apply_dropout_time(
308
- sliced_datasets_dict["sat"],
309
- sat_dropout_time,
310
- )
311
-
312
- if "gsp" in datasets_dict:
313
- gsp_config = config.input_data.gsp
314
-
315
- sliced_datasets_dict["gsp_future"] = select_time_slice(
316
- datasets_dict["gsp"],
317
- t0,
318
- sample_period_duration=minutes(gsp_config.time_resolution_minutes),
319
- interval_start=minutes(30),
320
- interval_end=minutes(gsp_config.forecast_minutes),
321
- )
322
-
323
- sliced_datasets_dict["gsp"] = select_time_slice(
324
- datasets_dict["gsp"],
325
- t0,
326
- sample_period_duration=minutes(gsp_config.time_resolution_minutes),
327
- interval_start=-minutes(gsp_config.history_minutes),
328
- interval_end=minutes(0),
329
- )
330
-
331
- # Dropout on the GSP, but not the future GSP
332
- gsp_dropout_time = draw_dropout_time(
333
- t0,
334
- dropout_timedeltas=minutes(gsp_config.dropout_timedeltas_minutes),
335
- dropout_frac=gsp_config.dropout_fraction,
336
- )
337
-
338
- sliced_datasets_dict["gsp"] = apply_dropout_time(sliced_datasets_dict["gsp"], gsp_dropout_time)
339
-
340
- return sliced_datasets_dict
341
-
342
-
343
- def fill_nans_in_arrays(batch: dict) -> dict:
344
- """Fills all NaN values in each np.ndarray in the batch dictionary with zeros.
345
-
346
- Operation is performed in-place on the batch.
347
- """
348
- for k, v in batch.items():
349
- if isinstance(v, np.ndarray) and np.issubdtype(v.dtype, np.number):
350
- if np.isnan(v).any():
351
- batch[k] = np.nan_to_num(v, copy=False, nan=0.0)
352
-
353
- # Recursion is included to reach NWP arrays in subdict
354
- elif isinstance(v, dict):
355
- fill_nans_in_arrays(v)
356
-
357
- return batch
358
-
359
-
360
-
361
- def merge_dicts(list_of_dicts: list[dict]) -> dict:
362
- """Merge a list of dictionaries into a single dictionary"""
363
- # TODO: This doesn't account for duplicate keys, which will be overwritten
364
- combined_dict = {}
365
- for d in list_of_dicts:
366
- combined_dict.update(d)
367
- return combined_dict
368
-
369
-
370
- def process_and_combine_datasets(
371
- dataset_dict: dict,
372
- config: Configuration,
373
- t0: pd.Timedelta,
374
- location: Location,
375
- ) -> dict:
376
- """Normalize and convert data to numpy arrays"""
377
-
378
- numpy_modalities = []
379
-
380
- if "nwp" in dataset_dict:
381
-
382
- nwp_numpy_modalities = dict()
383
-
384
- for nwp_key, da_nwp in dataset_dict["nwp"].items():
385
- # Standardise
386
- provider = config.input_data.nwp[nwp_key].nwp_provider
387
- da_nwp = (da_nwp - NWP_MEANS[provider]) / NWP_STDS[provider]
388
- # Convert to NumpyBatch
389
- nwp_numpy_modalities[nwp_key] = convert_nwp_to_numpy_batch(da_nwp)
390
-
391
- # Combine the NWPs into NumpyBatch
392
- numpy_modalities.append({NWPBatchKey.nwp: nwp_numpy_modalities})
393
-
394
- if "sat" in dataset_dict:
395
- # Satellite is already in the range [0-1] so no need to standardise
396
- da_sat = dataset_dict["sat"]
397
-
398
- # Convert to NumpyBatch
399
- numpy_modalities.append(convert_satellite_to_numpy_batch(da_sat))
400
-
401
- gsp_config = config.input_data.gsp
402
-
403
- if "gsp" in dataset_dict:
404
- da_gsp = xr.concat([dataset_dict["gsp"], dataset_dict["gsp_future"]], dim="time_utc")
405
- da_gsp = da_gsp / da_gsp.effective_capacity_mwp
406
-
407
- numpy_modalities.append(
408
- convert_gsp_to_numpy_batch(
409
- da_gsp,
410
- t0_idx=gsp_config.history_minutes / gsp_config.time_resolution_minutes
411
- )
412
- )
413
-
414
- # Make sun coords NumpyBatch
415
- datetimes = pd.date_range(
416
- t0-minutes(gsp_config.history_minutes),
417
- t0+minutes(gsp_config.forecast_minutes),
418
- freq=minutes(gsp_config.time_resolution_minutes),
419
- )
420
-
421
- lon, lat = osgb_to_lon_lat(location.x, location.y)
422
-
423
- numpy_modalities.append(make_sun_position_numpy_batch(datetimes, lon, lat))
424
-
425
- # Add coordinate data
426
- # TODO: Do we need all of these?
427
- numpy_modalities.append({
428
- GSPBatchKey.gsp_id: location.id,
429
- GSPBatchKey.x_osgb: location.x,
430
- GSPBatchKey.y_osgb: location.y,
431
- })
432
-
433
- # Combine all the modalities and fill NaNs
434
- combined_sample = merge_dicts(numpy_modalities)
435
- combined_sample = fill_nans_in_arrays(combined_sample)
436
-
437
- return combined_sample
438
-
439
-
440
- def compute(xarray_dict: dict) -> dict:
441
- """Eagerly load a nested dictionary of xarray DataArrays"""
442
- for k, v in xarray_dict.items():
443
- if isinstance(v, dict):
444
- xarray_dict[k] = compute(v)
445
- else:
446
- xarray_dict[k] = v.compute(scheduler="single-threaded")
447
- return xarray_dict
448
-
449
-
450
41
  def get_gsp_locations(gsp_ids: list[int] | None = None) -> list[Location]:
451
42
  """Get list of locations of all GSPs"""
452
43
 
@@ -473,7 +64,6 @@ def get_gsp_locations(gsp_ids: list[int] | None = None) -> list[Location]:
473
64
  return locations
474
65
 
475
66
 
476
-
477
67
  class PVNetUKRegionalDataset(Dataset):
478
68
  def __init__(
479
69
  self,
@@ -0,0 +1,196 @@
1
+ """Torch dataset for sites"""
2
+ import logging
3
+
4
+ import pandas as pd
5
+ import xarray as xr
6
+ from torch.utils.data import Dataset
7
+
8
+ from ocf_data_sampler.config import Configuration, load_yaml_configuration
9
+ from ocf_data_sampler.load.load_dataset import get_dataset_dict
10
+ from ocf_data_sampler.select import (
11
+ Location,
12
+ fill_time_periods,
13
+ find_contiguous_t0_periods,
14
+ intersection_of_multiple_dataframes_of_periods,
15
+ slice_datasets_by_time, slice_datasets_by_space
16
+ )
17
+ from ocf_data_sampler.time_functions import minutes
18
+ from ocf_data_sampler.torch_datasets.process_and_combine import process_and_combine_datasets, compute
19
+ from ocf_data_sampler.torch_datasets.valid_time_periods import find_valid_time_periods
20
+
21
+ xr.set_options(keep_attrs=True)
22
+
23
+
24
+ def find_valid_t0_and_site_ids(
25
+ datasets_dict: dict,
26
+ config: Configuration,
27
+ ) -> pd.DataFrame:
28
+ """Find the t0 times where all of the requested input data is available
29
+
30
+ The idea is to
31
+ 1. Get valid time period for nwp and satellite
32
+ 2. For each site location, find valid periods for that location
33
+
34
+ Args:
35
+ datasets_dict: A dictionary of input datasets
36
+ config: Configuration file
37
+ """
38
+
39
+ # 1. Get valid time period for nwp and satellite
40
+ datasets_nwp_and_sat_dict = {"nwp": datasets_dict["nwp"], "sat": datasets_dict["sat"]}
41
+ valid_time_periods = find_valid_time_periods(datasets_nwp_and_sat_dict, config)
42
+
43
+ # 2. Now lets loop over each location in system id and find the valid periods
44
+ # Should we have a different option if there are not nans
45
+ sites = datasets_dict["site"]
46
+ site_ids = sites.site_id.values
47
+ site_config = config.input_data.site
48
+ valid_t0_and_site_ids = []
49
+ for site_id in site_ids:
50
+ site = sites.sel(site_id=site_id)
51
+
52
+ # drop any nan values
53
+ # not sure this is right?
54
+ site = site.dropna(dim='time_utc')
55
+
56
+ # Get the valid time periods for this location
57
+ time_periods = find_contiguous_t0_periods(
58
+ pd.DatetimeIndex(site["time_utc"]),
59
+ sample_period_duration=minutes(site_config.time_resolution_minutes),
60
+ history_duration=minutes(site_config.history_minutes),
61
+ forecast_duration=minutes(site_config.forecast_minutes),
62
+ )
63
+ valid_time_periods_per_site = intersection_of_multiple_dataframes_of_periods(
64
+ [valid_time_periods, time_periods]
65
+ )
66
+
67
+ # Fill out the contiguous time periods to get the t0 times
68
+ valid_t0_times_per_site = fill_time_periods(
69
+ valid_time_periods_per_site,
70
+ freq=minutes(site_config.time_resolution_minutes)
71
+ )
72
+
73
+ valid_t0_per_site = pd.DataFrame(index=valid_t0_times_per_site)
74
+ valid_t0_per_site['site_id'] = site_id
75
+ valid_t0_and_site_ids.append(valid_t0_per_site)
76
+
77
+ valid_t0_and_site_ids = pd.concat(valid_t0_and_site_ids)
78
+ valid_t0_and_site_ids.index.name = 't0'
79
+ valid_t0_and_site_ids.reset_index(inplace=True)
80
+
81
+ return valid_t0_and_site_ids
82
+
83
+
84
+ def get_locations(site_xr: xr.Dataset):
85
+ """Get list of locations of all sites"""
86
+
87
+ locations = []
88
+ for site_id in site_xr.site_id.values:
89
+ site = site_xr.sel(site_id=site_id)
90
+ location = Location(
91
+ id=site_id,
92
+ x=site.longitude.values,
93
+ y=site.latitude.values,
94
+ coordinate_system="lon_lat"
95
+ )
96
+ locations.append(location)
97
+
98
+ return locations
99
+
100
+
101
+ class SitesDataset(Dataset):
102
+ def __init__(
103
+ self,
104
+ config_filename: str,
105
+ start_time: str | None = None,
106
+ end_time: str | None = None,
107
+ ):
108
+ """A torch Dataset for creating PVNet Site samples
109
+
110
+ Args:
111
+ config_filename: Path to the configuration file
112
+ start_time: Limit the init-times to be after this
113
+ end_time: Limit the init-times to be before this
114
+ """
115
+
116
+ config = load_yaml_configuration(config_filename)
117
+
118
+ datasets_dict = get_dataset_dict(config)
119
+
120
+ # get all locations
121
+ self.locations = get_locations(datasets_dict['site'])
122
+
123
+ # Get t0 times where all input data is available
124
+ valid_t0_and_site_ids = find_valid_t0_and_site_ids(datasets_dict, config)
125
+
126
+ # Filter t0 times to given range
127
+ if start_time is not None:
128
+ valid_t0_and_site_ids \
129
+ = valid_t0_and_site_ids[valid_t0_and_site_ids['t0'] >= pd.Timestamp(start_time)]
130
+
131
+ if end_time is not None:
132
+ valid_t0_and_site_ids \
133
+ = valid_t0_and_site_ids[valid_t0_and_site_ids['t0'] <= pd.Timestamp(end_time)]
134
+
135
+
136
+ # Assign coords and indices to self
137
+ self.valid_t0_and_site_ids = valid_t0_and_site_ids
138
+
139
+ # Assign config and input data to self
140
+ self.datasets_dict = datasets_dict
141
+ self.config = config
142
+
143
+ def __len__(self):
144
+ return len(self.valid_t0_and_site_ids)
145
+
146
+ def _get_sample(self, t0: pd.Timestamp, location: Location) -> dict:
147
+ """Generate the PVNet sample for given coordinates
148
+
149
+ Args:
150
+ t0: init-time for sample
151
+ location: location for sample
152
+ """
153
+ sample_dict = slice_datasets_by_space(self.datasets_dict, location, self.config)
154
+ sample_dict = slice_datasets_by_time(sample_dict, t0, self.config)
155
+ sample_dict = compute(sample_dict)
156
+
157
+ sample = process_and_combine_datasets(sample_dict, self.config, t0, location, sun_position_key='site')
158
+
159
+ return sample
160
+
161
+ def get_location_from_site_id(self, site_id):
162
+ """Get location from system id"""
163
+
164
+ locations = [loc for loc in self.locations if loc.id == site_id]
165
+ if len(locations) == 0:
166
+ raise ValueError(f"Location not found for site_id {site_id}")
167
+
168
+ if len(locations) > 1:
169
+ logging.warning(f"Multiple locations found for site_id {site_id}, but will take the first")
170
+
171
+ return locations[0]
172
+
173
+ def __getitem__(self, idx):
174
+
175
+ # Get the coordinates of the sample
176
+ t0, site_id = self.valid_t0_and_site_ids.iloc[idx]
177
+
178
+ # get location from site id
179
+ location = self.get_location_from_site_id(site_id)
180
+
181
+ # Generate the sample
182
+ return self._get_sample(t0, location)
183
+
184
+ def get_sample(self, t0: pd.Timestamp, site_id: int) -> dict:
185
+ """Generate a sample for a given site id and t0.
186
+
187
+ Useful for users to generate samples by t0 and site id
188
+
189
+ Args:
190
+ t0: init-time for sample
191
+ site_id: site id as int
192
+ """
193
+
194
+ location = self.get_location_from_site_id(site_id)
195
+
196
+ return self._get_sample(t0, location)