# -*- coding: utf-8 -*-
"""
Created on Mon Nov  2 08:58:43 2026

@author: chuffard
"""

#currents
#%% defs and libraries
import requests
import pandas as pd
from datetime import datetime
import calendar

def get_noaa_tides(start_date, end_date):

    station = '9413450'

    start = pd.to_datetime(start_date)
    end = pd.to_datetime(end_date)

    all_data = []

    # Split requests into monthly chunks
    current = start

    while current <= end:

        month_end = min(
            current + pd.offsets.MonthEnd(0),
            end
        )

        params = {
            'begin_date': current.strftime('%Y%m%d'),
            'end_date': month_end.strftime('%Y%m%d'),
            'station': station,
            'product': 'predictions',
            'datum': 'MSL',
            'time_zone': 'gmt',
            'units': 'metric',
            'interval': '6',
            'format': 'json'
        }

        url = (
            'https://api.tidesandcurrents.noaa.gov/'
            'api/prod/datagetter'
        )

        response = requests.get(url, params=params)
        response.raise_for_status()

        result = response.json()

        if 'predictions' not in result:
            raise ValueError(result)

        df_temp = pd.DataFrame(result['predictions'])

        all_data.append(df_temp)

        current = month_end + pd.Timedelta(days=1)

    tides = pd.concat(all_data, ignore_index=True)

    tides['datetime'] = pd.to_datetime(
        tides['t'],
        utc=True
    )

    tides['tide_height'] = pd.to_numeric(tides['v'])

    tides = tides[['datetime', 'tide_height']]

    return tides


#%% bring in MARS tides
MARS_currents = pd.read_csv('W:/Analyses/compare currents MARS_Monterey9413450/MARS2024SES.csv')

MARS_currents['datetimeLocal'] = pd.to_datetime(
    MARS_currents['ISO 8601 Time'],
    utc=False
)


MARS_currents['datetime'] = (MARS_currents['datetimeLocal']
              .dt.tz_localize('America/Los_Angeles')
              .dt.tz_convert('UTC'))

marsmin= MARS_currents['datetime'].min()

marsmax= MARS_currents['datetime'].max()

#%% bring in NOAA tides
# Example
tides = get_noaa_tides(
    marsmin,
    marsmax
)



# Merge current speed with tidal predictions
df = pd.merge_asof(
    MARS_currents.sort_values('datetime'),
    tides.sort_values('datetime'),
    on='datetime',
    direction='nearest',
    tolerance=pd.Timedelta('6min')
)

df = df.dropna()


df['change_tide_height'] = df['tide_height'].diff()

#%% analysis
df = df.sort_values('datetime')

dt_hours = (
    df['datetime'].diff().dt.total_seconds() / 3600
)

df['tide_rate'] = (
    df['tide_height'].diff() / dt_hours
)

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import pearsonr

def calculate_ccf(x, y, max_lag_hours=24):

    x = np.asarray(x)
    y = np.asarray(y)

    # Standardize
    x = (x - np.nanmean(x)) / np.nanstd(x)
    y = (y - np.nanmean(y)) / np.nanstd(y)

    max_lag = int(max_lag_hours)

    lags = np.arange(-max_lag, max_lag + 1)

    correlations = []

    for lag in lags:

        if lag < 0:
            a = x[:lag]
            b = y[-lag:]

        elif lag > 0:
            a = x[lag:]
            b = y[:-lag]

        else:
            a = x
            b = y

        valid = np.isfinite(a) & np.isfinite(b)

        if valid.sum() > 2:
            r, _ = pearsonr(a[valid], b[valid])
        else:
            r = np.nan

        correlations.append(r)

    results = pd.DataFrame({
        'lag_hours': lags,
        'correlation': correlations
    })

    return results

df.columns
# Index(['ISO 8601 Time', 'Speed (cm/s)', 'Heading (degrees)',
#        'Velocity-N (cm/s)', 'Velocity-E (cm/s)', 'datetime', 'datetimeUTC',
#        'datetimeLocal', 'tide_height', 'change_tide_height', 'tide_rate'],
#       dtype='object')


