Reword the comments in velofy.db

Each comment is one sentence or two short ones joined by "=>", without a final period.
This commit is contained in:
Alexander Hess 2026-12-03 10:38:28 +01:00
commit 1413d08ed9
Signed by: alexander
GPG key ID: B46EDB4DFC26805D
9 changed files with 43 additions and 71 deletions

View file

@ -144,9 +144,9 @@ class Path(meta.Base):
"""
paths = []
# We consider all 2-tuples of `Address`es. The symmetric graph is ...
# All 2-tuples of `Address`es suffice as the graph is symmetric ...
for pair in itertools.combinations(addresses, 2):
# ... implicitly enforced by a precedence constraint for the `.id`s.
# ... which a precedence constraint for the `.id`s enforces
first, second = sorted(pair, key=lambda address: address.id)
# If there is no `Path` object in the database ...
@ -155,7 +155,7 @@ class Path(meta.Base):
.where(cls.first_address == first)
.where(cls.second_address == second),
).first()
# ... create a new one.
# ... create a new one
if path is None:
air_distance = geo_distance.great_circle(
first.location.lat_lng,
@ -223,18 +223,16 @@ class Path(meta.Base):
mode="bicycling",
alternatives=False,
)
# Without "alternatives" and "waypoints", the `response` contains
# exactly one "route" that consists of exactly one "leg".
# Without "alternatives" and "waypoints",
# the `response` has exactly one "route" with exactly one "leg"
# Source: https://developers.google.com/maps/documentation/directions/get-directions#Legs # noqa:E501
route = response[0]["legs"][0]
self.bicycle_distance = route["distance"]["value"]
self.bicycle_duration = route["duration"]["value"]
# Each route consists of many "steps" that are instructions as to how to
# get from A to B. As a step's "start_location" may equal the previous step's
# "end_location", we use an `OrderedSet` to find the unique latitude-longitude
# pairs that make up the path from `.first_address` to `.second_address`.
# A step's "start_location" may equal the previous step's "end_location"
# => `OrderedSet` keeps only the unique points, in order
steps: ordered_set.OrderedSet[tuple[float, float]] = ordered_set.OrderedSet([])
for step in route["steps"]:
steps.add(

View file

@ -46,7 +46,7 @@ class AddressPixelAssociation(meta.Base):
onupdate="RESTRICT",
ondelete="RESTRICT",
),
# ... if their `.city` attributes match.
# ... if their `.city` attributes match
sa.ForeignKeyConstraint(
["grid_id", "city_id"],
["grids.id", "grids.city_id"],

View file

@ -175,8 +175,7 @@ class City(meta.Base):
).all()
for address in addresses:
# Show the restaurant's name if there is only one.
# Otherwise, list all the restaurants' ID's.
# Show a single restaurant's name, but only the IDs of several
restaurants = db.session.scalars(
sa.select(db.Restaurant)
.join(db.Address, db.Restaurant.address_id == db.Address.id)
@ -196,7 +195,7 @@ class City(meta.Base):
.join(db.Address, db.Order.pickup_address_id == db.Address.id)
.where(db.Address.primary_id == address.id),
).scalar_one()
# ... and adjust the size of the red dot on the `.map`.
# ... and adjust the size of the red dot on the `.map`
if n_orders >= 1000:
radius = 20
elif n_orders >= 500:

View file

@ -21,8 +21,7 @@ def get_engine() -> sa.Engine:
return sa.create_engine(t.cast(str, velofy.config.DATABASE_URI))
# `scoped_session()` accepts any callable creating sessions
# while its type stubs expect a `sessionmaker`
# `scoped_session()` accepts any session factory but its stubs expect a `sessionmaker`
# => The lambda defers creating the engine to first use
session: orm.scoped_session[orm.Session] = orm.scoped_session(
t.cast(

View file

@ -66,8 +66,8 @@ class Customer(meta.Base):
Returns:
`...city.map` for convenience in interactive usage
"""
# Note: a `Customer` may have more than one delivery `Address`es.
# That is not true for `Restaurant`s after the data cleaning.
# Unlike a `Restaurant` after the data cleaning,
# a `Customer` may have several delivery `Address`es
# Obtain all primary `Address`es
# where at least one delivery was made to `self`
@ -129,9 +129,8 @@ class Customer(meta.Base):
).all()
for address in pickup_addresses:
# Show the restaurant's name if there is only one.
# Otherwise, list all the restaurants' ID's.
# We cannot show the `Order.restaurant.name` due to the aggregation.
# Show a single restaurant's name, but only the IDs of several
# => `Order.restaurant.name` is not available after the aggregation
restaurants_at_address = db.session.scalars(
sa.select(db.Restaurant)
.join(db.Address, db.Restaurant.address_id == db.Address.id)

View file

@ -49,15 +49,14 @@ class Forecast(meta.Base):
sa.Unicode(length=20),
nullable=False,
)
# We also store the actual order counts for convenient retrieval.
# A `UniqueConstraint` below ensures that redundant values
# that are to be expected are consistent across rows.
# The actual order counts are stored for convenient retrieval
# => A `UniqueConstraint` below keeps the redundant values consistent
actual: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
)
# Raw `.prediction`s are stored as `float`s (possibly negative).
# The rounding is then done on the fly if required.
# Raw `.prediction`s are stored as `float`s (possibly negative)
# => They are rounded on the fly if required
prediction: orm.Mapped[float] = orm.mapped_column(
psql.DOUBLE_PRECISION,
nullable=False,
@ -243,8 +242,8 @@ class Forecast(meta.Base):
model=model,
actual=int(actual),
prediction=float(round(prediction, 5)),
# Explicit type casting. SQLAlchemy does not convert
# `float('NaN')`s into plain `None`s.
# `sqlalchemy` does not convert `float('NaN')`s into `None`s
# => Cast the values explicitly
low80=None if math.isnan(low80) else float(round(low80, 5)),
high80=None if math.isnan(high80) else float(round(high80, 5)),
low95=None if math.isnan(low95) else float(round(low95, 5)),

View file

@ -110,13 +110,13 @@ class Grid(meta.Base):
or address.y < 0
or address.y > city.total_y
)
# ... and, if so, the `address` does not belong to any `Pixel`.
# ... and, if so, the `address` does not belong to any `Pixel`
if not_within_city_viewport:
continue
# Determine which `pixel` the `address` belongs to ...
n_x, n_y = address.x // side_length, address.y // side_length
# ... and create a new `Pixel` object if necessary.
# ... and create a new `Pixel` object if necessary
if (n_x, n_y) not in pixels:
pixels[(n_x, n_y)] = db.Pixel(n_x=n_x, n_y=n_y)
grid.pixels.append(pixels[(n_x, n_y)])

