data_utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. # Copyright 2023 DeepMind Technologies Limited.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS-IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Dataset utilities."""
  15. from typing import Any, Mapping, Sequence, Tuple, Union
  16. import numpy as np
  17. import pandas as pd
  18. import xarray
  19. TimedeltaLike = Any # Something convertible to pd.Timedelta.
  20. TimedeltaStr = str # A string convertible to pd.Timedelta.
  21. TargetLeadTimes = Union[
  22. TimedeltaLike,
  23. Sequence[TimedeltaLike],
  24. slice # with TimedeltaLike as its start and stop.
  25. ]
  26. _SEC_PER_HOUR = 3600
  27. _HOUR_PER_DAY = 24
  28. SEC_PER_DAY = _SEC_PER_HOUR * _HOUR_PER_DAY
  29. _AVG_DAY_PER_YEAR = 365.24219
  30. AVG_SEC_PER_YEAR = SEC_PER_DAY * _AVG_DAY_PER_YEAR
  31. DAY_PROGRESS = "day_progress"
  32. YEAR_PROGRESS = "year_progress"
  33. def get_year_progress(seconds_since_epoch: np.ndarray) -> np.ndarray:
  34. """Computes year progress for times in seconds.
  35. Args:
  36. seconds_since_epoch: Times in seconds since the "epoch" (the point at which
  37. UNIX time starts).
  38. Returns:
  39. Year progress normalized to be in the [0, 1) interval for each time point.
  40. """
  41. # Start with the pure integer division, and then float at the very end.
  42. # We will try to keep as much precision as possible.
  43. years_since_epoch = (
  44. seconds_since_epoch / SEC_PER_DAY / np.float64(_AVG_DAY_PER_YEAR)
  45. )
  46. # Note depending on how these ops are down, we may end up with a "weak_type"
  47. # which can cause issues in subtle ways, and hard to track here.
  48. # In any case, casting to float32 should get rid of the weak type.
  49. # [0, 1.) Interval.
  50. return np.mod(years_since_epoch, 1.0).astype(np.float32)
  51. def get_day_progress(
  52. seconds_since_epoch: np.ndarray,
  53. longitude: np.ndarray,
  54. ) -> np.ndarray:
  55. """Computes day progress for times in seconds at each longitude.
  56. Args:
  57. seconds_since_epoch: 1D array of times in seconds since the 'epoch' (the
  58. point at which UNIX time starts).
  59. longitude: 1D array of longitudes at which day progress is computed.
  60. Returns:
  61. 2D array of day progress values normalized to be in the [0, 1) inverval
  62. for each time point at each longitude.
  63. """
  64. # [0.0, 1.0) Interval.
  65. day_progress_greenwich = (
  66. np.mod(seconds_since_epoch, SEC_PER_DAY) / SEC_PER_DAY
  67. )
  68. # Offset the day progress to the longitude of each point on Earth.
  69. longitude_offsets = np.deg2rad(longitude) / (2 * np.pi)
  70. day_progress = np.mod(
  71. day_progress_greenwich[..., np.newaxis] + longitude_offsets, 1.0
  72. )
  73. return day_progress.astype(np.float32)
  74. def featurize_progress(
  75. name: str, dims: Sequence[str], progress: np.ndarray
  76. ) -> Mapping[str, xarray.Variable]:
  77. """Derives features used by ML models from the `progress` variable.
  78. Args:
  79. name: Base variable name from which features are derived.
  80. dims: List of the output feature dimensions, e.g. ("day", "lon").
  81. progress: Progress variable values.
  82. Returns:
  83. Dictionary of xarray variables derived from the `progress` values. It
  84. includes the original `progress` variable along with its sin and cos
  85. transformations.
  86. Raises:
  87. ValueError if the number of feature dimensions is not equal to the number
  88. of data dimensions.
  89. """
  90. if len(dims) != progress.ndim:
  91. raise ValueError(
  92. f"Number of feature dimensions ({len(dims)}) must be equal to the"
  93. f" number of data dimensions: {progress.ndim}."
  94. )
  95. progress_phase = progress * (2 * np.pi)
  96. return {
  97. name: xarray.Variable(dims, progress),
  98. name + "_sin": xarray.Variable(dims, np.sin(progress_phase)),
  99. name + "_cos": xarray.Variable(dims, np.cos(progress_phase)),
  100. }
  101. def add_derived_vars(data: xarray.Dataset) -> None:
  102. """Adds year and day progress features to `data` in place.
  103. NOTE: `toa_incident_solar_radiation` needs to be computed in this function
  104. as well.
  105. Args:
  106. data: Xarray dataset to which derived features will be added.
  107. Raises:
  108. ValueError if `datetime` or `lon` are not in `data` coordinates.
  109. """
  110. for coord in ("datetime", "lon"):
  111. if coord not in data.coords:
  112. raise ValueError(f"'{coord}' must be in `data` coordinates.")
  113. # Compute seconds since epoch.
  114. # Note `data.coords["datetime"].astype("datetime64[s]").astype(np.int64)`
  115. # does not work as xarrays always cast dates into nanoseconds!
  116. seconds_since_epoch = (
  117. data.coords["datetime"].data.astype("datetime64[s]").astype(np.int64)
  118. )
  119. batch_dim = ("batch",) if "batch" in data.dims else ()
  120. # Add year progress features.
  121. year_progress = get_year_progress(seconds_since_epoch)
  122. data.update(
  123. featurize_progress(
  124. name=YEAR_PROGRESS, dims=batch_dim + ("time",), progress=year_progress
  125. )
  126. )
  127. # Add day progress features.
  128. longitude_coord = data.coords["lon"]
  129. day_progress = get_day_progress(seconds_since_epoch, longitude_coord.data)
  130. data.update(
  131. featurize_progress(
  132. name=DAY_PROGRESS,
  133. dims=batch_dim + ("time",) + longitude_coord.dims,
  134. progress=day_progress,
  135. )
  136. )
  137. def extract_input_target_times(
  138. dataset: xarray.Dataset,
  139. input_duration: TimedeltaLike,
  140. target_lead_times: TargetLeadTimes,
  141. ) -> Tuple[xarray.Dataset, xarray.Dataset]:
  142. """Extracts inputs and targets for prediction, from a Dataset with a time dim.
  143. The input period is assumed to be contiguous (specified by a duration), but
  144. the targets can be a list of arbitrary lead times.
  145. Examples:
  146. # Use 18 hours of data as inputs, and two specific lead times as targets:
  147. # 3 days and 5 days after the final input.
  148. extract_inputs_targets(
  149. dataset,
  150. input_duration='18h',
  151. target_lead_times=('3d', '5d')
  152. )
  153. # Use 1 day of data as input, and all lead times between 6 hours and
  154. # 24 hours inclusive as targets. Demonstrates a friendlier supported string
  155. # syntax.
  156. extract_inputs_targets(
  157. dataset,
  158. input_duration='1 day',
  159. target_lead_times=slice('6 hours', '24 hours')
  160. )
  161. # Just use a single target lead time of 3 days:
  162. extract_inputs_targets(
  163. dataset,
  164. input_duration='24h',
  165. target_lead_times='3d'
  166. )
  167. Args:
  168. dataset: An xarray.Dataset with a 'time' dimension whose coordinates are
  169. timedeltas. It's assumed that the time coordinates have a fixed offset /
  170. time resolution, and that the input_duration and target_lead_times are
  171. multiples of this.
  172. input_duration: pandas.Timedelta or something convertible to it (e.g. a
  173. shorthand string like '6h' or '5d12h').
  174. target_lead_times: Either a single lead time, a slice with start and stop
  175. (inclusive) lead times, or a sequence of lead times. Lead times should be
  176. Timedeltas (or something convertible to). They are given relative to the
  177. final input timestep, and should be positive.
  178. Returns:
  179. inputs:
  180. targets:
  181. Two datasets with the same shape as the input dataset except that a
  182. selection has been made from the time axis, and the origin of the
  183. time coordinate will be shifted to refer to lead times relative to the
  184. final input timestep. So for inputs the times will end at lead time 0,
  185. for targets the time coordinates will refer to the lead times requested.
  186. """
  187. (target_lead_times, target_duration
  188. ) = _process_target_lead_times_and_get_duration(target_lead_times)
  189. # Shift the coordinates for the time axis so that a timedelta of zero
  190. # corresponds to the forecast reference time. That is, the final timestep
  191. # that's available as input to the forecast, with all following timesteps
  192. # forming the target period which needs to be predicted.
  193. # This means the time coordinates are now forecast lead times.
  194. time = dataset.coords["time"]
  195. dataset = dataset.assign_coords(time=time + target_duration - time[-1])
  196. # Slice out targets:
  197. targets = dataset.sel({"time": target_lead_times})
  198. input_duration = pd.Timedelta(input_duration)
  199. # Both endpoints are inclusive with label-based slicing, so we offset by a
  200. # small epsilon to make one of the endpoints non-inclusive:
  201. zero = pd.Timedelta(0)
  202. epsilon = pd.Timedelta(1, "ns")
  203. inputs = dataset.sel({"time": slice(-input_duration + epsilon, zero)})
  204. return inputs, targets
  205. def _process_target_lead_times_and_get_duration(
  206. target_lead_times: TargetLeadTimes) -> TimedeltaLike:
  207. """Returns the minimum duration for the target lead times."""
  208. if isinstance(target_lead_times, slice):
  209. # A slice of lead times. xarray already accepts timedelta-like values for
  210. # the begin/end/step of the slice.
  211. if target_lead_times.start is None:
  212. # If the start isn't specified, we assume it starts at the next timestep
  213. # after lead time 0 (lead time 0 is the final input timestep):
  214. target_lead_times = slice(
  215. pd.Timedelta(1, "ns"), target_lead_times.stop, target_lead_times.step
  216. )
  217. target_duration = pd.Timedelta(target_lead_times.stop)
  218. else:
  219. if not isinstance(target_lead_times, (list, tuple, set)):
  220. # A single lead time, which we wrap as a length-1 array to ensure there
  221. # still remains a time dimension (here of length 1) for consistency.
  222. target_lead_times = [target_lead_times]
  223. # A list of multiple (not necessarily contiguous) lead times:
  224. target_lead_times = [pd.Timedelta(x) for x in target_lead_times]
  225. target_lead_times.sort()
  226. target_duration = target_lead_times[-1]
  227. return target_lead_times, target_duration
  228. def extract_inputs_targets_forcings(
  229. dataset: xarray.Dataset,
  230. *,
  231. input_variables: Tuple[str, ...],
  232. target_variables: Tuple[str, ...],
  233. forcing_variables: Tuple[str, ...],
  234. pressure_levels: Tuple[int, ...],
  235. input_duration: TimedeltaLike,
  236. target_lead_times: TargetLeadTimes,
  237. ) -> Tuple[xarray.Dataset, xarray.Dataset, xarray.Dataset]:
  238. """Extracts inputs, targets and forcings according to requirements."""
  239. dataset = dataset.sel(level=list(pressure_levels))
  240. # "Forcings" are derived variables and do not exist in the original ERA5 or
  241. # HRES datasets. Compute them if they are not in `dataset`.
  242. if not set(forcing_variables).issubset(set(dataset.data_vars)):
  243. add_derived_vars(dataset)
  244. # `datetime` is needed by add_derived_vars but breaks autoregressive rollouts.
  245. dataset = dataset.drop_vars("datetime")
  246. inputs, targets = extract_input_target_times(
  247. dataset,
  248. input_duration=input_duration,
  249. target_lead_times=target_lead_times)
  250. if set(forcing_variables) & set(target_variables):
  251. raise ValueError(
  252. f"Forcing variables {forcing_variables} should not "
  253. f"overlap with target variables {target_variables}."
  254. )
  255. inputs = inputs[list(input_variables)]
  256. # The forcing uses the same time coordinates as the target.
  257. forcings = targets[list(forcing_variables)]
  258. targets = targets[list(target_variables)]
  259. return inputs, targets, forcings