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/track/track.py ADDED
@@ -0,0 +1,778 @@
1
+ """Module providing a class that binds the TRACK code.
2
+
3
+ References
4
+ ----------
5
+ - `TRACK code on the University of Reading GitLab
6
+ <https://gitlab.act.reading.ac.uk/track/track>`__
7
+ - Publication describing the algorithm: `Hodges et al., 2017
8
+ <https://doi.org/10.1175/JCLI-D-16-0557.1>`__
9
+ """
10
+
11
+ import json
12
+ import shutil
13
+ import subprocess
14
+ import warnings
15
+ from dataclasses import asdict, dataclass
16
+ from pathlib import Path
17
+
18
+ import cf
19
+
20
+ from tctrack.core import TCTracker, TCTrackerMetadata, TCTrackerParameters, Trajectory
21
+ from tctrack.utils import lat_lon_sizes
22
+
23
+
24
+ @dataclass(repr=False)
25
+ class TRACKParameters(TCTrackerParameters):
26
+ """Dataclass containing values for parameters used by TRACK."""
27
+
28
+ base_dir: str
29
+ """The filepath to the directory where TRACK is installed."""
30
+
31
+ input_file: str
32
+ """
33
+ NetCDF input file containing the north and easterly wind speeds on a Gaussian grid
34
+ in m/s.
35
+ """
36
+
37
+ filter_distance: float | None = None
38
+ """The minimum start-to-end distance which trajectories must travel, in degrees."""
39
+
40
+ wind_var_names: tuple[str, str] = ("ua", "va")
41
+ """The variable names for the Eastward and Northward Wind in the input file."""
42
+
43
+ pressure_level: int = 85000
44
+ """The pressure level at which to calculate the vorticity. In Pa."""
45
+
46
+ binary: str = "bin/track.run"
47
+ """The filepath of the main TRACK compiled binary relative to :attr:`base_dir`."""
48
+
49
+ file_extension: str = "track_out"
50
+ """
51
+ The file extension to use for intermediate TRACK output files. This cannot be the
52
+ same as part of the /path/to/TRACK/outdat.
53
+ """
54
+
55
+ vorticity_file: str = "vor.dat"
56
+ """The filename for the vorticity intermediate output file."""
57
+
58
+ filt_vorticity_file: str = "vor_T63.dat"
59
+ """The filename for the spectral filtered vorticity intermediate output file."""
60
+
61
+ export_inputs: bool = False
62
+ """Flag to export the TRACK command line inputs to files."""
63
+
64
+ read_inputs: bool = False
65
+ """
66
+ Flag to read the command line inputs from files instead of TRACKParameters. There
67
+ should be a file for each step, named as ``calculate_vorticity.in``,
68
+ ``spectral_filtering.in``, ``tracking.in``, and ``filter_trajectories.in``. If a
69
+ file dose not exist it will generate inputs from TRACKParameters as normal.
70
+ """
71
+
72
+ inputs_directory: str | None = None
73
+ """
74
+ Directory containing files for exporting / reading command line inputs. This will be
75
+ created if it does not exist. By default, the current directory is used.
76
+ """
77
+
78
+
79
+ class TRACKTracker(TCTracker):
80
+ """Class containing bindings to the TRACK code.
81
+
82
+ Attributes
83
+ ----------
84
+ parameters : TRACKParameters
85
+ Class containing the parameters for the TRACK algorithm(s)
86
+
87
+ References
88
+ ----------
89
+ `TRACK code on the University of Reading GitLab <https://gitlab.act.reading.ac.uk/track/track>`__
90
+ """
91
+
92
+ # Private attributes
93
+ _nx: int # Length of the longitude dimension of the data
94
+ _ny: int # Length of the latitude dimension of the data
95
+
96
+ def __init__(self, parameters: TRACKParameters):
97
+ """Construct the TRACK class.
98
+
99
+ Parameters
100
+ ----------
101
+ parameters : TRACKParameters
102
+ Class containing the parameters for the TRACK algorithm(s)
103
+ Defaults to the default values in TRACKParameters Class
104
+
105
+ Raises
106
+ ------
107
+ FileNotFoundError
108
+ If the input file does not exist.
109
+ """
110
+ self.parameters: TRACKParameters = parameters
111
+
112
+ # Get sizes from input file
113
+ input_file = self.parameters.input_file
114
+ if not Path(input_file).exists():
115
+ msg = f"Input file does not exist ({input_file})."
116
+ raise FileNotFoundError(msg)
117
+ self._ny, self._nx = lat_lon_sizes(input_file)
118
+
119
+ # Set up files in the TRACK directory (if not already)
120
+ base_dir = self.parameters.base_dir
121
+ shutil.copy(base_dir + "/data/zone.dat", base_dir + "/data/zone.dat0")
122
+ shutil.copy(base_dir + "/data/adapt.dat", base_dir + "/data/adapt.dat0")
123
+
124
+ def _get_initialisation_inputs(self, inputs: list[str]):
125
+ """Add "initialisation" inputs common to both tracking and filter_tracks calls.
126
+
127
+ Parameters
128
+ ----------
129
+ inputs : list[str]
130
+ The list of inputs which will be appended to in-place.
131
+ """
132
+ inputs.append("0") # Binary input
133
+ inputs.append("y") # Frames separated by newline
134
+ inputs.append("n") # Translate the grid?
135
+ inputs.append("y") # Make periodic
136
+ inputs.append("g") # Geodesic distance metric
137
+ inputs.append("y") # Change projection
138
+ inputs.append("1") # Azimuthal projection
139
+ inputs.append("0") # Not already azimuthal
140
+ inputs.append("b") # Both hemispheres
141
+ inputs.append("2") # Stereogrphic azimuthal projection
142
+
143
+ # Hemisphere 1
144
+ inputs.append("90") # Origin lat
145
+ inputs.append("0") # Origin lon
146
+ inputs.append("1") # Start x
147
+ inputs.append("193") # End x
148
+ inputs.append("49") # Start y
149
+ inputs.append("96") # End y
150
+ inputs.append("0") # Define by number of points
151
+ inputs.append("150") # New grid points in x
152
+ inputs.append("150") # New grid points in y
153
+
154
+ # Hemisphere 2
155
+ inputs.append("-90") # Origin lat
156
+ inputs.append("0") # Origin lon
157
+ inputs.append("1") # Start x
158
+ inputs.append("193") # End x
159
+ inputs.append("1") # Start y
160
+ inputs.append("48") # End y
161
+ inputs.append("0") # Define by number of points
162
+ inputs.append("150") # New grid points in x
163
+ inputs.append("150") # New grid points in y
164
+
165
+ def _get_calculate_vorticity_inputs(self) -> list[str]:
166
+ """Build the list of TRACK input parameters to calculate the vorticity.
167
+
168
+ Returns
169
+ -------
170
+ list[str]
171
+ The list of input parameters.
172
+ """
173
+ params = self.parameters
174
+
175
+ inputs = []
176
+
177
+ # Initialisation
178
+ inputs.append("n") # No country map
179
+ inputs.append("0") # No initialisation file
180
+ inputs.append("4") # NetCDF input
181
+ inputs.append("n") # No file summary
182
+ inputs.append("1") # Use netcdf names
183
+ inputs.append("y") # Uses COARDS convention
184
+ inputs.append(params.wind_var_names[0]) # Variable to use
185
+ inputs.append("n") # Translate the grid?
186
+ inputs.append(str(params.pressure_level)) # Pressure level to use (in Pa)
187
+ inputs.append("n") # Make periodic? (Only needed for tracking)
188
+ inputs.append("g") # Geodesic distance metric
189
+ inputs.append("n") # Don't change projection
190
+ inputs.append("1") # Start x domain at 1
191
+ inputs.append(str(self._nx)) # End x domain at final lon id
192
+ inputs.append("1") # Start y domain at 1
193
+ inputs.append(str(self._ny)) # End y domain at final lat id
194
+ inputs.append("y") # Perform analysis
195
+
196
+ # Vorticity calculation
197
+ inputs.append("12") # Compute vorticity
198
+ inputs.append("0") # Use B-splines
199
+ inputs.append("2") # Vorticity from winds
200
+ inputs.append("y") # File has both u and v
201
+ inputs.append(params.wind_var_names[0]) # Field for u
202
+ inputs.append(str(params.pressure_level)) # Pressure level
203
+ inputs.append(params.wind_var_names[1]) # Field for v
204
+ inputs.append(str(params.pressure_level)) # Pressure level
205
+ inputs.append("1") # U start frame id
206
+ inputs.append("1") # U frame step(?)
207
+ inputs.append("10000") # U end frame id
208
+ inputs.append("1") # V start frame id
209
+ inputs.append("1") # V frame step (?)
210
+ inputs.append("10000") # V end frame id
211
+ inputs.append("y") # Continue despite missing data
212
+ output_file = params.base_dir + "/indat/" + params.vorticity_file
213
+ inputs.append(output_file) # Output file name
214
+ inputs.append("0") # Smoopy interpolation - no spherical continuity
215
+ inputs.append("10") # 10 wrap around (x?)
216
+ inputs.append("0") # No smoothing - interpolation only
217
+ inputs.append("0") # No smoothing - interpolation only
218
+ inputs.append("0") # Exit
219
+
220
+ return inputs
221
+
222
+ def _get_spectral_filtering_inputs(self) -> list[str]:
223
+ """Build the list of TRACK input parameters to perform the spectral filtering.
224
+
225
+ Returns
226
+ -------
227
+ list[str]
228
+ The list of input parameters.
229
+ """
230
+ inputs = []
231
+
232
+ # Initialisation
233
+ inputs.append("n") # No country map
234
+ inputs.append("0") # No initialisation file
235
+ inputs.append("0") # Binary input
236
+ inputs.append("y") # Frames separated by newline
237
+ inputs.append("n") # Translate the grid?
238
+ inputs.append("n") # Make periodic? (Only needed for tracking)
239
+ inputs.append("g") # Geodesic distance metric
240
+ inputs.append("n") # Don't change projection
241
+ inputs.append("1") # Start x domain at 1
242
+ inputs.append(str(self._nx)) # End x domain at final lon id
243
+ inputs.append("1") # Start y domain at 1
244
+ inputs.append(str(self._ny)) # End y domain at final lat id
245
+ inputs.append("y") # Perform analysis
246
+
247
+ # Spectral Filtering
248
+ inputs.append("4") # Spectral Filtering
249
+ inputs.append("1") # Start frame ID
250
+ inputs.append("1") # Frame step
251
+ inputs.append("10000") # End frame ID
252
+ inputs.append("1") # Fast spectral transform
253
+ inputs.append("n") # Derived fields are not required
254
+ inputs.append("63") # If ny>=96 use T63 truncation, otherwise T42 truncation
255
+ inputs.append("y") # Output on new grid
256
+ inputs.append("1") # Use a Gaussian grid
257
+ inputs.append("63") # Truncation for output grid
258
+ inputs.append("2") # Number of filter bands
259
+ inputs.append("y") # Use Hoskins filter
260
+ inputs.append("0.1") # Cutoff constant value
261
+ inputs.append("0") # Band boundary wavenumber 1
262
+ inputs.append("5") # Band boundary wavenumber 2
263
+ inputs.append("63") # Band boundary wavenumber 3
264
+ inputs.append("n") # Do not restrict values
265
+
266
+ return inputs
267
+
268
+ def _get_tracking_inputs(self) -> list[str]: # noqa: PLR0915
269
+ """Build the list of TRACK input parameters to perform the tracking.
270
+
271
+ Returns
272
+ -------
273
+ list[str]
274
+ The list of input parameters.
275
+ """
276
+ inputs = []
277
+
278
+ inputs.append("n") # No country map
279
+ inputs.append("0") # No initialisation file
280
+ self._get_initialisation_inputs(inputs)
281
+ inputs.append("n") # No analysis
282
+ inputs.append("n") # No existing set of object / feature data
283
+ inputs.append("n") # Don't compute tendency
284
+
285
+ # Repeat twice for each hemisphere
286
+ for _ in range(2):
287
+ inputs.append("y") # Scale the field
288
+ inputs.append("1.0e+5") # Scaling
289
+ inputs.append("n") # No offset subtraction
290
+ inputs.append("1.0") # Required threshold
291
+ inputs.append("1") # Sphery smoothing (spherical continuity)
292
+ inputs.append("n") # Don't add another field
293
+ inputs.append("1") # MAX thresholding
294
+ inputs.append("1") # Start at frame 1
295
+ inputs.append("1") # Frame interval
296
+ inputs.append("100000") # End frame
297
+ inputs.append("e") # Edge connectivity only (not vertex)
298
+ inputs.append("2") # Lower limiting size of objects
299
+ # Surface fitting of region of interest and local optimisation [0,3,4,7,8,9]
300
+ inputs.append("7")
301
+ inputs.append("n") # Don't compute anisotropy / orientation / area
302
+ inputs.append("0") # Smoopy interpolation
303
+ # Don't filter object feature points for unphysical values
304
+ inputs.append("n")
305
+ # Don't filter to retain the point with the largest value
306
+ inputs.append("n")
307
+ inputs.append("n") # Don't filter for points too close together
308
+ inputs.append("n") # Don't use time average subtraction / thresholding
309
+ inputs.append("0.") # Sphery smoothing factor (0 = spline interpolation)
310
+ inputs.append("y") # Specify continuity properties at the poles
311
+ inputs.append("1") # C1 continuity
312
+ # Don't exclude boundary maxima (close to threshold boundary)
313
+ inputs.append("0")
314
+ inputs.append("0") # Smoopy smoothing factor
315
+ inputs.append("y") # Constrained optimisation
316
+ inputs.append("d") # Use default constraints (see data/constraints.dat)
317
+ inputs.append("n") # Don't save object data to file as well as feature data
318
+ inputs.append("n") # Don't plot first chosen frame
319
+ inputs.append("0") # No other plotting
320
+
321
+ # Don't rotate feature locations (to account for a rotated pole)
322
+ inputs.append("n")
323
+ inputs.append("n") # Don't load an existing file of track data
324
+ inputs.append("0.2") # Input weight 1 for modified greedy exchange algorithm
325
+ inputs.append("0.8") # Input weight 2
326
+ inputs.append("n") # Don't make tracking aware of any missing frames
327
+ inputs.append("y") # Use regional upper bound displacements (data/zone.dat0)
328
+ inputs.append("y") # Use adaptive tracking
329
+ inputs.append("6.5") # Max upperbound displacement for a phantom point (dmax)
330
+ inputs.append("1") # Cost function penalty for a phantom point (phimax)
331
+ inputs.append("n") # Don't plot initial track data
332
+ inputs.append("n") # Don't use a different initialisation
333
+ inputs.append("n") # Don't do a missing frame search
334
+ # Apply zonal upper bound displacements / adaptive track smoothness
335
+ inputs.append("y")
336
+ inputs.append("n") # Don't make tracking aware of the missing frames
337
+ inputs.append("y") # Use regional upper bound displacments
338
+ inputs.append("y") # Use adaptive tracking
339
+ inputs.append("0") # No further plotting (min points = 0)
340
+ inputs.append("0") # No track plotted
341
+ inputs.append("n") # Don't repeat with a different parametisation
342
+
343
+ return inputs
344
+
345
+ def _get_filter_trajectories_inputs(self) -> list[str]:
346
+ """Build the list of TRACK input parameters to perform the track filtering.
347
+
348
+ Returns
349
+ -------
350
+ list[str]
351
+ The list of input parameters.
352
+ """
353
+ params = self.parameters
354
+
355
+ inputs = []
356
+
357
+ inputs.append("n") # No country map
358
+ inputs.append("0") # No initialisation file
359
+ self._get_initialisation_inputs(inputs)
360
+ inputs.append("y") # Perform combination / analysis / etc
361
+ inputs.append("1") # Combine track data
362
+ inputs.append("n") # Don't use an existing combined file
363
+ inputs.append("1") # Use matching
364
+ inputs.append("1") # Number of batches
365
+ objout_file = params.base_dir + "/outdat/objout.new." + params.file_extension
366
+ tdump_file = params.base_dir + "/outdat/tdump." + params.file_extension
367
+ inputs.append(objout_file) # object file to use
368
+ inputs.append(tdump_file) # track file to use
369
+ inputs.append("1") # First frame number
370
+ inputs.append("n") # Don't check for and merge split tracks
371
+ inputs.append("8") # Min number of points in a track
372
+ inputs.append("1000000") # Max number of points in a track
373
+ if params.filter_distance is None:
374
+ inputs.append("n") # Don't filter tracks according to distance
375
+ else:
376
+ inputs.append("y") # Filter tracks according to distance
377
+ inputs.append(str(params.filter_distance))
378
+ inputs.append("s") # Distance between start and finish (or along track 't')
379
+ inputs.append("n") # Don't filter by system strength
380
+ inputs.append("n") # Don't filter by propogation direction
381
+ inputs.append("n") # Don't restrict the frame range
382
+ inputs.append("a") # Use all tracks
383
+ inputs.append("n") # We don't want the nearest grid point positions
384
+ inputs.append("n") # Don't plot the combined track data
385
+ # Don't redo with different minimum lifetime / data set / area of interest
386
+ inputs.append("n")
387
+ inputs.append("0") # Exit
388
+
389
+ return inputs
390
+
391
+ def _prepare_inputs(self, command_name: str, inputs: list[str]) -> str:
392
+ """Get the inputs as a string. Optionally reading from / exporting to a file.
393
+
394
+ The file is a text file containing the raw, unlabelled inputs in a specific
395
+ order. Refer to the _get_<step>_inputs functions for descriptions of the
396
+ variables.
397
+
398
+ If :attr:`~TRACKParameters.read_inputs` is ``True`` but the file doesn't exist a
399
+ warning will be thrown and it will continue with the generated inputs.
400
+
401
+ Parameters
402
+ ----------
403
+ command_name : str
404
+ The name of the TRACK step. Used in the file name:
405
+ ``<inputs_directory>/<command_name>.in``.
406
+ inputs : list[str]
407
+ The list of input parameters to pass to the TRACK program.
408
+
409
+ Returns
410
+ -------
411
+ str
412
+ A string containing the (unlabelled) input parameters separated by newline
413
+ characters.
414
+ """
415
+ input_commands = "\n".join(inputs) + "\n"
416
+
417
+ inputs_file = Path(f"{command_name}.in")
418
+ inputs_directory = self.parameters.inputs_directory
419
+ if inputs_directory is not None:
420
+ inputs_file = Path(inputs_directory) / inputs_file
421
+
422
+ # Read from file
423
+ if self.parameters.read_inputs:
424
+ try:
425
+ with open(inputs_file, "r") as f:
426
+ input_commands = f.read()
427
+ warnings.warn(
428
+ f"TRACK inputs are being read from file for '{command_name}'. "
429
+ "TRACKParameter values will be ignored.",
430
+ stacklevel=4,
431
+ )
432
+ except FileNotFoundError:
433
+ warnings.warn(
434
+ f"Exported TRACK inputs file for '{command_name}' does not exist "
435
+ "despite read_inputs=True. Continuing with generated inputs.",
436
+ stacklevel=4,
437
+ )
438
+
439
+ # Export to file
440
+ if self.parameters.export_inputs:
441
+ if inputs_directory is not None:
442
+ Path(inputs_directory).mkdir(parents=True, exist_ok=True)
443
+ with open(inputs_file, "w") as f:
444
+ f.write(input_commands)
445
+
446
+ return input_commands
447
+
448
+ def _run_track_process(self, command_name: str, input_file: str, inputs: list[str]):
449
+ """Run a TRACK command.
450
+
451
+ Parameters
452
+ ----------
453
+ command_name : str
454
+ The name of the command to be used in the log and error reporting.
455
+ input_file : str
456
+ The filename containing the input data for the command. The file should
457
+ first be copied into the 'indat' directory in the TRACK root directory.
458
+ inputs : list[str]
459
+ The list of input parameters to pass to the TRACK program.
460
+
461
+ Returns
462
+ -------
463
+ dict
464
+ dict of subprocess output corresponding to stdout, stderr, and returncode.
465
+
466
+ Raises
467
+ ------
468
+ FileNotFoundError
469
+ If the TRACK executable cannot be found on the system.
470
+ RuntimeError
471
+ If the TRACK executable returns a non-zero exit code.
472
+ """
473
+ try:
474
+ params = self.parameters
475
+ command = [
476
+ params.base_dir + "/" + params.binary,
477
+ "-i",
478
+ input_file,
479
+ "-f",
480
+ params.file_extension,
481
+ ]
482
+
483
+ input_commands = self._prepare_inputs(command_name, inputs)
484
+
485
+ print(f"{command_name} running...")
486
+ result = subprocess.run( # noqa: S603 - no shell
487
+ command,
488
+ input=input_commands,
489
+ check=True,
490
+ capture_output=True,
491
+ text=True,
492
+ )
493
+ print(f"{command_name} completed successfully.")
494
+ print(
495
+ f"First 12 lines of output:\n"
496
+ f"{''.join(result.stdout.splitlines(True)[:12])}"
497
+ f"\n...\n\n"
498
+ f"Last 12 lines of output:\n"
499
+ f"{''.join(result.stdout.splitlines(True)[-12:])}"
500
+ )
501
+ return {
502
+ "stdout": result.stdout,
503
+ "stderr": result.stderr,
504
+ "returncode": result.returncode,
505
+ }
506
+ except FileNotFoundError as exc:
507
+ msg = (
508
+ f"{command_name} failed because the executable could not be found.\n"
509
+ "Did you provide the full executeable path or add it to $PATH?\n"
510
+ )
511
+ raise FileNotFoundError(msg) from exc
512
+ except subprocess.CalledProcessError as exc:
513
+ msg = (
514
+ f"{command_name} failed with a non-zero exit code:"
515
+ f"({exc.returncode}):\n"
516
+ f"{exc.stderr}"
517
+ )
518
+ raise RuntimeError(msg) from exc
519
+
520
+ def calculate_vorticity(self):
521
+ """Use TRACK to calculate the vorticity from the wind components.
522
+
523
+ This method requires the wind speed components to be on a Gaussian grid in a
524
+ netcdf file, given by :attr:`~TRACKParameters.input_file`. This is copied to the
525
+ TRACK 'indat' folder and used as an input for a system call to TRACK to
526
+ calculate the vorticity.
527
+
528
+ The vorticity is written to a new file in the 'indat' folder given by
529
+ :attr:`~TRACKParameters.vorticity_file`. This uses the following layout::
530
+
531
+ <n_lon> <n_lat> <n_frames>
532
+ <List of longitudes spaced 10 to a line>
533
+ <List of latitudes spaced 10 to a line>
534
+ FRAME 1
535
+ <Binary block of floats for the vorticities in frame 1>
536
+ FRAME 2
537
+ <Binary block of floats for the vorticities in frame 2>
538
+ ...
539
+
540
+ Raises
541
+ ------
542
+ FileNotFoundError
543
+ If the TRACK executable cannot be found on the system.
544
+ RuntimeError
545
+ If the TRACK executable returns a non-zero exit code.
546
+ """
547
+ params = self.parameters
548
+ # Copy the input file to TRACK
549
+ shutil.copy(params.input_file, params.base_dir + "/indat/")
550
+ input_filename = Path(params.input_file).name
551
+ # Run TRACK to perform the calculation
552
+ inputs = self._get_calculate_vorticity_inputs()
553
+ self._run_track_process("calculate_vorticity", input_filename, inputs)
554
+
555
+ def spectral_filtering(self):
556
+ """Use TRACK to perform the spectral filtering of the vorticity.
557
+
558
+ This makes a system call to TRACK to spectrally filter the vorticity (in the
559
+ file :attr:`~TRACKParameters.vorticity_file`) to keep only wavenumbers 6-63.
560
+
561
+ The output file is copied to :attr:`~TRACKParameters.filt_vorticity_file` in the
562
+ TRACK 'indat' folder, so that it can be used in :meth:`tracking`. This file
563
+ has the same format as described in :meth:`calculate_vorticity`.
564
+
565
+ Raises
566
+ ------
567
+ FileNotFoundError
568
+ If the TRACK executable cannot be found on the system.
569
+ RuntimeError
570
+ If the TRACK executable returns a non-zero exit code.
571
+ """
572
+ params = self.parameters
573
+ inputs = self._get_spectral_filtering_inputs()
574
+ self._run_track_process("spectral_filtering", params.vorticity_file, inputs)
575
+ shutil.copy(
576
+ f"{params.base_dir}/outdat/specfil.{params.file_extension}_band001",
577
+ f"{params.base_dir}/indat/{params.filt_vorticity_file}",
578
+ )
579
+
580
+ def tracking(self):
581
+ """Call the tracking utility of TRACK.
582
+
583
+ This will make a system call out to TRACK to perform the detection of tropical
584
+ cyclone candidates using the spectrally filtered vorticity (stored in the file
585
+ :attr:`~TRACKParameters.filt_vorticity_file`). These candidates are then
586
+ combined into trajectories by minimising a cost function.
587
+
588
+ The trajectories are output in the ``objout.new.<ext>`` and ``tdump.<ext>`` text
589
+ files in the TRACK 'outdat' folder.
590
+
591
+ Raises
592
+ ------
593
+ FileNotFoundError
594
+ If the TRACK executable cannot be found on the system.
595
+ RuntimeError
596
+ If the TRACK executable returns a non-zero exit code.
597
+ """
598
+ params = self.parameters
599
+ inputs = self._get_tracking_inputs()
600
+ self._run_track_process("tracking", params.filt_vorticity_file, inputs)
601
+
602
+ def filter_trajectories(self):
603
+ """Use TRACK to filter the identified trajectories.
604
+
605
+ This step takes the identified trajectories from the :meth:`tracking` step
606
+ stored in the ``objout.new.<ext>`` and ``tdump.<ext>`` files. It then filters
607
+ out trajectories with fewer than 8 points (i.e. based on the duration) or a
608
+ total distance less than :attr:`~TRACKParameters.filter_distance` (if set).
609
+
610
+ This step could also be used to combine multiple outputs if the previous
611
+ tracking step was batched. However, this is not currently used.
612
+
613
+ The output of this step is a ``ff_trs.<ext>.nc`` file in the TRACK 'outdat'
614
+ folder containing the data along the filtered trajectories. To convert this into
615
+ a CF-compliant trajectory format the :meth:`to_netcdf` function should be used.
616
+
617
+ Raises
618
+ ------
619
+ FileNotFoundError
620
+ If the TRACK executable cannot be found on the system.
621
+ RuntimeError
622
+ If the TRACK executable returns a non-zero exit code.
623
+ """
624
+ input_file = self.parameters.filt_vorticity_file
625
+ inputs = self._get_filter_trajectories_inputs()
626
+ self._run_track_process("filter_trajectories", input_file, inputs)
627
+
628
+ def read_trajectories(self) -> list[Trajectory]:
629
+ """Parse outputs from TRACK to list of :class:`tctrack.core.Trajectory`.
630
+
631
+ This reads the output file from the filter_trajectories step, i.e.
632
+ ``ff_trs.<ext>.nc`` in the TRACK 'outdat' folder. It also takes the times from
633
+ the data in :attr:`TRACKParameters.input_file`.
634
+
635
+ Returns
636
+ -------
637
+ list[Trajectory]
638
+ A list of :class:`tctrack.core.Trajectory` objects.
639
+
640
+ Raises
641
+ ------
642
+ FileNotFoundError
643
+ If the TRACK output file does not exist.
644
+ """
645
+ params = self.parameters
646
+ trajectory_file = f"{params.base_dir}/outdat/ff_trs.{params.file_extension}.nc"
647
+
648
+ try:
649
+ fields = cf.read(trajectory_file) # type: ignore[operator]
650
+ except FileNotFoundError as e:
651
+ msg = (
652
+ f"TRACK output trajectory file does not exist ({trajectory_file}).\n"
653
+ "Check if TRACK completed successfully."
654
+ )
655
+ raise FileNotFoundError(msg) from e
656
+
657
+ # Get the number of points for each track
658
+ num_pts_all = fields.select_field("ncvar%NUM_PTS").array
659
+ (ids,) = num_pts_all.nonzero()
660
+ num_pts = num_pts_all[ids]
661
+ i_start = fields.select_field("ncvar%FIRST_PT").array[ids]
662
+
663
+ # Get the data for each track
664
+ time_idx = fields.select_field("ncvar%time").array - 1 # This is 1-indexed
665
+ lon = fields.select_field("ncvar%longitude").array
666
+ lat = fields.select_field("ncvar%latitude").array
667
+ intensity = fields.select_field("ncvar%intensity").array
668
+
669
+ # Convert the time indicies to datetimes using the input file data
670
+ all_times = cf.read(params.input_file)[0].coordinate("time") # type: ignore[operator]
671
+ datetimes = all_times.datetime_array[time_idx]
672
+
673
+ trajectories: list[Trajectory] = []
674
+ for it in range(len(ids)):
675
+ i1 = i_start[it]
676
+ i2 = i1 + num_pts[it]
677
+ trajectory = Trajectory(it, datetimes[i1], calendar=all_times.calendar)
678
+ variables = {
679
+ "lon": lon[i1:i2],
680
+ "lat": lat[i1:i2],
681
+ "intensity": intensity[i1:i2],
682
+ }
683
+ trajectory.add_multiple_points(datetimes[i1:i2], variables)
684
+ trajectories.append(trajectory)
685
+
686
+ return trajectories
687
+
688
+ def set_metadata(self) -> None:
689
+ """
690
+ Set the global, time, and variable metadata attributes.
691
+
692
+ Raises
693
+ ------
694
+ ValueError
695
+ If a variable with time coordinate is not found in the input file.
696
+ """
697
+ super().set_metadata()
698
+
699
+ self.global_metadata["track_parameters"] = json.dumps(asdict(self.parameters))
700
+
701
+ vars_with_time = cf.read(self.parameters.input_file).select_by_construct("time") # type: ignore[operator] # type: ignore[operator]
702
+ if len(vars_with_time) == 0:
703
+ msg = r"No variable with 'time' coordinate found in TRACK input file."
704
+ raise ValueError(msg)
705
+ time_coord = vars_with_time[0].coordinate("time")
706
+ self._time_metadata = {
707
+ "calendar": time_coord.calendar,
708
+ "units": time_coord.units,
709
+ "start_time": time_coord.data[0],
710
+ "end_time": time_coord.data[-1],
711
+ }
712
+
713
+ self._variable_metadata = {}
714
+
715
+ plev_domain = cf.DomainAxis(size=1)
716
+ plev = cf.Data(self.parameters.pressure_level, units="Pa")
717
+ plev_coord = cf.AuxiliaryCoordinate(
718
+ data=plev,
719
+ properties={
720
+ "standard_name": "air_pressure",
721
+ "long_name": "pressure",
722
+ },
723
+ )
724
+
725
+ self._variable_metadata["intensity"] = TCTrackerMetadata(
726
+ properties={
727
+ "standard_name": "atmosphere_upward_relative_vorticity",
728
+ "long_name": f"Relative vorticity at {plev}",
729
+ "units": "s-1",
730
+ },
731
+ constructs=[plev_domain, plev_coord],
732
+ construct_kwargs=[{"key": "plev"}, {"axes": "plev"}],
733
+ )
734
+
735
+ def run_tracker(self, output_file: str):
736
+ """Run the TRACK tracker to obtain the tropical cyclone track trajectories.
737
+
738
+ This runs the relevant methods in order:
739
+
740
+ * :meth:`calculate_vorticity`
741
+ * :meth:`spectral_filtering`
742
+ * :meth:`tracking`
743
+ * :meth:`filter_trajectories`
744
+
745
+ Finally the output is then saved as a CF-compliant trajectory netCDF file by
746
+ calling :meth:`to_netcdf`.
747
+
748
+ This method will overwrite the files in the 'outdat' folder in the TRACK source
749
+ location. Therefore, any outputs from running TRACK manually should be moved
750
+ to prevent loss of data.
751
+
752
+ Arguments
753
+ ---------
754
+ output_file : str
755
+ Filename to which the tropical cyclone track trajectories are saved.
756
+
757
+ Raises
758
+ ------
759
+ FileNotFoundError
760
+ If the TRACK executable cannot be found.
761
+ RuntimeError
762
+ If the TRACK executable returns a non-zero exit code.
763
+
764
+ Examples
765
+ --------
766
+ To set the parameters, instantiate a :class:`TRACKTracker` instance and run the
767
+ algorithms to generate trajectories:
768
+
769
+ >>> track_params = TRACKParameters(...)
770
+ >>> my_tracker = TRACKTracker(track_params)
771
+ >>> my_tracker.run_tracker("trajectories.nc")
772
+ """
773
+ self.calculate_vorticity()
774
+ self.spectral_filtering()
775
+ self.tracking()
776
+ self.filter_trajectories()
777
+
778
+ self.to_netcdf(output_file)