Spectral Module

Spectral Analysis Module

This module provides comprehensive tools for spectral and harmonic analysis of environmental time series data.

Main Components

Spectral Analysis
  • Lomb-Scargle periodogram for unevenly sampled data

  • Fast Fourier Transform (FFT) for regularly sampled data

Harmonic (Tidal) Analysis from Observations
  • UTide-based harmonic analysis to extract tidal constituents from observations

  • Tidal level reconstruction from constituents

Tidal Predictions from Global Models
  • Configuration and interpolation from global tide models (EOT20, FES2014, TPXO9)

  • High-resolution tidal elevation predictions

  • Simplified workflow function for model-based predictions

Examples

Spectral analysis:
>>> psd = lombscargle_periodogram(data, 'variable', nperiods=5)
Harmonic analysis from observations:
>>> constituents = harmonic_analysis(obs_data, lat=41.173)
>>> reconstructed = reconstruct_tidal_level(df, constituents)
Tidal predictions from models:
>>> import datetime
>>> results = tidal_reconstruction_from_models(
...     latitude=41.173, longitude=-8.720,
...     start_date=datetime.date(2024, 1, 1),
...     end_date=datetime.date(2024, 1, 31)
... )

The spectral module provides tools for spectral and harmonic analysis of time series data, including frequency domain analysis and tidal predictions.

Spectral Analysis Functions

lombscargle_periodogram(data, variable[, ...])

Compute the Lomb-Scargle periodogram for unevenly sampled time series.

fast_fourier_transform(data, variable[, ...])

Compute the Fast Fourier Transform for regularly sampled time series.

Harmonic (Tidal) Analysis

harmonic_analysis(data, lat[, file_name])

Perform harmonic (tidal) analysis on observational time series data.

reconstruct_tidal_level(df, tidalConstituents)

Reconstruct tidal elevations from harmonic constituents.

Tidal Model Configuration

configure_tidal_model(model_name, database_path)

Configure and initialize the tidal model with specified parameters.

Time Series Generation

generate_datetime_series_from_range(...[, ...])

Generate datetime series for tidal prediction using start and end dates.

generate_datetime_series(start_date, ...[, ...])

Generate datetime series for tidal prediction with proper datetime indexing.

environmentaltools.spectral.analysis.generate_time_series(start_date: date, forecast_days: int, resolution_minutes: int = 1) Tuple[ndarray, ndarray][source]

Generate time series for tidal prediction.

Parameters:
  • start_date (datetime.date) – Starting date for the prediction

  • forecast_days (int) – Number of days to forecast

  • resolution_minutes (int, optional) – Time resolution in minutes (default: 1)

Returns:

tide_time: Time array in pyTMD format hours: Time array in hours

Return type:

Tuple[np.ndarray, np.ndarray]

Raises:

ValueError – If input parameters are invalid

Tidal Predictions

environmentaltools.spectral.analysis.interpolate_tidal_constants(longitude: float, latitude: float, model: pyTMD.io.model, method: str = 'spline', extrapolate: bool = True) Tuple[ndarray, ndarray][source]

Interpolate tidal harmonic constants for specified location.

Parameters:
  • longitude (float) – Longitude of the location (degrees East)

  • latitude (float) – Latitude of the location (degrees North)

  • model (pyTMD.io.model) – Configured tidal model instance

  • method (str, optional) – Interpolation method (default: “spline”)

  • extrapolate (bool, optional) – Whether to extrapolate beyond model domain (default: True)

Returns:

amplitude: Tidal constituent amplitudes phase: Tidal constituent phases in degrees

Return type:

Tuple[np.ndarray, np.ndarray]

Raises:

ValueError – If interpolation fails or coordinates are invalid

environmentaltools.spectral.analysis.predict_tidal_elevations(tide_time: ndarray, amplitude: ndarray, phase: ndarray, constituents: list, model: pyTMD.io.model, include_minor: bool = True, unit_factor: float = 100.0) ndarray[source]

Predict tidal elevations using harmonic analysis.

Parameters:
  • tide_time (np.ndarray) – Time array in pyTMD format

  • amplitude (np.ndarray) – Tidal constituent amplitudes

  • phase (np.ndarray) – Tidal constituent phases in degrees

  • constituents (list) – List of tidal constituents

  • model (pyTMD.io.model) – Configured tidal model instance

  • include_minor (bool, optional) – Whether to include minor constituent inference (default: True)

  • unit_factor (float, optional) – Unit conversion factor (default: 100.0 for cm)

Returns:

Predicted tidal elevations in specified units

Return type:

np.ndarray

Raises:

ValueError – If prediction calculation fails

Output

environmentaltools.spectral.analysis.save_results_to_csv(tidal_data: ndarray, datetime_index: DatetimeIndex, output_directory: str, location_name: str, obs_data: ndarray | None = None, decimal_places: int = 3) str[source]

Save tidal prediction results to CSV file with proper datetime formatting.

Parameters:
  • tidal_data (np.ndarray) – Predicted tidal elevations

  • datetime_index (pd.DatetimeIndex) – Datetime index for the data

  • output_directory (str) – Directory where the CSV file will be saved

  • location_name (str) – Name of the location for the filename

  • obs_data (np.ndarray, optional) – Observational data for comparison (if available)

  • decimal_places (int, default=3) – Number of decimal places for elevation values

Returns:

Path to the saved CSV file

Return type:

str

Raises:

ValueError – If saving fails

Tidal Reconstruction Workflow

environmentaltools.spectral.analysis.tidal_reconstruction_from_models(latitude: float, longitude: float, start_date: date, end_date: date, model_name: str = 'EOT20', database_path: str = None, time_resolution_minutes: int = 60, output_directory: str = '.', location_name: str = 'Unknown') Dict[str, Any][source]

Tidal reconstruction and prediction from global tide models.

This function provides a streamlined interface for tidal predictions using global tide models (e.g., EOT20, FES2014, TPXO9). It performs the complete workflow: model configuration, interpolation of tidal constants, prediction of elevations, and CSV export.

Parameters:
  • latitude (float) – Latitude of the location in decimal degrees (-90 to 90).

  • longitude (float) – Longitude of the location in decimal degrees (-180 to 360).

  • start_date (datetime.date) – Starting date for the prediction period.

  • end_date (datetime.date) – Ending date for the prediction period.

  • model_name (str, default='EOT20') – Name of the tidal model to use (e.g., ‘EOT20’, ‘FES2014’, ‘TPXO9’).

  • database_path (str, optional) – Path to the tidal model database directory. If None, uses current directory.

  • time_resolution_minutes (int, default=60) – Time resolution for predictions in minutes (e.g., 60 for hourly).

  • output_directory (str, default='.') – Directory where output files (CSV and plots) will be saved.

  • location_name (str, default='Unknown') – Name of the location for labeling outputs.

Returns:

Dictionary containing:

  • ’predictions’ : np.ndarray - Tidal elevation predictions

  • ’datetime_index’ : pd.DatetimeIndex - Time stamps for predictions

  • ’location’ : tuple - (latitude, longitude)

  • ’csv_file’ : str - Path to saved CSV file

  • ’plot_file’ : str - Path to saved plot

Return type:

dict

Examples

>>> import datetime
>>> results = tidal_reconstruction_from_models(
...     latitude=41.173,
...     longitude=-8.720,
...     start_date=datetime.date(2024, 1, 1),
...     end_date=datetime.date(2024, 1, 31),
...     location_name='Porto'
... )

Notes

This function is a simplified alternative to using complex configuration. For harmonic analysis from observational data, use harmonic_analysis() and reconstruct_tidal_level().