bluemath_tk.tcs package
Submodules
bluemath_tk.tcs.graffitiwaves module
bluemath_tk.tcs.parameterization module
bluemath_tk.tcs.qtcrain module
bluemath_tk.tcs.shytcwaves module
- bluemath_tk.tcs.shytcwaves.analogue_endpoints(df_seg: DataFrame, df_analogue: DataFrame) DataFrame [source]
Add segment endpoint coordinates by looking up the real target segment.
- Parameters:
df_seg (pd.DataFrame) – Parameterized historical storm track DataFrame containing: - lon, lat : Target origin coordinates - aseg : Warmup azimuth - daseg : Target azimuth variation
df_analogue (pd.DataFrame) – Analogue segments from library containing: - vseg : Mean translational speed (kt) - dvseg : Speed variation (kt) - daseg : Target azimuth variation
- Returns:
Updated analogue segments DataFrame with added columns: - aseg : Warmup azimuth - lon_w, lat_w : Warmup origin coordinates - lon_i, lat_i : Target origin coordinates (from df_seg) - lon_t, lat_t : Target endpoint coordinates
- Return type:
pd.DataFrame
Notes
The function: 1. Calculates warmup origin by shooting backwards 24h from target origin 2. Uses target origin from historical track 3. Calculates target endpoint by shooting forwards 6h from target origin 4. Accounts for hemisphere when calculating angles 5. Converts longitudes to [0-360°] convention
- bluemath_tk.tcs.shytcwaves.find_analogue(df_library: DataFrame, df_case: DataFrame, ix_weights: List[float]) ndarray [source]
Find the minimum distance in a 10-dimensional normalized space.
- Parameters:
df_library (pd.DataFrame) – Library parameters DataFrame containing the 10 SHyTCWaves parameters: {pseg, vseg, wseg, rseg, dp, dv, dw, dr, dA, lat}
df_case (pd.DataFrame) – Target case parameters DataFrame with same structure as df_library.
ix_weights (List[float]) – Weight factors for each parameter dimension.
- Returns:
Indices of nearest points in the library for each case point.
- Return type:
np.ndarray
Notes
The function finds the minimum distance in a normalized space corresponding to the SHyTCWaves 10 parameters: - pseg : Segment pressure - vseg : Mean translational speed - wseg : Maximum winds - rseg : RMW - dp : Pressure variation - dv : Speed variation - dw : Wind variation - dr : RMW variation - dA : Azimuth variation - lat : Latitude
- bluemath_tk.tcs.shytcwaves.find_nearest(cp_rad_ls: List[float], cp_ang_ls: List[float], mask_rad: ndarray, mask_ang: ndarray) ndarray [source]
Find nearest points in normalized space of radii and angles.
- Parameters:
cp_rad_ls (List[float]) – Control point radial distances.
cp_ang_ls (List[float]) – Control point angles.
mask_rad (np.ndarray) – SWAN output point radial distances.
mask_ang (np.ndarray) – SWAN output point angles.
- Returns:
Indices of nearest points in SWAN output grid for each control point.
- Return type:
np.ndarray
Notes
The function: 1. Creates dataframes from control points and SWAN grid points 2. Treats radial distances as scalar values 3. Treats angles as directional values (circular) 4. Uses nearest neighbor search in normalized space
- bluemath_tk.tcs.shytcwaves.get_coef_calibration() ndarray [source]
Get calibration coefficients for SHyTCWaves model pressure bias correction.
- Returns:
Linear fit coefficients for pressure bias correction.
- Return type:
np.ndarray
Notes
The function: 1. Uses Saffir-Simpson category center pressures as reference points 2. Applies calibrated pressure deltas based on validation against satellite data 3. Performs linear fit to get correction coefficients
- bluemath_tk.tcs.shytcwaves.get_cp_radii_angle(st_lat: float, st_lon: float, cp_lat_ls: List[float], cp_lon_ls: List[float], sign: int, aseg: float) Tuple[List[float], List[float]] [source]
Extract control point distances and angles in the relative coordinate system.
- Parameters:
st_lat (float) – Storm center latitude.
st_lon (float) – Storm center longitude.
cp_lat_ls (List[float]) – Control point latitudes.
cp_lon_ls (List[float]) – Control point longitudes.
sign (int) – Hemisphere indicator: 1 for north, -1 for south.
aseg (float) – Azimuth of the analogue warm segment (from geographic north).
- Returns:
Two lists containing: - cp_dist_ls : Distances from storm center to control points (km) - cp_ang_ls : Angles from storm center to control points (degrees)
- Return type:
Tuple[List[float], List[float]]
Notes
The function: 1. Calculates great circle distances between storm center and control points 2. Converts distances from degrees to kilometers 3. Calculates angles relative to geographic north 4. Transforms angles to relative coordinate system 5. Adjusts angles for southern hemisphere
- bluemath_tk.tcs.shytcwaves.get_mask_radii_angle(icase: int, mode: str = '') Tuple[ndarray, ndarray] [source]
Extract radii and angle indices for output points.
- Parameters:
icase (int) – Analogue case ID.
mode (str, optional) – Option to select SHyTCWaves library resolution (‘’, ‘_lowres’). Default is “”.
- Returns:
Two arrays containing: - rad : Radial distances from storm center (km) - ang : Angles from storm center (degrees)
- Return type:
Tuple[np.ndarray, np.ndarray]
Notes
The function: 1. Loads output indices associated with distances/angles to target origin 2. Determines grid size (small/medium/large) based on case ID 3. Extracts appropriate radii and angle arrays for the grid size 4. For low resolution mode, uses half the number of radial points
- bluemath_tk.tcs.shytcwaves.historic2shytcwaves_cluster(path_save: str, tc_name: str, storm: Dataset, center: str, lon: ndarray, lat: ndarray, dict_site: dict | None = None, calibration: bool = True, mode: str = '', database_on: bool = False, st_param: bool = False, extract_bulk: bool = True, max_segments: int = 300) None [source]
Process historical storm track data using SHyTCWaves methodology.
- Parameters:
path_save (str) – Base path to store results, without the file name.
tc_name (str) – Storm name.
storm (xr.Dataset) –
Storm track dataset with standard IBTrACS variables:
Required: - longitude, latitude : Storm coordinates - pressure : Central pressure (mbar) - maxwinds : Maximum sustained winds (kt)
Optional: - rmw : Radius of maximum winds (nmile) - dist2land : Distance to land - basin : Basin identifier
center (str) – IBTrACS center code.
lon (np.ndarray) – Longitude coordinates for swath calculation.
lat (np.ndarray) – Latitude coordinates for swath calculation.
dict_site (dict, optional) – Site data for superpoint building. Default is None. Must contain: - lonpts : Longitude coordinates - latpts : Latitude coordinates - namepts : Site names - site : Site identifier - sectors : Sectors - deg_superposition : Superposition degree
calibration (bool, optional) – Whether to apply SHyTCWaves calibration. Default is True.
mode (str, optional) – High or low resolution library indices. Default is “”.
database_on (bool, optional) – Whether to keep data only at 0,6,12,18 hours. Default is False.
st_param (bool, optional) – Whether to keep data as original. Default is False.
extract_bulk (bool, optional) – Whether to extract bulk wave parameters. Default is True.
max_segments (int, optional) – Maximum number of segments to process. Default is 300.
Notes
The function processes historical storm tracks in several steps: 1. Performs stopmotion segmentation at 6h intervals 2. Optionally applies SHyTCWaves calibration to track parameters 3. Trims track to target domain 4. Finds analogue segments from library 5. Extracts bulk wave parameters and/or spectral data 6. Saves results to specified directory
- bluemath_tk.tcs.shytcwaves.stopmotion_interpolation(df_seg: DataFrame, st: DataFrame = None, t_warm: int = 24, t_seg: int = 6, t_prop: int = 42) Tuple[List[DataFrame], List[DataFrame]] [source]
Generate SWAN cases in cartesian coordinates from stopmotion parameterized segments.
- Parameters:
df_seg (pd.DataFrame) – Stopmotion segments containing: - vseg : Mean translational speed (kt) - pseg : Segment pressure (mbar) - wseg : Maximum winds (kt) - rseg : RMW (nmile) - laseg : Absolute latitude (degrees) - dvseg : Speed variation (kt) - dpseg : Pressure variation (mbar) - dwseg : Wind variation (kt) - drseg : RMW variation (nmile) - daseg : Azimuth variation (degrees)
st (pd.DataFrame, optional) – Real storm track data. If None, MDA segments are used (unrelated to historic tracks).
t_warm (int, optional) – Warmup period in hours. Default is 24.
t_seg (int, optional) – Target period in hours. Default is 6.
t_prop (int, optional) – Propagation period in hours. Default is 42.
- Returns:
Two lists containing:
List of storm track DataFrames with columns: - x, y : Cartesian coordinates (m) - lon, lat : Geographic coordinates (degrees) - vf : Translation speed (kt) - vfx, vfy : Velocity components (kt) - pn : Surface pressure (1013 mbar) - p0 : Minimum central pressure (mbar) - vmax : Maximum winds (kt) - rmw : RMW (nmile) - latitude : Latitude with hemisphere sign
List of empty wave event DataFrames with columns: - hs, t02, dir, spr : Wave parameters - U10, V10 : Wind components - level, tide : Water level parameters
- Return type:
Tuple[List[pd.DataFrame], List[pd.DataFrame]]
Notes
The function generates SWAN cases in cartesian coordinates following SHyTCWaves configuration:
Warmup period (24h): Over the negative x-axis ending at (x,y)=(0,0)
Target period (6h): Starting at (x,y)=(0,0)
Propagation period (42h): No track coordinates (no wind forcing)
- bluemath_tk.tcs.shytcwaves.stopmotion_st_bmu(df_analogue: DataFrame, df_seg: DataFrame, st: DataFrame, cp_lon_ls: List[float], cp_lat_ls: List[float], max_dist: float = 60, list_out: bool = False, tqdm_out: bool = False, text_out: bool = True, mode: str = '') Dataset [source]
Extract bulk wave parameters from library analogue cases.
- Parameters:
df_analogue (pd.DataFrame) – Analogue prerun segments from library.
df_seg (pd.DataFrame) – Storm 6h-segments parameters.
st (pd.DataFrame) – Storm track interpolated every 6h.
cp_lon_ls (List[float]) – Control point longitude coordinates.
cp_lat_ls (List[float]) – Control point latitude coordinates.
max_dist (float, optional) – Maximum distance (km) to extract closest node. Default is 60.
list_out (bool, optional) – Whether to return list of datasets instead of merged dataset. Default is False.
tqdm_out (bool, optional) – Whether to show progress bar. Default is False.
text_out (bool, optional) – Whether to show text output. Default is True.
mode (str, optional) – High or low resolution library indices. Default is “”.
- Returns:
Wave directional spectra with dimensions: - case : Storm segments - point : Control points - time : Time steps
Contains variables: - hs : Significant wave height - tp : Peak period - lon, lat : Control point coordinates - ix_near : Nearest point indices - pos_nonan : Valid point mask - bmu : Best matching unit indices - hsbmu : Maximum Hs per point and time - tpbmu : Tp at maximum Hs - hswath : Maximum Hs per point - tswath : Tp at maximum Hs per point
- Return type:
xr.Dataset
Notes
The function: 1. Accesses library analogue cases for a given storm track 2. Calculates distance and angle from target segment origin to control points 3. Extracts wave parameters at closest nodes for each analogue segment 4. Computes bulk parameter envelope and swath 5. Handles both high and low resolution libraries
- bluemath_tk.tcs.shytcwaves.stopmotion_st_spectra(df_analogue: DataFrame, df_seg: DataFrame, st: DataFrame, cp_lon_ls: List[float], cp_lat_ls: List[float], cp_names: List[str] = [], max_dist: float = 60, list_out: bool = False, tqdm_out: bool = False, text_out: bool = True, mode: str = '') Tuple[Dataset, Dataset] [source]
Function to access the library analogue cases for a given storm track, calculate distance and angle from the target segment origin to the control point (relative coordinate system), and extract the directional wave spectra at the closest node (for every analogue segment)
- Parameters:
df_analogue (pd.DataFrame) – Analogue prerun segments from library.
df_seg (pd.DataFrame) – Storm 6h-segments parameters.
st (pd.DataFrame) – Storm track interpolated every 6h.
cp_lon_ls (List[float]) – Control point geographical coordinates.
cp_lat_ls (List[float]) – Control point geographical coordinates.
cp_names (List[str], optional) – Control point names. Default is [].
max_dist (float, optional) – Maximum distance [km] to extract closest node. Default is 60.
list_out (bool, optional) – Whether to list output. Default is False.
tqdm_out (bool, optional) – Whether to use tqdm. Default is False.
text_out (bool, optional) – Whether to print text. Default is True.
mode (str, optional) – Mode. Default is “”.
- Returns:
xds_spec : Wave directional spectra (dim ‘case’)
xds_bmu : BMU indices
- Return type:
Tuple[xr.Dataset, xr.Dataset]
Notes
The function: 1. Removes NaN values from df_seg and df_analogue 2. Assigns time to df_seg 3. Gets hemisphere sign 4. Gets bmu (wavespectra reconstructed) 5. Opens seg_sim dataset
- bluemath_tk.tcs.shytcwaves.storm2stopmotion(df_storm: DataFrame) DataFrame [source]
Generate stopmotion segments from storm track.
- Parameters:
df_storm (pd.DataFrame) – Storm track DataFrame containing: - lon : Longitude coordinates - lat : Latitude coordinates - p0 : Minimum central pressure (mbar) - vmax : Maximum sustained winds (kt) - rmw : Radius of maximum winds (nmile) - vmaxfill : Boolean indicating if winds were filled with estimates - rmwfill : Boolean indicating if RMW was filled with estimates
- Returns:
Stopmotion segments with columns: - vseg : Mean translational speed (kt) - dvseg : Speed variation (kt) - pseg : Segment pressure (mbar) - dpseg : Pressure variation (mbar) - wseg : Segment maximum winds (kt) - dwseg : Wind variation (kt) - rseg : Segment RMW (nmile) - drseg : RMW variation (nmile) - aseg : Azimuth from geographic North (degrees) - daseg : Azimuth variation (degrees) - lseg : Latitude (degrees) - laseg : Absolute latitude (degrees) - dlaseg : Latitude variation (degrees) - lon_w : Warmup origin longitude - lat_w : Warmup origin latitude - lon_i : Target origin longitude - lat_i : Target origin latitude - lon_t : Target endpoint longitude - lat_t : Target endpoint latitude
- Return type:
pd.DataFrame
Notes
The function generates stopmotion segments methodology from 6-hour storm track segments:
- Warmup segment (24h):
4 segments to define start/end coordinates
Defines {Vmean, relative angle}
Last 4th segment defines mean {Pmin, Wmax, Rmw}
Endpoint defines {lat}
- Target segment (6h):
Defines variations {dP, dV, dW, dR, dAng}
The absolute value of latitude is stored (start of target segment). Relative angle is referenced to geographic north (southern hemisphere is multiplied by -1).
bluemath_tk.tcs.tracks module
- bluemath_tk.tcs.tracks.check_and_plot_track_data(track_data: Dataset) Figure [source]
Check the track data for missing values and plot the track.
- Parameters:
track_data (xr.Dataset) – The track data to check in IBTrACS format. Must contain variables for time, longitude, latitude, pressure, and maximum winds for each center.
- Returns:
Figure object containing four subplots: 1. Storm coordinates (lon vs lat) 2. Minimum central pressure time series 3. Maximum sustained winds time series 4. Radii of maximum winds time series (if available)
- Return type:
plt.Figure
Notes
Longitude values are converted to [0-360º] convention
Wind speeds are converted to 1-minute average using center-specific factors
Variables that are entirely NaN are omitted from plots
- bluemath_tk.tcs.tracks.entrance_coords(delta: float, gamma: float, x0: float, y0: float, R: float, lon0: float, lon1: float, lat0: float, lat1: float) Tuple[float, float] [source]
Calculate storm entrance coordinates at computational domain boundary.
- Parameters:
delta (float) – Storm track angle parameter in degrees.
gamma (float) – Storm forward direction in degrees.
x0 (float) – Site longitude coordinate in degrees.
y0 (float) – Site latitude coordinate in degrees.
R (float) – Radius of influence in degrees.
lon0 (float) – Western longitude bound of computational domain.
lon1 (float) – Eastern longitude bound of computational domain.
lat0 (float) – Southern latitude bound of computational domain.
lat1 (float) – Northern latitude bound of computational domain.
- Returns:
Tuple containing: - x1 : Entrance longitude coordinate in degrees. - y1 : Entrance latitude coordinate in degrees.
- Return type:
Tuple[float, float]
Notes
The function: 1. Calculates entrance point on the radius of influence 2. Determines angles to domain corners from entrance point 3. Uses storm direction to determine intersection with domain boundary 4. Returns coordinates where storm track enters computational domain
Examples
>>> x1, y1 = entrance_coords(45, 270, -75, 25, 5, -80, -70, 20, 30) >>> print(f"Entrance point: ({x1:.1f}°, {y1:.1f}°)") Entrance point: (-78.5°, 27.5°)
- bluemath_tk.tcs.tracks.filter_track_by_basin(tracks_data: Dataset, id_basin: str) Dataset [source]
Filter the tracks data by basin.
- Parameters:
tracks_data (xr.Dataset) – The tracks data to filter in IBTrACS format. Must contain a ‘basin’ variable.
id_basin (str) – The basin ID to filter by (e.g., ‘NA’, ‘SP’, etc.)
- Returns:
The filtered tracks data containing only storms from the specified basin
- Return type:
xr.Dataset
Examples
>>> sp_tracks = filter_track_by_basin(tracks_data, "SP") >>> print(sp_tracks.storm.size)
- bluemath_tk.tcs.tracks.get_category(ycpres: ndarray) ndarray [source]
Calculate storm category based on central pressure.
- Parameters:
ycpres (np.ndarray) – Array of central pressures in millibars (mbar).
- Returns:
Array of storm categories: - 6: Missing data (pressure = 0 or NaN) - 5: Category 5 (pressure < 920 mbar) - 4: Category 4 (920 ≤ pressure < 944 mbar) - 3: Category 3 (944 ≤ pressure < 964 mbar) - 2: Category 2 (964 ≤ pressure < 979 mbar) - 1: Category 1 (979 ≤ pressure < 1000 mbar) - 0: Tropical Storm/Depression (pressure ≥ 1000 mbar)
- Return type:
np.ndarray
Notes
Uses np.select for vectorized operations. Categories are based on the Saffir-Simpson Hurricane Wind Scale pressure thresholds.
Examples
>>> pressures = np.array([915, 950, 980, 1005, np.nan]) >>> get_category(pressures) array([5, 3, 1, 0, 6])
- bluemath_tk.tcs.tracks.get_center_information(center: str = 'WMO') Dict[str, str | None] [source]
Get the center information from the configuration parameters for IBTrACS data.
- Parameters:
center (str, optional) – The name of the center to get information for. Default is “WMO”.
- Returns:
A dictionary containing the center information with the following keys: - source: Center ID - basin: Basin identifier - time: Time variable name - longitude: Longitude variable name - latitude: Latitude variable name - pressure: Pressure variable name - maxwinds: Maximum winds variable name - rmw: Radius of maximum winds variable name (if available) - dist2land: Distance to land variable name
- Return type:
Dict[str, Union[str, None]]
- Raises:
ValueError – If the specified center is not found in the configuration parameters.
Examples
>>> info = get_center_information("USA") >>> info["source"] 'usa' >>> info["rmw"] 'usa_rmw'
- bluemath_tk.tcs.tracks.get_vmean(lat1: float | ndarray, lon1: float | ndarray, lat2: float | ndarray, lon2: float | ndarray, deltat: float | ndarray) Tuple[float | ndarray, float | ndarray, float | ndarray, float | ndarray] [source]
Calculate storm translation speed and direction between two points.
- Parameters:
lat1 (Union[float, np.ndarray]) – Latitude of starting point(s) in degrees
lon1 (Union[float, np.ndarray]) – Longitude of starting point(s) in degrees
lat2 (Union[float, np.ndarray]) – Latitude of ending point(s) in degrees
lon2 (Union[float, np.ndarray]) – Longitude of ending point(s) in degrees
deltat (Union[float, np.ndarray]) – Time step(s) in hours
- Returns:
Tuple containing: - gamma_h : Forward direction in degrees from North - vmean : Translation speed in km/h - vu : x-component of translation velocity in km/h - vy : y-component of translation velocity in km/h
- Return type:
Tuple[Union[float, np.ndarray], Union[float, np.ndarray], Union[float, np.ndarray], Union[float, np.ndarray]]
Notes
Uses great circle distance calculation to determine distance between points. Translation speed is calculated by dividing distance by time step. Direction components are calculated using trigonometry.
Examples
>>> gamma, v, vx, vy = get_vmean(0, 0, 0, 1, 6) (270.0, 18.55, 18.55, 5.68e-15)
- bluemath_tk.tcs.tracks.historic_track_interpolation(df: DataFrame, dt_comp: float, y0: float = None, x0: float = None, great_circle: bool = True, wind_estimate_on: bool = False, fit: bool = False, interpolation: bool = True, mode: str = 'first', radi_estimate_on: bool = True) Tuple[DataFrame, ndarray] [source]
Interpolate storm track variables to computational time steps.
- Parameters:
df (pd.DataFrame) – Storm track DataFrame with historical data.
dt_comp (float) – Computation time step in minutes.
y0 (float, optional) – Target latitude coordinate. Default is None.
x0 (float, optional) – Target longitude coordinate. Default is None.
great_circle (bool, optional) – Whether to use great circle distances. Default is True.
wind_estimate_on (bool, optional) – Whether to use empirical estimates instead of historical winds. Default is False.
fit (bool, optional) – Whether to estimate winds when wind=0. Default is False.
interpolation (bool, optional) – Whether to interpolate storm variables. Default is True.
mode (str, optional) – Value selection for constant segments (‘first’ or ‘mean’). Default is “first”.
radi_estimate_on (bool, optional) – Whether to estimate missing RMW values. Default is True.
- Returns:
DataFrame with interpolated storm track variables.
Array of interpolated time coordinates.
- Return type:
Tuple[pd.DataFrame, np.ndarray]
Notes
The function: 1. Interpolates track points to match computational time step 2. Estimates missing values using empirical relationships:
Maximum winds from pressure (Pmin-Wmax relationship)
Radius of maximum winds (Knaff et al. 2016)
Can use either linear interpolation or constant segments
Preserves metadata and adds computational parameters
Examples
>>> st, times = historic_track_interpolation(track_data, dt_comp=30) >>> print(f"Interpolated points: {len(st)}") Interpolated points: 144
- bluemath_tk.tcs.tracks.historic_track_preprocessing(xds: Dataset, center: str = 'WMO', forecast_on: bool = False, database_on: bool = False, st_param: bool = False) DataFrame [source]
Preprocess historical storm track data from IBTrACS or forecast sources.
- Parameters:
xds (xr.Dataset) – Historical storm track dataset with storm dimension.
center (str, optional) – IBTrACS center code (e.g., ‘WMO’, ‘TOKYO’). Default is “WMO”.
forecast_on (bool, optional) – Whether track is forecasted (not IBTrACS). Default is False.
database_on (bool, optional) – Whether to keep data only at 0,6,12,18 hours. Default is False.
st_param (bool, optional) – Whether to keep data as original. Default is False.
- Returns:
Preprocessed storm track data with columns: - center : Storm center identifier - basin : Storm basin identifier - dist2land : Distance to nearest land (km) - longitude : Storm longitude (0-360°) - latitude : Storm latitude - move : Forward direction (degrees) - mean_velocity : Translation speed (kt) - pressure : Central pressure (mbar) - maxwinds : Maximum winds (kt, 1-min avg) - rmw : Radius of maximum winds (nmile) - category : Storm category (0-6) - timestep : Time step (hours) - storm_vmean : Mean translation speed (kt)
- Return type:
pd.DataFrame
Notes
Processing steps include: 1. Removing NaT/NaN values from time and pressure data 2. Converting longitudes to [0°-360°] convention 3. Rounding dates to nearest hour 4. Calculating translation speed and direction 5. Converting wind speeds to 1-min average 6. Determining storm category based on pressure
For forecast tracks: - Basin IDs are converted to IBTrACS equivalents - Missing pressures are estimated from wind speeds using fitted coefficients - Southern hemisphere basins are determined by latitude and longitude
Examples
>>> df = historic_track_preprocessing(track_data, center='WMO') >>> print(f"Track duration: {len(df)} time steps") Track duration: 48 >>> print(f"Storm category: {df['category'].iloc[0]}") Storm category: 3
- bluemath_tk.tcs.tracks.ibtracs_fit_pmin_wmax(ibtracs_data: Dataset = None, N: int = 3) Dataset [source]
Generate polynomial fit coefficients for pressure-wind relationship.
- Parameters:
ibtracs_data (xr.Dataset) – The IBTrACS dataset containing storm track data. Must include pressure and wind variables for each center.
N (int, optional) – The order of the polynomial fit. Default is 3.
- Returns:
A dataset containing: - coef_fit : Polynomial coefficients (center, basin, N+1) - pres_data : Pressure data used for fitting - wind_data : Wind data used for fitting
- Return type:
xr.Dataset
Notes
Maximum wind speeds are converted to 1-min average for all RSMC centers
The polynomial fit is of the form: p = a₀ + a₁w + a₂w² + … + aₙwⁿ where p is pressure and w is wind speed
Examples
>>> fit_data = ibtracs_fit_pmin_wmax(ibtracs_data, N=3) >>> print(fit_data.coef_fit.shape) # (n_centers, n_basins, N+1)
- bluemath_tk.tcs.tracks.nakajo_track_preprocessing(xds: Dataset, center: str = 'WMO') DataFrame [source]
Preprocess synthetic storm track data from Nakajo format.
- Parameters:
xds (xr.Dataset) – Synthetic storm track dataset with storm dimension in Nakajo format. Must contain variables for time, longitude (ylon_TC), latitude (ylat_TC), and pressure (yCPRES).
center (str, optional) – IBTrACS center code. Default is “WMO”.
- Returns:
Preprocessed storm track data with columns: - center : Storm center identifier - basin : Storm basin identifier (determined from coordinates) - dist2land : Distance to nearest land (fixed at 100 km) - longitude : Storm longitude (0-360°) - latitude : Storm latitude - move : Forward direction (degrees) - mean_velocity : Translation speed (kt) - pressure : Central pressure (mbar) - maxwinds : Maximum winds (kt, not provided) - rmw : Radius of maximum winds (not provided) - category : Storm category (0-6) - timestep : Time step (hours) - storm_vmean : Mean translation speed (kt)
- Return type:
pd.DataFrame
Notes
The function: 1. Removes NaT (Not a Time) values from time coordinate 2. Removes NaN values from pressure data 3. Converts longitudes to [0°-360°] convention 4. Determines basin based on storm coordinates 5. Rounds dates to nearest hour 6. Calculates translation speed and direction 7. Determines storm category based on pressure
Examples
>>> processed = nakajo_track_preprocessing(nakajo_data, center='WMO') >>> print(f"Track duration: {len(processed)} time steps") Track duration: 48 >>> print(f"Storm category: {processed['category'].iloc[0]}") Storm category: 3
- bluemath_tk.tcs.tracks.resample_storm_6h(storm: Dataset) Dataset [source]
Resample storm data to 6-hour intervals.
- Parameters:
storm (xr.Dataset) – Storm dataset containing time series data with arbitrary time intervals
- Returns:
Resampled storm dataset with 6-hour intervals
- Return type:
xr.Dataset
Notes
This function: 1. Removes NaT (Not a Time) values from time coordinate 2. Removes NaN values from WMO pressure data 3. Resets lon/lat coordinates 4. Resamples all variables to 6-hour intervals using linear interpolation 5. Preserves the original basin identifier
Examples
>>> resampled = resample_storm_6h(storm_data) >>> np.all(np.diff(resampled.time) == np.timedelta64(6, 'h')) True
- bluemath_tk.tcs.tracks.stopmotion_trim_circle(df_seg: DataFrame, plon: float, plat: float, radii: float) DataFrame [source]
Trim storm track segments to those intersecting a circular domain.
- Parameters:
df_seg (pd.DataFrame) – DataFrame containing storm track segments with start/end coordinates.
plon (float) – Longitude of circle center in degrees.
plat (float) – Latitude of circle center in degrees.
radii (float) – Radius of circular domain in degrees.
- Returns:
Trimmed DataFrame containing only segments that intersect the circular domain.
- Return type:
pd.DataFrame
Notes
The function: 1. Calculates geodesic distances from both endpoints of each segment to circle center 2. Takes minimum distance to determine if segment intersects circle 3. Returns continuous time segment containing all intersecting segments 4. Preserves original metadata in the returned DataFrame
Examples
>>> trimmed = stopmotion_trim_circle(segments, -75, 25, 5) >>> print(f"Segments intersecting circle: {len(trimmed)}") Segments intersecting circle: 8
- bluemath_tk.tcs.tracks.track_extent(st: DataFrame, time_input: ndarray, dt_comp: float, time_extent: float = 48.0) Tuple[DataFrame, DataFrame] [source]
Extend storm track data for wave propagation analysis.
- Parameters:
st (pd.DataFrame) – Storm track DataFrame containing time series data.
time_input (np.ndarray) – Array of time coordinates.
dt_comp (float) – Computational time step in minutes.
time_extent (float, optional) – Additional time to extend simulation in hours. Default is 48.
- Returns:
Tuple containing: - st_new : Extended storm track DataFrame. - we : Wave event DataFrame with empty fields for wave parameters.
- Return type:
Tuple[pd.DataFrame, pd.DataFrame]
Notes
The function: 1. Calculates total simulation period (storm + propagation) 2. Creates extended time array with specified time step 3. Fills storm data in initial period 4. Creates empty wave event DataFrame for entire period 5. Preserves metadata and adds computational time step override
Examples
>>> st_ext, wave_evt = track_extent(track_data, times, 30, time_extent=24) >>> print(f"Extended duration: {len(st_ext)} time steps") Extended duration: 96 time steps
- bluemath_tk.tcs.tracks.track_site_parameters(step: float, pmin: float, vmean: float, delta: float, gamma: float, x0: float, y0: float, lon0: float, lon1: float, lat0: float, lat1: float, R: float, date_ini: str, center: str = 'WMO', basin: str = 'SP') DataFrame [source]
Generate parameterized storm track within study area.
- Parameters:
step (float) – Computational time step in minutes.
pmin (float) – Minimum central pressure in millibars.
vmean (float) – Mean translation speed in knots.
delta (float) – Storm track angle parameter in degrees.
gamma (float) – Storm forward direction in degrees.
x0 (float) – Site longitude coordinate in degrees.
y0 (float) – Site latitude coordinate in degrees.
lon0 (float) – Western longitude bound of computational domain.
lon1 (float) – Eastern longitude bound of computational domain.
lat0 (float) – Southern latitude bound of computational domain.
lat1 (float) – Northern latitude bound of computational domain.
R (float) – Radius of influence in degrees.
date_ini (str) – Initial date in format ‘YYYY-MM-DD HH:MM’.
center (str, optional) – IBTrACS center code. Default is “WMO”.
basin (str, optional) – Storm basin identifier. Default is “SP”.
- Returns:
Storm track DataFrame with columns: - lon : Storm longitude coordinates - lat : Storm latitude coordinates - move : Forward direction (gamma) - vf : Translation speed (kt) - vfx : x-component of velocity - vfy : y-component of velocity - pn : Surface pressure (1013 mbar) - p0 : Minimum central pressure - vmax : Maximum winds (kt, 1-min avg) - rmw : Radius of maximum winds (nmile)
- Return type:
pd.DataFrame
Notes
The function: 1. Calculates entrance coordinates at domain boundary 2. Generates track points at computational time steps 3. Estimates maximum winds from pressure using fitted coefficients 4. Estimates radius of maximum winds using Knaff et al. (2016) 5. Preserves metadata including site coordinates and radius
Examples
>>> track = track_site_parameters( ... step=30, pmin=950, vmean=10, delta=45, gamma=270, ... x0=-75, y0=25, lon0=-80, lon1=-70, lat0=20, lat1=30, ... R=5, date_ini='2020-09-01 00:00' ... ) >>> print(f"Track points: {len(track)}") Track points: 96
- bluemath_tk.tcs.tracks.track_triming(st: DataFrame, lat00: float, lon00: float, lat01: float, lon01: float) DataFrame [source]
Trim storm track to specified geographical bounds.
- Parameters:
st (pd.DataFrame) – Storm track DataFrame containing time series data.
lat00 (float) – Southern latitude bound in degrees.
lon00 (float) – Western longitude bound in degrees.
lat01 (float) – Northern latitude bound in degrees.
lon01 (float) – Eastern longitude bound in degrees.
- Returns:
Trimmed storm track containing only points within the specified bounds and preserving continuous time segments.
- Return type:
pd.DataFrame
Notes
The function: 1. Identifies all track points within the specified bounds 2. Finds the earliest and latest times for points within bounds 3. Returns all track points between these times to maintain continuity 4. Preserves original metadata in the returned DataFrame
Examples
>>> trimmed = track_triming(track_data, 20, -80, 30, -60) >>> print(f"Points in bounds: {len(trimmed)}") Points in bounds: 24
- bluemath_tk.tcs.tracks.track_triming_circle(st: DataFrame, plon: float, plat: float, radii: float) DataFrame [source]
Trim storm track to points within a circular domain.
- Parameters:
st (pd.DataFrame) – Storm track DataFrame containing time series data.
plon (float) – Longitude of circle center in degrees.
plat (float) – Latitude of circle center in degrees.
radii (float) – Radius of circular domain in degrees.
- Returns:
Trimmed storm track containing only points within the circular domain and preserving continuous time segments.
- Return type:
pd.DataFrame
Notes
The function: 1. Calculates geodesic distance from each track point to circle center 2. Identifies points within the specified radius 3. Returns continuous time segment containing all points within radius 4. Preserves original metadata in the returned DataFrame
Examples
>>> trimmed = track_triming_circle(track_data, -75, 25, 5) >>> print(f"Points in circle: {len(trimmed)}") Points in circle: 18
- bluemath_tk.tcs.tracks.wind2pres(xds_coef: Dataset, st_wind: ndarray, st_center: str, st_basin: str) ndarray [source]
Convert maximum wind speeds to minimum central pressure using fitted coefficients. As many other functions in this module, this works for IBTrACS data for the moment.
- Parameters:
xds_coef (xr.Dataset) – Dataset containing polynomial fitting coefficients for Pmin-Wmax relationship.
st_wind (np.ndarray) – Storm maximum winds in knots (1-min average).
st_center (str) – Storm center/agency identifier (e.g., ‘WMO’, ‘TOKYO’).
st_basin (str) – Storm basin identifier (e.g., ‘NA’, ‘WP’).
- Returns:
Predicted minimum central pressure values in millibars
- Return type:
np.ndarray
Notes
Uses polynomial regression coefficients to estimate minimum central pressure from maximum wind speeds. The polynomial is of the form: p = a₀ + a₁w + a₂w² + … + aₙwⁿ where p is pressure and w is wind speed.
Examples
>>> pres = wind2pres(coef_dataset, np.array([100]), 'WMO', 'NA') array([955.2])
- bluemath_tk.tcs.tracks.wind2rmw(wmax: ndarray, vmean: ndarray, latitude: ndarray) ndarray [source]
Calculate radius of maximum winds using Knaff et al. (2016) formula.
- Parameters:
wmax (np.ndarray) – Maximum sustained winds in knots
vmean (np.ndarray) – Mean translational speed in knots
latitude (np.ndarray) – Latitude of the storm center in degrees
- Returns:
Radius of maximum winds (RMW) in nautical miles
- Return type:
np.ndarray
Notes
Implements the Knaff et al. (2016) formula for estimating RMW: 1. Subtracts translational speed from observed maximum wind speed 2. Converts 10m wind speed to gradient level wind speed using beta factor 3. Applies empirical formula accounting for wind speed and latitude
References
Knaff, J. A., et al. (2016). “Estimation of Tropical Cyclone Wind Structure Parameters from Satellite Imagery”, Weather and Forecasting.
Examples
>>> rmw = wind2rmw(np.array([100]), np.array([10]), np.array([25])) array([26.51])
bluemath_tk.tcs.vortex module
- bluemath_tk.tcs.vortex.vortex2delft_3D_FM_nc(mesh: Dataset, ds_vortex: Dataset) Dataset [source]
Convert the vortex dataset to a Delft3D FM compatible netCDF forcing file.
- Parameters:
mesh (xarray.Dataset) – The mesh dataset containing the node coordinates.
ds_vortex (xarray.Dataset) – The vortex dataset containing wind speed and pressure data.
path_output (str) – The output path where the netCDF file will be saved.
ds_name (str) – The name of the output netCDF file, default is “forcing_Tonga_vortex.nc”.
forcing_ext (str) – The extension for the forcing file, default is “GreenSurge_GFDcase_wind.ext”.
- Returns:
A dataset containing the interpolated wind speed and pressure data, ready for use in Delft3D FM.
- Return type:
xarray.Dataset
- bluemath_tk.tcs.vortex.vortex_model_grid(storm_track: DataFrame, cg_lon: ndarray, cg_lat: ndarray, coords_mode: str = 'SPHERICAL') Dataset [source]
Generate wind vortex fields from storm track parameters using the Dynamic Holland Model.
- Parameters:
storm_track (pd.DataFrame) – DataFrame containing storm track parameters. - obligatory fields: vfx, vfy, p0, pn, vmax, rmw - for SPHERICAL coordinates: lon, lat - for CARTESIAN coordinates: x, y, latitude
cg_lon (np.ndarray) – Computational grid longitudes.
cg_lat (np.ndarray) – Computational grid latitudes.
cg_lon – Computational grid in longitudes and latitudes.
cg_lat – Computational grid in longitudes and latitudes.
coords_mode (str) – ‘SPHERICAL’ for spherical coordinates (latitude, longitude), ‘CARTESIAN’ for Cartesian coordinates (x, y).
- Returns:
Dataset containing wind speed W, direction Dir (º from north), and pressure p at each grid point.
- Return type:
xarray.Dataset
Examples
>>> storm_track = pd.DataFrame({ ... 'vfx': [10, 12], 'vfy': [5, 6], ... 'p0': [1000, 990], 'pn': [980, 970], ... 'vmax': [50, 55], 'rmw': [30, 35], ... 'lon': [10, 12], 'lat': [20, 22] ... }) >>> cg_lon = np.array([10, 11, 12]) >>> cg_lat = np.array([20, 21, 22]) >>> coords_mode = 'SPHERICAL' >>> result = vortex_model_grid(storm_track, cg_lon, cg_lat, coords_mode) >>> print(result) <xarray.Dataset> Dimensions: (lat: 3, lon: 3, time: 2) Coordinates: * lat (lat) float64 20.0 21.0 22.0 * lon (lon) float64 10.0 11.0 12.0 * time (time) datetime64[ns] 2023-10-01 2023-10-02 Data variables: W (lat, lon, time) float64 0.0 0.0 0.0 ... 0.0 0.0 0.0 Dir (lat, lon, time) float64 0.0 0.0 0.0 ... 0.0 0.0 0.0 p (lat, lon, time) float64 0.0 0.0 0.0 ... 0.0 0.0 0.0
Module contents
Project: BlueMath_tk Sub-Module: tcs Author: GeoOcean Research Group, Universidad de Cantabria Repository: https://github.com/GeoOcean/BlueMath_tk.git Status: Under development (Working)