Core

The Core module contains key components that are used throughout TCTrack. They are generic, and not tied to any particular tracking code or algorithm.

class tctrack.core.Trajectory(trajectory_id, time, calendar='gregorian')[source]

Bases: object

A single Lagrangian cyclone trajectory/track with metadata and data points.

trajectory_id

The unique identifier for the trajectory.

Type:

int

observations

Number of points in the trajectory.

Type:

int

calendar

The calendar type to use for datetime handling. Options are “gregorian”, “360_day”, or “noleap”.

Type:

str

start_time

Start time of the trajectory as a cftime.datetime object.

Type:

cftime.datetime

data

Dict of data for various variables along the trajectory. Timestamp and other variables as supplied in file. For compatibility elsewhere in TCTrack trajectories are assumed to contain as a minimum data for lat, lon, and time.

Type:

dict

add_point(time, variables)[source]

Add a single data point to the trajectory.

Parameters:
  • time (Sequence[int] | cftime.datetime) – The time of the data point. If a list of integers this should be in the order: year, month, day, hour, minute, second. Any values not provided will be set to 0. This will be converted to a cftime.datetime using the appropriate calendar.

  • variables (dict) – A dict containing any variables for the point as key : value pairs

Raises:

TypeError – If time is not a Sequence[int] or cftime.datetime.

add_multiple_points(times, variables)[source]

Add multiple data points to the trajectory in one go.

Parameters:
  • times (Sequence[Sequence[int] | cftime.datetime]) – The times of the data points. If the individual times are a list of integers this should be in the order: year, month, day, hour, minute, second. Any values not provided will be set to 0. This will be converted to a cftime.datetime using the appropriate calendar.

  • variables (dict) – A dict containing arrays of any variables for the point as key : list[value] pairs

Raises:

ValueError – If the lengths of any variable array do not match the number of times.

class tctrack.core.TCTracker[source]

Bases: ABC

Abstract Base Class representing a generic TCTracker class.

_variable_metadata

A dictionary containing metadata for variables. This attribute must be initialized by the subclass through the set_metadata() method, prior to which it is initialised as None.

Type:

dict[str, TCTrackerMetadata] | None

_time_metadata

A dictionary containing metadata for times including calendar, units, and start and end times of the dataset. This attribute must be initialized by the subclass through the set_metadata() method, prior to which it is initialised as None.

Type:

dict[str, ] | None

_global_metadata

A dictionary containing global metadata about the data and TCTrack parameters. This attribute should be initialized by the subclass through the set_metadata() method. The parameters should be output in a json format using json.dumps(asdict(parameters))

Type:

dict[str, str]

property variable_metadata: dict

Read-only property containing NetCDF metadata for variables.

Raises:

AttributeError – If _variable_metadata has not been initialized.

Type:

dict

property time_metadata: TCTrackerTimeMetadata

Read-only property containing time metadata for this Tracker run.

Raises:

AttributeError – If _time_metadata has not been initialized.

Type:

dict

property global_metadata: dict

Read-only property containing metadata for tctrack / tracker instance.

Raises:

AttributeError – If _global_metadata has not been initialized.

Type:

dict

abstract set_metadata()[source]

Abstract method to initialize the metadata attributes.