ccf = calculate_ccf(
    df['Speed (cm/s)'],
    df['tide_rate'],
    max_lag_hours=24
)

plt.figure(figsize=(8, 4))

plt.plot(
    ccf['lag_hours'],
    ccf['correlation'],
    marker='o'
)

plt.axhline(0, color='black', linewidth=0.8)
plt.axvline(0, color='black', linestyle='--')

plt.xlabel('Lag (hours)')
plt.ylabel('Correlation')
plt.title('Current Speed vs. Tidal Rate')

plt.tight_layout()
plt.show()




#%% try 2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

current_col = 'Speed (cm/s)'
time_col = 'datetime'
tide_col = 'tide_height'


def lagged_correlation(df, time_col, current_col, tide_col,
                       freq='1h', max_lag='24h'):

    # Set timestamp as index
    data = df[[time_col, current_col, tide_col]].copy()
    data[time_col] = pd.to_datetime(data[time_col])
    data = data.set_index(time_col).sort_index()

    # Resample both variables to a regular time interval
    data = data[[current_col, tide_col]].resample(freq).mean()

    current = data[current_col]
    tide = data[tide_col]

    # Convert maximum lag into number of time steps
    interval = pd.Timedelta(freq)
    max_steps = int(pd.Timedelta(max_lag) / interval)

    # Calculate correlation at each positive and negative lag
    results = []

    for lag in range(-max_steps, max_steps + 1):

        # Positive lag: current follows tide
        # Negative lag: current leads tide
        paired = pd.concat(
            [current, tide.shift(lag)], axis=1
        ).dropna()

        r = paired.iloc[:, 0].corr(paired.iloc[:, 1])

        results.append({
            'lag_steps': lag,
            'lag_hours': lag * interval.total_seconds() / 3600,
            'correlation': r,
            'n': len(paired)
        })

    results = pd.DataFrame(results)

    # Find lag with strongest absolute correlation
    best = results.loc[
        results['correlation'].abs().idxmax()
    ]

    print('\nStrongest correlation:')
    print(f"Lag: {best['lag_hours']:.2f} hours")
    print(f"Correlation (r): {best['correlation']:.3f}")
    print(f"Number of paired observations: {best['n']}")

    if best['lag_hours'] > 0:
        print("Current speed follows tidal height.")
    elif best['lag_hours'] < 0:
        print("Current speed leads tidal height.")
    else:
        print("Current speed and tidal height are best correlated at zero lag.")

    # Plot correlation versus lag
    plt.figure(figsize=(8, 4))
    plt.plot(results['lag_hours'], results['correlation'],
             marker='o', markersize=3)

    plt.axhline(0, color='black', linewidth=0.8)
    plt.axvline(0, color='black', linestyle='--', linewidth=0.8)
    plt.axvline(best['lag_hours'], color='red',
                linestyle='--', label='Strongest correlation')

    plt.xlabel('Lag (hours)')
    plt.ylabel('Pearson correlation (r)')
    plt.title('Cross-correlation: Current speed vs. tidal height')
    plt.legend()
    plt.tight_layout()
    plt.show()

    return results, best

results, best = lagged_correlation(
    df,
    time_col='datetime',
    current_col=current_col,
    tide_col='tide_height',
    freq='1h',
    max_lag='24h'
)

#%% other plots

import pandas as pd
import matplotlib.pyplot as plt

df['datetime'] = pd.to_datetime(df['datetime'])
df = df.sort_values('datetime')

plt.figure(figsize=(12, 4))
plt.plot(df['datetime'], df['Speed (cm/s)'])
plt.xlabel('Date')
plt.ylabel('Current speed')
plt.title('Current speed time series')
plt.tight_layout()
plt.show()

#%%
#DOMINANT FREQUENCIES
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import periodogram

# Sampling interval in hours
interval_hours = 1

x = df['Speed (cm/s)'].dropna().values

# Calculate periodogram
frequencies, power = periodogram(
    x,
    fs=1/interval_hours,
    detrend='linear'
)

