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,1144 @@
1
+ """Module providing a class that binds the Tempest Extremes code.
2
+
3
+ References
4
+ ----------
5
+ - Tempest Extremes code on GitHub: https://github.com/ClimateGlobalChange/tempestextremes
6
+ - Tempest Extremes User Guide: https://climate.ucdavis.edu/tempestextremes.php
7
+ - GMD paper on Tempest Extremes v2.1: https://doi.org/10.5194/gmd-14-5023-2021
8
+ """
9
+
10
+ import csv
11
+ import json
12
+ import subprocess
13
+ import tempfile
14
+ from dataclasses import asdict, dataclass
15
+ from pathlib import Path
16
+ from typing import TypedDict
17
+
18
+ import cf
19
+
20
+ from tctrack.core import TCTracker, TCTrackerMetadata, TCTrackerParameters, Trajectory
21
+
22
+
23
+ def lod_to_te(inputs: list[dict]) -> str:
24
+ """
25
+ Convert a sane list of dicts to input format used by Tempest Extremes commands.
26
+
27
+ The input list of dictionaries will be concatenated to a single string of values
28
+ separated by `,` and dicts separated by `;`.
29
+
30
+ Parameters
31
+ ----------
32
+ inputs : list[dict]
33
+ List of the dictionaries to be concatenated.
34
+
35
+ Returns
36
+ -------
37
+ str
38
+ Single string of values separated by `,` and dicts separated by `;`
39
+
40
+ Examples
41
+ --------
42
+ >>> lod_to_te([{"a": 1, "b": 2, "c": 3}, {"d": 4, "e": 5, "f": 6}])
43
+ '1,2,3;4,5,6'
44
+ """
45
+ return ";".join(",".join(str(value) for value in d.values()) for d in inputs)
46
+
47
+
48
+ class TEContour(TypedDict):
49
+ """
50
+ Data required for checking a contour of a single variable during detection.
51
+
52
+ Points will be eliminated in a detection search if they fail this criterion.
53
+ The closed contour is determined by breadth first search: if any paths exist from
54
+ the candidate point (or nearby minima/maxima if minmaxdist is specified) that
55
+ reach the specified distance before achieving the specified delta then we say no
56
+ closed contour is present.
57
+ Each contour takes the form of a ``dict`` with keys ``"var"``, ``"delta"``,
58
+ ``"dist"``, and ``"minmaxdist"``.
59
+
60
+ See Also
61
+ --------
62
+ TETracker.detect : The DetectNodes call from the TETracker object
63
+ TEDetectParameters : The detection parameter class
64
+
65
+ References
66
+ ----------
67
+ `TempestExtremes Documentation <https://climate.ucdavis.edu/tempestextremes.php#DetectNodes>`__
68
+ and the `DetectNodes Source <https://github.com/ClimateGlobalChange/tempestextremes/blob/master/src/nodes/DetectNodes.cpp>`_
69
+
70
+ Examples
71
+ --------
72
+ To add a contour requirement on ``"psl"`` with a change of ``200.0`` within
73
+ ``5.5`` degrees of the candidate we create a TEContour as follows:
74
+
75
+ >>> TEContour(var="psl", delta=200.0, dist=5.5, minmaxdist=0.0)
76
+ {'var': 'psl', 'delta': 200.0, 'dist': 5.5, 'minmaxdist': 0.0}
77
+ """
78
+
79
+ var: str
80
+ """Name of the variable to contour in NetCDF files."""
81
+
82
+ delta: float
83
+ """
84
+ Amount by which the field must change from the pivot value.
85
+ If positive (negative) the field must increase (decrease) by this value along
86
+ the contour.
87
+ """
88
+
89
+ dist: float
90
+ """
91
+ Lesser-circle radius (degrees) from the pivot within which the
92
+ criteria must be satisfied.
93
+ """
94
+
95
+ minmaxdist: float
96
+ """
97
+ Lesser-circle radius away from the candidate to search for the minima/maxima.
98
+ If delta is positive (negative), the pivot is a local minimum (maximum).
99
+ """
100
+
101
+
102
+ class TEOutputCommand(TypedDict):
103
+ """
104
+ Data required to specify an additional column in the detection output.
105
+
106
+ Each output command takes the form of a ``dict`` with keys ``"var"``, ``"op"``, and
107
+ ``"dist"``.
108
+
109
+ See Also
110
+ --------
111
+ TETracker.detect : The DetectNodes call from the TETracker object
112
+ TEDetectParameters : The detection parameter class
113
+
114
+ References
115
+ ----------
116
+ `TempestExtremes Documentation <https://climate.ucdavis.edu/tempestextremes.php#DetectNodes>`__
117
+ and the `DetectNodes Source <https://github.com/ClimateGlobalChange/tempestextremes/blob/master/src/nodes/DetectNodes.cpp>`_
118
+
119
+ Examples
120
+ --------
121
+ To add an output column with the minimum ``"psl"`` at the candidate point:
122
+
123
+ >>> TEOutputCommand(var="psl", operator="min", dist=0.0)
124
+ {'var': 'psl', 'operator': 'min', 'dist': 0.0}
125
+ """
126
+
127
+ var: str
128
+ """Name of the variable to write in output files."""
129
+
130
+ operator: str
131
+ """
132
+ Operator that is applied over all points within the specified distance of the
133
+ candidate (options include ``"max"``, ``"min"``, ``"avg"``, ``"maxdist"``, and
134
+ ``"mindist"``).
135
+ """
136
+
137
+ dist: float
138
+ """
139
+ Lesser-circle radius (degrees) from the candidate within which the
140
+ operator is applied.
141
+ """
142
+
143
+
144
+ class TEThreshold(TypedDict):
145
+ """Data required for a threshold filter for a track trajectory when stitching.
146
+
147
+ Any storm track trajectories that do not satisfy the threshold value for a given
148
+ number of points will be filtered out.
149
+ Each condition is of the form "var,op,value,count" and multiple conditions are
150
+ separated by ";".
151
+
152
+ See Also
153
+ --------
154
+ TETracker.stitch : The StitchNodes call from the TETracker object.
155
+ TEStitchParameters : The stitching parameter class.
156
+
157
+ References
158
+ ----------
159
+ `TempestExtremes Documentation <https://climate.ucdavis.edu/tempestextremes.php#StitchNodes>`__
160
+ and the `StitchNodes Source <https://github.com/ClimateGlobalChange/tempestextremes/blob/master/src/nodes/StitchNodes.cpp>`_
161
+
162
+ Examples
163
+ --------
164
+ To add a filter requiring latitude ``"lat"`` to be less than 40 degrees for
165
+ 10 or more points in each track trajectory:
166
+
167
+ >>> TEThreshold(var="lat", op="<=", value=40, count=10)
168
+ {"var": "lat", "op": "<=", "value": 40, "count": 10},
169
+ """
170
+
171
+ var: str
172
+ """Name of the variable being tested. Called "col" in TempestExtremes."""
173
+
174
+ op: str
175
+ """Operator used for the comparison (options include >,>=,<,<=,=,!=,|>=,|<=)."""
176
+
177
+ value: float
178
+ """Value on the right-hand-side of the comparison."""
179
+
180
+ count: int | str
181
+ """
182
+ Either the minimum number of points where the threshold must be satisfied or the
183
+ instruction ``"all"``, ``"first"``, or ``"last"``. ``"all"`` for all points along
184
+ the path, ``"first"`` for just the first point, and ``"last"`` for only the last
185
+ point.
186
+ """
187
+
188
+
189
+ @dataclass(repr=False)
190
+ class TEDetectParameters(TCTrackerParameters):
191
+ """
192
+ Dataclass containing values used by the detection operation of TE.
193
+
194
+ See Also
195
+ --------
196
+ TEContour : The class used to define contour criteria
197
+ TEOutputCommand : The class used to define additional outputs
198
+
199
+ References
200
+ ----------
201
+ `TempestExtremes Documentation <https://climate.ucdavis.edu/tempestextremes.php#DetectNodes>`__
202
+ and the `DetectNodes Source <https://github.com/ClimateGlobalChange/tempestextremes/blob/master/src/nodes/DetectNodes.cpp>`_
203
+ """
204
+
205
+ in_data: list[str]
206
+ """List of strings of NetCDF input files."""
207
+
208
+ out_header: bool = False
209
+ """Include header at the top of the output file?"""
210
+
211
+ output_dir: str = "" # Not using None to keep type-checking simple
212
+ """
213
+ File path of the directory to output intermediate files. If left empty, it will use
214
+ a temporary directory that will last only for the lifetime of the :class:`TETracker`
215
+ instance.
216
+ """
217
+
218
+ output_file: str = "nodes.txt"
219
+ """Name of output nodefile to write to in the :attr:`output_dir` directory."""
220
+
221
+ search_by_min: str | None = None
222
+ """
223
+ Input variable in NetCDF files for selecting candidate points (defined as local
224
+ minima). If ``None``, then uses ``"PSL"`` in Tempest Extremes.
225
+ """
226
+
227
+ search_by_max: str | None = None
228
+ """
229
+ Input variable in NetCDF files for selecting candidate points (defined as local
230
+ maxima).
231
+ """
232
+
233
+ closed_contours: list[TEContour] | None = None
234
+ """
235
+ Criteria for candidates to be eliminated if they do not have a closed contour
236
+ as a list of separate :class:`TEContour` criteria.
237
+ """
238
+
239
+ merge_dist: float = 0.0
240
+ """
241
+ DetectNodes merges candidate points with a distance (in degrees) shorter than the
242
+ specified value. Among two candidates within the merge distance, only the candidate
243
+ with the lowest value of the search_by_min field or highest value of the
244
+ search_by_max field are retained.
245
+ """
246
+
247
+ time_filter: str | None = None
248
+ """
249
+ Filter for the input data frequency. Options are: `"3hr"`, `"6hr"`, `"daily"`.
250
+ Alternatively, can be a regex for the datetime using format `"YYYY-MM-DD HH:MM:SS"`.
251
+ """
252
+
253
+ lat_name: str = "lat"
254
+ """String for the latitude dimension in the NetCDF files."""
255
+
256
+ lon_name: str = "lon"
257
+ """String for the longitude dimension in the NetCDF files."""
258
+
259
+ min_lat: float = 0.0
260
+ """Minimum latitude for candidate points."""
261
+
262
+ max_lat: float = 0.0
263
+ """
264
+ Maximum latitude for candidate points.
265
+ If max_lat and min_lat are equal then these arguments are ignored.
266
+ """
267
+
268
+ min_lon: float = 0.0
269
+ """Minimum longitude for candidate points."""
270
+
271
+ max_lon: float = 0.0
272
+ """
273
+ Maximum longitude for candidate points.
274
+ If ``max_lon`` and ``min_lon`` are equal then these arguments are ignored.
275
+ """
276
+
277
+ regional: bool = False
278
+ """Should lat-lon grid be periodic in longitude."""
279
+
280
+ output_commands: list[TEOutputCommand] | None = None
281
+ """
282
+ Criteria for any additional columns to be added to the output. Criteria are provided
283
+ as a list of separate :class:`TEOutputCommand` criteria.
284
+ """
285
+
286
+
287
+ @dataclass(repr=False)
288
+ class TEStitchParameters(TCTrackerParameters):
289
+ """Dataclass containing values used by the stitch operation of TE.
290
+
291
+ References
292
+ ----------
293
+ `TempestExtremes Documentation <https://climate.ucdavis.edu/tempestextremes.php#StitchNodes>`__
294
+ and the `StitchNodes Source <https://github.com/ClimateGlobalChange/tempestextremes/blob/master/src/nodes/StitchNodes.cpp>`_
295
+ """
296
+
297
+ output_dir: str = "" # Not using None to keep type-checking simple
298
+ """
299
+ File path of the directory to output intermediate files. If left empty, it will use
300
+ the :attr:`TEDetectParameters.output_dir` value if one is provided. Otherwise, it
301
+ will use a temporary directory that will last only for the lifetime of the
302
+ :class:`TETracker` instance.
303
+ """
304
+
305
+ output_file: str = "trajectories.txt"
306
+ """
307
+ The output filename to write the trajectories to in the :attr:`output_dir`
308
+ directory.
309
+ """
310
+
311
+ in_file: str | None = None
312
+ """
313
+ Filepath of the DetectNodes output file. If this and ``in_list`` are ``None``, it
314
+ will be determined from :attr:`TEDetectParameters.output_dir` and
315
+ :attr:`TEDetectParameters.output_file`. Called "in" in TempestExtremes.
316
+ """
317
+
318
+ in_list: str | None = None
319
+ """
320
+ File containing a list of input files to be processed together. This is unadvised to
321
+ use at present as it is likely to be changed.
322
+ """
323
+
324
+ in_fmt: list[str] | None = None
325
+ """
326
+ List of the variables in the order they appear in the input file.
327
+ If ``None``, it will be ``["lon", "lat", ...]``, ending in variables defined in
328
+ :attr:`TEDetectParameters.output_commands`.
329
+ """
330
+
331
+ allow_repeated_times: bool = False
332
+ """
333
+ If ``False``, an error is thrown if there are multiple sections in the input
334
+ nodefile with the same time.
335
+ """
336
+
337
+ caltype: str = "standard"
338
+ """
339
+ The type of calendar to use. Options are ``"standard"`` (365 days with leap years),
340
+ ``"noleap"``, ``"360_day"``.
341
+ """
342
+
343
+ time_begin: str | None = None
344
+ """Starting date/time for stitching trajectories. Earlier times will be ignored."""
345
+
346
+ time_end: str | None = None
347
+ """Ending date/time for stitching trajectories. Later times will be ignored."""
348
+
349
+ max_sep: float = 5
350
+ """
351
+ The maximum distance allowed between candidates (degrees). Called "range" in
352
+ TempestExtremes.
353
+ """
354
+
355
+ max_gap: int | str = 0
356
+ """
357
+ The number of missing points allowed between candidates, as an integer. Or as a
358
+ string for the maximum time (inclusive) between points, e.g. ``"24hr"``.
359
+ """
360
+
361
+ min_time: int | str = 1
362
+ """
363
+ The minimum required length of a path. Either as an integer for the number of
364
+ candidates, or a string for total duration, e.g. ``"24h"``.
365
+ """
366
+
367
+ min_endpoint_dist: float = 0
368
+ """The minimum required distance between the first and last candidates (degrees)."""
369
+
370
+ min_path_dist: float = 0
371
+ """The minimum required acumulated distance along the path (degrees)."""
372
+
373
+ threshold_filters: list[TEThreshold] | None = None
374
+ """
375
+ Filters for paths based on the number of nodes that satisfy a threshold. Uses a list
376
+ of :class:`TEThreshold` objects. Called "thresholdcmd" in TempestExtremes.
377
+ """
378
+
379
+ prioritize: str | None = None
380
+ """
381
+ The variable to use to determine the precedence (lowest to highest) of nodes for
382
+ matching to the next position.
383
+ """
384
+
385
+ add_velocity: bool = False
386
+ """
387
+ Whether to include the velocity components (m/s) of the movement of the TC to the
388
+ output file.
389
+ """
390
+
391
+ out_file_format: str = "gfdl"
392
+ """
393
+ Format of the output file. ``"gfdl"``, ``"csv"``, or ``"csvnohead"``.
394
+ See :meth:`TETracker.stitch` for details.
395
+ """
396
+
397
+ out_seconds: bool = False
398
+ """
399
+ For GFDL output file types, determines whether to report the sub-daily time in
400
+ seconds (``True``) or hours (``False``).
401
+ """
402
+
403
+ def __post_init__(self):
404
+ """Validate parameters."""
405
+ if self.out_file_format not in ("gfdl", "csv", "csvnohead"):
406
+ msg = (
407
+ f"Invalid out_file_format ({self.out_file_format}). "
408
+ "Allowed values are 'gfdl', 'csv', or 'csvnohead'"
409
+ )
410
+ raise ValueError(msg)
411
+ if self.caltype not in ("standard", "noleap", "360_day"):
412
+ msg = (
413
+ f"Invalid caltype ({self.caltype}). "
414
+ "Allowed values are 'standard', 'noleap', or '360_day'"
415
+ )
416
+ raise ValueError(msg)
417
+
418
+
419
+ class TETracker(TCTracker):
420
+ """Class containing bindings to the Tempest Extremes code.
421
+
422
+ Attributes
423
+ ----------
424
+ detect_parameters : TEDetectParameters
425
+ Class containing the parameters for the detection step
426
+ stitch_parameters : TEStitchParameters | None
427
+ Class containing the parameters for the stitching step
428
+ """
429
+
430
+ # Private attributes
431
+ _tempdir: tempfile.TemporaryDirectory
432
+
433
+ def __init__(
434
+ self,
435
+ detect_parameters: TEDetectParameters,
436
+ stitch_parameters: TEStitchParameters | None = None,
437
+ ):
438
+ """
439
+ Construct the TempestExtremes class.
440
+
441
+ Parameters
442
+ ----------
443
+ detect_parameters : TEDetectParameters
444
+ Class containing the parameters for the detection step
445
+ stitch_parameters : TEStitchParameters | None
446
+ Class containing the parameters for the stitching step
447
+ Defaults to the default values in TEStitchParameters Class
448
+ """
449
+ self.detect_parameters: TEDetectParameters = detect_parameters
450
+
451
+ if stitch_parameters is not None:
452
+ self.stitch_parameters: TEStitchParameters = stitch_parameters
453
+ else:
454
+ self.stitch_parameters = TEStitchParameters()
455
+
456
+ dn_params = self.detect_parameters
457
+ sn_params = self.stitch_parameters
458
+
459
+ # Define the default output directories
460
+ if dn_params.output_dir == "":
461
+ # The temporary directory is deleted when the object goes out of scope.
462
+ # It is stored in an attribute to persist for the lifetime of the tracker.
463
+ self._tempdir = tempfile.TemporaryDirectory()
464
+ dn_params.output_dir = self._tempdir.name
465
+ if sn_params.output_dir == "":
466
+ sn_params.output_dir = dn_params.output_dir
467
+
468
+ # Set StitchNodes input arguments according to DetectNodes parameters,
469
+ # if not provided
470
+ if sn_params.in_file is None and sn_params.in_list is None:
471
+ sn_params.in_file = str(Path(dn_params.output_dir) / dn_params.output_file)
472
+ if sn_params.in_fmt is None and dn_params.output_commands is not None:
473
+ variables = [output["var"] for output in dn_params.output_commands]
474
+ sn_params.in_fmt = ["lon", "lat", *variables]
475
+
476
+ def _run_te_process(self, command_name: str, command_list: list[str]):
477
+ """Run a TempestExtremes command (DetectNodes or StitchNodes).
478
+
479
+ Parameters
480
+ ----------
481
+ command_name : str
482
+ The name of the command to be used in the log and error reporting.
483
+ command_list : list[str]
484
+ The list of strings that produce the command as given by
485
+ _make_detect_nodes_call and _make_stitch_nodes_call.
486
+
487
+ Returns
488
+ -------
489
+ dict
490
+ dict of subprocess output corresponding to stdout, stderr, and returncode.
491
+
492
+ Raises
493
+ ------
494
+ FileNotFoundError
495
+ If the DetectNodes executeable from TempestExtremes cannot be found.
496
+ RuntimeError
497
+ If Tempest Extremes DetectNodes returns a non-zero exit code.
498
+ """
499
+ try:
500
+ result = subprocess.run( # noqa: S603 - no shell
501
+ command_list,
502
+ check=True,
503
+ capture_output=True,
504
+ text=True,
505
+ )
506
+ print(f"{command_name} completed successfully.")
507
+ print(
508
+ f"First 12 lines of output:\n"
509
+ f"{''.join(result.stdout.splitlines(True)[:12])}"
510
+ f"\n...\n\n"
511
+ f"Last 12 lines of output:\n"
512
+ f"{''.join(result.stdout.splitlines(True)[-12:])}"
513
+ )
514
+ return {
515
+ "stdout": result.stdout,
516
+ "stderr": result.stderr,
517
+ "returncode": result.returncode,
518
+ }
519
+ except FileNotFoundError as exc:
520
+ msg = (
521
+ f"{command_name} failed because the executable could not be found.\n"
522
+ "Did you provide the full executeable path or add it to $PATH?\n"
523
+ )
524
+ raise FileNotFoundError(msg) from exc
525
+ except subprocess.CalledProcessError as exc:
526
+ msg = (
527
+ f"{command_name} failed with a non-zero exit code:"
528
+ f"({exc.returncode}):\n"
529
+ f"{exc.stderr}"
530
+ )
531
+ raise RuntimeError(msg) from exc
532
+
533
+ def _make_detect_nodes_call(self): # noqa: PLR0912 - all branches same logic
534
+ """
535
+ Construct a DetectNodes call based on options set in parameters.
536
+
537
+ Returns
538
+ -------
539
+ list[str]
540
+ list of strings that can be combined to form a DetectNodes command
541
+ based on the parameters set in self.detect_parameters
542
+ """
543
+ dn_argslist = ["DetectNodes"]
544
+
545
+ if self.detect_parameters.in_data is not None:
546
+ dn_argslist.extend(
547
+ [
548
+ "--in_data",
549
+ ";".join(self.detect_parameters.in_data),
550
+ ]
551
+ )
552
+ out_file = str(
553
+ Path(self.detect_parameters.output_dir) / self.detect_parameters.output_file
554
+ )
555
+ dn_argslist.extend(["--out", out_file])
556
+ if self.detect_parameters.out_header:
557
+ dn_argslist.extend(["--out_header"])
558
+ if self.detect_parameters.search_by_min is not None:
559
+ dn_argslist.extend(
560
+ [
561
+ "--searchbymin",
562
+ self.detect_parameters.search_by_min,
563
+ ]
564
+ )
565
+ if self.detect_parameters.search_by_max is not None:
566
+ dn_argslist.extend(
567
+ [
568
+ "--searchbymax",
569
+ self.detect_parameters.search_by_max,
570
+ ]
571
+ )
572
+ if self.detect_parameters.closed_contours is not None:
573
+ dn_argslist.extend(
574
+ [
575
+ "--closedcontourcmd",
576
+ lod_to_te(self.detect_parameters.closed_contours),
577
+ ]
578
+ )
579
+ dn_argslist.extend(
580
+ [
581
+ "--mergedist",
582
+ str(self.detect_parameters.merge_dist),
583
+ ]
584
+ )
585
+ if self.detect_parameters.time_filter is not None:
586
+ dn_argslist.extend(
587
+ [
588
+ "--timefilter",
589
+ self.detect_parameters.time_filter,
590
+ ]
591
+ )
592
+ if self.detect_parameters.lat_name is not None:
593
+ dn_argslist.extend(
594
+ [
595
+ "--latname",
596
+ self.detect_parameters.lat_name,
597
+ ]
598
+ )
599
+ if self.detect_parameters.lon_name is not None:
600
+ dn_argslist.extend(
601
+ [
602
+ "--lonname",
603
+ self.detect_parameters.lon_name,
604
+ ]
605
+ )
606
+ if self.detect_parameters.min_lat is not None:
607
+ dn_argslist.extend(
608
+ [
609
+ "--minlat",
610
+ str(self.detect_parameters.min_lat),
611
+ ]
612
+ )
613
+ if self.detect_parameters.max_lat is not None:
614
+ dn_argslist.extend(
615
+ [
616
+ "--maxlat",
617
+ str(self.detect_parameters.max_lat),
618
+ ]
619
+ )
620
+ if self.detect_parameters.min_lon is not None:
621
+ dn_argslist.extend(
622
+ [
623
+ "--minlon",
624
+ str(self.detect_parameters.min_lon),
625
+ ]
626
+ )
627
+ if self.detect_parameters.max_lon is not None:
628
+ dn_argslist.extend(
629
+ [
630
+ "--maxlon",
631
+ str(self.detect_parameters.max_lon),
632
+ ]
633
+ )
634
+ if self.detect_parameters.regional:
635
+ dn_argslist.extend(["--regional"])
636
+ if self.detect_parameters.output_commands is not None:
637
+ dn_argslist.extend(
638
+ [
639
+ "--outputcmd",
640
+ lod_to_te(self.detect_parameters.output_commands),
641
+ ]
642
+ )
643
+
644
+ return dn_argslist
645
+
646
+ def detect(self):
647
+ """
648
+ Call the DetectNodes utility of Tempest Extremes.
649
+
650
+ This will make a system call out to the DetectNodes method from Tempest Extremes
651
+ (provided it has been installed as an external dependency). DetectNodes will be
652
+ run according to the parameters in the :attr:`detect_parameters` attribute
653
+ that were set when the :class:`TETracker` instance was created.
654
+
655
+ The output file is a plain text file containing each of the TC candidates at
656
+ each time from the input files. If :attr:`~TEDetectParameters.output_dir` is
657
+ ``None`` this will be a temporary file lasting the lifetime of the
658
+ :class:`TETracker` instance. If :attr:`~TEDetectParameters.out_header` is
659
+ ``True`` the first two lines of the file will be a header describing the
660
+ structure of the data. After this each time is listed in the format:
661
+
662
+ .. code-block:: text
663
+
664
+ <year> <month> <day> <count> <hour>
665
+ <i> <j> <lon> <lat> <var1> <var2> ...
666
+ ...
667
+ <i> <j> <lon> <lat> <var1> <var2> ...
668
+
669
+ - ``count`` is the number of nodes at that time.
670
+ - ``i``, ``j`` are the grid indices of the node.
671
+ - ``var1``, ``var2``, etc., are scalar variables as defined by
672
+ :attr:`~TEDetectParameters.output_commands` (typically, psl, orog).
673
+
674
+ Returns
675
+ -------
676
+ dict
677
+ dict of subprocess output corresponding to stdout, stderr, and returncode.
678
+
679
+ Raises
680
+ ------
681
+ FileNotFoundError
682
+ If the DetectNodes executeable from TempestExtremes cannot be found.
683
+ RuntimeError
684
+ If Tempest Extremes DetectNodes returns a non-zero exit code.
685
+
686
+ References
687
+ ----------
688
+ `TempestExtremes Documentation <https://climate.ucdavis.edu/tempestextremes.php#DetectNodes>`__
689
+ and the `DetectNodes Source <https://github.com/ClimateGlobalChange/tempestextremes/blob/master/src/nodes/DetectNodes.cpp>`_
690
+
691
+ Examples
692
+ --------
693
+ To set the parameters, instantiate a :class:`TETracker` instance and run
694
+ DetectNodes:
695
+
696
+ >>> my_params = TEDetectParameters(...)
697
+ >>> my_tracker = TETracker(detect_parameters=my_params)
698
+ >>> result = my_tracker.detect()
699
+ """
700
+ Path(self.detect_parameters.output_dir).mkdir(parents=True, exist_ok=True)
701
+ dn_call_list = self._make_detect_nodes_call()
702
+ return self._run_te_process("DetectNodes", dn_call_list)
703
+
704
+ def _make_stitch_nodes_call(self):
705
+ """
706
+ Construct a StitchNodes call based on options set in parameters.
707
+
708
+ Returns
709
+ -------
710
+ list[str]
711
+ list of strings that can be combined to form a StitchNodes command
712
+ based on the parameters set in self.stitch_parameters
713
+ """
714
+ sn_argslist = ["StitchNodes"]
715
+ sn_params = self.stitch_parameters
716
+ out_file = str(Path(sn_params.output_dir) / sn_params.output_file)
717
+ sn_argslist.extend(["--out", out_file])
718
+ if sn_params.in_file is not None:
719
+ sn_argslist.extend(["--in", sn_params.in_file])
720
+ if sn_params.in_list is not None:
721
+ sn_argslist.extend(["--in_list", sn_params.in_list])
722
+ if sn_params.in_fmt is not None:
723
+ sn_argslist.extend(["--in_fmt", ",".join(sn_params.in_fmt)])
724
+ if sn_params.allow_repeated_times:
725
+ sn_argslist.extend(["--allow_repeated_times"])
726
+ sn_argslist.extend(["--caltype", str(sn_params.caltype)])
727
+ if sn_params.time_begin is not None:
728
+ sn_argslist.extend(["--time_begin", str(sn_params.time_begin)])
729
+ if sn_params.time_end is not None:
730
+ sn_argslist.extend(["--time_end", str(sn_params.time_end)])
731
+ sn_argslist.extend(["--range", str(sn_params.max_sep)])
732
+ sn_argslist.extend(["--maxgap", str(sn_params.max_gap)])
733
+ sn_argslist.extend(["--mintime", str(sn_params.min_time)])
734
+ sn_argslist.extend(["--min_endpoint_dist", str(sn_params.min_endpoint_dist)])
735
+ sn_argslist.extend(["--min_path_dist", str(sn_params.min_path_dist)])
736
+ if sn_params.threshold_filters is not None:
737
+ sn_argslist.extend(["--threshold", lod_to_te(sn_params.threshold_filters)])
738
+ if sn_params.prioritize is not None:
739
+ sn_argslist.extend(["--prioritize", str(sn_params.prioritize)])
740
+ if sn_params.add_velocity:
741
+ sn_argslist.extend(["--add_velocity"])
742
+ sn_argslist.extend(["--out_file_format", sn_params.out_file_format])
743
+ if sn_params.out_seconds:
744
+ sn_argslist.extend(["--out_seconds"])
745
+
746
+ return sn_argslist
747
+
748
+ def stitch(self):
749
+ """Call the StitchNodes utility in Tempest Extremes.
750
+
751
+ This will make a system call out to the StitchNodes method from Tempest Extremes
752
+ (provided it has been installed as an external dependency). StitchNodes will be
753
+ run according to the parameters in the :attr:`stitch_parameters` attribute
754
+ that were set when the :class:`TETracker` instance was created.
755
+
756
+ The output is a file containing the data for each node of each trajectory. If
757
+ :attr:`~TEStitchParameters.output_dir` is ``None`` this will be a temporary
758
+ file lasting the lifetime of the :class:`TETracker` instance. The format of the
759
+ file depends on the :attr:`~TEStitchParameters.out_file_format` parameter.
760
+ The default ``"gfdl"`` output is a plain-text "nodefile" format which contains a
761
+ number of track trajectories, each of which in the form.
762
+
763
+ .. code-block:: text
764
+
765
+ start <N> <year> <month> <day> <hour>
766
+ <i> <j> <var1> <var2> ... <year> <month> <day> <hour>
767
+ ...
768
+ <i> <j> <var1> <var2> ... <year> <month> <day> <hour>
769
+
770
+ - ``N`` is number of nodes in the trajectory (and number of lines below header).
771
+ - ``i``, ``j`` are grid indices.
772
+ - ``var1``, ``var2``, etc., are scalar variables as defined by
773
+ :attr:`~TEStitchParameters.in_fmt` (typically, lon, lat, psl, orog).
774
+ - ``hour`` may instead be seconds if :attr:`~TEStitchParameters.out_seconds`
775
+ is ``True``.
776
+
777
+ Returns
778
+ -------
779
+ dict
780
+ dict of subprocess output corresponding to stdout, stderr, and returncode.
781
+
782
+ Raises
783
+ ------
784
+ FileNotFoundError
785
+ If the StitchNodes executeable from TempestExtremes cannot be found.
786
+ RuntimeError
787
+ If Tempest Extremes StitchNodes returns a non-zero exit code.
788
+
789
+ References
790
+ ----------
791
+ `TempestExtremes Documentation <https://climate.ucdavis.edu/tempestextremes.php#StitchNodes>`__
792
+ and the `StitchNodes Source <https://github.com/ClimateGlobalChange/tempestextremes/blob/master/src/nodes/StitchNodes.cpp>`_
793
+
794
+ Examples
795
+ --------
796
+ To set the parameters, instantiate a :class:`TETracker` instance and perform
797
+ stitching:
798
+
799
+ >>> my_params = TEStitchParameters(...)
800
+ >>> my_tracker = TETracker(stitch_parameters=my_params)
801
+ >>> result = my_tracker.stitch()
802
+ """
803
+ Path(self.stitch_parameters.output_dir).mkdir(parents=True, exist_ok=True)
804
+ sn_call_list = self._make_stitch_nodes_call()
805
+ return self._run_te_process("StitchNodes", sn_call_list)
806
+
807
+ def read_trajectories(self) -> list[Trajectory]:
808
+ """
809
+ Parse outputs from Tempest Extremes to list of :class:`tctrack.core.Trajectory`.
810
+
811
+ The file to be read and its properties are based on the values in the
812
+ :attr:`stitch_parameters` attribute.
813
+
814
+ Returns
815
+ -------
816
+ list[Trajectory]
817
+ A list of :class:`tctrack.core.Trajectory` objects.
818
+ """
819
+ out_file = str(
820
+ Path(self.stitch_parameters.output_dir) / self.stitch_parameters.output_file
821
+ )
822
+ if self.stitch_parameters.out_file_format == "gfdl":
823
+ trajectories = self._parse_trajectories_gfdl(out_file)
824
+ elif self.stitch_parameters.out_file_format == "csv":
825
+ trajectories = self._parse_trajectories_csv(out_file, has_header=True)
826
+ elif self.stitch_parameters.out_file_format == "csvnohead":
827
+ trajectories = self._parse_trajectories_csv(out_file, has_header=False)
828
+ return trajectories
829
+
830
+ @staticmethod
831
+ def _parse_gfdl_line_to_point(
832
+ line: list[str], variable_names: list[str] | None = None
833
+ ) -> tuple[list[int], dict[str, int | float]]:
834
+ """
835
+ Parse line from StitchNodes gfdl output into a trajectory data point.
836
+
837
+ Data point format is that expected by a :class:`tctrack.core.Trajectory`.
838
+
839
+ Parameters
840
+ ----------
841
+ line : list[str]
842
+ A list of strings representing the line split into parts.
843
+ variable_names : list[str] | None
844
+ List of variable names for the data columns. Defaults to None.
845
+
846
+ Returns
847
+ -------
848
+ tuple
849
+ A tuple containing the time as an integer list of [year, day, month, hour]
850
+ and a dict of variables.
851
+ """
852
+ return_vars: dict[str, int | float] = {}
853
+ return_vars.update({"grid_i": int(line[0]), "grid_j": int(line[1])})
854
+ if variable_names:
855
+ return_vars.update(
856
+ {
857
+ name: float(value)
858
+ for name, value in zip(variable_names, line[2:-4], strict=False)
859
+ }
860
+ )
861
+ else:
862
+ return_vars.update(
863
+ {
864
+ f"var_{i}": float(value)
865
+ for i, value in enumerate(line[2:-4], start=1)
866
+ }
867
+ )
868
+ time = list(map(int, line[-4:]))
869
+ return time, return_vars
870
+
871
+ def _parse_trajectories_gfdl(self, file_path):
872
+ """
873
+ Parse track trajectories from a gfdl file.
874
+
875
+ Parameters
876
+ ----------
877
+ file_path : str
878
+ Path to the input file.
879
+
880
+ Returns
881
+ -------
882
+ list[Trajectory]
883
+ A list of :class:`tctrack.core.Trajectory` objects.
884
+ """
885
+ trajectories = {}
886
+ current_trajectory_id = 0 # Initialize trajectory ID
887
+
888
+ # Get variable names from in_fmt
889
+ var_names = self.stitch_parameters.in_fmt or []
890
+
891
+ with open(file_path, "r") as file:
892
+ for line in file:
893
+ items = line.split()
894
+ if items[0] == "start":
895
+ # Start of new trajectory.
896
+ # Extract metadata and add Trajectory to dict
897
+ current_trajectory_id += 1
898
+ time = list(map(int, items[2:6]))
899
+
900
+ trajectories[current_trajectory_id] = Trajectory(
901
+ current_trajectory_id,
902
+ time,
903
+ calendar=self.stitch_parameters.caltype,
904
+ )
905
+
906
+ # Continue processing ongoing trajectory
907
+ else:
908
+ trajectories[current_trajectory_id].add_point(
909
+ *self._parse_gfdl_line_to_point(items, var_names)
910
+ )
911
+
912
+ return list(trajectories.values())
913
+
914
+ def _parse_trajectories_csv(self, file_path, has_header=False):
915
+ """
916
+ Generalized function to parse trajectories from csv file with/without header.
917
+
918
+ Parameters
919
+ ----------
920
+ file_path : str
921
+ Path to the input file.
922
+ has_header : bool, optional
923
+ Whether the file has a header. Defaults to False.
924
+
925
+ Returns
926
+ -------
927
+ list[Trajectory]
928
+ A list of :class:`tctrack.core.Trajectory` objects.
929
+ """
930
+ trajectories = {}
931
+
932
+ with open(file_path, "r") as file:
933
+ reader = (
934
+ csv.DictReader(file, skipinitialspace=True)
935
+ if has_header
936
+ else csv.reader(file)
937
+ )
938
+ for row in reader:
939
+ if has_header:
940
+ # Read from dict extracting variable names from keys/header
941
+ trajectory_id = int(row["track_id"])
942
+ time = [int(row[k]) for k in ("year", "month", "day", "hour")]
943
+ variables_dict = {"grid_i": int(row["i"]), "grid_j": int(row["j"])}
944
+ variables_dict.update(
945
+ {
946
+ key: float(value)
947
+ for key, value in row.items()
948
+ if key
949
+ not in {
950
+ "track_id",
951
+ "year",
952
+ "month",
953
+ "day",
954
+ "hour",
955
+ "i",
956
+ "j",
957
+ }
958
+ }
959
+ )
960
+ else:
961
+ # Read from csv assuming: id, y, m, d, h, i, j, var1, ..., varn
962
+ trajectory_id = int(row[0])
963
+ time = list(map(int, row[1:5]))
964
+ variables_dict = {"grid_i": int(row[5]), "grid_j": int(row[6])}
965
+ # Get variable names from in_fmt
966
+ var_names = self.stitch_parameters.in_fmt or [
967
+ f"var_{i + 1}" for i in range(len(row[7:]))
968
+ ]
969
+ variables_dict.update(
970
+ {
971
+ var_name: float(row[7 + i])
972
+ for i, var_name in enumerate(var_names)
973
+ }
974
+ )
975
+
976
+ if trajectory_id not in trajectories:
977
+ trajectories[trajectory_id] = Trajectory(
978
+ trajectory_id=trajectory_id,
979
+ time=time,
980
+ calendar=self.stitch_parameters.caltype,
981
+ )
982
+
983
+ trajectories[trajectory_id].add_point(time, variables_dict)
984
+
985
+ return list(trajectories.values())
986
+
987
+ def set_metadata(self) -> None:
988
+ """
989
+ Set the global and variable (reading from input files) metadata attributes.
990
+
991
+ Reads metadata for each variable listed in
992
+ :attr:`detect_parameters.output_commands` from the input NetCDF files
993
+ defined in :attr:`detect_parameters.in_data` (matching the NetCDF variable
994
+ name). These will be stored in the :attr:`variable_metadata` attribute as a
995
+ dictionary of :class:`TCTrackerMetadata` objects. This will be called from the
996
+ :meth:`to_netcdf` method.
997
+
998
+ Raises
999
+ ------
1000
+ ValueError
1001
+ If a variable is not found in the input files.
1002
+
1003
+ Examples
1004
+ --------
1005
+ To read in the metadata for ``psl`` from ``inputs.nc``:
1006
+
1007
+ >>> detect_params = TEDetectParameters(
1008
+ >>> in_data=["inputs.nc"],
1009
+ >>> output_commands=[TEOutputCommand(var="psl", operator="min", dist=0)],
1010
+ >>> )
1011
+ >>> tracker = TETracker(detect_params, stitch_params)
1012
+ >>> tracker.set_metadata()
1013
+ >>> tracker.variable_metadata
1014
+ {
1015
+ "psl": TCTrackerMetadata(
1016
+ properties={
1017
+ "standard_name": "air_pressure_at_sea_level",
1018
+ "long_name": "Sea Level Pressure",
1019
+ "units": "Pa",
1020
+ },
1021
+ constructs=[<CF CellMethod: area: point>],
1022
+ ),
1023
+ }
1024
+ """
1025
+ super().set_metadata()
1026
+
1027
+ detect_params_json = json.dumps(asdict(self.detect_parameters))
1028
+ stitch_params_json = json.dumps(asdict(self.stitch_parameters))
1029
+ self.global_metadata["detect_parameters"] = detect_params_json
1030
+ self.global_metadata["stitch_parameters"] = stitch_params_json
1031
+
1032
+ input_files = self.detect_parameters.in_data
1033
+
1034
+ # set time metadata
1035
+ variable_name = (
1036
+ self.detect_parameters.search_by_min
1037
+ or self.detect_parameters.search_by_max
1038
+ or "PSL"
1039
+ )
1040
+ fields = cf.read(
1041
+ input_files,
1042
+ select=f"ncvar%{variable_name}", # type: ignore[operator]
1043
+ netcdf_backend="netCDF4",
1044
+ )
1045
+ if not fields:
1046
+ msg = f"Variable '{variable_name}' not found in input files."
1047
+ raise ValueError(msg)
1048
+ _, time_coord = fields[0].construct_item("time")
1049
+ time_arr = time_coord.datetime_array
1050
+ self._time_metadata = {
1051
+ "calendar": time_coord.get_property("calendar"),
1052
+ "units": time_coord.get_property("units"),
1053
+ "start_time": time_arr[0],
1054
+ "end_time": time_arr[-1],
1055
+ }
1056
+
1057
+ # set variable metadata
1058
+ self._variable_metadata = {}
1059
+
1060
+ # Set the variable metadata for the grid indices generated by Tempest Extremes
1061
+ self._variable_metadata["grid_i"] = TCTrackerMetadata(
1062
+ {"long_name": "longitudinal grid index"}
1063
+ )
1064
+ self._variable_metadata["grid_j"] = TCTrackerMetadata(
1065
+ {"long_name": "latitudinal grid index"}
1066
+ )
1067
+
1068
+ # Set the variable metadata for the output variables
1069
+ var_outputs = self.detect_parameters.output_commands
1070
+ if var_outputs is None or input_files is None:
1071
+ return
1072
+
1073
+ for var_output in var_outputs:
1074
+ var_name = var_output["var"]
1075
+
1076
+ # Get the variable field from the netcdf file
1077
+ fields = cf.read(
1078
+ input_files,
1079
+ select=f"ncvar%{var_name}", # type: ignore[operator]
1080
+ netcdf_backend="netCDF4",
1081
+ )
1082
+ if not fields:
1083
+ msg = f"Variable '{var_name}' not found in input files."
1084
+ raise ValueError(msg)
1085
+ field = fields[0]
1086
+
1087
+ # Read and store the relevant metadata
1088
+ self._variable_metadata[var_name] = TCTrackerMetadata(
1089
+ {
1090
+ "standard_name": field.get_property("standard_name", var_name),
1091
+ "long_name": field.get_property("long_name", var_name),
1092
+ "units": field.get_property("units", "unknown"),
1093
+ }
1094
+ )
1095
+
1096
+ # Add information about how the value is determined using `output_commands`
1097
+ methods = {
1098
+ "max": "maximum",
1099
+ "min": "minimum",
1100
+ "avg": "mean",
1101
+ }
1102
+ method = methods.get(var_output["operator"])
1103
+ if method is not None:
1104
+ dist = var_output["dist"]
1105
+ if dist == 0:
1106
+ cell_method = cf.CellMethod("area", "point")
1107
+ else:
1108
+ qualifier = {"comment": f"lesser circle of radius {dist} degrees"}
1109
+ cell_method = cf.CellMethod("area", method, qualifiers=qualifier)
1110
+ self._variable_metadata[var_name].constructs = [cell_method]
1111
+
1112
+ def run_tracker(self, output_file: str):
1113
+ """Run TempestExtremes tracker to obtain tropical cyclone track trajectories.
1114
+
1115
+ This first runs :meth:`detect` to get TC candidates at each time. Then
1116
+ these are combined into trajectories using :meth:`stitch`.
1117
+ The output is then saved as a CF-compliant NetCDF trajectory file.
1118
+
1119
+ Arguments
1120
+ ---------
1121
+ output_file : str
1122
+ Filename to which the tropical cyclone trajectories are saved.
1123
+
1124
+ Raises
1125
+ ------
1126
+ FileNotFoundError
1127
+ - If the TempestExtremes executables cannot be found.
1128
+ - If the stitch output file does not exist.
1129
+ RuntimeError
1130
+ If the TempestExtremes commands return a non-zero exit code.
1131
+
1132
+ Examples
1133
+ --------
1134
+ To create the tracker instance, then use run_tracker to perform the detection,
1135
+ stitching, and generate output.
1136
+
1137
+ >>> detect_params = TEDetectParameters(...)
1138
+ >>> stitch_params = TEStitchParameters(...)
1139
+ >>> my_tracker = TETracker(detect_params, stitch_params)
1140
+ >>> my_tracker.run_tracker()
1141
+ """
1142
+ self.detect()
1143
+ self.stitch()
1144
+ self.to_netcdf(output_file)