ocf-data-sampler 0.0.24__py3-none-any.whl → 0.0.26__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.

Files changed (28) hide show
  1. ocf_data_sampler/config/model.py +84 -87
  2. ocf_data_sampler/load/load_dataset.py +55 -0
  3. ocf_data_sampler/load/nwp/providers/ecmwf.py +5 -2
  4. ocf_data_sampler/load/site.py +30 -0
  5. ocf_data_sampler/numpy_batch/__init__.py +1 -0
  6. ocf_data_sampler/numpy_batch/site.py +29 -0
  7. ocf_data_sampler/select/__init__.py +8 -1
  8. ocf_data_sampler/select/dropout.py +2 -1
  9. ocf_data_sampler/select/geospatial.py +43 -1
  10. ocf_data_sampler/select/select_spatial_slice.py +8 -2
  11. ocf_data_sampler/select/spatial_slice_for_dataset.py +53 -0
  12. ocf_data_sampler/select/time_slice_for_dataset.py +124 -0
  13. ocf_data_sampler/time_functions.py +11 -0
  14. ocf_data_sampler/torch_datasets/process_and_combine.py +153 -0
  15. ocf_data_sampler/torch_datasets/pvnet_uk_regional.py +8 -418
  16. ocf_data_sampler/torch_datasets/site.py +196 -0
  17. ocf_data_sampler/torch_datasets/valid_time_periods.py +108 -0
  18. {ocf_data_sampler-0.0.24.dist-info → ocf_data_sampler-0.0.26.dist-info}/METADATA +1 -1
  19. {ocf_data_sampler-0.0.24.dist-info → ocf_data_sampler-0.0.26.dist-info}/RECORD +28 -16
  20. {ocf_data_sampler-0.0.24.dist-info → ocf_data_sampler-0.0.26.dist-info}/WHEEL +1 -1
  21. {ocf_data_sampler-0.0.24.dist-info → ocf_data_sampler-0.0.26.dist-info}/top_level.txt +1 -0
  22. scripts/refactor_site.py +50 -0
  23. tests/config/test_config.py +9 -6
  24. tests/conftest.py +62 -0
  25. tests/load/test_load_sites.py +14 -0
  26. tests/torch_datasets/test_pvnet_uk_regional.py +4 -4
  27. tests/torch_datasets/test_site.py +85 -0
  28. {ocf_data_sampler-0.0.24.dist-info → ocf_data_sampler-0.0.26.dist-info}/LICENSE +0 -0
@@ -14,7 +14,7 @@ import logging
14
14
  from typing import Dict, List, Optional
15
15
  from typing_extensions import Self
16
16
 
17
- from pydantic import BaseModel, Field, RootModel, field_validator, ValidationInfo, model_validator
17
+ from pydantic import BaseModel, Field, RootModel, field_validator, model_validator
18
18
  from ocf_data_sampler.constants import NWP_PROVIDERS
19
19
 
20
20
  logger = logging.getLogger(__name__)
@@ -34,27 +34,12 @@ class Base(BaseModel):
34
34
  class General(Base):
35
35
  """General pydantic model"""
36
36
 
37
- name: str = Field("example", description="The name of this configuration file.")
37
+ name: str = Field("example", description="The name of this configuration file")
38
38
  description: str = Field(
39
39
  "example configuration", description="Description of this configuration file"
40
40
  )
41
41
 
42
42
 
43
- class DataSourceMixin(Base):
44
- """Mixin class, to add forecast and history minutes"""
45
-
46
- forecast_minutes: int = Field(
47
- ...,
48
- ge=0,
49
- description="how many minutes to forecast in the future. ",
50
- )
51
- history_minutes: int = Field(
52
- ...,
53
- ge=0,
54
- description="how many historic minutes to use. ",
55
- )
56
-
57
-
58
43
  # noinspection PyMethodParameters
59
44
  class DropoutMixin(Base):
60
45
  """Mixin class, to add dropout minutes"""
