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.
@@ -0,0 +1,228 @@
1
+ """Module providing a class for storing data for a single cyclone trajectory."""
2
+
3
+ import numbers
4
+ import warnings
5
+ from collections.abc import Sequence
6
+ from itertools import zip_longest
7
+ from typing import TypeGuard
8
+
9
+ from cftime import datetime
10
+
11
+
12
+ def _is_datetime(x: object) -> TypeGuard[datetime]:
13
+ """Check (in a way the type-checker knows) that it is a datetime."""
14
+ return isinstance(x, datetime)
15
+
16
+
17
+ class Trajectory:
18
+ """
19
+ A single Lagrangian cyclone trajectory/track with metadata and data points.
20
+
21
+ Attributes
22
+ ----------
23
+ trajectory_id : int
24
+ The unique identifier for the trajectory.
25
+ observations : int
26
+ Number of points in the trajectory.
27
+ calendar : str
28
+ The calendar type to use for datetime handling.
29
+ Options are "gregorian", "360_day", or "noleap".
30
+ start_time : cftime.datetime
31
+ Start time of the trajectory as a cftime.datetime object.
32
+ data : dict
33
+ Dict of data for various variables along the trajectory.
34
+ Timestamp and other variables as supplied in file.
35
+ For compatibility elsewhere in TCTrack trajectories are assumed to contain as
36
+ a minimum data for ``lat``, ``lon``, and ``time``.
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ trajectory_id: int,
42
+ time: Sequence[int] | datetime,
43
+ calendar: str = "gregorian",
44
+ ):
45
+ """
46
+ Initialize a Trajectory object.
47
+
48
+ Parameters
49
+ ----------
50
+ trajectory_id : int
51
+ The unique identifier for the trajectory.
52
+ time : Sequence[int] | cftime.datetime
53
+ The starting time of the trajectory. If using a list of integers this should
54
+ be in the order: year, month, day, hour, minute, second. Any values not
55
+ provided will be set to 0. This will be converted to a ``cftime.datetime``
56
+ using the appropriate calendar.
57
+ calendar : str, optional
58
+ The calendar type to use for datetime handling if the time is provided as a
59
+ list. Options are "gregorian", "julian", "360_day", or "noleap".
60
+
61
+ Raises
62
+ ------
63
+ TypeError
64
+ If time is not a ``Sequence[int]`` or ``cftime.datetime``.
65
+ """
66
+ self.trajectory_id = trajectory_id
67
+ self.observations = 0
68
+ if isinstance(time, Sequence) and all(isinstance(t, int) for t in time):
69
+ self.calendar = calendar
70
+ self.start_time = self._create_datetime(time)
71
+ elif _is_datetime(time):
72
+ self.calendar = time.calendar
73
+ self.start_time = time
74
+ else:
75
+ msg = "Invalid type for 'time'. Must be a Sequence[int] or cftime.datetime."
76
+ raise TypeError(msg)
77
+ self.data: dict = {}
78
+
79
+ def _create_datetime(self, time: Sequence[int]) -> datetime:
80
+ """
81
+ Create a cftime object based on the specified calendar attribute.
82
+
83
+ Parameters
84
+ ----------
85
+ time : Sequence[int]
86
+ Time as a list of integers in the order: year, month, day, hour, minute,
87
+ second. Any values not provided will be set to 0.
88
+
89
+ Returns
90
+ -------
91
+ datetime : datetime
92
+ cftime.datetime object with the appropriate calendar setting
93
+
94
+ Raises
95
+ ------
96
+ ValueError
97
+ If the calendar is not one of the supported types.
98
+ UserWarning
99
+ If more than six values are passed as a time.
100
+ """
101
+ supported_types = {"360_day", "noleap", "julian", "gregorian", "standard"}
102
+ if self.calendar in supported_types:
103
+ time_units = ("year", "month", "day", "hour", "minute", "second")
104
+ # Set all the time units provided in `time`, set the rest to zero
105
+ time_dict = dict(zip_longest(time_units, time, fillvalue=0))
106
+ if len(time) > len(time_units):
107
+ msg = (
108
+ "The list for the time is too long. "
109
+ "Only the first six values will be used."
110
+ )
111
+ warnings.warn(msg, category=UserWarning, stacklevel=2)
112
+ return datetime(
113
+ *[time_dict[unit] for unit in time_units],
114
+ calendar=self.calendar,
115
+ )
116
+ else:
117
+ msg = (
118
+ f"Unsupported calendar type: {self.calendar}. "
119
+ "Supported types are "
120
+ f"{', '.join(f'`{caltype}`' for caltype in supported_types)}."
121
+ )
122
+ raise ValueError(msg)
123
+
124
+ def __str__(self) -> str:
125
+ """Improve the representation of Trajectory class to users."""
126
+ return (
127
+ f"Trajectory(observations={self.observations}, "
128
+ f"start_time={self.start_time}, "
129
+ f"calendar={self.calendar}, "
130
+ f"data_points={len(self.data)})"
131
+ )
132
+
133
+ def add_point(self, time: Sequence[int] | datetime, variables: dict):
134
+ """
135
+ Add a single data point to the trajectory.
136
+
137
+ Parameters
138
+ ----------
139
+ time : Sequence[int] | cftime.datetime
140
+ The time of the data point. If a list of integers this should be in the
141
+ order: year, month, day, hour, minute, second. Any values not provided will
142
+ be set to 0. This will be converted to a ``cftime.datetime`` using the
143
+ appropriate calendar.
144
+ variables : dict
145
+ A dict containing any variables for the point as key : value pairs
146
+
147
+ Raises
148
+ ------
149
+ TypeError
150
+ If time is not a ``Sequence[int]`` or ``cftime.datetime``.
151
+ """
152
+ # Validate variables as int or float
153
+ if not isinstance(variables, dict) or not all(
154
+ isinstance(value, numbers.Real) for value in variables.values()
155
+ ):
156
+ msg = (
157
+ f"Invalid variable data: {variables}."
158
+ " Must be a dictionary with numeric values."
159
+ )
160
+ raise ValueError(msg)
161
+
162
+ if _is_datetime(time):
163
+ pass # This assumes the time has the same calendar
164
+ elif isinstance(time, Sequence) and all(isinstance(t, int) for t in time):
165
+ time = self._create_datetime(time)
166
+ else:
167
+ msg = "Invalid type for 'time'. Must be a Sequence[int] or cftime.datetime."
168
+ raise TypeError(msg)
169
+
170
+ # Initialize data structure if empty
171
+ if not self.data:
172
+ self.data = {
173
+ "time": [],
174
+ **{key: [] for key in variables},
175
+ }
176
+
177
+ # Append data to the respective lists
178
+ self.data["time"].append(time)
179
+ for key, value in variables.items():
180
+ self.data[key].append(value)
181
+
182
+ self.observations += 1
183
+
184
+ def add_multiple_points(
185
+ self,
186
+ times: Sequence[Sequence[int] | datetime],
187
+ variables: dict,
188
+ ):
189
+ """
190
+ Add multiple data points to the trajectory in one go.
191
+
192
+ Parameters
193
+ ----------
194
+ times : Sequence[Sequence[int] | cftime.datetime]
195
+ The times of the data points. If the individual times are a list of integers
196
+ this should be in the order: year, month, day, hour, minute, second. Any
197
+ values not provided will be set to 0. This will be converted to a
198
+ ``cftime.datetime`` using the appropriate calendar.
199
+ variables : dict
200
+ A dict containing arrays of any variables for the point
201
+ as key : list[value] pairs
202
+
203
+ Raises
204
+ ------
205
+ ValueError
206
+ If the lengths of any variable array do not match the number of times.
207
+ """
208
+ # Ensure all input arrays are of the same length
209
+ if not all(len(values) == len(times) for values in variables.values()):
210
+ err_msg = "All input arrays must have the same length."
211
+ raise ValueError(err_msg)
212
+
213
+ # Add each data point
214
+ for time, variable_values in zip(
215
+ times,
216
+ zip(*variables.values(), strict=False),
217
+ strict=False,
218
+ ):
219
+ self.add_point(
220
+ time,
221
+ dict(
222
+ zip(
223
+ variables.keys(),
224
+ variable_values,
225
+ strict=False,
226
+ )
227
+ ),
228
+ )
@@ -0,0 +1,19 @@
1
+ """Package bindings to the Tempest Extremes tracking code."""
2
+
3
+ from .tempest_extremes import (
4
+ TEContour,
5
+ TEDetectParameters,
6
+ TEOutputCommand,
7
+ TEStitchParameters,
8
+ TEThreshold,
9
+ TETracker,
10
+ )
11
+
12
+ __all__ = [
13
+ "TEContour",
14
+ "TEDetectParameters",
15
+ "TEOutputCommand",
16
+ "TEStitchParameters",
17
+ "TEThreshold",
18
+ "TETracker",
19
+ ]