Skip to content
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

Update ruff to v6.8 and many typos #2548

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ repos:
- id: detect-private-key

- repo: https:/astral-sh/ruff-pre-commit
rev: v0.3.5
rev: v0.6.8
hooks:
# try to fix what is possible
- id: ruff
Expand Down
5 changes: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ but cannot always guarantee backwards compatibility. Changes that may **break co
- Updated the Ray Tune Hyperparameter Optimization example in the [user guide](https://unit8co.github.io/darts/userguide/hyperparameter_optimization.html) to work with the latest `ray` versions (`>=2.31.0`). [#2459](https:/unit8co/darts/pull/2459) by [He Weilin](https:/cnhwl).
- Indicate that `multi_models=False` induce a lags shift for each step in `output_chunk_length` in `RegressionModel` and `LinearRegressionModel`. [#2511](https:/unit8co/darts/pull/2511) by [Antoine Madrona](https:/madtoinou).
- Added reference to `timeseries_generation.datetime_attribute_timeseries` in `TimeSeries.add_datetime_attribute` (0-indexing of encoding is enforced). [#2511](https:/unit8co/darts/pull/2511) by [Antoine Madrona](https:/madtoinou).
- Update ruff to v6.8. Also fixed many typos [#2548](https:/unit8co/darts/pull/2548) by [Greg DeVosNouri](https:/gdevos010)

**Fixed**

Expand Down Expand Up @@ -228,11 +229,11 @@ but cannot always guarantee backwards compatibility. Changes that may **break co
**Fixed**

- Fixed a bug when using `RegressionModel` with `lags=None`, some `lags_*covariates`, and the covariates starting after or at the same time as the first predictable time step; the lags were not extracted from the correct indices. [#2176](https:/unit8co/darts/pull/2176) by [Dennis Bader](https:/dennisbader).
- Fixed a bug when calling `window_transform` on a `TimeSeries` with a hierarchy. The hierarchy is now only preseved for single transformations applied to all components, or removed otherwise. [#2207](https:/unit8co/darts/pull/2207) by [Antoine Madrona](https:/madtoinou).
- Fixed a bug when calling `window_transform` on a `TimeSeries` with a hierarchy. The hierarchy is now only preserved for single transformations applied to all components, or removed otherwise. [#2207](https:/unit8co/darts/pull/2207) by [Antoine Madrona](https:/madtoinou).
- Fixed a bug in probabilistic `LinearRegressionModel.fit()`, where the `model` attribute was not pointing to all underlying estimators. [#2205](https:/unit8co/darts/pull/2205) by [Antoine Madrona](https:/madtoinou).
- Raise an error in `RegressionEsembleModel` when the `regression_model` was created with `multi_models=False` (not supported). [#2205](https:/unit8co/darts/pull/2205) by [Antoine Madrona](https:/madtoinou).
- Fixed a bug in `coefficient_of_variation()` with `intersect=True`, where the coefficient was not computed on the intersection. [#2202](https:/unit8co/darts/pull/2202) by [Antoine Madrona](https:/madtoinou).
- Fixed a bug in `gridsearch()` with `use_fitted_values=True`, where the model was not propely instantiated for sanity checks. [#2222](https:/unit8co/darts/pull/2222) by [Antoine Madrona](https:/madtoinou).
- Fixed a bug in `gridsearch()` with `use_fitted_values=True`, where the model was not properly instantiated for sanity checks. [#2222](https:/unit8co/darts/pull/2222) by [Antoine Madrona](https:/madtoinou).
- Fixed a bug in `TimeSeries.append/prepend_values()`, where the component names and the hierarchy were dropped. [#2237](https:/unit8co/darts/pull/2237) by [Antoine Madrona](https:/madtoinou).
- Fixed a bug in `get_multioutput_estimator()`, where the index of the estimator was incorrectly calculated. [#2246](https:/unit8co/darts/pull/2246) by [Antoine Madrona](https:/madtoinou).
- 🔴 Fixed a bug in `datetime_attribute_timeseries()`, where 1-indexed attributes were not properly handled. Also, 0-indexing is now enforced for all the generated encodings. [#2242](https:/unit8co/darts/pull/2242) by [Antoine Madrona](https:/madtoinou).
Expand Down
2 changes: 1 addition & 1 deletion darts/ad/detectors/detectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ def fit_detect(
Returns
-------
Union[TimeSeries, Sequence[TimeSeries]]
Binary prediciton (1 if considered as an anomaly, 0 if not)
Binary prediction (1 if considered as an anomaly, 0 if not)
"""
self.fit(series)
return self.detect(series, name="series")
Expand Down
2 changes: 1 addition & 1 deletion darts/ad/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -666,7 +666,7 @@ def _plot_series(series, ax_id, linewidth, label_name, **kwargs):
series
The series to plot.
ax_id
The axis the series will be ploted on.
The axis the series will be plotted on.
linewidth
Thickness of the line.
label_name
Expand Down
6 changes: 3 additions & 3 deletions darts/dataprocessing/transformers/midas.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,14 @@ def __init__(
Whether to remove the NaNs from the start and the end of the transformed series.
drop_static_covariates
If set to `True`, the statics covariates of the input series won't be transferred to the output.
This migth be useful for multivariate series with component-specific static covariates.
This might be useful for multivariate series with component-specific static covariates.
name
A specific name for the scaler
n_jobs
The number of jobs to run in parallel. Parallel jobs are created only when a ``Sequence[TimeSeries]`` is
passed as input to a method, parallelising operations regarding different ``TimeSeries``. Defaults to `1`
passed as input to a method, parallelizing operations regarding different ``TimeSeries``. Defaults to `1`
(sequential). Setting the parameter to `-1` means using all the available processors.
Note: for a small amount of data, the parallelisation overhead could end up increasing the total
Note: for a small amount of data, the parallelization overhead could end up increasing the total
required amount of time.
verbose
Optionally, whether to print operations progress
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -260,9 +260,9 @@ def _create_component_masks(
"""
Returns a boolean array indicating which components of the UNTRANSFORMED
`stat_covs` are numerical and a boolean array indicating which components
of the UNTRANSFORMED `stat_covs` are categoical.
of the UNTRANSFORMED `stat_covs` are categorical.

It's important to recognise that these masks only apply to the UNTRANSFORMED
It's important to recognize that these masks only apply to the UNTRANSFORMED
static covariates since some transformations can generate multiple new components
from a single component (e.g. one-hot encoding).
"""
Expand Down Expand Up @@ -327,9 +327,9 @@ def _create_inv_component_masks(
"""
Returns a boolean array indicating which components of the TRANSFORMED
`stat_covs` are numerical and a boolean array indicating which components
of the TRANSFORMED `stat_covs` are categoical.
of the TRANSFORMED `stat_covs` are categorical.

It's important to recognise that these masks only apply to the UNTRANSFORMED
It's important to recognize that these masks only apply to the UNTRANSFORMED
static covariates since some transformations can generate multiple new components
from a single component (e.g. one-hot encoding).
"""
Expand Down
2 changes: 1 addition & 1 deletion darts/explainability/shap_explainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ def summary_plot(
Returns
-------
shaps_
A nested dictionary {horizon : {component : shap.Explaination}} containing the raw Explanations for all
A nested dictionary {horizon : {component : shap.Explanation}} containing the raw Explanations for all
the horizons and components.
"""

Expand Down
2 changes: 1 addition & 1 deletion darts/metrics/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
-------

For deterministic forecasts (point predictions with `num_samples == 1`), probabilistic forecasts (`num_samples > 1`),
and quantile forecasts. For probablistic and quantile forecasts, use parameter `q` to define the quantile(s) to
and quantile forecasts. For probabilistic and quantile forecasts, use parameter `q` to define the quantile(s) to
compute the deterministic metrics on:

- Aggregated over time:
Expand Down
6 changes: 3 additions & 3 deletions darts/metrics/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,14 +287,14 @@ def wrapper_multivariate_support(*args, **kwargs) -> METRIC_OUTPUT_TYPE:
raise_log(
ValueError(
"`q` must be of tuple of `(np.ndarray, Optional[pd.Index])` "
"where the (quantile values, optioanl quantile component names). "
"where the (quantile values, optional quantile component names). "
f"Received `q={q}`."
),
logger=logger,
)
q, q_comp_names = q
if not pred_series.is_stochastic:
# quantile component names are required if the predictions are not stochastic (as for stocahstic
# quantile component names are required if the predictions are not stochastic (as for stochastic
# predictions, the quantiles can be retrieved from the sample dimension for each component)
if q_comp_names is None:
q_comp_names = pd.Index(
Expand Down Expand Up @@ -611,7 +611,7 @@ def _get_error_scale(
"""Computes the error scale based on a naive seasonal forecasts on `insample` values with seasonality `m`."""
if not isinstance(m, int):
raise_log(
ValueError(f"Seasonality `m` must be of type `int`, recevied `m={m}`"),
ValueError(f"Seasonality `m` must be of type `int`, received `m={m}`"),
logger=logger,
)

Expand Down
2 changes: 1 addition & 1 deletion darts/models/forecasting/block_rnn_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ def __init__(
hidden_fc_sizes
Sizes of hidden layers connecting the last hidden layer of the RNN module to the output, if any.
dropout
Fraction of neurons afected by Dropout.
Fraction of neurons affected by Dropout.
activation
The name of a torch.nn activation function to be applied between the layers of the fully connected network.
Default: "ReLU".
Expand Down
2 changes: 1 addition & 1 deletion darts/models/forecasting/forecasting_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -3144,7 +3144,7 @@ def _verify_passed_predict_covariates(self, future_covariates):

@property
def _supress_generate_predict_encoding(self) -> bool:
"""Controls wether encodings should be generated in :func:`FutureCovariatesLocalForecastingModel.predict()``"""
"""Controls whether encodings should be generated in :func:`FutureCovariatesLocalForecastingModel.predict()``"""
return False

@property
Expand Down
2 changes: 1 addition & 1 deletion darts/models/forecasting/global_baseline_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def __init__(
To add a new naive model:
- subclass from `_GlobalNaiveModel` with implementation of private method `_create_model` that creates an
object of:
- subclass from `_GlobalNaiveModule` with implemention of private method `_forward`
- subclass from `_GlobalNaiveModule` with implementation of private method `_forward`

.. note::
- Model checkpointing with `save_checkpoints=True`, and checkpoint loading with `load_from_checkpoint()`
Expand Down
2 changes: 1 addition & 1 deletion darts/models/forecasting/linear_regression_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ def fit(

self._model_container[quantile] = self.model

# replace the last trained QuantileRegressor with the dictionnary of Regressors.
# replace the last trained QuantileRegressor with the dictionary of Regressors.
self.model = self._model_container

return self
Expand Down
2 changes: 1 addition & 1 deletion darts/models/forecasting/pl_forecasting_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,7 @@ def _produce_predict_output(self, x: Tuple) -> torch.Tensor:
def on_save_checkpoint(self, checkpoint: Dict[str, Any]) -> None:
# we must save the dtype for correct parameter precision at loading time
checkpoint["model_dtype"] = self.dtype
# we must save the shape of the input to be able to instanciate the model without calling fit_from_dataset
# we must save the shape of the input to be able to instantiate the model without calling fit_from_dataset
checkpoint["train_sample_shape"] = self.train_sample_shape
# we must save the loss to properly restore it when resuming training
checkpoint["loss_fn"] = self.criterion
Expand Down
4 changes: 2 additions & 2 deletions darts/models/forecasting/prophet_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def encode_year(idx):
}
..
cap
Parameter specifiying the maximum carrying capacity when predicting with logistic growth.
Parameter specifying the maximum carrying capacity when predicting with logistic growth.
Mandatory when `growth = 'logistic'`, otherwise ignored.
See <https://facebook.github.io/prophet/docs/saturating_forecasts.html> for more information
on logistic forecasts.
Expand All @@ -121,7 +121,7 @@ def encode_year(idx):
- a function taking a DatetimeIndex or RangeIndex and returning a corresponding a Sequence of numbers,
where each number indicates the carrying capacity at this index.
floor
Parameter specifiying the minimum carrying capacity when predicting logistic growth.
Parameter specifying the minimum carrying capacity when predicting logistic growth.
Optional when `growth = 'logistic'` (defaults to 0), otherwise ignored.
See <https://facebook.github.io/prophet/docs/saturating_forecasts.html> for more information
on logistic forecasts.
Expand Down
4 changes: 2 additions & 2 deletions darts/models/forecasting/regression_ensemble_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,12 +458,12 @@ def ensemble(
ensembled = [
self.regression_model.predict(
n=len(prediction),
series=serie,
series=series,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please revert this one, having both the element and iterable called series does not look good.

future_covariates=prediction,
num_samples=num_samples,
predict_likelihood_parameters=predict_likelihood_parameters,
)
for serie, prediction in zip(series, predictions)
for series, prediction in zip(series, predictions)
]
return seq2series(ensembled) if is_single_series else ensembled

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 @@ -369,7 +369,7 @@ def _generate_lags(
raise_log(
ValueError(
f"`{lags_name}` - `{comp_name}`: must be either a {supported_types}. "
f"Gived : {type(comp_lags)}."
f"Given : {type(comp_lags)}."
),
logger,
)
Expand Down
2 changes: 1 addition & 1 deletion darts/models/forecasting/rnn_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ def __init__(
n_rnn_layers
The number of recurrent layers.
dropout
Fraction of neurons afected by Dropout.
Fraction of neurons affected by Dropout.
training_length
The length of both input (target and covariates) and output (target) time series used during
training. Must have a larger value than `input_chunk_length`, because otherwise during training
Expand Down
2 changes: 1 addition & 1 deletion darts/tests/ad/test_aggregators.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ def test_aggregator_predict_wrong_inputs(self, config):

@pytest.mark.parametrize("config", list_NonFittableAggregator)
def test_NonFittableAggregator_predict(self, config):
"""Check that predict() works as intented"""
"""Check that predict() works as intended"""
aggregator_cls, cls_kwargs, _ = config
aggregator = aggregator_cls(**cls_kwargs)

Expand Down
8 changes: 4 additions & 4 deletions darts/tests/ad/test_scorers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1262,7 +1262,7 @@ def test_PyODScorer(self):
with pytest.raises(ValueError):
PyODScorer(model=KNN(), window=0)

# diff_fn paramter
# diff_fn parameter
# must be None, 'diff' or 'abs_diff'
with pytest.raises(ValueError):
PyODScorer(model=KNN(), diff_fn="random")
Expand Down Expand Up @@ -1531,7 +1531,7 @@ def helper_evaluate_nll_scorer(
np.array(deterministic_values).reshape(2, 2, -1)
)

# compute the NLL values witn score_from_prediction for scorer with window=1 and 2
# compute the NLL values with score_from_prediction for scorer with window=1 and 2
# t -> timestamp, c -> component and w -> window used in scorer
value_t1_c1_w1 = NLLscorer_w1.score_from_prediction(
series[0]["0"], distribution_series[0]["0"]
Expand Down Expand Up @@ -1570,7 +1570,7 @@ def helper_evaluate_nll_scorer(
)

# multivariate case
# compute the NLL values witn score_from_prediction for scorer with window=1 and window=2
# compute the NLL values with score_from_prediction for scorer with window=1 and window=2
value_t1_2_c1_2_w1 = NLLscorer_w1.score_from_prediction(
series, distribution_series
)
Expand Down Expand Up @@ -1686,7 +1686,7 @@ def test_window_greater_than_one(self, window, model, series):
assert score_T[-1] == score_F[-1]

def test_fun_window_agg(self):
"""Verify that the anomaly score aggregation works as intented"""
"""Verify that the anomaly score aggregation works as intended"""
# window = 2, alternating anomaly scores
window = 2
scorer = KMeansScorer(window=window)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -540,8 +540,8 @@ def test_include_current(self):
)
def test_ts_windowtransf_hierarchy(self, transforms):
"""Checking that supported transforms behave as expected:
- implicitely applied to all components
- passing explicitely all components
- implicitly applied to all components
- passing explicitly all components
"""
ts = helper_generate_ts_hierarchy(10)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def test_rin(self):
rin = RINorm(input_dim=7, affine=affine)
x_norm = rin(x)

# expand dims to simulate probablistic forecasting
# expand dims to simulate probabilistic forecasting
x_denorm = rin.inverse(x_norm.view(x_norm.shape + (1,))).squeeze(-1)
assert torch.all(torch.isclose(x, x_denorm)).item()

Expand Down
6 changes: 3 additions & 3 deletions darts/tests/models/forecasting/test_backtesting.py
Original file line number Diff line number Diff line change
Expand Up @@ -1122,15 +1122,15 @@ def test_gridsearch_sample_weight(self, config):
else:
sample_weight = "linear"

paramameters = {"lags": [3], "output_chunk_length": [1]}
parameters = {"lags": [3], "output_chunk_length": [1]}
start_kwargs = {"start": -1, "start_format": "position"}
gs_kwargs = {"val_series": ts} if use_val_series else {"forecast_horizon": 1}
gs_non_weighted = LinearRegressionModel.gridsearch(
paramameters, series=ts[:-1], **start_kwargs, **gs_kwargs
parameters, series=ts[:-1], **start_kwargs, **gs_kwargs
)[-1]

gs_weighted = LinearRegressionModel.gridsearch(
paramameters,
parameters,
series=ts[:-1],
sample_weight=sample_weight,
**start_kwargs,
Expand Down
2 changes: 1 addition & 1 deletion darts/tests/models/forecasting/test_ensemble_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def test_trained_models(self):

# both global trained, retrain = True
with pytest.raises(ValueError):
# models need to be explicitely reset before retraining them
# models need to be explicitly reset before retraining them
NaiveEnsembleModel(
[global_model, global_model], train_forecasting_models=True
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2323,7 +2323,7 @@ def test_predict_likelihood_parameters(self, model_type):
),
)
def test_probabilistic_optimized_hist_fc_regression(self, config):
"""Tests optimized probilistic historical forecasts for regression models."""
"""Tests optimized probabilistic historical forecasts for regression models."""
np.random.seed(42)
lpo, multi_models, n = config
ocl = 2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -520,7 +520,7 @@ def test_predict_likelihood_parameters_univariate_torch_models(
n_samples,
))

# Dirichlet must be handled sligthly differently since its multivariate
# Dirichlet must be handled slightly differently since its multivariate
if isinstance(lkl, DirichletLikelihood):
values = torch.swapaxes(values, 1, 3)
values = torch.squeeze(values, 3)
Expand Down
2 changes: 1 addition & 1 deletion darts/tests/models/forecasting/test_ptl_trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def test_builtin_extended_trainer(self):
)
model.fit(self.series, epochs=1)

# flaot 16 not supported
# float 16 not supported
with pytest.raises(ValueError):
invalid_trainer_kwarg = {
"precision": "16-mixed",
Expand Down
Loading
Loading