Skip to content

Commit

Permalink
Fix/flake8 issues (#748)
Browse files Browse the repository at this point in the history
* Fix W605

* Fix W291

* Fix F401

* Fix F541

* Fix F841 (partially)

* Fix E713

* Fix E731

* Fix E714

* Fix F841

* Fix E501

* Fix E501
  • Loading branch information
tomasvanpottelbergh committed Jan 21, 2022
1 parent 074be2a commit 96125f8
Show file tree
Hide file tree
Showing 27 changed files with 295 additions and 274 deletions.
7 changes: 3 additions & 4 deletions darts/dataprocessing/dtw/cost_matrix.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Tuple, Dict
from typing import Tuple
import numpy as np

from .window import Window, CRWindow
Expand Down Expand Up @@ -117,8 +117,8 @@ def to_dense(self) -> np.ndarray:

# TODO express only in terms of numpy operations
for i in range(1, self.n + 1):
start = self.window.column_ranges[i * 2 + 0] - 1
end = self.window.column_ranges[i * 2 + 1] - 1
start = ranges[i * 2 + 0] - 1
end = ranges[i * 2 + 1] - 1
len = lengths[i]
offset = self.offsets[i]

Expand Down Expand Up @@ -150,7 +150,6 @@ def __setitem__(self, elem, value):
i, j = elem

start = self.column_ranges[i * 2 + 0]
end = self.column_ranges[i * 2 + 1]

self.dense[self.offsets[i] + j - start] = value

Expand Down
2 changes: 0 additions & 2 deletions darts/dataprocessing/dtw/window.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Iterable, Tuple
from dataclasses import dataclass
import numpy as np
from darts.logging import raise_if_not, raise_if
from abc import ABC, abstractmethod
Expand Down
4 changes: 2 additions & 2 deletions darts/dataprocessing/transformers/base_data_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,8 @@ def _transform_iterator(
) -> Iterator[Tuple[TimeSeries]]:
"""
Return an ``Iterator`` object with tuples of inputs for each single call to :func:`ts_transform()`.
Additional `args` and `kwargs` from :func:`transform()` (constant across all the calls to :func:`ts_transform()`)
are already forwarded, and thus don't need to be included in this generator.
Additional `args` and `kwargs` from :func:`transform()` (constant across all the calls to
:func:`ts_transform()`) are already forwarded, and thus don't need to be included in this generator.
The basic implementation of this method returns ``zip(series)``, i.e., a generator of single-valued tuples,
each containing one ``TimeSeries`` object.
Expand Down
6 changes: 3 additions & 3 deletions darts/dataprocessing/transformers/boxcox.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,11 @@ def __init__(
name
A specific name for the transformer
lmbda
The parameter :math:`\lambda` of the Box-Cox transform. If a single float is given, the same
:math:`\lambda` value will be used for all dimensions of the series, for all the series.
The parameter :math:`\\lambda` of the Box-Cox transform. If a single float is given, the same
:math:`\\lambda` value will be used for all dimensions of the series, for all the series.
If a sequence is given, there is one value per component in the series. If a sequence of sequence
is given, there is one value per component for all series.
If `None` given, will automatically find an optimal value of :math:`\lambda` (for each dimension
If `None` given, will automatically find an optimal value of :math:`\\lambda` (for each dimension
of the time series, for each time series) using :func:`scipy.stats.boxcox_normmax`
with ``method=optim_method``.
optim_method
Expand Down
3 changes: 2 additions & 1 deletion darts/datasets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,8 @@ class TaylorDataset(DatasetLoaderCSV):
References
----------
.. [1] Taylor, J.W. (2003) Short-term electricity demand forecasting using double seasonal exponential smoothing. Journal of the Operational Research Society, 54, 799-805.
.. [1] Taylor, J.W. (2003) Short-term electricity demand forecasting using double seasonal exponential smoothing.
Journal of the Operational Research Society, 54, 799-805.
.. [2] https://www.rdocumentation.org/packages/forecast/versions/8.13/topics/taylor
"""
Expand Down
1 change: 0 additions & 1 deletion darts/datasets/dataset_loaders.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from abc import ABC, abstractmethod

import pandas as pd
import numpy as np
import requests

from darts import TimeSeries
Expand Down
6 changes: 3 additions & 3 deletions darts/metrics/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@
def multi_ts_support(func):
"""
This decorator further adapts the metrics that took as input two univariate/multivariate ``TimeSeries`` instances,
adding support for equally-sized sequences of ``TimeSeries`` instances. The decorator computes the pairwise metric for
``TimeSeries`` with the same indices, and returns a float value that is computed as a function of all the
adding support for equally-sized sequences of ``TimeSeries`` instances. The decorator computes the pairwise metric
for ``TimeSeries`` with the same indices, and returns a float value that is computed as a function of all the
pairwise metrics using a `inter_reduction` subroutine passed as argument to the metric function.
If a 'Sequence[TimeSeries]' is passed as input, this decorator provides also parallelisation of the metric
Expand Down Expand Up @@ -1146,7 +1146,7 @@ def rho_risk(
where :math:`L_{\\rho} \\left( Z, \\hat{Z}_{\\rho} \\right)` is the :math:`\\rho`-loss function:
.. math:: L_{\\rho} \\left( Z, \\hat{Z}_{\\rho} \\right) = 2 \\left( Z - \\hat{Z}_{\\rho} \\right)
\\left( \\rho I_{\\hat{Z}_{\\rho} < Z} - \\left( 1 - \\rho \\right) I_{\\hat{Z}_{\\rho} \geq Z} \\right),
\\left( \\rho I_{\\hat{Z}_{\\rho} < Z} - \\left( 1 - \\rho \\right) I_{\\hat{Z}_{\\rho} \\geq Z} \\right),
where :math:`Z = \\sum_{t=1}^{T} y_t` (1) is the aggregated target value and :math:`\\hat{Z}_{\\rho}` is the
:math:`\\rho`-quantile of the predicted values. For this, each sample realization :math:`i \\in N` is first
Expand Down
1 change: 0 additions & 1 deletion darts/models/filtering/gaussian_process_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Kernel

from darts.utils.utils import raise_if_not
from darts.models.filtering.filtering_model import FilteringModel


Expand Down
18 changes: 9 additions & 9 deletions darts/models/filtering/kalman_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ def __init__(self, dim_x: int = 1, kf: Optional[Kalman] = None):
This implementation uses Kalman from the NFourSID package. More information can be found here:
https://nfoursid.readthedocs.io/en/latest/source/kalman.html.
The dimensionality of the measurements z and optional control signal (covariates) u is automatically inferred upon
calling `filter()`.
The dimensionality of the measurements z and optional control signal (covariates) u is automatically inferred
upon calling `filter()`.
Parameters
----------
Expand All @@ -47,7 +47,7 @@ def __init__(self, dim_x: int = 1, kf: Optional[Kalman] = None):
If this is provided, the parameter dim_x is ignored. This instance will be copied for every
call to `filter()`, so the state is not carried over from one time series to another across several
calls to `filter()`.
The various dimensionalities of the filter must match those of the `TimeSeries` used when calling `filter()`.
The dimensionalities of the filter must match those of the `TimeSeries` used when calling `filter()`.
"""
# TODO: Add support for x_init. Needs reimplementation of NFourSID.

Expand Down Expand Up @@ -85,8 +85,8 @@ def fit(
The series of outputs (observations) used to infer the underlying state space model.
This must be a deterministic series (containing one sample).
covariates : Optional[TimeSeries]
An optional series of inputs (control signal) that will also be used to infer the underlying state space model.
This must be a deterministic series (containing one sample).
An optional series of inputs (control signal) that will also be used to infer the underlying state space
model. This must be a deterministic series (containing one sample).
num_block_rows : Optional[int]
The number of block rows to use in the block Hankel matrices used in the N4SID algorithm.
See the documentation of nfoursid.nfoursid.NFourSID for more information.
Expand Down Expand Up @@ -142,11 +142,11 @@ def filter(
Parameters
----------
series : TimeSeries
The series of outputs (observations) used to infer the underlying outputs according to the specified Kalman process.
This must be a deterministic series (containing one sample).
The series of outputs (observations) used to infer the underlying outputs according to the specified Kalman
process. This must be a deterministic series (containing one sample).
covariates : Optional[TimeSeries]
An optional series of inputs (control signal), necessary if the Kalman filter was initialized with covariates.
This must be a deterministic series (containing one sample).
An optional series of inputs (control signal), necessary if the Kalman filter was initialized with
covariates. This must be a deterministic series (containing one sample).
num_samples : int, default: 1
The number of samples to generate from the inferred distribution of the output z. If this is set to 1, the
output is a `TimeSeries` containing a single sample using the mean of the distribution.
Expand Down
6 changes: 3 additions & 3 deletions darts/models/forecasting/block_rnn_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,9 +226,9 @@ def __init__(
Default: ``torch.nn.MSELoss()``.
model_name
Name of the model. Used for creating checkpoints and saving tensorboard data. If not specified,
defaults to the following string ``"YYYY-mm-dd_HH:MM:SS_torch_model_run_PID"``, where the initial part of the
name is formatted with the local date and time, while PID is the processed ID (preventing models spawned at
the same time by different processes to share the same model_name). E.g.,
defaults to the following string ``"YYYY-mm-dd_HH:MM:SS_torch_model_run_PID"``, where the initial part of
the name is formatted with the local date and time, while PID is the processed ID (preventing models spawned
at the same time by different processes to share the same model_name). E.g.,
``"2021-06-14_09:53:32_torch_model_run_44607"``.
work_dir
Path of the working directory, where to save checkpoints and Tensorboard summaries.
Expand Down
6 changes: 4 additions & 2 deletions darts/models/forecasting/forecasting_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,8 +332,10 @@ def historical_forecasts(

# TODO: do we need a check here? I'd rather leave these checks to the models/datasets.
# if covariates:
# raise_if_not(series.end_time() <= covariates.end_time() and covariates.start_time() <= series.start_time(),
# 'The provided covariates must be at least as long as the target series.')
# raise_if_not(
# series.end_time() <= covariates.end_time() and covariates.start_time() <= series.start_time(),
# 'The provided covariates must be at least as long as the target series.'
# )

# only GlobalForecastingModels support historical forecastings without retraining the model
base_class_name = self.__class__.__base__.__name__
Expand Down
9 changes: 5 additions & 4 deletions darts/models/forecasting/nbeats.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@ def __init__(
The number of parameters of the likelihood (or 1 if no likelihood is used)
expansion_coefficient_dim
The dimensionality of the waveform generator parameters, also known as expansion coefficients.
Used in the generic architecture and the trend module of the interpretable architecture, where it determines the degree of the polynomial basis.
Used in the generic architecture and the trend module of the interpretable architecture, where it determines
the degree of the polynomial basis.
input_chunk_length
The length of the input sequence fed to the model.
target_length
Expand Down Expand Up @@ -562,9 +563,9 @@ def __init__(
Default: ``torch.nn.MSELoss()``.
model_name
Name of the model. Used for creating checkpoints and saving tensorboard data. If not specified,
defaults to the following string ``"YYYY-mm-dd_HH:MM:SS_torch_model_run_PID"``, where the initial part of the
name is formatted with the local date and time, while PID is the processed ID (preventing models spawned at
the same time by different processes to share the same model_name). E.g.,
defaults to the following string ``"YYYY-mm-dd_HH:MM:SS_torch_model_run_PID"``, where the initial part of
the name is formatted with the local date and time, while PID is the processed ID (preventing models spawned
at the same time by different processes to share the same model_name). E.g.,
``"2021-06-14_09:53:32_torch_model_run_44607"``.
work_dir
Path of the working directory, where to save checkpoints and Tensorboard summaries.
Expand Down
2 changes: 1 addition & 1 deletion darts/models/forecasting/regression_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ def _create_lagged_data(

raise_if(
X_y.shape[0] == 0,
f"Unable to build any training samples; target and covariate series overlap too little.",
"Unable to build any training samples; target and covariate series overlap too little.",
)

X, y = np.split(X_y, [df_X.shape[1]], axis=1)
Expand Down
6 changes: 3 additions & 3 deletions darts/models/forecasting/rnn_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,9 +210,9 @@ def __init__(
Default: ``torch.nn.MSELoss()``.
model_name
Name of the model. Used for creating checkpoints and saving tensorboard data. If not specified,
defaults to the following string ``"YYYY-mm-dd_HH:MM:SS_torch_model_run_PID"``, where the initial part of the
name is formatted with the local date and time, while PID is the processed ID (preventing models spawned at
the same time by different processes to share the same model_name). E.g.,
defaults to the following string ``"YYYY-mm-dd_HH:MM:SS_torch_model_run_PID"``, where the initial part of
the name is formatted with the local date and time, while PID is the processed ID (preventing models spawned
at the same time by different processes to share the same model_name). E.g.,
``"2021-06-14_09:53:32_torch_model_run_44607"``.
work_dir
Path of the working directory, where to save checkpoints and Tensorboard summaries.
Expand Down
6 changes: 3 additions & 3 deletions darts/models/forecasting/tcn_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,9 +338,9 @@ def __init__(
Default: ``torch.nn.MSELoss()``.
model_name
Name of the model. Used for creating checkpoints and saving tensorboard data. If not specified,
defaults to the following string ``"YYYY-mm-dd_HH:MM:SS_torch_model_run_PID"``, where the initial part of the
name is formatted with the local date and time, while PID is the processed ID (preventing models spawned at
the same time by different processes to share the same model_name). E.g.,
defaults to the following string ``"YYYY-mm-dd_HH:MM:SS_torch_model_run_PID"``, where the initial part of
the name is formatted with the local date and time, while PID is the processed ID (preventing models spawned
at the same time by different processes to share the same model_name). E.g.,
``"2021-06-14_09:53:32_torch_model_run_44607"``.
work_dir
Path of the working directory, where to save checkpoints and Tensorboard summaries.
Expand Down
6 changes: 3 additions & 3 deletions darts/models/forecasting/tft_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -675,9 +675,9 @@ def __init__(
Optionally, some keyword arguments for the PyTorch optimizer.
model_name
Name of the model. Used for creating checkpoints and saving tensorboard data. If not specified,
defaults to the following string ``"YYYY-mm-dd_HH:MM:SS_torch_model_run_PID"``, where the initial part of the
name is formatted with the local date and time, while PID is the processed ID (preventing models spawned at
the same time by different processes to share the same model_name). E.g.,
defaults to the following string ``"YYYY-mm-dd_HH:MM:SS_torch_model_run_PID"``, where the initial part of
the name is formatted with the local date and time, while PID is the processed ID (preventing models spawned
at the same time by different processes to share the same model_name). E.g.,
``"2021-06-14_09:53:32_torch_model_run_44607"``.
work_dir
Path of the working directory, where to save checkpoints and Tensorboard summaries.
Expand Down
14 changes: 9 additions & 5 deletions darts/models/forecasting/torch_forecasting_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,9 @@ def __init__(
Default: ``torch.nn.MSELoss()``.
model_name
Name of the model. Used for creating checkpoints and saving tensorboard data. If not specified,
defaults to the following string ``"YYYY-mm-dd_HH:MM:SS_torch_model_run_PID"``, where the initial part of the
name is formatted with the local date and time, while PID is the processed ID (preventing models spawned at
the same time by different processes to share the same model_name). E.g.,
defaults to the following string ``"YYYY-mm-dd_HH:MM:SS_torch_model_run_PID"``, where the initial part of
the name is formatted with the local date and time, while PID is the processed ID (preventing models spawned
at the same time by different processes to share the same model_name). E.g.,
``"2021-06-14_09:53:32_torch_model_run_44607"``.
work_dir
Path of the working directory, where to save checkpoints and Tensorboard summaries.
Expand Down Expand Up @@ -470,7 +470,11 @@ def fit(
past_covariates=past_covariates, future_covariates=future_covariates
)

wrap_fn = lambda ts: [ts] if isinstance(ts, TimeSeries) else ts
def wrap_fn(
ts: Union[TimeSeries, Sequence[TimeSeries]]
) -> Sequence[TimeSeries]:
return [ts] if isinstance(ts, TimeSeries) else ts

series = wrap_fn(series)
past_covariates = wrap_fn(past_covariates)
future_covariates = wrap_fn(future_covariates)
Expand Down Expand Up @@ -1527,7 +1531,7 @@ def _get_batch_prediction(

n_targets = past_target.shape[dim_component]
n_past_covs = (
past_covariates.shape[dim_component] if not past_covariates is None else 0
past_covariates.shape[dim_component] if past_covariates is not None else 0
)

input_past = torch.cat(
Expand Down
10 changes: 5 additions & 5 deletions darts/models/forecasting/transformer_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,9 +305,9 @@ def __init__(
Default: ``torch.nn.MSELoss()``.
model_name
Name of the model. Used for creating checkpoints and saving tensorboard data. If not specified,
defaults to the following string ``"YYYY-mm-dd_HH:MM:SS_torch_model_run_PID"``, where the initial part of the
name is formatted with the local date and time, while PID is the processed ID (preventing models spawned at
the same time by different processes to share the same model_name). E.g.,
defaults to the following string ``"YYYY-mm-dd_HH:MM:SS_torch_model_run_PID"``, where the initial part of
the name is formatted with the local date and time, while PID is the processed ID (preventing models spawned
at the same time by different processes to share the same model_name). E.g.,
``"2021-06-14_09:53:32_torch_model_run_44607"``.
work_dir
Path of the working directory, where to save checkpoints and Tensorboard summaries.
Expand All @@ -331,8 +331,8 @@ def __init__(
References
----------
.. [1] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and
Illia Polosukhin, "Attention Is All You Need", 2017. In Advances in Neural Information Processing Systems,
.. [1] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser,
and Illia Polosukhin, "Attention Is All You Need", 2017. In Advances in Neural Information Processing Systems,
pages 6000-6010. https://arxiv.org/abs/1706.03762.
Notes
Expand Down
1 change: 0 additions & 1 deletion darts/tests/models/forecasting/test_regression_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
LinearRegressionModel,
LightGBMModel,
)
from darts.utils.data.sequential_dataset import MixedCovariatesSequentialDataset
from darts.utils.data.inference_dataset import MixedCovariatesInferenceDataset
from darts.models.forecasting.regression_model import (
_shift_matrices,
Expand Down

0 comments on commit 96125f8

Please sign in to comment.