From 732a74be1c54179a89d3a1859df1a87aac2f6b5f Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 09:44:07 +0100 Subject: [PATCH 01/19] Declare `__all__` in all re-exporting packages Then, the linters know the imports are re-exports and not unused. --- src/velofy/forecasts/__init__.py | 7 +++++++ src/velofy/forecasts/methods/__init__.py | 8 ++++++++ tests/db/fake_data/factories/__init__.py | 11 +++++++++++ tests/db/fake_data/factories/orders/__init__.py | 7 +++++++ 4 files changed, 33 insertions(+) diff --git a/src/velofy/forecasts/__init__.py b/src/velofy/forecasts/__init__.py index 40a2c2c..bf5b5c5 100644 --- a/src/velofy/forecasts/__init__.py +++ b/src/velofy/forecasts/__init__.py @@ -27,3 +27,10 @@ applied to a horizontal time series is implemented in the `HorizontalETSModel`. from velofy.forecasts import methods from velofy.forecasts import models from velofy.forecasts import timify + + +__all__ = [ + "methods", + "models", + "timify", +] diff --git a/src/velofy/forecasts/methods/__init__.py b/src/velofy/forecasts/methods/__init__.py index 2d96068..aa57d9f 100644 --- a/src/velofy/forecasts/methods/__init__.py +++ b/src/velofy/forecasts/methods/__init__.py @@ -4,3 +4,11 @@ from velofy.forecasts.methods import arima from velofy.forecasts.methods import decomposition from velofy.forecasts.methods import ets from velofy.forecasts.methods import extrapolate_season + + +__all__ = [ + "arima", + "decomposition", + "ets", + "extrapolate_season", +] diff --git a/tests/db/fake_data/factories/__init__.py b/tests/db/fake_data/factories/__init__.py index 3d153ae..b0cc4e0 100644 --- a/tests/db/fake_data/factories/__init__.py +++ b/tests/db/fake_data/factories/__init__.py @@ -7,3 +7,14 @@ from tests.db.fake_data.factories.orders import AdHocOrderFactory from tests.db.fake_data.factories.orders import ReplayedOrderFactory from tests.db.fake_data.factories.orders import ScheduledOrderFactory from tests.db.fake_data.factories.restaurants import RestaurantFactory + + +__all__ = [ + "AdHocOrderFactory", + "AddressFactory", + "CourierFactory", + "CustomerFactory", + "ReplayedOrderFactory", + "RestaurantFactory", + "ScheduledOrderFactory", +] diff --git a/tests/db/fake_data/factories/orders/__init__.py b/tests/db/fake_data/factories/orders/__init__.py index d854b6c..e2e5e2a 100644 --- a/tests/db/fake_data/factories/orders/__init__.py +++ b/tests/db/fake_data/factories/orders/__init__.py @@ -3,3 +3,10 @@ from tests.db.fake_data.factories.orders.ad_hoc import AdHocOrderFactory from tests.db.fake_data.factories.orders.replayed import ReplayedOrderFactory from tests.db.fake_data.factories.orders.scheduled import ScheduledOrderFactory + + +__all__ = [ + "AdHocOrderFactory", + "ReplayedOrderFactory", + "ScheduledOrderFactory", +] From 454c2898a0932f6381494c485f09dd68a7c6357d Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 09:48:08 +0100 Subject: [PATCH 02/19] Remove the F401 ignore for `__init__.py` files All re-exporting packages declare `__all__`; so, unused imports are reported there, too. --- pyproject.toml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 48a7273..6cbf7bb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -351,8 +351,6 @@ extend-ignore = [ ] per-file-ignores = [ - # Top-levels of a sub-packages are intended to import a lot. - "**/__init__.py:F401", # Type annotations are not strictly enforced. "migrations/env.py:ANN0,ANN2", # - ANN0, ANN2 => Type annotations are not strictly enforced. @@ -733,8 +731,6 @@ external = [ [tool.ruff.lint.per-file-ignores] -# Top-levels of a sub-packages are intended to import a lot. -"**/__init__.py" = ["F401"] # Type annotations are not strictly enforced. "migrations/env.py" = ["ANN0", "ANN2"] # - ANN0, ANN2 => Type annotations are not strictly enforced. From 049a5f6f62e05f08ffdcb6ce90c1f07ec3042871 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 10:03:26 +0100 Subject: [PATCH 03/19] Remove periods from one-sentence comments --- migrations/env.py | 4 +- ...20210102_18_888e352d7526_add_pixel_grid.py | 4 +- ...05e_remove_orders_from_restaurants_with.py | 2 +- ...914_13_81aa304d7a6e_add_simulation_data.py | 10 +-- ...ename_constraints_to_follow_the_naming_.py | 2 +- pyproject.toml | 74 +++++++++---------- src/velofy/__init__.py | 2 +- src/velofy/configuration.py | 16 ++-- src/velofy/console/forecasts.py | 8 +- src/velofy/console/gridify.py | 2 +- src/velofy/console/main.py | 6 +- src/velofy/db/addresses.py | 2 +- src/velofy/db/addresses_addresses.py | 20 ++--- src/velofy/db/addresses_pixels.py | 4 +- src/velofy/db/cities.py | 10 +-- src/velofy/db/connection.py | 2 +- src/velofy/db/customers.py | 2 +- src/velofy/db/forecasts.py | 4 +- src/velofy/db/grids.py | 10 +-- src/velofy/db/orders.py | 6 +- src/velofy/db/pixels.py | 8 +- src/velofy/db/replay/orders.py | 10 +-- src/velofy/db/replay/simulations.py | 4 +- src/velofy/db/restaurants.py | 4 +- src/velofy/db/utils/locations.py | 2 +- src/velofy/forecasts/methods/arima.py | 8 +- src/velofy/forecasts/methods/decomposition.py | 8 +- src/velofy/forecasts/methods/ets.py | 8 +- .../forecasts/methods/extrapolate_season.py | 6 +- src/velofy/forecasts/models/base.py | 8 +- .../forecasts/models/tactical/horizontal.py | 14 ++-- src/velofy/forecasts/models/tactical/other.py | 8 +- .../forecasts/models/tactical/realtime.py | 14 ++-- .../forecasts/models/tactical/vertical.py | 14 ++-- src/velofy/forecasts/timify.py | 36 ++++----- src/velofy/init_r.py | 2 +- tests/config.py | 10 +-- tests/conftest.py | 8 +- tests/console/test_gridify.py | 6 +- tests/console/test_main.py | 2 +- tests/db/fake_data/factories/addresses.py | 4 +- tests/db/fake_data/factories/orders/ad_hoc.py | 8 +- .../fake_data/factories/orders/scheduled.py | 6 +- tests/db/fake_data/fixture_makers.py | 12 +-- tests/db/replay/test_orders.py | 18 ++--- tests/db/test_addresses.py | 4 +- tests/db/test_addresses_addresses.py | 16 ++-- tests/db/test_addresses_pixels.py | 10 +-- tests/db/test_forecasts.py | 6 +- tests/db/test_grids.py | 26 +++---- tests/db/test_orders.py | 70 +++++++++--------- tests/db/test_pixels.py | 2 +- tests/db/test_restaurants.py | 2 +- tests/db/utils/test_locations.py | 2 +- tests/forecasts/conftest.py | 2 +- tests/forecasts/methods/test_decomposition.py | 6 +- .../forecasts/timify/test_aggregate_orders.py | 34 ++++----- .../forecasts/timify/test_avg_daily_demand.py | 4 +- tests/test_config.py | 12 +-- tests/test_version.py | 2 +- 60 files changed, 308 insertions(+), 308 deletions(-) diff --git a/migrations/env.py b/migrations/env.py index 1f95d8c..69942d4 100644 --- a/migrations/env.py +++ b/migrations/env.py @@ -10,13 +10,13 @@ from velofy import config as pkg_config from velofy import db -# Disable the --sql option, a.k.a, the "offline mode". +# Disable the --sql option, a.k.a, the "offline mode" if context.is_offline_mode(): msg = "The --sql option is not implemented in this project" raise NotImplementedError(msg) -# Set up the default Python logger from the alembic.ini file. +# Set up the default Python logger from the alembic.ini file log_config.fileConfig(context.config.config_file_name) diff --git a/migrations/versions/rev_20210102_18_888e352d7526_add_pixel_grid.py b/migrations/versions/rev_20210102_18_888e352d7526_add_pixel_grid.py index cba80c2..9973ca9 100644 --- a/migrations/versions/rev_20210102_18_888e352d7526_add_pixel_grid.py +++ b/migrations/versions/rev_20210102_18_888e352d7526_add_pixel_grid.py @@ -37,7 +37,7 @@ def upgrade(): "side_length", name=op.f("uq_grids_on_city_id_side_length"), ), - # This `UniqueConstraint` is needed by the `addresses_pixels` table below. + # This `UniqueConstraint` is needed by the `addresses_pixels` table below sa.UniqueConstraint("id", "city_id", name=op.f("uq_grids_on_id_city_id")), schema=config.CLEAN_SCHEMA, ) @@ -90,7 +90,7 @@ def upgrade(): schema=config.CLEAN_SCHEMA, ) - # This `UniqueConstraint` is needed by the `addresses_pixels` table below. + # This `UniqueConstraint` is needed by the `addresses_pixels` table below op.create_unique_constraint( "uq_addresses_on_id_city_id", "addresses", diff --git a/migrations/versions/rev_20210123_15_e86290e7305e_remove_orders_from_restaurants_with.py b/migrations/versions/rev_20210123_15_e86290e7305e_remove_orders_from_restaurants_with.py index 088fc4b..6e10a38 100644 --- a/migrations/versions/rev_20210123_15_e86290e7305e_remove_orders_from_restaurants_with.py +++ b/migrations/versions/rev_20210123_15_e86290e7305e_remove_orders_from_restaurants_with.py @@ -326,7 +326,7 @@ def upgrade(): """, ) - # 4) Ensure every `Restaurant` has only one `Order.pickup_address`. + # 4) Ensure every `Restaurant` has only one `Order.pickup_address` op.execute( f""" UPDATE diff --git a/migrations/versions/rev_20210914_13_81aa304d7a6e_add_simulation_data.py b/migrations/versions/rev_20210914_13_81aa304d7a6e_add_simulation_data.py index fd4099d..e6a17a6 100644 --- a/migrations/versions/rev_20210914_13_81aa304d7a6e_add_simulation_data.py +++ b/migrations/versions/rev_20210914_13_81aa304d7a6e_add_simulation_data.py @@ -23,15 +23,15 @@ config = configuration.make_config("testing" if os.getenv("TESTING") else "produ def upgrade(): """Upgrade to revision 81aa304d7a6e.""" - # Drop unnecessary check constraint. - op.execute( # `.delivery_at` is not set for `.cancelled` orders anyways. + # Drop unnecessary check constraint + op.execute( # `.delivery_at` is not set for `.cancelled` orders anyways f""" ALTER TABLE {config.CLEAN_SCHEMA}.orders DROP CONSTRAINT ck_orders_on_ordered_timestamps_21; """, ) - # Add forgotten check constraints to the `orders` table. + # Add forgotten check constraints to the `orders` table op.execute( f""" ALTER TABLE {config.CLEAN_SCHEMA}.orders @@ -57,7 +57,7 @@ def upgrade(): """, ) - # This `UniqueConstraint` is needed by the `replayed_orders` table below. + # This `UniqueConstraint` is needed by the `replayed_orders` table below op.create_unique_constraint( "uq_orders_on_id_ad_hoc", "orders", @@ -125,7 +125,7 @@ def upgrade(): ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - # Needs the `UniqueConstraint` from above. + # Needs the `UniqueConstraint` from above ["actual_order_id", "ad_hoc"], [ f"{config.CLEAN_SCHEMA}.orders.id", diff --git a/migrations/versions/rev_20261201_22_87412e235878_rename_constraints_to_follow_the_naming_.py b/migrations/versions/rev_20261201_22_87412e235878_rename_constraints_to_follow_the_naming_.py index 9d7809d..e441b83 100644 --- a/migrations/versions/rev_20261201_22_87412e235878_rename_constraints_to_follow_the_naming_.py +++ b/migrations/versions/rev_20261201_22_87412e235878_rename_constraints_to_follow_the_naming_.py @@ -29,7 +29,7 @@ config = configuration.make_config("testing" if os.getenv("TESTING") else "produ # The order matters: the "ordered_timestamps_N" constraints are shifted -# by one from the top down such that every new name is free. +# by one from the top down such that every new name is free RENAMES = ( ( "forecasts", diff --git a/pyproject.toml b/pyproject.toml index 6cbf7bb..488e76c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -205,7 +205,7 @@ source = ["velofy"] # Source: https://flake8.pycqa.org/en/latest/user/configuration.html # Include error classes only explicitly -# to avoid forward compatibility issues. +# to avoid forward compatibility issues select = [ # ============= # flake8's base @@ -327,41 +327,41 @@ ignore = [] extend-ignore = [ # `ruff`'s A003 does this better, as it only flags actual shadowing "A003", - # Too long line => Duplicate with E501. + # Too long line => Duplicate with E501 "B950", - # PEP 257 documents the arguments of `__init__()` in its own docstring. + # PEP 257 documents the arguments of `__init__()` in its own docstring "DOC301", # Comply with black's style. # Source: https://github.com/psf/black/blob/master/docs/compatible_configs.md#flake8 "E203", "W503", - # `ruff`'s FBT003 does this better, as it allows builtins like `setattr()`. + # `ruff`'s FBT003 does this better, as it allows builtins like `setattr()` "FBT003", - # Every `.add()` looks like `pandas` to this rule (`ruff` omits it). + # Every `.add()` looks like `pandas` to this rule (`ruff` omits it) "PD005", - # Let's not do `@pytest.mark.no_cover()` instead of `@pytest.mark.no_cover`. + # Let's not do `@pytest.mark.no_cover()` instead of `@pytest.mark.no_cover` "PT023", - # Allow f-strings as the only type of string formatting. + # Allow f-strings as the only type of string formatting "SFS301", - # `bool()` around a comparison can be deliberate (`ruff` omits this rule). + # `bool()` around a comparison can be deliberate (`ruff` omits this rule) "SIM901", - # TODOs need neither an author nor an issue. + # TODOs need neither an author nor an issue "T002", "T003", - # Messages are written where the exceptions are raised. + # Messages are written where the exceptions are raised "TRY003", ] per-file-ignores = [ - # Type annotations are not strictly enforced. + # Type annotations are not strictly enforced "migrations/env.py:ANN0,ANN2", - # - ANN0, ANN2 => Type annotations are not strictly enforced. - # - S608 => Do not worry about SQL injection here. + # - ANN0, ANN2 => Type annotations are not strictly enforced + # - S608 => Do not worry about SQL injection here "migrations/versions/*.py:ANN0,ANN2,S608", - # Type annotations are not strictly enforced. + # Type annotations are not strictly enforced "noxfile.py:ANN0,ANN2", - # - ANN0, ANN2, DOC106, DOC107 => Type annotations are not strictly enforced. - # - D106 => The `Meta` class inside the factory_boy models do not need a docstring. - # - S101 => `assert` statements are ok in the test suite. - # - S311 => The `random` module is not used for cryptography. + # - ANN0, ANN2, DOC106, DOC107 => Type annotations are not strictly enforced + # - D106 => The `Meta` class inside the factory_boy models do not need a docstring + # - S101 => `assert` statements are ok in the test suite + # - S311 => The `random` module is not used for cryptography "tests/*.py:ANN0,ANN2,D106,DOC106,DOC107,S101,S311", ] @@ -374,7 +374,7 @@ max-complexity = 10 # Source: https://github.com/psf/black/blob/master/docs/the_black_code_style.md#line-length max-line-length = 88 -# Preview the code lines that cause errors. +# Preview the code lines that cause errors show-source = true # pydoclint @@ -396,7 +396,7 @@ unused-arguments-ignore-abstract-functions = true # ============================== # flake8-pytest-style's settings # ============================== -# Prefer @pytest.fixture over @pytest.fixture(). +# Prefer @pytest.fixture over @pytest.fixture() pytest-fixture-no-parentheses = true # Prefer @pytest.mark.parametrize(['param1', 'param2'], [(1, 2), (3, 4)]) # over @pytest.mark.parametrize(('param1', 'param2'), ([1, 2], [3, 4])) @@ -705,19 +705,19 @@ select = [ ] extend-ignore = [ - # Let the formatter handle trailing commas. + # Let the formatter handle trailing commas "COM812", - # Thresholds like the ones in the maps read better as literals. + # Thresholds like the ones in the maps read better as literals "PLR2004", - # Let's not do `@pytest.mark.no_cover()` instead of `@pytest.mark.no_cover`. + # Let's not do `@pytest.mark.no_cover()` instead of `@pytest.mark.no_cover` "PT023", - # An `elif` after a `return` keeps a case distinction together. + # An `elif` after a `return` keeps a case distinction together "RET505", - # Some "# noqa" comments are only for `flake8`, which `ruff` cannot know. + # Some "# noqa" comments are only for `flake8`, which `ruff` cannot know "RUF100", - # TODOs need neither an author nor an issue. + # TODOs need neither an author nor an issue "TD002", "TD003", - # Messages are written where the exceptions are raised. + # Messages are written where the exceptions are raised "TRY003", ] @@ -731,21 +731,21 @@ external = [ [tool.ruff.lint.per-file-ignores] -# Type annotations are not strictly enforced. +# Type annotations are not strictly enforced "migrations/env.py" = ["ANN0", "ANN2"] -# - ANN0, ANN2 => Type annotations are not strictly enforced. -# - S608 => Do not worry about SQL injection here. +# - ANN0, ANN2 => Type annotations are not strictly enforced +# - S608 => Do not worry about SQL injection here "migrations/versions/*.py" = ["ANN0", "ANN2", "S608"] -# Type annotations are not strictly enforced. +# Type annotations are not strictly enforced "noxfile.py" = ["ANN0", "ANN2"] # `print()` is ok in ad-hoc scripts "scripts/**" = ["T20"] -# - ANN0, ANN2 => Type annotations are not strictly enforced. -# - D106 => The `Meta` class inside the factory_boy models do not need a docstring. -# - PLR0913, PLR0917 => `pytest` passes fixtures as arguments. -# - S101 => `assert` statements are ok in the test suite. -# - S311 => The `random` module is not used for cryptography. -# - SLF001 => Tests may set up and inspect private members. +# - ANN0, ANN2 => Type annotations are not strictly enforced +# - D106 => The `Meta` class inside the factory_boy models do not need a docstring +# - PLR0913, PLR0917 => `pytest` passes fixtures as arguments +# - S101 => `assert` statements are ok in the test suite +# - S311 => The `random` module is not used for cryptography +# - SLF001 => Tests may set up and inspect private members "tests/**/*.py" = ["ANN0", "ANN2", "D106", "PLR0913", "PLR0917", "S101", "S311", "SLF001"] diff --git a/src/velofy/__init__.py b/src/velofy/__init__.py index cc0cd75..d30e38a 100644 --- a/src/velofy/__init__.py +++ b/src/velofy/__init__.py @@ -6,7 +6,7 @@ Example: True """ -# The config object must come before all other project-internal imports. +# The config object must come before all other project-internal imports from velofy.configuration import config # isort:skip from importlib import metadata as _metadata diff --git a/src/velofy/configuration.py b/src/velofy/configuration.py index 1660de8..88cb336 100644 --- a/src/velofy/configuration.py +++ b/src/velofy/configuration.py @@ -27,14 +27,14 @@ class Config: # Application-specific settings # ----------------------------- - # Date after which the real-life data is discarded. + # Date after which the real-life data is discarded CUTOFF_DAY = dt.datetime(2017, 2, 1) # If a scheduled pre-order is made within this - # time horizon, we treat it as an ad-hoc order. + # time horizon, we treat it as an ad-hoc order QUASI_AD_HOC_LIMIT = dt.timedelta(minutes=45) - # Operating hours of the platform. + # Operating hours of the platform SERVICE_START = 11 SERVICE_END = 23 @@ -43,7 +43,7 @@ class Config: GRID_SIDE_LENGTHS = (707, 1000, 1414) # Time steps (in minutes) used to aggregate the - # individual orders into time series. + # individual orders into time series TIME_STEPS = (60,) # Training horizons (in full weeks) used to train the forecasting models. @@ -51,10 +51,10 @@ class Config: # a previous study (note:4f79e8fa). TRAIN_HORIZONS = (7, 8) - # The demand forecasting methods used in the simulations. + # The demand forecasting methods used in the simulations FORECASTING_METHODS = ("hets", "rtarima") - # Colors for the visualizations ins `folium`. + # Colors for the visualizations ins `folium` RESTAURANT_COLOR = "red" CUSTOMER_COLOR = "blue" NEUTRAL_COLOR = "black" @@ -65,10 +65,10 @@ class Config: DATABASE_URI = os.getenv("DATABASE_URI") GOOGLE_MAPS_API_KEY = os.getenv("GOOGLE_MAPS_API_KEY") - # The PostgreSQL schema that holds the tables with the original data. + # The PostgreSQL schema that holds the tables with the original data ORIGINAL_SCHEMA = os.getenv("ORIGINAL_SCHEMA") or "public" - # The PostgreSQL schema that holds the tables with the cleaned data. + # The PostgreSQL schema that holds the tables with the cleaned data CLEAN_SCHEMA = os.getenv("CLEAN_SCHEMA") or "clean" ALEMBIC_TABLE = "alembic_version" diff --git a/src/velofy/console/forecasts.py b/src/velofy/console/forecasts.py index 9327635..d1841b8 100644 --- a/src/velofy/console/forecasts.py +++ b/src/velofy/console/forecasts.py @@ -65,7 +65,7 @@ def tactical_heuristic( # noqa:C901,D417,DOC001 TRAIN_HORIZON: length of the training horizon; defaults to `8` """ # noqa:D412,D417 => Formatted as `click` help text - # Input validation. + # Input validation try: city_obj = db.session.scalars( @@ -96,11 +96,11 @@ def tactical_heuristic( # noqa:C901,D417,DOC001 f"time_step={time_step}, train_horizon={train_horizon}", ) - # Load the historic order data. + # Load the historic order data order_history = timify.OrderHistory(grid=grid, time_step=time_step) order_history.aggregate_orders() - # Run the tactical heuristic. + # Run the tactical heuristic for pixel in grid.pixels: # Important: this check may need to be adapted once further @@ -136,7 +136,7 @@ def tactical_heuristic( # noqa:C901,D417,DOC001 f"for {predict_day} with {model.name}", ) - # Only loop over the time steps corresponding to working hours. + # Only loop over the time steps corresponding to working hours predict_at = dt.datetime( predict_day.year, predict_day.month, diff --git a/src/velofy/console/gridify.py b/src/velofy/console/gridify.py index 56f993e..76d4ada 100644 --- a/src/velofy/console/gridify.py +++ b/src/velofy/console/gridify.py @@ -36,7 +36,7 @@ def gridify() -> None: # pragma: no cover note:b1f68d24 click.echo(f" -> created {len(grid.pixels)} pixels") # Because the number of assigned addresses is the same across - # different `side_length`s, we can take the last `grid` from the `city`. + # different `side_length`s, we can take the last `grid` from the `city` last_grid_id = grid.id # type: ignore[possibly-undefined] n_assigned = db.session.execute( sa.select(sa.func.count()) diff --git a/src/velofy/console/main.py b/src/velofy/console/main.py index 0c7dac5..c96bd65 100644 --- a/src/velofy/console/main.py +++ b/src/velofy/console/main.py @@ -16,14 +16,14 @@ def show_version( ) -> None: """Show the package's version.""" # If --version / -V is NOT passed in, - # continue with the command. + # continue with the command if not value or ctx.resilient_parsing: return - # Mimic the colors of `poetry version`. + # Mimic the colors of `poetry version` pkg_name = click.style(velofy.__pkg_name__, fg="green") version = click.style(velofy.__version__, fg="blue") - # Include a warning for development versions. + # Include a warning for development versions warning = click.style(" (development)", fg="red") if ".dev" in version else "" click.echo(f"{pkg_name}, version {version}{warning}") ctx.exit() diff --git a/src/velofy/db/addresses.py b/src/velofy/db/addresses.py index 2ba8588..06c70c2 100644 --- a/src/velofy/db/addresses.py +++ b/src/velofy/db/addresses.py @@ -95,7 +95,7 @@ class Address(meta.Base): "-180 <= longitude AND longitude <= 180", name="longitude_between_180_degrees", ), - # Needed by a `ForeignKeyConstraint` in `AddressPixelAssociation`. + # Needed by a `ForeignKeyConstraint` in `AddressPixelAssociation` sa.UniqueConstraint("id", "city_id"), sa.CheckConstraint( "30000 <= zip_code AND zip_code <= 99999", diff --git a/src/velofy/db/addresses_addresses.py b/src/velofy/db/addresses_addresses.py index 25c545f..1919794 100644 --- a/src/velofy/db/addresses_addresses.py +++ b/src/velofy/db/addresses_addresses.py @@ -48,7 +48,7 @@ class Path(meta.Base): sa.SmallInteger, nullable=False, ) - # Distances are measured in meters. + # Distances are measured in meters air_distance: orm.Mapped[int] = orm.mapped_column( sa.Integer, nullable=False, @@ -57,12 +57,12 @@ class Path(meta.Base): sa.Integer, nullable=True, ) - # The duration is measured in seconds. + # The duration is measured in seconds bicycle_duration: orm.Mapped[int | None] = orm.mapped_column( sa.Integer, nullable=True, ) - # An array of latitude-longitude pairs approximating a courier's way. + # An array of latitude-longitude pairs approximating a courier's way _directions: orm.Mapped[list[list[float]] | None] = orm.mapped_column( "directions", psql.JSON, @@ -71,7 +71,7 @@ class Path(meta.Base): # Constraints __table_args__ = ( - # The two `Address` objects must be in the same `.city`. + # The two `Address` objects must be in the same `.city` sa.ForeignKeyConstraint( ["first_address_id", "city_id"], ["addresses.id", "addresses.city_id"], @@ -84,7 +84,7 @@ class Path(meta.Base): onupdate="RESTRICT", ondelete="RESTRICT", ), - # Each `Address`-`Address` pair only has one distance. + # Each `Address`-`Address` pair only has one distance sa.UniqueConstraint("first_address_id", "second_address_id"), sa.CheckConstraint( "first_address_id < second_address_id", @@ -96,7 +96,7 @@ class Path(meta.Base): ), sa.CheckConstraint( "bicycle_distance < 25000", # `.bicycle_distance` may not be negative - name="realistic_bicycle_distance", # due to the constraint below. + name="realistic_bicycle_distance", # due to the constraint below ), sa.CheckConstraint( "air_distance <= bicycle_distance", @@ -212,7 +212,7 @@ class Path(meta.Base): https://developers.google.com/maps/documentation/directions """ # To save costs, we do not make an API call - # if we already have data from Google Maps. + # if we already have data from Google Maps if self.bicycle_distance is not None: return @@ -302,11 +302,11 @@ class Path(meta.Base): `.map` for convenience in interactive usage """ # Without `self._directions` synced from Google Maps, - # the `.waypoints` are not available. + # the `.waypoints` are not available self.sync_with_google_maps() # First, plot the couriers' path between the start and - # end locations, so that it is below the `folium.Circle`s. + # end locations, so that it is below the `folium.Circle`s line = folium.PolyLine( locations=( self.first_address.location.lat_lng, @@ -319,7 +319,7 @@ class Path(meta.Base): line.add_to(self.map) # Draw the path's start and end locations, possibly reversed, - # on top of the couriers' path. + # on top of the couriers' path if reverse: start, end = self.second_address, self.first_address diff --git a/src/velofy/db/addresses_pixels.py b/src/velofy/db/addresses_pixels.py index 3fd5ed2..dc20b4a 100644 --- a/src/velofy/db/addresses_pixels.py +++ b/src/velofy/db/addresses_pixels.py @@ -53,9 +53,9 @@ class AddressPixelAssociation(meta.Base): onupdate="RESTRICT", ondelete="RESTRICT", ), - # Each `Address` can only be on a `Grid` once. + # Each `Address` can only be on a `Grid` once sa.UniqueConstraint("address_id", "grid_id"), - # An association must reference an existing `Grid`-`Pixel` pair. + # An association must reference an existing `Grid`-`Pixel` pair sa.ForeignKeyConstraint( ["pixel_id", "grid_id"], ["pixels.id", "pixels.grid_id"], diff --git a/src/velofy/db/cities.py b/src/velofy/db/cities.py index 94cc1aa..7a54a24 100644 --- a/src/velofy/db/cities.py +++ b/src/velofy/db/cities.py @@ -78,7 +78,7 @@ class City(meta.Base): back_populates="city", ) - # We do not implement a `.__init__()` method and use SQLAlchemy's default. + # We do not implement a `.__init__()` method and use SQLAlchemy's default def __repr__(self) -> str: """Non-literal text representation.""" @@ -162,7 +162,7 @@ class City(meta.Base): Returns: `.map` for convenience in interactive usage """ - # Obtain all primary `Address`es in the city that host `Restaurant`s. + # Obtain all primary `Address`es in the city that host `Restaurant`s addresses = db.session.scalars( sa.select(db.Address).where( db.Address.id.in_( @@ -236,7 +236,7 @@ class City(meta.Base): Returns: `.map` for convenience in interactive usage """ - # First, create a color map with distinct colors for each zip code. + # First, create a color map with distinct colors for each zip code all_zip_codes = sorted( row[0] for row in db.session.execute( @@ -258,9 +258,9 @@ class City(meta.Base): for index, code in enumerate(all_zip_codes) } - # Second, draw every address on the `.map. + # Second, draw every address on the `.map` for address in self.addresses: - # Non-primary addresses are covered by primary ones anyway. + # Non-primary addresses are covered by primary ones anyway if not address.is_primary: continue diff --git a/src/velofy/db/connection.py b/src/velofy/db/connection.py index 0e4a8cf..bab7f56 100644 --- a/src/velofy/db/connection.py +++ b/src/velofy/db/connection.py @@ -23,7 +23,7 @@ def get_engine() -> sa.Engine: # `scoped_session()` accepts any callable creating sessions # while its type stubs expect a `sessionmaker` -# => The lambda defers creating the engine to first use. +# => The lambda defers creating the engine to first use session: orm.scoped_session[orm.Session] = orm.scoped_session( t.cast( "orm.sessionmaker[orm.Session]", diff --git a/src/velofy/db/customers.py b/src/velofy/db/customers.py index f25b519..15fb3c2 100644 --- a/src/velofy/db/customers.py +++ b/src/velofy/db/customers.py @@ -70,7 +70,7 @@ class Customer(meta.Base): # That is not true for `Restaurant`s after the data cleaning. # Obtain all primary `Address`es where - # at least one delivery was made to `self`. + # at least one delivery was made to `self` delivery_addresses = db.session.scalars( sa.select(db.Address).where( db.Address.id.in_( diff --git a/src/velofy/db/forecasts.py b/src/velofy/db/forecasts.py index 6981aae..31ef318 100644 --- a/src/velofy/db/forecasts.py +++ b/src/velofy/db/forecasts.py @@ -63,7 +63,7 @@ class Forecast(meta.Base): nullable=False, ) # The confidence intervals are treated like the `.prediction`s - # but they may be nullable as some methods do not calculate them. + # but they may be nullable as some methods do not calculate them low80: orm.Mapped[float | None] = orm.mapped_column( psql.DOUBLE_PRECISION, nullable=True, @@ -165,7 +165,7 @@ class Forecast(meta.Base): """, name="ci95_must_be_wider_than_ci80", ), - # There can be only one prediction per forecasting setting. + # There can be only one prediction per forecasting setting sa.UniqueConstraint( "pixel_id", "start_at", diff --git a/src/velofy/db/grids.py b/src/velofy/db/grids.py index f711473..b5ffd91 100644 --- a/src/velofy/db/grids.py +++ b/src/velofy/db/grids.py @@ -43,9 +43,9 @@ class Grid(meta.Base): ondelete="RESTRICT", ), # Each `Grid`, characterized by its `.side_length`, - # may only exists once for a given `.city`. + # may only exists once for a given `.city` sa.UniqueConstraint("city_id", "side_length"), - # Needed by a `ForeignKeyConstraint` in `address_pixel_association`. + # Needed by a `ForeignKeyConstraint` in `address_pixel_association` sa.UniqueConstraint("id", "city_id"), ) @@ -88,10 +88,10 @@ class Grid(meta.Base): city.grids.append(grid) - # `Pixel`s grouped by `.n_x`-`.n_y` coordinates. + # `Pixel`s grouped by `.n_x`-`.n_y` coordinates pixels = {} - # `.unique()` because the `JOIN` yields an `Address` once per `Order`. + # `.unique()` because the `JOIN` yields an `Address` once per `Order` pickup_addresses = ( db.session.scalars( sa.select(db.Address) @@ -123,7 +123,7 @@ class Grid(meta.Base): pixel = pixels[(n_x, n_y)] - # Create an association between the `address` and `pixel`. + # Create an association between the `address` and `pixel` assoc = db.AddressPixelAssociation(address=address, pixel=pixel) pixel.addresses.append(assoc) diff --git a/src/velofy/db/orders.py b/src/velofy/db/orders.py index 4aaa6bf..e0878bc 100644 --- a/src/velofy/db/orders.py +++ b/src/velofy/db/orders.py @@ -275,7 +275,7 @@ class Order(meta.Base): onupdate="RESTRICT", ondelete="RESTRICT", ), - # Needed by a `ForeignKeyConstraint` in `ReplayedOrder`. + # Needed by a `ForeignKeyConstraint` in `ReplayedOrder` sa.UniqueConstraint("id", "ad_hoc"), sa.CheckConstraint( """ @@ -789,7 +789,7 @@ class Order(meta.Base): customer_tooltip = f"Customer #{self.customer.id}" # Because the underlying distance matrix is symmetric (i.e., a DB constraint), - # we must check if the `.pickup_address` is the couriers' `Path`'s start. + # we must check if the `.pickup_address` is the couriers' `Path`'s start if path.first_address is self.pickup_address: reverse = False start_tooltip, end_tooltip = restaurant_tooltip, customer_tooltip @@ -797,7 +797,7 @@ class Order(meta.Base): reverse = True start_tooltip, end_tooltip = customer_tooltip, restaurant_tooltip - # This triggers `Path.sync_with_google_maps()` behind the scenes. + # This triggers `Path.sync_with_google_maps()` behind the scenes return path.draw( reverse=reverse, start_tooltip=start_tooltip, diff --git a/src/velofy/db/pixels.py b/src/velofy/db/pixels.py index 321f5fc..2ddb3ef 100644 --- a/src/velofy/db/pixels.py +++ b/src/velofy/db/pixels.py @@ -57,9 +57,9 @@ class Pixel(meta.Base): ), sa.CheckConstraint("0 <= n_x", name="n_x_is_positive"), sa.CheckConstraint("0 <= n_y", name="n_y_is_positive"), - # Needed by a `ForeignKeyConstraint` in `AddressPixelAssociation`. + # Needed by a `ForeignKeyConstraint` in `AddressPixelAssociation` sa.UniqueConstraint("id", "grid_id"), - # Each coordinate within the same `grid` is used at most once. + # Each coordinate within the same `grid` is used at most once sa.UniqueConstraint("grid_id", "n_x", "n_y"), ) @@ -186,7 +186,7 @@ class Pixel(meta.Base): ) info_text = f"Pixel({self.n_x}|{self.n_y})" - # Make the `Pixel`s look like a checkerboard. + # Make the `Pixel`s look like a checkerboard color = "#808000" if (self.n_x + self.n_y) % 2 else "#ff8c00" marker = folium.Rectangle( @@ -203,7 +203,7 @@ class Pixel(meta.Base): if restaurants: # Obtain all primary `Address`es in the city that host `Restaurant`s - # and are in the `self` `Pixel`. + # and are in the `self` `Pixel` addresses = db.session.scalars( sa.select(db.Address).where( db.Address.id.in_( diff --git a/src/velofy/db/replay/orders.py b/src/velofy/db/replay/orders.py index 708f3e9..ffe126e 100644 --- a/src/velofy/db/replay/orders.py +++ b/src/velofy/db/replay/orders.py @@ -27,7 +27,7 @@ class ReplayedOrder(meta.Base): # `Order`-type related columns # `.ad_hoc` is part of a `ForeignKeyConstraint` to ensure the type # of the `ReplayedOrder` (i.e., ad-hoc or scheduled) is in line - # with the `.actual` order. + # with the `.actual` order ad_hoc: orm.Mapped[bool] = orm.mapped_column( sa.Boolean, nullable=False, @@ -36,13 +36,13 @@ class ReplayedOrder(meta.Base): sa.DateTime, nullable=False, ) - # Depending on `.ad_hoc`, `.scheduled_delivery_at` is either filled in or not. + # Depending on `.ad_hoc`, `.scheduled_delivery_at` is either filled in or not scheduled_delivery_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( sa.DateTime, nullable=True, ) # If an order is cancelled in a simulation, - # some of the columns below do not apply any more. + # some of the columns below do not apply any more cancelled_at: orm.Mapped[dt.datetime | None] = orm.mapped_column( sa.DateTime, nullable=True, @@ -137,11 +137,11 @@ class ReplayedOrder(meta.Base): onupdate="RESTRICT", ondelete="RESTRICT", ), - # The check constraints model some of the assumptions made in the simulations. + # The check constraints model some of the assumptions made in the simulations sa.CheckConstraint( # Align the order's type, ad-hoc or scheduled, with the type of the # `.actual` order and ensure the corresponding datetime column is set - # or not set. + # or not set """ ( ad_hoc IS TRUE diff --git a/src/velofy/db/replay/simulations.py b/src/velofy/db/replay/simulations.py index 50b93c3..76d047d 100644 --- a/src/velofy/db/replay/simulations.py +++ b/src/velofy/db/replay/simulations.py @@ -31,7 +31,7 @@ class ReplaySimulation(meta.Base): nullable=False, index=True, ) - # `.run` may be used as random seed. + # `.run` may be used as random seed run: orm.Mapped[int] = orm.mapped_column( sa.SmallInteger, nullable=False, @@ -45,7 +45,7 @@ class ReplaySimulation(meta.Base): onupdate="RESTRICT", ondelete="RESTRICT", ), - # A `.strategy` can be replayed several times per `.city`. + # A `.strategy` can be replayed several times per `.city` sa.UniqueConstraint("city_id", "strategy", "run"), sa.CheckConstraint("run >= 0", name="run_is_a_count"), ) diff --git a/src/velofy/db/restaurants.py b/src/velofy/db/restaurants.py index 34f9233..7a01f52 100644 --- a/src/velofy/db/restaurants.py +++ b/src/velofy/db/restaurants.py @@ -58,7 +58,7 @@ class Restaurant(meta.Base): "0 <= estimated_prep_duration AND estimated_prep_duration <= 2400", name="realistic_estimated_prep_duration", ), - # Needed by a `ForeignKeyConstraint` in `Order`. + # Needed by a `ForeignKeyConstraint` in `Order` sa.UniqueConstraint("id", "address_id"), ) @@ -111,7 +111,7 @@ class Restaurant(meta.Base): """ if customers: # Obtain all primary `Address`es in the city that - # received at least one delivery from `self`. + # received at least one delivery from `self` delivery_addresses = db.session.scalars( sa.select(db.Address).where( db.Address.id.in_( diff --git a/src/velofy/db/utils/locations.py b/src/velofy/db/utils/locations.py index 2859f94..0f234b9 100644 --- a/src/velofy/db/utils/locations.py +++ b/src/velofy/db/utils/locations.py @@ -27,7 +27,7 @@ class Location: easting, northing, zone, band = utm.from_latlon(self._latitude, self._longitude) - # `.easting` and `.northing` as `int`s are precise enough. + # `.easting` and `.northing` as `int`s are precise enough self._easting = int(easting) self._northing = int(northing) self._zone = zone diff --git a/src/velofy/forecasts/methods/arima.py b/src/velofy/forecasts/methods/arima.py index 7c09898..da5a7da 100644 --- a/src/velofy/forecasts/methods/arima.py +++ b/src/velofy/forecasts/methods/arima.py @@ -35,14 +35,14 @@ def predict( # For example, the nox session "ci-tests-fast" does not use it. from velofy import init_r # noqa:F401,PLC0415 - # Re-seed R every time it is used to ensure reproducibility. + # Re-seed R every time it is used to ensure reproducibility robjects.r("set.seed(42)") if training_ts.isna().any(): msg = "`training_ts` must not contain `NaN` values" raise ValueError(msg) - # Copy the data from Python to R. + # Copy the data from Python to R robjects.globalenv["data"] = robjects.r["ts"]( pandas2ri.py2rpy(training_ts), frequency=frequency, @@ -51,7 +51,7 @@ def predict( seasonal = "TRUE" if seasonal_fit else "FALSE" n_steps_ahead = len(forecast_interval) - # Make the predictions in R. + # Make the predictions in R result = robjects.r( f""" as.data.frame( @@ -63,7 +63,7 @@ def predict( """, ) - # Convert the results into a nice `pd.DataFrame` with the right `.index`. + # Convert the results into a nice `pd.DataFrame` with the right `.index` forecasts: pd.DataFrame = pandas2ri.rpy2py(result) forecasts.index = forecast_interval diff --git a/src/velofy/forecasts/methods/decomposition.py b/src/velofy/forecasts/methods/decomposition.py index 85099b0..ec71fec 100644 --- a/src/velofy/forecasts/methods/decomposition.py +++ b/src/velofy/forecasts/methods/decomposition.py @@ -91,7 +91,7 @@ def stl( # noqa:C901,PLR0912,PLR0913,PLR0915 Raises: ValueError: some argument does not adhere to the specifications above """ - # Validate all arguments and set default values. + # Validate all arguments and set default values if time_series.isna().any(): msg = "`time_series` must not contain `NaN` values" @@ -167,10 +167,10 @@ def stl( # noqa:C901,PLR0912,PLR0913,PLR0915 # For example, the nox session "ci-tests-fast" does not use it. from velofy import init_r # noqa:F401,PLC0415 - # Re-seed R every time it is used to ensure reproducibility. + # Re-seed R every time it is used to ensure reproducibility robjects.r("set.seed(42)") - # Call the STL function in R. + # Call the STL function in R ts = robjects.r["ts"](pandas2ri.py2rpy(time_series), frequency=frequency) result = robjects.r["stl"]( ts, @@ -188,7 +188,7 @@ def stl( # noqa:C901,PLR0912,PLR0913,PLR0915 no, ) - # Unpack the result to a `pd.DataFrame`. + # Unpack the result to a `pd.DataFrame` result = pandas2ri.rpy2py(result[0]) result = pd.DataFrame( data={ diff --git a/src/velofy/forecasts/methods/ets.py b/src/velofy/forecasts/methods/ets.py index d9691ff..021786e 100644 --- a/src/velofy/forecasts/methods/ets.py +++ b/src/velofy/forecasts/methods/ets.py @@ -36,14 +36,14 @@ def predict( # For example, the nox session "ci-tests-fast" does not use it. from velofy import init_r # noqa:F401,PLC0415 - # Re-seed R every time it is used to ensure reproducibility. + # Re-seed R every time it is used to ensure reproducibility robjects.r("set.seed(42)") if training_ts.isna().any(): msg = "`training_ts` must not contain `NaN` values" raise ValueError(msg) - # Copy the data from Python to R. + # Copy the data from Python to R robjects.globalenv["data"] = robjects.r["ts"]( pandas2ri.py2rpy(training_ts), frequency=frequency, @@ -52,7 +52,7 @@ def predict( model = "ZZZ" if seasonal_fit else "ZZN" n_steps_ahead = len(forecast_interval) - # Make the predictions in R. + # Make the predictions in R result = robjects.r( f""" as.data.frame( @@ -64,7 +64,7 @@ def predict( """, ) - # Convert the results into a nice `pd.DataFrame` with the right `.index`. + # Convert the results into a nice `pd.DataFrame` with the right `.index` forecasts: pd.DataFrame = pandas2ri.rpy2py(result) forecasts.index = forecast_interval diff --git a/src/velofy/forecasts/methods/extrapolate_season.py b/src/velofy/forecasts/methods/extrapolate_season.py index 021a413..deab4fc 100644 --- a/src/velofy/forecasts/methods/extrapolate_season.py +++ b/src/velofy/forecasts/methods/extrapolate_season.py @@ -45,12 +45,12 @@ def predict( for lag in range(frequency): # Obtain all `observations` of the same seasonal lag and - # fit a straight line through them (= `trend`). + # fit a straight line through them (= `trend`) observations = training_ts[slice(lag, 999_999_999, frequency)] trend = observations - tsa.detrend(observations) # Create a point forecast by linear extrapolation - # for one or even more time steps ahead. + # for one or even more time steps ahead slope = trend.iloc[-1] - trend.iloc[-2] prediction = trend.iloc[-1] + slope idx = observations.index.max() + seasonal_lag @@ -60,7 +60,7 @@ def predict( prediction += slope idx += seasonal_lag - # Sanity check. + # Sanity check if extrapolated_ts.isna().any(): # pragma: no cover msg = "missing predictions in the `forecast_interval`" raise ValueError(msg) diff --git a/src/velofy/forecasts/models/base.py b/src/velofy/forecasts/models/base.py index 2cc5671..fd8e9c0 100644 --- a/src/velofy/forecasts/models/base.py +++ b/src/velofy/forecasts/models/base.py @@ -94,10 +94,10 @@ class ForecastingModelABC(abc.ABC): # Horizontal and real-time `*Model`s return a `pd.DataFrame` with one # row corresponding to the time step starting at `predict_at` whereas - # vertical models return several rows, covering all time steps of a day. + # vertical models return several rows, covering all time steps of a day predictions = self.predict(pixel, predict_at, train_horizon) - # Convert the `predictions` into a `list` of `Forecast` objects. + # Convert the `predictions` into a `list` of `Forecast` objects forecasts = db.Forecast.from_dataframe( pixel=pixel, time_step=self._order_history.time_step, @@ -107,7 +107,7 @@ class ForecastingModelABC(abc.ABC): ) # We persist all `Forecast`s into the database to - # not have to run the same model training again. + # not have to run the same model training again db.session.add_all(forecasts) db.session.commit() @@ -117,7 +117,7 @@ class ForecastingModelABC(abc.ABC): if forecast.start_at == predict_at: return forecast - # ..., however, we put in a loud error, just in case. + # ..., however, we put in a loud error, just in case msg = ( # pragma: no cover "`Forecast` for `predict_at` was not returned by `*Model.predict()`" ) diff --git a/src/velofy/forecasts/models/tactical/horizontal.py b/src/velofy/forecasts/models/tactical/horizontal.py index 4d262d2..fa11e35 100644 --- a/src/velofy/forecasts/models/tactical/horizontal.py +++ b/src/velofy/forecasts/models/tactical/horizontal.py @@ -43,19 +43,19 @@ class HorizontalETSModel(base.ForecastingModelABC): Raises: RuntimeError: an internal consistency check fails """ - # Generate the historic (and horizontal) order time series. + # Generate the historic (and horizontal) order time series training_ts, frequency, actuals_ts = self._order_history.make_horizontal_ts( pixel_id=pixel.id, predict_at=predict_at, train_horizon=train_horizon, ) - # Sanity check. + # Sanity check if frequency != 7: # pragma: no cover msg = "`frequency` should be `7`" raise RuntimeError(msg) - # Make `predictions` with the seasonal ETS method ("ZZZ" model). + # Make `predictions` with the seasonal ETS method ("ZZZ" model) predictions = methods.ets.predict( training_ts=training_ts, forecast_interval=pd.DatetimeIndex(actuals_ts.index), @@ -65,7 +65,7 @@ class HorizontalETSModel(base.ForecastingModelABC): predictions.insert(loc=0, column="actual", value=actuals_ts) - # Sanity checks. + # Sanity checks if predictions.isna().sum().any(): # pragma: no cover msg = "missing predictions in hets model" raise RuntimeError(msg) @@ -103,14 +103,14 @@ class HorizontalSMAModel(base.ForecastingModelABC): Raises: RuntimeError: an internal consistency check fails """ - # Generate the historic (and horizontal) order time series. + # Generate the historic (and horizontal) order time series training_ts, frequency, actuals_ts = self._order_history.make_horizontal_ts( pixel_id=pixel.id, predict_at=predict_at, train_horizon=train_horizon, ) - # Sanity checks. + # Sanity checks if frequency != 7: # pragma: no cover msg = "`frequency` should be `7`" raise RuntimeError(msg) @@ -133,7 +133,7 @@ class HorizontalSMAModel(base.ForecastingModelABC): index=actuals_ts.index, ) - # Sanity checks. + # Sanity checks if predictions[["actual", "prediction"]].isna().any().any(): # pragma: no cover msg = "missing predictions in hsma model" raise RuntimeError(msg) diff --git a/src/velofy/forecasts/models/tactical/other.py b/src/velofy/forecasts/models/tactical/other.py index 0d0008e..ccb35d9 100644 --- a/src/velofy/forecasts/models/tactical/other.py +++ b/src/velofy/forecasts/models/tactical/other.py @@ -44,14 +44,14 @@ class TrivialModel(base.ForecastingModelABC): RuntimeError: an internal consistency check fails """ # Generate the historic order time series mainly to check if a valid - # `training_ts` exists (i.e., the demand history is long enough). + # `training_ts` exists (i.e., the demand history is long enough) _, frequency, actuals_ts = self._order_history.make_horizontal_ts( pixel_id=pixel.id, predict_at=predict_at, train_horizon=train_horizon, ) - # Sanity checks. + # Sanity checks if frequency != 7: # pragma: no cover msg = "`frequency` should be `7`" raise RuntimeError(msg) @@ -59,7 +59,7 @@ class TrivialModel(base.ForecastingModelABC): msg = "the trivial model can only predict one step into the future" raise RuntimeError(msg) - # The "prediction" is simply `0.0`. + # The "prediction" is simply `0.0` predictions = pd.DataFrame( data={ "actual": actuals_ts, @@ -72,7 +72,7 @@ class TrivialModel(base.ForecastingModelABC): index=actuals_ts.index, ) - # Sanity checks. + # Sanity checks if predictions["actual"].isna().any(): # pragma: no cover msg = "missing actuals in trivial model" raise RuntimeError(msg) diff --git a/src/velofy/forecasts/models/tactical/realtime.py b/src/velofy/forecasts/models/tactical/realtime.py index 9d0ce5b..81dad8d 100644 --- a/src/velofy/forecasts/models/tactical/realtime.py +++ b/src/velofy/forecasts/models/tactical/realtime.py @@ -45,7 +45,7 @@ class RealtimeARIMAModel(base.ForecastingModelABC): Raises: RuntimeError: an internal consistency check fails """ - # Generate the historic (and real-time) order time series. + # Generate the historic (and real-time) order time series training_ts, frequency, actuals_ts = self._order_history.make_realtime_ts( pixel_id=pixel.id, predict_at=predict_at, @@ -53,30 +53,30 @@ class RealtimeARIMAModel(base.ForecastingModelABC): ) # Decompose the `training_ts` to make predictions for the seasonal - # component and the seasonally adjusted observations separately. + # component and the seasonally adjusted observations separately decomposed_training_ts = methods.decomposition.stl( time_series=training_ts, frequency=frequency, # "Periodic" `ns` parameter => Same seasonal component value - # for observations of the same lag. + # for observations of the same lag ns=999, ) - # Make predictions for the seasonal component by linear extrapolation. + # Make predictions for the seasonal component by linear extrapolation seasonal_predictions = methods.extrapolate_season.predict( training_ts=decomposed_training_ts["seasonal"], forecast_interval=pd.DatetimeIndex(actuals_ts.index), frequency=frequency, ) - # Make predictions with the ARIMA model on the seasonally adjusted time series. + # Make predictions with the ARIMA model on the seasonally adjusted time series seasonally_adjusted_predictions = methods.arima.predict( training_ts=( decomposed_training_ts["trend"] + decomposed_training_ts["residual"] ), forecast_interval=pd.DatetimeIndex(actuals_ts.index), # Because the seasonality was taken out before, - # the `training_ts` has, by definition, a `frequency` of `1`. + # the `training_ts` has, by definition, a `frequency` of `1` frequency=1, seasonal_fit=False, ) @@ -112,7 +112,7 @@ class RealtimeARIMAModel(base.ForecastingModelABC): index=actuals_ts.index, ) - # Sanity checks. + # Sanity checks if len(predictions) != 1: # pragma: no cover msg = "real-time models should predict exactly one time step" raise RuntimeError(msg) diff --git a/src/velofy/forecasts/models/tactical/vertical.py b/src/velofy/forecasts/models/tactical/vertical.py index 1a8f10d..ae972d2 100644 --- a/src/velofy/forecasts/models/tactical/vertical.py +++ b/src/velofy/forecasts/models/tactical/vertical.py @@ -45,7 +45,7 @@ class VerticalARIMAModel(base.ForecastingModelABC): Raises: RuntimeError: an internal consistency check fails """ - # Generate the historic (and vertical) order time series. + # Generate the historic (and vertical) order time series training_ts, frequency, actuals_ts = self._order_history.make_vertical_ts( pixel_id=pixel.id, predict_day=predict_at.date(), @@ -53,30 +53,30 @@ class VerticalARIMAModel(base.ForecastingModelABC): ) # Decompose the `training_ts` to make predictions for the seasonal - # component and the seasonally adjusted observations separately. + # component and the seasonally adjusted observations separately decomposed_training_ts = methods.decomposition.stl( time_series=training_ts, frequency=frequency, # "Periodic" `ns` parameter => Same seasonal component value - # for observations of the same lag. + # for observations of the same lag ns=999, ) - # Make predictions for the seasonal component by linear extrapolation. + # Make predictions for the seasonal component by linear extrapolation seasonal_predictions = methods.extrapolate_season.predict( training_ts=decomposed_training_ts["seasonal"], forecast_interval=pd.DatetimeIndex(actuals_ts.index), frequency=frequency, ) - # Make predictions with the ARIMA model on the seasonally adjusted time series. + # Make predictions with the ARIMA model on the seasonally adjusted time series seasonally_adjusted_predictions = methods.arima.predict( training_ts=( decomposed_training_ts["trend"] + decomposed_training_ts["residual"] ), forecast_interval=pd.DatetimeIndex(actuals_ts.index), # Because the seasonality was taken out before, - # the `training_ts` has, by definition, a `frequency` of `1`. + # the `training_ts` has, by definition, a `frequency` of `1` frequency=1, seasonal_fit=False, ) @@ -112,7 +112,7 @@ class VerticalARIMAModel(base.ForecastingModelABC): index=actuals_ts.index, ) - # Sanity checks. + # Sanity checks if len(predictions) <= 1: # pragma: no cover msg = "vertical models should predict several time steps" raise RuntimeError(msg) diff --git a/src/velofy/forecasts/timify.py b/src/velofy/forecasts/timify.py index bb9ab81..61d09ba 100644 --- a/src/velofy/forecasts/timify.py +++ b/src/velofy/forecasts/timify.py @@ -31,7 +31,7 @@ class OrderHistory: self._grid = grid self._time_step = time_step - # Number of daily time steps must be a whole multiple of `time_step` length. + # Number of daily time steps must be a whole multiple of `time_step` length n_daily_time_steps = ( 60 * (pkg_config.SERVICE_END - pkg_config.SERVICE_START) / time_step ) @@ -40,7 +40,7 @@ class OrderHistory: raise RuntimeError(msg) self._n_daily_time_steps = int(n_daily_time_steps) - # The `_data` are populated by `.aggregate_orders()`. + # The `_data` are populated by `.aggregate_orders()` self._data: pd.DataFrame | None = None @property @@ -174,7 +174,7 @@ class OrderHistory: if pkg_config.SERVICE_START <= start_at.hour < pkg_config.SERVICE_END ) - # Re-index `data` filling in `0`s where there is no demand. + # Re-index `data` filling in `0`s where there is no demand index = pd.MultiIndex.from_tuples(gen) index.names = ["pixel_id", "start_at"] @@ -201,12 +201,12 @@ class OrderHistory: first_order = intra_pixel[intra_pixel["n_orders"] > 0].index.min() - # Sanity check: without an `Order`, the `Pixel` should not exist. + # Sanity check: without an `Order`, the `Pixel` should not exist if first_order is pd.NaT: # pragma: no cover msg = "no orders in the pixel" raise RuntimeError(msg) - # Return a proper `datetime.datetime` object. + # Return a proper `datetime.datetime` object return dt.datetime( first_order.year, first_order.month, @@ -236,12 +236,12 @@ class OrderHistory: last_order = intra_pixel[intra_pixel["n_orders"] > 0].index.max() - # Sanity check: without an `Order`, the `Pixel` should not exist. + # Sanity check: without an `Order`, the `Pixel` should not exist if last_order is pd.NaT: # pragma: no cover msg = "no orders in the pixel" raise RuntimeError(msg) - # Return a proper `datetime.datetime` object. + # Return a proper `datetime.datetime` object return dt.datetime( last_order.year, last_order.month, @@ -289,7 +289,7 @@ class OrderHistory: # The first and last training day are just before the `predict_at` day # and span exactly `train_horizon` weeks covering only the times of the - # day equal to the hour/minute of `predict_at`. + # day equal to the hour/minute of `predict_at` first_train_day = predict_at.date() - dt.timedelta(weeks=train_horizon) first_start_at = dt.datetime( first_train_day.year, @@ -307,10 +307,10 @@ class OrderHistory: predict_at.minute, ) - # The frequency is the number of weekdays. + # The frequency is the number of weekdays frequency = 7 - # Take only the counts at the `predict_at` time. + # Take only the counts at the `predict_at` time training_ts = intra_pixel.loc[ first_start_at : last_start_at : self._n_daily_time_steps, "n_orders", @@ -364,7 +364,7 @@ class OrderHistory: raise RuntimeError(msg) # The first and last training day are just before the `predict_day` - # and span exactly `train_horizon` weeks covering all times of the day. + # and span exactly `train_horizon` weeks covering all times of the day first_train_day = predict_day - dt.timedelta(weeks=train_horizon) first_start_at = dt.datetime( first_train_day.year, @@ -382,10 +382,10 @@ class OrderHistory: 0, ) - dt.timedelta(minutes=self._time_step) - # The frequency is the number of weekdays times the number of daily time steps. + # The frequency is the number of weekdays times the number of daily time steps frequency = 7 * self._n_daily_time_steps - # Take all the counts between `first_train_day` and `last_train_day`. + # Take all the counts between `first_train_day` and `last_train_day` training_ts = intra_pixel.loc[ first_start_at:last_start_at, "n_orders", @@ -458,7 +458,7 @@ class OrderHistory: # The first and last training day are just before the `predict_at` day # and span exactly `train_horizon` weeks covering all times of the day, - # including times on the `predict_at` day that are earlier than `predict_at`. + # including times on the `predict_at` day that are earlier than `predict_at` first_train_day = predict_at.date() - dt.timedelta(weeks=train_horizon) first_start_at = dt.datetime( first_train_day.year, @@ -485,11 +485,11 @@ class OrderHistory: last_train_time.minute, ) - dt.timedelta(minutes=self._time_step) - # The frequency is the number of weekdays times the number of daily time steps. + # The frequency is the number of weekdays times the number of daily time steps frequency = 7 * self._n_daily_time_steps # Take all the counts between `first_train_day` and `last_train_day`, - # including the ones on the `predict_at` day prior to `predict_at`. + # including the ones on the `predict_at` day prior to `predict_at` training_ts = intra_pixel.loc[ first_start_at:last_start_at, "n_orders", @@ -554,7 +554,7 @@ class OrderHistory: first_day = training_ts.index.min().date() last_day = training_ts.index.max().date() - # `+1` as both `first_day` and `last_day` are included. + # `+1` as both `first_day` and `last_day` are included n_days: int = (last_day - first_day).days + 1 return round(float(training_ts.sum()) / n_days, 1) @@ -597,7 +597,7 @@ class OrderHistory: ) # For now, we only make forecasts with 7 and 8 weeks - # as the training horizon (note:4f79e8fa). + # as the training horizon (note:4f79e8fa) if train_horizon in {7, 8}: if add >= 10: # = "high" or "medium demand" return models.HorizontalETSModel(order_history=self) diff --git a/src/velofy/init_r.py b/src/velofy/init_r.py index eada0be..c4d0ab1 100644 --- a/src/velofy/init_r.py +++ b/src/velofy/init_r.py @@ -18,7 +18,7 @@ r_callbacks.consolewrite_warnerror = lambda *_args, **_kwargs: None # pragma: n # For clarity and convenience, re-raise the error that results from missing R -# dependencies with clearer instructions as to how to deal with it. +# dependencies with clearer instructions as to how to deal with it try: r_packages.importr("forecast") r_packages.importr("zoo") diff --git a/tests/config.py b/tests/config.py index 9ee9a65..64c0817 100644 --- a/tests/config.py +++ b/tests/config.py @@ -5,12 +5,12 @@ import datetime as dt from velofy import config as pkg_config -# The day on which most test cases take place. +# The day on which most test cases take place YEAR, MONTH, DAY = 2016, 7, 1 -# Same day as a `tuple`. +# Same day as a `tuple` DATE = (YEAR, MONTH, DAY) -# The hour when most test cases take place. +# The hour when most test cases take place NOON = 12 # `START` and `END` constitute a 57-day time span, 8 full weeks plus 1 day. @@ -19,7 +19,7 @@ START = dt.datetime(YEAR, MONTH, DAY, pkg_config.SERVICE_START, 0) _end = START + dt.timedelta(days=56) # `56` as `START` is not included END = dt.datetime(_end.year, _end.month, _end.day, pkg_config.SERVICE_END, 0) -# Default time steps (in minutes), for example, for `OrderHistory` objects. +# Default time steps (in minutes), for example, for `OrderHistory` objects LONG_TIME_STEP = 60 SHORT_TIME_STEP = 30 TIME_STEPS = (SHORT_TIME_STEP, LONG_TIME_STEP) @@ -30,7 +30,7 @@ VERTICAL_FREQUENCY_LONG = 7 * 12 VERTICAL_FREQUENCY_SHORT = 7 * 24 # Default training horizons, for example, for -# `OrderHistory.make_horizontal_time_series()`. +# `OrderHistory.make_horizontal_time_series()` LONG_TRAIN_HORIZON = 8 SHORT_TRAIN_HORIZON = 2 TRAIN_HORIZONS = (SHORT_TRAIN_HORIZON, LONG_TRAIN_HORIZON) diff --git a/tests/conftest.py b/tests/conftest.py index 31f8442..e861199 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -28,7 +28,7 @@ pytest_plugins = [ # The TESTING environment variable is set -# in pyproject.toml in pytest's config section. +# in pyproject.toml in pytest's config section if not os.getenv("TESTING"): msg = "Tests must be executed with TESTING set in the environment" raise RuntimeError(msg) @@ -72,7 +72,7 @@ def db_connection(request): finally: # Close the connection first: this rolls back any transaction a test - # may have left open, which would otherwise swallow the `DROP`s below. + # may have left open, which would otherwise swallow the `DROP`s below connection.close() with engine.begin() as cleanup: @@ -95,7 +95,7 @@ def db_connection(request): def db_session(db_connection, monkeypatch): """A SQLAlchemy session that rolls back everything after a test case.""" # Begin the outermost transaction - # that is rolled back at the end of each test case. + # that is rolled back at the end of each test case transaction = db_connection.begin() # Create a session bound to the same connection as the `transaction`. @@ -104,7 +104,7 @@ def db_session(db_connection, monkeypatch): session = orm.Session(bind=db_connection, join_transaction_mode="create_savepoint") # Monkey patch the package's global `session` object, - # which is used heavily in the code base. + # which is used heavily in the code base monkeypatch.setattr(db, "session", session) try: diff --git a/tests/console/test_gridify.py b/tests/console/test_gridify.py index 0e7e92a..4945b0e 100644 --- a/tests/console/test_gridify.py +++ b/tests/console/test_gridify.py @@ -32,7 +32,7 @@ def test_two_pixels_with_two_addresses( # Locate a `Restaurant` at the two `Address` objects and # place one `Order` for each of them so that the `Address` - # objects are used as `Order.pickup_address`s. + # objects are used as `Order.pickup_address`s restaurant1 = make_restaurant(address=address1) restaurant2 = make_restaurant(address=address2) order1 = make_order(restaurant=restaurant1) @@ -44,10 +44,10 @@ def test_two_pixels_with_two_addresses( side_length = max(city.total_x // 2, city.total_y // 2) + 1 - # Hack the configuration regarding the grids to be created. + # Hack the configuration regarding the grids to be created monkeypatch.setattr(velofy.config, "GRID_SIDE_LENGTHS", (side_length,)) - # The `gridify` stage is locked to the revision it was carried out at. + # The `gridify` stage is locked to the revision it was carried out at monkeypatch.setattr( gridify.decorators, "current_db_revision", diff --git a/tests/console/test_main.py b/tests/console/test_main.py index 2dae56a..5646725 100644 --- a/tests/console/test_main.py +++ b/tests/console/test_main.py @@ -70,7 +70,7 @@ class TestCLIWithoutCommand: assert result.exit_code == 2 - # The following test cases validate the --version / -V option. + # The following test cases validate the --version / -V option version_options = ("--version", "-V") diff --git a/tests/db/fake_data/factories/addresses.py b/tests/db/fake_data/factories/addresses.py index fb52c42..3af587a 100644 --- a/tests/db/fake_data/factories/addresses.py +++ b/tests/db/fake_data/factories/addresses.py @@ -26,12 +26,12 @@ class AddressFactory(alchemy.SQLAlchemyModelFactory): # completeness sake, that is ok to do. primary_id = factory.LazyAttribute(lambda obj: obj.id) - # Mimic a Google Maps Place ID with just random characters. + # Mimic a Google Maps Place ID with just random characters place_id = factory.LazyFunction( lambda: "".join(random.choice(string.ascii_lowercase) for _ in range(20)), ) - # Place the addresses somewhere in downtown Paris. + # Place the addresses somewhere in downtown Paris latitude = factory.Faker("pyfloat", min_value=48.845, max_value=48.865) longitude = factory.Faker("pyfloat", min_value=2.31, max_value=2.37) # city -> set by the `make_address` fixture as there is only one `city` diff --git a/tests/db/fake_data/factories/orders/ad_hoc.py b/tests/db/fake_data/factories/orders/ad_hoc.py index 02bd8a7..7d125a1 100644 --- a/tests/db/fake_data/factories/orders/ad_hoc.py +++ b/tests/db/fake_data/factories/orders/ad_hoc.py @@ -40,7 +40,7 @@ class AdHocOrderFactory(alchemy.SQLAlchemyModelFactory): """ # Timestamps after `cancelled_at` are discarded - # by the `post_generation` hook at the end of the `OrderFactory`. + # by the `post_generation` hook at the end of the `OrderFactory` cancel_ = factory.Trait( # -> leading underscore does not work cancelled=True, cancelled_at_corrected=False, @@ -83,7 +83,7 @@ class AdHocOrderFactory(alchemy.SQLAlchemyModelFactory): ad_hoc = True scheduled_delivery_at = None scheduled_delivery_at_corrected = None - # Without statistical info, we assume an ad-hoc `Order` delivered after 45 minutes. + # Without statistical info, we assume an ad-hoc `Order` delivered after 45 minutes first_estimated_delivery_at = factory.LazyAttribute( lambda obj: obj.placed_at + dt.timedelta(minutes=45), ) @@ -118,7 +118,7 @@ class AdHocOrderFactory(alchemy.SQLAlchemyModelFactory): restaurant_confirmed_at_corrected = factory.LazyAttribute( lambda obj: False if obj.restaurant_confirmed_at else None, ) - # Use the database defaults of the historic data. + # Use the database defaults of the historic data estimated_prep_duration = 900 estimated_prep_duration_corrected = False estimated_prep_buffer = 480 @@ -150,7 +150,7 @@ class AdHocOrderFactory(alchemy.SQLAlchemyModelFactory): courier_accepted_at_corrected = factory.LazyAttribute( lambda obj: False if obj.courier_accepted_at else None, ) - # Sample a realistic utilization. + # Sample a realistic utilization utilization = factory.LazyFunction(lambda: random.choice([50, 60, 70, 80, 90, 100])) # Pickup-related attributes diff --git a/tests/db/fake_data/factories/orders/scheduled.py b/tests/db/fake_data/factories/orders/scheduled.py index 4fca9b4..7d4003f 100644 --- a/tests/db/fake_data/factories/orders/scheduled.py +++ b/tests/db/fake_data/factories/orders/scheduled.py @@ -20,10 +20,10 @@ class ScheduledOrderFactory(ad_hoc.AdHocOrderFactory): and calculated backwards from `.scheduled_delivery_at`. """ - # Attributes regarding the specialization of an `Order`: ad-hoc or scheduled. + # Attributes regarding the specialization of an `Order`: ad-hoc or scheduled placed_at = factory.LazyFunction(utils.early_in_the_morning) ad_hoc = False - # Discrete `datetime` objects in the "core" lunch time are enough. + # Discrete `datetime` objects in the "core" lunch time are enough scheduled_delivery_at = factory.LazyFunction( lambda: random.choice( [ @@ -38,7 +38,7 @@ class ScheduledOrderFactory(ad_hoc.AdHocOrderFactory): ), ) scheduled_delivery_at_corrected = False - # Assume the `Order` is on time. + # Assume the `Order` is on time first_estimated_delivery_at = factory.LazyAttribute( lambda obj: obj.scheduled_delivery_at, ) diff --git a/tests/db/fake_data/fixture_makers.py b/tests/db/fake_data/fixture_makers.py index 0a93683..dede148 100644 --- a/tests/db/fake_data/fixture_makers.py +++ b/tests/db/fake_data/fixture_makers.py @@ -8,7 +8,7 @@ from tests.db.fake_data import factories @pytest.fixture def make_address(city): """Replaces `AddressFactory.build()`: Create an `Address` in the `city`.""" - # Reset the identifiers before every test. + # Reset the identifiers before every test factories.AddressFactory.reset_sequence(1) def func(**kwargs): @@ -25,7 +25,7 @@ def make_address(city): @pytest.fixture def make_courier(): """Replaces `CourierFactory.build()`: Create a `Courier`.""" - # Reset the identifiers before every test. + # Reset the identifiers before every test factories.CourierFactory.reset_sequence(1) def func(**kwargs): @@ -38,7 +38,7 @@ def make_courier(): @pytest.fixture def make_customer(): """Replaces `CustomerFactory.build()`: Create a `Customer`.""" - # Reset the identifiers before every test. + # Reset the identifiers before every test factories.CustomerFactory.reset_sequence(1) def func(**kwargs): @@ -51,7 +51,7 @@ def make_customer(): @pytest.fixture def make_restaurant(make_address): """Replaces `RestaurantFactory.build()`: Create a `Restaurant`.""" - # Reset the identifiers before every test. + # Reset the identifiers before every test factories.RestaurantFactory.reset_sequence(1) def func(address=None, **kwargs): @@ -74,7 +74,7 @@ def make_restaurant(make_address): @pytest.fixture def make_order(make_address, make_courier, make_customer, make_restaurant): """Replaces `OrderFactory.build()`: Create a `Order`.""" - # Reset the identifiers before every test. + # Reset the identifiers before every test factories.AdHocOrderFactory.reset_sequence(1) def func(*, scheduled=False, restaurant=None, courier=None, **kwargs): @@ -119,7 +119,7 @@ def make_order(make_address, make_courier, make_customer, make_restaurant): @pytest.fixture def make_replay_order(make_order, simulation): """Replaces `ReplayedOrderFactory.build()`: Create a `ReplayedOrder`.""" - # Reset the identifiers before every test. + # Reset the identifiers before every test factories.ReplayedOrderFactory.reset_sequence(1) def func(*, scheduled=False, order=None, **kwargs): diff --git a/tests/db/replay/test_orders.py b/tests/db/replay/test_orders.py index 55beb6c..d7c497a 100644 --- a/tests/db/replay/test_orders.py +++ b/tests/db/replay/test_orders.py @@ -49,7 +49,7 @@ class TestConstraints: db_session.add(replayed_order) db_session.commit() - # Must delete without ORM as otherwise an UPDATE statement is emitted. + # Must delete without ORM as otherwise an UPDATE statement is emitted stmt = sa.delete(db.ReplaySimulation).where( db.ReplaySimulation.id == replayed_order.simulation.id, ) @@ -65,7 +65,7 @@ class TestConstraints: db_session.add(replayed_order) db_session.commit() - # Must delete without ORM as otherwise an UPDATE statement is emitted. + # Must delete without ORM as otherwise an UPDATE statement is emitted stmt = sa.delete(db.Order).where(db.Order.id == replayed_order.actual.id) with pytest.raises(sa_exc.IntegrityError, match="fk_replayed_orders_to_orders"): @@ -79,13 +79,13 @@ class TestConstraints: ): """Remove a record that is referenced with a FK.""" # Need a second courier, one that is - # not associated with the `.actual` order. + # not associated with the `.actual` order replayed_order.courier = make_courier() db_session.add(replayed_order) db_session.commit() - # Must delete without ORM as otherwise an UPDATE statement is emitted. + # Must delete without ORM as otherwise an UPDATE statement is emitted stmt = sa.delete(db.Courier).where(db.Courier.id == replayed_order.courier.id) with pytest.raises( @@ -304,12 +304,12 @@ class TestConstraints: # Make the `scheduled_delivery_at` the quarter of an hour # following the next quarter of an hour (i.e., the timestamp - # is between 15 and 30 minutes into the future). + # is between 15 and 30 minutes into the future) replay_pre_order.ad_hoc = False replay_pre_order.actual.ad_hoc = False minutes_to_next_quarter = 15 - (replay_pre_order.placed_at.minute % 15) scheduled_delivery_at = ( - # `.placed_at` may have non-0 seconds. + # `.placed_at` may have non-0 seconds replay_pre_order.placed_at.replace(second=0) + dt.timedelta(minutes=(minutes_to_next_quarter + 15)) ) @@ -398,11 +398,11 @@ class TestConstraints: ): """Insert an instance with invalid data.""" # Setting `.cancelled_at` to the end of a day - # ensures the timestamps are logically ok. + # ensures the timestamps are logically ok replayed_order.cancelled_at = dt.datetime(*test_config.DATE, 23) # Set all timestamps after `.reached_pickup_at` to NULL - # except the one under test. + # except the one under test for unset_column in ( "pickup_at", "left_pickup_at", @@ -572,7 +572,7 @@ class TestConstraints: """ replayed_pre_order = make_replay_order(scheduled=True) # As we subtract 1 second in the generic case, - # choose one second after a quarter of an hour. + # choose one second after a quarter of an hour replayed_pre_order.placed_at = dt.datetime(*test_config.DATE, 11, 45, 1) self.test_timestamps_unordered( db_session, diff --git a/tests/db/test_addresses.py b/tests/db/test_addresses.py index 759d39e..2d6af3d 100644 --- a/tests/db/test_addresses.py +++ b/tests/db/test_addresses.py @@ -43,7 +43,7 @@ class TestConstraints: def test_delete_a_referenced_address(self, db_session, address, make_address): """Remove a record that is referenced with a FK.""" db_session.add(address) - # Fake another_address that has the same `.primary_id` as `address`. + # Fake another_address that has the same `.primary_id` as `address` db_session.add(make_address(primary_id=address.id)) db_session.commit() @@ -60,7 +60,7 @@ class TestConstraints: db_session.add(address) db_session.commit() - # Must delete without ORM as otherwise an UPDATE statement is emitted. + # Must delete without ORM as otherwise an UPDATE statement is emitted stmt = sa.delete(db.City).where(db.City.id == address.city.id) with pytest.raises( diff --git a/tests/db/test_addresses_addresses.py b/tests/db/test_addresses_addresses.py index ab36221..2611e9c 100644 --- a/tests/db/test_addresses_addresses.py +++ b/tests/db/test_addresses_addresses.py @@ -25,7 +25,7 @@ def path(address, another_address, make_address): ).meters # We put 5 latitude-longitude pairs as the "path" from - # `.first_address` to `.second_address`. + # `.first_address` to `.second_address` directions = [ [float(add.latitude), float(add.longitude)] for add in (make_address() for _ in range(5)) @@ -68,7 +68,7 @@ class TestConstraints: db_session.add(path) db_session.commit() - # Must delete without ORM as otherwise an UPDATE statement is emitted. + # Must delete without ORM as otherwise an UPDATE statement is emitted stmt = sa.delete(db.Address).where(db.Address.id == path.first_address.id) with pytest.raises( @@ -82,7 +82,7 @@ class TestConstraints: db_session.add(path) db_session.commit() - # Must delete without ORM as otherwise an UPDATE statement is emitted. + # Must delete without ORM as otherwise an UPDATE statement is emitted stmt = sa.delete(db.Address).where(db.Address.id == path.second_address.id) with pytest.raises( @@ -98,7 +98,7 @@ class TestConstraints: db_session.commit() # Must insert without ORM as otherwise SQLAlchemy figures out - # that something is wrong before any query is sent to the database. + # that something is wrong before any query is sent to the database stmt = sa.insert(db.Path).values( first_address_id=address.id, second_address_id=another_address.id, @@ -118,7 +118,7 @@ class TestConstraints: db_session.commit() # Must insert without ORM as otherwise SQLAlchemy figures out - # that something is wrong before any query is sent to the database. + # that something is wrong before any query is sent to the database stmt = sa.insert(db.Path).values( first_address_id=path.first_address.id, second_address_id=path.second_address.id, @@ -311,7 +311,7 @@ class TestFromAddresses: assert result == 6 - # Tests for the `Path.from_order()` convenience method. + # Tests for the `Path.from_order()` convenience method def test_make_path_instance_from_order( self, @@ -385,7 +385,7 @@ class TestSyncWithGoogleMaps: { # We choose an artificially high distance of `9999` # so that the synced bicycle distance is longer than - # the randomized air distance (i.e., fake data) for sure. + # the randomized air distance (i.e., fake data) for sure "distance": {"text": "3.0 km", "value": 9999}, "duration": {"text": "10 mins", "value": 596}, "end_address": "13 Place Paul et Jean Paul Avisseau, ...", @@ -685,7 +685,7 @@ class TestProperties: result = path.waypoints # There are 5 inner points, excluding start and end, - # i.e., the `.first_address` and `second_address`. + # i.e., the `.first_address` and `second_address` assert len(result) == 5 def test_waypoints_is_cached(self, path): diff --git a/tests/db/test_addresses_pixels.py b/tests/db/test_addresses_pixels.py index 90af9ed..03af57d 100644 --- a/tests/db/test_addresses_pixels.py +++ b/tests/db/test_addresses_pixels.py @@ -65,7 +65,7 @@ class TestConstraints: db_session.add(assoc) db_session.commit() - # Must delete without ORM as otherwise an UPDATE statement is emitted. + # Must delete without ORM as otherwise an UPDATE statement is emitted stmt = sa.delete(db.Address).where(db.Address.id == assoc.address.id) with pytest.raises( @@ -81,7 +81,7 @@ class TestConstraints: db_session.commit() # Must insert without ORM as otherwise SQLAlchemy figures out - # that something is wrong before any query is sent to the database. + # that something is wrong before any query is sent to the database stmt = sa.insert(db.AddressPixelAssociation).values( address_id=address.id, city_id=999, @@ -102,7 +102,7 @@ class TestConstraints: db_session.commit() # Must insert without ORM as otherwise SQLAlchemy figures out - # that something is wrong before any query is sent to the database. + # that something is wrong before any query is sent to the database stmt = sa.insert(db.AddressPixelAssociation).values( address_id=address.id, city_id=address.city.id, @@ -121,7 +121,7 @@ class TestConstraints: db_session.add(assoc) db_session.commit() - # Must delete without ORM as otherwise an UPDATE statement is emitted. + # Must delete without ORM as otherwise an UPDATE statement is emitted stmt = sa.delete(db.Pixel).where(db.Pixel.id == assoc.pixel.id) with pytest.raises( @@ -135,7 +135,7 @@ class TestConstraints: db_session.add(assoc) db_session.commit() - # Create a neighboring `Pixel` and put the same `address` as in `pixel` in it. + # Create a neighboring `Pixel` and put the same `address` as in `pixel` in it neighbor = db.Pixel(grid=pixel.grid, n_x=pixel.n_x, n_y=pixel.n_y + 1) another_assoc = db.AddressPixelAssociation(address=address, pixel=neighbor) diff --git a/tests/db/test_forecasts.py b/tests/db/test_forecasts.py index 4720870..bb9fc2d 100644 --- a/tests/db/test_forecasts.py +++ b/tests/db/test_forecasts.py @@ -79,7 +79,7 @@ class TestConstraints: db_session.add(forecast) db_session.commit() - # Must delete without ORM as otherwise an UPDATE statement is emitted. + # Must delete without ORM as otherwise an UPDATE statement is emitted stmt = sa.delete(db.Pixel).where(db.Pixel.id == forecast.pixel.id) with pytest.raises( @@ -376,7 +376,7 @@ class TestConstraints: assert forecast.low80 is not None assert forecast.high80 is not None - # Do not trigger the "ci95_must_be_wider_than_ci80" constraint. + # Do not trigger the "ci95_must_be_wider_than_ci80" constraint forecast.low95 = None forecast.high95 = None @@ -398,7 +398,7 @@ class TestConstraints: assert forecast.low95 is not None assert forecast.high95 is not None - # Do not trigger the "ci95_must_be_wider_than_ci80" constraint. + # Do not trigger the "ci95_must_be_wider_than_ci80" constraint forecast.low80 = None forecast.high80 = None diff --git a/tests/db/test_grids.py b/tests/db/test_grids.py index 8116720..b5cd4cb 100644 --- a/tests/db/test_grids.py +++ b/tests/db/test_grids.py @@ -40,7 +40,7 @@ class TestConstraints: db_session.add(grid) db_session.commit() - # Must delete without ORM as otherwise an UPDATE statement is emitted. + # Must delete without ORM as otherwise an UPDATE statement is emitted stmt = sa.delete(db.City).where(db.City.id == grid.city.id) with pytest.raises( @@ -54,7 +54,7 @@ class TestConstraints: db_session.add(grid) db_session.commit() - # Create a `Grid` with the same `.side_length` in the same `.city`. + # Create a `Grid` with the same `.side_length` in the same `.city` another_grid = db.Grid(city=grid.city, side_length=grid.side_length) db_session.add(another_grid) @@ -71,7 +71,7 @@ class TestConstraints: db_session.add(grid) db_session.commit() - # Create a `Grid` with the same `.side_length` in another `.city`. + # Create a `Grid` with the same `.side_length` in another `.city` another_city = db.City(**(city_data | {"id": 2, "name": "Lyon"})) another_grid = db.Grid(city=another_city, side_length=grid.side_length) db_session.add(another_grid) @@ -132,7 +132,7 @@ class TestGridification: """ addresses_mock.return_value = [order.pickup_address] - # `+1` as otherwise there would be a second pixel in one direction. + # `+1` as otherwise there would be a second pixel in one direction side_length = max(city.total_x, city.total_y) + 1 result = db.Grid.gridify(city=city, side_length=side_length) @@ -152,7 +152,7 @@ class TestGridification: orders = [make_order(), make_order()] addresses_mock.return_value = [order.pickup_address for order in orders] - # `+1` as otherwise there would be a second pixel in one direction. + # `+1` as otherwise there would be a second pixel in one direction side_length = max(city.total_x, city.total_y) + 1 result = db.Grid.gridify(city=city, side_length=side_length) @@ -162,11 +162,11 @@ class TestGridification: def test_no_pixel_with_one_address_too_far_south(self, city, order, addresses_mock): """An `address` outside the `city`'s viewport is discarded.""" - # Move the `address` just below `city.southwest`. + # Move the `address` just below `city.southwest` order.pickup_address.latitude = city.southwest.latitude - 0.1 addresses_mock.return_value = [order.pickup_address] - # `+1` as otherwise there would be a second pixel in one direction. + # `+1` as otherwise there would be a second pixel in one direction side_length = max(city.total_x, city.total_y) + 1 result = db.Grid.gridify(city=city, side_length=side_length) @@ -181,11 +181,11 @@ class TestGridification: This test is a logical sibling to `test_no_pixel_with_one_address_too_far_south` and therefore redundant. """ - # Move the `address` just left to `city.southwest`. + # Move the `address` just left to `city.southwest` order.pickup_address.longitude = city.southwest.longitude - 0.1 addresses_mock.return_value = [order.pickup_address] - # `+1` as otherwise there would be a second pixel in one direction. + # `+1` as otherwise there would be a second pixel in one direction side_length = max(city.total_x, city.total_y) + 1 result = db.Grid.gridify(city=city, side_length=side_length) @@ -199,7 +199,7 @@ class TestGridification: This test is more of a sanity check. """ - # Create two `Address` objects in distinct `Pixel`s. + # Create two `Address` objects in distinct `Pixel`s addresses_mock.return_value = [ # One `Address` in the lower-left `Pixel`, ... make_address(latitude=48.8357377, longitude=2.2517412), @@ -209,12 +209,12 @@ class TestGridification: side_length = max(city.total_x // 2, city.total_y // 2) + 1 - # By assumption of the test data. + # By assumption of the test data n_pixels_x = (city.total_x // side_length) + 1 n_pixels_y = (city.total_y // side_length) + 1 assert n_pixels_x * n_pixels_y == 4 - # Create a `Grid` with at most four `Pixel`s. + # Create a `Grid` with at most four `Pixel`s result = db.Grid.gridify(city=city, side_length=side_length) assert isinstance(result, db.Grid) @@ -252,7 +252,7 @@ class TestGridification: assert isinstance(result, db.Grid) assert 1 <= len(result.pixels) <= n_pixels_x * n_pixels_y - # Sanity checks for `Pixel.southwest` and `Pixel.northeast`. + # Sanity checks for `Pixel.southwest` and `Pixel.northeast` for pixel in result.pixels: assert abs(pixel.southwest.x - pixel.n_x * side_length) < 2 assert abs(pixel.southwest.y - pixel.n_y * side_length) < 2 diff --git a/tests/db/test_orders.py b/tests/db/test_orders.py index f350057..38e8526 100644 --- a/tests/db/test_orders.py +++ b/tests/db/test_orders.py @@ -57,7 +57,7 @@ class TestConstraints: db_session.add(order) db_session.commit() - # Must delete without ORM as otherwise an UPDATE statement is emitted. + # Must delete without ORM as otherwise an UPDATE statement is emitted stmt = sa.delete(db.Customer).where(db.Customer.id == order.customer.id) with pytest.raises(sa_exc.IntegrityError, match="fk_orders_to_customers"): @@ -68,7 +68,7 @@ class TestConstraints: db_session.add(order) db_session.commit() - # Must delete without ORM as otherwise an UPDATE statement is emitted. + # Must delete without ORM as otherwise an UPDATE statement is emitted stmt = sa.delete(db.Courier).where(db.Courier.id == order.courier.id) with pytest.raises(sa_exc.IntegrityError, match="fk_orders_to_couriers"): @@ -79,7 +79,7 @@ class TestConstraints: db_session.add(order) db_session.commit() - # Must delete without ORM as otherwise an UPDATE statement is emitted. + # Must delete without ORM as otherwise an UPDATE statement is emitted stmt = sa.delete(db.Restaurant).where(db.Restaurant.id == order.restaurant.id) with pytest.raises(sa_exc.IntegrityError, match="fk_orders_to_restaurants"): @@ -93,7 +93,7 @@ class TestConstraints: db_session.add(order) db_session.commit() - # Give the `restaurant` another `address`. + # Give the `restaurant` another `address` order.restaurant.address = make_address() db_session.add(order.restaurant.address) @@ -111,7 +111,7 @@ class TestConstraints: db_session.add(order) db_session.commit() - # Must delete without ORM as otherwise an UPDATE statement is emitted. + # Must delete without ORM as otherwise an UPDATE statement is emitted stmt = sa.delete(db.Address).where(db.Address.id == order.delivery_address.id) with pytest.raises(sa_exc.IntegrityError, match="fk_orders_to_addresses"): @@ -295,11 +295,11 @@ class TestConstraints: # Make the `scheduled_delivery_at` the quarter of an hour # following the next quarter of an hour (i.e., the timestamp - # is between 15 and 30 minutes into the future). + # is between 15 and 30 minutes into the future) pre_order.ad_hoc = False minutes_to_next_quarter = 15 - (pre_order.placed_at.minute % 15) pre_order.scheduled_delivery_at = ( - # `.placed_at` may have non-0 seconds. + # `.placed_at` may have non-0 seconds pre_order.placed_at.replace(second=0) + dt.timedelta(minutes=(minutes_to_next_quarter + 15)) ) @@ -434,22 +434,22 @@ class TestConstraints: There are two special cases for this test case below, where other attributes on `order` must be unset. """ - # Set the actual timestamp to NULL. + # Set the actual timestamp to NULL setattr(order, column, None) - # Setting both the timestamp and its correction column to NULL is allowed. + # Setting both the timestamp and its correction column to NULL is allowed setattr(order, f"{column}_corrected", None) db_session.add(order) db_session.commit() - # Also, an unset timestamp column may always be marked as corrected. + # Also, an unset timestamp column may always be marked as corrected setattr(order, f"{column}_corrected", True) db_session.add(order) db_session.commit() - # Without a timestamp set, a column may not be marked as uncorrected. + # Without a timestamp set, a column may not be marked as uncorrected setattr(order, f"{column}_corrected", False) db_session.add(order) @@ -518,10 +518,10 @@ class TestConstraints: There are two special cases for this test case below, where other attributes on `order` must be unset. """ - # Ensure the timestamp is set. + # Ensure the timestamp is set assert getattr(order, column) is not None - # A set timestamp may be marked as either corrected or uncorrected. + # A set timestamp may be marked as either corrected or uncorrected setattr(order, f"{column}_corrected", True) @@ -533,7 +533,7 @@ class TestConstraints: db_session.add(order) db_session.commit() - # A set timestamp may not be left unmarked. + # A set timestamp may not be left unmarked setattr(order, f"{column}_corrected", None) db_session.add(order) @@ -659,7 +659,7 @@ class TestConstraints: This is one of two special cases. See the generic case above. """ # As we subtract 1 second in the generic case, - # choose one second after a quarter of an hour. + # choose one second after a quarter of an hour pre_order.placed_at = dt.datetime(*test_config.DATE, 11, 45, 1) self.test_timestamps_unordered( db_session, @@ -752,7 +752,7 @@ class TestProperties: def test_is_not_corrected(self, order): """Test `Order.corrected` property.""" - # By default, the `OrderFactory` sets all `.*_corrected` attributes to `False`. + # By default, the `OrderFactory` sets all `.*_corrected` attributes to `False` result = order.corrected assert result is False @@ -882,7 +882,7 @@ class TestProperties: def test_courier_is_early_at_pickup(self, order): """Test `Order.courier_early` property.""" - # Manipulate the attribute that determines `Order.scheduled_pickup_at`. + # Manipulate the attribute that determines `Order.scheduled_pickup_at` order.estimated_prep_duration = 999_999 result = order.courier_early @@ -891,7 +891,7 @@ class TestProperties: def test_courier_is_not_early_at_pickup(self, order): """Test `Order.courier_early` property.""" - # Manipulate the attribute that determines `Order.scheduled_pickup_at`. + # Manipulate the attribute that determines `Order.scheduled_pickup_at` order.estimated_prep_duration = 1 result = order.courier_early @@ -900,7 +900,7 @@ class TestProperties: def test_courier_is_late_at_pickup(self, order): """Test `Order.courier_late` property.""" - # Manipulate the attribute that determines `Order.scheduled_pickup_at`. + # Manipulate the attribute that determines `Order.scheduled_pickup_at` order.estimated_prep_duration = 1 result = order.courier_late @@ -909,7 +909,7 @@ class TestProperties: def test_courier_is_not_late_at_pickup(self, order): """Test `Order.courier_late` property.""" - # Manipulate the attribute that determines `Order.scheduled_pickup_at`. + # Manipulate the attribute that determines `Order.scheduled_pickup_at` order.estimated_prep_duration = 999_999 result = order.courier_late @@ -932,7 +932,7 @@ class TestProperties: def test_restaurant_early_at_pickup(self, order): """Test `Order.restaurant_early` property.""" - # Manipulate the attribute that determines `Order.scheduled_pickup_at`. + # Manipulate the attribute that determines `Order.scheduled_pickup_at` order.estimated_prep_duration = 999_999 result = order.restaurant_early @@ -941,7 +941,7 @@ class TestProperties: def test_restaurant_is_not_early_at_pickup(self, order): """Test `Order.restaurant_early` property.""" - # Manipulate the attribute that determines `Order.scheduled_pickup_at`. + # Manipulate the attribute that determines `Order.scheduled_pickup_at` order.estimated_prep_duration = 1 result = order.restaurant_early @@ -950,7 +950,7 @@ class TestProperties: def test_restaurant_is_late_at_pickup(self, order): """Test `Order.restaurant_late` property.""" - # Manipulate the attribute that determines `Order.scheduled_pickup_at`. + # Manipulate the attribute that determines `Order.scheduled_pickup_at` order.estimated_prep_duration = 1 result = order.restaurant_late @@ -959,7 +959,7 @@ class TestProperties: def test_restaurant_is_not_late_at_pickup(self, order): """Test `Order.restaurant_late` property.""" - # Manipulate the attribute that determines `Order.scheduled_pickup_at`. + # Manipulate the attribute that determines `Order.scheduled_pickup_at` order.estimated_prep_duration = 999_999 result = order.restaurant_late @@ -1038,14 +1038,14 @@ class TestProperties: def test_ad_hoc_order_cannot_be_early(self, order): """Test `Order.delivery_early` property.""" - # By default, the `OrderFactory` creates ad-hoc orders. + # By default, the `OrderFactory` creates ad-hoc orders with pytest.raises(AttributeError, match="scheduled"): int(order.delivery_early) def test_scheduled_order_delivered_early(self, make_order): """Test `Order.delivery_early` property.""" order = make_order(scheduled=True) - # Schedule the order to a lot later. + # Schedule the order to a lot later order.scheduled_delivery_at += dt.timedelta(hours=2) result = order.delivery_early @@ -1055,7 +1055,7 @@ class TestProperties: def test_scheduled_order_not_delivered_early(self, make_order): """Test `Order.delivery_early` property.""" order = make_order(scheduled=True) - # Schedule the order to a lot earlier. + # Schedule the order to a lot earlier order.scheduled_delivery_at -= dt.timedelta(hours=2) result = order.delivery_early @@ -1080,14 +1080,14 @@ class TestProperties: def test_ad_hoc_order_cannot_be_late(self, order): """Test Order.delivery_late property.""" - # By default, the `OrderFactory` creates ad-hoc orders. + # By default, the `OrderFactory` creates ad-hoc orders with pytest.raises(AttributeError, match="scheduled"): int(order.delivery_late) def test_scheduled_order_delivered_late(self, make_order): """Test `Order.delivery_early` property.""" order = make_order(scheduled=True) - # Schedule the order to a lot earlier. + # Schedule the order to a lot earlier order.scheduled_delivery_at -= dt.timedelta(hours=2) result = order.delivery_late @@ -1097,7 +1097,7 @@ class TestProperties: def test_scheduled_order_not_delivered_late(self, make_order): """Test `Order.delivery_early` property.""" order = make_order(scheduled=True) - # Schedule the order to a lot later. + # Schedule the order to a lot later order.scheduled_delivery_at += dt.timedelta(hours=2) result = order.delivery_late @@ -1162,23 +1162,23 @@ def test_make_random_orders( Ensure that all generated `Address`, `Courier`, `Customer`, `Restaurant`, and `Order` objects adhere to the database constraints. """ - # Generate a large number of `Order`s to obtain a large variance of data. + # Generate a large number of `Order`s to obtain a large variance of data for _ in range(1_000): - # Ad-hoc `Order`s are far more common than pre-orders. + # Ad-hoc `Order`s are far more common than pre-orders scheduled = random.choice([True, False, False, False, False]) # Randomly pass a `address` argument to `make_restaurant()` and - # a `restaurant` argument to `make_order()`. + # a `restaurant` argument to `make_order()` if random.random() < 0.5: address = random.choice([None, make_address()]) restaurant = make_restaurant(address=address) else: restaurant = None - # Randomly pass a `courier` argument to `make_order()`. + # Randomly pass a `courier` argument to `make_order()` courier = random.choice([None, make_courier()]) - # A tiny fraction of `Order`s get cancelled. + # A tiny fraction of `Order`s get cancelled if random.random() < 0.05: if random.random() < 0.5: cancel_before_pickup, cancel_after_pickup = True, False diff --git a/tests/db/test_pixels.py b/tests/db/test_pixels.py index 6284fa7..b8c7b06 100644 --- a/tests/db/test_pixels.py +++ b/tests/db/test_pixels.py @@ -40,7 +40,7 @@ class TestConstraints: db_session.add(pixel) db_session.commit() - # Must delete without ORM as otherwise an UPDATE statement is emitted. + # Must delete without ORM as otherwise an UPDATE statement is emitted stmt = sa.delete(db.Grid).where(db.Grid.id == pixel.grid.id) with pytest.raises( diff --git a/tests/db/test_restaurants.py b/tests/db/test_restaurants.py index 8737dac..6831e00 100644 --- a/tests/db/test_restaurants.py +++ b/tests/db/test_restaurants.py @@ -46,7 +46,7 @@ class TestConstraints: db_session.add(restaurant) db_session.commit() - # Must delete without ORM as otherwise an UPDATE statement is emitted. + # Must delete without ORM as otherwise an UPDATE statement is emitted stmt = sa.delete(db.Address).where(db.Address.id == restaurant.address.id) with pytest.raises( diff --git a/tests/db/utils/test_locations.py b/tests/db/utils/test_locations.py index ff9eefc..8fcf621 100644 --- a/tests/db/utils/test_locations.py +++ b/tests/db/utils/test_locations.py @@ -5,7 +5,7 @@ import pytest from velofy.db import utils -# All tests take place in Paris. +# All tests take place in Paris MIN_EASTING, MAX_EASTING = 443_100, 461_200 MIN_NORTHING, MAX_NORTHING = 5_407_200, 5_416_800 ZONE = "31U" diff --git a/tests/forecasts/conftest.py b/tests/forecasts/conftest.py index 8378d33..e11492d 100644 --- a/tests/forecasts/conftest.py +++ b/tests/forecasts/conftest.py @@ -116,7 +116,7 @@ def order_totals(good_pixel_id): if pkg_config.SERVICE_START <= start_at.hour < pkg_config.SERVICE_END ) - # Re-index `data` filling in `0`s where there is no demand. + # Re-index `data` filling in `0`s where there is no demand index = pd.MultiIndex.from_tuples(gen) index.names = ["pixel_id", "start_at"] diff --git a/tests/forecasts/methods/test_decomposition.py b/tests/forecasts/methods/test_decomposition.py index c351cda..09e6b59 100644 --- a/tests/forecasts/methods/test_decomposition.py +++ b/tests/forecasts/methods/test_decomposition.py @@ -9,7 +9,7 @@ from tests import config as test_config from velofy.forecasts.methods import decomposition -# The "periodic" `ns` suggested for the STL method. +# The "periodic" `ns` suggested for the STL method NS = 999 @@ -66,7 +66,7 @@ class TestInvalidArguments: @pytest.mark.parametrize("nt", [-99, -1, 0, 1, 99, 125]) def test_nt_not_at_least_the_default(self, vertical_no_demand, nt): """`nt` must be odd and `>= default_nt`.""" - # `default_nt` becomes 161. + # `default_nt` becomes 161 default_nt = math.ceil( (1.5 * test_config.VERTICAL_FREQUENCY_LONG) / (1 - (1.5 / NS)), ) @@ -210,7 +210,7 @@ class TestValidArguments: assert list(result.columns) == ["seasonal", "trend", "residual"] # Run the `stl()` function with all possible combinations of arguments, - # including default ones and explicitly set non-default ones. + # including default ones and explicitly set non-default ones @pytest.mark.parametrize("nt", [None, 163]) @pytest.mark.parametrize("nl", [None, 777]) @pytest.mark.parametrize("ds", [0, 1]) diff --git a/tests/forecasts/timify/test_aggregate_orders.py b/tests/forecasts/timify/test_aggregate_orders.py index 91d66d7..42a56eb 100644 --- a/tests/forecasts/timify/test_aggregate_orders.py +++ b/tests/forecasts/timify/test_aggregate_orders.py @@ -40,7 +40,7 @@ class TestAggregateOrders: """ addresses_mock.return_value = [restaurant.address] - # `+1` as otherwise there would be a second pixel in one direction. + # `+1` as otherwise there would be a second pixel in one direction side_length = max(city.total_x, city.total_y) + 1 grid = db.Grid.gridify(city=city, side_length=side_length) db_session.add(grid) @@ -71,7 +71,7 @@ class TestAggregateOrders: make_order, ): """12 ad-hoc orders, one per operating hour.""" - # Create one order per hour and 12 orders in total. + # Create one order per hour and 12 orders in total for hour in range(11, 23): order = make_order( scheduled=False, @@ -91,7 +91,7 @@ class TestAggregateOrders: result = oh.aggregate_orders() - # The resulting `DataFrame` has 12 rows holding `1`s. + # The resulting `DataFrame` has 12 rows holding `1`s assert len(result) == 12 assert result["n_orders"].min() == 1 assert result["n_orders"].max() == 1 @@ -105,7 +105,7 @@ class TestAggregateOrders: make_order, ): """10 ad-hoc orders, one per hour, no orders after 21.""" - # Create one order per hour and 10 orders in total. + # Create one order per hour and 10 orders in total for hour in range(11, 21): order = make_order( scheduled=False, @@ -141,7 +141,7 @@ class TestAggregateOrders: make_order, ): """6 ad-hoc orders, one every other hour.""" - # Create one order every other hour. + # Create one order every other hour for hour in range(11, 23, 2): order = make_order( scheduled=False, @@ -161,7 +161,7 @@ class TestAggregateOrders: result = oh.aggregate_orders() - # The resulting `DataFrame` has 12 rows, 6 holding `0`s, and 6 holding `1`s. + # The resulting `DataFrame` has 12 rows, 6 holding `0`s, and 6 holding `1`s assert len(result) == 12 assert result["n_orders"].min() == 0 assert result["n_orders"].max() == 1 @@ -204,7 +204,7 @@ class TestAggregateOrders: result = oh.aggregate_orders() - # The resulting `DataFrame` has 12 rows, 11 holding `0`s, and one holding a `1`. + # The resulting `DataFrame` has 12 rows, 11 holding `0`s, and one holding a `1` assert len(result) == 12 assert result["n_orders"].min() == 0 assert result["n_orders"].max() == 1 @@ -221,7 +221,7 @@ class TestAggregateOrders: In half the time steps, there is no demand. """ - # Create one order per hour and 10 orders in total. + # Create one order per hour and 10 orders in total for hour in range(11, 23): order = make_order( scheduled=False, @@ -261,7 +261,7 @@ class TestAggregateOrders: ... and 6 orders, one every other hour on the second day. In total, there are 18 orders. """ - # Create one order per hour and 12 orders in total. + # Create one order per hour and 12 orders in total for hour in range(11, 23): order = make_order( scheduled=False, @@ -270,7 +270,7 @@ class TestAggregateOrders: ) db_session.add(order) - # Create one order every other hour and 6 orders in total. + # Create one order every other hour and 6 orders in total for hour in range(11, 23, 2): order = make_order( scheduled=False, @@ -296,7 +296,7 @@ class TestAggregateOrders: result = oh.aggregate_orders() - # The resulting `DataFrame` has 24 rows, 12 for each day. + # The resulting `DataFrame` has 24 rows, 12 for each day assert len(result) == 24 assert result["n_orders"].min() == 0 assert result["n_orders"].max() == 1 @@ -319,11 +319,11 @@ class TestAggregateOrders: addresses_mock.return_value = [address1, address2] - # Create `Restaurant`s at the two addresses. + # Create `Restaurant`s at the two addresses make_restaurant(address=address1) make_restaurant(address=address2) - # This creates four `Pixel`s, two of which have no `pickup_address`. + # This creates four `Pixel`s, two of which have no `pickup_address` side_length = max(city.total_x // 2, city.total_y // 2) + 1 grid = db.Grid.gridify(city=city, side_length=side_length) @@ -346,10 +346,10 @@ class TestAggregateOrders: In total, there are 30 orders. """ address1, address2 = two_pixel_grid.city.addresses - # Rarely, an `Address` may have several `Restaurant`s in the real dataset. + # Rarely, an `Address` may have several `Restaurant`s in the real dataset restaurant1, restaurant2 = address1.restaurants[0], address2.restaurants[0] - # Create one order every other hour for `restaurant1`. + # Create one order every other hour for `restaurant1` for hour in range(11, 23, 2): order = make_order( scheduled=False, @@ -358,7 +358,7 @@ class TestAggregateOrders: ) db_session.add(order) - # Create two orders per hour for `restaurant2`. + # Create two orders per hour for `restaurant2` for hour in range(11, 23): order = make_order( scheduled=False, @@ -399,7 +399,7 @@ class TestAggregateOrders: result = oh.aggregate_orders() - # The resulting `DataFrame` has 24 rows, 12 for each pixel. + # The resulting `DataFrame` has 24 rows, 12 for each pixel assert len(result) == 24 assert result["n_orders"].min() == 0 assert result["n_orders"].max() == 2 diff --git a/tests/forecasts/timify/test_avg_daily_demand.py b/tests/forecasts/timify/test_avg_daily_demand.py index df41c84..669dd23 100644 --- a/tests/forecasts/timify/test_avg_daily_demand.py +++ b/tests/forecasts/timify/test_avg_daily_demand.py @@ -64,7 +64,7 @@ class TestChooseTacticalModel: predict_at, ): """With high demand, the average daily demand is `.>= 25.0`.""" - # With 12 time steps per day, the ADD becomes `36.0`. + # With 12 time steps per day, the ADD becomes `36.0` order_history._data.loc[:, "n_orders"] = 3 result = order_history.choose_tactical_model( @@ -82,7 +82,7 @@ class TestChooseTacticalModel: predict_at, ): """With medium demand, the average daily demand is `>= 10.0` and `< 25.0`.""" - # With 12 time steps per day, the ADD becomes `24.0`. + # With 12 time steps per day, the ADD becomes `24.0` order_history._data.loc[:, "n_orders"] = 2 result = order_history.choose_tactical_model( diff --git a/tests/test_config.py b/tests/test_config.py index fcbd5aa..c6e64fe 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -31,7 +31,7 @@ def test_database_uri_set(env, monkeypatch): monkeypatch.setattr(configuration.ProductionConfig, "DATABASE_URI", uri) monkeypatch.setattr(configuration.TestingConfig, "DATABASE_URI", uri) - # Prevent that a warning is emitted for a missing R_LIBS_PATH. + # Prevent that a warning is emitted for a missing R_LIBS_PATH monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", ".cache/r_libs") with warnings.catch_warnings(record=True) as record: @@ -49,7 +49,7 @@ def test_no_database_uri_set_with_testing_env_var(env, monkeypatch): monkeypatch.setenv("TESTING", "true") - # Prevent that a warning is emitted for a missing R_LIBS_PATH. + # Prevent that a warning is emitted for a missing R_LIBS_PATH monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", ".cache/r_libs") with warnings.catch_warnings(record=True) as record: @@ -67,7 +67,7 @@ def test_no_database_uri_set_without_testing_env_var(env, monkeypatch): monkeypatch.delenv("TESTING", raising=False) - # Prevent that a warning is emitted for a missing R_LIBS_PATH. + # Prevent that a warning is emitted for a missing R_LIBS_PATH monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", ".cache/r_libs") with pytest.warns(UserWarning, match="no DATABASE_URI"): @@ -79,7 +79,7 @@ def test_r_libs_path_set(env, monkeypatch): """Package does NOT emit a warning if R_LIBS is set in the environment.""" monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", ".cache/r_libs") - # Prevent that a warning is emitted for a missing DATABASE_URI. + # Prevent that a warning is emitted for a missing DATABASE_URI uri = "postgresql://user:password@localhost/db" monkeypatch.setattr(configuration.ProductionConfig, "DATABASE_URI", uri) @@ -99,7 +99,7 @@ def test_no_r_libs_path_set_with_testing_env_var(env, monkeypatch): monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", None) monkeypatch.setenv("TESTING", "true") - # Prevent that a warning is emitted for a missing DATABASE_URI. + # Prevent that a warning is emitted for a missing DATABASE_URI uri = "postgresql://user:password@localhost/db" monkeypatch.setattr(configuration.ProductionConfig, "DATABASE_URI", uri) @@ -119,7 +119,7 @@ def test_no_r_libs_path_set_without_testing_env_var(env, monkeypatch): monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", None) monkeypatch.delenv("TESTING", raising=False) - # Prevent that a warning is emitted for a missing DATABASE_URI. + # Prevent that a warning is emitted for a missing DATABASE_URI uri = "postgresql://user:password@localhost/db" monkeypatch.setattr(configuration.ProductionConfig, "DATABASE_URI", uri) diff --git a/tests/test_version.py b/tests/test_version.py index bc3fde0..651be23 100644 --- a/tests/test_version.py +++ b/tests/test_version.py @@ -55,7 +55,7 @@ class TestSemanticVersioning: assert result is not None - # The next two test cases are sanity checks to validate the version_pattern. + # The next two test cases are sanity checks to validate the version_pattern @pytest.mark.parametrize( "version", From 2f1afd459fe73c2ab4136acaa1f87ecf64212e9f Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 10:13:13 +0100 Subject: [PATCH 04/19] Break multi-line comments before conjunctions --- src/velofy/db/addresses_addresses.py | 4 ++-- src/velofy/db/customers.py | 4 ++-- src/velofy/db/forecasts.py | 4 ++-- src/velofy/db/replay/orders.py | 8 ++++---- src/velofy/db/restaurants.py | 4 ++-- src/velofy/forecasts/methods/extrapolate_season.py | 4 ++-- src/velofy/forecasts/models/base.py | 4 ++-- tests/console/test_gridify.py | 6 +++--- tests/db/fake_data/factories/addresses.py | 4 ++-- tests/db/test_addresses_addresses.py | 4 ++-- tests/db/test_orders.py | 8 ++++---- 11 files changed, 27 insertions(+), 27 deletions(-) diff --git a/src/velofy/db/addresses_addresses.py b/src/velofy/db/addresses_addresses.py index 1919794..eb31d2f 100644 --- a/src/velofy/db/addresses_addresses.py +++ b/src/velofy/db/addresses_addresses.py @@ -305,8 +305,8 @@ class Path(meta.Base): # the `.waypoints` are not available self.sync_with_google_maps() - # First, plot the couriers' path between the start and - # end locations, so that it is below the `folium.Circle`s + # First, plot the couriers' path between the start and end locations, + # so that it is below the `folium.Circle`s line = folium.PolyLine( locations=( self.first_address.location.lat_lng, diff --git a/src/velofy/db/customers.py b/src/velofy/db/customers.py index 15fb3c2..cb84ca7 100644 --- a/src/velofy/db/customers.py +++ b/src/velofy/db/customers.py @@ -69,8 +69,8 @@ class Customer(meta.Base): # Note: a `Customer` may have more than one delivery `Address`es. # That is not true for `Restaurant`s after the data cleaning. - # Obtain all primary `Address`es where - # at least one delivery was made to `self` + # Obtain all primary `Address`es + # where at least one delivery was made to `self` delivery_addresses = db.session.scalars( sa.select(db.Address).where( db.Address.id.in_( diff --git a/src/velofy/db/forecasts.py b/src/velofy/db/forecasts.py index 31ef318..d90c16c 100644 --- a/src/velofy/db/forecasts.py +++ b/src/velofy/db/forecasts.py @@ -50,8 +50,8 @@ class Forecast(meta.Base): nullable=False, ) # We also store the actual order counts for convenient retrieval. - # A `UniqueConstraint` below ensures that redundant values that - # are to be expected are consistent across rows. + # A `UniqueConstraint` below ensures that redundant values + # that are to be expected are consistent across rows. actual: orm.Mapped[int] = orm.mapped_column( sa.SmallInteger, nullable=False, diff --git a/src/velofy/db/replay/orders.py b/src/velofy/db/replay/orders.py index ffe126e..d9f5418 100644 --- a/src/velofy/db/replay/orders.py +++ b/src/velofy/db/replay/orders.py @@ -216,8 +216,8 @@ class ReplayedOrder(meta.Base): sa.CheckConstraint( # A simulation must fill in at least all the timing and dispatch related # columns, unless an order is cancelled in a run. - # Only `.estimated_prep_duration`, `.first_estimated_delivery_at`, and - # `.utilization` are truly optional. + # Only `.estimated_prep_duration`, `.first_estimated_delivery_at`, + # and `.utilization` are truly optional. # This constraint does allow missing columns for cancelled orders # in any combination of the below columns. So, no precedence constraints # are enforced (e.g., `.restaurant_notified_at` and `.restaurant_ready_at` @@ -326,8 +326,8 @@ class ReplayedOrder(meta.Base): name="orders_dispatched_in_business_hours", ), *( - # The timestamps must be in a logically correct order. That is the same as - # in the actual `Order` model with an extra `restaurant_ready_at` column + # The timestamps must be in a logically correct order. That is the same + # as in the actual `Order` model with an extra `restaurant_ready_at` column # and the non-simulated columns removed. sa.CheckConstraint( constraint, diff --git a/src/velofy/db/restaurants.py b/src/velofy/db/restaurants.py index 7a01f52..b1020f3 100644 --- a/src/velofy/db/restaurants.py +++ b/src/velofy/db/restaurants.py @@ -110,8 +110,8 @@ class Restaurant(meta.Base): `.address.city.map` for convenience in interactive usage """ if customers: - # Obtain all primary `Address`es in the city that - # received at least one delivery from `self` + # Obtain all primary `Address`es in the city + # that received at least one delivery from `self` delivery_addresses = db.session.scalars( sa.select(db.Address).where( db.Address.id.in_( diff --git a/src/velofy/forecasts/methods/extrapolate_season.py b/src/velofy/forecasts/methods/extrapolate_season.py index deab4fc..ffa6a5e 100644 --- a/src/velofy/forecasts/methods/extrapolate_season.py +++ b/src/velofy/forecasts/methods/extrapolate_season.py @@ -44,8 +44,8 @@ def predict( seasonal_lag = frequency * (training_ts.index[1] - training_ts.index[0]) for lag in range(frequency): - # Obtain all `observations` of the same seasonal lag and - # fit a straight line through them (= `trend`) + # Obtain all `observations` of the same seasonal lag + # and fit a straight line through them (= `trend`) observations = training_ts[slice(lag, 999_999_999, frequency)] trend = observations - tsa.detrend(observations) diff --git a/src/velofy/forecasts/models/base.py b/src/velofy/forecasts/models/base.py index fd8e9c0..0c490a8 100644 --- a/src/velofy/forecasts/models/base.py +++ b/src/velofy/forecasts/models/base.py @@ -93,8 +93,8 @@ class ForecastingModelABC(abc.ABC): return cached_forecast # Horizontal and real-time `*Model`s return a `pd.DataFrame` with one - # row corresponding to the time step starting at `predict_at` whereas - # vertical models return several rows, covering all time steps of a day + # row corresponding to the time step starting at `predict_at` + # whereas vertical models return several rows, covering all time steps of a day predictions = self.predict(pixel, predict_at, train_horizon) # Convert the `predictions` into a `list` of `Forecast` objects diff --git a/tests/console/test_gridify.py b/tests/console/test_gridify.py index 4945b0e..13bfba1 100644 --- a/tests/console/test_gridify.py +++ b/tests/console/test_gridify.py @@ -30,9 +30,9 @@ def test_two_pixels_with_two_addresses( # ... and another one in the upper-right one. address2 = make_address(latitude=48.8898312, longitude=2.4357622) - # Locate a `Restaurant` at the two `Address` objects and - # place one `Order` for each of them so that the `Address` - # objects are used as `Order.pickup_address`s + # Locate a `Restaurant` at the two `Address`es + # and place one `Order` for each of them + # so that the `Address`es are used as `Order.pickup_address`es restaurant1 = make_restaurant(address=address1) restaurant2 = make_restaurant(address=address2) order1 = make_order(restaurant=restaurant1) diff --git a/tests/db/fake_data/factories/addresses.py b/tests/db/fake_data/factories/addresses.py index 3af587a..594ea5b 100644 --- a/tests/db/fake_data/factories/addresses.py +++ b/tests/db/fake_data/factories/addresses.py @@ -21,8 +21,8 @@ class AddressFactory(alchemy.SQLAlchemyModelFactory): created_at = factory.LazyFunction(utils.early_in_the_morning) # When testing, all addresses are considered primary ones. - # As non-primary addresses have no different behavior and - # the property is only kept from the original dataset for + # As non-primary addresses have no different behavior + # and the property is only kept from the original dataset for # completeness sake, that is ok to do. primary_id = factory.LazyAttribute(lambda obj: obj.id) diff --git a/tests/db/test_addresses_addresses.py b/tests/db/test_addresses_addresses.py index 2611e9c..313f669 100644 --- a/tests/db/test_addresses_addresses.py +++ b/tests/db/test_addresses_addresses.py @@ -384,8 +384,8 @@ class TestSyncWithGoogleMaps: "legs": [ { # We choose an artificially high distance of `9999` - # so that the synced bicycle distance is longer than - # the randomized air distance (i.e., fake data) for sure + # so that the synced bicycle distance is longer + # than the randomized air distance (i.e., fake data) for sure "distance": {"text": "3.0 km", "value": 9999}, "duration": {"text": "10 mins", "value": 596}, "end_address": "13 Place Paul et Jean Paul Avisseau, ...", diff --git a/tests/db/test_orders.py b/tests/db/test_orders.py index 38e8526..b62d57a 100644 --- a/tests/db/test_orders.py +++ b/tests/db/test_orders.py @@ -100,8 +100,8 @@ class TestConstraints: with pytest.raises(sa_exc.IntegrityError, match="fk_orders_to_restaurants"): db_session.commit() - # Here should be a test to check deletion of a referenced pickup address, so - # `test_delete_a_referenced_pickup_address(self, db_session, order)`. + # Here should be a test to check deletion of a referenced pickup address, + # so `test_delete_a_referenced_pickup_address(self, db_session, order)`. # The corresponding "fk_orders_to_addresses_on_pickup_address_id" constraint # is very hard to test in isolation as the above "fk_orders_to_restaurants_..." # constraint ensures its integrity already. @@ -1167,8 +1167,8 @@ def test_make_random_orders( # Ad-hoc `Order`s are far more common than pre-orders scheduled = random.choice([True, False, False, False, False]) - # Randomly pass a `address` argument to `make_restaurant()` and - # a `restaurant` argument to `make_order()` + # Randomly pass a `address` argument to `make_restaurant()` + # and a `restaurant` argument to `make_order()` if random.random() < 0.5: address = random.choice([None, make_address()]) restaurant = make_restaurant(address=address) From ff7f705bc831734bbab63a43fd78a11121696bc5 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 10:16:13 +0100 Subject: [PATCH 05/19] Put identifiers in comments into backticks --- tests/test_config.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/test_config.py b/tests/test_config.py index c6e64fe..a4964a5 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -31,7 +31,7 @@ def test_database_uri_set(env, monkeypatch): monkeypatch.setattr(configuration.ProductionConfig, "DATABASE_URI", uri) monkeypatch.setattr(configuration.TestingConfig, "DATABASE_URI", uri) - # Prevent that a warning is emitted for a missing R_LIBS_PATH + # Prevent that a warning is emitted for a missing `R_LIBS_PATH` monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", ".cache/r_libs") with warnings.catch_warnings(record=True) as record: @@ -49,7 +49,7 @@ def test_no_database_uri_set_with_testing_env_var(env, monkeypatch): monkeypatch.setenv("TESTING", "true") - # Prevent that a warning is emitted for a missing R_LIBS_PATH + # Prevent that a warning is emitted for a missing `R_LIBS_PATH` monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", ".cache/r_libs") with warnings.catch_warnings(record=True) as record: @@ -67,7 +67,7 @@ def test_no_database_uri_set_without_testing_env_var(env, monkeypatch): monkeypatch.delenv("TESTING", raising=False) - # Prevent that a warning is emitted for a missing R_LIBS_PATH + # Prevent that a warning is emitted for a missing `R_LIBS_PATH` monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", ".cache/r_libs") with pytest.warns(UserWarning, match="no DATABASE_URI"): @@ -79,7 +79,7 @@ def test_r_libs_path_set(env, monkeypatch): """Package does NOT emit a warning if R_LIBS is set in the environment.""" monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", ".cache/r_libs") - # Prevent that a warning is emitted for a missing DATABASE_URI + # Prevent that a warning is emitted for a missing `DATABASE_URI` uri = "postgresql://user:password@localhost/db" monkeypatch.setattr(configuration.ProductionConfig, "DATABASE_URI", uri) @@ -99,7 +99,7 @@ def test_no_r_libs_path_set_with_testing_env_var(env, monkeypatch): monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", None) monkeypatch.setenv("TESTING", "true") - # Prevent that a warning is emitted for a missing DATABASE_URI + # Prevent that a warning is emitted for a missing `DATABASE_URI` uri = "postgresql://user:password@localhost/db" monkeypatch.setattr(configuration.ProductionConfig, "DATABASE_URI", uri) @@ -119,7 +119,7 @@ def test_no_r_libs_path_set_without_testing_env_var(env, monkeypatch): monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", None) monkeypatch.delenv("TESTING", raising=False) - # Prevent that a warning is emitted for a missing DATABASE_URI + # Prevent that a warning is emitted for a missing `DATABASE_URI` uri = "postgresql://user:password@localhost/db" monkeypatch.setattr(configuration.ProductionConfig, "DATABASE_URI", uri) From 1413d08ed9115501fa2757b97de23525581d9acf Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 10:38:28 +0100 Subject: [PATCH 06/19] Reword the comments in `velofy.db` Each comment is one sentence or two short ones joined by "=>", without a final period. --- src/velofy/db/addresses_addresses.py | 16 ++++---- src/velofy/db/addresses_pixels.py | 2 +- src/velofy/db/cities.py | 5 +-- src/velofy/db/connection.py | 3 +- src/velofy/db/customers.py | 9 ++--- src/velofy/db/forecasts.py | 13 +++---- src/velofy/db/grids.py | 4 +- src/velofy/db/pixels.py | 5 +-- src/velofy/db/replay/orders.py | 57 +++++++++------------------- 9 files changed, 43 insertions(+), 71 deletions(-) diff --git a/src/velofy/db/addresses_addresses.py b/src/velofy/db/addresses_addresses.py index eb31d2f..9fff47e 100644 --- a/src/velofy/db/addresses_addresses.py +++ b/src/velofy/db/addresses_addresses.py @@ -144,9 +144,9 @@ class Path(meta.Base): """ paths = [] - # We consider all 2-tuples of `Address`es. The symmetric graph is ... + # All 2-tuples of `Address`es suffice as the graph is symmetric ... for pair in itertools.combinations(addresses, 2): - # ... implicitly enforced by a precedence constraint for the `.id`s. + # ... which a precedence constraint for the `.id`s enforces first, second = sorted(pair, key=lambda address: address.id) # If there is no `Path` object in the database ... @@ -155,7 +155,7 @@ class Path(meta.Base): .where(cls.first_address == first) .where(cls.second_address == second), ).first() - # ... create a new one. + # ... create a new one if path is None: air_distance = geo_distance.great_circle( first.location.lat_lng, @@ -223,18 +223,16 @@ class Path(meta.Base): mode="bicycling", alternatives=False, ) - # Without "alternatives" and "waypoints", the `response` contains - # exactly one "route" that consists of exactly one "leg". + # Without "alternatives" and "waypoints", + # the `response` has exactly one "route" with exactly one "leg" # Source: https://developers.google.com/maps/documentation/directions/get-directions#Legs # noqa:E501 route = response[0]["legs"][0] self.bicycle_distance = route["distance"]["value"] self.bicycle_duration = route["duration"]["value"] - # Each route consists of many "steps" that are instructions as to how to - # get from A to B. As a step's "start_location" may equal the previous step's - # "end_location", we use an `OrderedSet` to find the unique latitude-longitude - # pairs that make up the path from `.first_address` to `.second_address`. + # A step's "start_location" may equal the previous step's "end_location" + # => `OrderedSet` keeps only the unique points, in order steps: ordered_set.OrderedSet[tuple[float, float]] = ordered_set.OrderedSet([]) for step in route["steps"]: steps.add( diff --git a/src/velofy/db/addresses_pixels.py b/src/velofy/db/addresses_pixels.py index dc20b4a..aa034b3 100644 --- a/src/velofy/db/addresses_pixels.py +++ b/src/velofy/db/addresses_pixels.py @@ -46,7 +46,7 @@ class AddressPixelAssociation(meta.Base): onupdate="RESTRICT", ondelete="RESTRICT", ), - # ... if their `.city` attributes match. + # ... if their `.city` attributes match sa.ForeignKeyConstraint( ["grid_id", "city_id"], ["grids.id", "grids.city_id"], diff --git a/src/velofy/db/cities.py b/src/velofy/db/cities.py index 7a54a24..3a8f2e6 100644 --- a/src/velofy/db/cities.py +++ b/src/velofy/db/cities.py @@ -175,8 +175,7 @@ class City(meta.Base): ).all() for address in addresses: - # Show the restaurant's name if there is only one. - # Otherwise, list all the restaurants' ID's. + # Show a single restaurant's name, but only the IDs of several restaurants = db.session.scalars( sa.select(db.Restaurant) .join(db.Address, db.Restaurant.address_id == db.Address.id) @@ -196,7 +195,7 @@ class City(meta.Base): .join(db.Address, db.Order.pickup_address_id == db.Address.id) .where(db.Address.primary_id == address.id), ).scalar_one() - # ... and adjust the size of the red dot on the `.map`. + # ... and adjust the size of the red dot on the `.map` if n_orders >= 1000: radius = 20 elif n_orders >= 500: diff --git a/src/velofy/db/connection.py b/src/velofy/db/connection.py index bab7f56..c8d2ac9 100644 --- a/src/velofy/db/connection.py +++ b/src/velofy/db/connection.py @@ -21,8 +21,7 @@ def get_engine() -> sa.Engine: return sa.create_engine(t.cast(str, velofy.config.DATABASE_URI)) -# `scoped_session()` accepts any callable creating sessions -# while its type stubs expect a `sessionmaker` +# `scoped_session()` accepts any session factory but its stubs expect a `sessionmaker` # => The lambda defers creating the engine to first use session: orm.scoped_session[orm.Session] = orm.scoped_session( t.cast( diff --git a/src/velofy/db/customers.py b/src/velofy/db/customers.py index cb84ca7..be53eaa 100644 --- a/src/velofy/db/customers.py +++ b/src/velofy/db/customers.py @@ -66,8 +66,8 @@ class Customer(meta.Base): Returns: `...city.map` for convenience in interactive usage """ - # Note: a `Customer` may have more than one delivery `Address`es. - # That is not true for `Restaurant`s after the data cleaning. + # Unlike a `Restaurant` after the data cleaning, + # a `Customer` may have several delivery `Address`es # Obtain all primary `Address`es # where at least one delivery was made to `self` @@ -129,9 +129,8 @@ class Customer(meta.Base): ).all() for address in pickup_addresses: - # Show the restaurant's name if there is only one. - # Otherwise, list all the restaurants' ID's. - # We cannot show the `Order.restaurant.name` due to the aggregation. + # Show a single restaurant's name, but only the IDs of several + # => `Order.restaurant.name` is not available after the aggregation restaurants_at_address = db.session.scalars( sa.select(db.Restaurant) .join(db.Address, db.Restaurant.address_id == db.Address.id) diff --git a/src/velofy/db/forecasts.py b/src/velofy/db/forecasts.py index d90c16c..066a573 100644 --- a/src/velofy/db/forecasts.py +++ b/src/velofy/db/forecasts.py @@ -49,15 +49,14 @@ class Forecast(meta.Base): sa.Unicode(length=20), nullable=False, ) - # We also store the actual order counts for convenient retrieval. - # A `UniqueConstraint` below ensures that redundant values - # that are to be expected are consistent across rows. + # The actual order counts are stored for convenient retrieval + # => A `UniqueConstraint` below keeps the redundant values consistent actual: orm.Mapped[int] = orm.mapped_column( sa.SmallInteger, nullable=False, ) - # Raw `.prediction`s are stored as `float`s (possibly negative). - # The rounding is then done on the fly if required. + # Raw `.prediction`s are stored as `float`s (possibly negative) + # => They are rounded on the fly if required prediction: orm.Mapped[float] = orm.mapped_column( psql.DOUBLE_PRECISION, nullable=False, @@ -243,8 +242,8 @@ class Forecast(meta.Base): model=model, actual=int(actual), prediction=float(round(prediction, 5)), - # Explicit type casting. SQLAlchemy does not convert - # `float('NaN')`s into plain `None`s. + # `sqlalchemy` does not convert `float('NaN')`s into `None`s + # => Cast the values explicitly low80=None if math.isnan(low80) else float(round(low80, 5)), high80=None if math.isnan(high80) else float(round(high80, 5)), low95=None if math.isnan(low95) else float(round(low95, 5)), diff --git a/src/velofy/db/grids.py b/src/velofy/db/grids.py index b5ffd91..7356deb 100644 --- a/src/velofy/db/grids.py +++ b/src/velofy/db/grids.py @@ -110,13 +110,13 @@ class Grid(meta.Base): or address.y < 0 or address.y > city.total_y ) - # ... and, if so, the `address` does not belong to any `Pixel`. + # ... and, if so, the `address` does not belong to any `Pixel` if not_within_city_viewport: continue # Determine which `pixel` the `address` belongs to ... n_x, n_y = address.x // side_length, address.y // side_length - # ... and create a new `Pixel` object if necessary. + # ... and create a new `Pixel` object if necessary if (n_x, n_y) not in pixels: pixels[(n_x, n_y)] = db.Pixel(n_x=n_x, n_y=n_y) grid.pixels.append(pixels[(n_x, n_y)]) diff --git a/src/velofy/db/pixels.py b/src/velofy/db/pixels.py index 2ddb3ef..0d0bb64 100644 --- a/src/velofy/db/pixels.py +++ b/src/velofy/db/pixels.py @@ -223,8 +223,7 @@ class Pixel(meta.Base): ).all() for address in addresses: - # Show the restaurant's name if there is only one. - # Otherwise, list all the restaurants' ID's. + # Show a single restaurant's name, but only the IDs of several restaurants_at_address = db.session.scalars( sa.select(db.Restaurant) .join(db.Address, db.Restaurant.address_id == db.Address.id) @@ -244,7 +243,7 @@ class Pixel(meta.Base): .join(db.Address, db.Order.pickup_address_id == db.Address.id) .where(db.Address.primary_id == address.id), ).scalar_one() - # ... and adjust the size of the red dot on the `.map`. + # ... and adjust the size of the red dot on the `.map` if n_orders >= 1000: radius = 20 elif n_orders >= 500: diff --git a/src/velofy/db/replay/orders.py b/src/velofy/db/replay/orders.py index d9f5418..f49ed81 100644 --- a/src/velofy/db/replay/orders.py +++ b/src/velofy/db/replay/orders.py @@ -25,9 +25,8 @@ class ReplayedOrder(meta.Base): ) # `Order`-type related columns - # `.ad_hoc` is part of a `ForeignKeyConstraint` to ensure the type - # of the `ReplayedOrder` (i.e., ad-hoc or scheduled) is in line - # with the `.actual` order + # `.ad_hoc` is part of a `ForeignKeyConstraint` + # => The type (i.e., ad-hoc or scheduled) matches the `.actual` order's ad_hoc: orm.Mapped[bool] = orm.mapped_column( sa.Boolean, nullable=False, @@ -139,9 +138,8 @@ class ReplayedOrder(meta.Base): ), # The check constraints model some of the assumptions made in the simulations sa.CheckConstraint( - # Align the order's type, ad-hoc or scheduled, with the type of the - # `.actual` order and ensure the corresponding datetime column is set - # or not set + # The type (i.e., ad-hoc or scheduled) must match the `.actual` order's + # => The corresponding datetime column is set accordingly """ ( ad_hoc IS TRUE @@ -214,15 +212,8 @@ class ReplayedOrder(meta.Base): name="scheduled_orders_not_within_30_minutes", ), sa.CheckConstraint( - # A simulation must fill in at least all the timing and dispatch related - # columns, unless an order is cancelled in a run. - # Only `.estimated_prep_duration`, `.first_estimated_delivery_at`, - # and `.utilization` are truly optional. - # This constraint does allow missing columns for cancelled orders - # in any combination of the below columns. So, no precedence constraints - # are enforced (e.g., `.restaurant_notified_at` and `.restaurant_ready_at` - # could be set without `.restaurant_confirmed_at`). That is acceptable - # as cancelled orders are left out in the optimized KPIs. + # Simulated orders must fill in all timing and dispatch columns + # => Cancelled orders are exempt as the optimized KPIs exclude them """ cancelled_at IS NOT NULL OR @@ -255,15 +246,8 @@ class ReplayedOrder(meta.Base): name="orders_must_be_either_cancelled_or_fully_simulated", ), sa.CheckConstraint( - # 23,487 out of the 660,608 orders were cancelled. In 685 of them, the - # cancellation occurred after the pickup (as modeled by the `.pickup_at` - # and `.left_pickup_at` columns, where the latter may be set with the - # former being unset). As a simplification, we only allow cancellations - # before the pickup in the simulations. Then, the restaurant throws away - # the meal and the courier is free for other orders right away. Orders - # cancelled after pickup in the actual data are assumed to be delivered - # to the customer's door (and then still accepted or thrown away by the - # customer). So, the courier becomes free only after the "fake" delivery. + # Simulations only allow cancellations before the pickup (simplification) + # => 685 of 23,487 actual cancellations after pickup count as delivered """ NOT ( -- Only occurred in 528 of 660,608 orders in the actual data. cancelled_at IS NOT NULL @@ -292,30 +276,26 @@ class ReplayedOrder(meta.Base): name="cancellations_may_only_occur_before_pickup", ), sa.CheckConstraint( - # The actual `.estimated_prep_duration` and `.estimated_prep_buffer` - # are modeled together as only one value. Therefore, the individual - # upper limits of 2700 and 900 are added and result in 3600. + # One value models the actual prep duration and buffer together + # => Their upper limits of 2700 and 900 add up to 3600 "0 <= estimated_prep_duration AND estimated_prep_duration <= 3600", name="estimated_prep_duration_between_0_and_3600", ), sa.CheckConstraint( - # We still round estimates of the preparation time to whole minutes. - # Other estimates are unlikely to change the simulation results in - # a significant way. + # Prep time estimates are still rounded to whole minutes + # => Other estimates are unlikely to change the simulation results "estimated_prep_duration % 60 = 0", name="estimated_prep_duration_must_be_whole_minutes", ), sa.CheckConstraint( - # If a simulation's `.strategy` models `.utilization`, it must be - # realistic. The value can be deduced from the actual order's - # courier's `.capacity` and the actual order's `.utilization`. + # A modeled `.utilization` must be realistic + # => It follows from the actual `.capacity` and `.utilization` "0 <= utilization AND utilization <= 100", name="utilization_between_0_and_100", ), sa.CheckConstraint( - # The UDP is open from 11 am to 11 pm. So, before 11 am there is no - # activity. After 11 pm, the last orders of a day are all assumed to be - # dispatched before midnight. + # The UDP operates from 11 am to 11 pm + # => All orders are dispatched between 11 am and midnight """ NOT ( EXTRACT(HOUR FROM restaurant_notified_at) < 11 @@ -326,9 +306,8 @@ class ReplayedOrder(meta.Base): name="orders_dispatched_in_business_hours", ), *( - # The timestamps must be in a logically correct order. That is the same - # as in the actual `Order` model with an extra `restaurant_ready_at` column - # and the non-simulated columns removed. + # The timestamps must be in the same order as in `Order`, extended by + # `.restaurant_ready_at` and without the non-simulated columns sa.CheckConstraint( constraint, name=f"ordered_timestamps_{index}", From 9b8fe8b8fd41e920954ce4cda5b2fd5e70b44185 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 10:43:35 +0100 Subject: [PATCH 07/19] Reword the comments in `velofy.forecasts` Each comment is one sentence or two short ones joined by "=>", without a final period. --- src/velofy/forecasts/methods/arima.py | 3 +-- src/velofy/forecasts/methods/decomposition.py | 3 +-- src/velofy/forecasts/methods/ets.py | 3 +-- src/velofy/forecasts/models/base.py | 5 ++-- .../forecasts/models/tactical/horizontal.py | 5 ++-- .../forecasts/models/tactical/realtime.py | 6 ++--- .../forecasts/models/tactical/vertical.py | 6 ++--- src/velofy/forecasts/timify.py | 23 ++++++++----------- 8 files changed, 20 insertions(+), 34 deletions(-) diff --git a/src/velofy/forecasts/methods/arima.py b/src/velofy/forecasts/methods/arima.py index da5a7da..7a59247 100644 --- a/src/velofy/forecasts/methods/arima.py +++ b/src/velofy/forecasts/methods/arima.py @@ -31,8 +31,7 @@ def predict( Raises: ValueError: if `training_ts` contains `NaN` values """ - # Initialize R only if it is actually used. - # For example, the nox session "ci-tests-fast" does not use it. + # Import R lazily => Code and tests not using it do not need R from velofy import init_r # noqa:F401,PLC0415 # Re-seed R every time it is used to ensure reproducibility diff --git a/src/velofy/forecasts/methods/decomposition.py b/src/velofy/forecasts/methods/decomposition.py index ec71fec..cb932e8 100644 --- a/src/velofy/forecasts/methods/decomposition.py +++ b/src/velofy/forecasts/methods/decomposition.py @@ -163,8 +163,7 @@ def stl( # noqa:C901,PLR0912,PLR0913,PLR0915 raise ValueError(msg) robust = no > 0 - # Initialize R only if it is actually used. - # For example, the nox session "ci-tests-fast" does not use it. + # Import R lazily => Code and tests not using it do not need R from velofy import init_r # noqa:F401,PLC0415 # Re-seed R every time it is used to ensure reproducibility diff --git a/src/velofy/forecasts/methods/ets.py b/src/velofy/forecasts/methods/ets.py index 021786e..6ecc193 100644 --- a/src/velofy/forecasts/methods/ets.py +++ b/src/velofy/forecasts/methods/ets.py @@ -32,8 +32,7 @@ def predict( Raises: ValueError: if `training_ts` contains `NaN` values """ - # Initialize R only if it is actually used. - # For example, the nox session "ci-tests-fast" does not use it. + # Import R lazily => Code and tests not using it do not need R from velofy import init_r # noqa:F401,PLC0415 # Re-seed R every time it is used to ensure reproducibility diff --git a/src/velofy/forecasts/models/base.py b/src/velofy/forecasts/models/base.py index 0c490a8..8a6e14b 100644 --- a/src/velofy/forecasts/models/base.py +++ b/src/velofy/forecasts/models/base.py @@ -92,9 +92,8 @@ class ForecastingModelABC(abc.ABC): ).one_or_none(): return cached_forecast - # Horizontal and real-time `*Model`s return a `pd.DataFrame` with one - # row corresponding to the time step starting at `predict_at` - # whereas vertical models return several rows, covering all time steps of a day + # Horizontal and real-time `*Model`s predict one time step, + # vertical ones all time steps of the day predictions = self.predict(pixel, predict_at, train_horizon) # Convert the `predictions` into a `list` of `Forecast` objects diff --git a/src/velofy/forecasts/models/tactical/horizontal.py b/src/velofy/forecasts/models/tactical/horizontal.py index fa11e35..bf934fc 100644 --- a/src/velofy/forecasts/models/tactical/horizontal.py +++ b/src/velofy/forecasts/models/tactical/horizontal.py @@ -118,9 +118,8 @@ class HorizontalSMAModel(base.ForecastingModelABC): msg = "the hsma model can only predict one step into the future" raise RuntimeError(msg) - # The "prediction" is calculated as the `np.mean()`. - # As the `training_ts` covers only full week horizons, - # no adjustment regarding the weekly seasonality is needed. + # The `training_ts` covers only full weeks + # => Its `np.mean()` needs no adjustment for weekly seasonality predictions = pd.DataFrame( data={ "actual": actuals_ts, diff --git a/src/velofy/forecasts/models/tactical/realtime.py b/src/velofy/forecasts/models/tactical/realtime.py index 81dad8d..369605c 100644 --- a/src/velofy/forecasts/models/tactical/realtime.py +++ b/src/velofy/forecasts/models/tactical/realtime.py @@ -81,10 +81,8 @@ class RealtimeARIMAModel(base.ForecastingModelABC): seasonal_fit=False, ) - # The overall `predictions` are the sum of the separate predictions above. - # As the linear extrapolation of the seasonal component has no - # confidence interval, we put the one from the ARIMA model around - # the extrapolated seasonal component. + # The seasonal extrapolation has no confidence interval + # => The ARIMA model's one is shifted by the seasonal predictions predictions = pd.DataFrame( data={ "actual": actuals_ts, diff --git a/src/velofy/forecasts/models/tactical/vertical.py b/src/velofy/forecasts/models/tactical/vertical.py index ae972d2..4d2528a 100644 --- a/src/velofy/forecasts/models/tactical/vertical.py +++ b/src/velofy/forecasts/models/tactical/vertical.py @@ -81,10 +81,8 @@ class VerticalARIMAModel(base.ForecastingModelABC): seasonal_fit=False, ) - # The overall `predictions` are the sum of the separate predictions above. - # As the linear extrapolation of the seasonal component has no - # confidence interval, we put the one from the ARIMA model around - # the extrapolated seasonal component. + # The seasonal extrapolation has no confidence interval + # => The ARIMA model's one is shifted by the seasonal predictions predictions = pd.DataFrame( data={ "actual": actuals_ts, diff --git a/src/velofy/forecasts/timify.py b/src/velofy/forecasts/timify.py index 61d09ba..09727b2 100644 --- a/src/velofy/forecasts/timify.py +++ b/src/velofy/forecasts/timify.py @@ -66,8 +66,8 @@ class OrderHistory: def aggregate_orders(self) -> pd.DataFrame: # pragma: no cover """Generate and load all order totals from the database.""" - # `data` is probably missing "pixel_id"-"start_at" pairs. - # This happens when there is no demand in the `Pixel` in the given `time_step`. + # Without any demand in a `time_step`, `data` lacks + # the corresponding "pixel_id"-"start_at" pair data = pd.read_sql_query( sa.text( f""" @@ -165,8 +165,7 @@ class OrderHistory: end_day.day, pkg_config.SERVICE_END, ) - # ... and all possible `tuple`s of "pixel_id"-"start_at" combinations. - # The "start_at" values must lie within the operating hours. + # ... and all "pixel_id"-"start_at" pairs within the operating hours gen = ( (pixel_id, start_at) for pixel_id in sorted(index.levels[0]) @@ -287,9 +286,8 @@ class OrderHistory: msg = "Internal error: cannot predict beyond the given data" raise RuntimeError(msg) - # The first and last training day are just before the `predict_at` day - # and span exactly `train_horizon` weeks covering only the times of the - # day equal to the hour/minute of `predict_at` + # The training days end just before the `predict_at` day and span + # `train_horizon` weeks, but only at the time of day of `predict_at` first_train_day = predict_at.date() - dt.timedelta(weeks=train_horizon) first_start_at = dt.datetime( first_train_day.year, @@ -456,9 +454,8 @@ class OrderHistory: msg = "Internal error: cannot predict beyond the given data" raise RuntimeError(msg) - # The first and last training day are just before the `predict_at` day - # and span exactly `train_horizon` weeks covering all times of the day, - # including times on the `predict_at` day that are earlier than `predict_at` + # The training days span `train_horizon` weeks before the `predict_at` day + # plus the times on the `predict_at` day before `predict_at` first_train_day = predict_at.date() - dt.timedelta(weeks=train_horizon) first_start_at = dt.datetime( first_train_day.year, @@ -467,10 +464,8 @@ class OrderHistory: pkg_config.SERVICE_START, 0, ) - # Predicting the first time step on the `predict_at` day is a corner case. - # Then, the previous day is indeed the `last_train_day`. Predicting any - # other time step implies that the `predict_at` day is the `last_train_day`. - # `last_train_time` is the last "start_at" before the one being predicted. + # Predicting the day's first time step is a corner case + # => Only then is the previous day the `last_train_day` if predict_at.hour == pkg_config.SERVICE_START: last_train_day = predict_at.date() - dt.timedelta(days=1) last_train_time = dt.time(pkg_config.SERVICE_END, 0) From 0f6970922623a7bda82b78bb48d5fb05646e7d45 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 10:46:24 +0100 Subject: [PATCH 08/19] Reword the comments in the rest of `velofy` Each comment is one sentence or two short ones joined by "=>", without a final period. --- src/velofy/configuration.py | 20 ++++++++------------ src/velofy/console/forecasts.py | 9 ++++----- src/velofy/init_r.py | 2 +- 3 files changed, 13 insertions(+), 18 deletions(-) diff --git a/src/velofy/configuration.py b/src/velofy/configuration.py index 88cb336..00020b5 100644 --- a/src/velofy/configuration.py +++ b/src/velofy/configuration.py @@ -38,17 +38,16 @@ class Config: SERVICE_START = 11 SERVICE_END = 23 - # Side lengths (in meters) for which pixel grids are created. - # They are the basis for the aggregated demand forecasts. + # Side lengths (in meters) of the pixel grids + # => They are the basis for the aggregated demand forecasts GRID_SIDE_LENGTHS = (707, 1000, 1414) # Time steps (in minutes) used to aggregate the # individual orders into time series TIME_STEPS = (60,) - # Training horizons (in full weeks) used to train the forecasting models. - # For now, we only use 7 and 8 weeks as that was the best performing in - # a previous study (note:4f79e8fa). + # Training horizons (in full weeks) for the forecasting models + # => 7 and 8 weeks performed best in a previous study (note:4f79e8fa) TRAIN_HORIZONS = (7, 8) # The demand forecasting methods used in the simulations @@ -118,19 +117,16 @@ def make_config(env: str = "production") -> Config: msg = "Must be either 'production' or 'testing'" raise ValueError(msg) - # Without a PostgreSQL database the package cannot work. - # As pytest sets the "TESTING" environment variable explicitly, - # the warning is only emitted if the code is not run by pytest. - # We see the bad configuration immediately as all "db" tests fail. + # pytest sets `TESTING` and fails all "db" tests without a database anyway + # => Warn only outside pytest if config.DATABASE_URI is None and not os.getenv("TESTING"): warnings.warn( "Bad configuration: no DATABASE_URI set in the environment", stacklevel=2, ) - # Some functionalities require R and some packages installed. - # To ensure isolation and reproducibility, the projects keeps the R dependencies - # in a project-local folder that must be set in the environment. + # The R packages live in a project-local folder for isolation and reproducibility + # => Its path must be set in the environment if config.R_LIBS_PATH is None and not os.getenv("TESTING"): warnings.warn( "Bad configuration: no R_LIBS set in the environment", diff --git a/src/velofy/console/forecasts.py b/src/velofy/console/forecasts.py index d1841b8..0abf5db 100644 --- a/src/velofy/console/forecasts.py +++ b/src/velofy/console/forecasts.py @@ -103,9 +103,8 @@ def tactical_heuristic( # noqa:C901,D417,DOC001 # Run the tactical heuristic for pixel in grid.pixels: - # Important: this check may need to be adapted once further - # commands are added the make `Forecast`s without the heuristic! - # Continue with forecasting on the day the last prediction was made ... + # Continue on the day of the last prediction ... + # (assuming that no other command makes `Forecast`s) last_predict_at = db.session.scalar( sa.select(sa.func.max(db.Forecast.start_at)) .join(db.Pixel, db.Forecast.pixel_id == db.Pixel.id) @@ -116,7 +115,7 @@ def tactical_heuristic( # noqa:C901,D417,DOC001 .where(db.Forecast.train_horizon == train_horizon), ) # ... or start `train_horizon` weeks after the first `Order` - # if no `Forecast`s are in the database yet. + # if no `Forecast`s are in the database yet if last_predict_at is None: predict_day = order_history.first_order_at(pixel_id=pixel.id).date() predict_day += dt.timedelta(weeks=train_horizon) @@ -125,7 +124,7 @@ def tactical_heuristic( # noqa:C901,D417,DOC001 # Go over all days in chronological order ... while predict_day <= order_history.last_order_at(pixel_id=pixel.id).date(): - # ... and choose the most promising `*Model` for that day. + # ... and choose the most promising `*Model` for that day model = order_history.choose_tactical_model( pixel_id=pixel.id, predict_day=predict_day, diff --git a/src/velofy/init_r.py b/src/velofy/init_r.py index c4d0ab1..cd62426 100644 --- a/src/velofy/init_r.py +++ b/src/velofy/init_r.py @@ -11,7 +11,7 @@ from rpy2.rinterface_lib import callbacks as r_callbacks from rpy2.robjects import packages as r_packages -# Suppress R's messages to stdout and stderr. +# R's console messages would clutter the output => Suppress them # Source: https://stackoverflow.com/a/63220287 r_callbacks.consolewrite_print = lambda *_args, **_kwargs: None # pragma: no cover r_callbacks.consolewrite_warnerror = lambda *_args, **_kwargs: None # pragma: no cover From bca4250b4d9512dde4f67996f21f4c4bc9c18387 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 10:52:09 +0100 Subject: [PATCH 09/19] Reword the comments in the test suite Each comment is one sentence or two short ones joined by "=>", without a final period. --- tests/config.py | 9 ++++----- tests/conftest.py | 9 ++++----- tests/console/test_gridify.py | 9 +++------ tests/db/fake_data/factories/addresses.py | 6 ++---- tests/db/fake_data/factories/orders/ad_hoc.py | 8 ++++---- tests/db/replay/test_orders.py | 8 +++----- tests/db/test_addresses_addresses.py | 5 ++--- tests/db/test_grids.py | 6 +++--- tests/db/test_orders.py | 19 +++++++------------ tests/forecasts/conftest.py | 9 +++------ .../forecasts/timify/test_aggregate_orders.py | 8 +++----- .../forecasts/timify/test_avg_daily_demand.py | 2 +- 12 files changed, 39 insertions(+), 59 deletions(-) diff --git a/tests/config.py b/tests/config.py index 64c0817..304ced3 100644 --- a/tests/config.py +++ b/tests/config.py @@ -13,8 +13,8 @@ DATE = (YEAR, MONTH, DAY) # The hour when most test cases take place NOON = 12 -# `START` and `END` constitute a 57-day time span, 8 full weeks plus 1 day. -# That implies a maximum `train_horizon` of `8` as that needs full 7-day weeks. +# `START` and `END` span 57 days, i.e., 8 full weeks plus 1 day +# => The maximum `train_horizon` is `8` as it needs full 7-day weeks START = dt.datetime(YEAR, MONTH, DAY, pkg_config.SERVICE_START, 0) _end = START + dt.timedelta(days=56) # `56` as `START` is not included END = dt.datetime(_end.year, _end.month, _end.day, pkg_config.SERVICE_END, 0) @@ -23,9 +23,8 @@ END = dt.datetime(_end.year, _end.month, _end.day, pkg_config.SERVICE_END, 0) LONG_TIME_STEP = 60 SHORT_TIME_STEP = 30 TIME_STEPS = (SHORT_TIME_STEP, LONG_TIME_STEP) -# The `frequency` of vertical time series is the number of days in a week, 7, -# times the number of time steps per day. With 12 operating hours (11 am - 11 pm) -# the `frequency`s are 84 and 168 for the `LONG/SHORT_TIME_STEP`s. +# Vertical `frequency`s are 7 days times the time steps per day (12 operating hours) +# => 84 and 168 for the `LONG_TIME_STEP` and `SHORT_TIME_STEP` VERTICAL_FREQUENCY_LONG = 7 * 12 VERTICAL_FREQUENCY_SHORT = 7 * 24 diff --git a/tests/conftest.py b/tests/conftest.py index e861199..30740d4 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -54,8 +54,8 @@ def db_connection(request): This ensures that Alembic's migration files are consistent. """ - # We need a fresh database connection for each of the two `params`. - # Otherwise, the first test of the parameter run second will fail. + # Each of the two `params` needs a fresh database connection + # => Otherwise, the first test of the second parameter run fails engine = sa.create_engine(pkg_config.DATABASE_URI) connection = engine.connect() @@ -98,9 +98,8 @@ def db_session(db_connection, monkeypatch): # that is rolled back at the end of each test case transaction = db_connection.begin() - # Create a session bound to the same connection as the `transaction`. - # Using any other session would not result in the roll back. - # Commits inside a test case then only release a savepoint. + # The session joins the `transaction`'s connection to be rolled back with it + # => Commits inside a test case only release a savepoint session = orm.Session(bind=db_connection, join_transaction_mode="create_savepoint") # Monkey patch the package's global `session` object, diff --git a/tests/console/test_gridify.py b/tests/console/test_gridify.py index 13bfba1..75b3d69 100644 --- a/tests/console/test_gridify.py +++ b/tests/console/test_gridify.py @@ -24,15 +24,12 @@ def test_two_pixels_with_two_addresses( `tests.db.test_grids.test_two_pixels_with_two_addresses`. The difference is that the result is written to the database. """ - # Create two `Address` objects in distinct `Pixel`s. - # One `Address` in the lower-left `Pixel`, ... + # Two `Address`es in distinct `Pixel`s: one in the lower-left `Pixel`, ... address1 = make_address(latitude=48.8357377, longitude=2.2517412) - # ... and another one in the upper-right one. + # ... and another one in the upper-right one address2 = make_address(latitude=48.8898312, longitude=2.4357622) - # Locate a `Restaurant` at the two `Address`es - # and place one `Order` for each of them - # so that the `Address`es are used as `Order.pickup_address`es + # `Restaurant`s with one `Order` each make the `Address`es pickup addresses restaurant1 = make_restaurant(address=address1) restaurant2 = make_restaurant(address=address2) order1 = make_order(restaurant=restaurant1) diff --git a/tests/db/fake_data/factories/addresses.py b/tests/db/fake_data/factories/addresses.py index 594ea5b..f123d04 100644 --- a/tests/db/fake_data/factories/addresses.py +++ b/tests/db/fake_data/factories/addresses.py @@ -20,10 +20,8 @@ class AddressFactory(alchemy.SQLAlchemyModelFactory): id = factory.Sequence(lambda num: num) created_at = factory.LazyFunction(utils.early_in_the_morning) - # When testing, all addresses are considered primary ones. - # As non-primary addresses have no different behavior - # and the property is only kept from the original dataset for - # completeness sake, that is ok to do. + # Non-primary addresses behave no differently in the tests + # => Treat all addresses as primary ones primary_id = factory.LazyAttribute(lambda obj: obj.id) # Mimic a Google Maps Place ID with just random characters diff --git a/tests/db/fake_data/factories/orders/ad_hoc.py b/tests/db/fake_data/factories/orders/ad_hoc.py index 7d125a1..b2af0a9 100644 --- a/tests/db/fake_data/factories/orders/ad_hoc.py +++ b/tests/db/fake_data/factories/orders/ad_hoc.py @@ -72,8 +72,8 @@ class AdHocOrderFactory(alchemy.SQLAlchemyModelFactory): id = factory.Sequence(lambda num: num) # customer -> set by the `make_order` fixture for better control - # Attributes regarding the specialization of an `Order`: ad-hoc or scheduled. - # Ad-hoc `Order`s are placed between 11.45 and 14.15. + # Attributes regarding the specialization of an `Order`: ad-hoc or scheduled + # Ad-hoc `Order`s are placed between 11.45 and 14.15 placed_at = factory.LazyFunction( lambda: ( dt.datetime(*test_config.DATE, 11, 45) @@ -88,8 +88,8 @@ class AdHocOrderFactory(alchemy.SQLAlchemyModelFactory): lambda obj: obj.placed_at + dt.timedelta(minutes=45), ) - # Attributes regarding the cancellation of an `Order`. - # May be overwritten with the `cancel_before_pickup` or `cancel_after_pickup` flags. + # Attributes regarding the cancellation of an `Order` + # May be overwritten with the `cancel_before_pickup` or `cancel_after_pickup` flags cancelled = False cancelled_at = None cancelled_at_corrected = None diff --git a/tests/db/replay/test_orders.py b/tests/db/replay/test_orders.py index d7c497a..356cc66 100644 --- a/tests/db/replay/test_orders.py +++ b/tests/db/replay/test_orders.py @@ -298,13 +298,11 @@ class TestConstraints: Scheduled orders must be at least 30 minutes into the future. """ - # Create an ad-hoc order first and then make that a scheduled order. - # This way, it is less work to keep the timestamps consistent. + # Turning an ad-hoc order into a scheduled one keeps the timestamps consistent replay_pre_order = make_replay_order(scheduled=False) - # Make the `scheduled_delivery_at` the quarter of an hour - # following the next quarter of an hour (i.e., the timestamp - # is between 15 and 30 minutes into the future) + # Schedule the delivery at the quarter of an hour after the next one + # => It is 15 to 30 minutes into the future replay_pre_order.ad_hoc = False replay_pre_order.actual.ad_hoc = False minutes_to_next_quarter = 15 - (replay_pre_order.placed_at.minute % 15) diff --git a/tests/db/test_addresses_addresses.py b/tests/db/test_addresses_addresses.py index 313f669..81e774a 100644 --- a/tests/db/test_addresses_addresses.py +++ b/tests/db/test_addresses_addresses.py @@ -383,9 +383,8 @@ class TestSyncWithGoogleMaps: "copyrights": "Map data ©2021", "legs": [ { - # We choose an artificially high distance of `9999` - # so that the synced bicycle distance is longer - # than the randomized air distance (i.e., fake data) for sure + # An artificially high distance of `9999` ensures + # that the synced bicycle distance exceeds the fake air distance "distance": {"text": "3.0 km", "value": 9999}, "duration": {"text": "10 mins", "value": 596}, "end_address": "13 Place Paul et Jean Paul Avisseau, ...", diff --git a/tests/db/test_grids.py b/tests/db/test_grids.py index b5cd4cb..9ff73fd 100644 --- a/tests/db/test_grids.py +++ b/tests/db/test_grids.py @@ -115,8 +115,8 @@ class TestGridification: """ addresses_mock.return_value = [] - # The chosen `side_length` would result in one `Pixel` if there were orders. - # `+1` as otherwise there would be a second pixel in one direction. + # One `Pixel` would cover the whole `city` if there were orders + # => `+1` as otherwise there would be a second one in one direction side_length = max(city.total_x, city.total_y) + 1 result = db.Grid.gridify(city=city, side_length=side_length) @@ -203,7 +203,7 @@ class TestGridification: addresses_mock.return_value = [ # One `Address` in the lower-left `Pixel`, ... make_address(latitude=48.8357377, longitude=2.2517412), - # ... and another one in the upper-right one. + # ... and another one in the upper-right one make_address(latitude=48.8898312, longitude=2.4357622), ] diff --git a/tests/db/test_orders.py b/tests/db/test_orders.py index b62d57a..b5bd5c2 100644 --- a/tests/db/test_orders.py +++ b/tests/db/test_orders.py @@ -100,11 +100,8 @@ class TestConstraints: with pytest.raises(sa_exc.IntegrityError, match="fk_orders_to_restaurants"): db_session.commit() - # Here should be a test to check deletion of a referenced pickup address, - # so `test_delete_a_referenced_pickup_address(self, db_session, order)`. - # The corresponding "fk_orders_to_addresses_on_pickup_address_id" constraint - # is very hard to test in isolation as the above "fk_orders_to_restaurants_..." - # constraint ensures its integrity already. + # No test for "fk_orders_to_addresses_on_pickup_address_id" as the + # "fk_orders_to_restaurants_..." constraint already ensures its integrity def test_delete_a_referenced_delivery_address(self, db_session, order): """Remove a record that is referenced with a FK.""" @@ -289,13 +286,11 @@ class TestConstraints: Scheduled orders must be at least 30 minutes into the future. """ - # Create an ad-hoc order first and then make that a scheduled order. - # This way, it is less work to keep the timestamps consistent. + # Turning an ad-hoc order into a scheduled one keeps the timestamps consistent pre_order = make_order(scheduled=False) - # Make the `scheduled_delivery_at` the quarter of an hour - # following the next quarter of an hour (i.e., the timestamp - # is between 15 and 30 minutes into the future) + # Schedule the delivery at the quarter of an hour after the next one + # => It is 15 to 30 minutes into the future pre_order.ad_hoc = False minutes_to_next_quarter = 15 - (pre_order.placed_at.minute % 15) pre_order.scheduled_delivery_at = ( @@ -1187,8 +1182,8 @@ def test_make_random_orders( else: cancel_before_pickup, cancel_after_pickup = False, False - # Write all the generated objects to the database. - # This should already trigger an `IntegrityError` if the data are flawed. + # Writing all generated objects to the database checks their integrity + # => An `IntegrityError` here means the fake data are flawed order = make_order( scheduled=scheduled, restaurant=restaurant, diff --git a/tests/forecasts/conftest.py b/tests/forecasts/conftest.py index e11492d..79c0136 100644 --- a/tests/forecasts/conftest.py +++ b/tests/forecasts/conftest.py @@ -27,8 +27,7 @@ def horizontal_datetime_index(): index = pd.Index(gen) index.name = "start_at" - # Sanity check. - # `+1` as both the `START` and `END` day are included. + # `n_days` includes both the `START` and `END` day => `+1` n_days = (test_config.END - test_config.START).days + 1 assert len(index) == n_days @@ -63,8 +62,7 @@ def vertical_datetime_index(): index = pd.Index(gen) index.name = "start_at" - # Sanity check: n_days * n_number_of_opening_hours. - # `+1` as both the `START` and `END` day are included. + # `n_days` includes both the `START` and `END` day => `+1` n_days = (test_config.END - test_config.START).days + 1 assert len(index) == n_days * 12 @@ -122,8 +120,7 @@ def order_totals(good_pixel_id): df = pd.DataFrame(data={"n_orders": 1}, index=index) - # Sanity check: n_pixels * n_time_steps_per_day * n_days. - # `+1` as both the `START` and `END` day are included. + # `n_days` includes both the `START` and `END` day => `+1` n_days = (test_config.END - test_config.START).days + 1 assert len(df) == 2 * 12 * n_days diff --git a/tests/forecasts/timify/test_aggregate_orders.py b/tests/forecasts/timify/test_aggregate_orders.py index 42a56eb..9b17a99 100644 --- a/tests/forecasts/timify/test_aggregate_orders.py +++ b/tests/forecasts/timify/test_aggregate_orders.py @@ -125,8 +125,7 @@ class TestAggregateOrders: result = oh.aggregate_orders() - # Even though there are only 10 orders, there are 12 rows in the `DataFrame`. - # That is so as `0`s are filled in for hours without any demand at the end. + # `0`s fill the hours without demand at the end => 12 rows from 10 orders assert len(result) == 12 assert result["n_orders"].min() == 0 assert result["n_orders"].max() == 1 @@ -241,8 +240,7 @@ class TestAggregateOrders: result = oh.aggregate_orders() - # The resulting `DataFrame` has 24 rows for the 24 30-minute time steps. - # The rows' values are `0` and `1` alternating. + # 24 rows for the 24 30-minute time steps, alternating between `0` and `1` assert len(result) == 24 assert result["n_orders"].min() == 0 assert result["n_orders"].max() == 1 @@ -314,7 +312,7 @@ class TestAggregateOrders: """A persisted `Grid` with two `Pixel` objects.""" # One `Address` in the lower-left `Pixel`, ... address1 = make_address(latitude=48.8357377, longitude=2.2517412) - # ... and another one in the upper-right one. + # ... and another one in the upper-right one address2 = make_address(latitude=48.8898312, longitude=2.4357622) addresses_mock.return_value = [address1, address2] diff --git a/tests/forecasts/timify/test_avg_daily_demand.py b/tests/forecasts/timify/test_avg_daily_demand.py index 669dd23..2ed131c 100644 --- a/tests/forecasts/timify/test_avg_daily_demand.py +++ b/tests/forecasts/timify/test_avg_daily_demand.py @@ -104,7 +104,7 @@ class TestChooseTacticalModel: data = order_history._data data.loc[:, "n_orders"] = 1 - # ... and we set three additional time steps per day to `0`. + # ... and we set three additional time steps per day to `0` data.loc[ # all `Pixel`s, all `Order`s in time steps starting at 11 am (slice(None), slice(data.index.levels[1][0], None, 12)), From 51f68743e537a9ffa744f47e65313485b0ecd3c5 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 11:01:12 +0100 Subject: [PATCH 10/19] Reword the comments in the config files Each comment is one sentence or two short ones joined by "=>", without a final period. --- .forgejo/actions/setup/action.yaml | 3 +-- noxfile.py | 11 ++++------- pyproject.toml | 15 ++++++--------- 3 files changed, 11 insertions(+), 18 deletions(-) diff --git a/.forgejo/actions/setup/action.yaml b/.forgejo/actions/setup/action.yaml index ab6de4b..6d800f3 100644 --- a/.forgejo/actions/setup/action.yaml +++ b/.forgejo/actions/setup/action.yaml @@ -17,8 +17,7 @@ runs: r-cran-zoo \ -y - # Built wheels (e.g., `rpy2`) and Python versions - # => A new key whenever the pinned dependencies or Python versions change + # Built wheels (e.g., `rpy2`) and Python versions, keyed by their pins # => Only the "lint" job in ci.yaml saves the cache - name: Restore the `uv` cache id: uv-cache diff --git a/noxfile.py b/noxfile.py index aaf1485..cd577df 100644 --- a/noxfile.py +++ b/noxfile.py @@ -299,9 +299,8 @@ def test_code(session: nox.Session) -> None: session.run("pytest", "--version") pytest_default_args = ( - # See "[tool.coverage]" in pyproject.toml for `coverage` settings, - # for example, branch coverage and report format, - # and "[tool.coverage.paths]" mapping `coverage` to src/ + # See "[tool.coverage]" in pyproject.toml for the branch coverage, + # the report format, and the mapping to src/ "--cov", "--no-cov-on-fail", "--cov-fail-under=100", @@ -478,10 +477,8 @@ def lock_dependencies(session: nox.Session) -> None: """ do_not_accept_arguments(session) - # Little hack: Create a flag in the env(ironment) - # and call `upgrade_dependencies()` directly - # because `session.notify()` starts sessions with a new - # `nox.Session` object that does not have the flag set + # `session.notify()` would start a new `nox.Session` without the flag + # => Set the flag in the env(ironment) and call `upgrade_dependencies()` directly session.env["_lock_only"] = "true" upgrade_dependencies(session) diff --git a/pyproject.toml b/pyproject.toml index 488e76c..47fd84b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,9 +26,8 @@ license = "MIT" readme = "README.md" classifiers = [ - # All `SUPPORTED_PYTHONS` listed here are automatically - # loaded by `nox`, our task runner, and made available - # for testing in isolated environments + # `nox` loads all `SUPPORTED_PYTHONS` listed here + # => The test suite runs with each of them in isolated environments "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", "Programming Language :: Python :: 3.15", @@ -318,8 +317,7 @@ select = [ # "UP", ] -# By default, flake8 ignores some errors. -# Instead, do not ignore anything. +# flake8 ignores some errors by default => Ignore nothing ignore = [] # If --ignore is passed on the command @@ -331,7 +329,7 @@ extend-ignore = [ "B950", # PEP 257 documents the arguments of `__init__()` in its own docstring "DOC301", - # Comply with black's style. + # Comply with black's style # Source: https://github.com/psf/black/blob/master/docs/compatible_configs.md#flake8 "E203", "W503", # `ruff`'s FBT003 does this better, as it allows builtins like `setattr()` @@ -365,12 +363,11 @@ per-file-ignores = [ "tests/*.py:ANN0,ANN2,D106,DOC106,DOC107,S101,S311", ] -# Explicitly set mccabe's maximum complexity to 10 as recommended by -# Thomas McCabe, the inventor of the McCabe complexity, and the NIST. +# 10 as recommended by Thomas McCabe, the metric's inventor, and the NIST # Source: https://en.wikipedia.org/wiki/Cyclomatic_complexity#Limiting_complexity_during_development max-complexity = 10 -# Comply with black's style. +# Comply with black's style # Source: https://github.com/psf/black/blob/master/docs/the_black_code_style.md#line-length max-line-length = 88 From f90f263dab12013cc1353381e6ee3258df5e9176 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 11:06:36 +0100 Subject: [PATCH 11/19] Explain the "why" in a few more comments Comments that only repeated the code are removed. --- src/velofy/db/grids.py | 1 - src/velofy/forecasts/models/base.py | 1 - src/velofy/forecasts/timify.py | 4 ++-- tests/db/fake_data/fixture_makers.py | 12 ++++++------ 4 files changed, 8 insertions(+), 10 deletions(-) diff --git a/src/velofy/db/grids.py b/src/velofy/db/grids.py index 7356deb..3421172 100644 --- a/src/velofy/db/grids.py +++ b/src/velofy/db/grids.py @@ -123,7 +123,6 @@ class Grid(meta.Base): pixel = pixels[(n_x, n_y)] - # Create an association between the `address` and `pixel` assoc = db.AddressPixelAssociation(address=address, pixel=pixel) pixel.addresses.append(assoc) diff --git a/src/velofy/forecasts/models/base.py b/src/velofy/forecasts/models/base.py index 8a6e14b..b4ea0f7 100644 --- a/src/velofy/forecasts/models/base.py +++ b/src/velofy/forecasts/models/base.py @@ -96,7 +96,6 @@ class ForecastingModelABC(abc.ABC): # vertical ones all time steps of the day predictions = self.predict(pixel, predict_at, train_horizon) - # Convert the `predictions` into a `list` of `Forecast` objects forecasts = db.Forecast.from_dataframe( pixel=pixel, time_step=self._order_history.time_step, diff --git a/src/velofy/forecasts/timify.py b/src/velofy/forecasts/timify.py index 09727b2..5d8851b 100644 --- a/src/velofy/forecasts/timify.py +++ b/src/velofy/forecasts/timify.py @@ -205,7 +205,7 @@ class OrderHistory: msg = "no orders in the pixel" raise RuntimeError(msg) - # Return a proper `datetime.datetime` object + # A plain `dt.datetime` instead of a `pd.Timestamp` return dt.datetime( first_order.year, first_order.month, @@ -240,7 +240,7 @@ class OrderHistory: msg = "no orders in the pixel" raise RuntimeError(msg) - # Return a proper `datetime.datetime` object + # A plain `dt.datetime` instead of a `pd.Timestamp` return dt.datetime( last_order.year, last_order.month, diff --git a/tests/db/fake_data/fixture_makers.py b/tests/db/fake_data/fixture_makers.py index dede148..268dc5f 100644 --- a/tests/db/fake_data/fixture_makers.py +++ b/tests/db/fake_data/fixture_makers.py @@ -8,7 +8,7 @@ from tests.db.fake_data import factories @pytest.fixture def make_address(city): """Replaces `AddressFactory.build()`: Create an `Address` in the `city`.""" - # Reset the identifiers before every test + # Identifiers start at 1 in every test, independent of the test order factories.AddressFactory.reset_sequence(1) def func(**kwargs): @@ -25,7 +25,7 @@ def make_address(city): @pytest.fixture def make_courier(): """Replaces `CourierFactory.build()`: Create a `Courier`.""" - # Reset the identifiers before every test + # Identifiers start at 1 in every test, independent of the test order factories.CourierFactory.reset_sequence(1) def func(**kwargs): @@ -38,7 +38,7 @@ def make_courier(): @pytest.fixture def make_customer(): """Replaces `CustomerFactory.build()`: Create a `Customer`.""" - # Reset the identifiers before every test + # Identifiers start at 1 in every test, independent of the test order factories.CustomerFactory.reset_sequence(1) def func(**kwargs): @@ -51,7 +51,7 @@ def make_customer(): @pytest.fixture def make_restaurant(make_address): """Replaces `RestaurantFactory.build()`: Create a `Restaurant`.""" - # Reset the identifiers before every test + # Identifiers start at 1 in every test, independent of the test order factories.RestaurantFactory.reset_sequence(1) def func(address=None, **kwargs): @@ -74,7 +74,7 @@ def make_restaurant(make_address): @pytest.fixture def make_order(make_address, make_courier, make_customer, make_restaurant): """Replaces `OrderFactory.build()`: Create a `Order`.""" - # Reset the identifiers before every test + # Identifiers start at 1 in every test, independent of the test order factories.AdHocOrderFactory.reset_sequence(1) def func(*, scheduled=False, restaurant=None, courier=None, **kwargs): @@ -119,7 +119,7 @@ def make_order(make_address, make_courier, make_customer, make_restaurant): @pytest.fixture def make_replay_order(make_order, simulation): """Replaces `ReplayedOrderFactory.build()`: Create a `ReplayedOrder`.""" - # Reset the identifiers before every test + # Identifiers start at 1 in every test, independent of the test order factories.ReplayedOrderFactory.reset_sequence(1) def func(*, scheduled=False, order=None, **kwargs): From c18fc2ba59ed9286336da113604a98f423cbc32f Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 11:09:38 +0100 Subject: [PATCH 12/19] Refer to sources with "See:" in comments --- pyproject.toml | 30 ++++++++++++++-------------- src/velofy/db/addresses_addresses.py | 2 +- src/velofy/init_r.py | 2 +- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 47fd84b..791833d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -150,7 +150,7 @@ verify-db = [ [tool.autoflake] -# Source: https://github.com/PyCQA/autoflake#configuration +# See: https://github.com/PyCQA/autoflake#configuration in-place = true recursive = true @@ -171,7 +171,7 @@ line-length = 88 [tool.coverage] -# Source: https://coverage.readthedocs.io/en/latest/config.html +# See: https://coverage.readthedocs.io/en/latest/config.html [tool.coverage.paths] @@ -201,7 +201,7 @@ source = ["velofy"] [tool.flake8] -# Source: https://flake8.pycqa.org/en/latest/user/configuration.html +# See: https://flake8.pycqa.org/en/latest/user/configuration.html # Include error classes only explicitly # to avoid forward compatibility issues @@ -330,7 +330,7 @@ extend-ignore = [ # PEP 257 documents the arguments of `__init__()` in its own docstring "DOC301", # Comply with black's style - # Source: https://github.com/psf/black/blob/master/docs/compatible_configs.md#flake8 + # See: https://github.com/psf/black/blob/master/docs/compatible_configs.md#flake8 "E203", "W503", # `ruff`'s FBT003 does this better, as it allows builtins like `setattr()` "FBT003", @@ -364,11 +364,11 @@ per-file-ignores = [ ] # 10 as recommended by Thomas McCabe, the metric's inventor, and the NIST -# Source: https://en.wikipedia.org/wiki/Cyclomatic_complexity#Limiting_complexity_during_development +# See: https://en.wikipedia.org/wiki/Cyclomatic_complexity#Limiting_complexity_during_development max-complexity = 10 # Comply with black's style -# Source: https://github.com/psf/black/blob/master/docs/the_black_code_style.md#line-length +# See: https://github.com/psf/black/blob/master/docs/the_black_code_style.md#line-length max-line-length = 88 # Preview the code lines that cause errors @@ -382,7 +382,7 @@ check-yield-types = false # flake8-docstrings docstring-convention = "google" # flake8-quotes -# Source: https://github.com/zheller/flake8-quotes#configuration +# See: https://github.com/zheller/flake8-quotes#configuration avoid-escape = true docstring-quotes = "double" inline-quotes = "double" @@ -404,7 +404,7 @@ pytest-parametrize-values-type = "list" [tool.isort] -# Source: https://pycqa.github.io/isort/docs/configuration/options.html +# See: https://pycqa.github.io/isort/docs/configuration/options.html atomic = true case_sensitive = false # Implied by "force_alphabetical_sort_within_sections" @@ -414,7 +414,7 @@ lines_after_imports = 2 remove_redundant_aliases = true # Comply with black's style -# Source: https://github.com/psf/black/blob/master/docs/compatible_configs.md#isort +# See: https://github.com/psf/black/blob/master/docs/compatible_configs.md#isort ensure_newline_before_comments = true force_grid_wrap = 0 include_trailing_comma = true @@ -424,13 +424,13 @@ use_parentheses = true # Comply with Google's Python Style Guide # => All imports go on a single line -# Source: https://google.github.io/styleguide/pyguide.html#313-imports-formatting +# See: https://google.github.io/styleguide/pyguide.html#313-imports-formatting force_single_line = true [tool.mypy] -# Source: https://mypy.readthedocs.io/en/stable/config_file.html +# See: https://mypy.readthedocs.io/en/stable/config_file.html cache_dir = ".cache/mypy" @@ -524,7 +524,7 @@ ignore_missing_imports = true [tool.pyright] -# Source: https://microsoft.github.io/pyright/#/configuration +# See: https://microsoft.github.io/pyright/#/configuration # Check against the oldest supported Python version, not the one running `pyright` pythonVersion = "3.13" @@ -535,7 +535,7 @@ useLibraryCodeForTypes = false [tool.pytest.ini_options] -# Source: https://docs.pytest.org/en/stable/reference/reference.html#ini-options-ref +# See: https://docs.pytest.org/en/stable/reference/reference.html#ini-options-ref cache_dir = ".cache/pytest" @@ -571,7 +571,7 @@ markers = [ [tool.ruff] -# Source: https://docs.astral.sh/ruff/ +# See: https://docs.astral.sh/ruff/ cache-dir = ".cache/ruff" @@ -807,7 +807,7 @@ convention = "google" [tool.uv] -# Source: https://docs.astral.sh/uv/reference/settings/ +# See: https://docs.astral.sh/uv/reference/settings/ required-version = ">=0.13.10,<0.14.0" # Same range as "uv_build" above diff --git a/src/velofy/db/addresses_addresses.py b/src/velofy/db/addresses_addresses.py index 9fff47e..73b5da1 100644 --- a/src/velofy/db/addresses_addresses.py +++ b/src/velofy/db/addresses_addresses.py @@ -225,7 +225,7 @@ class Path(meta.Base): ) # Without "alternatives" and "waypoints", # the `response` has exactly one "route" with exactly one "leg" - # Source: https://developers.google.com/maps/documentation/directions/get-directions#Legs # noqa:E501 + # See: https://developers.google.com/maps/documentation/directions/get-directions#Legs # noqa:E501 route = response[0]["legs"][0] self.bicycle_distance = route["distance"]["value"] diff --git a/src/velofy/init_r.py b/src/velofy/init_r.py index cd62426..c8d251f 100644 --- a/src/velofy/init_r.py +++ b/src/velofy/init_r.py @@ -12,7 +12,7 @@ from rpy2.robjects import packages as r_packages # R's console messages would clutter the output => Suppress them -# Source: https://stackoverflow.com/a/63220287 +# See: https://stackoverflow.com/a/63220287 r_callbacks.consolewrite_print = lambda *_args, **_kwargs: None # pragma: no cover r_callbacks.consolewrite_warnerror = lambda *_args, **_kwargs: None # pragma: no cover From 50889df24115e31ca466afcb7a3857a2cec5c68c Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 11:15:36 +0100 Subject: [PATCH 13/19] Skip the comment-only commits in `git blame` --- .git-blame-ignore-revs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 4967ce6..780741f 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -57,3 +57,33 @@ cf2534f41e9e535b8f68a38bb3e0ebadf3fb19b3 # Capitalize the explanations after "=>" 0090145b654c098cc464aed757e6c1fdda7487bd + +# Remove periods from one-sentence comments +049a5f6f62e05f08ffdcb6ce90c1f07ec3042871 + +# Break multi-line comments before conjunctions +2f1afd459fe73c2ab4136acaa1f87ecf64212e9f + +# Put identifiers in comments into backticks +ff7f705bc831734bbab63a43fd78a11121696bc5 + +# Reword the comments in `velofy.db` +1413d08ed9115501fa2757b97de23525581d9acf + +# Reword the comments in `velofy.forecasts` +9b8fe8b8fd41e920954ce4cda5b2fd5e70b44185 + +# Reword the comments in the rest of `velofy` +0f6970922623a7bda82b78bb48d5fb05646e7d45 + +# Reword the comments in the test suite +bca4250b4d9512dde4f67996f21f4c4bc9c18387 + +# Reword the comments in the config files +51f68743e537a9ffa744f47e65313485b0ecd3c5 + +# Explain the "why" in a few more comments +f90f263dab12013cc1353381e6ee3258df5e9176 + +# Refer to sources with "See:" in comments +c18fc2ba59ed9286336da113604a98f423cbc32f From 9c409b619edb8539014908636c05e16c6908f214 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 11:26:45 +0100 Subject: [PATCH 14/19] Apply the safe `ruff` fixes The fixes keep every value the same, so the stored outputs stay valid. For example, `np.NaN` becomes `np.nan`, which `numpy` v2 requires. --- research/01_clean_data.ipynb | 35 ++++++++++--------- research/03_grid_visualizations.ipynb | 3 +- .../07_visualizing_demand_forecasting.ipynb | 8 +++-- research/08_google_maps.ipynb | 3 +- 4 files changed, 28 insertions(+), 21 deletions(-) diff --git a/research/01_clean_data.ipynb b/research/01_clean_data.ipynb index 3ea3bd3..7d3e2c2 100644 --- a/research/01_clean_data.ipynb +++ b/research/01_clean_data.ipynb @@ -52,7 +52,8 @@ "metadata": {}, "outputs": [], "source": [ - "from velofy import config, db" + "from velofy import config\n", + "from velofy import db" ] }, { @@ -65,9 +66,9 @@ "import datetime\n", "import hashlib\n", "\n", + "import numpy as np\n", "import pandas as pd\n", "import pytz as tz\n", - "import numpy as np\n", "import sqlalchemy as sa" ] }, @@ -1118,16 +1119,16 @@ " addresses[\"zip\"].notnull()\n", " & ~invalid\n", " & ~(\n", - " (33000 <= addresses[\"zip\"]) & (addresses[\"zip\"] < 34000)\n", - " | (69000 <= addresses[\"zip\"]) & (addresses[\"zip\"] < 70000)\n", - " | (75000 <= addresses[\"zip\"]) & (addresses[\"zip\"] < 76000)\n", - " | (92000 <= addresses[\"zip\"]) & (addresses[\"zip\"] < 95000)\n", + " (addresses[\"zip\"] >= 33000) & (addresses[\"zip\"] < 34000)\n", + " | (addresses[\"zip\"] >= 69000) & (addresses[\"zip\"] < 70000)\n", + " | (addresses[\"zip\"] >= 75000) & (addresses[\"zip\"] < 76000)\n", + " | (addresses[\"zip\"] >= 92000) & (addresses[\"zip\"] < 95000)\n", " )\n", ")\n", "\n", "assert not_in_target_cities.sum() == 10\n", "\n", - "addresses.loc[invalid | not_in_target_cities, \"zip\"] = np.NaN" + "addresses.loc[invalid | not_in_target_cities, \"zip\"] = np.nan" ] }, { @@ -1215,7 +1216,7 @@ "source": [ "addresses[\"street\"] = (\n", " addresses[\"street\"]\n", - " .str.replace(\"\\s+\", \" \", regex=True)\n", + " .str.replace(r\"\\s+\", \" \", regex=True)\n", " .str.replace(\"'\", \"'\")\n", " # Get rid off accents.\n", " .str.normalize(\"NFKD\")\n", @@ -1319,7 +1320,7 @@ " .str.replace(\"n°\", \"\")\n", " .str.replace(\"#\", \"\")\n", " .str.replace(\"face l'assanceur\", \"\")\n", - " .str.replace(\"\\(drt\\)\", \"\")\n", + " .str.replace(r\"\\(drt\\)\", \"\")\n", " .str.replace(\"floor\", \"\")\n", " .str.replace(\"et demi\", \"\")\n", " .str.replace(\"et droite\", \"\")\n", @@ -1336,7 +1337,7 @@ " .str.replace(\"code\", \"\")\n", " .str.replace(\"perez\", \"\")\n", " .str.replace(\"-\", \"\")\n", - " .str.replace(\"\\s+\", \" \", regex=True)\n", + " .str.replace(r\"\\s+\", \" \", regex=True)\n", " .str.strip()\n", " # Abbreviations.\n", " .str.replace(\n", @@ -1405,7 +1406,7 @@ " .str.replace(\"n°\", \"\")\n", " .str.replace(\"#\", \"\")\n", " .str.replace(\"face l'assanceur\", \"\")\n", - " .str.replace(\"\\(drt\\)\", \"\")\n", + " .str.replace(r\"\\(drt\\)\", \"\")\n", " .str.replace(\"floor\", \"\")\n", " .str.replace(\"et demi\", \"\")\n", " .str.replace(\"et droite\", \"\")\n", @@ -1422,7 +1423,7 @@ " .str.replace(\"code\", \"\")\n", " .str.replace(\"perez\", \"\")\n", " .str.replace(\"-\", \"\")\n", - " .str.replace(\"\\s+\", \" \", regex=True)\n", + " .str.replace(r\"\\s+\", \" \", regex=True)\n", " .str.strip()\n", " # Abbreviations.\n", " .str.replace(\n", @@ -1672,7 +1673,7 @@ "metadata": {}, "outputs": [], "source": [ - "address_merger = collections.defaultdict(lambda: np.NaN)\n", + "address_merger = collections.defaultdict(lambda: np.nan)\n", "address_merger.update(\n", " {\n", " id_: merged_on_id\n", @@ -2371,7 +2372,7 @@ "source": [ "restaurants[\"name\"] = (\n", " restaurants[\"name\"]\n", - " .str.replace(\"\\s+\", \" \", regex=True)\n", + " .str.replace(r\"\\s+\", \" \", regex=True)\n", " .str.replace(\"'\", \"'\")\n", " # Get rid off accents.\n", " .str.normalize(\"NFKD\")\n", @@ -2483,7 +2484,7 @@ "metadata": {}, "outputs": [], "source": [ - "restaurants_merger = collections.defaultdict(lambda: np.NaN)\n", + "restaurants_merger = collections.defaultdict(lambda: np.nan)\n", "restaurants_merger.update(\n", " {\n", " id_: merged_on_id\n", @@ -2990,7 +2991,7 @@ "metadata": {}, "outputs": [], "source": [ - "couriers_merger = collections.defaultdict(lambda: np.NaN)\n", + "couriers_merger = collections.defaultdict(lambda: np.nan)\n", "couriers_merger.update(\n", " {\n", " id_: merged_on_id\n", @@ -4441,7 +4442,7 @@ "orders[\"pickup_address_id\"] = orders[\"pickup_address_id\"].map(address_merger)\n", "orders[\"delivery_address_id\"] = orders[\"delivery_address_id\"].map(address_merger)\n", "msk = orders[\"pickup_address_id\"].isnull() | orders[\"delivery_address_id\"].isnull()\n", - "orders = orders[~msk].astype({\"pickup_address_id\": int, \"delivery_address_id\": int,})\n", + "orders = orders[~msk].astype({\"pickup_address_id\": int, \"delivery_address_id\": int})\n", "\n", "assert msk.sum() == 160" ] diff --git a/research/03_grid_visualizations.ipynb b/research/03_grid_visualizations.ipynb index 7ca9f10..6215383 100644 --- a/research/03_grid_visualizations.ipynb +++ b/research/03_grid_visualizations.ipynb @@ -46,7 +46,8 @@ "metadata": {}, "outputs": [], "source": [ - "from velofy import config, db" + "from velofy import config\n", + "from velofy import db" ] }, { diff --git a/research/07_visualizing_demand_forecasting.ipynb b/research/07_visualizing_demand_forecasting.ipynb index fd70deb..11e114b 100644 --- a/research/07_visualizing_demand_forecasting.ipynb +++ b/research/07_visualizing_demand_forecasting.ipynb @@ -45,6 +45,7 @@ "outputs": [], "source": [ "import datetime as dt\n", + "\n", "import matplotlib\n", "import matplotlib.pyplot as plt" ] @@ -55,8 +56,11 @@ "metadata": {}, "outputs": [], "source": [ - "from velofy import config, db\n", - "from velofy.forecasts import methods, models, timify\n", + "from velofy import config\n", + "from velofy import db\n", + "from velofy.forecasts import methods\n", + "from velofy.forecasts import models\n", + "from velofy.forecasts import timify\n", "from velofy.forecasts.methods import decomposition" ] }, diff --git a/research/08_google_maps.ipynb b/research/08_google_maps.ipynb index 334215b..56ba6dd 100644 --- a/research/08_google_maps.ipynb +++ b/research/08_google_maps.ipynb @@ -51,7 +51,8 @@ "source": [ "import googlemaps as gm\n", "\n", - "from velofy import config, db" + "from velofy import config\n", + "from velofy import db" ] }, { From f9643642b8ff9f19704698b23bb192a86a1a7d1d Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 11:28:12 +0100 Subject: [PATCH 15/19] Use `isna()` and `notna()` `isnull()` and `notnull()` are mere aliases, so the stored outputs stay valid. --- research/01_clean_data.ipynb | 200 +++++++++++++++++------------------ 1 file changed, 100 insertions(+), 100 deletions(-) diff --git a/research/01_clean_data.ipynb b/research/01_clean_data.ipynb index 7d3e2c2..38924ce 100644 --- a/research/01_clean_data.ipynb +++ b/research/01_clean_data.ipynb @@ -916,7 +916,7 @@ "metadata": {}, "outputs": [], "source": [ - "msk = addresses[\"place_id\"].isnull() | (addresses[\"place_id\"] == \"\")\n", + "msk = addresses[\"place_id\"].isna() | (addresses[\"place_id\"] == \"\")\n", "addresses = addresses[~msk]\n", "\n", "assert msk.sum() == 139" @@ -1111,12 +1111,12 @@ "metadata": {}, "outputs": [], "source": [ - "invalid = addresses[\"zip\"].notnull() & (addresses[\"zip\"] < 10000)\n", + "invalid = addresses[\"zip\"].notna() & (addresses[\"zip\"] < 10000)\n", "\n", "assert invalid.sum() == 9\n", "\n", "not_in_target_cities = (\n", - " addresses[\"zip\"].notnull()\n", + " addresses[\"zip\"].notna()\n", " & ~invalid\n", " & ~(\n", " (addresses[\"zip\"] >= 33000) & (addresses[\"zip\"] < 34000)\n", @@ -1179,7 +1179,7 @@ "metadata": {}, "outputs": [], "source": [ - "msk = addresses[\"zip\"].isnull()\n", + "msk = addresses[\"zip\"].isna()\n", "addresses = addresses[~msk]\n", "\n", "assert msk.sum() == 21" @@ -1241,7 +1241,7 @@ "metadata": {}, "outputs": [], "source": [ - "assert not addresses[\"street\"].isnull().any()" + "assert not addresses[\"street\"].isna().any()" ] }, { @@ -1473,7 +1473,7 @@ "metadata": {}, "outputs": [], "source": [ - "msk = addresses[\"floor\"].isnull() & addresses[\"special_instructions\"].notnull()\n", + "msk = addresses[\"floor\"].isna() & addresses[\"special_instructions\"].notna()\n", "addresses.loc[msk, \"floor\"] = addresses.loc[msk, \"special_instructions\"].values" ] }, @@ -1508,7 +1508,7 @@ "metadata": {}, "outputs": [], "source": [ - "addresses.loc[addresses[\"floor\"].notnull() & (addresses[\"floor\"] > 40), \"floor\"] = pd.NA" + "addresses.loc[addresses[\"floor\"].notna() & (addresses[\"floor\"] > 40), \"floor\"] = pd.NA" ] }, { @@ -1524,7 +1524,7 @@ "metadata": {}, "outputs": [], "source": [ - "assert len(addresses.loc[addresses[\"floor\"].isnull(), \"floor\"]) == 307_973" + "assert len(addresses.loc[addresses[\"floor\"].isna(), \"floor\"]) == 307_973" ] }, { @@ -2416,7 +2416,7 @@ "metadata": {}, "outputs": [], "source": [ - "assert not restaurants[\"address_id\"].isnull().any()" + "assert not restaurants[\"address_id\"].isna().any()" ] }, { @@ -4441,7 +4441,7 @@ "source": [ "orders[\"pickup_address_id\"] = orders[\"pickup_address_id\"].map(address_merger)\n", "orders[\"delivery_address_id\"] = orders[\"delivery_address_id\"].map(address_merger)\n", - "msk = orders[\"pickup_address_id\"].isnull() | orders[\"delivery_address_id\"].isnull()\n", + "msk = orders[\"pickup_address_id\"].isna() | orders[\"delivery_address_id\"].isna()\n", "orders = orders[~msk].astype({\"pickup_address_id\": int, \"delivery_address_id\": int})\n", "\n", "assert msk.sum() == 160" @@ -4469,7 +4469,7 @@ "metadata": {}, "outputs": [], "source": [ - "assert not orders[\"restaurant_id\"].isnull().any()" + "assert not orders[\"restaurant_id\"].isna().any()" ] }, { @@ -4502,7 +4502,7 @@ "outputs": [], "source": [ "assert set(couriers.index) == set(\n", - " orders.loc[orders[\"courier_id\"].notnull(), \"courier_id\"].unique()\n", + " orders.loc[orders[\"courier_id\"].notna(), \"courier_id\"].unique()\n", ")" ] }, @@ -4554,10 +4554,10 @@ "outputs": [], "source": [ "assert not (\n", - " (orders[\"ad_hoc\"] == True) & orders[\"scheduled_delivery_at\"].notnull()\n", + " (orders[\"ad_hoc\"] == True) & orders[\"scheduled_delivery_at\"].notna()\n", ").any()\n", "assert not (\n", - " (orders[\"ad_hoc\"] == False) & orders[\"scheduled_delivery_at\"].isnull()\n", + " (orders[\"ad_hoc\"] == False) & orders[\"scheduled_delivery_at\"].isna()\n", ").any()" ] }, @@ -4588,7 +4588,7 @@ " \"delivery_at\",\n", "]:\n", " orders[column + \"_corrected\"] = False\n", - " orders.loc[orders[column].isnull(), column + \"_corrected\"] = pd.NA" + " orders.loc[orders[column].isna(), column + \"_corrected\"] = pd.NA" ] }, { @@ -5156,7 +5156,7 @@ "source": [ "claimed_to_be_delivered = (orders[\"cancelled\"] == True) & orders[\n", " \"delivery_at\"\n", - "].notnull()\n", + "].notna()\n", "\n", "assert (\n", " orders.loc[claimed_to_be_delivered, \"cancelled_at\"].min()\n", @@ -5198,8 +5198,8 @@ "cancelled = orders[\"cancelled\"] == True\n", "completed = orders[\"cancelled\"] == False\n", "\n", - "assert not orders.loc[cancelled, \"cancelled_at\"].isnull().any()\n", - "assert not orders.loc[completed, \"cancelled_at\"].notnull().any()" + "assert not orders.loc[cancelled, \"cancelled_at\"].isna().any()\n", + "assert not orders.loc[completed, \"cancelled_at\"].notna().any()" ] }, { @@ -5409,9 +5409,9 @@ ], "source": [ "all_data_available = (\n", - " orders[\"logged_confirmed_total_time\"].notnull()\n", - " & orders[\"delivery_at\"].notnull()\n", - " & orders[\"placed_at\"].notnull()\n", + " orders[\"logged_confirmed_total_time\"].notna()\n", + " & orders[\"delivery_at\"].notna()\n", + " & orders[\"placed_at\"].notna()\n", ")\n", "good_data = (\n", " orders[\"logged_confirmed_total_time\"]\n", @@ -5455,9 +5455,9 @@ ], "source": [ "all_data_available = (\n", - " orders[\"logged_accepting_time\"].notnull()\n", - " & orders[\"courier_accepted_at\"].notnull()\n", - " & orders[\"dispatch_at\"].notnull()\n", + " orders[\"logged_accepting_time\"].notna()\n", + " & orders[\"courier_accepted_at\"].notna()\n", + " & orders[\"dispatch_at\"].notna()\n", ")\n", "good_data = (\n", " orders[\"logged_accepting_time\"]\n", @@ -5488,9 +5488,9 @@ "outputs": [], "source": [ "extrapolate = (\n", - " orders[\"dispatch_at\"].isnull()\n", - " & orders[\"courier_accepted_at\"].notnull()\n", - " & orders[\"logged_accepting_time\"].notnull()\n", + " orders[\"dispatch_at\"].isna()\n", + " & orders[\"courier_accepted_at\"].notna()\n", + " & orders[\"logged_accepting_time\"].notna()\n", ")\n", "\n", "accept_time = orders[\"logged_accepting_time\"].map(\n", @@ -5532,9 +5532,9 @@ ], "source": [ "all_data_available = (\n", - " orders[\"logged_reaction_time\"].notnull()\n", - " & orders[\"courier_accepted_at\"].notnull()\n", - " & orders[\"courier_notified_at\"].notnull()\n", + " orders[\"logged_reaction_time\"].notna()\n", + " & orders[\"courier_accepted_at\"].notna()\n", + " & orders[\"courier_notified_at\"].notna()\n", ")\n", "good_data = (\n", " orders[\"logged_reaction_time\"]\n", @@ -5565,9 +5565,9 @@ "outputs": [], "source": [ "extrapolate = (\n", - " orders[\"courier_notified_at\"].isnull()\n", - " & orders[\"courier_accepted_at\"].notnull()\n", - " & orders[\"logged_reaction_time\"].notnull()\n", + " orders[\"courier_notified_at\"].isna()\n", + " & orders[\"courier_accepted_at\"].notna()\n", + " & orders[\"logged_reaction_time\"].notna()\n", ")\n", "extrapolated_courier_notified_at = (\n", " orders[\"courier_accepted_at\"]\n", @@ -5599,9 +5599,9 @@ "outputs": [], "source": [ "assert not (\n", - " orders[\"courier_notified_at\"].notnull()\n", - " & orders[\"courier_accepted_at\"].isnull()\n", - " & orders[\"logged_reaction_time\"].notnull()\n", + " orders[\"courier_notified_at\"].notna()\n", + " & orders[\"courier_accepted_at\"].isna()\n", + " & orders[\"logged_reaction_time\"].notna()\n", ").any()\n", "\n", "del orders[\"logged_reaction_time\"]" @@ -5633,20 +5633,20 @@ ], "source": [ "all_data_available = (\n", - " orders[\"estimated_prep_duration\"].notnull()\n", - " & orders[\"expected_wait_pickup_time\"].notnull()\n", + " orders[\"estimated_prep_duration\"].notna()\n", + " & orders[\"expected_wait_pickup_time\"].notna()\n", ")\n", "good_data = (\n", " orders[\"estimated_prep_duration\"] - orders[\"expected_wait_pickup_time\"]\n", ").abs() <= 5\n", "\n", - "no_duration = orders[\"estimated_prep_duration\"].isnull()\n", + "no_duration = orders[\"estimated_prep_duration\"].isna()\n", "\n", - "assert not (no_duration & orders[\"expected_wait_pickup_time\"].notnull()).any()\n", - "assert (~no_duration & orders[\"expected_wait_pickup_time\"].isnull()).sum() == 19_865\n", + "assert not (no_duration & orders[\"expected_wait_pickup_time\"].notna()).any()\n", + "assert (~no_duration & orders[\"expected_wait_pickup_time\"].isna()).sum() == 19_865\n", "assert not (\n", " (orders[\"placed_at\"].dt.date > datetime.date(2016, 5, 24))\n", - " & orders[\"expected_wait_pickup_time\"].isnull()\n", + " & orders[\"expected_wait_pickup_time\"].isna()\n", " & (orders[\"cancelled\"] == False)\n", ").any()\n", "\n", @@ -5686,9 +5686,9 @@ ], "source": [ "all_data_available = (\n", - " orders[\"estimated_prep_duration\"].notnull()\n", - " & orders[\"restaurant_notified_at\"].notnull()\n", - " & orders[\"scheduled_pickup_at\"].notnull()\n", + " orders[\"estimated_prep_duration\"].notna()\n", + " & orders[\"restaurant_notified_at\"].notna()\n", + " & orders[\"scheduled_pickup_at\"].notna()\n", ")\n", "good_data = (\n", " orders[\"estimated_prep_duration\"]\n", @@ -5758,9 +5758,9 @@ "extrapolated = orders[\"scheduled_pickup_at\"] - duration\n", "\n", "extrapolate = (\n", - " orders[\"restaurant_notified_at\"].isnull()\n", - " & orders[\"scheduled_pickup_at\"].notnull()\n", - " & orders[\"estimated_prep_duration\"].notnull()\n", + " orders[\"restaurant_notified_at\"].isna()\n", + " & orders[\"scheduled_pickup_at\"].notna()\n", + " & orders[\"estimated_prep_duration\"].notna()\n", ")\n", "still_wrong = (\n", " (extrapolated <= orders[\"placed_at\"])\n", @@ -5794,9 +5794,9 @@ "extrapolated = (extrapolated.dt.total_seconds() // 60 * 60).astype(\"Int64\")\n", "\n", "extrapolate = (\n", - " orders[\"restaurant_notified_at\"].notnull()\n", - " & orders[\"scheduled_pickup_at\"].notnull()\n", - " & orders[\"estimated_prep_duration\"].isnull()\n", + " orders[\"restaurant_notified_at\"].notna()\n", + " & orders[\"scheduled_pickup_at\"].notna()\n", + " & orders[\"estimated_prep_duration\"].isna()\n", ")\n", "orders.loc[extrapolate, \"estimated_prep_duration\"] = extrapolated.loc[extrapolate]\n", "orders.loc[extrapolate, \"estimated_prep_duration_corrected\"] = True\n", @@ -5830,7 +5830,7 @@ } ], "source": [ - "more_than_45_mins = orders[\"estimated_prep_duration\"].notnull()\n", + "more_than_45_mins = orders[\"estimated_prep_duration\"].notna()\n", "more_than_45_mins &= orders[\"estimated_prep_duration\"] > 45 * 60\n", "\n", "orders.loc[more_than_45_mins, \"estimated_prep_duration\"] = 45 * 60\n", @@ -5838,7 +5838,7 @@ "\n", "assert more_than_45_mins.sum() == 449\n", "\n", - "round((~more_than_45_mins).sum() / orders[\"estimated_prep_duration\"].notnull().sum(), 5)" + "round((~more_than_45_mins).sum() / orders[\"estimated_prep_duration\"].notna().sum(), 5)" ] }, { @@ -5877,10 +5877,10 @@ "source": [ "orders[\"pickup_not_confirmed\"] = False\n", "\n", - "msk = orders[\"courier_no_pickup_confirmed_issue\"].notnull()\n", + "msk = orders[\"courier_no_pickup_confirmed_issue\"].notna()\n", "orders.loc[msk, \"pickup_not_confirmed\"] = True\n", "\n", - "msk = orders[\"pickup_at\"].isnull()\n", + "msk = orders[\"pickup_at\"].isna()\n", "orders.loc[msk, \"pickup_not_confirmed\"] = pd.NA\n", "\n", "del orders[\"courier_no_pickup_confirmed_issue\"]\n", @@ -5916,11 +5916,11 @@ "assert (orders[\"logged_pickup_time\"] < 0).sum() == 30\n", "\n", "all_data_available = (\n", - " orders[\"logged_to_pickup_time\"].notnull()\n", - " & orders[\"logged_pickup_time\"].notnull()\n", + " orders[\"logged_to_pickup_time\"].notna()\n", + " & orders[\"logged_pickup_time\"].notna()\n", " & (orders[\"logged_pickup_time\"] >= 0)\n", - " & orders[\"pickup_at\"].notnull()\n", - " & orders[\"courier_accepted_at\"].notnull()\n", + " & orders[\"pickup_at\"].notna()\n", + " & orders[\"courier_accepted_at\"].notna()\n", ")\n", "good_data = (\n", " orders[\"logged_to_pickup_time\"]\n", @@ -6021,7 +6021,7 @@ "\n", "orders[\"reached_pickup_at\"] = pd.NaT\n", "msk = (\n", - " completed & reached_pickup_at.notnull() & (reached_pickup_at < orders[\"pickup_at\"])\n", + " completed & reached_pickup_at.notna() & (reached_pickup_at < orders[\"pickup_at\"])\n", ")\n", "orders.loc[msk, \"reached_pickup_at\"] = reached_pickup_at.loc[msk]\n", "\n", @@ -6043,29 +6043,29 @@ "source": [ "assert not (\n", " (\n", - " orders[\"logged_courier_late_time\"].notnull()\n", - " & orders[\"logged_restaurant_late_time\"].isnull()\n", + " orders[\"logged_courier_late_time\"].notna()\n", + " & orders[\"logged_restaurant_late_time\"].isna()\n", " )\n", " | (\n", - " orders[\"logged_courier_late_time\"].isnull()\n", - " & orders[\"logged_restaurant_late_time\"].notnull()\n", + " orders[\"logged_courier_late_time\"].isna()\n", + " & orders[\"logged_restaurant_late_time\"].notna()\n", " )\n", ").any()\n", "\n", "assert orders.loc[\n", - " orders[\"logged_courier_late_time\"].isnull(), \"placed_at\"\n", + " orders[\"logged_courier_late_time\"].isna(), \"placed_at\"\n", "].min().date() == datetime.date(2016, 2, 22)\n", "\n", "assert orders.loc[\n", - " orders[\"logged_courier_late_time\"].isnull(), \"placed_at\"\n", + " orders[\"logged_courier_late_time\"].isna(), \"placed_at\"\n", "].max().date() == datetime.date(2017, 1, 31)\n", "\n", "assert orders.loc[\n", - " orders[\"logged_courier_late_time\"].notnull(), \"placed_at\"\n", + " orders[\"logged_courier_late_time\"].notna(), \"placed_at\"\n", "].min().date() == datetime.date(2016, 2, 21)\n", "\n", "assert orders.loc[\n", - " orders[\"logged_courier_late_time\"].notnull(), \"placed_at\"\n", + " orders[\"logged_courier_late_time\"].notna(), \"placed_at\"\n", "].max().date() == datetime.date(2017, 1, 31)" ] }, @@ -6094,9 +6094,9 @@ ], "source": [ "all_data_available = (\n", - " orders[\"logged_courier_late_time\"].notnull()\n", - " & orders[\"reached_pickup_at\"].notnull()\n", - " & orders[\"scheduled_pickup_at\"].notnull()\n", + " orders[\"logged_courier_late_time\"].notna()\n", + " & orders[\"reached_pickup_at\"].notna()\n", + " & orders[\"scheduled_pickup_at\"].notna()\n", ")\n", "good_data = (\n", " orders[\"logged_courier_late_time\"]\n", @@ -6138,9 +6138,9 @@ ], "source": [ "all_data_available = (\n", - " orders[\"logged_restaurant_late_time\"].notnull()\n", - " & orders[\"pickup_at\"].notnull()\n", - " & orders[\"scheduled_pickup_at\"].notnull()\n", + " orders[\"logged_restaurant_late_time\"].notna()\n", + " & orders[\"pickup_at\"].notna()\n", + " & orders[\"scheduled_pickup_at\"].notna()\n", ")\n", "good_data = (\n", " orders[\"logged_restaurant_late_time\"]\n", @@ -6188,9 +6188,9 @@ ], "source": [ "all_data_available = (\n", - " (orders[\"logged_wait_pickup_time\"]).notnull()\n", - " & orders[\"reached_pickup_at\"].notnull()\n", - " & orders[\"left_pickup_at\"].notnull()\n", + " (orders[\"logged_wait_pickup_time\"]).notna()\n", + " & orders[\"reached_pickup_at\"].notna()\n", + " & orders[\"left_pickup_at\"].notna()\n", ")\n", "good_data = (\n", " orders[\"logged_wait_pickup_time\"]\n", @@ -6224,10 +6224,10 @@ ], "source": [ "all_data_available = (\n", - " (orders[\"logged_wait_pickup_time\"]).notnull()\n", + " (orders[\"logged_wait_pickup_time\"]).notna()\n", " & (orders[\"logged_courier_late_time\"] >= 0)\n", - " & orders[\"reached_pickup_at\"].notnull()\n", - " & orders[\"left_pickup_at\"].notnull()\n", + " & orders[\"reached_pickup_at\"].notna()\n", + " & orders[\"left_pickup_at\"].notna()\n", ")\n", "good_data = (\n", " orders[\"logged_wait_pickup_time\"]\n", @@ -6290,10 +6290,10 @@ "source": [ "orders[\"delivery_not_confirmed\"] = False\n", "\n", - "msk = orders[\"courier_no_delivery_confirmed_issue\"].notnull()\n", + "msk = orders[\"courier_no_delivery_confirmed_issue\"].notna()\n", "orders.loc[msk, \"delivery_not_confirmed\"] = True\n", "\n", - "msk = orders[\"delivery_at\"].isnull()\n", + "msk = orders[\"delivery_at\"].isna()\n", "orders.loc[msk, \"delivery_not_confirmed\"] = pd.NA\n", "\n", "del orders[\"courier_no_delivery_confirmed_issue\"]\n", @@ -6329,10 +6329,10 @@ "assert not (orders[\"logged_delivery_time\"] < 0).any()\n", "\n", "all_data_available = (\n", - " orders[\"logged_to_delivery_time\"].notnull()\n", - " & orders[\"logged_delivery_time\"].notnull()\n", - " & orders[\"delivery_at\"].notnull()\n", - " & orders[\"pickup_at\"].notnull()\n", + " orders[\"logged_to_delivery_time\"].notna()\n", + " & orders[\"logged_delivery_time\"].notna()\n", + " & orders[\"delivery_at\"].notna()\n", + " & orders[\"pickup_at\"].notna()\n", ")\n", "good_data = (\n", " orders[\"logged_to_delivery_time\"]\n", @@ -6456,7 +6456,7 @@ "mins = orders[\"courier_waited_at_delivery_issue\"].str.contains(\"minutes\").fillna(0)\n", "orders.loc[mins, \"courier_waited_at_delivery\"] = 60 * waited_at_delivery.loc[mins]\n", "\n", - "customer_late = orders[\"courier_waited_at_delivery_issue\"].notnull()\n", + "customer_late = orders[\"courier_waited_at_delivery_issue\"].notna()\n", "\n", "del orders[\"courier_waited_at_delivery_issue\"]\n", "\n", @@ -6533,7 +6533,7 @@ "\n", "msk = (\n", " completed\n", - " & reached_delivery_at.notnull()\n", + " & reached_delivery_at.notna()\n", " & (reached_delivery_at < orders[\"delivery_at\"])\n", ")\n", "orders.loc[msk, \"reached_delivery_at\"] = reached_delivery_at.loc[msk]\n", @@ -6587,9 +6587,9 @@ "source": [ "all_data_available = (\n", " scheduled\n", - " & orders[\"logged_delivery_late_time\"].notnull()\n", - " & orders[\"delivery_at\"].notnull()\n", - " & orders[\"scheduled_delivery_at\"].notnull()\n", + " & orders[\"logged_delivery_late_time\"].notna()\n", + " & orders[\"delivery_at\"].notna()\n", + " & orders[\"scheduled_delivery_at\"].notna()\n", ")\n", "good_data = (\n", " orders[\"logged_delivery_late_time\"]\n", @@ -6636,9 +6636,9 @@ ], "source": [ "all_data_available = (\n", - " orders[\"expected_delivery_time\"].notnull()\n", - " & orders[\"placed_at\"].notnull()\n", - " & orders[\"scheduled_delivery_at\"].notnull()\n", + " orders[\"expected_delivery_time\"].notna()\n", + " & orders[\"placed_at\"].notna()\n", + " & orders[\"scheduled_delivery_at\"].notna()\n", ")\n", "good_data = (\n", " orders[\"expected_delivery_time\"]\n", @@ -6681,9 +6681,9 @@ ], "source": [ "all_data_available = (\n", - " orders[\"courier_waited_at_delivery\"].notnull()\n", - " & orders[\"delivery_at\"].notnull()\n", - " & orders[\"reached_delivery_at\"].notnull()\n", + " orders[\"courier_waited_at_delivery\"].notna()\n", + " & orders[\"delivery_at\"].notna()\n", + " & orders[\"reached_delivery_at\"].notna()\n", ")\n", "good_data = (\n", " orders[\"courier_waited_at_delivery\"]\n", @@ -6719,9 +6719,9 @@ "metadata": {}, "outputs": [], "source": [ - "msk = orders[\"delivery_at\"].notnull() & orders[\"courier_waited_at_delivery\"].notnull()\n", + "msk = orders[\"delivery_at\"].notna() & orders[\"courier_waited_at_delivery\"].notna()\n", "orders[\"courier_waited_at_delivery\"] = pd.NA\n", - "orders.loc[orders[\"delivery_at\"].notnull(), \"courier_waited_at_delivery\"] = False\n", + "orders.loc[orders[\"delivery_at\"].notna(), \"courier_waited_at_delivery\"] = False\n", "orders.loc[msk, \"courier_waited_at_delivery\"] = True\n", "\n", "assert orders[\"courier_waited_at_delivery\"].sum() == msk.sum() == 30_658" @@ -7458,7 +7458,7 @@ "outputs": [], "source": [ "assert set(couriers.reset_index()[\"id\"]) == set(\n", - " orders.loc[orders[\"courier_id\"].notnull(), \"courier_id\"].unique()\n", + " orders.loc[orders[\"courier_id\"].notna(), \"courier_id\"].unique()\n", ")" ] }, From a06cb5bdfba6a4a84d0b9efe0d260437e37d5a90 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 11:31:07 +0100 Subject: [PATCH 16/19] Resolve the remaining `ruff` findings Every change keeps the values the same, so the stored outputs stay valid. `init_r` keeps its import because only its side effect matters. --- research/00_r_dependencies.ipynb | 7 +- research/01_clean_data.ipynb | 181 +++++++++--------- research/03_grid_visualizations.ipynb | 4 +- .../07_visualizing_demand_forecasting.ipynb | 9 +- research/08_google_maps.ipynb | 4 +- 5 files changed, 101 insertions(+), 104 deletions(-) diff --git a/research/00_r_dependencies.ipynb b/research/00_r_dependencies.ipynb index 68ce353..1b65d27 100644 --- a/research/00_r_dependencies.ipynb +++ b/research/00_r_dependencies.ipynb @@ -19,6 +19,7 @@ "metadata": {}, "outputs": [], "source": [ + "import contextlib\n", "import getpass\n", "import os\n", "import shutil" @@ -110,10 +111,8 @@ "outputs": [], "source": [ "# Create a fresh folder for the R dependencies.\n", - "try:\n", + "with contextlib.suppress(FileNotFoundError):\n", " shutil.rmtree(r_libs_path)\n", - "except FileNotFoundError:\n", - " pass\n", "os.makedirs(r_libs_path)" ] }, @@ -1840,7 +1839,7 @@ "metadata": {}, "outputs": [], "source": [ - "from velofy import init_r" + "from velofy import init_r # noqa: F401" ] } ], diff --git a/research/01_clean_data.ipynb b/research/01_clean_data.ipynb index 38924ce..a8d87eb 100644 --- a/research/01_clean_data.ipynb +++ b/research/01_clean_data.ipynb @@ -52,7 +52,7 @@ "metadata": {}, "outputs": [], "source": [ - "from velofy import config\n", + "from velofy import config as pkg_config\n", "from velofy import db" ] }, @@ -63,13 +63,12 @@ "outputs": [], "source": [ "import collections\n", - "import datetime\n", + "import datetime as dt\n", "import hashlib\n", "\n", "import numpy as np\n", "import pandas as pd\n", - "import pytz as tz\n", - "import sqlalchemy as sa" + "import pytz as tz" ] }, { @@ -138,7 +137,7 @@ } ], "source": [ - "config.CLEAN_SCHEMA" + "pkg_config.CLEAN_SCHEMA" ] }, { @@ -165,7 +164,7 @@ } ], "source": [ - "config.ORIGINAL_SCHEMA" + "pkg_config.ORIGINAL_SCHEMA" ] }, { @@ -299,9 +298,9 @@ " cities.name,\n", " geo_areas.kml\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.cities\n", + " {pkg_config.ORIGINAL_SCHEMA}.cities\n", " LEFT OUTER JOIN\n", - " {config.ORIGINAL_SCHEMA}.geo_areas ON cities.geo_area_id = geo_areas.id\n", + " {pkg_config.ORIGINAL_SCHEMA}.geo_areas ON cities.geo_area_id = geo_areas.id\n", " WHERE\n", " cities.id IN %(city_ids)s\n", " ORDER BY\n", @@ -578,7 +577,7 @@ " floor,\n", " special_instructions\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.addresses\n", + " {pkg_config.ORIGINAL_SCHEMA}.addresses\n", " WHERE\n", " city_id IN %(city_ids)s\n", " AND\n", @@ -588,16 +587,16 @@ " SELECT DISTINCT\n", " pickup_address_id AS address_id\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.orders\n", + " {pkg_config.ORIGINAL_SCHEMA}.orders\n", " WHERE\n", - " created_at < '{config.CUTOFF_DAY}'\n", + " created_at < '{pkg_config.CUTOFF_DAY}'\n", " UNION\n", " SELECT DISTINCT\n", " dropoff_address_id AS address_id\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.orders\n", + " {pkg_config.ORIGINAL_SCHEMA}.orders\n", " WHERE\n", - " created_at < '{config.CUTOFF_DAY}'\n", + " created_at < '{pkg_config.CUTOFF_DAY}'\n", " ) AS orders\n", " )\n", " ORDER BY\n", @@ -860,7 +859,7 @@ " .dt.tz_convert(tz.timezone(\"Europe/Paris\"))\n", " .dt.tz_localize(None)\n", " .map(\n", - " lambda x: datetime.datetime(\n", + " lambda x: dt.datetime(\n", " x.year, x.month, x.day, x.hour, x.minute, x.second\n", " )\n", " if x is not pd.NaT\n", @@ -1474,7 +1473,7 @@ "outputs": [], "source": [ "msk = addresses[\"floor\"].isna() & addresses[\"special_instructions\"].notna()\n", - "addresses.loc[msk, \"floor\"] = addresses.loc[msk, \"special_instructions\"].values" + "addresses.loc[msk, \"floor\"] = addresses.loc[msk, \"special_instructions\"].to_numpy()" ] }, { @@ -2173,13 +2172,13 @@ " address_id,\n", " estimated_prep_duration\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.businesses\n", + " {pkg_config.ORIGINAL_SCHEMA}.businesses\n", " WHERE\n", " address_id IN (\n", - " SELECT id FROM {config.ORIGINAL_SCHEMA}.addresses WHERE city_id IN %(city_ids)s\n", + " SELECT id FROM {pkg_config.ORIGINAL_SCHEMA}.addresses WHERE city_id IN %(city_ids)s\n", " )\n", " AND\n", - " created_at < '{config.CUTOFF_DAY}'\n", + " created_at < '{pkg_config.CUTOFF_DAY}'\n", " ORDER BY\n", " id\n", " \"\"\",\n", @@ -2706,33 +2705,33 @@ " couriers.pay_per_hour,\n", " couriers.pay_per_order\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.couriers\n", + " {pkg_config.ORIGINAL_SCHEMA}.couriers\n", " LEFT OUTER JOIN\n", - " {config.ORIGINAL_SCHEMA}.vehicles ON couriers.vehicle_id = vehicles.id\n", + " {pkg_config.ORIGINAL_SCHEMA}.vehicles ON couriers.vehicle_id = vehicles.id\n", " LEFT OUTER JOIN\n", - " {config.ORIGINAL_SCHEMA}.vehicle_types ON vehicles.vehicle_type_id = vehicle_types.id\n", + " {pkg_config.ORIGINAL_SCHEMA}.vehicle_types ON vehicles.vehicle_type_id = vehicle_types.id\n", " LEFT OUTER JOIN\n", - " {config.ORIGINAL_SCHEMA}.vehicle_bag_types ON vehicles.vehicle_bag_type_id = vehicle_bag_types.id\n", + " {pkg_config.ORIGINAL_SCHEMA}.vehicle_bag_types ON vehicles.vehicle_bag_type_id = vehicle_bag_types.id\n", " WHERE\n", " couriers.id in (\n", " SELECT DISTINCT\n", " deliveries.courier_id\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.orders\n", + " {pkg_config.ORIGINAL_SCHEMA}.orders\n", " INNER JOIN\n", - " {config.ORIGINAL_SCHEMA}.deliveries ON orders.id = deliveries.order_id\n", + " {pkg_config.ORIGINAL_SCHEMA}.deliveries ON orders.id = deliveries.order_id\n", " WHERE\n", " orders.featured_business_id IN (\n", " SELECT -- Subquery based off the restaurants query above!\n", " id\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.businesses\n", + " {pkg_config.ORIGINAL_SCHEMA}.businesses\n", " WHERE\n", " address_id IN (\n", - " SELECT id FROM {config.ORIGINAL_SCHEMA}.addresses WHERE city_id IN %(city_ids)s\n", + " SELECT id FROM {pkg_config.ORIGINAL_SCHEMA}.addresses WHERE city_id IN %(city_ids)s\n", " )\n", " AND\n", - " created_at < '{config.CUTOFF_DAY}'\n", + " created_at < '{pkg_config.CUTOFF_DAY}'\n", " )\n", " AND\n", " deliveries.courier_id IS NOT NULL\n", @@ -3484,7 +3483,7 @@ " CASE\n", " WHEN orders.preorder IS FALSE\n", " THEN TRUE\n", - " ELSE FALSE \n", + " ELSE FALSE\n", " END AS ad_hoc,\n", " CASE\n", " WHEN orders.preorder is TRUE\n", @@ -3537,27 +3536,27 @@ " delivery_timings.total_time AS logged_total_time,\n", " delivery_timings.confirmed_total_time AS logged_confirmed_total_time\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.orders\n", + " {pkg_config.ORIGINAL_SCHEMA}.orders\n", " LEFT OUTER JOIN\n", - " {config.ORIGINAL_SCHEMA}.deliveries ON orders.id = deliveries.order_id\n", + " {pkg_config.ORIGINAL_SCHEMA}.deliveries ON orders.id = deliveries.order_id\n", " LEFT OUTER JOIN\n", " (\n", " SELECT\n", " order_id,\n", " CAST(100 * SUM(price) AS INTEGER) AS sub_total\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.order_records\n", + " {pkg_config.ORIGINAL_SCHEMA}.order_records\n", " GROUP BY\n", " order_id\n", " ) AS items_totals ON orders.id = items_totals.order_id\n", " LEFT OUTER JOIN\n", - " {config.ORIGINAL_SCHEMA}.delivery_timings ON deliveries.id = delivery_timings.delivery_id\n", + " {pkg_config.ORIGINAL_SCHEMA}.delivery_timings ON deliveries.id = delivery_timings.delivery_id\n", " LEFT OUTER JOIN (\n", " SELECT\n", " delivery_id,\n", " MAX(notes) AS issue\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.issues\n", + " {pkg_config.ORIGINAL_SCHEMA}.issues\n", " WHERE\n", " type = 'DispatchIssue'\n", " AND\n", @@ -3570,7 +3569,7 @@ " delivery_id,\n", " MAX(notes) AS issue\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.issues\n", + " {pkg_config.ORIGINAL_SCHEMA}.issues\n", " WHERE\n", " type = 'PickupIssue'\n", " AND\n", @@ -3583,7 +3582,7 @@ " delivery_id,\n", " MAX(notes) AS issue\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.issues\n", + " {pkg_config.ORIGINAL_SCHEMA}.issues\n", " WHERE\n", " type = 'PickupIssue'\n", " AND\n", @@ -3596,7 +3595,7 @@ " delivery_id,\n", " MAX(notes) AS issue\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.issues\n", + " {pkg_config.ORIGINAL_SCHEMA}.issues\n", " WHERE\n", " type = 'PickupIssue'\n", " AND\n", @@ -3609,7 +3608,7 @@ " delivery_id,\n", " MAX(notes) AS issue\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.issues\n", + " {pkg_config.ORIGINAL_SCHEMA}.issues\n", " WHERE\n", " type = 'DropoffIssue'\n", " AND\n", @@ -3622,7 +3621,7 @@ " delivery_id,\n", " MAX(notes) AS issue\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.issues\n", + " {pkg_config.ORIGINAL_SCHEMA}.issues\n", " WHERE\n", " type = 'DropoffIssue'\n", " AND\n", @@ -3635,7 +3634,7 @@ " delivery_id,\n", " MAX(notes) AS issue\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.issues\n", + " {pkg_config.ORIGINAL_SCHEMA}.issues\n", " WHERE\n", " type = 'DropoffIssue'\n", " AND\n", @@ -3654,7 +3653,7 @@ " (metadata -> 'courier_id')::TEXT::INTEGER AS courier_id,\n", " created_at\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.delivery_transitions\n", + " {pkg_config.ORIGINAL_SCHEMA}.delivery_transitions\n", " WHERE\n", " to_state = 'left_pickup'\n", " ) AS left_pickups\n", @@ -3667,7 +3666,7 @@ " delivery_id,\n", " MAX(created_at) AS cancelled_at\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.delivery_transitions\n", + " {pkg_config.ORIGINAL_SCHEMA}.delivery_transitions\n", " WHERE\n", " to_state = 'cancelled'\n", " GROUP BY\n", @@ -3678,16 +3677,16 @@ " SELECT -- Subquery based off the restaurants query above!\n", " id\n", " FROM\n", - " {config.ORIGINAL_SCHEMA}.businesses\n", + " {pkg_config.ORIGINAL_SCHEMA}.businesses\n", " WHERE\n", " address_id IN (\n", - " SELECT id FROM {config.ORIGINAL_SCHEMA}.addresses WHERE city_id IN %(city_ids)s\n", + " SELECT id FROM {pkg_config.ORIGINAL_SCHEMA}.addresses WHERE city_id IN %(city_ids)s\n", " )\n", " AND\n", - " created_at < '{config.CUTOFF_DAY}'\n", + " created_at < '{pkg_config.CUTOFF_DAY}'\n", " )\n", " AND\n", - " scheduled_dropoff_at < '{config.CUTOFF_DAY}'\n", + " scheduled_dropoff_at < '{pkg_config.CUTOFF_DAY}'\n", " AND\n", " deliveries.is_primary IS TRUE\n", " ORDER BY\n", @@ -4627,7 +4626,7 @@ "source": [ "msk = (orders[\"ad_hoc\"] == False) & (\n", " orders[\"scheduled_delivery_at\"] - orders[\"placed_at\"]\n", - " < datetime.timedelta(minutes=30)\n", + " < dt.timedelta(minutes=30)\n", ")\n", "orders.loc[msk, \"ad_hoc\"] = True\n", "orders.loc[msk, \"scheduled_delivery_at\"] = pd.NaT\n", @@ -4674,13 +4673,13 @@ "orders.loc[round_down, \"scheduled_delivery_at\"] = orders.loc[\n", " round_down, \"scheduled_delivery_at\"\n", "] - (orders.loc[round_down, \"scheduled_delivery_at\"].dt.minute % 15).map(\n", - " lambda m: datetime.timedelta(minutes=m)\n", + " lambda m: dt.timedelta(minutes=m)\n", ")\n", "round_up = msk & (orders[\"scheduled_delivery_at\"].dt.minute % 15 >= 8)\n", "orders.loc[round_up, \"scheduled_delivery_at\"] = orders.loc[\n", " round_up, \"scheduled_delivery_at\"\n", "] + (orders.loc[round_up, \"scheduled_delivery_at\"].dt.minute % 15).map(\n", - " lambda m: datetime.timedelta(minutes=(15 - m))\n", + " lambda m: dt.timedelta(minutes=(15 - m))\n", ")\n", "orders.loc[msk, \"scheduled_delivery_at_corrected\"] = True\n", "\n", @@ -4857,8 +4856,8 @@ "orders.loc[msk, \"left_pickup_at_corrected\"] = True\n", "\n", "assert msk.sum() == 14_013\n", - "assert orders.loc[msk, \"placed_at\"].min().date() == datetime.date(2016, 9, 6)\n", - "assert orders.loc[msk, \"placed_at\"].max().date() == datetime.date(2016, 10, 17)" + "assert orders.loc[msk, \"placed_at\"].min().date() == dt.date(2016, 9, 6)\n", + "assert orders.loc[msk, \"placed_at\"].max().date() == dt.date(2016, 10, 17)" ] }, { @@ -4920,7 +4919,7 @@ "orders.loc[msk, \"courier_notified_at_corrected\"] = True\n", "\n", "assert msk.sum() == 8\n", - "assert set(orders.loc[msk, \"status\"].unique()) == set([\"cancelled\"])" + "assert set(orders.loc[msk, \"status\"].unique()) == {\"cancelled\"}" ] }, { @@ -5053,7 +5052,7 @@ "msk = (orders[\"scheduled_delivery_at\"].dt.hour == 11) & (\n", " orders[\"scheduled_delivery_at\"].dt.minute == 30\n", ")\n", - "orders.loc[msk, \"scheduled_delivery_at\"] += datetime.timedelta(minutes=15)\n", + "orders.loc[msk, \"scheduled_delivery_at\"] += dt.timedelta(minutes=15)\n", "orders.loc[msk, \"scheduled_delivery_at_corrected\"] = True\n", "\n", "assert msk.sum() == 37\n", @@ -5061,7 +5060,7 @@ "msk = (orders[\"scheduled_delivery_at\"].dt.hour == 11) & (\n", " orders[\"scheduled_delivery_at\"].dt.minute == 15\n", ")\n", - "orders.loc[msk, \"scheduled_delivery_at\"] += datetime.timedelta(minutes=30)\n", + "orders.loc[msk, \"scheduled_delivery_at\"] += dt.timedelta(minutes=30)\n", "orders.loc[msk, \"scheduled_delivery_at_corrected\"] = True\n", "\n", "assert msk.sum() == 1\n", @@ -5124,7 +5123,7 @@ "metadata": {}, "outputs": [], "source": [ - "assert set(orders[\"status\"].unique()) == set([\"cancelled\", \"completed\"])" + "assert set(orders[\"status\"].unique()) == {\"cancelled\", \"completed\"}" ] }, { @@ -5161,7 +5160,7 @@ "assert (\n", " orders.loc[claimed_to_be_delivered, \"cancelled_at\"].min()\n", " == orders.loc[claimed_to_be_delivered, \"cancelled_at\"].max()\n", - " == datetime.datetime(2016, 10, 18, 9, 52, 45)\n", + " == dt.datetime(2016, 10, 18, 9, 52, 45)\n", ")\n", "\n", "realistically_delivered = (\n", @@ -5222,7 +5221,7 @@ "metadata": {}, "outputs": [], "source": [ - "batch = orders[\"cancelled_at\"] == datetime.datetime(2016, 10, 18, 9, 52, 45)\n", + "batch = orders[\"cancelled_at\"] == dt.datetime(2016, 10, 18, 9, 52, 45)\n", "orders.loc[cancelled & batch, \"cancelled_at\"] = pd.NaT\n", "orders.loc[cancelled & batch, \"cancelled_at_corrected\"] = True\n", "\n", @@ -5276,7 +5275,7 @@ "outputs": [], "source": [ "msk = orders[\"cancelled_at\"] == orders[\"dispatch_at\"]\n", - "orders.loc[msk, \"dispatch_at\"] -= datetime.timedelta(seconds=1)\n", + "orders.loc[msk, \"dispatch_at\"] -= dt.timedelta(seconds=1)\n", "orders.loc[msk, \"dispatch_at_corrected\"] = True\n", "\n", "assert msk.sum() == 3" @@ -5296,7 +5295,7 @@ "outputs": [], "source": [ "msk = orders[\"cancelled_at\"] == orders[\"courier_notified_at\"]\n", - "orders.loc[msk, \"courier_notified_at\"] -= datetime.timedelta(seconds=1)\n", + "orders.loc[msk, \"courier_notified_at\"] -= dt.timedelta(seconds=1)\n", "orders.loc[msk, \"courier_notified_at_corrected\"] = True\n", "\n", "assert msk.sum() == 1" @@ -5309,7 +5308,7 @@ "outputs": [], "source": [ "msk = orders[\"cancelled_at\"] == orders[\"courier_accepted_at\"]\n", - "orders.loc[msk, \"courier_accepted_at\"] -= datetime.timedelta(seconds=1)\n", + "orders.loc[msk, \"courier_accepted_at\"] -= dt.timedelta(seconds=1)\n", "orders.loc[msk, \"courier_accepted_at_corrected\"] = True\n", "\n", "assert msk.sum() == 8" @@ -5329,7 +5328,7 @@ "outputs": [], "source": [ "msk = orders[\"cancelled_at\"] == orders[\"pickup_at\"]\n", - "orders.loc[msk, \"pickup_at\"] -= datetime.timedelta(seconds=1)\n", + "orders.loc[msk, \"pickup_at\"] -= dt.timedelta(seconds=1)\n", "orders.loc[msk, \"pickup_at_corrected\"] = True\n", "\n", "assert msk.sum() == 1" @@ -5494,7 +5493,7 @@ ")\n", "\n", "accept_time = orders[\"logged_accepting_time\"].map(\n", - " lambda x: datetime.timedelta(seconds=x) if x is not pd.NA else pd.NaT\n", + " lambda x: dt.timedelta(seconds=x) if x is not pd.NA else pd.NaT\n", ")\n", "extrapolated_dispatch_at = orders[\"courier_accepted_at\"] - accept_time\n", "still_wrong = extrapolated_dispatch_at >= orders[\"courier_notified_at\"]\n", @@ -5573,7 +5572,7 @@ " orders[\"courier_accepted_at\"]\n", " # Some values for logged_reaction_time are <= 0.\n", " - orders[\"logged_reaction_time\"].map(\n", - " lambda x: datetime.timedelta(seconds=x) if x is not pd.NA and x > 0 else pd.NaT\n", + " lambda x: dt.timedelta(seconds=x) if x is not pd.NA and x > 0 else pd.NaT\n", " )\n", ")\n", "still_wrong = extrapolated_courier_notified_at <= orders[\"dispatch_at\"]\n", @@ -5645,17 +5644,17 @@ "assert not (no_duration & orders[\"expected_wait_pickup_time\"].notna()).any()\n", "assert (~no_duration & orders[\"expected_wait_pickup_time\"].isna()).sum() == 19_865\n", "assert not (\n", - " (orders[\"placed_at\"].dt.date > datetime.date(2016, 5, 24))\n", + " (orders[\"placed_at\"].dt.date > dt.date(2016, 5, 24))\n", " & orders[\"expected_wait_pickup_time\"].isna()\n", " & (orders[\"cancelled\"] == False)\n", ").any()\n", "\n", "del orders[\"expected_wait_pickup_time\"]\n", "\n", - "assert orders.loc[no_duration, \"placed_at\"].min().date() == datetime.date(2016, 2, 21)\n", - "assert orders.loc[no_duration, \"placed_at\"].max().date() == datetime.date(2016, 5, 24)\n", - "assert orders.loc[~no_duration, \"placed_at\"].min().date() == datetime.date(2016, 5, 24)\n", - "assert orders.loc[~no_duration, \"placed_at\"].max().date() == datetime.date(2017, 1, 31)\n", + "assert orders.loc[no_duration, \"placed_at\"].min().date() == dt.date(2016, 2, 21)\n", + "assert orders.loc[no_duration, \"placed_at\"].max().date() == dt.date(2016, 5, 24)\n", + "assert orders.loc[~no_duration, \"placed_at\"].min().date() == dt.date(2016, 5, 24)\n", + "assert orders.loc[~no_duration, \"placed_at\"].max().date() == dt.date(2017, 1, 31)\n", "assert not (~no_duration & (orders[\"estimated_prep_duration\"] % 60 != 0)).any()\n", "\n", "round((all_data_available & good_data).sum() / all_data_available.sum(), 3)" @@ -5719,7 +5718,7 @@ "outputs": [], "source": [ "duration = orders[\"estimated_prep_duration\"].map(\n", - " lambda x: datetime.timedelta(seconds=x) if x is not pd.NA else pd.NaT\n", + " lambda x: dt.timedelta(seconds=x) if x is not pd.NA else pd.NaT\n", ")\n", "calc_restaurant_notified_at = orders[\"scheduled_pickup_at\"] - duration\n", "\n", @@ -5735,8 +5734,8 @@ "\n", "assert (all_data_available & ~good_data).sum() == 7_514\n", "assert msk.sum() == 2_425\n", - "assert orders.loc[msk, \"placed_at\"].min().date() == datetime.date(2016, 5, 24)\n", - "assert orders.loc[msk, \"placed_at\"].max().date() == datetime.date(2017, 1, 31)" + "assert orders.loc[msk, \"placed_at\"].min().date() == dt.date(2016, 5, 24)\n", + "assert orders.loc[msk, \"placed_at\"].max().date() == dt.date(2017, 1, 31)" ] }, { @@ -5753,7 +5752,7 @@ "outputs": [], "source": [ "duration = orders[\"estimated_prep_duration\"].map(\n", - " lambda x: datetime.timedelta(seconds=x) if x is not pd.NA else pd.NaT\n", + " lambda x: dt.timedelta(seconds=x) if x is not pd.NA else pd.NaT\n", ")\n", "extrapolated = orders[\"scheduled_pickup_at\"] - duration\n", "\n", @@ -5774,7 +5773,7 @@ "\n", "assert extrapolate.sum() == 469\n", "assert msk.sum() == 374\n", - "assert orders.loc[msk, \"placed_at\"].min().date() == datetime.date(2016, 5, 29)" + "assert orders.loc[msk, \"placed_at\"].min().date() == dt.date(2016, 5, 29)" ] }, { @@ -5802,8 +5801,8 @@ "orders.loc[extrapolate, \"estimated_prep_duration_corrected\"] = True\n", "\n", "assert extrapolate.sum() == 108_398\n", - "assert orders.loc[extrapolate, \"placed_at\"].min().date() == datetime.date(2016, 2, 21)\n", - "assert orders.loc[extrapolate, \"placed_at\"].max().date() == datetime.date(2016, 5, 24)" + "assert orders.loc[extrapolate, \"placed_at\"].min().date() == dt.date(2016, 2, 21)\n", + "assert orders.loc[extrapolate, \"placed_at\"].max().date() == dt.date(2016, 5, 24)" ] }, { @@ -5953,10 +5952,10 @@ "calc_pickup_at = (\n", " orders[\"courier_accepted_at\"]\n", " + orders[\"logged_to_pickup_time\"].map(\n", - " lambda x: datetime.timedelta(seconds=x) if x is not pd.NA else pd.NaT\n", + " lambda x: dt.timedelta(seconds=x) if x is not pd.NA else pd.NaT\n", " )\n", " + orders[\"logged_pickup_time\"].map(\n", - " lambda x: datetime.timedelta(seconds=x) if x is not pd.NA else pd.NaT\n", + " lambda x: dt.timedelta(seconds=x) if x is not pd.NA else pd.NaT\n", " )\n", ")\n", "\n", @@ -6015,7 +6014,7 @@ "outputs": [], "source": [ "to_pickup_time = orders[\"logged_to_pickup_time\"].map(\n", - " lambda x: datetime.timedelta(seconds=x) if x is not pd.NA and x > 0 else pd.NaT\n", + " lambda x: dt.timedelta(seconds=x) if x is not pd.NA and x > 0 else pd.NaT\n", ")\n", "reached_pickup_at = orders[\"courier_accepted_at\"] + to_pickup_time\n", "\n", @@ -6054,19 +6053,19 @@ "\n", "assert orders.loc[\n", " orders[\"logged_courier_late_time\"].isna(), \"placed_at\"\n", - "].min().date() == datetime.date(2016, 2, 22)\n", + "].min().date() == dt.date(2016, 2, 22)\n", "\n", "assert orders.loc[\n", " orders[\"logged_courier_late_time\"].isna(), \"placed_at\"\n", - "].max().date() == datetime.date(2017, 1, 31)\n", + "].max().date() == dt.date(2017, 1, 31)\n", "\n", "assert orders.loc[\n", " orders[\"logged_courier_late_time\"].notna(), \"placed_at\"\n", - "].min().date() == datetime.date(2016, 2, 21)\n", + "].min().date() == dt.date(2016, 2, 21)\n", "\n", "assert orders.loc[\n", " orders[\"logged_courier_late_time\"].notna(), \"placed_at\"\n", - "].max().date() == datetime.date(2017, 1, 31)" + "].max().date() == dt.date(2017, 1, 31)" ] }, { @@ -6480,10 +6479,10 @@ "calc_delivery_at = (\n", " orders[\"pickup_at\"]\n", " + orders[\"logged_to_delivery_time\"].map(\n", - " lambda x: datetime.timedelta(seconds=x) if x is not pd.NA else pd.NaT\n", + " lambda x: dt.timedelta(seconds=x) if x is not pd.NA else pd.NaT\n", " )\n", " + orders[\"logged_delivery_time\"].map(\n", - " lambda x: datetime.timedelta(seconds=x) if x is not pd.NA else pd.NaT\n", + " lambda x: dt.timedelta(seconds=x) if x is not pd.NA else pd.NaT\n", " )\n", ")\n", "\n", @@ -6523,7 +6522,7 @@ "outputs": [], "source": [ "to_delivery_time = orders[\"logged_to_delivery_time\"].map(\n", - " lambda x: datetime.timedelta(seconds=x) if x is not pd.NA and x > 0 else pd.NaT\n", + " lambda x: dt.timedelta(seconds=x) if x is not pd.NA and x > 0 else pd.NaT\n", ")\n", "reached_delivery_at = orders[\"pickup_at\"] + to_delivery_time\n", "\n", @@ -7536,7 +7535,7 @@ } ], "source": [ - "config.CLEAN_SCHEMA" + "pkg_config.CLEAN_SCHEMA" ] }, { @@ -7548,7 +7547,7 @@ "cities.to_sql(\n", " \"cities\",\n", " con=connection,\n", - " schema=config.CLEAN_SCHEMA,\n", + " schema=pkg_config.CLEAN_SCHEMA,\n", " if_exists=\"append\",\n", " index=True,\n", ")" @@ -7563,7 +7562,7 @@ "addresses.to_sql(\n", " \"addresses\",\n", " con=connection,\n", - " schema=config.CLEAN_SCHEMA,\n", + " schema=pkg_config.CLEAN_SCHEMA,\n", " if_exists=\"append\",\n", " index=True,\n", ")" @@ -7578,7 +7577,7 @@ "restaurants.to_sql(\n", " \"restaurants\",\n", " con=connection,\n", - " schema=config.CLEAN_SCHEMA,\n", + " schema=pkg_config.CLEAN_SCHEMA,\n", " if_exists=\"append\",\n", " index=True,\n", ")" @@ -7593,7 +7592,7 @@ "couriers.to_sql(\n", " \"couriers\",\n", " con=connection,\n", - " schema=config.CLEAN_SCHEMA,\n", + " schema=pkg_config.CLEAN_SCHEMA,\n", " if_exists=\"append\",\n", " index=True,\n", ")" @@ -7610,7 +7609,7 @@ "customers.to_sql(\n", " \"customers\",\n", " con=connection,\n", - " schema=config.CLEAN_SCHEMA,\n", + " schema=pkg_config.CLEAN_SCHEMA,\n", " if_exists=\"append\",\n", " index=True,\n", ")" @@ -7625,7 +7624,7 @@ "orders.to_sql(\n", " \"orders\",\n", " con=connection,\n", - " schema=config.CLEAN_SCHEMA,\n", + " schema=pkg_config.CLEAN_SCHEMA,\n", " if_exists=\"append\",\n", " index=True,\n", ")" diff --git a/research/03_grid_visualizations.ipynb b/research/03_grid_visualizations.ipynb index 6215383..0105430 100644 --- a/research/03_grid_visualizations.ipynb +++ b/research/03_grid_visualizations.ipynb @@ -46,7 +46,7 @@ "metadata": {}, "outputs": [], "source": [ - "from velofy import config\n", + "from velofy import config as pkg_config\n", "from velofy import db" ] }, @@ -106,7 +106,7 @@ } ], "source": [ - "config.GRID_SIDE_LENGTHS # choose one of these values" + "pkg_config.GRID_SIDE_LENGTHS # choose one of these values" ] }, { diff --git a/research/07_visualizing_demand_forecasting.ipynb b/research/07_visualizing_demand_forecasting.ipynb index 11e114b..3620341 100644 --- a/research/07_visualizing_demand_forecasting.ipynb +++ b/research/07_visualizing_demand_forecasting.ipynb @@ -46,7 +46,6 @@ "source": [ "import datetime as dt\n", "\n", - "import matplotlib\n", "import matplotlib.pyplot as plt" ] }, @@ -56,7 +55,7 @@ "metadata": {}, "outputs": [], "source": [ - "from velofy import config\n", + "from velofy import config as pkg_config\n", "from velofy import db\n", "from velofy.forecasts import methods\n", "from velofy.forecasts import models\n", @@ -79,7 +78,7 @@ "metadata": {}, "outputs": [], "source": [ - "matplotlib.style.use(\"ggplot\")" + "plt.style.use(\"ggplot\")" ] }, { @@ -129,7 +128,7 @@ } ], "source": [ - "config.GRID_SIDE_LENGTHS # possible values" + "pkg_config.GRID_SIDE_LENGTHS # possible values" ] }, { @@ -158,7 +157,7 @@ } ], "source": [ - "config.TIME_STEPS # possible values" + "pkg_config.TIME_STEPS # possible values" ] }, { diff --git a/research/08_google_maps.ipynb b/research/08_google_maps.ipynb index 56ba6dd..a776c08 100644 --- a/research/08_google_maps.ipynb +++ b/research/08_google_maps.ipynb @@ -51,7 +51,7 @@ "source": [ "import googlemaps as gm\n", "\n", - "from velofy import config\n", + "from velofy import config as pkg_config\n", "from velofy import db" ] }, @@ -298,7 +298,7 @@ "metadata": {}, "outputs": [], "source": [ - "client = gm.Client(config.GOOGLE_MAPS_API_KEY)" + "client = gm.Client(pkg_config.GOOGLE_MAPS_API_KEY)" ] }, { From 7a000145a7c4f4266ae67b21b8d49a63fca87511 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 11:45:15 +0100 Subject: [PATCH 17/19] Lint the notebooks in the `lint` session Only `ruff` checks them because the formatters would rewrite the cells. The per-file ignores fit exploratory code that is never rerun. --- noxfile.py | 7 ++++++- pyproject.toml | 9 +++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/noxfile.py b/noxfile.py index cd577df..8a4b435 100644 --- a/noxfile.py +++ b/noxfile.py @@ -97,6 +97,9 @@ PACKAGE_LOCATION = "src/" DOCS_BUILD = ".cache/docs/" DOCS_LOCATION = "docs/" +# Only `ruff` lints the notebooks because the formatters would rewrite them +NOTEBOOKS_LOCATION = "research/" + SCRIPTS_LOCATION = "scripts/" TESTS_LOCATION = "tests/" @@ -266,6 +269,8 @@ def lint_code(session: nox.Session) -> None: # Interpret extra arguments as `locations` of source files locations = session.posargs or SRC_LOCATIONS + ruff_locations = session.posargs or (*SRC_LOCATIONS, NOTEBOOKS_LOCATION) + # `flake8` reads the "[tool.flake8]" section in pyproject.toml # only with the `flake8-pyproject` plugin installed session.run("flake8", "--version") @@ -275,7 +280,7 @@ def lint_code(session: nox.Session) -> None: session.run("isort", "--check-only", *locations) session.run("ruff", "--version") - session.run("ruff", "check", *locations) + session.run("ruff", "check", *ruff_locations) session.run("mypy", "--version") session.run("mypy", *TYPECHECK_LOCATIONS) diff --git a/pyproject.toml b/pyproject.toml index 791833d..23469bb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -735,6 +735,15 @@ external = [ "migrations/versions/*.py" = ["ANN0", "ANN2", "S608"] # Type annotations are not strictly enforced "noxfile.py" = ["ANN0", "ANN2"] +"research/*.ipynb" = [ + "ANN0", "ANN2", # Type annotations are not strictly enforced + "E501", # Exploratory cells read better unwrapped + "E712", # `== True` filters `pandas` columns element-wise + "PTH", # Paths stay `str`s as in the stored outputs + "S101", # `assert` statements document expectations + "S605", "S608", # No untrusted input + "T20", # `print()` shows results +] # `print()` is ok in ad-hoc scripts "scripts/**" = ["T20"] # - ANN0, ANN2 => Type annotations are not strictly enforced From 47a22f9587f94fa5bc2705302a3e29dca3701dcf Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 11:47:26 +0100 Subject: [PATCH 18/19] Put the `ruff` per-file ignores on separate lines Each reason now sits next to its codes, which reads better than a separate list. --- pyproject.toml | 42 ++++++++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 23469bb..2a975ed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -728,13 +728,19 @@ external = [ [tool.ruff.lint.per-file-ignores] -# Type annotations are not strictly enforced -"migrations/env.py" = ["ANN0", "ANN2"] -# - ANN0, ANN2 => Type annotations are not strictly enforced -# - S608 => Do not worry about SQL injection here -"migrations/versions/*.py" = ["ANN0", "ANN2", "S608"] -# Type annotations are not strictly enforced -"noxfile.py" = ["ANN0", "ANN2"] +"migrations/env.py" = [ + "ANN0", "ANN2", # Type annotations are not strictly enforced +] + +"migrations/versions/*.py" = [ + "ANN0", "ANN2", # Type annotations are not strictly enforced + "S608", # Do not worry about SQL injection here +] + +"noxfile.py" = [ + "ANN0", "ANN2", # Type annotations are not strictly enforced +] + "research/*.ipynb" = [ "ANN0", "ANN2", # Type annotations are not strictly enforced "E501", # Exploratory cells read better unwrapped @@ -744,15 +750,19 @@ external = [ "S605", "S608", # No untrusted input "T20", # `print()` shows results ] -# `print()` is ok in ad-hoc scripts -"scripts/**" = ["T20"] -# - ANN0, ANN2 => Type annotations are not strictly enforced -# - D106 => The `Meta` class inside the factory_boy models do not need a docstring -# - PLR0913, PLR0917 => `pytest` passes fixtures as arguments -# - S101 => `assert` statements are ok in the test suite -# - S311 => The `random` module is not used for cryptography -# - SLF001 => Tests may set up and inspect private members -"tests/**/*.py" = ["ANN0", "ANN2", "D106", "PLR0913", "PLR0917", "S101", "S311", "SLF001"] + +"scripts/**" = [ + "T20", # `print()` is ok in ad-hoc scripts +] + +"tests/**/*.py" = [ + "ANN0", "ANN2", # Type annotations are not strictly enforced + "D106", # The `Meta` class inside the factory_boy models do not need a docstring + "PLR0913", "PLR0917", # `pytest` passes fixtures as arguments + "S101", # `assert` statements are ok in the test suite + "S311", # The `random` module is not used for cryptography + "SLF001", # Tests may set up and inspect private members +] [tool.ruff.lint.flake8-pytest-style] # aligned with [tool.flake8] above From f9fce093d13a8f5b7d7d4d5ffbcaec54aeee893c Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 11:48:33 +0100 Subject: [PATCH 19/19] Skip the per-file ignores reformatting in `git blame` --- .git-blame-ignore-revs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 780741f..923a3e0 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -87,3 +87,6 @@ f90f263dab12013cc1353381e6ee3258df5e9176 # Refer to sources with "See:" in comments c18fc2ba59ed9286336da113604a98f423cbc32f + +# Put the `ruff` per-file ignores on separate lines +47a22f9587f94fa5bc2705302a3e29dca3701dcf