vtools.functions package

Submodules

vtools.functions.blend module

ts_blend(series, names=None, blend_length=None)[source]

Blend multiple time series together, using higher priority where possible, but ramping in lower-priority data near gaps in the higher-priority series.

Parameters:
seriessequence of pandas.Series or pandas.DataFrame

Higher priority first. All indexes must be DatetimeIndex or PeriodIndex.

namesNone, str, or iterable of str, optional

Same semantics as ts_merge / ts_splice.

blend_lengthint or Timedelta-like, optional

Controls the width of the blending zone around gaps in the higher-priority series.

  • If an integer N is given, then up to N samples on each side of any gap in the higher-priority series will be blended using a kernel based on the distance to the gap edge (in sample counts).

  • If a Timedelta-like value (e.g. ‘2h’, pd.Timedelta(‘30min’)), then blending is performed in time units on the regular working index.

If None or non-positive, ts_blend behaves like a hard-priority merge with no soft shoulder blending.

Blending happens only on the shoulders of gaps, where both series have data. At distance d from the nearest gap the lower-priority series gets weight (L - d) / L (L = blend_length), so the weight ramps linearly from 0 at d >= L toward 1, which is reached in the gap itself. For example, with blend_length=4 the shoulder weights are 0.75, 0.5, 0.25 and 0 at distances 1 to 4 samples.

Returns:
pandas.Series or pandas.DataFrame

A time series combining all inputs, with soft transitions near gaps.

Raises:
ValueError

If the inputs do not have a common regular frequency.

vtools.functions.climatology module

apply_climatology(climate, index=None, start=None, end=None, freq=None, substep_interp='fill', **kwargs)[source]

Apply hourly, daily or monthly climatology to a new index or generate index from start/end/freq

Parameters:
climateDataFrame or Series

DataFrame with integer index representing month of year (Jan=1), day of year or hour of year. Must be of size 12, 365, 366 or 8760. Day 366 will be inferred from day 365 value. An hourly (8760) climatology uses a 365-day calendar: Feb 29 takes the Feb 28 values. The values are treated as averages over their period (month, day or hour beginning at the label).

indexpandas.DatetimeIndex, optional

Locations to be inferred. If not provided, must specify start, end, and freq.

startstr or datetime-like, optional

Start date for generating index (used if index is None).

endstr or datetime-like, optional

End date for generating index (used if index is None).

freqstr, optional

Frequency string for generating index (used if index is None). E.g., ‘D’ for daily, ‘M’ for monthly.

substep_interp{“fill”, “linear”, “rhistinterp”}, default “fill”

How values are obtained at times within a climatology period (e.g. a 15min index with a daily climatology).

  • “fill”: each timestamp takes the value of the month, day or hour containing it, giving a step function.

  • “linear”: linear interpolation in time between the middles of the periods.

  • “rhistinterp”: rational histospline (see vtools.rhistinterp()) that preserves the period averages. Requires a climatology without missing values.

**kwargs

Only for substep_interp="rhistinterp"; passed to vtools.rhistinterp(). Notably p, the spline tension (default 2.0; larger values are closer to monotonic and strictly positive), and lowbound, a lower bound for the interpolated values.

Returns:
DataFrame or Series

Values extracted from climatology for the month, day or hour at the specified index.

Notes

  • If index is not provided, start, end, and freq must be specified to generate a DatetimeIndex using pandas.date_range.

climatology(ts, freq, nsmooth=None, nday=None)[source]

“ Create a climatology on the columns of ts

Parameters:
ts: DataFrame or Series
DataStructure to be analyzed. Must have a length of at least 2*freq
freq: period [“hour”,”day”,”month”]
Period over which the climatology is analyzed. “hour” produces one value for each hour of
a 365-day year (8760 values); Feb 29 is ignored. Data are first averaged into hourly bins
labeled at the start of the hour, so ts must be hourly or finer.
nsmooth: int

For “day” and “month”: window size (number of values) of pre-smoothing of the input. This may not make sense for series that are not approximately regular. An odd number is usually best. For “hour”: odd window size in hours (e.g. 3 for +/- 1 hour) applied to the hourly climatology after averaging across years, wrapping around the end of the year.

nday: int

Only for “hour”. Odd number of days (e.g. 5 for +/- 2 days) over which the same hour of day is pooled to strengthen the estimate, wrapping around the end of the year. None means no pooling across days.

Returns:

out: DataFrame or Series Data structure of the same type as ts, with Integer index representing month (Jan=1), day of year (1:365) or hour of year (1:8760, Jan 1 00:00 = 1). Hourly values with no data in their window are NaN.

climatology_quantiles(ts, min_day_year, max_day_year, window_width, quantiles=[0.05, 0.25, 0.5, 0.75, 0.95])[source]

“ Create windowed quantiles across years on a time series

Parameters:
ts: DataFrame or Series
DataStructure to be analyzed.
min_day_year: int
Minimum Julian day to be considered
freq: period [“day”,”month”]
Maximum Julian day to be considered
window_width: int
Number of days to include, including the central day and days on each side. So for instance window_width=15 would span the central date and 7 days on each side
quantiles: array-like

quantiles requested

Returns:

out: DataFrame or Series Data structure with Julian day as the index and quantiles as columns.

vtools.functions.coarsen module

ts_coarsen(df: DataFrame, *, grid: str | None = '1min', qwidth: float | None = None, use_original_vals: bool = True, heartbeat_freq: str | None = '120min', preserve_vals: Sequence[float] = (), preserve_eps: float | None = None, preserve_enter_dwell: str = '2min', preserve_exit_dwell: str = '30s', hyst: float = 1.0) → DataFrame[source]

Coarsen a multivariate time series by gridding, preserving semantic states, hysteretic quantization, and thinning.

Parameters:
dfpd.DataFrame

Input time series with DatetimeIndex and numeric columns.

gridstr or None

Pandas resample frequency. If None, operate on original timestamps. The grid roughly defines the output resolution. It will be refined based on preservation and coarasened based on quantization, but loss due to the grid is not recoverable.

qwidthfloat or None

Post-grid quantization width. None disables quantization.

use_original_valsbool

If True, emit raw gridded values at kept timestamps after gridding; otherwise emit quantized values used for change detection. Setting this to False will give a more “digitize” feel. Recomment True for most use cases, and required with gridding, but False can be useful for debugging or if you want to quantize without gridding.

heartbeat_freqstr or None

Periodic keep-alive frequency preventing long gaps. None disables heartbeat.

preserve_valssequence of float

Values (e.g. 0.0, 1.0) defining semantic states to preserve, kind of like a combination of snapping and preservation of entry/exit points. If a preserve value is within preserve_eps of the raw value, it is considered to be in that state for preservation purposes.

preserve_epsfloat or None

Tolerance around preserve values. Defaults to 0.5*qwidth or 0.0.

preserve_enter_dwellstr

Minimum dwell time to enter a preserved state.

preserve_exit_dwellstr

Maximum gap to bridge between preserved state segments.

hystfloat

Hysteresis factor for quantization (multiplier on qwidth). Default of 0.5 is intermediate – quantization only occurs if value changes by more than half qwidth. hyst > 1, as it will give a choppy feel. Low is fine and 0 disbles.

Returns:
pd.DataFrame

Coarsened time series with preserved semantic information.

vtools.functions.colname_align module

Column naming alignment utilities for time series composition functions.

This module provides decorators that standardize how functions like ts_merge, ts_splice, and transition_ts handle their names argument and enforce column consistency across multiple time series inputs.

