Make mypy work again #8

Merged
alexander merged 16 commits from fix-mypy into develop 2026-11-30 14:13:44 +01:00
25 changed files with 769 additions and 228 deletions

View file

@ -3,7 +3,7 @@
By default, `uv run nox` runs the sessions that assure code quality: By default, `uv run nox` runs the sessions that assure code quality:
- "format": Format source files with `autoflake`, `black`, `flynt`, `isort`, and `ruff` - "format": Format source files with `autoflake`, `black`, `flynt`, `isort`, and `ruff`
- "lint": Lint source files with `flake8`, `isort`, and `ruff` - "lint": Lint source files with `flake8`, `isort`, `mypy`, and `ruff`
- "test": Run the test suite with `pytest` - "test": Run the test suite with `pytest`
- "doctest": Check if code snippets in the docstrings run - "doctest": Check if code snippets in the docstrings run
@ -176,17 +176,21 @@ def format_code(session: Session) -> None:
@nox.session(name="lint", python=MAIN_PYTHON) @nox.session(name="lint", python=MAIN_PYTHON)
def lint_code(session: Session) -> None: def lint_code(session: Session) -> None:
"""Lint source files with `flake8`, `isort`, and `ruff`. """Lint source files with `flake8`, `isort`, `mypy`, and `ruff`.
If no extra arguments are provided, all source files are linted. If no extra arguments are provided, all source files are linted.
Otherwise, they are interpreted as paths the linters work on recursively. Otherwise, they are interpreted as paths the linters work on recursively.
`mypy` always checks the entire package regardless
because it needs the whole program to follow types across modules.
""" """
start(session) start(session)
# The linters do not need `velofy` installed
# because they work on the source files directly
install_pinned( install_pinned(
session, session,
# `mypy` needs the dependencies of `velofy` installed
# because otherwise it treats missing packages as `Any`
".",
"flake8", "flake8",
"flake8-annotations", "flake8-annotations",
"flake8-bandit", "flake8-bandit",
@ -204,8 +208,7 @@ def lint_code(session: Session) -> None:
"flake8-todos", "flake8-todos",
"flake8-unused-arguments", "flake8-unused-arguments",
"isort", "isort",
# TODO: See comment on `mypy` below "mypy",
# 'mypy',
"pep8-naming", "pep8-naming",
"pydoclint[flake8]", "pydoclint[flake8]",
"ruff", "ruff",
@ -225,12 +228,8 @@ def lint_code(session: Session) -> None:
session.run("ruff", "--version") session.run("ruff", "--version")
session.run("ruff", "check", *locations) session.run("ruff", "check", *locations)
# TODO: Include `mypy` once it passes session.run("mypy", "--version")
# - Only for the *.py files to be packaged session.run("mypy", PACKAGE_LOCATION)
# - It then needs the developed package and its dependencies installed
# as it treats missing packages as `Any` and reports false successes
# session.run('mypy', '--version') # noqa:ERA001
# session.run('mypy', PACKAGE_LOCATION) # noqa:ERA001
@nox.session(name="test", python=MAIN_PYTHON) @nox.session(name="test", python=MAIN_PYTHON)

View file

@ -354,28 +354,30 @@ disallow_any_generics = true
# Disallow functions with incomplete type annotations # Disallow functions with incomplete type annotations
disallow_incomplete_defs = true disallow_incomplete_defs = true
# Disallow calling functions without type annotations # Disallow calling functions without type annotations ...
disallow_untyped_calls = true disallow_untyped_calls = true
# ... except for libraries without type annotations
untyped_calls_exclude = [
"folium",
]
# Disallow functions without type annotations (or incomplete annotations) # Disallow functions without type annotations (or incomplete annotations)
disallow_untyped_defs = true disallow_untyped_defs = true
# Require an error code in all "# type: ignore" comments
enable_error_code = ["ignore-without-code"]
# Report "# type: ignore" comments that are not needed anymore
warn_unused_ignores = true
[[tool.mypy.overrides]] [[tool.mypy.overrides]]
module = [ module = [
"folium.*",
"geopy.*", "geopy.*",
"googlemaps.*", "googlemaps.*",
"matplotlib.*",
"nox.*",
"numpy.*",
"ordered_set.*",
"packaging",
"pandas", "pandas",
"pytest",
"rpy2.*", "rpy2.*",
"sqlalchemy.*",
"statsmodels.*", "statsmodels.*",
"utm.*", "utm.*",
] ]

View file

@ -112,8 +112,8 @@ def tactical_heuristic( # noqa:C901,D417,DOC001
.filter(db.Grid.side_length == side_length) .filter(db.Grid.side_length == side_length)
.filter(db.Forecast.time_step == time_step) .filter(db.Forecast.time_step == time_step)
.filter(db.Forecast.train_horizon == train_horizon) .filter(db.Forecast.train_horizon == train_horizon)
.first() .scalar()
)[0] )
# ... or start `train_horizon` weeks after the first `Order` # ... or start `train_horizon` weeks after the first `Order`
# if no `Forecast`s are in the database yet. # if no `Forecast`s are in the database yet.
if last_predict_at is None: if last_predict_at is None:

View file

@ -35,8 +35,7 @@ def gridify() -> None: # pragma: no cover note:b1f68d24
click.echo(f" -> created {len(grid.pixels)} pixels") click.echo(f" -> created {len(grid.pixels)} pixels")
# Because the number of assigned addresses is the same across # Because the number of assigned addresses is the same across
# different `side_length`s, we can take any `grid` from the `city`. # different `side_length`s, we can take the last `grid` from the `city`.
grid = db.session.query(db.Grid).filter_by(city=city).first()
n_assigned = ( n_assigned = (
db.session.query(db.AddressPixelAssociation) db.session.query(db.AddressPixelAssociation)
.filter(db.AddressPixelAssociation.grid_id == grid.id) .filter(db.AddressPixelAssociation.grid_id == grid.id)

View file

@ -4,8 +4,6 @@ from velofy.db.addresses import Address
from velofy.db.addresses_addresses import Path from velofy.db.addresses_addresses import Path
from velofy.db.addresses_pixels import AddressPixelAssociation from velofy.db.addresses_pixels import AddressPixelAssociation
from velofy.db.cities import City from velofy.db.cities import City
from velofy.db.connection import connection
from velofy.db.connection import engine
from velofy.db.connection import session from velofy.db.connection import session
from velofy.db.couriers import Courier from velofy.db.couriers import Courier
from velofy.db.customers import Customer from velofy.db.customers import Customer

View file

@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
import datetime as dt
import functools import functools
from typing import Any from typing import Any
@ -22,17 +23,56 @@ class Address(meta.Base):
__tablename__ = "addresses" __tablename__ = "addresses"
# Columns # Columns
id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) id: orm.Mapped[int] = orm.mapped_column(
primary_id = sa.Column(sa.Integer, nullable=False, index=True) sa.Integer,
created_at = sa.Column(sa.DateTime, nullable=False) primary_key=True,
place_id = sa.Column(sa.Unicode(length=120), nullable=False, index=True) autoincrement=False,
latitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) )
longitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) primary_id: orm.Mapped[int] = orm.mapped_column(
city_id = sa.Column(sa.SmallInteger, nullable=False, index=True) sa.Integer,
city_name = sa.Column("city", sa.Unicode(length=25), nullable=False) nullable=False,
zip_code = sa.Column(sa.Integer, nullable=False, index=True) index=True,
street = sa.Column(sa.Unicode(length=80), nullable=False) )
floor = sa.Column(sa.SmallInteger) created_at: orm.Mapped[dt.datetime] = orm.mapped_column(
sa.DateTime,
nullable=False,
)
place_id: orm.Mapped[str] = orm.mapped_column(
sa.Unicode(length=120),
nullable=False,
index=True,
)
latitude: orm.Mapped[float] = orm.mapped_column(
postgresql.DOUBLE_PRECISION,
nullable=False,
)
longitude: orm.Mapped[float] = orm.mapped_column(
postgresql.DOUBLE_PRECISION,
nullable=False,
)
city_id: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
index=True,
)
city_name: orm.Mapped[str] = orm.mapped_column(
"city",
sa.Unicode(length=25),
nullable=False,
)
zip_code: orm.Mapped[int] = orm.mapped_column(
sa.Integer,
nullable=False,
index=True,
)
street: orm.Mapped[str] = orm.mapped_column(
sa.Unicode(length=80),
nullable=False,
)
floor: orm.Mapped[int | None] = orm.mapped_column(
sa.SmallInteger,
nullable=True,
)
# Constraints # Constraints
__table_args__ = ( __table_args__ = (
@ -157,7 +197,7 @@ class Address(meta.Base):
Returns: Returns:
`.city.map` for convenience in interactive usage `.city.map` for convenience in interactive usage
""" """
defaults = { defaults: dict[str, Any] = {
"color": f"{config.NEUTRAL_COLOR}", "color": f"{config.NEUTRAL_COLOR}",
"popup": f"{self.street}, {self.zip_code} {self.city_name}", "popup": f"{self.street}, {self.zip_code} {self.city_name}",
} }

View file

@ -39,16 +39,38 @@ class Path(meta.Base):
__tablename__ = "addresses_addresses" __tablename__ = "addresses_addresses"
# Columns # Columns
first_address_id = sa.Column(sa.Integer, primary_key=True) first_address_id: orm.Mapped[int] = orm.mapped_column(
second_address_id = sa.Column(sa.Integer, primary_key=True) sa.Integer,
city_id = sa.Column(sa.SmallInteger, nullable=False) primary_key=True,
)
second_address_id: orm.Mapped[int] = orm.mapped_column(
sa.Integer,
primary_key=True,
)
city_id: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
)
# Distances are measured in meters. # Distances are measured in meters.
air_distance = sa.Column(sa.Integer, nullable=False) air_distance: orm.Mapped[int] = orm.mapped_column(
bicycle_distance = sa.Column(sa.Integer, nullable=True) sa.Integer,
nullable=False,
)
bicycle_distance: orm.Mapped[int | None] = orm.mapped_column(
sa.Integer,
nullable=True,
)
# The duration is measured in seconds. # The duration is measured in seconds.
bicycle_duration = sa.Column(sa.Integer, nullable=True) 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 = sa.Column("directions", postgresql.JSON, nullable=True) _directions: orm.Mapped[str | None] = orm.mapped_column(
"directions",
postgresql.JSON,
nullable=True,
)
# Constraints # Constraints
__table_args__ = ( __table_args__ = (
@ -248,6 +270,9 @@ class Path(meta.Base):
Implementation detail: This property is cached as none of the Implementation detail: This property is cached as none of the
underlying attributes (i.e., `._directions`) are to be changed. underlying attributes (i.e., `._directions`) are to be changed.
""" """
if not self._directions:
raise RuntimeError("_directions is not set")
points = [utils.Location(*point) for point in json.loads(self._directions)] points = [utils.Location(*point) for point in json.loads(self._directions)]
for point in points: for point in points:
point.relate_to(self.first_address.city.southwest) point.relate_to(self.first_address.city.southwest)

View file

@ -19,10 +19,22 @@ class AddressPixelAssociation(meta.Base):
__tablename__ = "addresses_pixels" __tablename__ = "addresses_pixels"
# Columns # Columns
address_id = sa.Column(sa.Integer, primary_key=True) address_id: orm.Mapped[int] = orm.mapped_column(
city_id = sa.Column(sa.SmallInteger, nullable=False) sa.Integer,
grid_id = sa.Column(sa.SmallInteger, nullable=False) primary_key=True,
pixel_id = sa.Column(sa.Integer, primary_key=True) )
city_id: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
)
grid_id: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
)
pixel_id: orm.Mapped[int] = orm.mapped_column(
sa.Integer,
primary_key=True,
)
# Constraints # Constraints
__table_args__ = ( __table_args__ = (

View file

@ -21,22 +21,49 @@ class City(meta.Base):
__tablename__ = "cities" __tablename__ = "cities"
# Generic columns # Generic columns
id = sa.Column( id: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger, sa.SmallInteger,
primary_key=True, primary_key=True,
autoincrement=False, autoincrement=False,
) )
name = sa.Column(sa.Unicode(length=10), nullable=False) name: orm.Mapped[str] = orm.mapped_column(
kml = sa.Column(sa.UnicodeText, nullable=False) sa.Unicode(length=10),
nullable=False,
)
kml: orm.Mapped[str] = orm.mapped_column(
sa.UnicodeText,
nullable=False,
)
# Google Maps related columns # Google Maps related columns
center_latitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) center_latitude: orm.Mapped[float] = orm.mapped_column(
center_longitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) postgresql.DOUBLE_PRECISION,
northeast_latitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) nullable=False,
northeast_longitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) )
southwest_latitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) center_longitude: orm.Mapped[float] = orm.mapped_column(
southwest_longitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) postgresql.DOUBLE_PRECISION,
initial_zoom = sa.Column(sa.SmallInteger, nullable=False) nullable=False,
)
northeast_latitude: orm.Mapped[float] = orm.mapped_column(
postgresql.DOUBLE_PRECISION,
nullable=False,
)
northeast_longitude: orm.Mapped[float] = orm.mapped_column(
postgresql.DOUBLE_PRECISION,
nullable=False,
)
southwest_latitude: orm.Mapped[float] = orm.mapped_column(
postgresql.DOUBLE_PRECISION,
nullable=False,
)
southwest_longitude: orm.Mapped[float] = orm.mapped_column(
postgresql.DOUBLE_PRECISION,
nullable=False,
)
initial_zoom: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
)
# Relationships # Relationships
addresses = orm.relationship("Address", back_populates="city") addresses = orm.relationship("Address", back_populates="city")

