-
Notifications
You must be signed in to change notification settings - Fork 814
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix/ts gaps #1265
Merged
Merged
Fix/ts gaps #1265
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
1cfa030
first version of TimeSeries.gaps fix
madtoinou 8c67497
correcting bug in gaps, propagated new argument to methods calling gaps
madtoinou a6572f6
added tests to cover the new argument of the gaps function
madtoinou 492558e
corrected code and documentation according to reviewers comments
madtoinou 7cdc2be
fixed typos in documentation
madtoinou 94a9ea9
Merge branch 'master' into fix/ts-gaps
madtoinou 536dffb
Merge branch 'master' into fix/ts-gaps
madtoinou File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -35,7 +35,7 @@ | |
import pickle | ||
from collections import defaultdict | ||
from inspect import signature | ||
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union | ||
from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Tuple, Union | ||
|
||
import matplotlib.pyplot as plt | ||
import numpy as np | ||
|
@@ -1857,23 +1857,39 @@ def concatenate( | |
============= | ||
""" | ||
|
||
def gaps(self) -> pd.DataFrame: | ||
def gaps(self, mode: Literal["all", "any"] = "all") -> pd.DataFrame: | ||
""" | ||
A function to compute and return gaps in the TimeSeries. | ||
Works only on deterministic time series. | ||
A function to compute and return gaps in the TimeSeries. Works only on deterministic time series (1 sample). | ||
|
||
Parameters | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
---------- | ||
mode | ||
Only relevant for multivariate time series. The mode defines how gaps are defined. Set to | ||
'any' if a NaN value in any columns should be considered as as gaps. 'all' will only | ||
consider periods where all columns' values are NaN. Defaults to 'all'. | ||
|
||
Returns | ||
------- | ||
pd.DataFrame | ||
A dataframe containing a row for every gap (rows with all-NaN values in underlying DataFrame) | ||
A pandas.DataFrame containing a row for every gap (rows with all-NaN values in underlying DataFrame) | ||
in this time series. The DataFrame contains three columns that include the start and end time stamps | ||
of the gap and the integer length of the gap (in `self.freq` units if the series is indexed | ||
by a DatetimeIndex). | ||
""" | ||
|
||
df = self.pd_dataframe() | ||
|
||
is_nan_series = df.isna().all(axis=1).astype(int) | ||
if mode == "all": | ||
is_nan_series = df.isna().all(axis=1).astype(int) | ||
elif mode == "any": | ||
is_nan_series = df.isna().any(axis=1).astype(int) | ||
else: | ||
raise_log( | ||
ValueError( | ||
f"Keyword mode accepts only 'any' or 'all'. Provided {mode}" | ||
), | ||
logger, | ||
) | ||
diff = pd.Series(np.diff(is_nan_series.values), index=is_nan_series.index[:-1]) | ||
gap_starts = diff[diff == 1].index + self._freq | ||
gap_ends = diff[diff == -1].index | ||
|
@@ -1883,21 +1899,25 @@ def gaps(self) -> pd.DataFrame: | |
if is_nan_series.iloc[-1] == 1: | ||
gap_ends = gap_ends.insert(len(gap_ends), self.end_time()) | ||
|
||
gap_df = pd.DataFrame() | ||
gap_df["gap_start"] = gap_starts | ||
gap_df["gap_end"] = gap_ends | ||
gap_df = pd.DataFrame(columns=["gap_start", "gap_end"]) | ||
|
||
def intvl(start, end): | ||
if self._has_datetime_index: | ||
return pd.date_range(start=start, end=end, freq=self._freq).size | ||
else: | ||
return int((end - start) / self._freq) + 1 | ||
if gap_starts.size == 0: | ||
return gap_df | ||
else: | ||
|
||
gap_df["gap_size"] = gap_df.apply( | ||
lambda row: intvl(start=row.gap_start, end=row.gap_end), axis=1 | ||
) | ||
def intvl(start, end): | ||
if self._has_datetime_index: | ||
return pd.date_range(start=start, end=end, freq=self._freq).size | ||
else: | ||
return int((end - start) / self._freq) + 1 | ||
|
||
gap_df["gap_start"] = gap_starts | ||
gap_df["gap_end"] = gap_ends | ||
gap_df["gap_size"] = gap_df.apply( | ||
lambda row: intvl(start=row.gap_start, end=row.gap_end), axis=1 | ||
) | ||
|
||
return gap_df | ||
return gap_df | ||
|
||
def copy(self) -> "TimeSeries": | ||
""" | ||
|
@@ -2278,22 +2298,37 @@ def strip(self) -> "TimeSeries": | |
new_series, static_covariates=self.static_covariates | ||
) | ||
|
||
def longest_contiguous_slice(self, max_gap_size: int = 0) -> "TimeSeries": | ||
def longest_contiguous_slice( | ||
self, max_gap_size: int = 0, mode: str = "all" | ||
) -> "TimeSeries": | ||
""" | ||
Return the largest TimeSeries slice of this deterministic series that contains no gaps | ||
(contiguous all-NaN values) larger than `max_gap_size`. | ||
|
||
This method is only applicable to deterministic series (i.e., having 1 sample). | ||
|
||
Parameters | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please keep the empty lines above "Parameters" |
||
---------- | ||
max_gap_size | ||
Indicate the maximum gap size that the TimeSerie can contain | ||
mode | ||
Only relevant for multivariate time series. The mode defines how gaps are defined. Set to | ||
'any' if a NaN value in any columns should be considered as as gaps. 'all' will only | ||
consider periods where all columns' values are NaN. Defaults to 'all'. | ||
|
||
Returns | ||
------- | ||
TimeSeries | ||
a new series constituting the largest slice of the original with no or bounded gaps | ||
|
||
See Also | ||
-------- | ||
TimeSeries.gaps : return the gaps in the TimeSeries | ||
""" | ||
if not (np.isnan(self._xa)).any(): | ||
return self.copy() | ||
stripped_series = self.strip() | ||
gaps = stripped_series.gaps() | ||
gaps = stripped_series.gaps(mode=mode) | ||
relevant_gaps = gaps[gaps["gap_size"] > max_gap_size] | ||
|
||
curr_slice_start = stripped_series.start_time() | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
cool, thanks for these tests!