Main features

  • Column consistency enforcement: Ensures that when names=None (default), all input DataFrames share identical columns. This prevents accidental creation of staggered or mismatched columns.

  • Centralized naming behavior: Applies uniform handling of names values:

    • None — require identical columns across all inputs and keep them.

    • str — require univariate inputs (single column each); output is a single-column DataFrame (or Series if all inputs were Series) with this name.

    • Iterable[str] — treated as a column selector: these columns are selected (and ordered) from the final output and must exist in every input.

  • Support for both list-style and pairwise APIs: Works for functions that accept a sequence of time series (like ts_merge/ts_splice) or two explicit series arguments (like transition_ts).

Usage pattern

Decorate your functions as follows:

@columns_aligned(mode="same_set")
@names_aligned(seq_arg=0, pre_rename=True)
def ts_splice(series, names=None, ...):
    ...

@columns_aligned(mode="same_set")
@names_aligned_pair(ts0_kw="ts0", ts1_kw="ts1")
def transition_ts(ts0, ts1, names=None, ...):
    ...

This ensures consistent semantics for all multi-series combination tools.

align_inputs_pair_strict(ts0_kw='ts0', ts1_kw='ts1', names_kw='names')[source]
align_inputs_strict(seq_arg=0, names_kw='names')[source]
align_names(result, names)[source]

vtools.functions.envelope module

generate_simplified_mixed_tide(start_time='2022-01-01', ndays=40, freq='15min', A_M2=1.0, A_K1=0.5, A_O1=0.5, phase_D1=1.570795, noise_amplitude=0.08, return_components=False)[source]

Generate a simplified synthetic mixed semidiurnal/diurnal tide with explicit O1 and K1.

Parameters:
start_timestr

Start time for the series.

ndaysint

Number of days.

freqstr

Sampling interval.

A_M2float

Amplitude of M2.

A_K1float

Amplitude of K1.

A_O1float

Amplitude of O1.

phase_D1float

Common phase shift for O1 and K1.

return_componentsbool

Whether to return individual components.

Returns:
pd.Series or pd.DataFrame

Combined tide or components with time index.

tidal_envelope(series, smoothing_window_hours=2.5, n_good=3, peak_prominence=0.05, saliency_window_hours=14, max_anchor_gap_hours=36, envelope_type='outer')[source]

Compute the tidal envelope (high and low) of a time series using smoothing, extrema detection, and interpolation. This function processes a time series to extract its tidal envelope by smoothing the data, identifying significant peaks and troughs, filtering out unreliable extrema, selecting salient extrema within a specified window, and interpolating between anchor points to generate continuous envelope curves.

Parameters:
seriespandas.Series

Time-indexed series of water levels or similar data.

smoothing_window_hoursfloat, optional

Window size in hours for smoothing the input series (default is 2.5).

n_goodint, optional

Minimum number of good points required for an extremum to be considered valid (default is 3).

peak_prominencefloat, optional

Minimum prominence of peaks/troughs to be considered as extrema (default is 0.05).

saliency_window_hoursfloat, optional

Window size in hours for selecting salient extrema (default is 14).

max_anchor_gap_hoursfloat, optional

Maximum allowed gap in hours between anchor points for interpolation (default is 36).

envelope_typestr, optional

Type of envelope to compute, e.g., “outer” (default is “outer”).

Returns:
env_highpandas.Series

Interpolated high (upper) envelope of the input series.

env_lowpandas.Series

Interpolated low (lower) envelope of the input series.

anchor_highspandas.DataFrame

DataFrame of selected anchor points for the high envelope.

anchor_lowspandas.DataFrame

DataFrame of selected anchor points for the low envelope.

smoothedpandas.Series

Smoothed version of the input series.

Notes

This function assumes regular time intervals in the input series. If the frequency cannot be inferred, it is estimated from the first two timestamps.

vtools.functions.error_detect module

bounds_test(ts, bounds)[source]
choose_npartitions(nrows, *, window, small_series_threshold=None, min_partition_size=None, target_partition_size=5000)[source]
despike(arr, n1=2, n2=20, block=10, *, as_anomaly=False)[source]

Detect and optionally remove isolated spikes using overlapping-window statistics.

This is a legacy-style spike scrubber rather than a pure anomaly detector. It runs two passes:

  1. Compute a rolling (left-aligned) window mean/std and flag values whose deviation exceeds n1 * std. Those flagged values are temporarily set to NaN.

  2. Recompute rolling window mean/std on the NaN-masked signal and flag values whose deviation exceeds n2 * std. These flags are the final spikes.

Parameters:
arrarray-like

1D numeric signal.

n1float, default 2

Pass-1 threshold multiplier on the rolling standard deviation.

n2float, default 20

Pass-2 threshold multiplier on the rolling standard deviation.

blockint, default 10

Rolling window length (number of samples). Windows are left-aligned (i.e., window i is arr[i:i+block]). The final mean/std arrays are extended by repeating the last window’s stats for the last block-1 samples, matching the historical behavior.

as_anomalybool, default False

If False (default), return a cleaned array where spikes are replaced with NaN. If True, return a boolean mask (True where spikes are detected by pass-2).

Returns:
np.ndarray

If as_anomaly is False: a float array (same length) with spikes set to NaN. If as_anomaly is True: a boolean array (same length) marking spikes.

Notes

  • The implementation uses NumPy’s sliding_window_view instead of an external rolling_window helper to make the behavior explicit and self-contained.

  • Any NaNs in the input are treated as missing data via masked arrays.

  • This function copies the input and does not modify it in-place.

example()[source]
example2()[source]
max_change_test(ts, max_change, max_plateau_len=0)[source]

Flag interiors of excursions with excessive adjacent changes.

Parameters:
tspandas.Series or pandas.DataFrame

Numeric observations in sampling order. DataFrame columns are tested independently. Input values are not modified.

max_changefloat

Positive, finite absolute-change limit per sampling interval. A change equal to the limit is accepted. This is not a rate per unit time; choose the limit for the input sampling interval.

max_plateau_lenint, default 0

Maximum number of consecutive non-excessive difference intervals between excessive-change runs that may be bridged. Merge neighboring runs left-to-right only when their combined mean absolute change, including the plateau, strictly exceeds max_change. Missing or non-finite differences cannot be bridged.

Returns:
pandas.Series or pandas.DataFrame

Boolean anomaly mask with the input index, name, and columns. Only observations strictly inside each resulting run are flagged; its two endpoint observations are retained. An isolated excessive difference has no interior observation and flags nothing.

Notes

Endpoint retention assumes the excursion starts and ends at good data. Persistent steps and bad endpoints require complementary tests. Absolute variation is accumulated, so changes of opposite sign do not cancel. Prefix sums and a single merge scan give linear cost per column. Merge order is deliberately left-to-right and can affect the resulting groups.

med_outliers(ts, level=4.0, scale=None, filt_len=7, range=(None, None), quantiles=(0.01, 0.99), copy=True, as_anomaly=False)[source]

Detect outliers by running a median filter, subtracting it from the original series and comparing the resulting residuals to a global robust range of scale (the interquartile range). Individual time points are rejected if the residual at that time point is more than level times the range of scale.

The original concept comes from Basu & Meckesheimer (2007) Automatic outlier detection for time series: an application to sensor data although they didn’t use the interquartile range but rather expert judgment. To use this function effectively, you need to be thoughtful about what the interquartile range will be. For instance, for a strongly tidal flow station it is likely to

level: Number of times the scale or interquantile range the data has to be

to be rejected.d

scale: Expert judgment of the scale of maximum variation over a time step.

If None, the interquartile range will be used. Note that for a strongly tidal station the interquartile range may substantially overestimate the reasonable variation over a single time step, in which case the filter will work fine, but level should be set to a number (less than one) accordingly.

filt_len: length of median filter, default is 5

quantilestuple of quantiles defining the measure of scale. Ignored