@@ -65,7 +50,12 @@ class DropoutMixin(Base):
65
50
  "negative or zero.",
66
51
  )
67
52
 
68
- dropout_fraction: float = Field(0, description="Chance of dropout being applied to each sample")
53
+ dropout_fraction: float = Field(
54
+ default=0,
55
+ description="Chance of dropout being applied to each sample",
56
+ ge=0,
57
+ le=1,
58
+ )
69
59
 
70
60
  @field_validator("dropout_timedeltas_minutes")
71
61
  def dropout_timedeltas_minutes_negative(cls, v: List[int]) -> List[int]:
@@ -75,12 +65,6 @@ class DropoutMixin(Base):
75
65
  assert m <= 0, "Dropout timedeltas must be negative"
76
66
  return v
77
67
 
78
- @field_validator("dropout_fraction")
79
- def dropout_fraction_valid(cls, v: float) -> float:
80
- """Validate 'dropout_fraction'"""
81
- assert 0 <= v <= 1, "Dropout fraction must be between 0 and 1"
82
- return v
83
-
84
68
  @model_validator(mode="after")
85
69
  def dropout_instructions_consistent(self) -> Self:
86
70
  if self.dropout_fraction == 0:
@@ -93,36 +77,67 @@ class DropoutMixin(Base):
93
77
 
94
78
 
95
79
  # noinspection PyMethodParameters
96
- class TimeResolutionMixin(Base):
80
+ class TimeWindowMixin(Base):
97
81
  """Time resolution mix in"""
98
82
 
99
83
  time_resolution_minutes: int = Field(
100
84
  ...,
85
+ gt=0,
101
86
  description="The temporal resolution of the data in minutes",
102
87
  )
103
88
 
89
+ forecast_minutes: int = Field(
90
+ ...,
91
+ ge=0,
92
+ description="how many minutes to forecast in the future",
93
+ )
94
+ history_minutes: int = Field(
95
+ ...,
96
+ ge=0,
97
+ description="how many historic minutes to use",
98
+ )
104
99
 
105
- class Satellite(DataSourceMixin, TimeResolutionMixin, DropoutMixin):
106
- """Satellite configuration model"""
100
+ @field_validator("forecast_minutes")
101
+ def forecast_minutes_divide_by_time_resolution(cls, v, values) -> int:
102
+ if v % values.data["time_resolution_minutes"] != 0:
103
+ message = "Forecast duration must be divisible by time resolution"
104
+ logger.error(message)
105
+ raise Exception(message)
106
+ return v
107
107
 