# Convert frequency to period (hours)
periods = 1 / frequencies[1:]
power = power[1:]

plt.figure(figsize=(10, 4))
plt.plot(periods, power)

plt.axvline(12.42, color='red', linestyle='--',
            label='M2: 12.42 hours')
plt.axvline(12.00, color='orange', linestyle='--',
            label='S2: 12.00 hours')
plt.axvline(23.93, color='green', linestyle='--',
            label='K1: 23.93 hours')
plt.axvline(25.82, color='purple', linestyle='--',
            label='O1: 25.82 hours')

plt.xlim(5, 30)
plt.xlabel('Period (hours)')
plt.ylabel('Spectral power')
plt.title('Periodogram of current speed')
plt.legend()
plt.tight_layout()
plt.show()

#%%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from scipy.signal import periodogram, coherence, csd
from scipy.stats import linregress
import statsmodels.api as sm
from statsmodels.tsa.stattools import acf

# --------------------------------------------------
# USER SETTINGS
# --------------------------------------------------

TIME_COL = 'datetime'             # Change to your timestamp column
CURRENT_COL = 'Speed (cm/s)'      # Your current-speed column
TIDE_COL = 'tide_height'         # Change to your tidal-height column

FREQ = '1h'                       # Sampling interval
MAX_LAG_HOURS = 24                # Maximum lag for cross-correlation

# --------------------------------------------------
# PREPARE DATA
# --------------------------------------------------

data = df[[TIME_COL, CURRENT_COL, TIDE_COL]].copy()

data[TIME_COL] = pd.to_datetime(data[TIME_COL])
data = data.sort_values(TIME_COL).set_index(TIME_COL)

# Convert to numeric in case columns were imported as strings
data[CURRENT_COL] = pd.to_numeric(data[CURRENT_COL], errors='coerce')
data[TIDE_COL] = pd.to_numeric(data[TIDE_COL], errors='coerce')

# Resample to a regular time interval
data = data.resample(FREQ).mean()

# Interpolate only short gaps (up to 2 consecutive missing observations)
data[[CURRENT_COL, TIDE_COL]] = (
    data[[CURRENT_COL, TIDE_COL]]
    .interpolate(method='time', limit=2, limit_area='inside')
)

# Use the same complete observations for both variables
data = data.dropna(subset=[CURRENT_COL, TIDE_COL])

# Sampling interval in hours
dt_hours = pd.Timedelta(FREQ).total_seconds() / 3600

current = data[CURRENT_COL]
tide = data[TIDE_COL]

print('Number of observations:', len(data))
print('Start:', data.index.min())
print('End:', data.index.max())
print('Sampling interval:', dt_hours, 'hours')

fig, ax1 = plt.subplots(figsize=(12, 4))

ax1.plot(data.index, current, color='tab:blue')
ax1.set_ylabel('Current speed (cm/s)', color='tab:blue')
ax1.set_xlabel('Date')

ax2 = ax1.twinx()
ax2.plot(data.index, tide, color='tab:orange', alpha=0.7)
ax2.set_ylabel('Tidal height', color='tab:orange')

plt.title('Current speed and tidal height')
plt.tight_layout()
plt.show()

max_lags = int(72 / dt_hours)

acf_values = acf(current, nlags=max_lags, fft=True)
lags_hours = np.arange(len(acf_values)) * dt_hours

plt.figure(figsize=(10, 4))
plt.plot(lags_hours, acf_values, marker='o', markersize=3)

plt.axhline(0, color='black', linewidth=0.8)

# Reference tidal periods
for period, label in [
    (12.42, 'M2'),
    (12.00, 'S2'),
    (23.93, 'K1'),
    (25.82, 'O1')
]:
    plt.axvline(period, linestyle='--', alpha=0.7, label=label)

plt.xlabel('Lag (hours)')
plt.ylabel('Autocorrelation')
plt.title('Autocorrelation of current speed')
plt.legend()
plt.tight_layout()
plt.show()




# Time in hours since the beginning of the dataset
t_hours = (
    (data.index - data.index[0]).total_seconds() / 3600
).to_numpy()

