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

View file

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

View file

@ -175,8 +175,7 @@ class City(meta.Base):
).all() ).all()
for address in addresses: for address in addresses:
# Show the restaurant's name if there is only one. # Show a single restaurant's name, but only the IDs of several
# Otherwise, list all the restaurants' ID's.
restaurants = db.session.scalars( restaurants = db.session.scalars(
sa.select(db.Restaurant) sa.select(db.Restaurant)
.join(db.Address, db.Restaurant.address_id == db.Address.id) .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) .join(db.Address, db.Order.pickup_address_id == db.Address.id)
.where(db.Address.primary_id == address.id), .where(db.Address.primary_id == address.id),
).scalar_one() ).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: if n_orders >= 1000:
radius = 20 radius = 20
elif n_orders >= 500: 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)) return sa.create_engine(t.cast(str, velofy.config.DATABASE_URI))
# `scoped_session()` accepts any callable creating sessions # `scoped_session()` accepts any session factory but its stubs expect a `sessionmaker`
# 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( session: orm.scoped_session[orm.Session] = orm.scoped_session(
t.cast( t.cast(

View file

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

View file

@ -49,15 +49,14 @@ class Forecast(meta.Base):
sa.Unicode(length=20), sa.Unicode(length=20),
nullable=False, nullable=False,
) )
# We also store the actual order counts for convenient retrieval. # The actual order counts are stored for convenient retrieval
# A `UniqueConstraint` below ensures that redundant values # => A `UniqueConstraint` below keeps the redundant values consistent
# that are to be expected are consistent across rows.
actual: orm.Mapped[int] = orm.mapped_column( actual: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger, sa.SmallInteger,
nullable=False, nullable=False,
) )
# Raw `.prediction`s are stored as `float`s (possibly negative). # Raw `.prediction`s are stored as `float`s (possibly negative)
# The rounding is then done on the fly if required. # => They are rounded on the fly if required
prediction: orm.Mapped[float] = orm.mapped_column( prediction: orm.Mapped[float] = orm.mapped_column(
psql.DOUBLE_PRECISION, psql.DOUBLE_PRECISION,
nullable=False, nullable=False,
@ -243,8 +242,8 @@ class Forecast(meta.Base):
model=model, model=model,
actual=int(actual), actual=int(actual),
prediction=float(round(prediction, 5)), prediction=float(round(prediction, 5)),
# Explicit type casting. SQLAlchemy does not convert # `sqlalchemy` does not convert `float('NaN')`s into `None`s
# `float('NaN')`s into plain `None`s. # => Cast the values explicitly
low80=None if math.isnan(low80) else float(round(low80, 5)), low80=None if math.isnan(low80) else float(round(low80, 5)),
high80=None if math.isnan(high80) else float(round(high80, 5)), high80=None if math.isnan(high80) else float(round(high80, 5)),
low95=None if math.isnan(low95) else float(round(low95, 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 < 0
or address.y > city.total_y 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: if not_within_city_viewport:
continue continue
# Determine which `pixel` the `address` belongs to ... # Determine which `pixel` the `address` belongs to ...
n_x, n_y = address.x // side_length, address.y // side_length 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: if (n_x, n_y) not in pixels:
pixels[(n_x, n_y)] = db.Pixel(n_x=n_x, n_y=n_y) pixels[(n_x, n_y)] = db.Pixel(n_x=n_x, n_y=n_y)
grid.pixels.append(pixels[(n_x, n_y)]) grid.pixels.append(pixels[(n_x, n_y)])

View file

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

View file

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