From 049a5f6f62e05f08ffdcb6ce90c1f07ec3042871 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Thu, 3 Dec 2026 10:03:26 +0100 Subject: [PATCH] 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",