From 4ffb0252ec056729a4ee9169c9e5da0b8a1a85f7 Mon Sep 17 00:00:00 2001 From: BaptisteDE Date: Tue, 6 Jan 2026 10:25:54 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20time=5Fintegrate=20uses=20?= =?UTF-8?q?numpy=20for=20trapz.=20Also=20handle=20empty=20DataFrame?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_math.py | 12 ++++++++++++ tide/math.py | 17 ++++++++--------- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/tests/test_math.py b/tests/test_math.py index f98045e..797a29d 100644 --- a/tests/test_math.py +++ b/tests/test_math.py @@ -70,6 +70,18 @@ def test_time_integrate(self): pd.testing.assert_series_equal(ref, time_integrate(test) / 3600) + test = pd.DataFrame( + { + "cpt1": [], + "cpt2": [], + }, + index=pd.date_range("2009-01-01 00:00:00", freq="10s", periods=0, tz="UTC"), + ) + + ref = pd.Series(index=test.columns, dtype=float) + + pd.testing.assert_series_equal(ref, time_integrate(test)) + def test_aggregate_time_series(self): sim_res = pd.DataFrame( {"a": [1, 2], "b": [3, 4]}, diff --git a/tide/math.py b/tide/math.py index 1baf283..de1d187 100644 --- a/tide/math.py +++ b/tide/math.py @@ -3,7 +3,6 @@ import pandas as pd import numpy as np -from scipy import integrate from collections.abc import Callable from tide.utils import check_and_return_dt_index_df @@ -80,8 +79,8 @@ def time_gradient(data: pd.DataFrame | pd.Series) -> pd.DataFrame: def time_integrate(data: pd.DataFrame | pd.Series) -> pd.Series: """ - Perform time Integration of given time series in X DartaFrame or in a Series. - The function computes the integral of each column using `scipy.integrate.trapz` + Perform time Integration of given time series in X DataFrame or in a Series. + The function computes the integral of each column using `np.trapz` function and the time difference between consecutive data points. Parameters: @@ -92,14 +91,14 @@ def time_integrate(data: pd.DataFrame | pd.Series) -> pd.Series: """ data = check_and_return_dt_index_df(data) - chrono = (data.index - data.index[0]).to_series() - chrono = chrono.dt.total_seconds() + if data.empty: + return pd.Series(index=data.columns, dtype=float) - res_series = pd.Series(dtype="float64") - for col in data: - res_series[col] = integrate.trapezoid(data[col], chrono) + t = (data.index.view("int64") - data.index[0].value) * 1e-9 # seconds + y = data.to_numpy() + result = np.trapz(y, t, axis=0) - return res_series + return pd.Series(result, index=data.columns) def aggregate_time_series(