This method must be implemented by subclasses to populate the _variable_metadata attribute with relevant metadata for variables, :attr:`_time_metadata with metadata about the time for the dataset, and the _global_metadata attribute for metadata about the TCTrack parameters and name of the tracker.

This will be called from the to_netcdf() method.

Return type:

None

Notes

The _variable_metadata attribute is expected to be a dictionary where keys are variable names and values are instances of TCTrackerMetadata containing the metadata for that variable (e.g., standard_name, long_name, units).

The _time_metadata attribute is expected to be a typed dictionary of the TCTrackerTimeMetadata form containing the calendar type and units of the dataset, as well as the start and end times.

The _global_metadata should contain each parameter object in a json format using json.dumps(asdict(parameters)).

Examples

>>> class MyTracker(TCTracker):
...     def set_metadata(self):
...         super().set_metadata()
...         self._variable_metadata = {
...             "example_variable": TCTrackerMetadata(
...                 properties={
...                     "standard_name": "example_standard_name",
...                     "long_name": "Example Long Name",
...                     "units": "example_units",
...                 },
...                 constructs=[<CF CellMethod>],
...             }
...         }
...         self._time_metadata = {
...             "calendar": "example_calendar",
...             "units": "days since yyyy-mm-dd",
...             "start_time": cftime.datetime(
...                 yyyy, mm, dd, hh, calendar=self.example_calendar
...             ),
...             "end_time": cftime.datetime(
...                 yyyy, mm, dd, hh, calendar=self.example_calendar
...             ),
...         }
...         self.global_metadata["mytracker_parameters"] = json.dumps(
...             asdict(MyTrackerParameters)
...         ),
abstract read_trajectories()[source]

Parse tracking algorithm outputs into list of tctrack.core.Trajectory.

Implementation is deferred to the specific tracking algorithm. For compatibility elsewhere in TCTrack trajectories are assumed to contain as a minimum data for lat, lon, and timestep.

Returns:

A list of tctrack.core.Trajectory objects.

Return type:

list[Trajectory]

to_netcdf(output_file)[source]

Write track trajectories to CF-compliant NetCDF trajectory file.

Reads in trajectories based on the parameters set for a specific implementation of the class and writes them to a CF-Conventions compliant NetCDF trajectory file using cf-python. Trajectories are assumed to contain as a minimum data for lat, lon, and timestep.

An ancillary field variable is added to the output file indicating any tracks that start/end within 1 day of the input dataset boundaries.

Parameters:

output_file (str) – filename for the output netCDF file Note: This will be placed in the local directory unless a full path is given

Return type:

None

Warning

UserWarning

If there are no trajectories read in from the tracker outputs by read_trajectories() meaning no NetCDF output file can be written.

References

CF-Conventions v1.1 - H.4. Trajectory Data cf-python documentation

Examples

Instantiate a TCTracker subclass instance with appropriate parameters, run the relevant methods to generate cyclone track trajectories, and then save the results to a CF-compliant trajectory file:

>>> my_tracker = TCTracker(...)
>>> ...
>>> my_tracker.to_netcdf("my_netcdf_file.nc")
abstract run_tracker(output_file)[source]

Run the tracker to obtain tropical cyclone track trajectories as NetCDF file.

Implementation is deferred to the specific tracking algorithm.

This should first run any relevant methods for generating cyclone trajectories from the input data files. The trajectories output is then saved as a CF-compliant trajectory netCDF file by calling the to_netcdf() method of this class.

Parameters:

output_file (str) – Filename to which the tropical cyclone trajectories are saved.

Return type:

None

class tctrack.core.TCTrackerParameters[source]

Bases: object

Base Data Class for containing parameters of TCTracker classes.

Parameters for a specific algorithm should be subclassed from this base class. The child class should be annotated as a dataclass using @dataclass(repr=False).

Examples

>>> from tctrack.core import TCTrackerParameters
>>>
>>> @dataclass(repr=False)
>>> class MyTrackerParameters(TCTrackerParameters):
>>>     param_a: int
>>>     param_b: str
>>>
>>> params = MyTrackerParameters(param_a=1, param_b="example")
>>>
>>> print(params)
MyTrackerParameters(
    param_a     = 1
    param_b     = example
)
class tctrack.core.TCTrackerMetadata(properties, constructs=None, construct_kwargs=None)[source]

Dataclass containing the metadata for a single variable in variable_metadata.

properties: dict[str, str]

The basic metadata properties for the variable.

constructs: list | None = None

A list of any CF constructs to add, such as cf.CellMethod constructs.

construct_kwargs: list[dict] | None = None

A list of kwargs (as dicts) to use when the cf.Field.set_construct() method is called in TCTracker.to_netcdf(). This can be left as None, otherwise it must be the same length as constructs.

class tctrack.core.TCTrackerTimeMetadata[source]

Dataclass containing the time metadata for a dataset used by a Tracker.

calendar: str

The calendar type as a string.

units: str

The calendar units as a string.

start_time: datetime

The start time of the data processed as a cftime.datetime object.

end_time: datetime

The final time of the data processed as a cftime.datetime object.