Polars¶
flowcean.polars provides dataframe environments, dataset splitting, time-series transforms, and baseline learners.
See environments and transforms for usage concepts.
polars
¶
Attributes¶
Classes¶
DummyLearner
¶
Bases: SupervisedLearner, SupervisedIncrementalLearner
Dummy learner that learns nothing.
This learner is useful for testing purposes.
Methods:¶
DummyModel
¶
DataFrame
¶
Bases: OfflineEnvironment
A dataset environment.
This environment represents static tabular datasets.
Attributes:
| Name | Type | Description |
|---|---|---|
data |
LazyFrame
|
The data to represent. |
Initialize the dataset environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame | LazyFrame
|
The data to represent. |
required |
Attributes¶
Methods:¶
to_incremental
¶
to_incremental(batch_size: int = 1) -> StreamingOfflineEnvironment
Convert the DataFrame to an incremental environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
The size of each batch. Defaults to 1. |
1
|
from_csv
classmethod
¶
Load a dataset from a CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to the CSV file. |
required |
separator
|
str
|
Value separator. Defaults to ",". |
','
|
from_json
classmethod
¶
Load a dataset from a JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to the JSON file. |
required |
from_parquet
classmethod
¶
Load a dataset from a Parquet file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to the Parquet file. |
required |
from_yaml
classmethod
¶
Load a dataset from a YAML file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the YAML file. |
required |
from_uri
classmethod
¶
Load a dataset from a URI.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
The URI to load the dataset from. |
required |
from_rosbag
classmethod
¶
from_rosbag(path: str | PathLike[str], topics: dict[str, list[str]], *, message_paths: Iterable[str | PathLike[str]] | None = None, cache: bool = True, cache_path: str | PathLike[str] | None = None) -> Self
Load a dataset from a ROS2 Humble rosbag file.
The structure of the data is inferred from the message definitions. If a message definition is not found in the ROS2 Humble typestore, it is added from the provided paths. Once all the message definitions are added, the data is loaded from the rosbag file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to the rosbag. |
required |
topics
|
dict[str, list[str]]
|
Dictionary of topics to load ( |
required |
message_paths
|
Iterable[str | PathLike[str]] | None
|
List of paths to additional message definitions. |
None
|
cache
|
bool
|
Whether to cache the data to a Parquet file. |
True
|
cache_path
|
str | PathLike[str] | None
|
Path to the cache file. If None, defaults to the same directory as the rosbag file with a .parquet extension. |
None
|
InvalidUriSchemeError
¶
Bases: Exception
Exception raised when an URI scheme is invalid.
Initialize the InvalidUriSchemeError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scheme
|
str
|
Invalid URI scheme. |
required |
UnsupportedFileTypeError
¶
Bases: Exception
Exception raised when a file type is not supported.
Initialize the UnsupportedFileTypeError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
suffix
|
str
|
File type suffix. |
required |
DatasetPredictionEnvironment
¶
DatasetPredictionEnvironment(environment: DataFrame, batch_size: int)
Bases: ActiveEnvironment
Dataset prediction environment.
Initialize the dataset prediction environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
environment
|
DataFrame
|
The dataset to use for prediction. |
required |
batch_size
|
int
|
The batch size of the prediction. |
required |
JoinedOfflineEnvironment
¶
JoinedOfflineEnvironment(environments: Iterable[OfflineEnvironment])
Bases: OfflineEnvironment
Environment that joins multiple offline environments.
Attributes:
| Name | Type | Description |
|---|---|---|
environments |
Iterable[OfflineEnvironment]
|
The offline environments to join. |
Initialize the joined offline environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
environments
|
Iterable[OfflineEnvironment]
|
The offline environments to join. |
required |
Attributes¶
StreamingOfflineEnvironment
¶
StreamingOfflineEnvironment(environment: OfflineEnvironment, batch_size: int, *, size: int | None = None)
Bases: IncrementalEnvironment
Streaming offline environment.
This environment streams data from an offline environment in batches.
Initialize the streaming offline environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
environment
|
OfflineEnvironment
|
The offline environment to stream. |
required |
batch_size
|
int
|
The batch size of the streaming environment. |
required |
size
|
int | None
|
The number of samples in the environment. If provided, the number of steps will be calculated based on this value. |
None
|
TrainTestSplit
¶
Split data into train and test sets.
Initialize the train-test splitter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ratio
|
float
|
The ratio of the data to put in the training set. |
required |
shuffle
|
bool
|
Whether to shuffle the data before splitting. |
False
|
Attributes¶
Methods:¶
split
¶
split(environment: OfflineEnvironment) -> tuple[DataFrame, DataFrame]
Split the data into train and test sets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
environment
|
OfflineEnvironment
|
The environment to split. |
required |
LazyMixin
¶
SelectMixin
¶
Cast
¶
Cast(target_type: PolarsDataType | dict[str, PolarsDataType], *, features: Iterable[str] | None = None)
Bases: Transform
Cast features to a different datatype.
This transform allows to change the datatype of features in a DataFrame.
To cast all features to the same datatype, provide a single type as the
target_type argument e.g.
By specifying the features keyword argument, only the selected features
will be cast e.g.
Lastly, to cast features to different datatypes, provide a dictionary with feature names as keys and target types as values e.g.
Initializes the Cast transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_type
|
PolarsDataType | dict[str, PolarsDataType]
|
Type to which the features will be cast.
If a single type is provided, all features or those provided in
the |
required |
features
|
Iterable[str] | None
|
The features to cast. If |
None
|
Cluster
¶
Cluster(clusterer: Clusterer, *, cluster_feature_name: str = 'cluster_label', features: Iterable[str] | None = None)
Bases: Transform
Cluster data using a clustering algorithm.
This transform allows to cluster data using a specified clustering algorithm. The resulting cluster label is added as a new feature to the DataFrame.
Initializes the Cluster transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
clusterer
|
Clusterer
|
The clustering algorithm to use. |
required |
cluster_feature_name
|
str
|
The name of the feature to store the cluster labels. |
'cluster_label'
|
features
|
Iterable[str] | None
|
The features to use for clustering. If None, all features are used. |
None
|
DiscreteDerivative
¶
DiscreteDerivative(features: str | Iterable[str], *, method: DiscreteDerivativeKind = 'central', derivative_suffix: str = '_derivative')
Bases: Transform
Calculates the discrete derivative of time series features.
Calculates the discrete derivative of time series features using either forward, backward, or central differences.
Initializes the DiscreteDerivative transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
str | Iterable[str]
|
Features that shall be differentiated. Result features
will be named |
required |
method
|
DiscreteDerivativeKind
|
Method to use for calculating the derivative. Valid options are "forward", "backward", and "central". Defaults to "central". |
'central'
|
derivative_suffix
|
str
|
Suffix to append to the feature name for the resulting derivative feature. Defaults to "_derivative". |
'_derivative'
|
Drop
¶
Explode
¶
Bases: Transform
This wraps the explode method of Polars.
Reference: https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.explode.html#polars.DataFrame.explode
If features is None, all columns will be exploded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
list[str] | None
|
List of features to explode. |
None
|
ExplodeTimeSeries
¶
Bases: Transform
Transform that explodes nested time series data into individual rows.
Each time series is represented as a list of structs, where each struct
contains a timestamp and a value. The value is itself a struct
holding multiple feature values at that timestamp. This transform expands
the list into separate rows, then unnests the nested structs into columns.
Example
Input DataFrame: ┌─────┬────────────────────────────────────────┐ │ id │ series │ │ --- │ --- │ │ i64 │ list[struct[timestamp: str, value]] │ ├─────┼────────────────────────────────────────┤ │ 1 │ [{t1, {a=1, b=10}}, {t2, {a=2, b=20}}] │ │ 2 │ [{t3, {a=3, b=30}}, {t4, {a=4, b=40}}] │ └─────┴────────────────────────────────────────┘
After applying ExplodeTimeSeries("series"):
┌─────┬────────────┬─────┬─────┐
│ id │ timestamp │ a │ b │
│ --- │ --- │ --- │ --- │
│ i64 │ str │ i64 │ i64 │
├─────┼────────────┼─────┼─────┤
│ 1 │ t1 │ 1 │ 10 │
│ 1 │ t2 │ 2 │ 20 │
│ 2 │ t3 │ 3 │ 30 │
│ 2 │ t4 │ 4 │ 40 │
└─────┴────────────┴─────┴─────┘
CollectionExpr
¶
CollectionExpr(expressions: str | FilterExpr | Iterable[str | FilterExpr])
Bases: FilterExpr
Attributes¶
expr_collection
instance-attribute
¶
expr_collection: Iterable[Expr] = (expression() if isinstance(expression, FilterExpr) else _str_to_pl(expression) for expression in expressions)
Filter
¶
Filter(expression: str | FilterExpr)
Bases: Transform
Filter an environment based on one or multiple expressions.
This transform allows to filter an environment based on or multiple boolean expressions. Assuming the input environment is given by
| t | N | x |
|---|---|---|
| 1 | 10 | 0 |
| 2 | 12 | 1 |
| 3 | 5 | 2 |
| 4 | 15 | 1 |
| 5 | 17 | 0 |
The following transformation can be used to filter the environment so that
the result contains only records where x=1:
The result dataset after applying the transform will be
| t | N | x |
|---|---|---|
| 2 | 15 | 1 |
| 4 | 12 | 1 |
To only get records where x=1 and t > 3 the filter expression
can be used.
To filter all records where x=1 and t > 3 or N < 15 use
Initializes the Filter transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expression
|
str | FilterExpr
|
String or filter expression used to filter the environment. Records that do not match the expression are discarded. Standard comparison and mathematical operations are supported within the expressions. Features can be accessed by there name. |
required |
FilterExpr
¶
Not
¶
Not(expression: str | FilterExpr)
Bases: FilterExpr
Attributes¶
expression
instance-attribute
¶
expression: Expr = expression() if isinstance(expression, FilterExpr) else _str_to_pl(expression)
Methods:¶
First
¶
Bases: Transform
Selects the first time value of a time-series feature.
Initializes the First transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
str | Iterable[str]
|
The features to apply this transform to. |
required |
replace
|
bool
|
Whether to replace the original features with the
transformed ones. If set to False, the default, the value will
be added as a new feature named |
False
|
FeatureLengthVaryError
¶
Bases: Exception
Length of a feature varies over different rows.
Flatten
¶
Bases: Transform
Flatten all time series in a DataFrame to individual features.
The given DataFrame's time series are converted into individual features, with each time step creating a new feature. This transform will change the order of the columns in the resulting dataset.
For example the dataset
| series_data | A | B |
|---|---|---|
| {[0, 0], [1, 1], [2, 2]} | 42 | 43 |
| {[0, 3], [1, 4], [2, 5]} | 44 | 45 |
gets flattened into the dataset
| series_data_0 | series_data_1 | series_data_2 | A | B |
|---|---|---|---|---|
| 0 | 1 | 2 | 42 | 43 |
| 3 | 4 | 5 | 42 | 43 |
Initialize the flatten transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
Iterable[str] | None
|
The features to flatten. If not provided or set to None, all possible features from the given dataframe will be flattened. |
None
|
NoTimeSeriesFeatureError
¶
Bases: Exception
Feature is no time series.
Lambda
¶
Bases: Transform
Apply a custom function to the data of an environment.
Initializes the Lambda transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[[LazyFrame], LazyFrame]
|
Function handle to be applied to the data. |
required |
Last
¶
Bases: Transform
Selects the last time value of a time-series feature.
Initializes the Last transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
str | Iterable[str]
|
The features to apply this transform to. |
required |
replace
|
bool
|
Whether to replace the original features with the
transformed ones. If set to False, the default, the value will
be added as a new feature named |
False
|
FeatureNotFoundError
¶
Bases: Exception
Feature not found in the DataFrame.
This exception is raised when a feature is not found in the DataFrame.
MatchSamplingRate
¶
MatchSamplingRate(reference_feature_name: str, feature_interpolation_map: dict[str, MatchSamplingRateMethod] | None = None, fill_strategy: FillStrategy = 'both_ways')
Bases: Transform
Matches the sampling rate of all time series in the DataFrame.
Interpolates the time series to match the sampling rate of the reference
time series. The feature_interpolation_map parameter is a dictionary that
specifies the interpolation method for each feature. The keys are
the feature names, and the values are the interpolation methods.
The interpolation method can be 'linear' or 'nearest'. If the
feature_interpolation_map parameter is not provided, all features
except the reference feature will be interpolated using the
'nearest' method. The fill_strategy parameter specifies the
strategy to fill missing values after interpolation. The default
value is 'both_ways', which means that missing values will be
filled using both forward and backward filling. Other options
include 'forward', 'backward', 'min', 'max', 'mean', 'zero', and
'one'.The below example shows the usage of a MatchSamplingRate
transform in a run.py file. Assuming the loaded data is
represented by the table:
| feature_a | feature_b | const |
| --- | --- | --- |
| list[struct[time,struct[]]] | list[struct[time,struct[]]] | int |
| --------------------------- | --------------------------- | ----- |
| [{12:26:01.0, {1.2}}, | [{12:26:00.0, {1.0}}, | 1 |
| {12:26:02.0, {2.4}}, | {12:26:05.0, {2.0}}] | |
| {12:26:03.0, {3.6}}, | | |
| {12:26:04.0, {4.8}}] | | |
The following transform can be used to match the sampling rate
of the time series feature_b to the sampling rate
of the time series feature_a.
...
environment.load()
data = environment.get_data()
transform = MatchSamplingRate(
reference_feature_name="feature_a",
feature_interpolation_map={
"feature_b": "linear",
},
)
transformed_data = transform.transform(data)
...
The resulting Dataframe after the transform is:
| feature_a | feature_b | const |
| --- | --- | --- |
| list[struct[time,struct[]]] | list[struct[time,struct[]]] | int |
| --------------------------- | --------------------------- | ----- |
| [{12:26:00.0, {1.2}}, | [{12:26:00.0, {1.2}}, | 1 |
| {12:26:01.0, {2.4}}, | {12:26:01.0, {1.4}}, | |
| {12:26:02.0, {3.6}}, | {12:26:02.0, {1.6}}, | |
| {12:26:03.0, {4.8}}] | {12:26:03.0, {1.8}}] | |
Initialize the transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reference_feature_name
|
str
|
Reference timeseries feature. |
required |
feature_interpolation_map
|
dict[str, MatchSamplingRateMethod] | None
|
Key-value pairs of the timeseries features that are targeted in interpolation columns and the interpolation method to use. The interpolation method can be 'linear' or 'nearest'. |
None
|
fill_strategy
|
FillStrategy
|
Strategy to fill missing values after interpolation. |
'both_ways'
|
Mean
¶
Bases: Transform
Replaces time-series features with their mean value.
Initializes the Mean transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
str | Iterable[str]
|
The feature or features the mean should be calculated for. |
required |
replace
|
bool
|
Whether to replace the original features with the
transformed ones. If set to False, the default, the value will
be added as a new feature named |
False
|
Median
¶
Bases: Transform
Replaces time-series features with their median value.
Initializes the Median transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
str | Iterable[str]
|
The feature or features the median should be calculated for. |
required |
replace
|
bool
|
Whether to replace the original features with the
transformed ones. If set to False, the default, the value will
be added as a new feature named |
False
|
Mode
¶
Bases: Transform
Mode finds the value that appears most often in time-series features.
Initializes the Mode transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
str | Iterable[str]
|
The features to apply this transform to. |
required |
replace
|
bool
|
Whether to replace the original features with the
transformed ones. If set to False, the default, the value will
be added as a new feature named |
False
|
OneCold
¶
Bases: Transform
Transforms integer features into a set of binary one-cold features.
Transforms integer features into a set of binary one-cold features. The original integer features are dropped and are not part of the resulting data frame.
As an example consider the following data
| feature |
|---|
| 0 |
| 1 |
| 2 |
| 1 |
| 5 |
When the one-cold transformation is applied, the result is as follows
| feature_0 | feature_1 | feature_2 | feature_5 |
|---|---|---|---|
| 0 | 1 | 1 | 1 |
| 1 | 0 | 1 | 1 |
| 1 | 1 | 0 | 1 |
| 1 | 0 | 1 | 1 |
| 1 | 1 | 1 | 0 |
In the default configuration missing categories are ignored. Their respective entries will all be one. If you however want to enforce that each data entry belongs to a certain category, you can set the check_for_missing_categories flag to true when constructing a One-Cold transform. In that case if an unknown value is found which does not belong to any category, a NoMatchingCategoryError is thrown. This however has an impact on the performance and will slow down the transform.
If you want to enable this check, create the transform as follows:
python
transform = OneCold(
feature_categories={
"feature": [0, 1, 2, 5]
},
check_for_missing_categories=True
)
Initializes the One-Hot transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
feature_categories
|
dict[str, list[Any]]
|
Dictionary of features and a list of categorical values to encode for each. |
required |
check_for_missing_categories
|
bool
|
If set to true, a check is performed to see if all values belong to a category. If an unknown value is found which does not belong to any category, a NoMatchingCategoryError is thrown. To perform this check, the dataframe must be materialised, resulting in a potential performance decrease. Therefore it defaults to false. |
False
|
Attributes¶
feature_category_mapping
instance-attribute
¶
feature_category_mapping: dict[str, dict[str, Any]] = {feature: {f'{feature}_{value}': value for value in values} for feature, values in feature_categories.items()}
check_for_missing_categories
instance-attribute
¶
Methods:¶
apply
¶
Transform data with this one hot transformation.
Transform data with this one hot transformation and return the resulting dataframe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
LazyFrame
|
The data to transform. |
required |
Returns:
| Type | Description |
|---|---|
LazyFrame
|
The transformed data. |
from_dataframe
classmethod
¶
from_dataframe(data: DataFrame, features: Iterable[str], *, check_for_missing_categories: bool = False) -> Self
Creates a new one-hot transformation based on sample data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
A dataframe containing sample data for determining the categories of the transform. |
required |
features
|
Iterable[str]
|
Name of the features for which the one hot transformation will determine the categories. |
required |
check_for_missing_categories
|
bool
|
If set to true, a check is performed to see if all values belong to a category. If an unknown value is found which does not belong to any category, a NoMatchingCategoryError is thrown. To perform this check, the dataframe must be materialised, resulting in a potential performance decrease. Therefore it defaults to false. |
False
|
NoCategoriesError
¶
Bases: Exception
NoMatchingCategoryError
¶
Bases: Exception
OneHot
¶
Bases: Transform
Transforms integer features into a set of binary one-hot features.
Transforms integer features into a set of binary one-hot features. The original integer features are dropped and are not part of the resulting data frame.
As an example consider the following data
| feature |
|---|
| 0 |
| 1 |
| 2 |
| 1 |
| 5 |
When the one-hot transformation is applied, the result is as follows
| feature_0 | feature_1 | feature_2 | feature_5 |
|---|---|---|---|
| 1 | 0 | 0 | 0 |
| 0 | 1 | 0 | 0 |
| 0 | 0 | 1 | 0 |
| 0 | 1 | 0 | 0 |
| 0 | 0 | 0 | 1 |
Initializes the One-Hot transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
feature_categories
|
dict[str, list[Any]]
|
Dictionary of features and a list of categorical values to encode for each. |
required |
check_for_missing_categories
|
bool
|
If set to true, a check is performed to see if all values belong to a category. If an unknown value is found which does not belong to any category, a NoMatchingCategoryError is thrown. To perform this check, the dataframe must be materialised, resulting in a potential performance decrease. Therefore it defaults to false. |
False
|
Attributes¶
feature_category_mapping
instance-attribute
¶
feature_category_mapping: dict[str, dict[str, Any]] = {feature: {f'{feature}_{value}': value for value in values} for feature, values in feature_categories.items()}
check_for_missing_categories
instance-attribute
¶
Methods:¶
apply
¶
Transform data with this one hot transformation.
Transform data with this one hot transformation and return the resulting dataframe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
LazyFrame
|
The data to transform. |
required |
Returns:
| Type | Description |
|---|---|
LazyFrame
|
The transformed data. |
from_dataframe
classmethod
¶
from_dataframe(data: LazyFrame, features: Iterable[str], *, check_for_missing_categories: bool = False) -> Self
Creates a new one-hot transformation based on sample data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
LazyFrame
|
A dataframe containing sample data for determining the categories of the transform. |
required |
features
|
Iterable[str]
|
Name of the features for which the one hot transformation will determine the categories. |
required |
check_for_missing_categories
|
bool
|
If set to true, a check is performed to see if all values belong to a category. If an unknown value is found which does not belong to any category, a NoMatchingCategoryError is thrown. To perform this check, the dataframe must be materialised, resulting in a potential performance decrease. Therefore it defaults to false. |
False
|
Pad
¶
Bases: Transform
Pad time-series features to the specified length.
Pad time-series features to the specified end-time by holding their last
value for one more sample.
This is useful for ensuring that all time-series features cover at least a
time interval of the specified length. Time-series that are already longer
than the specified will not be modified.
The resulting features will not be equidistant in time. To achieve
equidistant time-series, consider using the Resample transform after
padding.
Initializes the Pad transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
length
|
float
|
The length (time) to pad the features to. This is the minimum length that the features will have after applying this transform. |
required |
features
|
str | Iterable[str] | None
|
The features to apply this transform to. Defaults to
|
None
|
Rename
¶
Bases: Transform
Rename features in an environment.
Initializes the Rename transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
dict[str, str]
|
Key value pairs that map from the old feature name to the new one. |
required |
Resample
¶
Resample(sampling_rate: float | dict[str, float], *, interpolation_method: InterpolationMethod = 'linear')
Bases: Transform
Resample time series features to a given sampling rate.
Initializes the Resample transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sampling_rate
|
float | dict[str, float]
|
Target sampling rate for time series features. If a float is provided, all possible time series features will be resampled. Alternatively, a dictionary can be provided where the key is the feature and the value is the target sample rate. |
required |
interpolation_method
|
InterpolationMethod
|
The interpolation method to use. Supported are "linear" and "cubic", with the default being "linear". |
'linear'
|
ScaleToRange
dataclass
¶
ScaleToRange(*, features: list[str] | None = None, lower_range: float = -1.0, upper_range: float = 1.0)
Bases: Invertible, Transform
Scale features to a fixed range using a linear mapping.
A sample \(x\) is scaled as:
where
- \(m\) is the scaling factor
- \(b\) is the offset.
When instantiating this transform directly, the scaling factor \(m\) and
offset \(b\) for each feature are calculated during training from the data.
To specify the scaling factor \(m\) and offset \(b\) directly, use the
from_limits method.
Attributes:
| Name | Type | Description |
|---|---|---|
m |
dict[str, float] | None
|
The scaling factor \(m\) of each feature. |
b |
dict[str, float] | None
|
The offset \(b\) of each feature. |
Attributes¶
Methods:¶
from_limits
classmethod
¶
from_limits(feature_limits: dict[str, tuple[float, float]], *, lower_range: float = -1.0, upper_range: float = 1.0) -> Self
Creates a new ScaleToRange transform based on the given limits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
feature_limits
|
dict[str, tuple[float, float]]
|
A dictionary mapping each features name to its (min_value, max_value) tuple. |
required |
lower_range
|
float
|
The lower bound of the range to scale to. |
-1.0
|
upper_range
|
float
|
The upper bound of the range to scale to. |
1.0
|
Select
¶
Bases: Transform
Selects a subset of features from the data.
Initializes the Select transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
IntoExpr | Iterable[IntoExpr]
|
The features to select. Treats the selection as a
parameter to polars |
required |
SignalFilter
¶
SignalFilter(features: Iterable[str], filter_type: SignalFilterType, filter_frequency: float, *, order: int = 5)
Bases: Transform
Applies a Butterworth filter to time series features.
Applies a Butterworth lowpass or highpass filter to time series features. For this transform to work, the time series must already have a uniform sampling rate. Use a `Resample' transform to uniformly sample the points of a time series.
Initializes the Filter transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
Iterable[str]
|
Features that shall be filtered. |
required |
filter_type
|
SignalFilterType
|
Type of the filter to apply. Valid options are "lowpass" and "highpass". |
required |
filter_frequency
|
float
|
Characteristic frequency of the filter in Hz. For high- and lowpass this is the cutoff frequency. |
required |
order
|
int
|
Order of the Butterworth filter to uses. Defaults to 5. |
5
|
SliceTimeSeries
¶
Bases: Transform
Slices a time series at given slice points.
The transform takes two columns as input: 'time_series' and 'slice_points.' The 'time_series' column is sliced at the points specified by the 'time' entry of the 'slice_points' column. The result is a new time series column where each entry contains only the values from the original time series that fall between the specified slice points.
Suppose you have a dataframe with a single line entry as follows:
| time_series | slice_points |
|---|---|
| [(00:00:03, 1), | [(00:00:05, 0), |
| (00:00:04, 2), | (00:00:08, 1)] |
| (00:00:06, 7), | |
| (00:00:09, 0)] |
Applying the slice time series transform results in a multi-line dataframe, where each line corresponds to a slice point:
| time_series | slice_points |
|---|---|
| [(00:00:03, 1), | [(00:00:05, 0)] |
| (00:00:04, 2)] | |
| [(00:00:06, 7)] | [(00:00:08, 1)] |
The transform operates line-wise, meaning that each line in the input dataframe is processed independently. The resulting dataframe will have multiple lines depending on the number of slice points specified in each line.
Initialize the SliceTimeSeries transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time_series
|
str
|
the time series column to slice. |
required |
slice_points
|
str
|
the column that specifies the slice points. |
required |
SlidingWindow
¶
Bases: Transform
Transforms the data with a sliding window.
The sliding window transform transforms the data by creating a sliding window over the row dimension. The data is then transformed by creating a new column for each column in the original data. The new columns are named by appending the index of the row in the sliding window to the original column name. As an example, consider the following data:
| x | y | z |
|---|---|---|
| 1 | 10 | 100 |
| 2 | 20 | 200 |
| 3 | 30 | 300 |
| 4 | 40 | 400 |
| 5 | 50 | 500 |
If we apply a sliding window with a window size of 3, we get the following
| x_0 | y_0 | z_0 | x_1 | y_1 | z_1 | x_2 | y_2 | z_2 |
|---|---|---|---|---|---|---|---|---|
| 1 | 10 | 100 | 2 | 20 | 200 | 3 | 30 | 300 |
| 2 | 20 | 200 | 3 | 30 | 300 | 4 | 40 | 400 |
| 3 | 30 | 300 | 4 | 40 | 400 | 5 | 50 | 500 |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window_size
|
int
|
size of the sliding window. |
required |
TimeSeriesSlidingWindow
¶
TimeSeriesSlidingWindow(window_size: int, *, features: str | Iterable[str] | None = None, stride: int = 1, rechunk: bool = True)
Bases: Transform
Convert single large time series into a set of smaller sub-series.
Applies a sliding window to each individual time series sample of all or
selected time series features while leaving other features unchanged.
As a result, the resulting data frame will contain multiple samples for
each original sample, where each sample is a sub-series of the original
time series. The number of features (columns) will remain the same.
For this transform to work, all selected time series features of a sample
must have the same time vector. Use a MatchSamplingRate or Resample
transform to ensure this is the case.
Initializes the TimeSeriesSlidingWindow transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window_size
|
int
|
The size of the sliding window. |
required |
features
|
str | Iterable[str] | None
|
The features to apply the sliding window to. If None, all time series features are selected. |
None
|
stride
|
int
|
The stride of the sliding window. |
1
|
rechunk
|
bool
|
Whether to rechunk the data after applying the transform. Rechunking improves performance of subsequent operations, but increases memory usage and may slow down the initial operation. |
True
|
Standardize
dataclass
¶
Bases: Invertible, Transform
Standardize features by removing the mean and scaling to unit variance.
A sample \(x\) is standardized as:
where
- \(\mu\) is the mean of the samples
- \(\sigma\) is the standard deviation of the samples.
Attributes:
| Name | Type | Description |
|---|---|---|
mean |
dict[str, float] | None
|
The mean \(\mu\) of each feature. |
std |
dict[str, float] | None
|
The standard deviation \(\sigma\) of each feature. |
TimeWindow
¶
TimeWindow(*, features: Iterable[str] | None = None, time_start: float = 0.0, time_end: float = inf)
Bases: Transform
Limit time series to a certain time window.
Initializes the TimeWindow transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
Iterable[str] | None
|
The features to apply this transformation to. If |
None
|
time_start
|
float
|
Window start time. Defaults to zero. All data before this time will be removed from the time series when applying the transform. |
0.0
|
time_end
|
float
|
Window end time. Defaults to infinite. All data after this time will be removed from the time series when applying the transform. |
inf
|
ToTimeSeries
¶
Unnest
¶
Bases: Transform
Decompose struct columns into separate columns for each field.
Example:
data_frame = pl.Series(
"c",
[
{"a": 1, "t": 1},
{"a": 4, "t": 2},
{"a": 7, "t": 3},
{"a": 10, "t": 4},
{"a": 15, "t": 5},
],
).to_frame()
Initializes the Unnest transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
ColumnNameOrSelector | Collection[ColumnNameOrSelector]
|
The features to unnest. Treats the selection as a
parameter to polars |
required |
ZeroOrderHold
¶
Bases: Transform
Aligns multiple time series features using zero-order-hold.
Initialize the ZeroOrderHoldMatching transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
list[str]
|
List of topics to align. |
required |
name
|
str
|
Name of the output time series feature. |
'aligned'
|
drop
|
bool
|
Whether to drop the original features after alignment. |
True
|
Functions:¶
collect
¶
collect(environment: Iterable[LazyFrame] | Collection[LazyFrame], n: int | None = None, *, progress_bar: bool | dict[str, Any] = True) -> DataFrame
Collect data from an environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
environment
|
Iterable[LazyFrame] | Collection[LazyFrame]
|
The environment to collect data from. |
required |
n
|
int | None
|
Number of samples to collect. If None, all samples are collected. |
None
|
progress_bar
|
bool | dict[str, Any]
|
Whether to show a progress bar. If a dictionary is provided, it will be passed to the progress bar. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The collected dataset. |
is_timeseries_feature
¶
Check if the given column is a time series feature.
A time series feature contains a list of structs with fields time and value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
DataFrame | LazyFrame | Schema
|
The LazyFrame, DataFrame or schema to check. |
required |
name
|
str
|
The column to check. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the column is a time series feature, False otherwise. |