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
|
@@ -0,0 +1,1075 @@
|
|
|
1
|
+
"""Module providing classes that bind the TSTORMS code.
|
|
2
|
+
|
|
3
|
+
References
|
|
4
|
+
----------
|
|
5
|
+
- TSTORMS NOAA page: https://www.gfdl.noaa.gov/tstorms/
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import subprocess
|
|
11
|
+
import tempfile
|
|
12
|
+
import textwrap
|
|
13
|
+
import warnings
|
|
14
|
+
from dataclasses import asdict, dataclass
|
|
15
|
+
|
|
16
|
+
import cf
|
|
17
|
+
from cftime import num2date
|
|
18
|
+
from netCDF4 import Dataset
|
|
19
|
+
|
|
20
|
+
from tctrack.core import TCTracker, TCTrackerMetadata, TCTrackerParameters, Trajectory
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(repr=False)
|
|
24
|
+
class TSTORMSBaseParameters(TCTrackerParameters):
|
|
25
|
+
"""
|
|
26
|
+
Dataclass containing values used in configuring the TSTORMS install.
|
|
27
|
+
|
|
28
|
+
This class is intended to configure the install so that executables can be run
|
|
29
|
+
correctly and data stored in a desired location.
|
|
30
|
+
Configuration of the actual cyclone detection algorithm is done using
|
|
31
|
+
:class:`TSTORMSDetectParameters` and :class:`TSTORMSStitchParameters`.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
tstorms_dir: str
|
|
35
|
+
"""
|
|
36
|
+
Full path to the TSTORMS installation directory. This will be likely be a directory
|
|
37
|
+
named `tropical_storms_pub/` and should contain `tstorms_driver/` and
|
|
38
|
+
`trajectory_analysis/` subdirectories.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
output_dir: str
|
|
42
|
+
"""
|
|
43
|
+
Full path to the directory where TSTORMS outputs should be deposited.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
input_dir: str = ""
|
|
47
|
+
"""
|
|
48
|
+
Full path to the directory where TSTORMS input files can be found.
|
|
49
|
+
Defaults to empty string which will load from current directory.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(repr=False)
|
|
54
|
+
class TSTORMSDetectParameters(TCTrackerParameters):
|
|
55
|
+
"""
|
|
56
|
+
Dataclass of values used by the Driver operation of TSTORMS for candidate detection.
|
|
57
|
+
|
|
58
|
+
Default values are set to match those in the TSTORMS tstorms_driver source-code.
|
|
59
|
+
|
|
60
|
+
Raises
|
|
61
|
+
------
|
|
62
|
+
ValueError
|
|
63
|
+
- If northern latitude bound is less than the southern latitude bound.
|
|
64
|
+
- If any of the input file filenames are left as ``None``.
|
|
65
|
+
UserWarning
|
|
66
|
+
- If do_thickness is set to True as this has no effect.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
u_in_file: str
|
|
70
|
+
"""
|
|
71
|
+
Filename of the u (zonal) velocity input file.
|
|
72
|
+
This should be a NetCDF file containing a single lat-lon slice of the u field named
|
|
73
|
+
``u_ref`` (if :attr:`use_sfc_wind` is ``True``) or ``u850``.
|
|
74
|
+
This should be the full path unless the location of input files was specified in
|
|
75
|
+
:class:`TSTORMSBaseParameters`' ``input_dir``.
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
v_in_file: str
|
|
79
|
+
"""
|
|
80
|
+
Filename of the v (meridional) velocity input file.
|
|
81
|
+
This should be a NetCDF file containing a single lat-lon slice of the v field named
|
|
82
|
+
``v_ref`` (if :attr:`use_sfc_wind` is ``True``) or ``v850``.
|
|
83
|
+
This should be the full path unless the location of input files was specified in
|
|
84
|
+
:class:`TSTORMSBaseParameters`' ``input_dir``.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
vort_in_file: str
|
|
88
|
+
"""
|
|
89
|
+
Filename of the vorticity input file.
|
|
90
|
+
This should be a NetCDF file containing a single lat-lon slice of the vorticity
|
|
91
|
+
field named ``vort850`` at the 850 hPa level.
|
|
92
|
+
This should be the full path unless the location of input files was specified in
|
|
93
|
+
:class:`TSTORMSBaseParameters`' ``input_dir``.
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
tm_in_file: str
|
|
97
|
+
"""
|
|
98
|
+
Filename of the temperature input file.
|
|
99
|
+
This should be a NetCDF file containing a single lat-lon slice of the mean
|
|
100
|
+
temperature of the warm-core layer named ``tm``.
|
|
101
|
+
This should be the full path unless the location of input files was specified in
|
|
102
|
+
:class:`TSTORMSBaseParameters`' ``input_dir``.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
slp_in_file: str
|
|
106
|
+
"""
|
|
107
|
+
Filename of the sea-level pressure input file.
|
|
108
|
+
This should be a NetCDF file containing a single lat-lon slice of sea-level pressure
|
|
109
|
+
named ``slp``.
|
|
110
|
+
This should be the full path unless the location of input files was specified in
|
|
111
|
+
:class:`TSTORMSBaseParameters`' ``input_dir``.
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
use_sfc_wind: bool = True
|
|
115
|
+
"""
|
|
116
|
+
Whether to use surface winds (``True``), or winds at 850 hPa level.
|
|
117
|
+
"""
|
|
118
|
+
|
|
119
|
+
vort_crit: float = 3.5e-5
|
|
120
|
+
"""
|
|
121
|
+
Critical vorticity threshold [s-1] to be exceeded to qualify as a candidate storm.
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
tm_crit: float = 0.5
|
|
125
|
+
"""
|
|
126
|
+
Critical warm core local maximum to be exceeded to qualify as a candidate storm.
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
thick_crit: float = 50.0
|
|
130
|
+
"""
|
|
131
|
+
Critical thickness threshold to be exceeded to qualify as a candidate storm.
|
|
132
|
+
Note that thickness calculations are not yet implemented in TSTORMS.
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
dist_crit: float = 4.0
|
|
136
|
+
"""
|
|
137
|
+
Critical radius [degrees] within which vorticity, sea-level pressure, and other
|
|
138
|
+
maxima/minima must lie within each other to qualify as a candidate storm.
|
|
139
|
+
"""
|
|
140
|
+
|
|
141
|
+
lat_bound_n: float = 90.0
|
|
142
|
+
"""
|
|
143
|
+
Northern latitude bound [degrees] below which storm detection should occur.
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
lat_bound_s: float = -90.0
|
|
147
|
+
"""
|
|
148
|
+
Southern latitude bound [degrees] above which storm detection should occur.
|
|
149
|
+
"""
|
|
150
|
+
|
|
151
|
+
do_spline: bool = False
|
|
152
|
+
"""
|
|
153
|
+
Whether to use splines for detecting minma instead of gridpointwise search.
|
|
154
|
+
"""
|
|
155
|
+
|
|
156
|
+
do_thickness: bool = False
|
|
157
|
+
"""
|
|
158
|
+
Whether to use thickness of the 200-1000 hPa layer as a variable for detecting
|
|
159
|
+
candidate storms. Note that this functionality is not yet implemented in TSTORMS.
|
|
160
|
+
"""
|
|
161
|
+
|
|
162
|
+
def __post_init__(self):
|
|
163
|
+
"""Validate parameters."""
|
|
164
|
+
if self.lat_bound_n < self.lat_bound_s:
|
|
165
|
+
msg = (
|
|
166
|
+
f"Northern latitude bound ({self.lat_bound_n}) is less than "
|
|
167
|
+
f"Southern latitude bound ({self.lat_bound_s})."
|
|
168
|
+
)
|
|
169
|
+
raise ValueError(msg)
|
|
170
|
+
if self.do_thickness:
|
|
171
|
+
msg = (
|
|
172
|
+
"`do_thickness` is set, but will have no effect as this feature is not "
|
|
173
|
+
"implemented in TSTORMS."
|
|
174
|
+
)
|
|
175
|
+
warnings.warn(msg, category=UserWarning, stacklevel=3)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@dataclass(repr=False)
|
|
179
|
+
class TSTORMSStitchParameters(TCTrackerParameters):
|
|
180
|
+
"""
|
|
181
|
+
Dataclass containing values used by the stitching trajectory operation of TSTORMS.
|
|
182
|
+
|
|
183
|
+
Default values are set to match those in the TSTORMS trajectory_analysis
|
|
184
|
+
source-code.
|
|
185
|
+
|
|
186
|
+
Raises
|
|
187
|
+
------
|
|
188
|
+
ValueError
|
|
189
|
+
If northern latitude bound is less than the southern latitude bound.
|
|
190
|
+
UserWarning
|
|
191
|
+
If do_thickness is set to True as this has no effect.
|
|
192
|
+
"""
|
|
193
|
+
|
|
194
|
+
r_crit: float = 900.0
|
|
195
|
+
"""Maximum daily track length [km] between succcessive points in a trajectory."""
|
|
196
|
+
|
|
197
|
+
wind_crit: float = 17.0
|
|
198
|
+
"""Critical wind speed [m/s] for trajectory calculations."""
|
|
199
|
+
|
|
200
|
+
vort_crit: float = 3.5e-5
|
|
201
|
+
"""Critical vorticity threshold [s-1] for trajectory calculations."""
|
|
202
|
+
|
|
203
|
+
tm_crit: float = 0.5
|
|
204
|
+
"""Critical warm core threshold for trajectory calculations."""
|
|
205
|
+
|
|
206
|
+
thick_crit: float = 50.0
|
|
207
|
+
"""Critical thickness threshold for trajectory calculations."""
|
|
208
|
+
|
|
209
|
+
n_day_crit: int = 2
|
|
210
|
+
"""Minimum number of days a trajectory must last to be valid."""
|
|
211
|
+
|
|
212
|
+
do_filter: bool = True
|
|
213
|
+
r"""
|
|
214
|
+
Whether to apply filtering of trajectories.
|
|
215
|
+
Filtering is based on landmask and lat-lon bounds to generate \*_filt output files.
|
|
216
|
+
"""
|
|
217
|
+
|
|
218
|
+
lat_bound_n: float = 40.0
|
|
219
|
+
"""Northern latitude bound [degrees] for trajectory filtering."""
|
|
220
|
+
|
|
221
|
+
lat_bound_s: float = -40.0
|
|
222
|
+
"""Southern latitude bound [degrees] for trajectory filtering."""
|
|
223
|
+
|
|
224
|
+
do_spline: bool = False
|
|
225
|
+
"""
|
|
226
|
+
Whether to use splines for trajectory calculations.
|
|
227
|
+
Should match the value used in the Driver routine.
|
|
228
|
+
If splines used then :attr:`twc_crit` and :attr:`thick_crit` will not be used in
|
|
229
|
+
comparisons.
|
|
230
|
+
"""
|
|
231
|
+
|
|
232
|
+
do_thickness: bool = False
|
|
233
|
+
"""
|
|
234
|
+
Whether to use thickness of the 200-1000 hPa layer as a variable for detecting
|
|
235
|
+
candidate storms. Note that this functionality is not yet implemented in TSTORMS.
|
|
236
|
+
"""
|
|
237
|
+
|
|
238
|
+
def __post_init__(self):
|
|
239
|
+
"""Validate parameters."""
|
|
240
|
+
if self.lat_bound_n < self.lat_bound_s:
|
|
241
|
+
msg = (
|
|
242
|
+
f"Northern latitude bound ({self.lat_bound_n}) is less than "
|
|
243
|
+
f"Southern latitude bound ({self.lat_bound_s})."
|
|
244
|
+
)
|
|
245
|
+
raise ValueError(msg)
|
|
246
|
+
if self.do_thickness:
|
|
247
|
+
msg = (
|
|
248
|
+
"`do_thickness` is set, but will have no effect as this feature is not "
|
|
249
|
+
"implemented in TSTORMS."
|
|
250
|
+
)
|
|
251
|
+
warnings.warn(msg, category=UserWarning, stacklevel=3)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
class TSTORMSTracker(TCTracker):
|
|
255
|
+
"""Class containing bindings to the TSTORMS code.
|
|
256
|
+
|
|
257
|
+
Attributes
|
|
258
|
+
----------
|
|
259
|
+
driver_parameters : TSTORMSDetectParameters | None
|
|
260
|
+
Class containing the parameters for the driver detection algorithm
|
|
261
|
+
trajectory_parameters : TSTORMSStitchParameters | None
|
|
262
|
+
Class containing the parameters for the trajectory stitching algorithm
|
|
263
|
+
"""
|
|
264
|
+
|
|
265
|
+
# Private attributes
|
|
266
|
+
_tempdir: tempfile.TemporaryDirectory
|
|
267
|
+
|
|
268
|
+
def __init__(
|
|
269
|
+
self,
|
|
270
|
+
tstorms_parameters: TSTORMSBaseParameters,
|
|
271
|
+
detect_parameters: TSTORMSDetectParameters,
|
|
272
|
+
stitch_parameters: TSTORMSStitchParameters | None = None,
|
|
273
|
+
):
|
|
274
|
+
"""
|
|
275
|
+
Construct the TSTORMSTracker class.
|
|
276
|
+
|
|
277
|
+
Parameters
|
|
278
|
+
----------
|
|
279
|
+
tstorms_parameters : TSTORMSBaseParameters
|
|
280
|
+
Class containing the parameters for setting up TSTORMS usage.
|
|
281
|
+
detect_parameters : TSTORMSDetectParameters
|
|
282
|
+
Class containing the parameters for the node detection in TSTORMS.
|
|
283
|
+
Used to create the namelists for `tstorms_driver`.
|
|
284
|
+
stitch_parameters : TSTORMSStitchParameters | None
|
|
285
|
+
Class containing the parameters for the stitching algorithm of TSTORMS
|
|
286
|
+
Defaults to the default values in TSTORMSStitchParameters Class
|
|
287
|
+
"""
|
|
288
|
+
self.tstorms_parameters: TSTORMSBaseParameters = tstorms_parameters
|
|
289
|
+
self.detect_parameters: TSTORMSDetectParameters = detect_parameters
|
|
290
|
+
|
|
291
|
+
if stitch_parameters is not None:
|
|
292
|
+
self.stitch_parameters: TSTORMSStitchParameters = stitch_parameters
|
|
293
|
+
else:
|
|
294
|
+
self.stitch_parameters = TSTORMSStitchParameters()
|
|
295
|
+
|
|
296
|
+
# Ensure the output directory exists, create if not.
|
|
297
|
+
output_dir = self.tstorms_parameters.output_dir
|
|
298
|
+
os.makedirs(output_dir, exist_ok=True)
|
|
299
|
+
|
|
300
|
+
def _run_tstorms_process(
|
|
301
|
+
self,
|
|
302
|
+
command_name: str,
|
|
303
|
+
command_list: list[str],
|
|
304
|
+
input_file: str,
|
|
305
|
+
verbose: bool = False,
|
|
306
|
+
):
|
|
307
|
+
"""Run a TSTORMS command.
|
|
308
|
+
|
|
309
|
+
Parameters
|
|
310
|
+
----------
|
|
311
|
+
command_name : str
|
|
312
|
+
The name of the command to be used in the log and error reporting.
|
|
313
|
+
command_list : list[str]
|
|
314
|
+
The list of strings that produce the command as given by
|
|
315
|
+
_make_driver_call and _make_trajectories_call.
|
|
316
|
+
input_file : str
|
|
317
|
+
Path to an input file to be passed to the command's stdin (e.g. namelist).
|
|
318
|
+
Defaults to None.
|
|
319
|
+
verbose : bool
|
|
320
|
+
Whether to print the entire TSTORMS output to screen in real-time or just
|
|
321
|
+
the start/end summary. Defaults to False.
|
|
322
|
+
|
|
323
|
+
Returns
|
|
324
|
+
-------
|
|
325
|
+
dict
|
|
326
|
+
dict of subprocess output corresponding to stdout, stderr, and returncode.
|
|
327
|
+
|
|
328
|
+
Raises
|
|
329
|
+
------
|
|
330
|
+
FileNotFoundError
|
|
331
|
+
If the tstorms executable from cannot be found.
|
|
332
|
+
RuntimeError
|
|
333
|
+
If tstorms executable returns a non-zero exit code.
|
|
334
|
+
"""
|
|
335
|
+
# Execute subproces commands from output_dir so outputs appear there.
|
|
336
|
+
output_dir = self.tstorms_parameters.output_dir
|
|
337
|
+
try:
|
|
338
|
+
if verbose:
|
|
339
|
+
with open(input_file, "r") as stdin:
|
|
340
|
+
# Real-time output with Popen
|
|
341
|
+
process = subprocess.Popen( # noqa: S603 - no shell
|
|
342
|
+
command_list,
|
|
343
|
+
stdin=stdin,
|
|
344
|
+
stdout=subprocess.PIPE,
|
|
345
|
+
stderr=subprocess.PIPE,
|
|
346
|
+
text=True,
|
|
347
|
+
shell=False,
|
|
348
|
+
bufsize=1, # Line-buffered output
|
|
349
|
+
cwd=output_dir,
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
# Print stdout in real-time
|
|
353
|
+
for line in iter(process.stdout.readline, ""): # type: ignore[union-attr]
|
|
354
|
+
print(line, end="")
|
|
355
|
+
|
|
356
|
+
stdout, stderr = process.communicate()
|
|
357
|
+
returncode = process.returncode
|
|
358
|
+
|
|
359
|
+
if returncode != 0:
|
|
360
|
+
err_msg = (
|
|
361
|
+
f"{command_name} failed with a non-zero exit code: "
|
|
362
|
+
f"{returncode}:\n{stderr}"
|
|
363
|
+
)
|
|
364
|
+
raise RuntimeError(err_msg)
|
|
365
|
+
else:
|
|
366
|
+
# verbose=False: Concise output print start/end summary
|
|
367
|
+
with open(input_file, "r") as stdin:
|
|
368
|
+
print(f"Executing {command_name}...")
|
|
369
|
+
result = subprocess.run( # noqa: S603 - no shell
|
|
370
|
+
command_list,
|
|
371
|
+
stdin=stdin,
|
|
372
|
+
check=True,
|
|
373
|
+
capture_output=True,
|
|
374
|
+
text=True,
|
|
375
|
+
cwd=output_dir,
|
|
376
|
+
)
|
|
377
|
+
stdout, stderr, returncode = (
|
|
378
|
+
result.stdout,
|
|
379
|
+
result.stderr,
|
|
380
|
+
result.returncode,
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
print(f"{command_name} completed successfully.")
|
|
384
|
+
print(
|
|
385
|
+
f"First 12 lines of output:\n"
|
|
386
|
+
f"{''.join(stdout.splitlines(True)[:12])}"
|
|
387
|
+
f"\n...\n\n"
|
|
388
|
+
f"Last 12 lines of output:\n"
|
|
389
|
+
f"{''.join(stdout.splitlines(True)[-12:])}"
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
return {
|
|
393
|
+
"stdout": stdout,
|
|
394
|
+
"stderr": stderr,
|
|
395
|
+
"returncode": returncode,
|
|
396
|
+
}
|
|
397
|
+
except FileNotFoundError as exc:
|
|
398
|
+
msg = f"{command_name} failed because the executable could not be found."
|
|
399
|
+
raise FileNotFoundError(msg) from exc
|
|
400
|
+
except subprocess.CalledProcessError as exc:
|
|
401
|
+
msg = (
|
|
402
|
+
f"{command_name} failed with a non-zero exit code:"
|
|
403
|
+
f"({exc.returncode}):\n"
|
|
404
|
+
f"{exc.stderr}"
|
|
405
|
+
)
|
|
406
|
+
raise RuntimeError(msg) from exc
|
|
407
|
+
|
|
408
|
+
def _write_driver_namelist(self) -> str:
|
|
409
|
+
"""
|
|
410
|
+
Generate the namelist file for the tstorms_driver routine.
|
|
411
|
+
|
|
412
|
+
The namelist file will be written to the ``output_dir`` specified in
|
|
413
|
+
:attr:`tstorms_parameters`.
|
|
414
|
+
|
|
415
|
+
Returns
|
|
416
|
+
-------
|
|
417
|
+
str
|
|
418
|
+
The full path to the generated namelist file.
|
|
419
|
+
|
|
420
|
+
Raises
|
|
421
|
+
------
|
|
422
|
+
FileNotFoundError
|
|
423
|
+
If the `tstorms_dir` does not exist.
|
|
424
|
+
"""
|
|
425
|
+
# Ensure the output_dir exists to place namelist in
|
|
426
|
+
output_dir = self.tstorms_parameters.output_dir
|
|
427
|
+
if not os.path.exists(output_dir):
|
|
428
|
+
err_msg = f"TSTORMS output directory '{output_dir}' does not exist."
|
|
429
|
+
raise FileNotFoundError(err_msg)
|
|
430
|
+
|
|
431
|
+
namelist_path = os.path.join(output_dir, "nml_driver")
|
|
432
|
+
|
|
433
|
+
# Format the namelist content
|
|
434
|
+
input_dir = self.tstorms_parameters.input_dir
|
|
435
|
+
detect_params = self.detect_parameters
|
|
436
|
+
namelist_content = textwrap.dedent(f"""
|
|
437
|
+
&nml_tstorms
|
|
438
|
+
crit_vort = {detect_params.vort_crit:.4E}
|
|
439
|
+
crit_twc = {detect_params.tm_crit:.4f}
|
|
440
|
+
crit_thick = {detect_params.thick_crit:.4f}
|
|
441
|
+
crit_dist = {detect_params.dist_crit:.4f}
|
|
442
|
+
lat_bound_n = {detect_params.lat_bound_n:.4f}
|
|
443
|
+
lat_bound_s = {detect_params.lat_bound_s:.4f}
|
|
444
|
+
do_spline = {".true." if detect_params.do_spline else ".false."}
|
|
445
|
+
do_thickness= {".true." if detect_params.do_thickness else ".false."}
|
|
446
|
+
&end
|
|
447
|
+
&input
|
|
448
|
+
fn_u = '{os.path.join(input_dir, detect_params.u_in_file)}'
|
|
449
|
+
fn_v = '{os.path.join(input_dir, detect_params.v_in_file)}'
|
|
450
|
+
fn_vort = '{os.path.join(input_dir, detect_params.vort_in_file)}'
|
|
451
|
+
fn_tm = '{os.path.join(input_dir, detect_params.tm_in_file)}'
|
|
452
|
+
fn_slp = '{os.path.join(input_dir, detect_params.slp_in_file)}'
|
|
453
|
+
use_sfc_wnd = {".true." if detect_params.use_sfc_wind else ".false."}
|
|
454
|
+
&end
|
|
455
|
+
""")
|
|
456
|
+
|
|
457
|
+
# Write the namelist content to the file
|
|
458
|
+
with open(namelist_path, "w") as namelist_file:
|
|
459
|
+
namelist_file.write(namelist_content)
|
|
460
|
+
|
|
461
|
+
return namelist_path
|
|
462
|
+
|
|
463
|
+
def _make_driver_call(self):
|
|
464
|
+
"""
|
|
465
|
+
Construct a driver call based on options set in driver_parameters.
|
|
466
|
+
|
|
467
|
+
Makes a call to write the namelist and then construct and call the driver
|
|
468
|
+
command.
|
|
469
|
+
|
|
470
|
+
Returns
|
|
471
|
+
-------
|
|
472
|
+
list[str]
|
|
473
|
+
list of strings that can be combined to form a driver command
|
|
474
|
+
based on the parameters set in self.detect_parameters
|
|
475
|
+
"""
|
|
476
|
+
tstorms_driver_dir = os.path.join(
|
|
477
|
+
self.tstorms_parameters.tstorms_dir, "tstorms_driver"
|
|
478
|
+
)
|
|
479
|
+
dn_argslist = [os.path.join(tstorms_driver_dir, "tstorms_driver.exe")]
|
|
480
|
+
|
|
481
|
+
return dn_argslist
|
|
482
|
+
|
|
483
|
+
def detect(self, verbose=False):
|
|
484
|
+
"""
|
|
485
|
+
Call the driver utility of TSTORMS.
|
|
486
|
+
|
|
487
|
+
This will make a system call out to the tstorms_driver code from TSTORMS
|
|
488
|
+
(provided it has been installed as an external dependency). This will be
|
|
489
|
+
run according to the parameters in the :attr:`detect_parameters` attribute
|
|
490
|
+
that were set when the :class:`TSTORMSTracker` instance was created.
|
|
491
|
+
|
|
492
|
+
The output file is a plain text file named ``cyclones`` containing each of the
|
|
493
|
+
TC candidates at each time from the input files. This will be generated
|
|
494
|
+
in the desired output location provided in the base parameters attribute
|
|
495
|
+
:attr:`tstorms_parameters`.
|
|
496
|
+
Cyclones in the file are listed for each time in the format:
|
|
497
|
+
|
|
498
|
+
.. code-block:: text
|
|
499
|
+
|
|
500
|
+
<day> <month> <year> <number> <hour>
|
|
501
|
+
<i_index> <j_index> <lon_slpmin> <lat_slpmin>
|
|
502
|
+
<max_wind> <max_vort> <min_slp> <exist_warm_core> <exist_thickness>
|
|
503
|
+
<max_warm_core> <max_thickness>
|
|
504
|
+
...
|
|
505
|
+
|
|
506
|
+
- ``number`` is the number of nodes at that time.
|
|
507
|
+
- ``i_index``, ``j_index`` are the grid indices of the node.
|
|
508
|
+
- ``lon_slpmin``, ``lat_slpmin`` are the coordinates of the slp minimum.
|
|
509
|
+
- Other values are the variable values for the cyclone output from the code.
|
|
510
|
+
|
|
511
|
+
Parameters
|
|
512
|
+
----------
|
|
513
|
+
verbose : bool
|
|
514
|
+
Whether to print the entire TSTORMS output to screen in real-time or just
|
|
515
|
+
the start/end summary.
|
|
516
|
+
Defaults to False.
|
|
517
|
+
|
|
518
|
+
Returns
|
|
519
|
+
-------
|
|
520
|
+
dict
|
|
521
|
+
dict of subprocess output corresponding to stdout, stderr, and returncode.
|
|
522
|
+
|
|
523
|
+
Raises
|
|
524
|
+
------
|
|
525
|
+
FileNotFoundError
|
|
526
|
+
If the tstorms_driver executeable from TSTORMS cannot be found.
|
|
527
|
+
RuntimeError
|
|
528
|
+
If the tstorms_driver executeable from TSTORMS returns a non-zero exit code.
|
|
529
|
+
|
|
530
|
+
Examples
|
|
531
|
+
--------
|
|
532
|
+
To set the parameters, instantiate a :class:`TSTORMSTracker` instance and run
|
|
533
|
+
detect:
|
|
534
|
+
|
|
535
|
+
>>> base_params = TSTORMSBaseParameters(...)
|
|
536
|
+
>>> detect_params = TSTORMSDetectParameters(...)
|
|
537
|
+
>>> my_tracker = TSTORMSTracker(
|
|
538
|
+
tstorms_parameters=base_params,
|
|
539
|
+
detect_parameters=detect_params
|
|
540
|
+
)
|
|
541
|
+
>>> result = my_tracker.detect()
|
|
542
|
+
"""
|
|
543
|
+
namelist_filepath = self._write_driver_namelist()
|
|
544
|
+
driver_call_list = self._make_driver_call()
|
|
545
|
+
process_output = self._run_tstorms_process(
|
|
546
|
+
"Detect", driver_call_list, namelist_filepath, verbose=verbose
|
|
547
|
+
)
|
|
548
|
+
|
|
549
|
+
return process_output
|
|
550
|
+
|
|
551
|
+
def _write_trajectory_analysis_namelist(self) -> str:
|
|
552
|
+
"""Generate the namelist file for the trajectory_analysis routine.
|
|
553
|
+
|
|
554
|
+
The namelist file will be written to the ``output_dir`` specified in
|
|
555
|
+
:attr:`tstorms_parameters`.
|
|
556
|
+
|
|
557
|
+
Returns
|
|
558
|
+
-------
|
|
559
|
+
str
|
|
560
|
+
The full path to the generated namelist file.
|
|
561
|
+
|
|
562
|
+
Raises
|
|
563
|
+
------
|
|
564
|
+
FileNotFoundError
|
|
565
|
+
If the `trajectory_analysis` directory does not exist.
|
|
566
|
+
"""
|
|
567
|
+
tstorms_dir = self.tstorms_parameters.tstorms_dir
|
|
568
|
+
# Ensure the output_dir exists to place namelist in
|
|
569
|
+
output_dir = self.tstorms_parameters.output_dir
|
|
570
|
+
if not os.path.exists(output_dir):
|
|
571
|
+
err_msg = f"TSTORMS output directory '{output_dir}' does not exist."
|
|
572
|
+
raise FileNotFoundError(err_msg)
|
|
573
|
+
|
|
574
|
+
# Define the namelist file path
|
|
575
|
+
namelist_path = os.path.join(output_dir, "nml_traj")
|
|
576
|
+
|
|
577
|
+
# Format the namelist content
|
|
578
|
+
stitch_params = self.stitch_parameters
|
|
579
|
+
namelist_content = textwrap.dedent(f"""
|
|
580
|
+
&input
|
|
581
|
+
rcrit = {stitch_params.r_crit:.4f}
|
|
582
|
+
wcrit = {stitch_params.wind_crit:.4f}
|
|
583
|
+
vcrit = {stitch_params.vort_crit:.4E}
|
|
584
|
+
twc_crit = {stitch_params.tm_crit:.4f}
|
|
585
|
+
thick_crit = {stitch_params.thick_crit:.4f}
|
|
586
|
+
nwcrit = {stitch_params.n_day_crit:.4f}
|
|
587
|
+
do_filt = {".true." if stitch_params.do_filter else ".false."}
|
|
588
|
+
nlat = {stitch_params.lat_bound_n:.4f}
|
|
589
|
+
slat = {stitch_params.lat_bound_s:.4f}
|
|
590
|
+
do_spline = {".true." if stitch_params.do_spline else ".false."}
|
|
591
|
+
do_thickness = {".true." if stitch_params.do_thickness else ".false."}
|
|
592
|
+
landmask = '{os.path.join(tstorms_dir, "trajectory_analysis/landsea.map")}'
|
|
593
|
+
cmask = '{os.path.join(tstorms_dir, "trajectory_analysis/imask_2")}'
|
|
594
|
+
&end
|
|
595
|
+
""")
|
|
596
|
+
|
|
597
|
+
# Write the namelist content to the file
|
|
598
|
+
with open(namelist_path, "w") as namelist_file:
|
|
599
|
+
namelist_file.write(namelist_content)
|
|
600
|
+
|
|
601
|
+
return namelist_path
|
|
602
|
+
|
|
603
|
+
def _make_trajectory_analysis_call(self):
|
|
604
|
+
"""
|
|
605
|
+
Construct a trajectory_analysis call based on options set in stitch_parameters.
|
|
606
|
+
|
|
607
|
+
Makes a call to write the namelist and then construct and call the
|
|
608
|
+
trajectory_analysis command.
|
|
609
|
+
|
|
610
|
+
Returns
|
|
611
|
+
-------
|
|
612
|
+
list[str]
|
|
613
|
+
list of strings that can be combined to form a trajectory_analysis command
|
|
614
|
+
based on the parameters set in self.stitch_parameters
|
|
615
|
+
"""
|
|
616
|
+
tstorms_trajectory_analysis_dir = os.path.join(
|
|
617
|
+
self.tstorms_parameters.tstorms_dir, "trajectory_analysis"
|
|
618
|
+
)
|
|
619
|
+
stitch_argslist = [
|
|
620
|
+
os.path.join(tstorms_trajectory_analysis_dir, "trajectory_analysis_csc.exe")
|
|
621
|
+
]
|
|
622
|
+
|
|
623
|
+
return stitch_argslist
|
|
624
|
+
|
|
625
|
+
def stitch(self, verbose=False):
|
|
626
|
+
"""
|
|
627
|
+
Call the trajectory analysis utility of TSTORMS to stitch candidate storms.
|
|
628
|
+
|
|
629
|
+
This will make a system call out to the trajectory_analysis code from TSTORMS
|
|
630
|
+
(provided it has been installed as an external dependency). This will be
|
|
631
|
+
run according to the parameters in the :attr:`stitch_parameters` attribute
|
|
632
|
+
that were set when the :class:`TSTORMSTracker` instance was created.
|
|
633
|
+
It assumes that the candidate storms are contained in the output_dir
|
|
634
|
+
directory in a file ``cyclones`` text file.
|
|
635
|
+
|
|
636
|
+
The outputs are plain text files named:
|
|
637
|
+
|
|
638
|
+
- ``ori`` containing the origins of each storm in the form
|
|
639
|
+
``lon, lat, YY, MM, DD, HH``,
|
|
640
|
+
- ``traj`` containing trajectory point data in the form
|
|
641
|
+
``lon, lat, wind, psl, YY, MM, DD, HH`` for each trajectory,
|
|
642
|
+
- ``trav`` containing trajectory point data and vorticity in the form
|
|
643
|
+
``lon, lat, wind, psl, vort_max, YY, MM, DD, HH`` for each trajectory,
|
|
644
|
+
- ``stats`` containing information about the number of storms per month/year
|
|
645
|
+
in each basin.
|
|
646
|
+
|
|
647
|
+
If filtering is applied (:attr:`stitch_parameters` ``do_filter``) there will be
|
|
648
|
+
additional files ``ori_filt``, ``traj_filt``, and ``trav_filt`` from after this
|
|
649
|
+
takes place.
|
|
650
|
+
These files will be generated in the desired output location provided in the
|
|
651
|
+
base parameters attribute :attr:`tstorms_parameters`.
|
|
652
|
+
|
|
653
|
+
Parameters
|
|
654
|
+
----------
|
|
655
|
+
verbose : bool
|
|
656
|
+
Whether to print the entire TSTORMS output to screen in real-time or just
|
|
657
|
+
the start/end summary.
|
|
658
|
+
Defaults to False.
|
|
659
|
+
|
|
660
|
+
Returns
|
|
661
|
+
-------
|
|
662
|
+
dict
|
|
663
|
+
dict of subprocess output corresponding to stdout, stderr, and returncode.
|
|
664
|
+
|
|
665
|
+
Raises
|
|
666
|
+
------
|
|
667
|
+
FileNotFoundError
|
|
668
|
+
If the trajectory_analysis executeable from TSTORMS cannot be found.
|
|
669
|
+
RuntimeError
|
|
670
|
+
If the trajectory_analysis executeable from TSTORMS returns a non-zero
|
|
671
|
+
exit code.
|
|
672
|
+
|
|
673
|
+
Examples
|
|
674
|
+
--------
|
|
675
|
+
To set the parameters, instantiate a :class:`TSTORMSTracker` instance and run
|
|
676
|
+
stitch:
|
|
677
|
+
|
|
678
|
+
>>> base_params = TSTORMSBaseParameters(...)
|
|
679
|
+
>>> stitch_params = TSTORMSStitchParameters(...)
|
|
680
|
+
>>> stitch_params = TSTORMSTracker(
|
|
681
|
+
tstorms_parameters=base_params,
|
|
682
|
+
stitch_parameters=stitch_params
|
|
683
|
+
)
|
|
684
|
+
>>> result = my_tracker.stitch()
|
|
685
|
+
"""
|
|
686
|
+
# Check if the cyclones file exists before proceeding
|
|
687
|
+
cyclones_file = os.path.join(self.tstorms_parameters.output_dir, "cyclones")
|
|
688
|
+
if not os.path.exists(cyclones_file):
|
|
689
|
+
err_msg = (
|
|
690
|
+
"No cyclones file found in the output directory. "
|
|
691
|
+
"Did you forget to run `detect` or delete the file?"
|
|
692
|
+
)
|
|
693
|
+
raise FileNotFoundError(err_msg)
|
|
694
|
+
|
|
695
|
+
namelist_filepath = self._write_trajectory_analysis_namelist()
|
|
696
|
+
trajectory_call_list = self._make_trajectory_analysis_call()
|
|
697
|
+
process_output = self._run_tstorms_process(
|
|
698
|
+
"Stitch", trajectory_call_list, namelist_filepath, verbose=verbose
|
|
699
|
+
)
|
|
700
|
+
|
|
701
|
+
return process_output
|
|
702
|
+
|
|
703
|
+
def set_metadata(self) -> None:
|
|
704
|
+
"""
|
|
705
|
+
Set the global and variable (reading from input files) metadata attributes.
|
|
706
|
+
|
|
707
|
+
Reads metadata for each variable from the input NetCDF files
|
|
708
|
+
defined in :attr:`detect_parameters`.
|
|
709
|
+
These will be stored in the :attr:`variable_metadata` attribute as a
|
|
710
|
+
dictionary of :class:`TCTrackerMetadata` objects.
|
|
711
|
+
This will be called from the :meth:`to_netcdf` method.
|
|
712
|
+
|
|
713
|
+
Raises
|
|
714
|
+
------
|
|
715
|
+
ValueError
|
|
716
|
+
If a variable is not found in the input files.
|
|
717
|
+
|
|
718
|
+
Examples
|
|
719
|
+
--------
|
|
720
|
+
To generate in the metadata for variables from parameters and inputs:
|
|
721
|
+
|
|
722
|
+
>>> tracker = TSTORMSTracker(tstorms_params, detect_params, stitch_params)
|
|
723
|
+
>>> tracker.set_metadata()
|
|
724
|
+
>>> tracker.variable_metadata
|
|
725
|
+
{
|
|
726
|
+
"wind_speed": TCTrackerMetadata(
|
|
727
|
+
properties={
|
|
728
|
+
"standard_name": "wind_speed",
|
|
729
|
+
"long_name": "Wind Speed",
|
|
730
|
+
...
|
|
731
|
+
},
|
|
732
|
+
)
|
|
733
|
+
...
|
|
734
|
+
}
|
|
735
|
+
"""
|
|
736
|
+
super().set_metadata()
|
|
737
|
+
|
|
738
|
+
tstorms_params_json = json.dumps(asdict(self.tstorms_parameters))
|
|
739
|
+
detect_params_json = json.dumps(asdict(self.detect_parameters))
|
|
740
|
+
stitch_params_json = json.dumps(asdict(self.stitch_parameters))
|
|
741
|
+
self.global_metadata["tstorms_parameters"] = tstorms_params_json
|
|
742
|
+
self.global_metadata["detect_parameters"] = detect_params_json
|
|
743
|
+
self.global_metadata["stitch_parameters"] = stitch_params_json
|
|
744
|
+
|
|
745
|
+
if not self._time_metadata:
|
|
746
|
+
self._set_time_metadata()
|
|
747
|
+
|
|
748
|
+
if not self._variable_metadata:
|
|
749
|
+
self._set_variable_metadata()
|
|
750
|
+
|
|
751
|
+
def _set_variable_metadata(self) -> None:
|
|
752
|
+
"""
|
|
753
|
+
Extract variable metadata from inputs and return dict for setting.
|
|
754
|
+
|
|
755
|
+
TSTORMS calculates windspeed as Euclidian norm of u and v, so read
|
|
756
|
+
key units and attributes from u and assume they apply.
|
|
757
|
+
Vorticity, Temperature, and Sea-level-pressure all read in directly from file.
|
|
758
|
+
|
|
759
|
+
Note that there is some slight misdirection here in that wind, slp, and tm are
|
|
760
|
+
detected relative to the vorticity location, but the slp location is used to
|
|
761
|
+
provide coordinates. This means a situation could arise in which points are
|
|
762
|
+
in fact from an area more than quoted (up to twice the radius).
|
|
763
|
+
|
|
764
|
+
Raises
|
|
765
|
+
------
|
|
766
|
+
FileNotFoundError
|
|
767
|
+
If an input file cannot be found.
|
|
768
|
+
ValueError
|
|
769
|
+
If a variable is not found in the input files.
|
|
770
|
+
"""
|
|
771
|
+
input_dir = self.tstorms_parameters.input_dir
|
|
772
|
+
detect_params = self.detect_parameters
|
|
773
|
+
var_outputs: list[dict] = [
|
|
774
|
+
{
|
|
775
|
+
"std_name": "wind_speed",
|
|
776
|
+
"long_name": (
|
|
777
|
+
"Surface Wind Speed" if detect_params.use_sfc_wind else "Wind Speed"
|
|
778
|
+
),
|
|
779
|
+
"tstorms_name": ("u_ref" if detect_params.use_sfc_wind else "u850"),
|
|
780
|
+
"filename": os.path.join(input_dir, detect_params.u_in_file),
|
|
781
|
+
"cellmethod": cf.CellMethod(
|
|
782
|
+
"area",
|
|
783
|
+
"maximum",
|
|
784
|
+
qualifiers={
|
|
785
|
+
"comment": (
|
|
786
|
+
f"lesser circle of radius {detect_params.dist_crit} degrees"
|
|
787
|
+
),
|
|
788
|
+
},
|
|
789
|
+
),
|
|
790
|
+
},
|
|
791
|
+
{
|
|
792
|
+
"std_name": "air_pressure_at_mean_sea_level",
|
|
793
|
+
"long_name": "Air Pressure at Mean Sea Level",
|
|
794
|
+
"tstorms_name": "slp",
|
|
795
|
+
"filename": os.path.join(input_dir, detect_params.slp_in_file),
|
|
796
|
+
"cellmethod": cf.CellMethod(
|
|
797
|
+
"area",
|
|
798
|
+
"maximum",
|
|
799
|
+
qualifiers={
|
|
800
|
+
"comment": (
|
|
801
|
+
f"lesser circle of radius {detect_params.dist_crit} degrees"
|
|
802
|
+
),
|
|
803
|
+
},
|
|
804
|
+
),
|
|
805
|
+
},
|
|
806
|
+
{
|
|
807
|
+
"std_name": "atmosphere_upward_relative_vorticity",
|
|
808
|
+
"long_name": "Atmosphere Upward Relative Vorticity",
|
|
809
|
+
"tstorms_name": "vort850",
|
|
810
|
+
"filename": os.path.join(input_dir, detect_params.vort_in_file),
|
|
811
|
+
"cellmethod": cf.CellMethod(
|
|
812
|
+
"area",
|
|
813
|
+
"maximum",
|
|
814
|
+
qualifiers={
|
|
815
|
+
"comment": (
|
|
816
|
+
f"lesser circle of radius {detect_params.dist_crit} degrees"
|
|
817
|
+
),
|
|
818
|
+
},
|
|
819
|
+
),
|
|
820
|
+
},
|
|
821
|
+
]
|
|
822
|
+
|
|
823
|
+
# Initialise variable metadata as empty dict to populate
|
|
824
|
+
self._variable_metadata = {}
|
|
825
|
+
|
|
826
|
+
for output in var_outputs:
|
|
827
|
+
# Check input file exists to read from
|
|
828
|
+
if not os.path.exists(output["filename"]):
|
|
829
|
+
errmsg = f"Input file '{output['filename']}' not found."
|
|
830
|
+
raise FileNotFoundError(errmsg)
|
|
831
|
+
|
|
832
|
+
var_name = output["std_name"]
|
|
833
|
+
tstorms_name = output["tstorms_name"]
|
|
834
|
+
|
|
835
|
+
# Get the variable field from the netcdf file
|
|
836
|
+
fields = cf.read(output["filename"], select=f"ncvar%{tstorms_name}") # type: ignore[operator]
|
|
837
|
+
if not fields:
|
|
838
|
+
msg = (
|
|
839
|
+
f"Variable '{tstorms_name}' not found "
|
|
840
|
+
f"in input file {output['filename']}."
|
|
841
|
+
)
|
|
842
|
+
raise ValueError(msg)
|
|
843
|
+
field = fields[0]
|
|
844
|
+
|
|
845
|
+
# Read and store the relevant metadata
|
|
846
|
+
# Override wind speed as reading from u file but this is zonal velocity
|
|
847
|
+
self._variable_metadata[var_name] = TCTrackerMetadata(
|
|
848
|
+
{
|
|
849
|
+
"standard_name": (
|
|
850
|
+
output["std_name"]
|
|
851
|
+
if var_name == "wind_speed"
|
|
852
|
+
else field.get_property("standard_name", output["std_name"])
|
|
853
|
+
),
|
|
854
|
+
"long_name": (
|
|
855
|
+
output["long_name"]
|
|
856
|
+
if var_name == "wind_speed"
|
|
857
|
+
else field.get_property("long_name", output["long_name"])
|
|
858
|
+
),
|
|
859
|
+
"units": field.get_property("units", "unknown"),
|
|
860
|
+
}
|
|
861
|
+
)
|
|
862
|
+
self._variable_metadata[var_name].constructs = [output["cellmethod"]]
|
|
863
|
+
|
|
864
|
+
def _set_time_metadata(self):
|
|
865
|
+
"""
|
|
866
|
+
Extract time metadata from u_ref input and set attribute.
|
|
867
|
+
|
|
868
|
+
Calendar type, units, start time, and end time extracted from u_ref as for
|
|
869
|
+
TSTORMS by identifying the unlimited dimension and fetching coordinate
|
|
870
|
+
attributes. Assumes other files match.
|
|
871
|
+
If file not found or variable cannot be identified errors are raised.
|
|
872
|
+
The calendar defaults to Julian as for TSTORMS.
|
|
873
|
+
|
|
874
|
+
Raises
|
|
875
|
+
------
|
|
876
|
+
KeyError
|
|
877
|
+
If no unlimited dimension or corresponding coordinate is found in the u
|
|
878
|
+
input file.
|
|
879
|
+
ValueError
|
|
880
|
+
If multiple unlimited dimensions are found in the u input file.
|
|
881
|
+
ValueError
|
|
882
|
+
If the 'units' attribute is missing for the time coordinate.
|
|
883
|
+
|
|
884
|
+
Warnings
|
|
885
|
+
--------
|
|
886
|
+
UserWarning
|
|
887
|
+
If the 'calendar' attribute is missing for the coordinate variable.
|
|
888
|
+
Defaults to 'julian'.
|
|
889
|
+
"""
|
|
890
|
+
input_u_file = os.path.join(
|
|
891
|
+
self.tstorms_parameters.input_dir, self.detect_parameters.u_in_file
|
|
892
|
+
)
|
|
893
|
+
|
|
894
|
+
with Dataset(input_u_file, "r") as nc_file:
|
|
895
|
+
unlimited_dims = [
|
|
896
|
+
dim
|
|
897
|
+
for dim in nc_file.dimensions
|
|
898
|
+
if nc_file.dimensions[dim].isunlimited()
|
|
899
|
+
]
|
|
900
|
+
if not unlimited_dims:
|
|
901
|
+
errmsg = (
|
|
902
|
+
"No unlimited dimension found in the u_ref NetCDF file "
|
|
903
|
+
"to set calendar."
|
|
904
|
+
)
|
|
905
|
+
raise KeyError(errmsg)
|
|
906
|
+
if len(unlimited_dims) > 1:
|
|
907
|
+
errmsg = (
|
|
908
|
+
"TSTORMS expects only a single unlimited variable in NetCDF "
|
|
909
|
+
"files corresponding to the time dimension. "
|
|
910
|
+
f"Multiple found: {unlimited_dims}."
|
|
911
|
+
)
|
|
912
|
+
raise ValueError(errmsg)
|
|
913
|
+
|
|
914
|
+
unlimited_dim = unlimited_dims[0]
|
|
915
|
+
if unlimited_dim not in nc_file.variables:
|
|
916
|
+
errmsg = (
|
|
917
|
+
"Coordinate variable for unlimited dimension "
|
|
918
|
+
f"'{unlimited_dim}' not found."
|
|
919
|
+
)
|
|
920
|
+
raise KeyError(errmsg)
|
|
921
|
+
|
|
922
|
+
coord_var = nc_file.variables[unlimited_dim]
|
|
923
|
+
units = getattr(coord_var, "units", None)
|
|
924
|
+
if units is None:
|
|
925
|
+
msg = "The 'units' attribute is required for the time coordinate."
|
|
926
|
+
raise ValueError(msg)
|
|
927
|
+
|
|
928
|
+
calendar = getattr(coord_var, "calendar", None)
|
|
929
|
+
if calendar is None:
|
|
930
|
+
msg = (
|
|
931
|
+
"The 'calendar' attribute is missing for the coordinate variable.\n"
|
|
932
|
+
"defaulting to 'julian'"
|
|
933
|
+
)
|
|
934
|
+
warnings.warn(msg, category=UserWarning, stacklevel=2)
|
|
935
|
+
calendar = "julian"
|
|
936
|
+
|
|
937
|
+
start_time_num = coord_var[0]
|
|
938
|
+
end_time_num = coord_var[-1]
|
|
939
|
+
|
|
940
|
+
self._time_metadata = {
|
|
941
|
+
"calendar": calendar,
|
|
942
|
+
"units": units,
|
|
943
|
+
"start_time": num2date(start_time_num, units=units, calendar=calendar),
|
|
944
|
+
"end_time": num2date(end_time_num, units=units, calendar=calendar),
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
def read_trajectories(self):
|
|
948
|
+
"""
|
|
949
|
+
Parse outputs from TSTORMS to list of :class:`tctrack.core.Trajectory`.
|
|
950
|
+
|
|
951
|
+
This will read from the ``trav`` file output from trajectory stitching, or
|
|
952
|
+
``trav_filt`` if filtering was applied (see ``do_filter`` in the
|
|
953
|
+
:attr:`tstorms_parameters` attribute).
|
|
954
|
+
|
|
955
|
+
Returns
|
|
956
|
+
-------
|
|
957
|
+
trajectories : list[Trajectory]
|
|
958
|
+
A list of :class:`tctrack.core.Trajectory` objects.
|
|
959
|
+
"""
|
|
960
|
+
trajectories = []
|
|
961
|
+
current_trajectory_id = 0 # Initialize trajectory ID
|
|
962
|
+
|
|
963
|
+
# We need time metadata, so set the metadata if not done already
|
|
964
|
+
if not self._time_metadata:
|
|
965
|
+
self._set_time_metadata()
|
|
966
|
+
|
|
967
|
+
# Use the trav file to get full data (including vorticity)
|
|
968
|
+
# If filtering was applied use filtered file
|
|
969
|
+
output_dir = self.tstorms_parameters.output_dir
|
|
970
|
+
trav_file = "trav_filt" if self.stitch_parameters.do_filter else "trav"
|
|
971
|
+
output_trav_filepath = os.path.join(output_dir, trav_file)
|
|
972
|
+
|
|
973
|
+
with open(output_trav_filepath, "r") as file:
|
|
974
|
+
for line in file:
|
|
975
|
+
items = line.split()
|
|
976
|
+
if items[0] == "start":
|
|
977
|
+
# Start of new trajectory.
|
|
978
|
+
# Extract metadata and add Trajectory to dict
|
|
979
|
+
current_trajectory_id += 1
|
|
980
|
+
time = list(map(int, items[2:6]))
|
|
981
|
+
|
|
982
|
+
trajectories.append(
|
|
983
|
+
Trajectory(
|
|
984
|
+
current_trajectory_id,
|
|
985
|
+
time,
|
|
986
|
+
calendar=self.time_metadata["calendar"],
|
|
987
|
+
)
|
|
988
|
+
)
|
|
989
|
+
|
|
990
|
+
# Continue processing ongoing trajectory
|
|
991
|
+
# Trajectories indexed from 1 so subtract when assigning
|
|
992
|
+
else:
|
|
993
|
+
trajectories[current_trajectory_id - 1].add_point(
|
|
994
|
+
*self._parse_tstorms_trav_line_to_point(items)
|
|
995
|
+
)
|
|
996
|
+
return trajectories
|
|
997
|
+
|
|
998
|
+
@staticmethod
|
|
999
|
+
def _parse_tstorms_trav_line_to_point(
|
|
1000
|
+
line: list[str], variable_names: list[str] | None = None
|
|
1001
|
+
) -> tuple[list[int], dict[str, int | float]]:
|
|
1002
|
+
"""
|
|
1003
|
+
Parse line from TSTORMS trav output into a trajectory data point.
|
|
1004
|
+
|
|
1005
|
+
Data point format is that expected by a :class:`tctrack.core.Trajectory`.
|
|
1006
|
+
|
|
1007
|
+
Data from a traj file can be parsed by providing a different set of
|
|
1008
|
+
``variable_names``
|
|
1009
|
+
|
|
1010
|
+
Parameters
|
|
1011
|
+
----------
|
|
1012
|
+
line : list[str]
|
|
1013
|
+
A list of strings representing the line split into parts.
|
|
1014
|
+
variable_names : list[str] | None
|
|
1015
|
+
List of variable names for the data columns.
|
|
1016
|
+
Defaults to None and then set to those for a trav file.
|
|
1017
|
+
|
|
1018
|
+
Returns
|
|
1019
|
+
-------
|
|
1020
|
+
tuple
|
|
1021
|
+
A tuple containing the time as an integer list of [year, day, month, hour]
|
|
1022
|
+
and a dict of variables.
|
|
1023
|
+
"""
|
|
1024
|
+
if not variable_names:
|
|
1025
|
+
variable_names = [
|
|
1026
|
+
"lon",
|
|
1027
|
+
"lat",
|
|
1028
|
+
"wind_speed",
|
|
1029
|
+
"air_pressure_at_mean_sea_level",
|
|
1030
|
+
"atmosphere_upward_relative_vorticity",
|
|
1031
|
+
]
|
|
1032
|
+
|
|
1033
|
+
return_vars: dict[str, int | float] = {}
|
|
1034
|
+
return_vars.update(
|
|
1035
|
+
{
|
|
1036
|
+
name: float(value)
|
|
1037
|
+
for name, value in zip(variable_names, line[:-4], strict=True)
|
|
1038
|
+
}
|
|
1039
|
+
)
|
|
1040
|
+
time = list(map(int, line[-4:]))
|
|
1041
|
+
return time, return_vars
|
|
1042
|
+
|
|
1043
|
+
def run_tracker(self, output_file: str):
|
|
1044
|
+
"""Run TSTORMS tracker to obtain tropical cyclone track trajectories.
|
|
1045
|
+
|
|
1046
|
+
This first runs :meth:`detect` to get TC candidates at each time. Then
|
|
1047
|
+
these are combined into trajectories using :meth:`stitch`.
|
|
1048
|
+
The output is then saved as a CF-compliant NetCDF trajectory file.
|
|
1049
|
+
|
|
1050
|
+
Arguments
|
|
1051
|
+
---------
|
|
1052
|
+
output_file : str
|
|
1053
|
+
Filename to which the tropical cyclone trajectories are saved.
|
|
1054
|
+
|
|
1055
|
+
Raises
|
|
1056
|
+
------
|
|
1057
|
+
FileNotFoundError
|
|
1058
|
+
- If the TSTORMS executables cannot be found.
|
|
1059
|
+
RuntimeError
|
|
1060
|
+
If the TSTORMS commands return a non-zero exit code.
|
|
1061
|
+
|
|
1062
|
+
Examples
|
|
1063
|
+
--------
|
|
1064
|
+
To set the parameters, instantiate a :class:`TSTORMSTracker` instance and run
|
|
1065
|
+
`run_tracker()`:
|
|
1066
|
+
|
|
1067
|
+
>>> tstorms_params = TSTORMSBaseParameters(...)
|
|
1068
|
+
>>> detect_params = TSTORMSDetectParameters(...)
|
|
1069
|
+
>>> stitch_params = TSTORMSStitchParameters(...)
|
|
1070
|
+
>>> my_tracker = TSTORMSTracker(tstorms_params, detect_params, stitch_params)
|
|
1071
|
+
>>> my_tracker.run_tracker()
|
|
1072
|
+
"""
|
|
1073
|
+
self.detect()
|
|
1074
|
+
self.stitch()
|
|
1075
|
+
self.to_netcdf(output_file)
|