tctrack 0.2__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.
- tctrack/__init__.py +5 -0
- tctrack/core/__init__.py +19 -0
- tctrack/core/tracker.py +530 -0
- tctrack/core/trajectory.py +228 -0
- tctrack/tempest_extremes/__init__.py +19 -0
- tctrack/tempest_extremes/tempest_extremes.py +1144 -0
- tctrack/track/__init__.py +11 -0
- tctrack/track/track.py +778 -0
- tctrack/tstorms/__init__.py +15 -0
- tctrack/tstorms/tstorms.py +1075 -0
- tctrack/utils/__init__.py +7 -0
- tctrack/utils/utils.py +29 -0
- tctrack-0.2.dist-info/METADATA +155 -0
- tctrack-0.2.dist-info/RECORD +17 -0
- tctrack-0.2.dist-info/WHEEL +5 -0
- tctrack-0.2.dist-info/licenses/LICENSE +674 -0
- tctrack-0.2.dist-info/top_level.txt +1 -0
tctrack/__init__.py
ADDED
tctrack/core/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Package providing core utilities used throughout TCTrack."""
|
|
2
|
+
|
|
3
|
+
from .tracker import (
|
|
4
|
+
TCTracker,
|
|
5
|
+
TCTrackerMetadata,
|
|
6
|
+
TCTrackerParameters,
|
|
7
|
+
TCTrackerTimeMetadata,
|
|
8
|
+
)
|
|
9
|
+
from .trajectory import (
|
|
10
|
+
Trajectory,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"TCTracker",
|
|
15
|
+
"TCTrackerMetadata",
|
|
16
|
+
"TCTrackerParameters",
|
|
17
|
+
"TCTrackerTimeMetadata",
|
|
18
|
+
"Trajectory",
|
|
19
|
+
]
|
tctrack/core/tracker.py
ADDED
|
@@ -0,0 +1,530 @@
|
|
|
1
|
+
"""Module providing an abstract base classes for creating specific trackers."""
|
|
2
|
+
|
|
3
|
+
import importlib.metadata
|
|
4
|
+
import warnings
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from dataclasses import dataclass, fields
|
|
7
|
+
from datetime import timedelta
|
|
8
|
+
from typing import TypedDict
|
|
9
|
+
|
|
10
|
+
import cf
|
|
11
|
+
from cftime import date2num, datetime
|
|
12
|
+
|
|
13
|
+
from .trajectory import Trajectory
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class TCTrackerParameters:
|
|
18
|
+
"""
|
|
19
|
+
Base Data Class for containing parameters of TCTracker classes.
|
|
20
|
+
|
|
21
|
+
Parameters for a specific algorithm should be subclassed from this base class.
|
|
22
|
+
The child class should be annotated as a dataclass using ``@dataclass(repr=False)``.
|
|
23
|
+
|
|
24
|
+
Examples
|
|
25
|
+
--------
|
|
26
|
+
>>> from tctrack.core import TCTrackerParameters
|
|
27
|
+
>>>
|
|
28
|
+
>>> @dataclass(repr=False)
|
|
29
|
+
>>> class MyTrackerParameters(TCTrackerParameters):
|
|
30
|
+
>>> param_a: int
|
|
31
|
+
>>> param_b: str
|
|
32
|
+
>>>
|
|
33
|
+
>>> params = MyTrackerParameters(param_a=1, param_b="example")
|
|
34
|
+
>>>
|
|
35
|
+
>>> print(params)
|
|
36
|
+
MyTrackerParameters(
|
|
37
|
+
param_a = 1
|
|
38
|
+
param_b = example
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __repr__(self) -> str:
|
|
44
|
+
"""Provide string representation of Parameters to users."""
|
|
45
|
+
attributes = "\n\t".join(
|
|
46
|
+
f"{field.name} \t = {getattr(self, field.name)}" for field in fields(self)
|
|
47
|
+
)
|
|
48
|
+
return f"{type(self).__name__}(\n\t{attributes}\n)"
|
|
49
|
+
|
|
50
|
+
def __str__(self) -> str:
|
|
51
|
+
"""Provide string representation of Parameters."""
|
|
52
|
+
return self.__repr__()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class TCTrackerTimeMetadata(TypedDict):
|
|
56
|
+
"""Dataclass containing the time metadata for a dataset used by a Tracker."""
|
|
57
|
+
|
|
58
|
+
calendar: str
|
|
59
|
+
"""The calendar type as a string."""
|
|
60
|
+
units: str
|
|
61
|
+
"""The calendar units as a string."""
|
|
62
|
+
start_time: datetime
|
|
63
|
+
"""The start time of the data processed as a ``cftime.datetime`` object."""
|
|
64
|
+
end_time: datetime
|
|
65
|
+
"""The final time of the data processed as a ``cftime.datetime`` object."""
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def is_typed_dict_instance(data, typed_dict_class):
|
|
69
|
+
"""Check if an object has all required keys of the TypedDict class."""
|
|
70
|
+
return isinstance(data, dict) and all(
|
|
71
|
+
key in data for key in typed_dict_class.__required_keys__
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass
|
|
76
|
+
class TCTrackerMetadata:
|
|
77
|
+
"""Dataclass containing the metadata for a single variable in variable_metadata."""
|
|
78
|
+
|
|
79
|
+
properties: dict[str, str]
|
|
80
|
+
"""The basic metadata properties for the variable."""
|
|
81
|
+
|
|
82
|
+
constructs: list | None = None
|
|
83
|
+
"""A list of any CF constructs to add, such as :class:`cf.CellMethod` constructs."""
|
|
84
|
+
|
|
85
|
+
construct_kwargs: list[dict] | None = None
|
|
86
|
+
"""
|
|
87
|
+
A list of kwargs (as dicts) to use when the :meth:`cf.Field.set_construct` method
|
|
88
|
+
is called in :meth:`TCTracker.to_netcdf`. This can be left as ``None``, otherwise it
|
|
89
|
+
must be the same length as :attr:`constructs`.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
def __post_init__(self):
|
|
93
|
+
"""Ensure both constructs and construct_kwargs are the same length."""
|
|
94
|
+
if (
|
|
95
|
+
self.constructs
|
|
96
|
+
and self.construct_kwargs
|
|
97
|
+
and len(self.constructs) != len(self.construct_kwargs)
|
|
98
|
+
):
|
|
99
|
+
msg = (
|
|
100
|
+
"'constructs' and 'construct_kwargs' have mismatched lengths "
|
|
101
|
+
f"(got {len(self.constructs)} and {len(self.construct_kwargs)})"
|
|
102
|
+
)
|
|
103
|
+
raise ValueError(msg)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class TCTracker(ABC):
|
|
107
|
+
"""
|
|
108
|
+
Abstract Base Class representing a generic TCTracker class.
|
|
109
|
+
|
|
110
|
+
Attributes
|
|
111
|
+
----------
|
|
112
|
+
_variable_metadata : dict[str, TCTrackerMetadata] | None
|
|
113
|
+
A dictionary containing metadata for variables.
|
|
114
|
+
This attribute must be initialized by the subclass through the
|
|
115
|
+
:meth:`set_metadata` method, prior to which it is initialised as ``None``.
|
|
116
|
+
_time_metadata : dict[str, ] | None
|
|
117
|
+
A dictionary containing metadata for times including calendar, units, and start
|
|
118
|
+
and end times of the dataset.
|
|
119
|
+
This attribute must be initialized by the subclass through the
|
|
120
|
+
:meth:`set_metadata` method, prior to which it is initialised as ``None``.
|
|
121
|
+
_global_metadata : dict[str, str]
|
|
122
|
+
A dictionary containing global metadata about the data and TCTrack parameters.
|
|
123
|
+
This attribute should be initialized by the subclass through the
|
|
124
|
+
:meth:`set_metadata` method. The parameters should be output in a json format
|
|
125
|
+
using ``json.dumps(asdict(parameters))``
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
# Private attributes
|
|
129
|
+
_variable_metadata: dict[str, TCTrackerMetadata] | None = None
|
|
130
|
+
_time_metadata: TCTrackerTimeMetadata | None = None
|
|
131
|
+
_global_metadata: dict[str, str]
|
|
132
|
+
|
|
133
|
+
@property
|
|
134
|
+
def variable_metadata(self) -> dict:
|
|
135
|
+
"""
|
|
136
|
+
dict: Read-only property containing NetCDF metadata for variables.
|
|
137
|
+
|
|
138
|
+
Raises
|
|
139
|
+
------
|
|
140
|
+
AttributeError
|
|
141
|
+
If `_variable_metadata` has not been initialized.
|
|
142
|
+
"""
|
|
143
|
+
if not self._variable_metadata:
|
|
144
|
+
err_msg = "_variable_metadata has not been initialized."
|
|
145
|
+
raise AttributeError(err_msg)
|
|
146
|
+
return self._variable_metadata
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def time_metadata(self) -> TCTrackerTimeMetadata:
|
|
150
|
+
"""
|
|
151
|
+
dict: Read-only property containing time metadata for this Tracker run.
|
|
152
|
+
|
|
153
|
+
Raises
|
|
154
|
+
------
|
|
155
|
+
AttributeError
|
|
156
|
+
If `_time_metadata` has not been initialized.
|
|
157
|
+
"""
|
|
158
|
+
if not self._time_metadata:
|
|
159
|
+
err_msg = "_time_metadata has not been initialized."
|
|
160
|
+
raise AttributeError(err_msg)
|
|
161
|
+
if self._time_metadata and not is_typed_dict_instance(
|
|
162
|
+
self._time_metadata, TCTrackerTimeMetadata
|
|
163
|
+
):
|
|
164
|
+
err_msg = (
|
|
165
|
+
"_time_metadata does not conform to the expected format of "
|
|
166
|
+
"`TCTrackerTimeMetadata`."
|
|
167
|
+
)
|
|
168
|
+
raise TypeError(err_msg)
|
|
169
|
+
|
|
170
|
+
return self._time_metadata
|
|
171
|
+
|
|
172
|
+
@property
|
|
173
|
+
def global_metadata(self) -> dict:
|
|
174
|
+
"""
|
|
175
|
+
dict: Read-only property containing metadata for tctrack / tracker instance.
|
|
176
|
+
|
|
177
|
+
Raises
|
|
178
|
+
------
|
|
179
|
+
AttributeError
|
|
180
|
+
If `_global_metadata` has not been initialized.
|
|
181
|
+
"""
|
|
182
|
+
if not hasattr(self, "_global_metadata"):
|
|
183
|
+
err_msg = "_global_metadata has not been initialized."
|
|
184
|
+
raise AttributeError(err_msg)
|
|
185
|
+
return self._global_metadata
|
|
186
|
+
|
|
187
|
+
@abstractmethod
|
|
188
|
+
def set_metadata(self) -> None:
|
|
189
|
+
"""
|
|
190
|
+
Abstract method to initialize the metadata attributes.
|
|
191
|
+
|
|
192
|
+
This method must be implemented by subclasses to populate the
|
|
193
|
+
:attr:`_variable_metadata` attribute with relevant metadata for variables,
|
|
194
|
+
`:attr:`_time_metadata` with metadata about the time for the dataset, and
|
|
195
|
+
the :attr:`_global_metadata` attribute for metadata about the TCTrack
|
|
196
|
+
parameters and name of the tracker.
|
|
197
|
+
|
|
198
|
+
This will be called from the :meth:`to_netcdf` method.
|
|
199
|
+
|
|
200
|
+
Notes
|
|
201
|
+
-----
|
|
202
|
+
The :attr:`_variable_metadata` attribute is expected to be a dictionary where
|
|
203
|
+
keys are variable names and values are instances of :class:`TCTrackerMetadata`
|
|
204
|
+
containing the metadata for that variable (e.g., `standard_name`, `long_name`,
|
|
205
|
+
`units`).
|
|
206
|
+
|
|
207
|
+
The :attr:`_time_metadata` attribute is expected to be a typed dictionary of
|
|
208
|
+
the :class:`TCTrackerTimeMetadata` form containing the calendar type and units
|
|
209
|
+
of the dataset, as well as the start and end times.
|
|
210
|
+
|
|
211
|
+
The :attr:`_global_metadata` should contain each parameter object in a json
|
|
212
|
+
format using ``json.dumps(asdict(parameters))``.
|
|
213
|
+
|
|
214
|
+
Examples
|
|
215
|
+
--------
|
|
216
|
+
>>> class MyTracker(TCTracker):
|
|
217
|
+
... def set_metadata(self):
|
|
218
|
+
... super().set_metadata()
|
|
219
|
+
... self._variable_metadata = {
|
|
220
|
+
... "example_variable": TCTrackerMetadata(
|
|
221
|
+
... properties={
|
|
222
|
+
... "standard_name": "example_standard_name",
|
|
223
|
+
... "long_name": "Example Long Name",
|
|
224
|
+
... "units": "example_units",
|
|
225
|
+
... },
|
|
226
|
+
... constructs=[<CF CellMethod>],
|
|
227
|
+
... }
|
|
228
|
+
... }
|
|
229
|
+
... self._time_metadata = {
|
|
230
|
+
... "calendar": "example_calendar",
|
|
231
|
+
... "units": "days since yyyy-mm-dd",
|
|
232
|
+
... "start_time": cftime.datetime(
|
|
233
|
+
... yyyy, mm, dd, hh, calendar=self.example_calendar
|
|
234
|
+
... ),
|
|
235
|
+
... "end_time": cftime.datetime(
|
|
236
|
+
... yyyy, mm, dd, hh, calendar=self.example_calendar
|
|
237
|
+
... ),
|
|
238
|
+
... }
|
|
239
|
+
... self.global_metadata["mytracker_parameters"] = json.dumps(
|
|
240
|
+
... asdict(MyTrackerParameters)
|
|
241
|
+
... ),
|
|
242
|
+
"""
|
|
243
|
+
self._global_metadata = {
|
|
244
|
+
"tctrack_version": importlib.metadata.version("tctrack"),
|
|
245
|
+
"tctrack_tracker": type(self).__name__,
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
@abstractmethod
|
|
249
|
+
def read_trajectories(self) -> list[Trajectory]:
|
|
250
|
+
"""
|
|
251
|
+
Parse tracking algorithm outputs into list of :class:`tctrack.core.Trajectory`.
|
|
252
|
+
|
|
253
|
+
Implementation is deferred to the specific tracking algorithm.
|
|
254
|
+
For compatibility elsewhere in TCTrack trajectories are assumed to contain as
|
|
255
|
+
a minimum data for ``lat``, ``lon``, and ``timestep``.
|
|
256
|
+
|
|
257
|
+
Returns
|
|
258
|
+
-------
|
|
259
|
+
list[Trajectory]
|
|
260
|
+
A list of :class:`tctrack.core.Trajectory` objects.
|
|
261
|
+
"""
|
|
262
|
+
|
|
263
|
+
def to_netcdf(self, output_file: str) -> None: # noqa: PLR0915, PLR0912
|
|
264
|
+
"""
|
|
265
|
+
Write track trajectories to CF-compliant NetCDF trajectory file.
|
|
266
|
+
|
|
267
|
+
Reads in trajectories based on the parameters set for a specific implementation
|
|
268
|
+
of the class and writes them to a CF-Conventions compliant NetCDF trajectory
|
|
269
|
+
file using cf-python.
|
|
270
|
+
Trajectories are assumed to contain as a minimum data for ``lat``, ``lon``,
|
|
271
|
+
and ``timestep``.
|
|
272
|
+
|
|
273
|
+
An ancillary field variable is added to the output file indicating any tracks
|
|
274
|
+
that start/end within 1 day of the input dataset boundaries.
|
|
275
|
+
|
|
276
|
+
Parameters
|
|
277
|
+
----------
|
|
278
|
+
output_file: str
|
|
279
|
+
filename for the output netCDF file
|
|
280
|
+
Note: This will be placed in the local directory unless a full path is given
|
|
281
|
+
|
|
282
|
+
Warnings
|
|
283
|
+
--------
|
|
284
|
+
UserWarning
|
|
285
|
+
If there are no trajectories read in from the tracker outputs by
|
|
286
|
+
:meth:`read_trajectories()` meaning no NetCDF output file can be written.
|
|
287
|
+
|
|
288
|
+
References
|
|
289
|
+
----------
|
|
290
|
+
`CF-Conventions v1.1 - H.4. Trajectory Data <https://cfconventions.org/Data/cf-conventions/cf-conventions-1.11/cf-conventions.html#trajectory-data>`_
|
|
291
|
+
`cf-python documentation <https://ncas-cms.github.io/cf-python/index.html>`_
|
|
292
|
+
|
|
293
|
+
Examples
|
|
294
|
+
--------
|
|
295
|
+
Instantiate a :class:`TCTracker` subclass instance with appropriate parameters,
|
|
296
|
+
run the relevant methods to generate cyclone track trajectories, and then save
|
|
297
|
+
the results to a CF-compliant trajectory file:
|
|
298
|
+
|
|
299
|
+
>>> my_tracker = TCTracker(...)
|
|
300
|
+
>>> ...
|
|
301
|
+
>>> my_tracker.to_netcdf("my_netcdf_file.nc")
|
|
302
|
+
"""
|
|
303
|
+
# Set the metadata if not done already
|
|
304
|
+
if (
|
|
305
|
+
not self._variable_metadata
|
|
306
|
+
or not self._global_metadata
|
|
307
|
+
or not self._time_metadata
|
|
308
|
+
):
|
|
309
|
+
self.set_metadata()
|
|
310
|
+
|
|
311
|
+
# Read in the trajectories generated by the tracker implementation
|
|
312
|
+
# Ensure they contain assumed variables lon, lat, time
|
|
313
|
+
trajectories = self.read_trajectories()
|
|
314
|
+
|
|
315
|
+
if len(trajectories) == 0:
|
|
316
|
+
msg = (
|
|
317
|
+
"There are no trajectories in this period so no output file will be "
|
|
318
|
+
"written."
|
|
319
|
+
)
|
|
320
|
+
warnings.warn(msg, category=UserWarning, stacklevel=3)
|
|
321
|
+
return
|
|
322
|
+
|
|
323
|
+
# Validate that each trajectory contains the required keys and
|
|
324
|
+
# check for trajectories starting and ending on file boundaries
|
|
325
|
+
required_keys = {"time", "lat", "lon"}
|
|
326
|
+
starting_trajectory = [False] * len(trajectories)
|
|
327
|
+
ending_trajectory = [False] * len(trajectories)
|
|
328
|
+
|
|
329
|
+
for i, trajectory in enumerate(trajectories):
|
|
330
|
+
missing_keys = required_keys - trajectory.data.keys()
|
|
331
|
+
if missing_keys:
|
|
332
|
+
errmsg = (
|
|
333
|
+
f"Trajectory {i} is missing required keys: "
|
|
334
|
+
f"{', '.join(missing_keys)}"
|
|
335
|
+
)
|
|
336
|
+
raise ValueError(errmsg)
|
|
337
|
+
|
|
338
|
+
# Check for trajectories starting and ending within a day of file boundaries
|
|
339
|
+
if (
|
|
340
|
+
trajectory.data["time"][0] - self.time_metadata["start_time"]
|
|
341
|
+
) <= timedelta(days=1):
|
|
342
|
+
starting_trajectory[i] = True
|
|
343
|
+
if (
|
|
344
|
+
self.time_metadata["end_time"] - trajectory.data["time"][-1]
|
|
345
|
+
) <= timedelta(days=1):
|
|
346
|
+
ending_trajectory[i] = True
|
|
347
|
+
|
|
348
|
+
start_field = cf.FieldAncillary(
|
|
349
|
+
data=starting_trajectory,
|
|
350
|
+
properties={
|
|
351
|
+
"standard_name": "status_flag",
|
|
352
|
+
"long_name": "Trajectory starting at start of dataset flag.",
|
|
353
|
+
},
|
|
354
|
+
)
|
|
355
|
+
start_field.nc_set_variable("start_flag")
|
|
356
|
+
end_field = cf.FieldAncillary(
|
|
357
|
+
data=ending_trajectory,
|
|
358
|
+
properties={
|
|
359
|
+
"standard_name": "status_flag",
|
|
360
|
+
"long_name": "Trajectory finishing at end of dataset flag.",
|
|
361
|
+
},
|
|
362
|
+
)
|
|
363
|
+
end_field.nc_set_variable("end_flag")
|
|
364
|
+
|
|
365
|
+
# Determine dimensions
|
|
366
|
+
num_trajectories = len(trajectories)
|
|
367
|
+
max_obs = max(trajectory.observations for trajectory in trajectories)
|
|
368
|
+
|
|
369
|
+
# Define domain axes and coords based on number of trajectories and max lengths
|
|
370
|
+
domain_axis_traj = cf.DomainAxis(size=num_trajectories)
|
|
371
|
+
domain_axis_obs = cf.DomainAxis(size=max_obs)
|
|
372
|
+
domain_axis_traj.nc_set_dimension("trajectory")
|
|
373
|
+
domain_axis_obs.nc_set_dimension("observation")
|
|
374
|
+
|
|
375
|
+
dim_traj = cf.DimensionCoordinate(
|
|
376
|
+
data=cf.Data(range(num_trajectories)),
|
|
377
|
+
properties={
|
|
378
|
+
"standard_name": "trajectory",
|
|
379
|
+
"cf_role": "trajectory_id",
|
|
380
|
+
"long_name": "trajectory index",
|
|
381
|
+
},
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
dim_obs = cf.DimensionCoordinate(
|
|
385
|
+
data=cf.Data(range(max_obs)),
|
|
386
|
+
properties={
|
|
387
|
+
"standard_name": "observation",
|
|
388
|
+
"long_name": "observation index",
|
|
389
|
+
},
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
# Create auxiliary coordinates for time, latitude, longitude
|
|
393
|
+
# Convert time from cftime to num format to write out via cf
|
|
394
|
+
time_fill = -1e8
|
|
395
|
+
time_data = cf.Data(
|
|
396
|
+
[
|
|
397
|
+
date2num(
|
|
398
|
+
trajectory.data["time"],
|
|
399
|
+
units=self.time_metadata["units"],
|
|
400
|
+
calendar=self.time_metadata["calendar"],
|
|
401
|
+
).tolist()
|
|
402
|
+
+ [time_fill] * (max_obs - trajectory.observations)
|
|
403
|
+
for trajectory in trajectories
|
|
404
|
+
],
|
|
405
|
+
fill_value=time_fill,
|
|
406
|
+
)
|
|
407
|
+
time_coord = cf.AuxiliaryCoordinate(
|
|
408
|
+
data=time_data,
|
|
409
|
+
properties={
|
|
410
|
+
"standard_name": "time",
|
|
411
|
+
"long_name": "time",
|
|
412
|
+
"units": cf.Units(
|
|
413
|
+
self.time_metadata["units"], calendar=self.time_metadata["calendar"]
|
|
414
|
+
),
|
|
415
|
+
"missing_value": time_fill,
|
|
416
|
+
},
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
lat_lon_fill = -999.9
|
|
420
|
+
lat_data = cf.Data(
|
|
421
|
+
[
|
|
422
|
+
trajectory.data["lat"] + [None] * (max_obs - trajectory.observations)
|
|
423
|
+
for trajectory in trajectories
|
|
424
|
+
],
|
|
425
|
+
fill_value=lat_lon_fill,
|
|
426
|
+
)
|
|
427
|
+
lat_coord = cf.AuxiliaryCoordinate(
|
|
428
|
+
data=lat_data,
|
|
429
|
+
properties={
|
|
430
|
+
"standard_name": "latitude",
|
|
431
|
+
"long_name": "latitude",
|
|
432
|
+
"units": "degrees_north",
|
|
433
|
+
"missing_value": lat_lon_fill,
|
|
434
|
+
},
|
|
435
|
+
)
|
|
436
|
+
|
|
437
|
+
lon_data = cf.Data(
|
|
438
|
+
[
|
|
439
|
+
trajectory.data["lon"] + [None] * (max_obs - trajectory.observations)
|
|
440
|
+
for trajectory in trajectories
|
|
441
|
+
],
|
|
442
|
+
fill_value=lat_lon_fill,
|
|
443
|
+
)
|
|
444
|
+
lon_coord = cf.AuxiliaryCoordinate(
|
|
445
|
+
data=lon_data,
|
|
446
|
+
properties={
|
|
447
|
+
"standard_name": "longitude",
|
|
448
|
+
"long_name": "longitude",
|
|
449
|
+
"units": "degrees_east",
|
|
450
|
+
"missing_value": lat_lon_fill,
|
|
451
|
+
},
|
|
452
|
+
)
|
|
453
|
+
|
|
454
|
+
# Create a cf.Field for each non-coordinate variable in Track.data
|
|
455
|
+
# Assumes all trajectories contain the same variables
|
|
456
|
+
fields = []
|
|
457
|
+
for variable in trajectories[0].data:
|
|
458
|
+
if variable in {"time", "lat", "lon"}:
|
|
459
|
+
continue
|
|
460
|
+
|
|
461
|
+
# Define the variable metadata
|
|
462
|
+
metadata = self.variable_metadata.get(variable, TCTrackerMetadata({}))
|
|
463
|
+
metadata.properties["featureType"] = "trajectory"
|
|
464
|
+
|
|
465
|
+
field = cf.Field(properties=metadata.properties)
|
|
466
|
+
|
|
467
|
+
# By default cf-python sets variable name as the standard name.
|
|
468
|
+
# If there is no standard name in the metadata for this variable we set
|
|
469
|
+
# it manually to something meaningful (cf-python default is `data_n`).
|
|
470
|
+
if "standard_name" not in metadata.properties:
|
|
471
|
+
field.nc_set_variable(variable)
|
|
472
|
+
# Add any metadata constructs
|
|
473
|
+
if metadata.constructs:
|
|
474
|
+
for ic, construct in enumerate(metadata.constructs):
|
|
475
|
+
kwargs = {}
|
|
476
|
+
if metadata.construct_kwargs:
|
|
477
|
+
kwargs = metadata.construct_kwargs[ic]
|
|
478
|
+
field.set_construct(construct, **kwargs)
|
|
479
|
+
|
|
480
|
+
# Add the axes / coordinates
|
|
481
|
+
axis_traj = field.set_construct(domain_axis_traj)
|
|
482
|
+
axis_obs = field.set_construct(domain_axis_obs)
|
|
483
|
+
field.set_construct(dim_traj, axes=(axis_traj,))
|
|
484
|
+
field.set_construct(dim_obs, axes=(axis_obs,))
|
|
485
|
+
field.set_construct(time_coord, axes=(axis_traj, axis_obs))
|
|
486
|
+
field.set_construct(lat_coord, axes=(axis_traj, axis_obs))
|
|
487
|
+
field.set_construct(lon_coord, axes=(axis_traj, axis_obs))
|
|
488
|
+
field.set_construct(start_field, axes=(axis_traj))
|
|
489
|
+
field.set_construct(end_field, axes=(axis_traj))
|
|
490
|
+
|
|
491
|
+
field_fill = -1e10
|
|
492
|
+
variable_data = cf.Data(
|
|
493
|
+
[
|
|
494
|
+
trajectory.data[variable]
|
|
495
|
+
+ [None] * (max_obs - trajectory.observations)
|
|
496
|
+
for trajectory in trajectories
|
|
497
|
+
],
|
|
498
|
+
fill_value=field_fill,
|
|
499
|
+
)
|
|
500
|
+
|
|
501
|
+
# Add the variable coordinate to the field
|
|
502
|
+
field.set_data(variable_data, axes=(axis_traj, axis_obs))
|
|
503
|
+
field.set_property("missing_value", field_fill)
|
|
504
|
+
|
|
505
|
+
# Add the global metadata
|
|
506
|
+
if self.global_metadata:
|
|
507
|
+
field.nc_set_global_attributes(self.global_metadata)
|
|
508
|
+
|
|
509
|
+
fields.append(field)
|
|
510
|
+
|
|
511
|
+
# Write to file
|
|
512
|
+
cf.write(fields, output_file) # type: ignore[operator]
|
|
513
|
+
|
|
514
|
+
@abstractmethod
|
|
515
|
+
def run_tracker(self, output_file: str) -> None:
|
|
516
|
+
"""
|
|
517
|
+
Run the tracker to obtain tropical cyclone track trajectories as NetCDF file.
|
|
518
|
+
|
|
519
|
+
Implementation is deferred to the specific tracking algorithm.
|
|
520
|
+
|
|
521
|
+
This should first run any relevant methods for generating cyclone trajectories
|
|
522
|
+
from the input data files.
|
|
523
|
+
The trajectories output is then saved as a CF-compliant trajectory netCDF file
|
|
524
|
+
by calling the :meth:`to_netcdf()` method of this class.
|
|
525
|
+
|
|
526
|
+
Arguments
|
|
527
|
+
---------
|
|
528
|
+
output_file : str
|
|
529
|
+
Filename to which the tropical cyclone trajectories are saved.
|
|
530
|
+
"""
|