View file

@ -1,28 +1,25 @@
"""Provide connection utils for the ORM layer. """Provide connection utils for the ORM layer.
This module defines fully configured `engine`, `connection`, and `session` This module defines a fully configured `session` object
objects to be used as globals within the `velofy` package. to be used as a global within the `velofy` package.
If a database is not guaranteed to be available, they are set to `None`. If a database is not guaranteed to be available, it is set to `None`.
That is the case on the CI server. That is the case on the CI server.
""" """
import os import os
from typing import cast
import sqlalchemy as sa import sqlalchemy as sa
from sqlalchemy import engine as engine_mod
from sqlalchemy import orm from sqlalchemy import orm
import velofy import velofy
if os.getenv("TESTING"): if os.getenv("TESTING"):
# Specify the types explicitly to make mypy happy. # Placeholder that the test fixtures replace
engine: engine_mod.Engine = None session: orm.Session = None # type: ignore[assignment]
connection: engine_mod.Connection = None
session: orm.Session = None
else: # pragma: no cover else: # pragma: no cover
engine = sa.create_engine(velofy.config.DATABASE_URI) engine = sa.create_engine(cast(str, velofy.config.DATABASE_URI))
connection = engine.connect() session = orm.Session(bind=engine)
session = orm.sessionmaker(bind=connection)()