if scale is given directly. Default is interquartile range, and this is almost always a reasonable choice.

copy: if True, a copy is made leaving original series intact

You can also specify rejection of values based on a simple range

Returns: copy of series with outliers replaced by nan

median_test(ts, level=4, filt_len=7, quantiles=(0.005, 0.095), copy=True)[source]
nrepeat(ts)[source]

Return the length of consecutive runs of repeated values

Parameters:
ts: DataFrame or series
Returns:
Like-indexed series with lengths of runs. Nans will be mapped to 0
steep_then_nan(ts, level=4.0, scale=None, filt_len=11, range=(None, None), quantiles=(0.01, 0.99), copy=True, as_anomaly=True, *, gap_aggregation='any', smallgaplen=3, neargapdist=5)[source]

Detect outliers via a median-filter residual test, gated by proximity to large gaps.

This is a Basu/median-style residual detector (median filter + robust global scale) with an additional gap proximity gate: only points close to a large gap are eligible to be flagged. “Small gaps” are treated as ignorable by converting them to a sentinel before computing gap distance.

Parameters:
tspandas.Series or pandas.DataFrame

Input time series. For DataFrames, residual/outlier detection is performed per column.

levelfloat, default 4.0

Threshold multiplier applied to the robust scale. A point is an outlier if abs(residual) > level * scale.

scalefloat or pandas.Series, optional

If None, compute a robust global scale from residual quantiles. If provided, it is used directly (scalar or per-column Series).

filt_lenint, default 11

Median filter window length passed to scipy.signal.medfilt.

rangetuple, default (None, None)

Optional (lo, hi) bounds applied to the input before residual calculation. If lo or hi is None, that side is not applied.

quantilestuple[float, float], default (0.01, 0.99)

Quantiles defining the robust range used as the scale when scale is None.

copybool, default True

If True, work on a copy of ts.

as_anomalybool, default True

If True, return a boolean anomaly mask (same shape as ts). If False, return a copy of ts with anomalies replaced by NaN.

gap_aggregation{“any”, “all”}, default “any”

How to combine gap proximity across columns when ts is a DataFrame.

  • “any”: a time is considered near a large gap if ANY column is near a gap.

  • “all”: a time is considered near a large gap only if ALL columns are near a gap.

This only affects the near-gap gate; residual outliers are still computed per column.

smallgaplenint, default 3

Gaps of length <= smallgaplen are treated as “small” and replaced by a sentinel before gap distance is computed.

neargapdistint, default 5

A time is considered “near a large gap” if its distance-to-gap (in samples) is < neargapdist.

Returns:
pandas.Series or pandas.DataFrame

If as_anomaly=True, returns a boolean mask with the same shape as ts. If as_anomaly=False, returns a copy of ts with flagged points set to NaN.

Notes

  • Gap proximity is computed using gapdist_test_series and gap_distance. For DataFrames, the per-column gap distance is reduced to a time mask using gap_aggregation.

  • This function is intended for offline QC where gap-adjacent behavior is considered more suspect than behavior in continuous data.

threshold(ts, bounds, copy=True)[source]

vtools.functions.example2 module

main()[source]

vtools.functions.filter module

Module contains filter used in tidal time series analysis.

butterworth(ts, cutoff_period=None, cutoff_frequency=None, order=4)[source]

low-pass butterworth-squared filter on a regular time series.

Parameters:
tsDataFrame

Must be one or two dimensional, and regular.

order: int ,optional

The default is 4.

cutoff_frequency: float,optional

Cutoff frequency expressed as a ratio with Nyquist frequency, should within the range (0,1). For a discretely sampled system, the Nyquist frequency is the fastest frequency that can be resolved by that sampling, which is half the sampling frequency. For example, if the sampling frequency is 1 sample/1 hour, the Nyquist frequency is 1 sample/2 hours. If we want a 36 hour cutoff period, the frequency is 1/36 or 0.0278 cycles per hour. Hence the cutoff frequency argument used here would be 0.0278/0.5 = 0.056.

cutoff_periodstring or _time_interval

Period corresponding to cutoff frequency. If input as a string, it must be convertible to a regular interval using the same rules as a pandas frequency.. cutoff_frequency and cutoff_period can’t be specified at the same time.

Returns:
result

A new regular time series with the same interval as ts.

Raises:
ValueError

If input order is not even, or input timeseries is not regular, or neither cutoff_period and cutoff_frequency is given while input time series interval is not 15min or 1 hour, or cutoff_period and cutoff_frequency are given at the same time.

cosine_lanczos(ts, cutoff_period=None, cutoff_frequency=None, filter_len=None, padtype=None, padlen=None, fill_edge_nan=True)[source]
godin(ts)[source]

Low-pass Godin filter a regular time series. Applies the \(\mathcal{A_{24}^{2}A_{25}}\) Godin filter [1] The filter is generalized to be the equivalent of one boxcar of the length of the lunar diurnal (~25 hours) constituent and two of the solar diurnal (~24 hours), though the implementation combines these steps.

Parameters:
tsDataFrame
Returns:
resultDataFrame

A new regular time series with the same interval of ts.

Raises:
NotImplementedError

If input time series is not univariate

References

[1]

Godin (1972) Analysis of Tides

lanczos(ts, cutoff_period=None, cutoff_frequency=None, filter_len=None, padtype=None, padlen=None, fill_edge_nan=True)[source]
lowpass_cosine_lanczos_filter_coef(cf, m, normalize=True)[source]

return the convolution coefficients for low pass lanczos filter.

Parameters:
cf: float

Cutoff frequency expressed as a ratio of a Nyquist frequency.

m: int

Size of filtering window size.

Returns:
results: list

Coefficients of filtering window.

lowpass_lanczos_filter_coef(cf, m, normalize=True, cosine_taper=False)[source]

Return the convolution coefficients for a low-pass Lanczos filter.

Parameters:
cffloat

Cutoff frequency expressed as a ratio of the Nyquist frequency.

mint

Size of the filtering window.

normalizebool, optional

Whether to normalize the filter coefficients so they sum to 1.

cosine_taperbool, optional

If True, applies a cosine-squared taper to the Lanczos window.

Returns:
resnp.ndarray

Coefficients of the filtering window.

ts_gaussian_filter(ts, sigma, order=0, mode='reflect', cval=0.0, truncate=4.0)[source]