View file

@ -223,8 +223,7 @@ class Pixel(meta.Base):
).all()
for address in addresses:
# Show the restaurant's name if there is only one.
# Otherwise, list all the restaurants' ID's.
# Show a single restaurant's name, but only the IDs of several
restaurants_at_address = db.session.scalars(
sa.select(db.Restaurant)
.join(db.Address, db.Restaurant.address_id == db.Address.id)
@ -244,7 +243,7 @@ class Pixel(meta.Base):
.join(db.Address, db.Order.pickup_address_id == db.Address.id)
.where(db.Address.primary_id == address.id),
).scalar_one()
# ... and adjust the size of the red dot on the `.map`.
# ... and adjust the size of the red dot on the `.map`
if n_orders >= 1000:
radius = 20
elif n_orders >= 500:

View file

@ -25,9 +25,8 @@ class ReplayedOrder(meta.Base):
)
# `Order`-type related columns
# `.ad_hoc` is part of a `ForeignKeyConstraint` to ensure the type
# of the `ReplayedOrder` (i.e., ad-hoc or scheduled) is in line
# with the `.actual` order
# `.ad_hoc` is part of a `ForeignKeyConstraint`
# => The type (i.e., ad-hoc or scheduled) matches the `.actual` order's
ad_hoc: orm.Mapped[bool] = orm.mapped_column(
sa.Boolean,
nullable=False,
@ -139,9 +138,8 @@ class ReplayedOrder(meta.Base):
),
# The check constraints model some of the assumptions made in the simulations
sa.CheckConstraint(
# Align the order's type, ad-hoc or scheduled, with the type of the
# `.actual` order and ensure the corresponding datetime column is set
# or not set
# The type (i.e., ad-hoc or scheduled) must match the `.actual` order's
# => The corresponding datetime column is set accordingly
"""
(
ad_hoc IS TRUE
@ -214,15 +212,8 @@ class ReplayedOrder(meta.Base):
name="scheduled_orders_not_within_30_minutes",
),
sa.CheckConstraint(
# A simulation must fill in at least all the timing and dispatch related
# columns, unless an order is cancelled in a run.
# Only `.estimated_prep_duration`, `.first_estimated_delivery_at`,
# and `.utilization` are truly optional.
# This constraint does allow missing columns for cancelled orders
# in any combination of the below columns. So, no precedence constraints
# are enforced (e.g., `.restaurant_notified_at` and `.restaurant_ready_at`
# could be set without `.restaurant_confirmed_at`). That is acceptable
# as cancelled orders are left out in the optimized KPIs.
# Simulated orders must fill in all timing and dispatch columns
# => Cancelled orders are exempt as the optimized KPIs exclude them
"""
cancelled_at IS NOT NULL
OR
@ -255,15 +246,8 @@ class ReplayedOrder(meta.Base):
name="orders_must_be_either_cancelled_or_fully_simulated",
),
sa.CheckConstraint(
# 23,487 out of the 660,608 orders were cancelled. In 685 of them, the
# cancellation occurred after the pickup (as modeled by the `.pickup_at`
# and `.left_pickup_at` columns, where the latter may be set with the
# former being unset). As a simplification, we only allow cancellations
# before the pickup in the simulations. Then, the restaurant throws away
# the meal and the courier is free for other orders right away. Orders
# cancelled after pickup in the actual data are assumed to be delivered
# to the customer's door (and then still accepted or thrown away by the
# customer). So, the courier becomes free only after the "fake" delivery.
# Simulations only allow cancellations before the pickup (simplification)
# => 685 of 23,487 actual cancellations after pickup count as delivered
"""
NOT ( -- Only occurred in 528 of 660,608 orders in the actual data.
cancelled_at IS NOT NULL
@ -292,30 +276,26 @@ class ReplayedOrder(meta.Base):
name="cancellations_may_only_occur_before_pickup",
),
sa.CheckConstraint(
# The actual `.estimated_prep_duration` and `.estimated_prep_buffer`
# are modeled together as only one value. Therefore, the individual
# upper limits of 2700 and 900 are added and result in 3600.
# One value models the actual prep duration and buffer together
# => Their upper limits of 2700 and 900 add up to 3600
"0 <= estimated_prep_duration AND estimated_prep_duration <= 3600",
name="estimated_prep_duration_between_0_and_3600",
),
sa.CheckConstraint(
# We still round estimates of the preparation time to whole minutes.
# Other estimates are unlikely to change the simulation results in
# a significant way.
# Prep time estimates are still rounded to whole minutes
# => Other estimates are unlikely to change the simulation results
"estimated_prep_duration % 60 = 0",
name="estimated_prep_duration_must_be_whole_minutes",
),
sa.CheckConstraint(
# If a simulation's `.strategy` models `.utilization`, it must be
# realistic. The value can be deduced from the actual order's
# courier's `.capacity` and the actual order's `.utilization`.
# A modeled `.utilization` must be realistic
# => It follows from the actual `.capacity` and `.utilization`
"0 <= utilization AND utilization <= 100",
name="utilization_between_0_and_100",
),
sa.CheckConstraint(
# The UDP is open from 11 am to 11 pm. So, before 11 am there is no
# activity. After 11 pm, the last orders of a day are all assumed to be
# dispatched before midnight.
# The UDP operates from 11 am to 11 pm
# => All orders are dispatched between 11 am and midnight
"""
NOT (
EXTRACT(HOUR FROM restaurant_notified_at) < 11
@ -326,9 +306,8 @@ class ReplayedOrder(meta.Base):
name="orders_dispatched_in_business_hours",
),
*(
# The timestamps must be in a logically correct order. That is the same
# as in the actual `Order` model with an extra `restaurant_ready_at` column
# and the non-simulated columns removed.
# The timestamps must be in the same order as in `Order`, extended by
# `.restaurant_ready_at` and without the non-simulated columns
sa.CheckConstraint(
constraint,
name=f"ordered_timestamps_{index}",