Use double quotes

This commit is contained in:
Alexander Hess 2026-11-28 03:08:55 +01:00
commit ea8f1a13e3
Signed by: alexander
GPG key ID: B46EDB4DFC26805D
17 changed files with 2464 additions and 2466 deletions

View file

@ -19,7 +19,7 @@ from velofy.db import utils
class Address(meta.Base):
"""An address of a `Customer` or a `Restaurant` on the UDP."""
__tablename__ = 'addresses'
__tablename__ = "addresses"
# Columns
id = sa.Column(sa.Integer, primary_key=True, autoincrement=False)
@ -29,7 +29,7 @@ class Address(meta.Base):
latitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False)
longitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False)
city_id = sa.Column(sa.SmallInteger, nullable=False, index=True)
city_name = sa.Column('city', sa.Unicode(length=25), nullable=False)
city_name = sa.Column("city", sa.Unicode(length=25), nullable=False)
zip_code = sa.Column(sa.Integer, nullable=False, index=True)
street = sa.Column(sa.Unicode(length=80), nullable=False)
floor = sa.Column(sa.SmallInteger)
@ -37,52 +37,52 @@ class Address(meta.Base):
# Constraints
__table_args__ = (
sa.ForeignKeyConstraint(
['primary_id'],
['addresses.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["primary_id"],
["addresses.id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.ForeignKeyConstraint(
['city_id'],
['cities.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["city_id"],
["cities.id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.CheckConstraint(
'-90 <= latitude AND latitude <= 90',
name='latitude_between_90_degrees',
"-90 <= latitude AND latitude <= 90",
name="latitude_between_90_degrees",
),
sa.CheckConstraint(
'-180 <= longitude AND longitude <= 180',
name='longitude_between_180_degrees',
"-180 <= longitude AND longitude <= 180",
name="longitude_between_180_degrees",
),
# Needed by a `ForeignKeyConstraint` in `AddressPixelAssociation`.
sa.UniqueConstraint('id', 'city_id'),
sa.UniqueConstraint("id", "city_id"),
sa.CheckConstraint(
'30000 <= zip_code AND zip_code <= 99999',
name='valid_zip_code',
"30000 <= zip_code AND zip_code <= 99999",
name="valid_zip_code",
),
sa.CheckConstraint('0 <= floor AND floor <= 40', name='realistic_floor'),
sa.CheckConstraint("0 <= floor AND floor <= 40", name="realistic_floor"),
)
# Relationships
city = orm.relationship('City', back_populates='addresses')
restaurants = orm.relationship('Restaurant', back_populates='address')
city = orm.relationship("City", back_populates="addresses")
restaurants = orm.relationship("Restaurant", back_populates="address")
orders_picked_up = orm.relationship(
'Order',
back_populates='pickup_address',
foreign_keys='[Order.pickup_address_id]',
"Order",
back_populates="pickup_address",
foreign_keys="[Order.pickup_address_id]",
)
orders_delivered = orm.relationship(
'Order',
back_populates='delivery_address',
foreign_keys='[Order.delivery_address_id]',
"Order",
back_populates="delivery_address",
foreign_keys="[Order.delivery_address_id]",
)
pixels = orm.relationship('AddressPixelAssociation', back_populates='address')
pixels = orm.relationship("AddressPixelAssociation", back_populates="address")
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}({street} in {city})>'.format(
return "<{cls}({street} in {city})>".format(
cls=self.__class__.__name__,
street=self.street,
city=self.city_name,
@ -162,8 +162,8 @@ class Address(meta.Base):
`.city.map` for convenience in interactive usage
"""
defaults = {
'color': f'{config.NEUTRAL_COLOR}',
'popup': f'{self.street}, {self.zip_code} {self.city_name}',
"color": f"{config.NEUTRAL_COLOR}",
"popup": f"{self.street}, {self.zip_code} {self.city_name}",
}
defaults.update(kwargs)

View file

@ -36,7 +36,7 @@ class Path(meta.Base):
https://docs.sqlalchemy.org/en/stable/orm/basic_relationships.html#association-object # noqa:E501
"""
__tablename__ = 'addresses_addresses'
__tablename__ = "addresses_addresses"
# Columns
first_address_id = sa.Column(sa.Integer, primary_key=True)
@ -48,56 +48,56 @@ class Path(meta.Base):
# The duration is measured in seconds.
bicycle_duration = sa.Column(sa.Integer, nullable=True)
# An array of latitude-longitude pairs approximating a courier's way.
_directions = sa.Column('directions', postgresql.JSON, nullable=True)
_directions = sa.Column("directions", postgresql.JSON, nullable=True)
# Constraints
__table_args__ = (
# The two `Address` objects must be in the same `.city`.
sa.ForeignKeyConstraint(
['first_address_id', 'city_id'],
['addresses.id', 'addresses.city_id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["first_address_id", "city_id"],
["addresses.id", "addresses.city_id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.ForeignKeyConstraint(
['second_address_id', 'city_id'],
['addresses.id', 'addresses.city_id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["second_address_id", "city_id"],
["addresses.id", "addresses.city_id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
# Each `Address`-`Address` pair only has one distance.
sa.UniqueConstraint('first_address_id', 'second_address_id'),
sa.UniqueConstraint("first_address_id", "second_address_id"),
sa.CheckConstraint(
'first_address_id < second_address_id',
name='distances_are_symmetric_for_bicycles',
"first_address_id < second_address_id",
name="distances_are_symmetric_for_bicycles",
),
sa.CheckConstraint(
'0 <= air_distance AND air_distance < 20000',
name='realistic_air_distance',
"0 <= air_distance AND air_distance < 20000",
name="realistic_air_distance",
),
sa.CheckConstraint(
'bicycle_distance < 25000', # `.bicycle_distance` may not be negative
name='realistic_bicycle_distance', # due to the constraint below.
"bicycle_distance < 25000", # `.bicycle_distance` may not be negative
name="realistic_bicycle_distance", # due to the constraint below.
),
sa.CheckConstraint(
'air_distance <= bicycle_distance',
name='air_distance_is_shortest',
"air_distance <= bicycle_distance",
name="air_distance_is_shortest",
),
sa.CheckConstraint(
'0 <= bicycle_duration AND bicycle_duration <= 3600',
name='realistic_bicycle_travel_time',
"0 <= bicycle_duration AND bicycle_duration <= 3600",
name="realistic_bicycle_travel_time",
),
)
# Relationships
first_address = orm.relationship(
'Address',
foreign_keys='[Path.first_address_id, Path.city_id]',
"Address",
foreign_keys="[Path.first_address_id, Path.city_id]",
)
second_address = orm.relationship(
'Address',
foreign_keys='[Path.second_address_id, Path.city_id]',
overlaps='first_address',
"Address",
foreign_keys="[Path.second_address_id, Path.city_id]",
overlaps="first_address",
)
@classmethod
@ -202,28 +202,28 @@ class Path(meta.Base):
response = client.directions(
origin=self.first_address.location.lat_lng,
destination=self.second_address.location.lat_lng,
mode='bicycling',
mode="bicycling",
alternatives=False,
)
# Without "alternatives" and "waypoints", the `response` contains
# exactly one "route" that consists of exactly one "leg".
# 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_duration = route['duration']['value']
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`.
steps: ordered_set.OrderedSet[Tuple[float, float]] = ordered_set.OrderedSet()
for step in route['steps']:
for step in route["steps"]:
steps.add(
(step['start_location']['lat'], step['start_location']['lng']),
(step["start_location"]["lat"], step["start_location"]["lng"]),
)
steps.add(
(step['end_location']['lat'], step['end_location']['lng']),
(step["end_location"]["lat"], step["end_location"]["lng"]),
)
steps.discard(self.first_address.location.lat_lng)
@ -258,11 +258,11 @@ class Path(meta.Base):
self,
*,
reverse: bool = False,
start_tooltip: str = 'Start',
end_tooltip: str = 'End',
start_color: str = 'green',
end_color: str = 'red',
path_color: str = 'black',
start_tooltip: str = "Start",
end_tooltip: str = "End",
start_color: str = "green",
end_color: str = "red",
path_color: str = "black",
) -> folium.Map: # pragma: no cover
"""Draw the `.waypoints` from `.first_address` to `.second_address`.

View file

@ -16,7 +16,7 @@ class AddressPixelAssociation(meta.Base):
https://docs.sqlalchemy.org/en/stable/orm/basic_relationships.html#association-object # noqa:E501
"""
__tablename__ = 'addresses_pixels'
__tablename__ = "addresses_pixels"
# Columns
address_id = sa.Column(sa.Integer, primary_key=True)
@ -28,29 +28,29 @@ class AddressPixelAssociation(meta.Base):
__table_args__ = (
# An `Address` can only be on a `Grid` ...
sa.ForeignKeyConstraint(
['address_id', 'city_id'],
['addresses.id', 'addresses.city_id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["address_id", "city_id"],
["addresses.id", "addresses.city_id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
# ... if their `.city` attributes match.
sa.ForeignKeyConstraint(
['grid_id', 'city_id'],
['grids.id', 'grids.city_id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["grid_id", "city_id"],
["grids.id", "grids.city_id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
# Each `Address` can only be on a `Grid` once.
sa.UniqueConstraint('address_id', 'grid_id'),
sa.UniqueConstraint("address_id", "grid_id"),
# An association must reference an existing `Grid`-`Pixel` pair.
sa.ForeignKeyConstraint(
['pixel_id', 'grid_id'],
['pixels.id', 'pixels.grid_id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["pixel_id", "grid_id"],
["pixels.id", "pixels.grid_id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
)
# Relationships
address = orm.relationship('Address', back_populates='pixels')
pixel = orm.relationship('Pixel', back_populates='addresses')
address = orm.relationship("Address", back_populates="pixels")
pixel = orm.relationship("Pixel", back_populates="addresses")

View file

@ -18,7 +18,7 @@ from velofy.db import utils
class City(meta.Base):
"""A city where the UDP operates in."""
__tablename__ = 'cities'
__tablename__ = "cities"
# Generic columns
id = sa.Column(
@ -39,16 +39,16 @@ class City(meta.Base):
initial_zoom = sa.Column(sa.SmallInteger, nullable=False)
# Relationships
addresses = orm.relationship('Address', back_populates='city')
grids = orm.relationship('Grid', back_populates='city')
replays = orm.relationship('ReplaySimulation', back_populates='city')
addresses = orm.relationship("Address", back_populates="city")
grids = orm.relationship("Grid", back_populates="city")
replays = orm.relationship("ReplaySimulation", back_populates="city")
# We do not implement a `.__init__()` method and use SQLAlchemy's default.
# The uninitialized attribute `._map` is computed on the fly. note:d334120ei
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}({name})>'.format(cls=self.__class__.__name__, name=self.name)
return "<{cls}({name})>".format(cls=self.__class__.__name__, name=self.name)
@functools.cached_property
def center(self) -> utils.Location:
@ -115,7 +115,7 @@ class City(meta.Base):
See docstring for `.clear_map()` for further info.
"""
if not hasattr(self, '_map'): # note:d334120e
if not hasattr(self, "_map"): # note:d334120e
self.clear_map()
return self._map
@ -157,10 +157,10 @@ class City(meta.Base):
.all()
)
if len(restaurants) == 1:
tooltip = f'{restaurants[0].name} (#{restaurants[0].id})'
tooltip = f"{restaurants[0].name} (#{restaurants[0].id})"
else:
tooltip = 'Restaurants ' + ', '.join(
f'#{restaurant.id}' for restaurant in restaurants
tooltip = "Restaurants " + ", ".join(
f"#{restaurant.id}" for restaurant in restaurants
)
if order_counts:
@ -183,7 +183,7 @@ class City(meta.Base):
else:
radius = 1
tooltip += f' | n_orders={n_orders}'
tooltip += f" | n_orders={n_orders}"
address.draw(
radius=radius,

View file

@ -16,7 +16,7 @@ from sqlalchemy import orm
import velofy
if os.getenv('TESTING'):
if os.getenv("TESTING"):
# Specify the types explicitly to make mypy happy.
engine: engine_mod.Engine = None
connection: engine_mod.Connection = None

View file

@ -10,13 +10,13 @@ from velofy.db import meta
class Courier(meta.Base):
"""A courier working for the UDP."""
__tablename__ = 'couriers'
__tablename__ = "couriers"
# Columns
id = sa.Column(sa.Integer, primary_key=True, autoincrement=False)
created_at = sa.Column(sa.DateTime, nullable=False)
vehicle = sa.Column(sa.Unicode(length=10), nullable=False)
historic_speed = sa.Column('speed', postgresql.DOUBLE_PRECISION, nullable=False)
historic_speed = sa.Column("speed", postgresql.DOUBLE_PRECISION, nullable=False)
capacity = sa.Column(sa.SmallInteger, nullable=False)
pay_per_hour = sa.Column(sa.SmallInteger, nullable=False)
pay_per_order = sa.Column(sa.SmallInteger, nullable=False)
@ -25,29 +25,29 @@ class Courier(meta.Base):
__table_args__ = (
sa.CheckConstraint(
"vehicle IN ('bicycle', 'motorcycle')",
name='available_vehicle_types',
name="available_vehicle_types",
),
sa.CheckConstraint('0 <= speed AND speed <= 30', name='realistic_speed'),
sa.CheckConstraint("0 <= speed AND speed <= 30", name="realistic_speed"),
sa.CheckConstraint(
'0 <= capacity AND capacity <= 200',
name='capacity_under_200_liters',
"0 <= capacity AND capacity <= 200",
name="capacity_under_200_liters",
),
sa.CheckConstraint(
'0 <= pay_per_hour AND pay_per_hour <= 1500',
name='realistic_pay_per_hour',
"0 <= pay_per_hour AND pay_per_hour <= 1500",
name="realistic_pay_per_hour",
),
sa.CheckConstraint(
'0 <= pay_per_order AND pay_per_order <= 650',
name='realistic_pay_per_order',
"0 <= pay_per_order AND pay_per_order <= 650",
name="realistic_pay_per_order",
),
)
# Relationships
orders = orm.relationship('Order', back_populates='courier')
orders = orm.relationship("Order", back_populates="courier")
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}(#{courier_id})>'.format(
return "<{cls}(#{courier_id})>".format(
cls=self.__class__.__name__,
courier_id=self.id,
)

View file

@ -14,20 +14,20 @@ from velofy.db import meta
class Customer(meta.Base):
"""A customer of the UDP."""
__tablename__ = 'customers'
__tablename__ = "customers"
# Columns
id = sa.Column(sa.Integer, primary_key=True, autoincrement=False)
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}(#{customer_id})>'.format(
return "<{cls}(#{customer_id})>".format(
cls=self.__class__.__name__,
customer_id=self.id,
)
# Relationships
orders = orm.relationship('Order', back_populates='customer')
orders = orm.relationship("Order", back_populates="customer")
def clear_map(self) -> Customer: # pragma: no cover
"""Shortcut to the `...city.clear_map()` method.
@ -108,7 +108,7 @@ class Customer(meta.Base):
color=config.CUSTOMER_COLOR,
fill_color=config.CUSTOMER_COLOR,
fill_opacity=0.3,
tooltip=f'n_orders={n_orders}',
tooltip=f"n_orders={n_orders}",
)
else:
@ -144,11 +144,11 @@ class Customer(meta.Base):
)
if len(restaurants) == 1: # type:ignore
tooltip = (
f'{restaurants[0].name} (#{restaurants[0].id})' # type:ignore
f"{restaurants[0].name} (#{restaurants[0].id})" # type:ignore
)
else:
tooltip = 'Restaurants ' + ', '.join(
f'#{restaurant.id}' for restaurant in restaurants # type:ignore
tooltip = "Restaurants " + ", ".join(
f"#{restaurant.id}" for restaurant in restaurants # type:ignore
)
if order_counts:
@ -170,7 +170,7 @@ class Customer(meta.Base):
else:
radius = 1
tooltip += f' | n_orders={n_orders}'
tooltip += f" | n_orders={n_orders}"
address.draw(
radius=radius,

View file

@ -20,7 +20,7 @@ class Forecast(meta.Base):
the `.model` and `.actual` hold redundant values.
"""
__tablename__ = 'forecasts'
__tablename__ = "forecasts"
# Columns
id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
@ -46,10 +46,10 @@ class Forecast(meta.Base):
# Constraints
__table_args__ = (
sa.ForeignKeyConstraint(
['pixel_id'],
['pixels.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["pixel_id"],
["pixels.id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.CheckConstraint(
"""
@ -59,26 +59,26 @@ class Forecast(meta.Base):
EXTRACT(HOUR FROM start_at) > 22
)
""",
name='start_at_must_be_within_operating_hours',
name="start_at_must_be_within_operating_hours",
),
sa.CheckConstraint(
'CAST(EXTRACT(MINUTES FROM start_at) AS INTEGER) % 15 = 0',
name='start_at_minutes_must_be_quarters_of_the_hour',
"CAST(EXTRACT(MINUTES FROM start_at) AS INTEGER) % 15 = 0",
name="start_at_minutes_must_be_quarters_of_the_hour",
),
sa.CheckConstraint(
'EXTRACT(SECONDS FROM start_at) = 0',
name='start_at_allows_no_seconds',
"EXTRACT(SECONDS FROM start_at) = 0",
name="start_at_allows_no_seconds",
),
sa.CheckConstraint(
'CAST(EXTRACT(MICROSECONDS FROM start_at) AS INTEGER) % 1000000 = 0',
name='start_at_allows_no_microseconds',
"CAST(EXTRACT(MICROSECONDS FROM start_at) AS INTEGER) % 1000000 = 0",
name="start_at_allows_no_microseconds",
),
sa.CheckConstraint('time_step > 0', name='time_step_must_be_positive'),
sa.CheckConstraint("time_step > 0", name="time_step_must_be_positive"),
sa.CheckConstraint(
'train_horizon > 0',
name='training_horizon_must_be_positive',
"train_horizon > 0",
name="training_horizon_must_be_positive",
),
sa.CheckConstraint('actual >= 0', name='actuals_must_be_non_negative'),
sa.CheckConstraint("actual >= 0", name="actuals_must_be_non_negative"),
sa.CheckConstraint(
"""
NOT (
@ -91,7 +91,7 @@ class Forecast(meta.Base):
low95 IS NOT NULL AND high95 IS NULL
)
""",
name='ci_upper_and_lower_bounds',
name="ci_upper_and_lower_bounds",
),
sa.CheckConstraint(
"""
@ -105,7 +105,7 @@ class Forecast(meta.Base):
prediction > high95
)
""",
name='prediction_must_be_within_ci',
name="prediction_must_be_within_ci",
),
sa.CheckConstraint(
"""
@ -115,7 +115,7 @@ class Forecast(meta.Base):
low95 > high95
)
""",
name='ci_upper_bound_greater_than_lower_bound',
name="ci_upper_bound_greater_than_lower_bound",
),
sa.CheckConstraint(
"""
@ -125,24 +125,24 @@ class Forecast(meta.Base):
high80 > high95
)
""",
name='ci95_must_be_wider_than_ci80',
name="ci95_must_be_wider_than_ci80",
),
# There can be only one prediction per forecasting setting.
sa.UniqueConstraint(
'pixel_id',
'start_at',
'time_step',
'train_horizon',
'model',
"pixel_id",
"start_at",
"time_step",
"train_horizon",
"model",
),
)
# Relationships
pixel = orm.relationship('Pixel', back_populates='forecasts')
pixel = orm.relationship("Pixel", back_populates="forecasts")
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}: {prediction} for pixel ({n_x}|{n_y}) at {start_at}>'.format(
return "<{cls}: {prediction} for pixel ({n_x}|{n_y}) at {start_at}>".format(
cls=self.__class__.__name__,
prediction=self.prediction,
n_x=self.pixel.n_x,
@ -187,16 +187,16 @@ class Forecast(meta.Base):
for timestamp_idx in data.index:
start_at = timestamp_idx.to_pydatetime()
actual = int(data.loc[timestamp_idx, 'actual'])
prediction = float(round(data.loc[timestamp_idx, 'prediction'], 5))
actual = int(data.loc[timestamp_idx, "actual"])
prediction = float(round(data.loc[timestamp_idx, "prediction"], 5))
# Explicit type casting. SQLAlchemy does not convert
# `float('NaN')`s into plain `None`s.
low80 = data.loc[timestamp_idx, 'low80']
high80 = data.loc[timestamp_idx, 'high80']
low95 = data.loc[timestamp_idx, 'low95']
high95 = data.loc[timestamp_idx, 'high95']
low80 = data.loc[timestamp_idx, "low80"]
high80 = data.loc[timestamp_idx, "high80"]
low95 = data.loc[timestamp_idx, "low95"]
high95 = data.loc[timestamp_idx, "high95"]
if math.isnan(low80):
low80 = None

View file

@ -19,7 +19,7 @@ class Grid(meta.Base):
That is configures via the `Grid.side_length` attribute.
"""
__tablename__ = 'grids'
__tablename__ = "grids"
# Columns
id = sa.Column(
@ -33,25 +33,25 @@ class Grid(meta.Base):
# Constraints
__table_args__ = (
sa.ForeignKeyConstraint(
['city_id'],
['cities.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["city_id"],
["cities.id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
# Each `Grid`, characterized by its `.side_length`,
# may only exists once for a given `.city`.
sa.UniqueConstraint('city_id', 'side_length'),
sa.UniqueConstraint("city_id", "side_length"),
# Needed by a `ForeignKeyConstraint` in `address_pixel_association`.
sa.UniqueConstraint('id', 'city_id'),
sa.UniqueConstraint("id", "city_id"),
)
# Relationships
city = orm.relationship('City', back_populates='grids')
pixels = orm.relationship('Pixel', back_populates='grid')
city = orm.relationship("City", back_populates="grids")
pixels = orm.relationship("Pixel", back_populates="grid")
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}: {area} sqr. km>'.format(
return "<{cls}: {area} sqr. km>".format(
cls=self.__class__.__name__,
area=self.pixel_area,
)

View file

@ -12,11 +12,11 @@ Base: Any = orm.declarative_base(
metadata=sa.MetaData(
schema=velofy.config.CLEAN_SCHEMA,
naming_convention={
'pk': 'pk_%(table_name)s',
'fk': 'fk_%(table_name)s_to_%(referred_table_name)s_via_%(column_0_N_name)s', # noqa:E501
'uq': 'uq_%(table_name)s_on_%(column_0_N_name)s',
'ix': 'ix_%(table_name)s_on_%(column_0_N_name)s',
'ck': 'ck_%(table_name)s_on_%(constraint_name)s',
"pk": "pk_%(table_name)s",
"fk": "fk_%(table_name)s_to_%(referred_table_name)s_via_%(column_0_N_name)s", # noqa:E501
"uq": "uq_%(table_name)s_on_%(column_0_N_name)s",
"ix": "ix_%(table_name)s_on_%(column_0_N_name)s",
"ck": "ck_%(table_name)s_on_%(constraint_name)s",
},
),
)

View file

@ -15,11 +15,11 @@ from velofy.db import meta
class Order(meta.Base):
"""An order by a `Customer` of the UDP."""
__tablename__ = 'orders'
__tablename__ = "orders"
# Generic columns
id = sa.Column(sa.Integer, primary_key=True, autoincrement=False)
_delivery_id = sa.Column('delivery_id', sa.Integer, index=True, unique=True)
_delivery_id = sa.Column("delivery_id", sa.Integer, index=True, unique=True)
customer_id = sa.Column(sa.Integer, nullable=False, index=True)
placed_at = sa.Column(sa.DateTime, nullable=False, index=True)
ad_hoc = sa.Column(sa.Boolean, nullable=False)
@ -70,7 +70,7 @@ class Order(meta.Base):
delivery_at = sa.Column(sa.DateTime)
delivery_at_corrected = sa.Column(sa.Boolean, index=True)
delivery_not_confirmed = sa.Column(sa.Boolean)
_courier_waited_at_delivery = sa.Column('courier_waited_at_delivery', sa.Boolean)
_courier_waited_at_delivery = sa.Column("courier_waited_at_delivery", sa.Boolean)
# Statistical columns
logged_delivery_distance = sa.Column(sa.SmallInteger, nullable=True)
@ -80,46 +80,46 @@ class Order(meta.Base):
# Constraints
__table_args__ = (
sa.ForeignKeyConstraint(
['customer_id'],
['customers.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["customer_id"],
["customers.id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.ForeignKeyConstraint(
['courier_id'],
['couriers.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["courier_id"],
["couriers.id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.ForeignKeyConstraint(
['pickup_address_id'],
['addresses.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["pickup_address_id"],
["addresses.id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.ForeignKeyConstraint(
# This foreign key ensures that there is only
# one `.pickup_address` per `.restaurant`
['restaurant_id', 'pickup_address_id'],
['restaurants.id', 'restaurants.address_id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["restaurant_id", "pickup_address_id"],
["restaurants.id", "restaurants.address_id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.ForeignKeyConstraint(
['delivery_address_id'],
['addresses.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["delivery_address_id"],
["addresses.id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
# Needed by a `ForeignKeyConstraint` in `ReplayedOrder`.
sa.UniqueConstraint('id', 'ad_hoc'),
sa.UniqueConstraint("id", "ad_hoc"),
sa.CheckConstraint(
"""
(ad_hoc IS TRUE AND scheduled_delivery_at IS NULL)
OR
(ad_hoc IS FALSE AND scheduled_delivery_at IS NOT NULL)
""",
name='either_ad_hoc_or_scheduled_order',
name="either_ad_hoc_or_scheduled_order",
),
sa.CheckConstraint(
"""
@ -132,7 +132,7 @@ class Order(meta.Base):
)
)
""",
name='ad_hoc_orders_within_business_hours',
name="ad_hoc_orders_within_business_hours",
),
sa.CheckConstraint(
"""
@ -153,7 +153,7 @@ class Order(meta.Base):
)
)
""",
name='scheduled_orders_within_business_hours',
name="scheduled_orders_within_business_hours",
),
sa.CheckConstraint(
"""
@ -167,7 +167,7 @@ class Order(meta.Base):
= 0
)
""",
name='scheduled_orders_must_be_at_quarters_of_an_hour',
name="scheduled_orders_must_be_at_quarters_of_an_hour",
),
sa.CheckConstraint(
"""
@ -175,7 +175,7 @@ class Order(meta.Base):
EXTRACT(EPOCH FROM scheduled_delivery_at - placed_at) < 1800
)
""",
name='scheduled_orders_not_within_30_minutes',
name="scheduled_orders_not_within_30_minutes",
),
sa.CheckConstraint(
"""
@ -185,7 +185,7 @@ class Order(meta.Base):
cancelled_at IS NOT NULL
)
""",
name='only_cancelled_orders_may_have_cancelled_at',
name="only_cancelled_orders_may_have_cancelled_at",
),
sa.CheckConstraint(
"""
@ -195,27 +195,27 @@ class Order(meta.Base):
delivery_at IS NOT NULL
)
""",
name='cancelled_orders_must_not_be_delivered',
name="cancelled_orders_must_not_be_delivered",
),
sa.CheckConstraint(
'0 <= estimated_prep_duration AND estimated_prep_duration <= 2700',
name='estimated_prep_duration_between_0_and_2700',
"0 <= estimated_prep_duration AND estimated_prep_duration <= 2700",
name="estimated_prep_duration_between_0_and_2700",
),
sa.CheckConstraint(
'estimated_prep_duration % 60 = 0',
name='estimated_prep_duration_must_be_whole_minutes',
"estimated_prep_duration % 60 = 0",
name="estimated_prep_duration_must_be_whole_minutes",
),
sa.CheckConstraint(
'0 <= estimated_prep_buffer AND estimated_prep_buffer <= 900',
name='estimated_prep_buffer_between_0_and_900',
"0 <= estimated_prep_buffer AND estimated_prep_buffer <= 900",
name="estimated_prep_buffer_between_0_and_900",
),
sa.CheckConstraint(
'estimated_prep_buffer % 60 = 0',
name='estimated_prep_buffer_must_be_whole_minutes',
"estimated_prep_buffer % 60 = 0",
name="estimated_prep_buffer_must_be_whole_minutes",
),
sa.CheckConstraint(
'0 <= utilization AND utilization <= 100',
name='utilization_between_0_and_100',
"0 <= utilization AND utilization <= 100",
name="utilization_between_0_and_100",
),
*(
sa.CheckConstraint(
@ -226,21 +226,21 @@ class Order(meta.Base):
OR
({column} IS NOT NULL AND {column}_corrected IS NOT NULL)
""",
name=f'corrections_only_for_set_value_{index}',
name=f"corrections_only_for_set_value_{index}",
)
for index, column in enumerate(
(
'scheduled_delivery_at',
'cancelled_at',
'restaurant_notified_at',
'restaurant_confirmed_at',
'estimated_prep_duration',
'dispatch_at',
'courier_notified_at',
'courier_accepted_at',
'pickup_at',
'left_pickup_at',
'delivery_at',
"scheduled_delivery_at",
"cancelled_at",
"restaurant_notified_at",
"restaurant_confirmed_at",
"estimated_prep_duration",
"dispatch_at",
"courier_notified_at",
"courier_accepted_at",
"pickup_at",
"left_pickup_at",
"delivery_at",
),
)
),
@ -251,9 +251,9 @@ class Order(meta.Base):
OR
({event}_at IS NOT NULL AND {event}_not_confirmed IS NOT NULL)
""",
name=f'{event}_not_confirmed_only_if_{event}',
name=f"{event}_not_confirmed_only_if_{event}",
)
for event in ('pickup', 'delivery')
for event in ("pickup", "delivery")
),
sa.CheckConstraint(
"""
@ -261,92 +261,92 @@ class Order(meta.Base):
OR
(delivery_at IS NOT NULL AND courier_waited_at_delivery IS NOT NULL)
""",
name='courier_waited_at_delivery_only_if_delivery',
name="courier_waited_at_delivery_only_if_delivery",
),
*(
sa.CheckConstraint(
constraint,
name='ordered_timestamps_{index}'.format(index=index),
name="ordered_timestamps_{index}".format(index=index),
)
for index, constraint in enumerate(
(
'placed_at < scheduled_delivery_at',
'placed_at < first_estimated_delivery_at',
'placed_at < cancelled_at',
'placed_at < restaurant_notified_at',
'placed_at < restaurant_confirmed_at',
'placed_at < dispatch_at',
'placed_at < courier_notified_at',
'placed_at < courier_accepted_at',
'placed_at < reached_pickup_at',
'placed_at < pickup_at',
'placed_at < left_pickup_at',
'placed_at < reached_delivery_at',
'placed_at < delivery_at',
'cancelled_at > restaurant_notified_at',
'cancelled_at > restaurant_confirmed_at',
'cancelled_at > dispatch_at',
'cancelled_at > courier_notified_at',
'cancelled_at > courier_accepted_at',
'cancelled_at > reached_pickup_at',
'cancelled_at > pickup_at',
'cancelled_at > left_pickup_at',
'cancelled_at > reached_delivery_at',
'restaurant_notified_at < restaurant_confirmed_at',
'restaurant_notified_at < pickup_at',
'restaurant_confirmed_at < pickup_at',
'dispatch_at < courier_notified_at',
'dispatch_at < courier_accepted_at',
'dispatch_at < reached_pickup_at',
'dispatch_at < pickup_at',
'dispatch_at < left_pickup_at',
'dispatch_at < reached_delivery_at',
'dispatch_at < delivery_at',
'courier_notified_at < courier_accepted_at',
'courier_notified_at < reached_pickup_at',
'courier_notified_at < pickup_at',
'courier_notified_at < left_pickup_at',
'courier_notified_at < reached_delivery_at',
'courier_notified_at < delivery_at',
'courier_accepted_at < reached_pickup_at',
'courier_accepted_at < pickup_at',
'courier_accepted_at < left_pickup_at',
'courier_accepted_at < reached_delivery_at',
'courier_accepted_at < delivery_at',
'reached_pickup_at < pickup_at',
'reached_pickup_at < left_pickup_at',
'reached_pickup_at < reached_delivery_at',
'reached_pickup_at < delivery_at',
'pickup_at < left_pickup_at',
'pickup_at < reached_delivery_at',
'pickup_at < delivery_at',
'left_pickup_at < reached_delivery_at',
'left_pickup_at < delivery_at',
'reached_delivery_at < delivery_at',
"placed_at < scheduled_delivery_at",
"placed_at < first_estimated_delivery_at",
"placed_at < cancelled_at",
"placed_at < restaurant_notified_at",
"placed_at < restaurant_confirmed_at",
"placed_at < dispatch_at",
"placed_at < courier_notified_at",
"placed_at < courier_accepted_at",
"placed_at < reached_pickup_at",
"placed_at < pickup_at",
"placed_at < left_pickup_at",
"placed_at < reached_delivery_at",
"placed_at < delivery_at",
"cancelled_at > restaurant_notified_at",
"cancelled_at > restaurant_confirmed_at",
"cancelled_at > dispatch_at",
"cancelled_at > courier_notified_at",
"cancelled_at > courier_accepted_at",
"cancelled_at > reached_pickup_at",
"cancelled_at > pickup_at",
"cancelled_at > left_pickup_at",
"cancelled_at > reached_delivery_at",
"restaurant_notified_at < restaurant_confirmed_at",
"restaurant_notified_at < pickup_at",
"restaurant_confirmed_at < pickup_at",
"dispatch_at < courier_notified_at",
"dispatch_at < courier_accepted_at",
"dispatch_at < reached_pickup_at",
"dispatch_at < pickup_at",
"dispatch_at < left_pickup_at",
"dispatch_at < reached_delivery_at",
"dispatch_at < delivery_at",
"courier_notified_at < courier_accepted_at",
"courier_notified_at < reached_pickup_at",
"courier_notified_at < pickup_at",
"courier_notified_at < left_pickup_at",
"courier_notified_at < reached_delivery_at",
"courier_notified_at < delivery_at",
"courier_accepted_at < reached_pickup_at",
"courier_accepted_at < pickup_at",
"courier_accepted_at < left_pickup_at",
"courier_accepted_at < reached_delivery_at",
"courier_accepted_at < delivery_at",
"reached_pickup_at < pickup_at",
"reached_pickup_at < left_pickup_at",
"reached_pickup_at < reached_delivery_at",
"reached_pickup_at < delivery_at",
"pickup_at < left_pickup_at",
"pickup_at < reached_delivery_at",
"pickup_at < delivery_at",
"left_pickup_at < reached_delivery_at",
"left_pickup_at < delivery_at",
"reached_delivery_at < delivery_at",
),
)
),
)
# Relationships
customer = orm.relationship('Customer', back_populates='orders')
customer = orm.relationship("Customer", back_populates="orders")
restaurant = orm.relationship(
'Restaurant',
back_populates='orders',
primaryjoin='Restaurant.id == Order.restaurant_id',
"Restaurant",
back_populates="orders",
primaryjoin="Restaurant.id == Order.restaurant_id",
)
courier = orm.relationship('Courier', back_populates='orders')
courier = orm.relationship("Courier", back_populates="orders")
pickup_address = orm.relationship(
'Address',
back_populates='orders_picked_up',
foreign_keys='[Order.pickup_address_id]',
"Address",
back_populates="orders_picked_up",
foreign_keys="[Order.pickup_address_id]",
)
delivery_address = orm.relationship(
'Address',
back_populates='orders_delivered',
foreign_keys='[Order.delivery_address_id]',
"Address",
back_populates="orders_delivered",
foreign_keys="[Order.delivery_address_id]",
)
replays = orm.relationship('ReplayedOrder', back_populates='actual')
replays = orm.relationship("ReplayedOrder", back_populates="actual")
# Convenience properties
@ -385,9 +385,9 @@ class Order(meta.Base):
This measures the time it took the UDP to notify the `.courier` after dispatch.
"""
if not self.dispatch_at:
raise RuntimeError('dispatch_at is not set')
raise RuntimeError("dispatch_at is not set")
if not self.courier_accepted_at:
raise RuntimeError('courier_accepted_at is not set')
raise RuntimeError("courier_accepted_at is not set")
return self.courier_accepted_at - self.dispatch_at
@property
@ -397,36 +397,36 @@ class Order(meta.Base):
A subset of `.time_to_accept`.
"""
if not self.courier_notified_at:
raise RuntimeError('courier_notified_at is not set')
raise RuntimeError("courier_notified_at is not set")
if not self.courier_accepted_at:
raise RuntimeError('courier_accepted_at is not set')
raise RuntimeError("courier_accepted_at is not set")
return self.courier_accepted_at - self.courier_notified_at
@property
def time_to_pickup(self) -> datetime.timedelta:
"""Time from the `.courier`'s acceptance to arrival at `.pickup_address`."""
if not self.courier_accepted_at:
raise RuntimeError('courier_accepted_at is not set')
raise RuntimeError("courier_accepted_at is not set")
if not self.reached_pickup_at:
raise RuntimeError('reached_pickup_at is not set')
raise RuntimeError("reached_pickup_at is not set")
return self.reached_pickup_at - self.courier_accepted_at
@property
def time_at_pickup(self) -> datetime.timedelta:
"""Time the `.courier` stayed at the `.pickup_address`."""
if not self.reached_pickup_at:
raise RuntimeError('reached_pickup_at is not set')
raise RuntimeError("reached_pickup_at is not set")
if not self.pickup_at:
raise RuntimeError('pickup_at is not set')
raise RuntimeError("pickup_at is not set")
return self.pickup_at - self.reached_pickup_at
@property
def scheduled_pickup_at(self) -> datetime.datetime:
"""Point in time at which the pickup was scheduled."""
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:
raise RuntimeError('estimated_prep_duration is not set')
raise RuntimeError("estimated_prep_duration is not set")
delta = datetime.timedelta(seconds=self.estimated_prep_duration)
return self.restaurant_notified_at + delta
@ -488,18 +488,18 @@ class Order(meta.Base):
def time_to_delivery(self) -> datetime.timedelta:
"""Time the `.courier` took from `.pickup_address` to `.delivery_address`."""
if not self.pickup_at:
raise RuntimeError('pickup_at is not set')
raise RuntimeError("pickup_at is not set")
if not self.reached_delivery_at:
raise RuntimeError('reached_delivery_at is not set')
raise RuntimeError("reached_delivery_at is not set")
return self.reached_delivery_at - self.pickup_at
@property
def time_at_delivery(self) -> datetime.timedelta:
"""Time the `.courier` stayed at the `.delivery_address`."""
if not self.reached_delivery_at:
raise RuntimeError('reached_delivery_at is not set')
raise RuntimeError("reached_delivery_at is not set")
if not self.delivery_at:
raise RuntimeError('delivery_at is not set')
raise RuntimeError("delivery_at is not set")
return self.delivery_at - self.reached_delivery_at
@property
@ -520,7 +520,7 @@ class Order(meta.Base):
Goes together with `.delivery_late`.
"""
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)
@property
@ -534,23 +534,23 @@ class Order(meta.Base):
Goes together with `.delivery_early`.
"""
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)
@property
def total_time(self) -> datetime.timedelta:
"""Time from order placement to delivery for an `.ad_hoc` order."""
if self.scheduled:
raise AttributeError('Scheduled orders have no total_time')
raise AttributeError("Scheduled orders have no total_time")
if self.cancelled:
raise RuntimeError('Cancelled orders have no total_time')
raise RuntimeError("Cancelled orders have no total_time")
return self.delivery_at - self.placed_at
# Other Methods
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}(#{order_id})>'.format(
return "<{cls}(#{order_id})>".format(
cls=self.__class__.__name__,
order_id=self.id,
)
@ -566,8 +566,8 @@ class Order(meta.Base):
"""
path = db.Path.from_order(self)
restaurant_tooltip = f'{self.restaurant.name} (#{self.restaurant.id})'
customer_tooltip = f'Customer #{self.customer.id}'
restaurant_tooltip = f"{self.restaurant.name} (#{self.restaurant.id})"
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.

View file

@ -25,7 +25,7 @@ class Pixel(meta.Base):
Every `Pixel` has a unique `n_x`-`n_y` coordinate within the `Grid`.
"""
__tablename__ = 'pixels'
__tablename__ = "pixels"
# Columns
id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
@ -36,27 +36,27 @@ class Pixel(meta.Base):
# Constraints
__table_args__ = (
sa.ForeignKeyConstraint(
['grid_id'],
['grids.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["grid_id"],
["grids.id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.CheckConstraint('0 <= n_x', name='n_x_is_positive'),
sa.CheckConstraint('0 <= n_y', name='n_y_is_positive'),
sa.CheckConstraint("0 <= n_x", name="n_x_is_positive"),
sa.CheckConstraint("0 <= n_y", name="n_y_is_positive"),
# Needed by a `ForeignKeyConstraint` in `AddressPixelAssociation`.
sa.UniqueConstraint('id', 'grid_id'),
sa.UniqueConstraint("id", "grid_id"),
# Each coordinate within the same `grid` is used at most once.
sa.UniqueConstraint('grid_id', 'n_x', 'n_y'),
sa.UniqueConstraint("grid_id", "n_x", "n_y"),
)
# Relationships
grid = orm.relationship('Grid', back_populates='pixels')
addresses = orm.relationship('AddressPixelAssociation', back_populates='pixel')
forecasts = orm.relationship('Forecast', back_populates='pixel')
grid = orm.relationship("Grid", back_populates="pixels")
addresses = orm.relationship("AddressPixelAssociation", back_populates="pixel")
forecasts = orm.relationship("Forecast", back_populates="pixel")
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}: ({x}|{y})>'.format(
return "<{cls}: ({x}|{y})>".format(
cls=self.__class__.__name__,
x=self.n_x,
y=self.n_y,
@ -163,17 +163,17 @@ class Pixel(meta.Base):
(self.southwest.latitude, self.southwest.longitude),
(self.northeast.latitude, self.northeast.longitude),
)
info_text = f'Pixel({self.n_x}|{self.n_y})'
info_text = f"Pixel({self.n_x}|{self.n_y})"
# Make the `Pixel`s look like a checkerboard.
if (self.n_x + self.n_y) % 2:
color = '#808000'
color = "#808000"
else:
color = '#ff8c00'
color = "#ff8c00"
marker = folium.Rectangle(
bounds=bounds,
color='gray',
color="gray",
opacity=0.2,
weight=5,
fill_color=color,
@ -220,11 +220,11 @@ class Pixel(meta.Base):
)
if len(restaurants) == 1: # type:ignore
tooltip = (
f'{restaurants[0].name} (#{restaurants[0].id})' # type:ignore
f"{restaurants[0].name} (#{restaurants[0].id})" # type:ignore
)
else:
tooltip = 'Restaurants ' + ', '.join(
f'#{restaurant.id}' for restaurant in restaurants # type:ignore
tooltip = "Restaurants " + ", ".join(
f"#{restaurant.id}" for restaurant in restaurants # type:ignore
)
if order_counts:
@ -247,7 +247,7 @@ class Pixel(meta.Base):
else:
radius = 1
tooltip += f' | n_orders={n_orders}'
tooltip += f" | n_orders={n_orders}"
address.draw(
radius=radius,

View file

@ -11,7 +11,7 @@ from velofy.db import meta
class ReplayedOrder(meta.Base):
"""A simulated order by a `Customer` of the UDP."""
__tablename__ = 'replayed_orders'
__tablename__ = "replayed_orders"
# Generic columns
simulation_id = sa.Column(sa.Integer, primary_key=True)
@ -55,22 +55,22 @@ class ReplayedOrder(meta.Base):
# Constraints
__table_args__ = (
sa.ForeignKeyConstraint(
['simulation_id'],
['replay_simulations.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["simulation_id"],
["replay_simulations.id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.ForeignKeyConstraint(
['actual_order_id', 'ad_hoc'],
['orders.id', 'orders.ad_hoc'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["actual_order_id", "ad_hoc"],
["orders.id", "orders.ad_hoc"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.ForeignKeyConstraint(
['courier_id'],
['couriers.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["courier_id"],
["couriers.id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
# The check constraints model some of the assumptions made in the simulations.
sa.CheckConstraint(
@ -90,7 +90,7 @@ class ReplayedOrder(meta.Base):
scheduled_delivery_at IS NOT NULL
)
""",
name='either_ad_hoc_or_scheduled_order',
name="either_ad_hoc_or_scheduled_order",
),
sa.CheckConstraint(
"""
@ -103,7 +103,7 @@ class ReplayedOrder(meta.Base):
)
)
""",
name='ad_hoc_orders_within_business_hours',
name="ad_hoc_orders_within_business_hours",
),
sa.CheckConstraint(
"""
@ -124,7 +124,7 @@ class ReplayedOrder(meta.Base):
)
)
""",
name='scheduled_orders_within_business_hours',
name="scheduled_orders_within_business_hours",
),
sa.CheckConstraint(
"""
@ -138,7 +138,7 @@ class ReplayedOrder(meta.Base):
= 0
)
""",
name='scheduled_orders_must_be_at_quarters_of_an_hour',
name="scheduled_orders_must_be_at_quarters_of_an_hour",
),
sa.CheckConstraint(
"""
@ -146,7 +146,7 @@ class ReplayedOrder(meta.Base):
EXTRACT(EPOCH FROM scheduled_delivery_at - placed_at) < 1800
)
""",
name='scheduled_orders_not_within_30_minutes',
name="scheduled_orders_not_within_30_minutes",
),
sa.CheckConstraint(
# A simulation must fill in at least all the timing and dispatch related
@ -187,7 +187,7 @@ class ReplayedOrder(meta.Base):
delivery_at IS NOT NULL
)
""",
name='orders_must_be_either_cancelled_or_fully_simulated',
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
@ -224,28 +224,28 @@ class ReplayedOrder(meta.Base):
delivery_at IS NOT NULL
)
""",
name='cancellations_may_only_occur_before_pickup',
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.
'0 <= estimated_prep_duration AND estimated_prep_duration <= 3600',
name='estimated_prep_duration_between_0_and_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.
'estimated_prep_duration % 60 = 0',
name='estimated_prep_duration_must_be_whole_minutes',
"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`.
'0 <= utilization AND utilization <= 100',
name='utilization_between_0_and_100',
"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
@ -258,7 +258,7 @@ class ReplayedOrder(meta.Base):
EXTRACT(HOUR FROM dispatch_at) < 11
)
""",
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 as
@ -266,79 +266,79 @@ class ReplayedOrder(meta.Base):
# and the non-simulated columns removed.
sa.CheckConstraint(
constraint,
name='ordered_timestamps_{index}'.format(index=index),
name="ordered_timestamps_{index}".format(index=index),
)
for index, constraint in enumerate(
(
'placed_at < scheduled_delivery_at',
'placed_at < cancelled_at',
'placed_at < restaurant_notified_at',
'placed_at < restaurant_confirmed_at',
'placed_at < restaurant_ready_at',
'placed_at < dispatch_at',
'placed_at < first_estimated_delivery_at',
'placed_at < courier_notified_at',
'placed_at < courier_accepted_at',
'placed_at < reached_pickup_at',
'placed_at < pickup_at',
'placed_at < left_pickup_at',
'placed_at < reached_delivery_at',
'placed_at < delivery_at',
'cancelled_at > restaurant_notified_at',
'cancelled_at > restaurant_confirmed_at',
'cancelled_at > restaurant_ready_at',
'cancelled_at > dispatch_at',
'cancelled_at > courier_notified_at',
'cancelled_at > courier_accepted_at',
'cancelled_at > reached_pickup_at',
'restaurant_notified_at < restaurant_confirmed_at',
'restaurant_notified_at < restaurant_ready_at',
'restaurant_notified_at < pickup_at',
'restaurant_confirmed_at < restaurant_ready_at',
'restaurant_confirmed_at < pickup_at',
'restaurant_ready_at < pickup_at',
'dispatch_at < first_estimated_delivery_at',
'dispatch_at < courier_notified_at',
'dispatch_at < courier_accepted_at',
'dispatch_at < reached_pickup_at',
'dispatch_at < pickup_at',
'dispatch_at < left_pickup_at',
'dispatch_at < reached_delivery_at',
'dispatch_at < delivery_at',
'courier_notified_at < courier_accepted_at',
'courier_notified_at < reached_pickup_at',
'courier_notified_at < pickup_at',
'courier_notified_at < left_pickup_at',
'courier_notified_at < reached_delivery_at',
'courier_notified_at < delivery_at',
'courier_accepted_at < reached_pickup_at',
'courier_accepted_at < pickup_at',
'courier_accepted_at < left_pickup_at',
'courier_accepted_at < reached_delivery_at',
'courier_accepted_at < delivery_at',
'reached_pickup_at < pickup_at',
'reached_pickup_at < left_pickup_at',
'reached_pickup_at < reached_delivery_at',
'reached_pickup_at < delivery_at',
'pickup_at < left_pickup_at',
'pickup_at < reached_delivery_at',
'pickup_at < delivery_at',
'left_pickup_at < reached_delivery_at',
'left_pickup_at < delivery_at',
'reached_delivery_at < delivery_at',
"placed_at < scheduled_delivery_at",
"placed_at < cancelled_at",
"placed_at < restaurant_notified_at",
"placed_at < restaurant_confirmed_at",
"placed_at < restaurant_ready_at",
"placed_at < dispatch_at",
"placed_at < first_estimated_delivery_at",
"placed_at < courier_notified_at",
"placed_at < courier_accepted_at",
"placed_at < reached_pickup_at",
"placed_at < pickup_at",
"placed_at < left_pickup_at",
"placed_at < reached_delivery_at",
"placed_at < delivery_at",
"cancelled_at > restaurant_notified_at",
"cancelled_at > restaurant_confirmed_at",
"cancelled_at > restaurant_ready_at",
"cancelled_at > dispatch_at",
"cancelled_at > courier_notified_at",
"cancelled_at > courier_accepted_at",
"cancelled_at > reached_pickup_at",
"restaurant_notified_at < restaurant_confirmed_at",
"restaurant_notified_at < restaurant_ready_at",
"restaurant_notified_at < pickup_at",
"restaurant_confirmed_at < restaurant_ready_at",
"restaurant_confirmed_at < pickup_at",
"restaurant_ready_at < pickup_at",
"dispatch_at < first_estimated_delivery_at",
"dispatch_at < courier_notified_at",
"dispatch_at < courier_accepted_at",
"dispatch_at < reached_pickup_at",
"dispatch_at < pickup_at",
"dispatch_at < left_pickup_at",
"dispatch_at < reached_delivery_at",
"dispatch_at < delivery_at",
"courier_notified_at < courier_accepted_at",
"courier_notified_at < reached_pickup_at",
"courier_notified_at < pickup_at",
"courier_notified_at < left_pickup_at",
"courier_notified_at < reached_delivery_at",
"courier_notified_at < delivery_at",
"courier_accepted_at < reached_pickup_at",
"courier_accepted_at < pickup_at",
"courier_accepted_at < left_pickup_at",
"courier_accepted_at < reached_delivery_at",
"courier_accepted_at < delivery_at",
"reached_pickup_at < pickup_at",
"reached_pickup_at < left_pickup_at",
"reached_pickup_at < reached_delivery_at",
"reached_pickup_at < delivery_at",
"pickup_at < left_pickup_at",
"pickup_at < reached_delivery_at",
"pickup_at < delivery_at",
"left_pickup_at < reached_delivery_at",
"left_pickup_at < delivery_at",
"reached_delivery_at < delivery_at",
),
)
),
)
# Relationships
simulation = orm.relationship('ReplaySimulation', back_populates='orders')
actual = orm.relationship('Order', back_populates='replays')
courier = orm.relationship('Courier')
simulation = orm.relationship("ReplaySimulation", back_populates="orders")
actual = orm.relationship("Order", back_populates="replays")
courier = orm.relationship("Courier")
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}(#{order_id})>'.format(
return "<{cls}(#{order_id})>".format(
cls=self.__class__.__name__,
order_id=self.actual.id,
)

View file

@ -12,7 +12,7 @@ class ReplaySimulation(meta.Base):
... for the orders as they arrived in reality.
"""
__tablename__ = 'replay_simulations'
__tablename__ = "replay_simulations"
# Columns
id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
@ -24,23 +24,23 @@ class ReplaySimulation(meta.Base):
# Constraints
__table_args__ = (
sa.ForeignKeyConstraint(
['city_id'],
['cities.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["city_id"],
["cities.id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
# A `.strategy` can be replayed several times per `.city`.
sa.UniqueConstraint('city_id', 'strategy', 'run'),
sa.CheckConstraint('run >= 0', name='run_is_a_count'),
sa.UniqueConstraint("city_id", "strategy", "run"),
sa.CheckConstraint("run >= 0", name="run_is_a_count"),
)
# Relationships
city = orm.relationship('City', back_populates='replays')
orders = orm.relationship('ReplayedOrder', back_populates='simulation')
city = orm.relationship("City", back_populates="replays")
orders = orm.relationship("ReplayedOrder", back_populates="simulation")
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}({strategy} #{run} in {city})>'.format(
return "<{cls}({strategy} #{run} in {city})>".format(
cls=self.__class__.__name__,
strategy=self.strategy,
run=self.run,

View file

@ -19,7 +19,7 @@ class Restaurant(meta.Base):
which in most cases is also the only one.
"""
__tablename__ = 'restaurants'
__tablename__ = "restaurants"
# Columns
id = sa.Column(
@ -35,30 +35,30 @@ class Restaurant(meta.Base):
# Constraints
__table_args__ = (
sa.ForeignKeyConstraint(
['address_id'],
['addresses.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
["address_id"],
["addresses.id"],
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.CheckConstraint(
'0 <= estimated_prep_duration AND estimated_prep_duration <= 2400',
name='realistic_estimated_prep_duration',
"0 <= estimated_prep_duration AND estimated_prep_duration <= 2400",
name="realistic_estimated_prep_duration",
),
# Needed by a `ForeignKeyConstraint` in `Order`.
sa.UniqueConstraint('id', 'address_id'),
sa.UniqueConstraint("id", "address_id"),
)
# Relationships
address = orm.relationship('Address', back_populates='restaurants')
address = orm.relationship("Address", back_populates="restaurants")
orders = orm.relationship(
'Order',
back_populates='restaurant',
overlaps='orders_picked_up,pickup_address',
"Order",
back_populates="restaurant",
overlaps="orders_picked_up,pickup_address",
)
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}({name})>'.format(cls=self.__class__.__name__, name=self.name)
return "<{cls}({name})>".format(cls=self.__class__.__name__, name=self.name)
def clear_map(self) -> Restaurant: # pragma: no cover
"""Shortcut to the `.address.city.clear_map()` method.
@ -139,7 +139,7 @@ class Restaurant(meta.Base):
color=config.CUSTOMER_COLOR,
fill_color=config.CUSTOMER_COLOR,
fill_opacity=0.3,
tooltip=f'n_orders={n_orders}',
tooltip=f"n_orders={n_orders}",
)
else:
@ -153,7 +153,7 @@ class Restaurant(meta.Base):
color=config.RESTAURANT_COLOR,
fill_color=config.RESTAURANT_COLOR,
fill_opacity=0.3,
tooltip=f'{self.name} (#{self.id}) | n_orders={len(self.orders)}',
tooltip=f"{self.name} (#{self.id}) | n_orders={len(self.orders)}",
)
return self.map

View file

@ -49,7 +49,7 @@ def make_random_cmap(
]
return colors.LinearSegmentedColormap.from_list(
'random_color_map',
"random_color_map",
rgb_colors,
N=n_colors,
)
@ -69,4 +69,4 @@ def rgb_to_hex(*args: float) -> str: # pragma: no cover
int(255 * args[1]),
int(255 * args[2]),
)
return f'#{red:02x}{green:02x}{blue:02x}'
return f"#{red:02x}{green:02x}{blue:02x}"

View file

@ -50,7 +50,7 @@ class Location:
>>> Location(43.6532, -79.3832)
<Location: 17T 630378 4834625>
"""
return f'<Location: {self.zone} {self.easting} {self.northing}>'
return f"<Location: {self.zone} {self.easting} {self.northing}>"
@property
def latitude(self) -> float:
@ -86,7 +86,7 @@ class Location:
@property
def zone(self) -> str:
"""The UTM zone of the location."""
return f'{self._zone}{self._band}'
return f"{self._zone}{self._band}"
@property
def zone_details(self) -> Tuple[int, str]:
@ -99,7 +99,7 @@ class Location:
return NotImplemented
if self.zone != other.zone:
raise ValueError('locations must be in the same zone, including the band')
raise ValueError("locations must be in the same zone, including the band")
return (self.easting, self.northing) == (other.easting, other.northing)
@ -110,7 +110,7 @@ class Location:
The origin, which defines the `(0, 0)` coordinate, is set with `.relate_to()`.
"""
if self._normalized_easting is None:
raise RuntimeError('an origin to relate to must be set first')
raise RuntimeError("an origin to relate to must be set first")
return self._normalized_easting
@ -121,7 +121,7 @@ class Location:
The origin, which defines the `(0, 0)` coordinate, is set with `.relate_to()`.
"""
if self._normalized_northing is None:
raise RuntimeError('an origin to relate to must be set first')
raise RuntimeError("an origin to relate to must be set first")
return self._normalized_northing
@ -136,13 +136,13 @@ class Location:
properties, the `other` origin may only be set once!
"""
if self._normalized_easting is not None:
raise RuntimeError('the `other` origin may only be set once')
raise RuntimeError("the `other` origin may only be set once")
if not isinstance(other, Location):
raise TypeError('`other` is not a `Location` object')
raise TypeError("`other` is not a `Location` object")
if self.zone != other.zone:
raise ValueError('`other` must be in the same zone, including the band')
raise ValueError("`other` must be in the same zone, including the band")
self._normalized_easting = self.easting - other.easting
self._normalized_northing = self.northing - other.northing