# Tidal constituent periods in hours
constituents = {
    'M2': 12.4206,
    'S2': 12.0000,
    'K1': 23.9345,
    'O1': 25.8193
}

# Build harmonic regression model
X = pd.DataFrame(index=data.index)
X['Intercept'] = 1

for name, period in constituents.items():
    frequency = 1 / period
    X[name + '_sin'] = np.sin(2 * np.pi * frequency * t_hours)
    X[name + '_cos'] = np.cos(2 * np.pi * frequency * t_hours)

model_harmonic = sm.OLS(current.values, X.values).fit()

# Extract amplitudes and phases
harmonic_results = []

for name, period in constituents.items():

    sin_coef = model_harmonic.params[
        X.columns.get_loc(name + '_sin')
    ]

    cos_coef = model_harmonic.params[
        X.columns.get_loc(name + '_cos')
    ]

    amplitude = np.sqrt(sin_coef**2 + cos_coef**2)

    # Phase expressed as hours relative to the start of the record
    phase_radians = np.arctan2(cos_coef, sin_coef)
    phase_hours = (phase_radians / (2 * np.pi)) * period
    phase_hours = phase_hours % period

    harmonic_results.append({
        'Constituent': name,
        'Period (hours)': period,
        'Amplitude (cm/s)': amplitude,
        'Phase (hours)': phase_hours
    })

harmonic_results = pd.DataFrame(harmonic_results)

print(harmonic_results.round(3))

# Plot observed and fitted current speed
fitted = model_harmonic.predict(X.values)

plt.figure(figsize=(12, 4))
plt.plot(data.index, current, label='Observed', alpha=0.6)
plt.plot(data.index, fitted, label='Harmonic fit', linewidth=2)

plt.xlabel('Date')
plt.ylabel('Current speed (cm/s)')
plt.title('Harmonic regression of current speed')
plt.legend()
plt.tight_layout()
plt.show()

print('Harmonic model R-squared:', round(model_harmonic.rsquared, 3))



max_steps = int(MAX_LAG_HOURS / dt_hours)

ccf_results = []

for lag in range(-max_steps, max_steps + 1):

    # Positive lag: current follows tide
    paired = pd.concat(
        [current, tide.shift(lag)],
        axis=1
    ).dropna()

    r = paired.iloc[:, 0].corr(paired.iloc[:, 1])

    ccf_results.append({
        'Lag (hours)': lag * dt_hours,
        'Correlation': r,
        'N': len(paired)
    })

ccf_results = pd.DataFrame(ccf_results)

best_ccf = ccf_results.loc[
    ccf_results['Correlation'].abs().idxmax()
]

print('Strongest cross-correlation:')
print(best_ccf)

plt.figure(figsize=(10, 4))

plt.plot(
    ccf_results['Lag (hours)'],
    ccf_results['Correlation'],
    marker='o',
    markersize=3
)

plt.axhline(0, color='black', linewidth=0.8)
plt.axvline(0, color='black', linestyle='--')
plt.axvline(
    best_ccf['Lag (hours)'],
    color='red',
    linestyle='--',
    label='Strongest correlation'
)

plt.xlabel('Lag (hours)')
plt.ylabel('Pearson correlation (r)')
plt.title('Cross-correlation: Current speed vs. tidal height')
plt.legend()
plt.tight_layout()
plt.show()

from scipy.signal import coherence, csd

# Calculate coherence
frequencies, coh = coherence(
    tide.values,
    current.values,
    fs=1 / dt_hours,
    nperseg=min(256, len(data))
)

# Calculate cross-spectral density
frequencies_csd, Pxy = csd(
    tide.values,
    current.values,
    fs=1 / dt_hours,
    nperseg=min(256, len(data))
)

# Phase of current relative to tide
phase = np.angle(Pxy)

# Convert phase to time lag
# Positive lag means current follows tide
valid = frequencies > 0

phase_lag_hours = (
    -phase[valid] / (2 * np.pi * frequencies[valid])
)

period_hours = 1 / frequencies[valid]

# Plot coherence against period
plt.figure(figsize=(10, 4))