View file

@ -1,5 +1,7 @@
"""Provide the ORM's `Courier` model.""" """Provide the ORM's `Courier` model."""
import datetime as dt
import sqlalchemy as sa import sqlalchemy as sa
from sqlalchemy import orm from sqlalchemy import orm
from sqlalchemy.dialects import postgresql from sqlalchemy.dialects import postgresql
@ -13,13 +15,36 @@ class Courier(meta.Base):
__tablename__ = "couriers" __tablename__ = "couriers"
# Columns # Columns
id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) id: orm.Mapped[int] = orm.mapped_column(
created_at = sa.Column(sa.DateTime, nullable=False) sa.Integer,
vehicle = sa.Column(sa.Unicode(length=10), nullable=False) primary_key=True,
historic_speed = sa.Column("speed", postgresql.DOUBLE_PRECISION, nullable=False) autoincrement=False,
capacity = sa.Column(sa.SmallInteger, nullable=False) )
pay_per_hour = sa.Column(sa.SmallInteger, nullable=False) created_at: orm.Mapped[dt.datetime] = orm.mapped_column(
pay_per_order = sa.Column(sa.SmallInteger, nullable=False) sa.DateTime,
nullable=False,
)
vehicle: orm.Mapped[str] = orm.mapped_column(
sa.Unicode(length=10),
nullable=False,
)
historic_speed: orm.Mapped[float] = orm.mapped_column(
"speed",
postgresql.DOUBLE_PRECISION,
nullable=False,
)
capacity: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
)
pay_per_hour: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
)
pay_per_order: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
)
# Constraints # Constraints
__table_args__ = ( __table_args__ = (

View file

@ -17,7 +17,11 @@ class Customer(meta.Base):
__tablename__ = "customers" __tablename__ = "customers"
# Columns # Columns
id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) id: orm.Mapped[int] = orm.mapped_column(
sa.Integer,
primary_key=True,
autoincrement=False,
)
def __repr__(self) -> str: def __repr__(self) -> str:
"""Non-literal text representation.""" """Non-literal text representation."""
@ -133,17 +137,17 @@ class Customer(meta.Base):
# Show the restaurant's name if there is only one. # Show the restaurant's name if there is only one.
# Otherwise, list all the restaurants' ID's. # Otherwise, list all the restaurants' ID's.
# We cannot show the `Order.restaurant.name` due to the aggregation. # We cannot show the `Order.restaurant.name` due to the aggregation.
restaurants = ( restaurants_at_address = (
db.session.query(db.Restaurant) db.session.query(db.Restaurant)
.join(db.Address, db.Restaurant.address_id == db.Address.id) .join(db.Address, db.Restaurant.address_id == db.Address.id)
.filter(db.Address.primary_id == address.id) .filter(db.Address.primary_id == address.id)
.all() .all()
) )
if len(restaurants) == 1: # type:ignore if len(restaurants_at_address) == 1:
restaurant = restaurants[0] # type:ignore restaurant = restaurants_at_address[0]
tooltip = f"{restaurant.name} (#{restaurant.id})" tooltip = f"{restaurant.name} (#{restaurant.id})"
else: else:
ids = ", ".join(f"#{r.id}" for r in restaurants) # type:ignore ids = ", ".join(f"#{r.id}" for r in restaurants_at_address)
tooltip = f"Restaurants {ids}" tooltip = f"Restaurants {ids}"
if order_counts: if order_counts:

View file

@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
import datetime as dt
import math import math
from typing import List from typing import List
@ -23,25 +24,63 @@ class Forecast(meta.Base):
__tablename__ = "forecasts" __tablename__ = "forecasts"
# Columns # Columns
id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) id: orm.Mapped[int] = orm.mapped_column(
pixel_id = sa.Column(sa.Integer, nullable=False, index=True) sa.Integer,
start_at = sa.Column(sa.DateTime, nullable=False) primary_key=True,
time_step = sa.Column(sa.SmallInteger, nullable=False) autoincrement=True,
train_horizon = sa.Column(sa.SmallInteger, nullable=False) )
model = sa.Column(sa.Unicode(length=20), nullable=False) pixel_id: orm.Mapped[int] = orm.mapped_column(
sa.Integer,
nullable=False,
index=True,
)
start_at: orm.Mapped[dt.datetime] = orm.mapped_column(
sa.DateTime,
nullable=False,
)
time_step: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
)
train_horizon: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
)
model: orm.Mapped[str] = orm.mapped_column(
sa.Unicode(length=20),
nullable=False,
)
# We also store the actual order counts for convenient retrieval. # We also store the actual order counts for convenient retrieval.
# A `UniqueConstraint` below ensures that redundant values that # A `UniqueConstraint` below ensures that redundant values that
# are to be expected are consistent across rows. # are to be expected are consistent across rows.
actual = sa.Column(sa.SmallInteger, nullable=False) actual: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
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. # The rounding is then done on the fly if required.
prediction = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) prediction: orm.Mapped[float] = orm.mapped_column(
postgresql.DOUBLE_PRECISION,
nullable=False,
)
# The confidence intervals are treated like the `.prediction`s # 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 = sa.Column(postgresql.DOUBLE_PRECISION, nullable=True) low80: orm.Mapped[float | None] = orm.mapped_column(
high80 = sa.Column(postgresql.DOUBLE_PRECISION, nullable=True) postgresql.DOUBLE_PRECISION,
low95 = sa.Column(postgresql.DOUBLE_PRECISION, nullable=True) nullable=True,
high95 = sa.Column(postgresql.DOUBLE_PRECISION, nullable=True) )
high80: orm.Mapped[float | None] = orm.mapped_column(
postgresql.DOUBLE_PRECISION,
nullable=True,
)
low95: orm.Mapped[float | None] = orm.mapped_column(
postgresql.DOUBLE_PRECISION,
nullable=True,
)
high95: orm.Mapped[float | None] = orm.mapped_column(
postgresql.DOUBLE_PRECISION,
nullable=True,
)
# Constraints # Constraints
__table_args__ = ( __table_args__ = (

View file

@ -22,13 +22,20 @@ class Grid(meta.Base):
__tablename__ = "grids" __tablename__ = "grids"
# Columns # Columns
id = sa.Column( id: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger, sa.SmallInteger,
primary_key=True, primary_key=True,
autoincrement=True, autoincrement=True,
) )
city_id = sa.Column(sa.SmallInteger, nullable=False) city_id: orm.Mapped[int] = orm.mapped_column(
side_length = sa.Column(sa.SmallInteger, nullable=False, unique=True) sa.SmallInteger,
nullable=False,
)
side_length: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
unique=True,
)
# Constraints # Constraints
__table_args__ = ( __table_args__ = (

View file

@ -1,6 +1,6 @@
"""Provide the ORM's `Order` model.""" """Provide the ORM's `Order` model."""
import datetime import datetime as dt
import folium import folium
import sqlalchemy as sa import sqlalchemy as sa
@ -18,64 +18,228 @@ class Order(meta.Base):
__tablename__ = "orders" __tablename__ = "orders"
# Generic columns # Generic columns
id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) id: orm.Mapped[int] = orm.mapped_column(
_delivery_id = sa.Column("delivery_id", sa.Integer, index=True, unique=True) sa.Integer,
customer_id = sa.Column(sa.Integer, nullable=False, index=True) primary_key=True,
placed_at = sa.Column(sa.DateTime, nullable=False, index=True) autoincrement=False,
ad_hoc = sa.Column(sa.Boolean, nullable=False) )
scheduled_delivery_at = sa.Column(sa.DateTime, index=True) _delivery_id: orm.Mapped[int | None] = orm.mapped_column(
scheduled_delivery_at_corrected = sa.Column(sa.Boolean, index=True) "delivery_id",
first_estimated_delivery_at = sa.Column(sa.DateTime) sa.Integer,
cancelled = sa.Column(sa.Boolean, nullable=False, index=True) nullable=True,
cancelled_at = sa.Column(sa.DateTime) index=True,
cancelled_at_corrected = sa.Column(sa.Boolean, index=True) unique=True,
)
customer_id: orm.Mapped[int] = orm.mapped_column(
sa.Integer,
nullable=False,
index=True,
)
placed_at: orm.Mapped[dt.datetime] = orm.mapped_column(
sa.DateTime,
nullable=False,
index=True,
)
ad_hoc: orm.Mapped[bool] = orm.mapped_column(
sa.Boolean,
nullable=False,
)
scheduled_delivery_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
index=True,
)
scheduled_delivery_at_corrected: orm.Mapped[bool | None] = orm.mapped_column(
sa.Boolean,
nullable=True,
index=True,
)
first_estimated_delivery_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
cancelled: orm.Mapped[bool] = orm.mapped_column(
sa.Boolean,
nullable=False,
index=True,
)
cancelled_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
cancelled_at_corrected: orm.Mapped[bool | None] = orm.mapped_column(
sa.Boolean,
nullable=True,
index=True,
)
# Price-related columns # Price-related columns
sub_total = sa.Column(sa.Integer, nullable=False) sub_total: orm.Mapped[int] = orm.mapped_column(
delivery_fee = sa.Column(sa.SmallInteger, nullable=False) sa.Integer,
total = sa.Column(sa.Integer, nullable=False) nullable=False,
)
delivery_fee: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
)
total: orm.Mapped[int] = orm.mapped_column(
sa.Integer,
nullable=False,
)
# Restaurant-related columns # Restaurant-related columns
restaurant_id = sa.Column(sa.SmallInteger, nullable=False, index=True) restaurant_id: orm.Mapped[int] = orm.mapped_column(
restaurant_notified_at = sa.Column(sa.DateTime) sa.SmallInteger,
restaurant_notified_at_corrected = sa.Column(sa.Boolean, index=True) nullable=False,
restaurant_confirmed_at = sa.Column(sa.DateTime) index=True,
restaurant_confirmed_at_corrected = sa.Column(sa.Boolean, index=True) )
estimated_prep_duration = sa.Column(sa.Integer, index=True) restaurant_notified_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
estimated_prep_duration_corrected = sa.Column(sa.Boolean, index=True) sa.DateTime,
estimated_prep_buffer = sa.Column(sa.Integer, nullable=False, index=True) nullable=True,
)
restaurant_notified_at_corrected: orm.Mapped[bool | None] = orm.mapped_column(
sa.Boolean,
nullable=True,
index=True,
)
restaurant_confirmed_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
restaurant_confirmed_at_corrected: orm.Mapped[bool | None] = orm.mapped_column(
sa.Boolean,
nullable=True,
index=True,
)
estimated_prep_duration: orm.Mapped[int | None] = orm.mapped_column(
sa.Integer,
nullable=True,
index=True,
)
estimated_prep_duration_corrected: orm.Mapped[bool | None] = orm.mapped_column(
sa.Boolean,
nullable=True,
index=True,
)
estimated_prep_buffer: orm.Mapped[int] = orm.mapped_column(
sa.Integer,
nullable=False,
index=True,
)
# Dispatch-related columns # Dispatch-related columns
courier_id = sa.Column(sa.Integer, index=True) courier_id: orm.Mapped[int | None] = orm.mapped_column(
dispatch_at = sa.Column(sa.DateTime) sa.Integer,
dispatch_at_corrected = sa.Column(sa.Boolean, index=True) nullable=True,
courier_notified_at = sa.Column(sa.DateTime) index=True,
courier_notified_at_corrected = sa.Column(sa.Boolean, index=True) )
courier_accepted_at = sa.Column(sa.DateTime) dispatch_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
courier_accepted_at_corrected = sa.Column(sa.Boolean, index=True) sa.DateTime,
utilization = sa.Column(sa.SmallInteger, nullable=False) nullable=True,
)
dispatch_at_corrected: orm.Mapped[bool | None] = orm.mapped_column(
sa.Boolean,
nullable=True,
index=True,
)
courier_notified_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
courier_notified_at_corrected: orm.Mapped[bool | None] = orm.mapped_column(
sa.Boolean,
nullable=True,
index=True,
)
courier_accepted_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
courier_accepted_at_corrected: orm.Mapped[bool | None] = orm.mapped_column(
sa.Boolean,
nullable=True,
index=True,
)
utilization: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
)
# Pickup-related columns # Pickup-related columns
pickup_address_id = sa.Column(sa.Integer, nullable=False, index=True) pickup_address_id: orm.Mapped[int] = orm.mapped_column(
reached_pickup_at = sa.Column(sa.DateTime) sa.Integer,
pickup_at = sa.Column(sa.DateTime) nullable=False,
pickup_at_corrected = sa.Column(sa.Boolean, index=True) index=True,
pickup_not_confirmed = sa.Column(sa.Boolean) )
left_pickup_at = sa.Column(sa.DateTime) reached_pickup_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
left_pickup_at_corrected = sa.Column(sa.Boolean, index=True) sa.DateTime,
nullable=True,
)
pickup_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
pickup_at_corrected: orm.Mapped[bool | None] = orm.mapped_column(
sa.Boolean,
nullable=True,
index=True,
)
pickup_not_confirmed: orm.Mapped[bool | None] = orm.mapped_column(
sa.Boolean,
nullable=True,
)
left_pickup_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
left_pickup_at_corrected: orm.Mapped[bool | None] = orm.mapped_column(
sa.Boolean,
nullable=True,
index=True,
)
# Delivery-related columns # Delivery-related columns
delivery_address_id = sa.Column(sa.Integer, nullable=False, index=True) delivery_address_id: orm.Mapped[int] = orm.mapped_column(
reached_delivery_at = sa.Column(sa.DateTime) sa.Integer,
delivery_at = sa.Column(sa.DateTime) nullable=False,
delivery_at_corrected = sa.Column(sa.Boolean, index=True) index=True,
delivery_not_confirmed = sa.Column(sa.Boolean) )
_courier_waited_at_delivery = sa.Column("courier_waited_at_delivery", sa.Boolean) reached_delivery_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
delivery_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
delivery_at_corrected: orm.Mapped[bool | None] = orm.mapped_column(
sa.Boolean,
nullable=True,
index=True,
)
delivery_not_confirmed: orm.Mapped[bool | None] = orm.mapped_column(
sa.Boolean,
nullable=True,
)
_courier_waited_at_delivery: orm.Mapped[bool | None] = orm.mapped_column(
"courier_waited_at_delivery",
sa.Boolean,
nullable=True,
)
# Statistical columns # Statistical columns
logged_delivery_distance = sa.Column(sa.SmallInteger, nullable=True) logged_delivery_distance: orm.Mapped[int | None] = orm.mapped_column(
logged_avg_speed = sa.Column(postgresql.DOUBLE_PRECISION, nullable=True) sa.SmallInteger,
logged_avg_speed_distance = sa.Column(sa.SmallInteger, nullable=True) nullable=True,
)
logged_avg_speed: orm.Mapped[float | None] = orm.mapped_column(
postgresql.DOUBLE_PRECISION,
nullable=True,
)
logged_avg_speed_distance: orm.Mapped[int | None] = orm.mapped_column(
sa.SmallInteger,
nullable=True,
)
# Constraints # Constraints
__table_args__ = ( __table_args__ = (
@ -363,7 +527,7 @@ class Order(meta.Base):
@property @property
def corrected(self) -> bool: def corrected(self) -> bool:
"""If any timestamp was corrected as compared to the original data.""" """If any timestamp was corrected as compared to the original data."""
return ( return bool(
self.scheduled_delivery_at_corrected # => too much logic self.scheduled_delivery_at_corrected # => too much logic
or self.cancelled_at_corrected or self.cancelled_at_corrected
or self.restaurant_notified_at_corrected or self.restaurant_notified_at_corrected
@ -373,13 +537,13 @@ class Order(meta.Base):
or self.courier_accepted_at_corrected or self.courier_accepted_at_corrected
or self.pickup_at_corrected or self.pickup_at_corrected
or self.left_pickup_at_corrected or self.left_pickup_at_corrected
or self.delivery_at_corrected or self.delivery_at_corrected,
) )
# Timing-related properties # Timing-related properties
@property @property
def time_to_accept(self) -> datetime.timedelta: def time_to_accept(self) -> dt.timedelta:
"""Time until the `.courier` accepted the order. """Time until the `.courier` accepted the order.
This measures the time it took the UDP to notify the `.courier` after dispatch. This measures the time it took the UDP to notify the `.courier` after dispatch.
@ -391,7 +555,7 @@ class Order(meta.Base):
return self.courier_accepted_at - self.dispatch_at return self.courier_accepted_at - self.dispatch_at
@property @property
def time_to_react(self) -> datetime.timedelta: def time_to_react(self) -> dt.timedelta:
"""Time the `.courier` took to accept an order. """Time the `.courier` took to accept an order.
A subset of `.time_to_accept`. A subset of `.time_to_accept`.
@ -403,7 +567,7 @@ class Order(meta.Base):
return self.courier_accepted_at - self.courier_notified_at return self.courier_accepted_at - self.courier_notified_at
@property @property
def time_to_pickup(self) -> datetime.timedelta: def time_to_pickup(self) -> dt.timedelta:
"""Time from the `.courier`'s acceptance to arrival at `.pickup_address`.""" """Time from the `.courier`'s acceptance to arrival at `.pickup_address`."""
if not self.courier_accepted_at: if not self.courier_accepted_at:
raise RuntimeError("courier_accepted_at is not set") raise RuntimeError("courier_accepted_at is not set")
@ -412,7 +576,7 @@ class Order(meta.Base):
return self.reached_pickup_at - self.courier_accepted_at return self.reached_pickup_at - self.courier_accepted_at
@property @property
def time_at_pickup(self) -> datetime.timedelta: def time_at_pickup(self) -> dt.timedelta:
"""Time the `.courier` stayed at the `.pickup_address`.""" """Time the `.courier` stayed at the `.pickup_address`."""
if not self.reached_pickup_at: if not self.reached_pickup_at:
raise RuntimeError("reached_pickup_at is not set") raise RuntimeError("reached_pickup_at is not set")
@ -421,71 +585,83 @@ class Order(meta.Base):
return self.pickup_at - self.reached_pickup_at return self.pickup_at - self.reached_pickup_at
@property @property
def scheduled_pickup_at(self) -> datetime.datetime: def scheduled_pickup_at(self) -> dt.datetime:
"""Point in time at which the pickup was scheduled.""" """Point in time at which the pickup was scheduled."""
if not self.restaurant_notified_at: if not self.restaurant_notified_at:
raise RuntimeError("restaurant_notified_at is not set") raise RuntimeError("restaurant_notified_at is not set")
if not self.estimated_prep_duration: if not self.estimated_prep_duration:
raise RuntimeError("estimated_prep_duration is not set") raise RuntimeError("estimated_prep_duration is not set")
delta = datetime.timedelta(seconds=self.estimated_prep_duration) delta = dt.timedelta(seconds=self.estimated_prep_duration)
return self.restaurant_notified_at + delta return self.restaurant_notified_at + delta
@property @property
def courier_early(self) -> datetime.timedelta: def courier_early(self) -> dt.timedelta:
"""Time by which the `.courier` is early for pickup. """Time by which the `.courier` is early for pickup.
Measured relative to `.scheduled_pickup_at`. Measured relative to `.scheduled_pickup_at`.
`datetime.timedelta(seconds=0)` if the `.courier` is on time or late. `dt.timedelta(seconds=0)` if the `.courier` is on time or late.
Goes together with `.courier_late`. Goes together with `.courier_late`.
""" """
if not self.reached_pickup_at:
raise RuntimeError("reached_pickup_at is not set")
return max( return max(
datetime.timedelta(), dt.timedelta(),
self.scheduled_pickup_at - self.reached_pickup_at, self.scheduled_pickup_at - self.reached_pickup_at,
) )
@property @property
def courier_late(self) -> datetime.timedelta: def courier_late(self) -> dt.timedelta:
"""Time by which the `.courier` is late for pickup. """Time by which the `.courier` is late for pickup.
Measured relative to `.scheduled_pickup_at`. Measured relative to `.scheduled_pickup_at`.
`datetime.timedelta(seconds=0)` if the `.courier` is on time or early. `dt.timedelta(seconds=0)` if the `.courier` is on time or early.
Goes together with `.courier_early`. Goes together with `.courier_early`.
""" """
if not self.reached_pickup_at:
raise RuntimeError("reached_pickup_at is not set")
return max( return max(
datetime.timedelta(), dt.timedelta(),
self.reached_pickup_at - self.scheduled_pickup_at, self.reached_pickup_at - self.scheduled_pickup_at,
) )
@property @property
def restaurant_early(self) -> datetime.timedelta: def restaurant_early(self) -> dt.timedelta:
"""Time by which the `.restaurant` is early for pickup. """Time by which the `.restaurant` is early for pickup.
Measured relative to `.scheduled_pickup_at`. Measured relative to `.scheduled_pickup_at`.
`datetime.timedelta(seconds=0)` if the `.restaurant` is on time or late. `dt.timedelta(seconds=0)` if the `.restaurant` is on time or late.
Goes together with `.restaurant_late`. Goes together with `.restaurant_late`.
""" """
return max(datetime.timedelta(), self.scheduled_pickup_at - self.pickup_at) if not self.pickup_at:
raise RuntimeError("pickup_at is not set")
return max(dt.timedelta(), self.scheduled_pickup_at - self.pickup_at)
@property @property
def restaurant_late(self) -> datetime.timedelta: def restaurant_late(self) -> dt.timedelta:
"""Time by which the `.restaurant` is late for pickup. """Time by which the `.restaurant` is late for pickup.
Measured relative to `.scheduled_pickup_at`. Measured relative to `.scheduled_pickup_at`.
`datetime.timedelta(seconds=0)` if the `.restaurant` is on time or early. `dt.timedelta(seconds=0)` if the `.restaurant` is on time or early.
Goes together with `.restaurant_early`. Goes together with `.restaurant_early`.
""" """
return max(datetime.timedelta(), self.pickup_at - self.scheduled_pickup_at) if not self.pickup_at:
raise RuntimeError("pickup_at is not set")
return max(dt.timedelta(), self.pickup_at - self.scheduled_pickup_at)
@property @property
def time_to_delivery(self) -> datetime.timedelta: def time_to_delivery(self) -> dt.timedelta:
"""Time the `.courier` took from `.pickup_address` to `.delivery_address`.""" """Time the `.courier` took from `.pickup_address` to `.delivery_address`."""
if not self.pickup_at: if not self.pickup_at:
raise RuntimeError("pickup_at is not set") raise RuntimeError("pickup_at is not set")
@ -494,7 +670,7 @@ class Order(meta.Base):
return self.reached_delivery_at - self.pickup_at return self.reached_delivery_at - self.pickup_at
@property @property
def time_at_delivery(self) -> datetime.timedelta: def time_at_delivery(self) -> dt.timedelta:
"""Time the `.courier` stayed at the `.delivery_address`.""" """Time the `.courier` stayed at the `.delivery_address`."""
if not self.reached_delivery_at: if not self.reached_delivery_at:
raise RuntimeError("reached_delivery_at is not set") raise RuntimeError("reached_delivery_at is not set")
@ -503,47 +679,57 @@ class Order(meta.Base):
return self.delivery_at - self.reached_delivery_at return self.delivery_at - self.reached_delivery_at
@property @property
def courier_waited_at_delivery(self) -> datetime.timedelta: def courier_waited_at_delivery(self) -> dt.timedelta:
"""Time the `.courier` waited at the `.delivery_address`.""" """Time the `.courier` waited at the `.delivery_address`."""
if self._courier_waited_at_delivery: if self._courier_waited_at_delivery:
return self.time_at_delivery return self.time_at_delivery
return datetime.timedelta() return dt.timedelta()
@property @property
def delivery_early(self) -> datetime.timedelta: def delivery_early(self) -> dt.timedelta:
"""Time by which a `.scheduled` order was early. """Time by which a `.scheduled` order was early.
Measured relative to `.scheduled_delivery_at`. Measured relative to `.scheduled_delivery_at`.
`datetime.timedelta(seconds=0)` if the delivery is on time or late. `dt.timedelta(seconds=0)` if the delivery is on time or late.
Goes together with `.delivery_late`. Goes together with `.delivery_late`.
""" """
if not self.scheduled: if not self.scheduled:
raise AttributeError("Makes sense only for scheduled orders") raise AttributeError("Makes sense only for scheduled orders")
return max(datetime.timedelta(), self.scheduled_delivery_at - self.delivery_at) if not self.scheduled_delivery_at:
raise RuntimeError("scheduled_delivery_at is not set")
if not self.delivery_at:
raise RuntimeError("delivery_at is not set")
return max(dt.timedelta(), self.scheduled_delivery_at - self.delivery_at)
@property @property
def delivery_late(self) -> datetime.timedelta: def delivery_late(self) -> dt.timedelta:
"""Time by which a `.scheduled` order was late. """Time by which a `.scheduled` order was late.
Measured relative to `.scheduled_delivery_at`. Measured relative to `.scheduled_delivery_at`.
`datetime.timedelta(seconds=0)` if the delivery is on time or early. `dt.timedelta(seconds=0)` if the delivery is on time or early.
Goes together with `.delivery_early`. Goes together with `.delivery_early`.
""" """
if not self.scheduled: if not self.scheduled:
raise AttributeError("Makes sense only for scheduled orders") raise AttributeError("Makes sense only for scheduled orders")
return max(datetime.timedelta(), self.delivery_at - self.scheduled_delivery_at) if not self.scheduled_delivery_at:
raise RuntimeError("scheduled_delivery_at is not set")
if not self.delivery_at:
raise RuntimeError("delivery_at is not set")
return max(dt.timedelta(), self.delivery_at - self.scheduled_delivery_at)
@property @property
def total_time(self) -> datetime.timedelta: def total_time(self) -> dt.timedelta:
"""Time from order placement to delivery for an `.ad_hoc` order.""" """Time from order placement to delivery for an `.ad_hoc` order."""
if self.scheduled: if self.scheduled:
raise AttributeError("Scheduled orders have no total_time") raise AttributeError("Scheduled orders have no total_time")
if self.cancelled: if self.cancelled:
raise RuntimeError("Cancelled orders have no total_time") raise RuntimeError("Cancelled orders have no total_time")
if not self.delivery_at:
raise RuntimeError("delivery_at is not set")
return self.delivery_at - self.placed_at return self.delivery_at - self.placed_at
# Other Methods # Other Methods

View file

@ -28,10 +28,26 @@ class Pixel(meta.Base):
__tablename__ = "pixels" __tablename__ = "pixels"
# Columns # Columns
id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) id: orm.Mapped[int] = orm.mapped_column(
grid_id = sa.Column(sa.SmallInteger, nullable=False, index=True) sa.Integer,
n_x = sa.Column(sa.SmallInteger, nullable=False, index=True) primary_key=True,
n_y = sa.Column(sa.SmallInteger, nullable=False, index=True) autoincrement=True,
)
grid_id: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
index=True,
)
n_x: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
index=True,
)
n_y: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
index=True,
)
# Constraints # Constraints
__table_args__ = ( __table_args__ = (
@ -208,17 +224,17 @@ class Pixel(meta.Base):
for address in addresses: for address in addresses:
# Show the restaurant's name if there is only one. # Show the restaurant's name if there is only one.
# Otherwise, list all the restaurants' ID's. # Otherwise, list all the restaurants' ID's.
restaurants = ( restaurants_at_address = (
db.session.query(db.Restaurant) db.session.query(db.Restaurant)
.join(db.Address, db.Restaurant.address_id == db.Address.id) .join(db.Address, db.Restaurant.address_id == db.Address.id)
.filter(db.Address.primary_id == address.id) .filter(db.Address.primary_id == address.id)
.all() .all()
) )
if len(restaurants) == 1: # type:ignore if len(restaurants_at_address) == 1:
restaurant = restaurants[0] # type:ignore restaurant = restaurants_at_address[0]
tooltip = f"{restaurant.name} (#{restaurant.id})" tooltip = f"{restaurant.name} (#{restaurant.id})"
else: else:
ids = ", ".join(f"#{r.id}" for r in restaurants) # type:ignore ids = ", ".join(f"#{r.id}" for r in restaurants_at_address)
tooltip = f"Restaurants {ids}" tooltip = f"Restaurants {ids}"
if order_counts: if order_counts:

View file

@ -2,6 +2,8 @@
from __future__ import annotations from __future__ import annotations
import datetime as dt
import sqlalchemy as sa import sqlalchemy as sa
from sqlalchemy import orm from sqlalchemy import orm
@ -14,43 +16,107 @@ class ReplayedOrder(meta.Base):
__tablename__ = "replayed_orders" __tablename__ = "replayed_orders"
# Generic columns # Generic columns
simulation_id = sa.Column(sa.Integer, primary_key=True) simulation_id: orm.Mapped[int] = orm.mapped_column(
actual_order_id = sa.Column(sa.Integer, primary_key=True) sa.Integer,
primary_key=True,
)
actual_order_id: orm.Mapped[int] = orm.mapped_column(
sa.Integer,
primary_key=True,
)
# `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` to ensure the type
# of the `ReplayedOrder` (i.e., ad-hoc or scheduled) is in line # of the `ReplayedOrder` (i.e., ad-hoc or scheduled) is in line
# with the `.actual` order. # with the `.actual` order.
ad_hoc = sa.Column(sa.Boolean, nullable=False) ad_hoc: orm.Mapped[bool] = orm.mapped_column(
placed_at = sa.Column(sa.DateTime, nullable=False) sa.Boolean,
nullable=False,
)
placed_at: orm.Mapped[dt.datetime] = orm.mapped_column(
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 = sa.Column(sa.DateTime) scheduled_delivery_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
# If an order is cancelled in a simulation, # 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 = sa.Column(sa.DateTime) cancelled_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
# Restaurant-related columns # Restaurant-related columns
estimated_prep_duration = sa.Column(sa.SmallInteger) estimated_prep_duration: orm.Mapped[int | None] = orm.mapped_column(
restaurant_notified_at = sa.Column(sa.DateTime) sa.SmallInteger,
restaurant_confirmed_at = sa.Column(sa.DateTime) nullable=True,
restaurant_ready_at = sa.Column(sa.DateTime) )
restaurant_notified_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
restaurant_confirmed_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
restaurant_ready_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
# Dispatch-related columns # Dispatch-related columns
dispatch_at = sa.Column(sa.DateTime) dispatch_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
first_estimated_delivery_at = sa.Column(sa.DateTime) sa.DateTime,
courier_id = sa.Column(sa.Integer, index=True) nullable=True,
courier_notified_at = sa.Column(sa.DateTime) )
courier_accepted_at = sa.Column(sa.DateTime) first_estimated_delivery_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
utilization = sa.Column(sa.SmallInteger) sa.DateTime,
nullable=True,
)
courier_id: orm.Mapped[int | None] = orm.mapped_column(
sa.Integer,
nullable=True,
index=True,
)
courier_notified_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
courier_accepted_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
utilization: orm.Mapped[int | None] = orm.mapped_column(
sa.SmallInteger,
nullable=True,
)
# Pickup-related columns # Pickup-related columns
reached_pickup_at = sa.Column(sa.DateTime) reached_pickup_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
pickup_at = sa.Column(sa.DateTime) sa.DateTime,
left_pickup_at = sa.Column(sa.DateTime) nullable=True,
)
pickup_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
left_pickup_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
# Delivery-related columns # Delivery-related columns
reached_delivery_at = sa.Column(sa.DateTime) reached_delivery_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
delivery_at = sa.Column(sa.DateTime) sa.DateTime,
nullable=True,
)
delivery_at: orm.Mapped[dt.datetime | None] = orm.mapped_column(
sa.DateTime,
nullable=True,
)
# Constraints # Constraints
__table_args__ = ( __table_args__ = (

View file

@ -15,11 +15,26 @@ class ReplaySimulation(meta.Base):
__tablename__ = "replay_simulations" __tablename__ = "replay_simulations"
# Columns # Columns
id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) id: orm.Mapped[int] = orm.mapped_column(
city_id = sa.Column(sa.SmallInteger, nullable=False, index=True) sa.Integer,
strategy = sa.Column(sa.Unicode(length=100), nullable=False, index=True) primary_key=True,
autoincrement=True,
)
city_id: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
index=True,
)
strategy: orm.Mapped[str] = orm.mapped_column(
sa.Unicode(length=100),
nullable=False,
index=True,
)
# `.run` may be used as random seed. # `.run` may be used as random seed.
run = sa.Column(sa.SmallInteger, nullable=False) run: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
)
# Constraints # Constraints
__table_args__ = ( __table_args__ = (

View file

@ -2,6 +2,8 @@
from __future__ import annotations from __future__ import annotations
import datetime as dt
import folium import folium
import sqlalchemy as sa import sqlalchemy as sa
from sqlalchemy import orm from sqlalchemy import orm
@ -22,15 +24,28 @@ class Restaurant(meta.Base):
__tablename__ = "restaurants" __tablename__ = "restaurants"
# Columns # Columns
id = sa.Column( id: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger, sa.SmallInteger,
primary_key=True, primary_key=True,
autoincrement=False, autoincrement=False,
) )
created_at = sa.Column(sa.DateTime, nullable=False) created_at: orm.Mapped[dt.datetime] = orm.mapped_column(
name = sa.Column(sa.Unicode(length=45), nullable=False) sa.DateTime,
address_id = sa.Column(sa.Integer, nullable=False, index=True) nullable=False,
estimated_prep_duration = sa.Column(sa.SmallInteger, nullable=False) )
name: orm.Mapped[str] = orm.mapped_column(
sa.Unicode(length=45),
nullable=False,
)
address_id: orm.Mapped[int] = orm.mapped_column(
sa.Integer,
nullable=False,
index=True,
)
estimated_prep_duration: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger,
nullable=False,
)
# Constraints # Constraints
__table_args__ = ( __table_args__ = (

View file

@ -141,7 +141,7 @@ class OrderHistory:
start_at; start_at;
""", # noqa:S608 """, # noqa:S608
), ),
con=db.connection, con=db.session.connection(),
index_col=["pixel_id", "start_at"], index_col=["pixel_id", "start_at"],
) )
@ -299,7 +299,7 @@ class OrderHistory:
# Take only the counts at the `predict_at` time. # Take only the counts at the `predict_at` time.
training_ts = intra_pixel.loc[ training_ts = intra_pixel.loc[
first_start_at : last_start_at : self._n_daily_time_steps, # type:ignore first_start_at : last_start_at : self._n_daily_time_steps,
"n_orders", "n_orders",
] ]
if len(training_ts) != frequency * train_horizon: if len(training_ts) != frequency * train_horizon:
@ -370,7 +370,7 @@ class OrderHistory:
# 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[ training_ts = intra_pixel.loc[
first_start_at:last_start_at, # type:ignore first_start_at:last_start_at,
"n_orders", "n_orders",
] ]
if len(training_ts) != frequency * train_horizon: if len(training_ts) != frequency * train_horizon:
@ -392,7 +392,7 @@ class OrderHistory:
) - dt.timedelta(minutes=self._time_step) ) - dt.timedelta(minutes=self._time_step)
actuals_ts = intra_pixel.loc[ actuals_ts = intra_pixel.loc[
first_prediction_at:last_prediction_at, # type:ignore first_prediction_at:last_prediction_at,
"n_orders", "n_orders",
] ]
if not len(actuals_ts): # pragma: no cover if not len(actuals_ts): # pragma: no cover
@ -470,7 +470,7 @@ class OrderHistory:
# Take all the counts between `first_train_day` and `last_train_day`, # 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[ training_ts = intra_pixel.loc[
first_start_at:last_start_at, # type:ignore first_start_at:last_start_at,
"n_orders", "n_orders",
] ]
n_time_steps_on_predict_day = ( n_time_steps_on_predict_day = (

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