Clean up the comments and lint the notebooks #22

Merged
alexander merged 19 commits from lint-cleanups into develop 2026-12-03 12:26:19 +01:00
60 changed files with 308 additions and 308 deletions
Showing only changes of commit 049a5f6f62 - Show all commits

Remove periods from one-sentence comments

Alexander Hess 2026-12-03 10:03:26 +01:00
Signed by: alexander
GPG key ID: B46EDB4DFC26805D

View file

@ -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)

View file

@ -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",

View file

@ -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

View file

@ -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",

View file

@ -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",

View file

@ -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"]

View file

@ -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

View file

@ -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"

View file

@ -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,

View file

@ -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())

View file

@ -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()

View file

@ -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",

View file

@ -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

View file

@ -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"],

View file

@ -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

View file

@ -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]",

View file

@ -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_(

View file

@ -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",

View file

@ -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)

View file

@ -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,

Some files were not shown because too many files have changed in this diff Show more