plt.plot(
    period_hours,
    coh[valid]
)

for period, label in [
    (12.42, 'M2'),
    (12.00, 'S2'),
    (23.93, 'K1'),
    (25.82, 'O1')
]:
    plt.axvline(period, linestyle='--', alpha=0.7, label=label)

plt.xlim(5, 30)
plt.ylim(0, 1)
plt.xlabel('Period (hours)')
plt.ylabel('Coherence')
plt.title('Cross-spectral coherence')
plt.legend()
plt.tight_layout()
plt.show()

# Plot phase-derived lag
plt.figure(figsize=(10, 4))

plt.plot(period_hours, phase_lag_hours, marker='o', markersize=3)
plt.axhline(0, color='black', linewidth=0.8)

plt.xlim(5, 30)
plt.xlabel('Period (hours)')
plt.ylabel('Phase-derived lag (hours)')
plt.title('Phase difference between tide and current speed')
plt.tight_layout()
plt.show()




# Calculate rate of change of tidal height
data['Tide_rate'] = tide.diff() / dt_hours

# Classify tidal phase
data['Tide_phase'] = np.where(
    data['Tide_rate'] > 0,
    'Rising',
    'Falling'
)

# Exclude observations with zero or undefined tide rate
phase_data = data[
    data['Tide_rate'].notna() &
    (data['Tide_rate'] != 0)
].copy()

# Summary statistics
print(
    phase_data.groupby('Tide_phase')[CURRENT_COL]
    .agg(['count', 'mean', 'median', 'std'])
)

# Scatterplot: current speed versus tidal height
plt.figure(figsize=(7, 5))

for phase, group in phase_data.groupby('Tide_phase'):
    plt.scatter(
        group[TIDE_COL],
        group[CURRENT_COL],
        alpha=0.5,
        label=phase
    )

plt.xlabel('Tidal height')
plt.ylabel('Current speed (cm/s)')
plt.title('Current speed versus tidal height by tidal phase')
plt.legend()
plt.tight_layout()
plt.show()

# Scatterplot: current speed versus rate of tide change
plt.figure(figsize=(7, 5))

plt.scatter(
    phase_data['Tide_rate'],
    phase_data[CURRENT_COL],
    alpha=0.5
)

plt.xlabel('Rate of change of tidal height')
plt.ylabel('Current speed (cm/s)')
plt.title('Current speed versus rate of tidal change')
plt.tight_layout()
plt.show()




import matplotlib.pyplot as plt
import numpy as np

colors = np.where(df['tide_rate'] > 0, 'steelblue', 'darkorange')

plt.figure(figsize=(6, 5))

plt.scatter(
    df['tide_height'],
    df['Speed (cm/s)'],
    c=colors,
    alpha=0.2,
    s=20
)

plt.axhline(0, color='black', linewidth=0.8)
plt.legend()
plt.xlabel('tide height')
plt.ylabel('Speed (cm/s)')
plt.tight_layout()
plt.show()



import matplotlib.pyplot as plt
import numpy as np

colors = np.where(df['tide_rate'] > 0, 'steelblue', 'darkorange')

plt.figure(figsize=(6, 5))

plt.scatter(
    df['change_tide_height'],
    df['Speed (cm/s)'],
    c=colors,
    alpha=0.2,
    s=20
)

plt.axhline(0, color='black', linewidth=0.8)
plt.legend()
plt.xlabel('change_tide_height')
plt.ylabel('Speed (cm/s)')
plt.tight_layout()
plt.show()









window_hours = 72
window_steps = int(window_hours / dt_hours)

rolling_results = []

for i in range(window_steps, len(data) + 1):

    subset = data.iloc[i - window_steps:i]

    x = subset[CURRENT_COL]
    y = subset[TIDE_COL]

    correlations = []

    for lag in range(-max_steps, max_steps + 1):

        paired = pd.concat(
            [x, y.shift(lag)],
            axis=1
        ).dropna()

        r = paired.iloc[:, 0].corr(paired.iloc[:, 1])
        correlations.append(r)

    correlations = np.array(correlations)

    if np.all(np.isnan(correlations)):
        continue

    best_index = np.nanargmax(np.abs(correlations))

    rolling_results.append({
        'Date': subset.index[-1],
        'Best lag (hours)': (
            best_index - max_steps
        ) * dt_hours,
        'Best correlation': correlations[best_index]
    })

