Solve all issues detected by PyCharm

- as of September 2021, PyCharm is used to write some of the code
- PyCharm's built-in code styler, linter, and type checker issued
  some warnings that are resolved in this commit
  + spelling mistakes
  + all instance attributes must be specified explicitly
    in a class's __init__() method
    => use `functools.cached_property` for caching
  + make `tuple`s explicit with `(...)`
  + one test failed randomly although everything is ok
    => adjust the fixture's return value (stub for Google Directions API)
  + reformulate SQL so that PyCharm can understand the symbols
This commit is contained in:
Alexander Hess 2021-09-08 12:07:44 +02:00
commit 1c19da2f70
Signed by: alexander
GPG key ID: 344EA5AB10D868E0
9 changed files with 136 additions and 151 deletions

View file

@ -31,8 +31,8 @@ def predict(
Raises:
ValueError: if `training_ts` contains `NaN` values
"""
# Initialize R only if necessary as it is tested only in nox's
# "ci-tests-slow" session and "ci-tests-fast" should not fail.
# Initialize R only if it is actually used.
# For example, the nox session "ci-tests-fast" does not use it.
from urban_meal_delivery import init_r # noqa:F401,WPS433
# Re-seed R every time it is used to ensure reproducibility.

View file

@ -154,8 +154,8 @@ def stl( # noqa:C901,WPS210,WPS211,WPS231
else:
robust = False
# Initialize R only if necessary as it is tested only in nox's
# "ci-tests-slow" session and "ci-tests-fast" should not fail.
# Initialize R only if it is actually used.
# For example, the nox session "ci-tests-fast" does not use it.
from urban_meal_delivery import init_r # noqa:F401,WPS433
# Re-seed R every time it is used to ensure reproducibility.

View file

@ -32,8 +32,8 @@ def predict(
Raises:
ValueError: if `training_ts` contains `NaN` values
"""
# Initialize R only if necessary as it is tested only in nox's
# "ci-tests-slow" session and "ci-tests-fast" should not fail.
# Initialize R only if it is actually used.
# For example, the nox session "ci-tests-fast" does not use it.
from urban_meal_delivery import init_r # noqa:F401,WPS433
# Re-seed R every time it is used to ensure reproducibility.

View file

@ -15,7 +15,7 @@ For the paper check:
This sub-package is organized as follows. The `base` module defines an abstract
`ForecastingModelABC` class that unifies how the concrete `*Model`s work.
While the abstact `.predict()` method returns a `pd.DataFrame` (= basically,
While the abstract `.predict()` method returns a `pd.DataFrame` (= basically,
the result of one of the forecasting `methods`, the concrete `.make_forecast()`
method converts the results into `Forecast` (=ORM) objects.
Also, `.make_forecast()` implements a caching strategy where already made
@ -23,7 +23,7 @@ Also, `.make_forecast()` implements a caching strategy where already made
which could be a heavier computation.
The `tactical` sub-package contains all the `*Model`s used to implement the
UDP's predictive routing strategy.
predictive routing strategy employed by the UDP.
A future `planning` sub-package will contain the `*Model`s used to plan the
`Courier`'s shifts a week ahead.

View file

@ -1,8 +1,8 @@
"""Forecasting `*Model`s to predict demand for tactical purposes.
The `*Model`s in this module predict only a small number (e.g., one)
of time steps into the near future and are used to implement the UDP's
predictive routing strategies.
of time steps into the near future and are used to implement the
predictive routing strategies employed by the UDP.
They are classified into "horizontal", "vertical", and "real-time" models
with respect to what historic data they are trained on and how often they

View file

@ -51,7 +51,7 @@ class HorizontalETSModel(base.ForecastingModelABC):
# Make `predictions` with the seasonal ETS method ("ZZZ" model).
predictions = methods.ets.predict(
training_ts=training_ts,
forecast_interval=actuals_ts.index,
forecast_interval=pd.DatetimeIndex(actuals_ts.index),
frequency=frequency, # `== 7`, the number of weekdays
seasonal_fit=True, # because there was no decomposition before
)
@ -59,7 +59,7 @@ class HorizontalETSModel(base.ForecastingModelABC):
predictions.insert(loc=0, column='actual', value=actuals_ts)
# Sanity checks.
if predictions.isnull().any().any(): # pragma: no cover
if predictions.isnull().sum().any(): # pragma: no cover
raise RuntimeError('missing predictions in hets model')
if predict_at not in predictions.index: # pragma: no cover
raise RuntimeError('missing prediction for `predict_at`')

View file

@ -59,7 +59,7 @@ class RealtimeARIMAModel(base.ForecastingModelABC):
# Make predictions for the seasonal component by linear extrapolation.
seasonal_predictions = methods.extrapolate_season.predict(
training_ts=decomposed_training_ts['seasonal'],
forecast_interval=actuals_ts.index,
forecast_interval=pd.DatetimeIndex(actuals_ts.index),
frequency=frequency,
)
@ -68,7 +68,7 @@ class RealtimeARIMAModel(base.ForecastingModelABC):
training_ts=(
decomposed_training_ts['trend'] + decomposed_training_ts['residual']
),
forecast_interval=actuals_ts.index,
forecast_interval=pd.DatetimeIndex(actuals_ts.index),
# Because the seasonality was taken out before,
# the `training_ts` has, by definition, a `frequency` of `1`.
frequency=1,
@ -109,7 +109,7 @@ class RealtimeARIMAModel(base.ForecastingModelABC):
# Sanity checks.
if len(predictions) != 1: # pragma: no cover
raise RuntimeError('real-time models should predict exactly one time step')
if predictions.isnull().any().any(): # pragma: no cover
if predictions.isnull().sum().any(): # pragma: no cover
raise RuntimeError('missing predictions in rtarima model')
if predict_at not in predictions.index: # pragma: no cover
raise RuntimeError('missing prediction for `predict_at`')

View file

@ -61,7 +61,7 @@ class VerticalARIMAModel(base.ForecastingModelABC):
# Make predictions for the seasonal component by linear extrapolation.
seasonal_predictions = methods.extrapolate_season.predict(
training_ts=decomposed_training_ts['seasonal'],
forecast_interval=actuals_ts.index,
forecast_interval=pd.DatetimeIndex(actuals_ts.index),
frequency=frequency,
)
@ -70,7 +70,7 @@ class VerticalARIMAModel(base.ForecastingModelABC):
training_ts=(
decomposed_training_ts['trend'] + decomposed_training_ts['residual']
),
forecast_interval=actuals_ts.index,
forecast_interval=pd.DatetimeIndex(actuals_ts.index),
# Because the seasonality was taken out before,
# the `training_ts` has, by definition, a `frequency` of `1`.
frequency=1,
@ -111,7 +111,7 @@ class VerticalARIMAModel(base.ForecastingModelABC):
# Sanity checks.
if len(predictions) <= 1: # pragma: no cover
raise RuntimeError('vertical models should predict several time steps')
if predictions.isnull().any().any(): # pragma: no cover
if predictions.isnull().sum().any(): # pragma: no cover
raise RuntimeError('missing predictions in varima model')
if predict_at not in predictions.index: # pragma: no cover
raise RuntimeError('missing prediction for `predict_at`')

View file

@ -84,41 +84,50 @@ class OrderHistory:
pixels.pixel_id,
DATE_TRUNC('MINUTE', orders.placed_at)
AS placed_at_without_seconds,
((
EXTRACT(MINUTES FROM orders.placed_at)::INTEGER
% {self._time_step}
)::TEXT || ' MINUTES')::INTERVAL
AS minutes_to_be_cut
(
(
(
EXTRACT(MINUTES FROM orders.placed_at)::INTEGER
% {self._time_step}
)::TEXT
||
' MINUTES'
)::INTERVAL
) AS minutes_to_be_cut
FROM (
SELECT
id,
placed_at,
pickup_address_id
{config.CLEAN_SCHEMA}.orders.id,
{config.CLEAN_SCHEMA}.orders.placed_at,
{config.CLEAN_SCHEMA}.orders.pickup_address_id
FROM
{config.CLEAN_SCHEMA}.orders
INNER JOIN (
SELECT
id AS address_id
{config.CLEAN_SCHEMA}.addresses.id AS address_id
FROM
{config.CLEAN_SCHEMA}.addresses
WHERE
city_id = {self._grid.city.id}
{config.CLEAN_SCHEMA}.addresses.city_id
= {self._grid.city.id}
) AS in_city
ON orders.pickup_address_id = in_city.address_id
ON {config.CLEAN_SCHEMA}.orders.pickup_address_id
= in_city.address_id
WHERE
ad_hoc IS TRUE
{config.CLEAN_SCHEMA}.orders.ad_hoc IS TRUE
) AS
orders
INNER JOIN (
SELECT
address_id,
pixel_id
{config.CLEAN_SCHEMA}.addresses_pixels.address_id,
{config.CLEAN_SCHEMA}.addresses_pixels.pixel_id
FROM
{config.CLEAN_SCHEMA}.addresses_pixels
WHERE
grid_id = {self._grid.id}
{config.CLEAN_SCHEMA}.addresses_pixels.grid_id
= {self._grid.id}
AND
city_id = {self._grid.city.id} -- -> sanity check
{config.CLEAN_SCHEMA}.addresses_pixels.city_id
= {self._grid.city.id} -- -> sanity check
) AS pixels
ON orders.pickup_address_id = pixels.address_id
) AS placed_at_aggregated_into_start_at