time_constant
TimeConstant
Bases: TimeRelatedTransformer
Transformation to create a time constant variable from a pandas series and time/sequence scenario. This transformation needs to be fitted by a referenced dates to be computed for any new data.
Example
TimeConstant(periodicity=True, values=[1,0,0,0.5]) is a transformation than generate a continuation of sequence of values every 4 periods. TimeConstant(periodicity=True, values=[1], default_value=1) is a transformation that generate a constant variable of value 1 for any period. TimeConstant(periodicity=False, values=[0,0,..,0,1,,..,1,1], default_value=1) is a transformation that generate a split with only 1 after a given date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
periodicity(bool) | True if it is a periodic sequence, False if not. | required | |
values(List[float]) | Values of the sequence. Ex: [0]*51 + [1] for a dummy at Christmas week. | required | |
default_value | Optional[float] | value set for dates out of the range time period specified by values and start_date when there is no periodicity. | None |
start_date | Optional[np.datetime64] | start_date date to identify the date when the sequence starts. Ex: np.datetime64("2018-01-01"). Optional, will be computed on fitted dates if not specified. | None |
granularity | Optional[np.timedelta64] | time period between two observations. Ex: np.timedelta64(7,'D') for weekly. Optional, will be computed on fitted dates if not specified. | None |
Attributes:
| Name | Type | Description |
|---|---|---|
periodicity(bool) | True if it is a periodic sequence, False if not. | |
values(List[float]) | Values of the sequence. Ex: [0]*51 + [1] for a dummy at Christmas week. | |
default_value | Optional[float] | default value set for dates out of the time period delimited by values. The default_value is set only if periodicity is False. |
start_date | Optional[np.datetime64] | start_date date to identify the date when the sequence starts. Ex: np.datetime64("2018-01-01"). Optional, will be computed on fitted dates if not specified. |
granularity | Optional[np.timedelta64] | time period between two observations. Ex: np.timedelta64(7,'D') for weekly. Optional, will be computed on fitted dates if not specified. |
Source code in eki_mmo_equations/time_related_transformations/time_constant.py
class TimeConstant(TimeRelatedTransformer):
"""Transformation to create a time constant variable from a pandas series and time/sequence scenario.
This transformation needs to be fitted by a referenced dates to be computed for any new data.
Example:
TimeConstant(periodicity=True, values=[1,0,0,0.5]) is a transformation than generate a
continuation of sequence of values every 4 periods.
TimeConstant(periodicity=True, values=[1], default_value=1) is a transformation that generate a constant
variable of value 1 for any period.
TimeConstant(periodicity=False, values=[0,0,..,0,1,,..,1,1], default_value=1) is a transformation that generate
a split with only 1 after a given date.
Args:
periodicity(bool): True if it is a periodic sequence, False if not.
values(List[float]): Values of the sequence. Ex: [0]*51 + [1] for a dummy at Christmas week.
default_value (Optional[float]): value set for dates out of the range time period specified
by values and start_date when there is no periodicity.
start_date (Optional[np.datetime64], optional): start_date date to identify the date when the sequence starts.
Ex: np.datetime64("2018-01-01"). Optional, will be computed on fitted dates if not specified.
granularity (Optional[np.timedelta64], optional): time period between two observations.
Ex: np.timedelta64(7,'D') for weekly. Optional, will be computed on fitted dates if not specified.
Attributes:
periodicity(bool): True if it is a periodic sequence, False if not.
values(List[float]): Values of the sequence. Ex: [0]*51 + [1] for a dummy at Christmas week.
default_value (Optional[float]): default value set for dates out of the time period delimited by values.
The default_value is set only if periodicity is False.
start_date (Optional[np.datetime64], optional): start_date date to identify the date when the sequence starts.
Ex: np.datetime64("2018-01-01"). Optional, will be computed on fitted dates if not specified.
granularity (Optional[np.timedelta64], optional): time period between two observations.
Ex: np.timedelta64(7,'D') for weekly. Optional, will be computed on fitted dates if not specified.
"""
def __init__(
self,
periodicity: bool,
values: List[float],
default_value: Optional[float] = None,
start_date: Optional[np.datetime64] = None,
granularity: Optional[np.timedelta64] = None,
) -> None:
self.periodicity: bool = periodicity
self.values: List[float] = values
self.default_value: float = default_value if default_value else 0
self.start_date: Optional[np.datetime64] = start_date if start_date else None
self.granularity: Optional[np.timedelta64] = granularity if granularity else None
@property
def parameters(self) -> Dict[str, float]:
"""Returns instant transformation parameters
Returns:
(Dict[str, float]): Instant transformation parameters
"""
return self.__dict__
# ------- METHODS -------
def fit(self, dates: npt.NDArray[np.datetime64]):
"""Fit transformation on dates by computing start_date and granularity
Args:
dates (npt.NDArray[np.datetime64]): dates to fit on
"""
seasonal_scenario = get_seasonal_scenario(dates)
self.start_date = seasonal_scenario["start_date"]
self.granularity = seasonal_scenario["granularity"]
return super().fit(dates)
def transform(self, dates: npt.NDArray[np.datetime64]) -> npt.NDArray[np.float64]:
"""Method to compute time constant value for dates
Args:
dates (npt.NDArray[np.datetime64]): dates to transform
start_date (numpy.datetime64): start_date date to identify the date when the sequence starts.
Ex: np.datetime64("2018-01-01").
granularity (np.timedelta64): time period between two observations. Ex: np.timedelta64(7,'D') for weekly.
periodicity (bool): True if it is a periodic sequence, False if not.
values (List[float]): values of the sequence. Ex: [0]*51 + [1] for a dummy at Christmas week.
default_value (float): default value set for dates out of the time period delimited by values.
Returns:
(npt.NDArray[np.float64]): computed value for each date
"""
super().transform(dates)
if not self.start_date or not self.granularity:
raise TimeConstantError("start_date and granularity must be filled")
return self._transformer(
dates, self.start_date, self.granularity, self.periodicity, self.values, self.default_value
)
# ------- TRANSFORMERS -------
@staticmethod
def _transformer(
dates: npt.NDArray[np.datetime64],
start_date: np.datetime64,
granularity: np.timedelta64,
periodicity: bool,
values: List[float],
default_value: float,
) -> npt.NDArray[np.float64]:
"""Method to compute time constant value for dates
Args:
dates (npt.NDArray[np.datetime64]): dates to transform
start_date (numpy.datetime64): start_date date to identify the date when the sequence starts.
Ex: np.datetime64("2018-01-01").
granularity (np.timedelta64): time period between two observations. Ex: np.timedelta64(7,'D') for weekly.
periodicity (bool): True if it is a periodic sequence, False if not.
values (List[float]): values of the sequence. Ex: [0]*51 + [1] for a dummy at Christmas week.
default_value (float): default value set for dates out of the time period delimited by values.
Returns:
(npt.NDArray[np.float64]): computed value for each date
"""
return np.array(
[predict_value(date, start_date, granularity, periodicity, values, default_value) for date in dates]
)
# ------- CHECKERS -------
def check_params(self):
"""Check if parameters respect their application scope."""
pass
parameters: Dict[str, float] property
Returns instant transformation parameters
Returns:
| Type | Description |
|---|---|
Dict[str, float] | Instant transformation parameters |
check_params()
Check if parameters respect their application scope.
Source code in eki_mmo_equations/time_related_transformations/time_constant.py
def check_params(self):
"""Check if parameters respect their application scope."""
pass
fit(dates)
Fit transformation on dates by computing start_date and granularity
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dates | npt.NDArray[np.datetime64] | dates to fit on | required |
Source code in eki_mmo_equations/time_related_transformations/time_constant.py
def fit(self, dates: npt.NDArray[np.datetime64]):
"""Fit transformation on dates by computing start_date and granularity
Args:
dates (npt.NDArray[np.datetime64]): dates to fit on
"""
seasonal_scenario = get_seasonal_scenario(dates)
self.start_date = seasonal_scenario["start_date"]
self.granularity = seasonal_scenario["granularity"]
return super().fit(dates)
transform(dates)
Method to compute time constant value for dates
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dates | npt.NDArray[np.datetime64] | dates to transform | required |
start_date | numpy.datetime64 | start_date date to identify the date when the sequence starts. Ex: np.datetime64("2018-01-01"). | required |
granularity | np.timedelta64 | time period between two observations. Ex: np.timedelta64(7,'D') for weekly. | required |
periodicity | bool | True if it is a periodic sequence, False if not. | required |
values | List[float] | values of the sequence. Ex: [0]*51 + [1] for a dummy at Christmas week. | required |
default_value | float | default value set for dates out of the time period delimited by values. | required |
Returns:
| Type | Description |
|---|---|
npt.NDArray[np.float64] | computed value for each date |
Source code in eki_mmo_equations/time_related_transformations/time_constant.py
def transform(self, dates: npt.NDArray[np.datetime64]) -> npt.NDArray[np.float64]:
"""Method to compute time constant value for dates
Args:
dates (npt.NDArray[np.datetime64]): dates to transform
start_date (numpy.datetime64): start_date date to identify the date when the sequence starts.
Ex: np.datetime64("2018-01-01").
granularity (np.timedelta64): time period between two observations. Ex: np.timedelta64(7,'D') for weekly.
periodicity (bool): True if it is a periodic sequence, False if not.
values (List[float]): values of the sequence. Ex: [0]*51 + [1] for a dummy at Christmas week.
default_value (float): default value set for dates out of the time period delimited by values.
Returns:
(npt.NDArray[np.float64]): computed value for each date
"""
super().transform(dates)
if not self.start_date or not self.granularity:
raise TimeConstantError("start_date and granularity must be filled")
return self._transformer(
dates, self.start_date, self.granularity, self.periodicity, self.values, self.default_value
)
TimeConstantError
Bases: Exception
Exception raised if start_date and granularity are missing.
Source code in eki_mmo_equations/time_related_transformations/time_constant.py
class TimeConstantError(Exception):
"""Exception raised if start_date and granularity are missing."""
pass
predict_value(date_value, start_date, granularity, periodicity, values, default_value)
Function which predicts from a given referential time start_date (start_date), for a given granularity of time (granularity), a periodic sequential of values (periodicity) that can also be a unique infinite term (ex: periodicity=True, default_value=1 for the constant).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_value | np.datetime64 | date to predict the value for | required |
start_date | numpy.datetime64 | start_date date to identify the date when the sequence starts. Ex: np.datetime64("2018-01-01"). | required |
granularity | numpy.timedelta64 | number of days between two observations. Ex: np.timedelta64(7,'D') | required |
periodicity | bool | True if it is a periodic sequence, False if not. | required |
values | List[float] | values of the sequence. Ex: [0]*51 + [1] for a dummy at Christmas week. | required |
default_value | Optional[float] | value set for dates out of the range time period specified by values and start_date when there is no periodicity. infinite. Ex: 0 for a windows tranformation | required |
Returns:
| Type | Description |
|---|---|
float | predicted value |
Source code in eki_mmo_equations/time_related_transformations/time_constant.py
def predict_value(
date_value: np.datetime64,
start_date: np.datetime64,
granularity: np.timedelta64,
periodicity: bool,
values: list[float],
default_value: float,
) -> float:
"""Function which predicts from a given referential time start_date (start_date),
for a given granularity of time (granularity), a periodic sequential of values (periodicity)
that can also be a unique infinite term (ex: periodicity=True, default_value=1 for the constant).
Args:
date_value (np.datetime64): date to predict the value for
start_date (numpy.datetime64): start_date date to identify the date when the sequence starts.
Ex: np.datetime64("2018-01-01").
granularity (numpy.timedelta64): number of days between two observations. Ex: np.timedelta64(7,'D')
periodicity (bool): True if it is a periodic sequence, False if not.
values (List[float]): values of the sequence. Ex: [0]*51 + [1] for a dummy at Christmas week.
default_value (Optional[float]): value set for dates out of the range time period specified
by values and start_date when there is no periodicity.
infinite. Ex: 0 for a windows tranformation
Returns:
(float): predicted value
"""
absolute_value_start_date = round((date_value - start_date) / granularity)
if (not periodicity) and (abs(absolute_value_start_date // len(values)) > 0):
return default_value
return values[(absolute_value_start_date % len(values))]