108
- # Todo: remove 'satellite' from names
109
- satellite_zarr_path: str | tuple[str] | list[str] = Field(
108
+ @field_validator("history_minutes")
109
+ def history_minutes_divide_by_time_resolution(cls, v, values) -> int:
110
+ if v % values.data["time_resolution_minutes"] != 0:
111
+ message = "History duration must be divisible by time resolution"
112
+ logger.error(message)
113
+ raise Exception(message)
114
+ return v
115
+
116
+
117
+ class SpatialWindowMixin(Base):
118
+ """Mixin class, to add path and image size"""
119
+
120
+ image_size_pixels_height: int = Field(
110
121
  ...,
111
- description="The path or list of paths which hold the satellite zarr",
112
- )
113
- satellite_channels: list[str] = Field(
114
- ..., description="the satellite channels that are used"
122
+ description="The number of pixels of the height of the region of interest",
115
123
  )
116
- satellite_image_size_pixels_height: int = Field(
124
+
125
+ image_size_pixels_width: int = Field(
117
126
  ...,
118
- description="The number of pixels of the height of the region of interest"
119
- " for non-HRV satellite channels.",
127
+ description="The number of pixels of the width of the region of interest",
120
128
  )
121
129
 
122
- satellite_image_size_pixels_width: int = Field(
130
+
131
+ class Satellite(TimeWindowMixin, DropoutMixin, SpatialWindowMixin):
132
+ """Satellite configuration model"""
133
+
134
+ zarr_path: str | tuple[str] | list[str] = Field(
123
135
  ...,
124
- description="The number of pixels of the width of the region "
125
- "of interest for non-HRV satellite channels.",
136
+ description="The path or list of paths which hold the data zarr",
137
+ )
138
+
139
+ channels: list[str] = Field(
140
+ ..., description="the satellite channels that are used"
126
141
  )
127
142
 
128
143
  live_delay_minutes: int = Field(
@@ -131,21 +146,21 @@ class Satellite(DataSourceMixin, TimeResolutionMixin, DropoutMixin):
131
146
 
132
147
 
133
148
  # noinspection PyMethodParameters
134
- class NWP(DataSourceMixin, TimeResolutionMixin, DropoutMixin):
149
+ class NWP(TimeWindowMixin, DropoutMixin, SpatialWindowMixin):
135
150
  """NWP configuration model"""
136
-
137
- nwp_zarr_path: str | tuple[str] | list[str] = Field(
151
+
152
+ zarr_path: str | tuple[str] | list[str] = Field(
138
153
  ...,
139
- description="The path which holds the NWP zarr",
154
+ description="The path or list of paths which hold the data zarr",
140
155
  )
141
- nwp_channels: list[str] = Field(
156
+
157
+ channels: list[str] = Field(
142
158
  ..., description="the channels used in the nwp data"
143
159
  )
144
- nwp_accum_channels: list[str] = Field([], description="the nwp channels which need to be diffed")
145
- nwp_image_size_pixels_height: int = Field(..., description="The size of NWP spacial crop in pixels")
146
- nwp_image_size_pixels_width: int = Field(..., description="The size of NWP spacial crop in pixels")
147
160
 
148
- nwp_provider: str = Field(..., description="The provider of the NWP data")
161
+ provider: str = Field(..., description="The provider of the NWP data")
162
+
163
+ accum_channels: list[str] = Field([], description="the nwp channels which need to be diffed")
149
164
 
150
165
  max_staleness_minutes: Optional[int] = Field(
151
166
  None,
@@ -154,33 +169,15 @@ class NWP(DataSourceMixin, TimeResolutionMixin, DropoutMixin):
154
169
  " the maximum forecast horizon of the NWP and the requested forecast length.",
155
170
  )
156
171
 
157
-
158
- @field_validator("nwp_provider")
159
- def validate_nwp_provider(cls, v: str) -> str:
160
- """Validate 'nwp_provider'"""
172
+ @field_validator("provider")
173
+ def validate_provider(cls, v: str) -> str:
174
+ """Validate 'provider'"""
161
175
  if v.lower() not in NWP_PROVIDERS:
162
176
  message = f"NWP provider {v} is not in {NWP_PROVIDERS}"
163
177
  logger.warning(message)
164
178
  raise Exception(message)
165
179
  return v
166
180
 
167
- # Todo: put into time mixin when moving intervals there
168
- @field_validator("forecast_minutes")
169
- def forecast_minutes_divide_by_time_resolution(cls, v: int, info: ValidationInfo) -> int:
170
- if v % info.data["time_resolution_minutes"] != 0:
171
- message = "Forecast duration must be divisible by time resolution"
172
- logger.error(message)
173
- raise Exception(message)
174
- return v
175
-
176
- @field_validator("history_minutes")
177
- def history_minutes_divide_by_time_resolution(cls, v: int, info: ValidationInfo) -> int:
178
- if v % info.data["time_resolution_minutes"] != 0:
179
- message = "History duration must be divisible by time resolution"
180
- logger.error(message)
181
- raise Exception(message)
182
- return v
183
-
184
181
 
185
182
  class MultiNWP(RootModel):
186
183
  """Configuration for multiple NWPs"""
@@ -208,27 +205,26 @@ class MultiNWP(RootModel):
208
205
  return self.root.items()
209
206
 
210
207
 
211
- # noinspection PyMethodParameters
212
- class GSP(DataSourceMixin, TimeResolutionMixin, DropoutMixin):
208
+ class GSP(TimeWindowMixin, DropoutMixin):
213
209
  """GSP configuration model"""
214
210
 
215
- gsp_zarr_path: str = Field(..., description="The path which holds the GSP zarr")
211
+ zarr_path: str = Field(..., description="The path which holds the GSP zarr")
216
212
 
217
- @field_validator("forecast_minutes")
218
- def forecast_minutes_divide_by_time_resolution(cls, v: int, info: ValidationInfo) -> int:
219
- if v % info.data["time_resolution_minutes"] != 0:
220
- message = "Forecast duration must be divisible by time resolution"
221
- logger.error(message)
222
- raise Exception(message)
223
- return v
224
213
 
225
- @field_validator("history_minutes")
226
- def history_minutes_divide_by_time_resolution(cls, v: int, info: ValidationInfo) -> int:
227
- if v % info.data["time_resolution_minutes"] != 0:
228
- message = "History duration must be divisible by time resolution"
229
- logger.error(message)
230
- raise Exception(message)
231
- return v
214
+ class Site(TimeWindowMixin, DropoutMixin):
215
+ """Site configuration model"""
216
+
217
+ file_path: str = Field(
218
+ ...,
219
+ description="The NetCDF files holding the power timeseries.",
220
+ )
221
+ metadata_file_path: str = Field(
222
+ ...,
223
+ description="The CSV files describing power system",
224
+ )
225
+
226
+ # TODO validate the netcdf for sites
227
+ # TODO validate the csv for metadata
232
228
 
233
229
 
234
230
  # noinspection PyPep8Naming
@@ -240,10 +236,11 @@ class InputData(Base):
240
236
  satellite: Optional[Satellite] = None
241
237
  nwp: Optional[MultiNWP] = None
242
238
  gsp: Optional[GSP] = None
239
+ site: Optional[Site] = None
243
240
 
244
241
 
245
242
  class Configuration(Base):
246
243
  """Configuration model for the dataset"""
247
244
 
248
245
  general: General = General()
249
- input_data: InputData = InputData()
246
+ input_data: InputData = InputData()
@@ -0,0 +1,55 @@
1
+ """ Loads all data sources """
2
+ import xarray as xr
3
+
4
+ from ocf_data_sampler.config import Configuration
5
+ from ocf_data_sampler.load.gsp import open_gsp
6
+ from ocf_data_sampler.load.nwp import open_nwp
7
+ from ocf_data_sampler.load.satellite import open_sat_data
8
+ from ocf_data_sampler.load.site import open_site
9
+
10
+
11
+ def get_dataset_dict(config: Configuration) -> dict[str, dict[xr.DataArray]]:
12
+ """Construct dictionary of all of the input data sources
13
+
14
+ Args:
15
+ config: Configuration file
16
+ """
17
+
18
+ in_config = config.input_data
19
+
20
+ datasets_dict = {}
21
+
22
+ # Load GSP data unless the path is None
23
+ if in_config.gsp and in_config.gsp.zarr_path:
24
+ da_gsp = open_gsp(zarr_path=in_config.gsp.zarr_path).compute()
25
+
26
+ # Remove national GSP
27
+ datasets_dict["gsp"] = da_gsp.sel(gsp_id=slice(1, None))
28
+
29
+ # Load NWP data if in config
30
+ if in_config.nwp:
31
+
32
+ datasets_dict["nwp"] = {}
33
+ for nwp_source, nwp_config in in_config.nwp.items():
34
+
35
+ da_nwp = open_nwp(nwp_config.zarr_path, provider=nwp_config.provider)
36
+
37
+ da_nwp = da_nwp.sel(channel=list(nwp_config.channels))
38
+
39
+ datasets_dict["nwp"][nwp_source] = da_nwp
40
+
41
+ # Load satellite data if in config
42
+ if in_config.satellite:
43
+ sat_config = config.input_data.satellite
44
+
45
+ da_sat = open_sat_data(sat_config.zarr_path)
46
+
47
+ da_sat = da_sat.sel(channel=list(sat_config.channels))
48
+
49
+ datasets_dict["sat"] = da_sat
50
+
51
+ if in_config.site:
52
+ da_sites = open_site(in_config.site)
53
+ datasets_dict["site"] = da_sites
54
+
55
+ return datasets_dict
@@ -9,7 +9,6 @@ from ocf_data_sampler.load.utils import (
9
9
  )
10
10
 
11
11
 
12
-
13
12
  def open_ifs(zarr_path: Path | str | list[Path] | list[str]) -> xr.DataArray:
14
13
  """
15
14
  Opens the ECMWF IFS NWP data
@@ -27,10 +26,14 @@ def open_ifs(zarr_path: Path | str | list[Path] | list[str]) -> xr.DataArray:
27
26
  ds = ds.rename(
28
27
  {
29
28
  "init_time": "init_time_utc",
30
- "variable": "channel",
31
29
  }
32
30
  )
33
31
 
32
+ # LEGACY SUPPORT
33
+ # rename variable to channel if it exists
34
+ if "variable" in ds:
35
+ ds = ds.rename({"variable": "channel"})
36
+
34
37
  # Check the timestamps are unique and increasing
35
38
  check_time_unique_increasing(ds.init_time_utc)
36
39
 
@@ -0,0 +1,30 @@
1
+ import pandas as pd
2
+ import xarray as xr
3
+ import numpy as np
4
+
5
+ from ocf_data_sampler.config.model import Site
6
+
7
+
8
+ def open_site(sites_config: Site) -> xr.DataArray:
9
+
10
+ # Load site generation xr.Dataset
11
+ data_ds = xr.open_dataset(sites_config.file_path)
12
+
13
+ # Load site generation data
14
+ metadata_df = pd.read_csv(sites_config.metadata_file_path, index_col="site_id")
15
+
16
+ # Add coordinates
17
+ ds = data_ds.assign_coords(
18
+ latitude=(metadata_df.latitude.to_xarray()),
19
+ longitude=(metadata_df.longitude.to_xarray()),
20
+ capacity_kwp=data_ds.capacity_kwp,
21
+ )
22
+
23
+ # Sanity checks
24
+ assert np.isfinite(data_ds.capacity_kwp.values).all()
25
+ assert (data_ds.capacity_kwp.values > 0).all()
26
+ assert metadata_df.index.is_unique
27
+
28
+ return ds.generation_kw
29
+
30
+
@@ -4,4 +4,5 @@ from .gsp import convert_gsp_to_numpy_batch, GSPBatchKey
4
4
  from .nwp import convert_nwp_to_numpy_batch, NWPBatchKey
5
5
  from .satellite import convert_satellite_to_numpy_batch, SatelliteBatchKey
6
6
  from .sun_position import make_sun_position_numpy_batch
7
+ from .site import convert_site_to_numpy_batch
7
8
 
@@ -0,0 +1,29 @@
1
+ """Convert site to Numpy Batch"""
2
+
3
+ import xarray as xr
4
+
5
+
6
+ class SiteBatchKey:
7
+
8
+ generation = "site"
9
+ site_capacity_kwp = "site_capacity_kwp"
10
+ site_time_utc = "site_time_utc"
11
+ site_t0_idx = "site_t0_idx"
12
+ site_solar_azimuth = "site_solar_azimuth"
13
+ site_solar_elevation = "site_solar_elevation"
14
+ site_id = "site_id"
15
+
16
+
17
+ def convert_site_to_numpy_batch(da: xr.DataArray, t0_idx: int | None = None) -> dict:
18
+ """Convert from Xarray to NumpyBatch"""
19
+
20
+ example = {
21
+ SiteBatchKey.generation: da.values,
22
+ SiteBatchKey.site_capacity_kwp: da.isel(time_utc=0)["capacity_kwp"].values,
23
+ SiteBatchKey.site_time_utc: da["time_utc"].values.astype(float),
24
+ }
25
+
26
+ if t0_idx is not None:
27
+ example[SiteBatchKey.site_t0_idx] = t0_idx
28
+
29
+ return example
@@ -1 +1,8 @@
1
-
1
+ from .fill_time_periods import fill_time_periods
2
+ from .find_contiguous_time_periods import (
3
+ find_contiguous_t0_periods,
4
+ intersection_of_multiple_dataframes_of_periods,
5
+ )
6
+ from .location import Location
7
+ from .spatial_slice_for_dataset import slice_datasets_by_space
8
+ from .time_slice_for_dataset import slice_datasets_by_time
@@ -1,3 +1,4 @@
1
+ """ Functions for simulating dropout in time series data """
1
2
  import numpy as np
2
3
  import pandas as pd
3
4
  import xarray as xr
@@ -5,7 +6,7 @@ import xarray as xr
5
6
 
6
7
  def draw_dropout_time(
7
8
  t0: pd.Timestamp,
8
- dropout_timedeltas: list[pd.Timedelta] | None,
9
+ dropout_timedeltas: list[pd.Timedelta] | pd.Timedelta | None,
9
10
  dropout_frac: float = 0,
10
11
  ):
11
12
 
@@ -55,6 +55,23 @@ def lon_lat_to_osgb(
55
55
  return _lon_lat_to_osgb(xx=x, yy=y)
56
56
 
57
57
 
58
+ def lon_lat_to_geostationary_area_coords(
59
+ longitude: Union[Number, np.ndarray],
60
+ latitude: Union[Number, np.ndarray],
61
+ xr_data: xr.DataArray,
62
+ ) -> tuple[Union[Number, np.ndarray], Union[Number, np.ndarray]]:
63
+ """Loads geostationary area and transformation from lat-lon to geostationary coords
64
+
65
+ Args:
66
+ longitude: longitude
67
+ latitude: latitude
68
+ xr_data: xarray object with geostationary area
69
+
70
+ Returns:
71
+ Geostationary coords: x, y
72
+ """
73
+ return coordinates_to_geostationary_area_coords(longitude, latitude, xr_data, WGS84)
74
+
58
75
  def osgb_to_geostationary_area_coords(
59
76
  x: Union[Number, np.ndarray],
60
77
  y: Union[Number, np.ndarray],
@@ -70,6 +87,31 @@ def osgb_to_geostationary_area_coords(
70
87
  Returns:
71
88
  Geostationary coords: x, y
72
89
  """
90
+
91
+ return coordinates_to_geostationary_area_coords(x, y, xr_data, OSGB36)
92
+
93
+
94
+
95
+ def coordinates_to_geostationary_area_coords(
96
+ x: Union[Number, np.ndarray],
97
+ y: Union[Number, np.ndarray],
98
+ xr_data: xr.DataArray,
99
+ crs_from: int
100
+ ) -> tuple[Union[Number, np.ndarray], Union[Number, np.ndarray]]:
101
+ """Loads geostationary area and transformation from respective coordiates to geostationary coords
102
+
103
+ Args:
104
+ x: osgb east-west, or latitude
105
+ y: osgb north-south, or longitude
106
+ xr_data: xarray object with geostationary area
107
+ crs_from: the cordiates system of x,y
108
+
109
+ Returns:
110
+ Geostationary coords: x, y
111
+ """
112
+
113
+ assert crs_from in [OSGB36, WGS84], f"Unrecognized coordinate system: {crs_from}"
114
+
73
115
  # Only load these if using geostationary projection
74
116
  import pyresample
75
117
 
@@ -80,7 +122,7 @@ def osgb_to_geostationary_area_coords(
80
122
  )
81
123
  geostationary_crs = geostationary_area_definition.crs
82
124
  osgb_to_geostationary = pyproj.Transformer.from_crs(
83
- crs_from=OSGB36, crs_to=geostationary_crs, always_xy=True
125
+ crs_from=crs_from, crs_to=geostationary_crs, always_xy=True
84
126
  ).transform
85
127
  return osgb_to_geostationary(xx=x, yy=y)
86
128
 
@@ -8,6 +8,7 @@ import xarray as xr
8
8
  from ocf_data_sampler.select.location import Location
9
9
  from ocf_data_sampler.select.geospatial import (
10
10
  lon_lat_to_osgb,
11
+ lon_lat_to_geostationary_area_coords,
11
12
  osgb_to_geostationary_area_coords,
12
13
  osgb_to_lon_lat,
13
14
  spatial_coord_type,
@@ -101,7 +102,7 @@ def _get_idx_of_pixel_closest_to_poi(
101
102
 
102
103
  def _get_idx_of_pixel_closest_to_poi_geostationary(
103
104
  da: xr.DataArray,
104
- center_osgb: Location,
105
+ center: Location,
105
106
  ) -> Location:
106
107
  """
107
108
  Return x and y index location of pixel at center of region of interest.
@@ -116,7 +117,12 @@ def _get_idx_of_pixel_closest_to_poi_geostationary(
116
117
 
117
118
  _, x_dim, y_dim = spatial_coord_type(da)
118
119
 
119
- x, y = osgb_to_geostationary_area_coords(x=center_osgb.x, y=center_osgb.y, xr_data=da)
120
+ if center.coordinate_system == 'osgb':
121
+ x, y = osgb_to_geostationary_area_coords(x=center.x, y=center.y, xr_data=da)
122
+ elif center.coordinate_system == 'lon_lat':
123
+ x, y = lon_lat_to_geostationary_area_coords(longitude=center.x, latitude=center.y, xr_data=da)
124
+ else:
125
+ x,y = center.x, center.y
120
126
  center_geostationary = Location(x=x, y=y, coordinate_system="geostationary")
121
127
 
122
128
  # Check that the requested point lies within the data
@@ -0,0 +1,53 @@
1
+ """ Functions for selecting data around a given location """
2
+ from ocf_data_sampler.config import Configuration
3
+ from ocf_data_sampler.select.location import Location
4
+ from ocf_data_sampler.select.select_spatial_slice import select_spatial_slice_pixels
5
+
6
+
7
+ def slice_datasets_by_space(
8
+ datasets_dict: dict,
9
+ location: Location,
10
+ config: Configuration,
11
+ ) -> dict:
12
+ """Slice the dictionary of input data sources around a given location
13
+
14
+ Args:
15
+ datasets_dict: Dictionary of the input data sources
16
+ location: The location to sample around
17
+ config: Configuration object.
18
+ """
19
+
20
+ assert set(datasets_dict.keys()).issubset({"nwp", "sat", "gsp", "site"})
21
+
22
+ sliced_datasets_dict = {}
23
+
24
+ if "nwp" in datasets_dict:
25
+
26
+ sliced_datasets_dict["nwp"] = {}
27
+
28
+ for nwp_key, nwp_config in config.input_data.nwp.items():
29
+
30
+ sliced_datasets_dict["nwp"][nwp_key] = select_spatial_slice_pixels(
31
+ datasets_dict["nwp"][nwp_key],
32
+ location,
33
+ height_pixels=nwp_config.image_size_pixels_height,
34
+ width_pixels=nwp_config.image_size_pixels_width,
35
+ )
36
+
37
+ if "sat" in datasets_dict:
38
+ sat_config = config.input_data.satellite
39
+
40
+ sliced_datasets_dict["sat"] = select_spatial_slice_pixels(
41
+ datasets_dict["sat"],
42
+ location,
43
+ height_pixels=sat_config.image_size_pixels_height,
44
+ width_pixels=sat_config.image_size_pixels_width,
45
+ )
46
+
47
+ if "gsp" in datasets_dict:
48
+ sliced_datasets_dict["gsp"] = datasets_dict["gsp"].sel(gsp_id=location.id)
49
+
50
+ if "site" in datasets_dict:
51
+ sliced_datasets_dict["site"] = datasets_dict["site"].sel(site_id=location.id)
52
+
53
+ return sliced_datasets_dict