Column-wise Gaussian smoothing of regular time series. Missing/irregular values are not handled, which means this function is not much different from a rolling window gaussian average in pandas which may be preferable in the case of missing data (ts.rolling(window=5,win_type=’gaussian’).mean. This function has been kept around awaiting irreg as an aspiration but yet to be implemented.

Parameters:
tsDataFrame

The series to be smoothed

sigmaint or freq

The sigma scale of the smoothing (analogous to std. deviation), given as a number of steps or freq

Returns:
resultDataFrame

A new regular time series with the same interval of ts.

vtools.functions.frequency_response module

compare_response(cutoff_period)[source]

Generate frequency response plot of low-pass filters: cosine_lanczos, boxcar 24h, boxcar 25h, and godin.

Parameters:
cutoff_periodint

Low-pass filter cutoff period in number of hours.

Returns:
None.
unit_impulse_ts(size, interval)[source]
Parameters:
sizeint

Length of impluse time series, odd number.

intervalstring

time series interval, such as “15min”

Returns:
pandas.Dataframe

time series value 0.0 except 1 at the middle of time series.

vtools.functions.ha_utils module

nodal_factors(t_dates, tref_date, constituents, lat_deg, nodal_linear_time=False, phase='Greenwich')[source]

Compute nodal factors F, nodal phase U (cycles), and astronomical argument V (cycles).

Parameters:
t_datesarray-like pandas.Timestamp or array-like of datetime

Time in datetime.

tref_datedatetime or pandas.Timestamp

Reference date, used for nodal amp and phase correction calculations. Resulted nodal factors will be computed at this reference date if nodal_linear_time=True, a single nodal factor(F/U) is returned for each constituent, otherwise nodal factors will be computed at t_dates for all constituents.

constituentssequence[str]

Constituent abbreviations, e.g. [“M2”, “K1”, “MK3”, “MO3”].

lat_degfloat

Latitude in degrees.

nodal_linear_timebool

Linearized nodal variation, check with tref_date for details.

phase{“Greenwich”, “linear_time”, “raw”}

Tide Greenwich equilibrium phase correction convention. Greenwich: Greenwich equilibrium argument computed on all t_dates linear_time: single Greenwich equilibrium argument computed at tref_date (UT) and applied to all t_dates raw: no Greenwich equilibrium argument applied.

Returns:
Fndarray (n, nc)

Nodal amplitude factors. n is the length of t_dates when nodal_linear_time=False, otherwise n=1. nc is the number of constituents.

Undarray (n, nc)

Nodal phase corrections (cycles). n is the length of t_dates when nodal_linear_time=False, otherwise n=1. nc is the number of constituents.

Vndarray (nt, nc)

Astronomical arguments reckoned from tref_date (cycles). nt is the length of t_dates. nc is the number of constituents.

vtools.functions.interannual module

interannual(ts)[source]

Pivots years of multiyear series to columns and convert index to elapsed time of year

Parameters:
tsseries Univariate series
Returns:
annualDataFrame with year in the columns and elapsed time of year as index
interannual_sample()[source]
interannual_ticks_labels(freq)[source]

Convenient ticks and labels for interannual

Parameters:
freqFrequency string for desired spacing. Must be “Q”,”QS”,”M”,”MS” for quarterly or monthly
Returns:
ticks_labelstuple of tick locations and labels

vtools.functions.interpolate module

Module for data interpolation using splines or interfaces unavailable in Pandas.

monotonic_spline(ts, dest)[source]

Interpolating a regular time series (rts) to a finer rts by rational histospline.

The rational histospline preserves area under the curve. This is a good choice of spline for period averaged data where an interpolant is desired that is ‘conservative’. Note that it is the underlying continuous interpolant that will be ‘conservative though, not the returned discrete time series which merely samples the underlying interpolant.

Parameters:
tsPandas.DataFrame

Series to be interpolated, typically with DatetimeIndex

desta pandas freq code (e.g. ‘16min’ or ‘D’) or a DateTimeIndex
Returns:
resultDataFrame

A regular time series with same columns as ts, populated with instantaneous values and with an index of type DateTimeIndex

rhistinterp(ts, dest, p=2.0, lowbound=None, tolbound=0.001, maxiter=5)[source]

Interpolate a regular time series (rts) to a finer rts by rational histospline.

The rational histospline preserves area under the curve. This is a good choice of spline for period averaged data where an interpolant is desired that is ‘conservative’. Note that it is the underlying continuous interpolant that will be ‘conservative though, not the returned discrete time series which merely samples the underlying interpolant.

Parameters:
tsPandas.DataFrame

Series to be interpolated, with period index and assuming time stamps at beginning of the period and no missing data

deststring or DateTimeIndex

A pandas freq code (e.g. ‘16min’ or ‘D’) or a DateTimeIndex

pfloat, optional

Spline tension, usually between 0 and 20. Must >-1. For a ‘sufficiently large’ value of p, the interpolant will be monotonicity-preserving and will maintain strict positivity (always being strictly > lowbound). It will also preserve the original shape of the time series.

lowboundfloat, optional

Lower bound of interpolated values.

tolboundfloat, optional

Tolerance for determining if an input is on the bound.

Returns:
resultpandas.DataFrame

A regular time series with same columns as ts, populated with instantaneous values and with an index of type DateTimeIndex

vtools.functions.lag_cross_correlation module

calculate_lag(lagged, base, max_lag, res, interpolate_method='linear')[source]

Calculate shift in lagged, that maximizes cross-correlation with base.

Parameters:
base,lagged: :class:`Pandas.Series`

time series to compare. The result is relative to base

max_lag: interval

Maximum pos/negative time shift to consider in cross-correlation (ie, from -max_lag to +max_lag). Required windows in lagged will account for this bracket. For series dominated by a single frequency (eg 1c/12.5 hours for tides), the algorithm can tolerate a range of 180 degrees (6 hours)

res: interval

Resolution of analysis. The series lagged will be interpolated to this resolution using interpolate_method. Unit used here will determine the type of the output. See documentation of the interval concept which is most compatible with pandas.tseries.offsets, not timeDelta, because of better math properties in things like division – vtime helpers like minutes(1) may be helpful

interpolate_method: str, optional

Interpolate method to refine lagged to res. Must be compatible with pandas interpolation method names (and hence scipy)

Returns:
laginterval

Shift as a pandas.tseries.offsets subtype that matches units with res This shift is the apparent lateness (pos) or earliness (neg). It must be applied to base or removed to lagged to align the features.

vtools.functions.merge module

ts_merge(series, names=None, strict_priority=False, preserve_freq=True)[source]

Merge multiple time series together, prioritizing series in order.

Parameters:
seriessequence of pandas.Series or pandas.DataFrame

Higher priority first. All indexes must be DatetimeIndex.

namesNone, str, or iterable of str, optional
  • If None (default), inputs must share compatible column names.

  • If str, the output is univariate and will be named accordingly.

  • If iterable, it is used as a subset/ordering of columns.

strict_prioritybool, default False

If False (default): lower-priority data may fill NaNs in higher-priority series anywhere (traditional merge/overlay). If True: for each column, within the window [first_valid_index, last_valid_index] of any higher-priority series, lower-priority data are masked out — even if the higher-priority value is NaN. Outside those windows, behavior is unchanged.

preserve_freqbool, default True

If True, attempt to preserve a common regular frequency across inputs. When a common regular frequency can be established, the output is reindexed to that regular extent. When it cannot be established, ts_merge falls back to index-based merge behavior, which for strict_priority=True is a patchwise combination of the indexes and for False is a shuffle.

Returns:
pandas.Series or pandas.DataFrame
ts_splice(series, names=None, transition='prefer_last', floor_dates=False, preserve_freq=True)[source]

Splice multiple time series together, prioritizing series in patches of time.

Unlike ts_merge, which blends overlapping data points, ts_splice stitches together time series without overlap. The function determines when to switch between series based on a transition strategy.

Parameters:
seriestuple or list of pandas.DataFrame or pandas.Series

A tuple or list of time series. Each series must have a DatetimeIndex and consistent column structure.

namesNone, str, or iterable of str, optional
  • If None (default), all input series must share common column names, and the output will merge common columns.

  • If a str, all input series must have a single column, and the output will be a DataFrame with this name as the column name.

  • If an iterable of str, all input DataFrames must have the same number of columns matching the length of names, and these will be used for the output.

transition{‘prefer_first’, ‘prefer_last’} or list of pandas.Timestamp

Defines how to determine breakpoints between time series: - ‘prefer_first’: Uses the earlier series on the list during until its valid timestamp. - ‘prefer_last’: Uses the later series starting from its first valid timestamp. - A list of specific timestamps can also be provided as transition points.

floor_datesbool, optional, default=False

If True, inferred transition timestamps (prefer_first or prefer_last) are floored to the beginning of the day. This can introduce NaNs if the input series are regular with a freq attribute.

preserve_freqbool, default True

If True, attempt to preserve a common regular frequency across inputs. When a common regular frequency can be established, the output is reindexed to that regular extent. When it cannot be established, ts_merge falls back to index-based merge behavior, which for strict_priority=True is a patchwise combination of the indexes and for False is a shuffle.

Returns:
pandas.DataFrame or pandas.Series
  • If the input contains multi-column DataFrames, the output is a DataFrame with the same column structure.

  • If a collection of single-column Series is provided, the output will be a Series.

  • The output retains a freq attribute if all inputs share the same frequency.

See also

ts_merge

Merges series by filling gaps in order of priority.

Notes

  • The output time index is the union of input time indices.

  • If transition is ‘prefer_first’, gaps may appear in the final time series.

  • If transition is ‘prefer_last’, overlapping data is resolved in favor of later series.

vtools.functions.neighbor_fill module

Neighbor-based time-series gap filling.

This module provides a single high-level API, fill_from_neighbor(), with pluggable backends for common algorithms used to infer a target series from one or more nearby stations. It is designed for operational use in Delta/Bay hydrodynamics workflows, but is intentionally general.

Highlights

  • Robust time alignment and optional resampling.

  • Multiple modeling strategies: OLS/robust, rolling regression, lagged elastic-net, and state-space/Kalman.

  • Forward-chaining (temporal) cross-validation utilities.

  • Optional regime stratification (e.g., barrier in/out, season).

  • Uncertainty estimates where available (analytic or residual-based).

  • Clear return structure with diagnostics for auditability.

Example

>>> res = fill_from_neighbor(
...     target=y, neighbor=x, method="state_space", lags=range(0, 4),
...     bounds=(0.0, None), regime=regime_series
... )
>>> filled = res["filled"]
>>> info = res["model_info"]

Notes

  • “Neighbor” can be one series or multiple (as a DataFrame); both are supported.

  • Missing data in the target are left as-is where the model cannot reasonably infer a value (e.g.no overlapping neighbor data). Where predictions exist, they are merged into the target to produce filled. DFM methods can carry through a gap in the neighbor.

class FillResult(filled: Series, yhat: Series, pi_lower: Series | None, pi_upper: Series | None, model_info: Dict[str, Any], metrics: Dict[str, float])[source]

Bases: object

Container for gap-filling outputs.

Parameters:
filledpd.Series

Target series with gaps filled where possible.

yhatpd.Series

Model predictions aligned to the union index used for fitting/prediction.

pi_lower, pi_upperOptional[pd.Series]

Prediction interval bounds where available; otherwise None.

model_infodict

Method, parameters, chosen lags, training window, etc.

metricsdict

Holdout scores (MAE/RMSE/R^2) using forward-chaining CV where configured.

Methods

to_dict

filled: Series
metrics: Dict[str, float]
model_info: Dict[str, Any]
pi_lower: Series | None
pi_upper: Series | None
to_dict() → Dict[str, Any][source]
yhat: Series
dfm_pack_params(model_info: dict) → dict[source]

Return a portable blob of fitted DFM params.

Parameters:
model_infodict

Model info dictionary, typically from fill_from_neighbor.

Returns:
dict

Dictionary containing fitted DFM parameters with the following keys: - ‘param_names’: list of parameter names. - ‘transformed’: list of transformed parameter values. - ‘constrained’: dictionary of constrained parameter values. - ‘mle’: dictionary with optimizer info (optional). - ‘reused’: bool indicating if parameters were reused (optional).

Raises:
TypeError

If model_info is not a dictionary.

ValueError

If no fitted parameters are found in model_info.

fill_from_neighbor(target: Series, neighbor: Series | DataFrame, method: str = 'substitute', regime: Series | None = None, bounds: Tuple[float | None, float | None] = (None, None), *, params: dict | None = None, **kwargs) → Dict[str, Any][source]

Fill gaps in target using information from neighbor.

This is a high-level wrapper with multiple method backends (OLS/robust, rolling regression, lagged regression, LOESS-in-time, Trimbur-style DFM variants, residual-interpolation baselines, or simple substitution). Inputs must already lie on the same regular time grid (same step and phase); this function does not resample.

Parameters:
targetpandas.Series

Target time series with a DatetimeIndex on a regular grid. Values may be NaN.

neighborpandas.Series or pandas.DataFrame

One or more neighbor series with a DatetimeIndex on the same grid as target (same step and phase). Values may be NaN.

method{‘substitute’, ‘ols’, ‘huber’, ‘rolling’, ‘lagged_reg’, ‘loess’, ‘dfm_trimbur_rw’, ‘dfm_trimbur_ar’, ‘resid_interp_linear’, ‘resid_interp_pchip’}

Algorithm to use:

  • 'substitute': pass-through neighbor after mean/scale alignment.

  • 'ols': ordinary least squares on overlap (optionally with lags).

  • 'huber': robust regression with Huber loss (optionally with lags).

  • 'rolling': rolling-window OLS in sample units (not time offsets).

  • 'lagged_reg': multivariate regression on specified neighbor lags.

  • 'loess': LOESS (time → value) smoothing using neighbor as scaffold.

  • 'dfm_trimbur_rw': dynamic factor model (Trimbur factor) with random-walk anomaly for the target.

  • 'dfm_trimbur_ar': dynamic factor model (Trimbur factor) with AR anomaly on the neighbor.

  • 'resid_interp_linear' / 'resid_interp_pchip': baseline y≈a+bx fit on overlap, then interpolate residuals (linear or PCHIP) across gaps.

regimepandas.Series, optional

Optional categorical series indexed like target to stratify fits (e.g., barrier in/out). If provided, models are fit per category and stitched back together.

bounds(float or None, float or None)

Lower/upper bounds to clip the final filled values (applied at the end).

paramsdict, optional

Pre-fitted/packed parameter blob for methods that support parameter reuse (e.g., the DFM backends). If provided, fitting is skipped and the supplied parameters are used directly.

**kwargs

Method-specific optional arguments. Unsupported keys are ignored unless otherwise noted. Typical extras by method:

Common
lagsint or Sequence[int], optional

Non-negative lags (in samples) for neighbor features. If an int m is provided, implementations may expand to range(0, m+1). Default behavior varies by method (often no lags or a small heuristic set).

seedint, optional

Random seed for any stochastic initializations (where applicable).

‘ols’

lags : int or Sequence[int], optional

add_constbool, default True

Include an intercept term.

fit_intercept : bool, alias of add_const.

‘huber’

lags : int or Sequence[int], optional

huber_tfloat, default 1.35

Huber threshold (in residual σ units).

maxiter : int, default 200

tol : float, default 1e-6

‘rolling’
windowint, required

Rolling window length in samples (integer). Time-offset strings (e.g., ‘14D’) are not supported here.

min_periodsint, optional

Minimum non-NaN samples required inside each window (default = window).

centerbool, default False

Whether to center the rolling window.

lagsint or Sequence[int], optional

If provided, each regression uses lagged neighbor columns inside the window.

‘lagged_reg’

lags : int or Sequence[int], recommended

alphafloat, optional

Ridge/L2 penalty (if the backend supports it).

l1_ratiofloat, optional

Elastic-net mixing (if the backend supports it).

standardizebool, default True

Standardize columns before regression.

‘loess’
fracfloat, default 0.25

LOESS span as a fraction of the data length (used in time→value smoothing).

itint, default 0

Number of robustifying reweighting iterations.

degreeint, default 1

Local polynomial degree.

‘dfm_trimbur_rw’ / ‘dfm_trimbur_ar’
rx_scalefloat, default 1.0

Relative scale factor for neighbor measurement noise.

maxiterint, default 80

Maximum optimizer iterations during parameter fitting.

dispint, default 0

Optimizer verbosity (0 = silent).

anom_var{‘target’,’neighbor’}, optional

Which series carries the anomaly/noise term (fixed by the variant, but may be overridden).

ar_orderint, optional

AR order for the anomaly in the '_ar' variant (default may be 1).

param_nameslist[str], optional

For advanced users: explicit parameter naming (used when packing).

Note: DFM backends accept params=... at the top level for reuse.

‘resid_interp_linear’ / ‘resid_interp_pchip’
min_overlapint, default 3

Minimum overlapping samples required to fit the baseline y≈a+bx.

clip_residuals_sigmafloat, optional

Winsorize residuals before interpolation (σ units).

enforce_monotonebool, default False

For PCHIP path only: enforce monotonic segments where applicable.

Returns:
dict

Dictionary with the following keys:

yhatpandas.Series

Filled series on the same index as target.

pi_lowerpandas.Series or None

Lower uncertainty band (if the method provides one), otherwise None.

pi_upperpandas.Series or None

Upper uncertainty band (if the method provides one), otherwise None.

model_infodict

Method-specific diagnostics and metadata. Typical fields include: method, param_names, fitted_params (packed blob for reuse), scaling (means/stds used), goodness-of-fit (e.g., llf, aic, bic), and per-regime info when regime is provided.

Raises:
ValueError

If indices are not equally spaced, or grids mismatch in step or phase, or if required method-specific kwargs are missing (e.g., window for method='rolling').

KeyError

If an unknown method name is provided.

load_dfm_params(path: str) → Dict[str, Any][source]

Load a DFM parameter blob from YAML and validate minimal schema.

save_dfm_params(params: Dict[str, Any], path: str) → None[source]

Save a DFM parameter blob to YAML (preferred for this codebase). File extension may be .yaml or .yml. Other extensions raise.

vtools.functions.period_op module

period_op(ts, period='D', agg='mean', max_absent_frac=0.0)[source]
window_op(ts, window, period='D', agg='mean', max_absent_frac=0.0)[source]

vtools.functions.rhistinterp module

Conservative period-to-instantaneous interpolation with optional threshold protection.

This module provides a new implementation of rhistinterp that can reproduce the legacy behavior exactly when thresh=None and can switch to a hybrid mode when a threshold is supplied. In hybrid mode, source intervals with values at or below the threshold are reconstructed as constant plateaus, while contiguous runs of remaining intervals are interpolated conservatively.

rhistinterp(ts, dest, p=2.0, lowbound=None, thresh=None, tolbound=0.001, maxiter=5)[source]

Interpolate a regular time series to a finer series by conservative reconstruction.

Parameters:
tspandas.Series or pandas.DataFrame

Input series with PeriodIndex.

deststr or pandas.DatetimeIndex

Target frequency or explicit destination index.

pfloat or ndarray, optional

Initial spline tension parameter.

lowboundfloat, optional

Lower bound of interpolated values.

threshfloat, optional

Threshold above lowbound. Intervals with values at or below this threshold are reconstructed as constant plateaus. If None, legacy behavior is used.

tolboundfloat, optional

Tolerance for lower-bound enforcement.

maxiterint, optional

Maximum iterations for local tension tightening.

Returns:
pandas.Series or pandas.DataFrame

Interpolated instantaneous time series.

vtools.functions.savitzky_golay module

main()[source]
savgol_filter_numba(y, window_length, degree, error)[source]
savgol_filter_weighted(data, window_length, degree, error=None, cov_matrix=None, deriv=None, use_numba=True)[source]

Apply a Savitzky–Golay filter with weights to a univariate DataFrame or Series.

Parameters:
datapandas.DataFrame or pandas.Series

DataFrame or Series containing your data.

window_lengthint

Length of the filter window (must be odd).

degreeint

Degree of the polynomial fit.

errorpandas.Series, optional

Series containing the error (used to compute weights).

cov_matrix2D numpy array, optional

Covariance matrix for the errors.

derivint, optional

Derivative order to compute.

use_numbabool, optional

If True, uses the Numba-accelerated kernel.

Returns:
pandas.Series

Series of the filtered values.

Notes

The practical size of window_length depends on the data and the computational resources. Larger window lengths provide smoother results but require more computation and may not capture local variations well. It is recommended to experiment with different window lengths to find the optimal value for your specific application.

Some of the workflow derived from this work: https://github.com/surhudm/savitzky_golay_with_errors

savgol_filter_werror(y, window_length, degree, error=None, cov=None, deriv=None)[source]
solve_leastsq(yarr, ycov, vander, vanderT, deriv=None)[source]
solve_polyfit(xarr, yarr, degree, weight, deriv=None)[source]

vtools.functions.separate_species module

Separation of tidal data into species The key function in this module is separate_species, which decomposes tides into subtidal, diurnal, semidiurnal and noise components.

The fileters are long, so the time resolution of the amplitude may be limited. A demo function is also provided that reads tide series (6min intervl) from input files, seperates the species, writes results and optionally plots an example

plot_result(ts, ts_semi, ts_diurnal, ts_sub_tide, station)[source]
run_example()[source]

This is the data for the example. Note that you want the data to be at least 4 days longer than the desired output

separate_species(ts, noise_thresh_min=40)[source]

Separate species into subtidal, diurnal, semidiurnal and noise components

Input:

ts: timeseries to be decomposed into species, assumed to be at six minute intervals. The filters used have long lenghts, so avoid missing data and allow for four extra days worth of data on each end.

Output:

four regular time series, representing subtidal, diurnal, semi-diurnal and noise

write_th(filename, ts_output)[source]

This works fine for fairly big series

vtools.functions.skill_metrics module

corr_coefficient(predictions, targets, method='pearson')[source]

Calculates the correlation coefficient (the ‘r’ in ‘-squared’ between two series.

For time series where the targets are serially correlated and may span only a fraction of the natural variability, this statistic may not be appropriate and Murphy (1988) explains why caution should be exercised in using this statistic.

Parameters:
predictions, targetsarray_like

Time series to analyze

methodpearson’, ‘kendall’, ‘spearman’

Method compatilble with pandasa

Returns:
rfloat

Correlation coefficient

mean_error(predictions, targets, proportiontocut=None)[source]

Calculate the untrimmed mean error, discounting nan values

Parameters:
predictions, targetsarray_like

Time series or arrays to be analyzed

Returns:
medfloat

Median error

median_error(predictions, targets)[source]

Calculate the median error, discounting nan values

Parameters:
predictions, targetsarray_like

Time series or arrays to be analyzed

Returns:
medfloat

Median error

mse(predictions, targets)[source]

Mean squared error

Parameters:
predictions, targetsarray_like

Time series or arrays to analyze

Returns:
msevtools.data.timeseries.TimeSeries

Mean squared error between predictions and targets

rmse(predictions, targets)[source]

Root mean squared error

Parameters:
predictions, targetsarray_like

Time series or arrays to analyze

Returns:
msefloat

Mean squared error

skill_score(predictions, targets, ref=None)[source]

Calculate a Nash-Sutcliffe-like skill score based on mean squared error

As per the discussion in Murphy (1988) other reference forecasts (climatology, harmonic tide, etc.) are possible.

Parameters:
predictions, targetsarray_like

Time series or arrays to be analyzed

Returns:
rmsefloat

Root mean squared error

tmean_error(predictions, targets, limits=None, inclusive=[True, True])[source]

Calculate the (possibly trimmed) mean error, discounting nan values

Parameters:
predictions, targetsarray_like

Time series or arrays to be analyzed

limitstuple(float)

Low and high limits for trimming

inclusive[boolean, boolean]

True if clipping is inclusive on the low/high end

Returns:
meanfloat

Trimmed mean error

willmott_score(predictions, targets, ref=None)[source]

Calculate a Nash-Sutcliffe-like skill score based on mean squared error

As per the discussion in Murphy (1988) other reference forecasts (climatology, harmonic tide, etc.) are possible.

Parameters:
predictions, targetsarray_like

Time series or arrays to be analyzed

Returns:
rmsefloat

Root mean squared error

vtools.functions.tidalhl module

get_tidal_amplitude(dfh, dfl)[source]

Tidal amplitude given tidal highs and lows

Args:

dfh (DataFrame): Tidal highs time series

dfl (DataFrame): Tidal lows time series

Returns:

DataFrame: Amplitude timeseries, at the times of the low following the high being used for amplitude calculation

get_tidal_hh_lh(sh)[source]

return HH(1) or LH (0) based from input tide highs (sh) using rolling window of 2 and tlmax function

get_tidal_hl(df, cutoff_period='2h', resample_period='1min', interpolate_method='pchip', moving_window_size='7h', method='rolling')[source]

Get Tidal highs and lows

Args:

df (DataFrame): A single column dataframe indexed by datetime

cutoff_period (str, optional): cutoff period for cosine lanczos filter. Defaults to ‘2h’.

resample_period (str, optional): Resample to regular period after filtering.

Pass None to skip resampling and operate at the native input frequency. Ignored when method=’find_peaks’. Defaults to ‘1min’.

interpolate_method (str, optional): interpolation for resampling. Defaults to ‘pchip’.

moving_window_size (str, optional): moving window size for rolling method. Defaults to ‘7h’.

method (str, optional): Peak-detection method. 'rolling' (default) uses the

numba-accelerated sliding-window approach — robust for noisy signals. 'find_peaks' filters at native resolution then uses sequential 25h windows with scipy find_peaks — ~400x faster for pre-filtered smooth inputs such as SF tidal records.

Returns:

tuple of DataFrame: Tidal high and tidal low time series

get_tidal_hl_zerocrossing(df, round_to='1min')[source]

Finds the tidal high and low times using zero crossings of the first derivative.

This works for all situations but is not robust in the face of noise and perturbations in the signal

get_tidal_ll_hl(sl)[source]

return LL(1) or HL (0) based from input tide lows (sl) using rolling window of 2 and tlmin function

get_tidal_phase_diff(dfh2, dfl2, dfh1, dfl1, tolerance='4h')[source]

Calculates the phase difference between df2 and df1 tidal highs and lows

Scans +/- 4 hours in df1 to get the highs and lows in that windows for df2 to get the tidal highs and lows at the times of df1

Args:

dfh2 (DataFrame): Timeseries of tidal highs

dfl2 (DataFrame): Timeseries of tidal lows

dfh1 (DataFrame): Timeseries of tidal highs

dfl1 (DataFRame): Timeseries of tidal lows

Returns:

DataFrame: Phase difference (dfh2-dfh1) and (dfl2-dfl1) in minutes

vtools.functions.tidalhours module

Functions for analyzing tidal cycles from time series data.

This module provides functions to analyze tidal time series, identify slack water times, and map any time to its position within the tidal cycle (tidal hour). This is useful for tidal phase analysis in estuarine and coastal studies.

Functions

find_slack(jd, u, leave_mean=False, which=’both’)

Identifies the times of “slack water”—the moments when tidal current velocity (u) crosses zero.

hour_tide(jd, u=None, h=None, jd_new=None, leave_mean=False)

Calculates the “tidal hour” for each time point, i.e., the phase of the tidal cycle (0–12, where 0 is slack before ebb).

hour_tide_fn(jd, u, leave_mean=False)

Returns a function that computes tidal hour for arbitrary time points, based on the provided time/velocity series.

tidal_hour_signal(ts, filter=True)

Compute the tidal hour of a semidiurnal signal.

diff_h(tidal_hour_series)

Compute the time derivative of tidal hour.

diff_h(tidal_hour_series)[source]

Compute the time derivative of tidal hour.

Parameters:
tidal_hour_seriespandas.Series

Output of tidal_hour_signal, indexed by datetime.

Returns:
pandas.Series

Time derivative of tidal hour (dH/dt) in hours/hour, indexed by datetime.

Notes

This derivative is often included to capture how rapidly the tidal phase is changing, which can be important in modeling flow reversals, estuarine dynamics, or for detecting slack tide conditions where the rate of change is near zero.

find_slack(jd, u, leave_mean=False, which='both')[source]

Identify slack water times from a velocity time series.

Parameters:
jdarray-like

Array of time values (Julian days or similar).

uarray-like

Array of velocity values (flood-positive).

leave_meanbool, optional

If False, removes the mean (low-frequency) component from u.

which{‘both’, ‘high’, ‘low’}, optional

Specifies which zero-crossings to return.

Returns:
jd_slackndarray

Array of times when slack water occurs.

start{‘ebb’, ‘flood’}

String indicating the initial state.

Notes

This function detects transitions in the velocity time series where the current reverses direction (i.e., crosses zero), which correspond to slack water events.

hour_tide(jd, u=None, h=None, jd_new=None, leave_mean=False, start_datum='ebb')[source]

Calculate tidal hour from a time series of velocity or water level.

Parameters:
jdarray-like

Time in days (e.g., Julian day, datenum, etc.).

uarray-like, optional

Velocity, flood-positive.

harray-like, optional

Water level, positive up.

jd_newarray-like, optional

Optional new time points to evaluate.

leave_meanbool, optional

By default, the time series mean is removed, but this can be disabled by passing True.

start_datum{‘ebb’, ‘flood’}, optional

Desired starting datum for tidal hour.

Returns:
ndarray

Array of tidal hour values (0–12) for each time point.

Notes

This function computes the phase of the tidal cycle (tidal hour) for each time point, based on either velocity or water level time series. The tidal hour is defined such that 0 corresponds to slack before ebb.

hour_tide_fn(jd, u, start_datum='ebb', leave_mean=False)[source]

Return a function for extracting tidal hour from the time/velocity given.

Parameters:
jdarray-like

Time array.

uarray-like

Velocity array.

start_datum{‘ebb’, ‘flood’}, optional

Desired starting datum for tidal hour.

leave_meanbool, optional

If False, removes the mean (low-frequency) component from u.

Returns:
function

Function: fn(jd_new) → tidal hour array.

Notes

This function generates a callable that computes tidal hour for arbitrary time points, based on the provided time and velocity series. The tidal hour is referenced to slack water.

tidal_hour_signal(ts, filter=True)[source]

Compute the tidal hour of a semidiurnal signal.

Parameters:
tspandas.Series

Time series of water level or other semidiurnal signal. Must have a datetime index.

filterbool, default True

Whether to apply a 40-hour cosine Lanczos filter to the input signal. If False, uses the raw signal.

Returns:
pandas.Series

Tidal hour as a float (range [0, 12)), indexed by datetime.

See also

diff_h

Compute the derivative (rate of change) of tidal hour.

cosine_lanczos

External function used to apply low-pass filtering.

Notes

This function returns the instantaneous phase-based tidal hour for a time series, assuming a semidiurnal signal. Optionally applies a cosine Lanczos low-pass filter (e.g., 40h) to isolate tidal components from subtidal or noisy fluctuations.

The tidal hour is computed using the phase of the analytic signal obtained via the Hilbert transform. This phase is then scaled to range from 0 to 12 hours to represent one semidiurnal tidal cycle. The output is a pandas Series aligned with the input time index.

The tidal hour is derived from the instantaneous phase of the analytic signal. This signal is computed as:

analytic_signal = ts + 1j * hilbert(ts)

The phase (angle) of this complex signal varies smoothly over time and reflects the oscillatory nature of the tide, allowing us to construct a continuous representation of “tidal time” even between extrema.

The use of the Hilbert transform provides a smooth interpolation of the signal’s phase progression, since it yields the narrow-band envelope and instantaneous phase of the dominant frequency component (assumed to be semidiurnal here).

vtools.functions.transition module

transition_ts(ts0, ts1, method='linear', window=None, overlap=(0, 0), return_type='series', names=None, max_snap=None)[source]

Create a smooth transition between two aligned time series.

Parameters:
ts0pandas.Series or pandas.DataFrame

The initial time series segment. Must share the same frequency and type as ts1.

ts1pandas.Series or pandas.DataFrame

The final time series segment. Must share the same frequency and type as ts0.

method{“linear”, “pchip”, “blend”}, default=”linear”

The interpolation strategy:

  • “linear”: interpolate across a gap using endpoints from ts0/ts1.

  • “pchip”: shape-preserving interpolation using nearby points (see overlap).

  • “blend”: requires an explicit window=(start, end) where both ts0 and ts1 have values on every timestamp; returns a linear combination (1 - w(t)) * ts0(t) + w(t) * ts1(t) with w(start)=0 → w(end)=1.

window[start, end] or None
  • For “linear”/”pchip”: If None and there’s a natural gap (ts0.last < ts1.first), that full gap is used. If provided, start<end, ts0 must have a sample at/before start and ts1 at/after end; optional widening to a natural gap via max_snap.

  • For “blend”: Required. Both series must cover every timestamp in [start, end] with non-missing values; no widening or gap logic is applied.

namesNone, str, or iterable of str, optional
  • If None (default), inputs must share compatible column names.

  • If str, the output is univariate and will be named accordingly.

  • If iterable, it is used as a subset/ordering of columns.

overlaptuple of int or str, default=(0, 0)

Amount of overlap to use for interpolation anchoring in pchip mode. Each entry can be: - An integer: number of data points before/after to use. - A pandas-compatible frequency string: e.g., “2h” or “45min”.

max_snapNone | Timedelta-like | (Timedelta-like, Timedelta-like)

Optional widening ONLY when window is strictly inside the natural gap. Expands start earlier and end later by up to max_snap, but never past (ts0.last, ts1.first). Default None = no widening.

return_type{“series”, “glue”}, default=”series”
  • “series”: returns the full merged series including ts0, transition, ts1.

  • “glue”: returns only the interpolated transition segment.

Returns:
pandas.Series or pandas.DataFrame

The resulting time series segment, either the full merged series or just the transition zone.

Raises:
ValueError

If ts0 and ts1 have mismatched types or frequencies, or if overlap exists but window is not specified.

vtools.functions.unit_conversions module

Unit conversion helpers.

This module provides:
  • linear/affine converters for common engineering units: metres↔feet, cms↔cfs, °F↔°C (all functional, no in-place mutation).

  • Domain-specific conversions between electrical conductivity (EC, μS/cm) and practical salinity (PSU) at 25 °C, with optional Hill low-salinity correction and an accuracy-improving root-finding “refinement” step.

  • a general-purpose unit conversion function convert_units() that uses Pint by default (with an optional cf_units backend via an environment variable), and that has fast paths for the above common conversions.

Notes

  • PSU is treated here as a practical “unit” for salinity in workflows, even though in a strict metrological sense it is unitless.

  • The EC↔PSU conversions assume 25 °C and no explicit temperature dependence beyond the optional Hill correction.

References

Schemel, L.E. (2001) Empirical relationships between salinity and specific conductance in San Francisco Bay, California.

Hill, K. (low-salinity correction widely used in estuarine practice).

celsius_to_fahrenheit(x)[source]

Convert °C to °F.

Parameters:
xscalar | array-like | pd.Series | pd.DataFrame

Value(s) in celsius.

Returns:
same type as x

Value(s) in farenheit.

cfs_to_cms(x)[source]

Convert ft³/s to m³/s.

Parameters:
xscalar | array-like | pd.Series | pd.DataFrame

Value(s) in cfs.

Returns:
same type as x

Value(s) in cubic meters per second.

cms_to_cfs(x)[source]

Convert m³/s to ft³/s.

Parameters:
xscalar | array-like | pd.Series | pd.DataFrame

Value(s) in cms.

Returns:
same type as x

Value(s) in cfs.

convert_units(values, in_unit: str, out_unit: str)[source]

Convert array-like / pandas objects between units. Fast custom paths for EC↔PSU@25C, temperature, cfs↔cms, ft↔m; else Pint-backed.

Parameters:
valuesarray-like | pd.Series | pd.DataFrame
in_unit, out_unitstr

Unit strings. Shorthands like ‘cfs’,’cms’,’ft3/s’,’μS/cm’,’deg F’ accepted.

Returns:
Same type as values, converted.
ec_psu_25c(ec, hill_correction=True)[source]

Convert electrical conductivity (EC, μS/cm) to practical salinity (PSU) at 25 °C.

This implements the empirical relationship used for estuarine work, with an optional Hill correction that improves behavior at low salinities.

Parameters:
ecarray-like or scalar

Electrical conductivity in μS/cm.

hill_correctionbool, default True

Apply Hill low-salinity correction.

Returns:
ndarray or scalar

Practical salinity (PSU). For negative EC inputs: - scalar input → returns NaN - array input → returns NaN at those positions

Notes

  • Assumes temperature is 25 °C.

  • Negative EC values are internally floored to a small positive ratio for computation (R=1e-4); those outputs are then set to NaN on array paths (or NaN returned for scalar paths).

fahrenheit_to_celsius(x)[source]

Convert °F to °C.

Parameters:
xscalar | array-like | pd.Series | pd.DataFrame

Value(s) in degrees F.

Returns:
same type as x

Value(s) in degrees celsius.

ft_to_m(x)[source]

Convert feet to metres.

Parameters:
xscalar | array-like | pd.Series | pd.DataFrame

Value(s) in feet.

Returns:
same type as x

Value(s) in meters.

m_to_ft(x)[source]

Convert metres to feet.

Parameters:
xscalar | array-like | pd.Series | pd.DataFrame

Value(s) in metres.

Returns:
same type as x

Value(s) in feet.

psu_ec_25c(psu, refine=True, hill_correction=True)[source]

Convert practical salinity (PSU) to EC (μS/cm) at 25 °C (vectorized).

Parameters:
psuarray-like or scalar

Practical salinity value(s).

refinebool, default True

Use root finding via psu_ec_25c_scalar() for accuracy.

hill_correctionbool, default True

See psu_ec_25c_scalar().

Returns:
ndarray or scalar

EC in μS/cm. Scalar input returns a scalar; array-like input returns a NumPy array of the same shape.

psu_ec_25c_scalar(psu, refine=True, hill_correction=True)[source]

Convert practical salinity (PSU) to EC (μS/cm) at 25 °C for a scalar value.

Parameters:
psufloat

Practical salinity. Must be non-negative and ≤ ~35 for oceanic cases (a hard check is enforced near sea salinity when refine is True).

refinebool, default True

If True, use a scalar root finder (Brent) to invert the EC→PSU mapping accurately. If False, use a closed-form Schemel-style polynomial approximation.

hill_correctionbool, default True

Only meaningful with refine=True; raises if refine=False and hill_correction=True.

Returns:
float

Electrical conductivity (μS/cm).

Raises:
ValueError

If psu < 0, if psu exceeds the sea-salinity cap in refine mode, or if an invalid combination of refine/hill_correction is requested.

Notes

  • The refinement typically converges in ~4–6 iterations.

  • The non-refined polynomial is faster but can drift on round trips (EC→PSU→EC).

psu_ec_resid(x, psu, hill_correction)[source]

Module contents