rolling_results = pd.DataFrame(rolling_results).set_index('Date')

fig, ax1 = plt.subplots(figsize=(12, 5))

ax1.plot(
    rolling_results.index,
    rolling_results['Best correlation'],
    color='tab:blue'
)
ax1.set_ylabel('Strongest correlation', color='tab:blue')
ax1.axhline(0, color='black', linewidth=0.8)

ax2 = ax1.twinx()
ax2.plot(
    rolling_results.index,
    rolling_results['Best lag (hours)'],
    color='tab:orange'
)
ax2.set_ylabel('Lag (hours)', color='tab:orange')

plt.title('Moving-window cross-correlation (3-day windows)')
plt.tight_layout()
plt.show()


# Create predictors
regression_data = data.copy()

regression_data['Tide_rate'] = (
    regression_data[TIDE_COL].diff() / dt_hours
)

regression_data = regression_data.dropna()

X = regression_data[[TIDE_COL, 'Tide_rate']]
X = sm.add_constant(X)

y = regression_data[CURRENT_COL]

regression_model = sm.OLS(y, X).fit()

print(regression_model.summary())





import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.nonparametric.smoothers_lowess import lowess

# Settings
TIME_COL = 'datetime'
TIDE_COL = 'tide_height'
CURRENT_COL = 'Speed (cm/s)'
LOESS_FRAC = 0.3

# Prepare data
plot_data = df[[TIME_COL, TIDE_COL, CURRENT_COL]].copy()

plot_data[TIME_COL] = pd.to_datetime(plot_data[TIME_COL])
plot_data = plot_data.sort_values(TIME_COL)

plot_data[TIDE_COL] = pd.to_numeric(plot_data[TIDE_COL], errors='coerce')
plot_data[CURRENT_COL] = pd.to_numeric(plot_data[CURRENT_COL], errors='coerce')

plot_data = plot_data.dropna()

# Classify rising and falling tide
plot_data['Tide_rate'] = (
    plot_data[TIDE_COL].diff() /
    plot_data[TIME_COL].diff().dt.total_seconds()
)

plot_data['Tide_phase'] = np.where(
    plot_data['Tide_rate'] > 0, 'Rising', 'Falling'
)

plot_data = plot_data[plot_data['Tide_rate'] != 0].dropna()

# Plot
plt.figure(figsize=(7, 5))

colors = {
    'Rising': 'steelblue',
    'Falling': 'darkorange'
}

for phase in ['Rising', 'Falling']:

    subset = plot_data[plot_data['Tide_phase'] == phase]

    x = subset[TIDE_COL].values
    y = subset[CURRENT_COL].values

    # Sort by tidal height
    idx = np.argsort(x)
    x = x[idx]
    y = y[idx]

    # LOESS fit
    fit = lowess(
        y, x,
        frac=LOESS_FRAC,
        return_sorted=True
    )

    x_fit = fit[:, 0]
    y_fit = fit[:, 1]

    # Approximate confidence ribbon using residual standard error
    y_pred = np.interp(x, x_fit, y_fit)
    residuals = y - y_pred
    se = np.std(residuals, ddof=1)

    plt.scatter(
        x, y,
        color=colors[phase],
        alpha=0.12,
        s=10
    )

    plt.plot(
        x_fit, y_fit,
        color=colors[phase],
        linewidth=2,
        label=phase
    )

    plt.fill_between(
        x_fit,
        y_fit - 1.96 * se,
        y_fit + 1.96 * se,
        color=colors[phase],
        alpha=0.2
    )

plt.xlabel('Tidal height')
plt.ylabel('Current speed (cm/s)')
plt.title('Current speed versus tidal height')
plt.legend(title='Tidal phase')
plt.tight_layout()
plt.show()