Upgrade black

This commit is contained in:
Alexander Hess 2026-11-25 10:24:07 +01:00
commit dbdce83067
Signed by: alexander
GPG key ID: B46EDB4DFC26805D
25 changed files with 1208 additions and 914 deletions

View file

@ -5,6 +5,7 @@ Example:
>>> velofy.__version__ != '0.0.0'
True
"""
# The config object must come before all other project-internal imports.
from velofy.configuration import config # isort:skip

View file

@ -25,7 +25,10 @@ from velofy.forecasts import timify
@click.argument('train_horizon', default=8, type=int)
@decorators.db_revision('8bfb928a31f8')
def tactical_heuristic( # noqa:C901,WPS213,WPS216
city: str, side_length: int, time_step: int, train_horizon: int,
city: str,
side_length: int,
time_step: int,
train_horizon: int,
) -> None: # pragma: no cover
"""Predict demand for all pixels and days in a city.
@ -125,7 +128,9 @@ def tactical_heuristic( # noqa:C901,WPS213,WPS216
while predict_day <= order_history.last_order_at(pixel_id=pixel.id).date():
# ... and choose the most promising `*Model` for that day.
model = order_history.choose_tactical_model(
pixel_id=pixel.id, predict_day=predict_day, train_horizon=train_horizon,
pixel_id=pixel.id,
predict_day=predict_day,
train_horizon=train_horizon,
)
click.echo(
f'Predicting pixel #{pixel.id} in {city} '
@ -141,7 +146,9 @@ def tactical_heuristic( # noqa:C901,WPS213,WPS216
)
while predict_at.hour < config.SERVICE_END:
model.make_forecast(
pixel=pixel, predict_at=predict_at, train_horizon=train_horizon,
pixel=pixel,
predict_at=predict_at,
train_horizon=train_horizon,
)
predict_at += dt.timedelta(minutes=time_step)

View file

@ -37,13 +37,20 @@ 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',
@ -52,7 +59,8 @@ class Address(meta.Base):
# Needed by a `ForeignKeyConstraint` in `AddressPixelAssociation`.
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'),
)
@ -75,7 +83,9 @@ class Address(meta.Base):
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}({street} in {city})>'.format(
cls=self.__class__.__name__, street=self.street, city=self.city_name,
cls=self.__class__.__name__,
street=self.street,
city=self.city_name,
)
@hybrid.hybrid_property

View file

@ -73,14 +73,16 @@ class Path(meta.Base):
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.
),
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',
@ -90,7 +92,8 @@ class Path(meta.Base):
# 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',
@ -100,7 +103,9 @@ class Path(meta.Base):
@classmethod
def from_addresses(
cls, *addresses: db.Address, google_maps: bool = False,
cls,
*addresses: db.Address,
google_maps: bool = False,
) -> List[Path]:
"""Calculate pair-wise paths for `Address` objects.
@ -138,7 +143,8 @@ class Path(meta.Base):
# ... create a new one.
if path is None:
air_distance = geo_distance.great_circle(
first.location.lat_lng, second.location.lat_lng,
first.location.lat_lng,
second.location.lat_lng,
)
path = cls(
@ -174,7 +180,9 @@ class Path(meta.Base):
path
"""
return cls.from_addresses(
order.pickup_address, order.delivery_address, google_maps=google_maps,
order.pickup_address,
order.delivery_address,
google_maps=google_maps,
)[0]
def sync_with_google_maps(self) -> None:

View file

@ -22,7 +22,9 @@ class City(meta.Base):
# Generic columns
id = sa.Column( # noqa:WPS125
sa.SmallInteger, primary_key=True, autoincrement=False,
sa.SmallInteger,
primary_key=True,
autoincrement=False,
)
name = sa.Column(sa.Unicode(length=10), nullable=False)
kml = sa.Column(sa.UnicodeText, nullable=False)
@ -119,7 +121,8 @@ class City(meta.Base):
return self._map
def draw_restaurants(
self, order_counts: bool = False, # pragma: no cover
self,
order_counts: bool = False, # pragma: no cover
) -> folium.Map:
"""Draw all restaurants on the`.map`.
@ -192,7 +195,9 @@ class City(meta.Base):
else:
address.draw(
radius=1, color=config.RESTAURANT_COLOR, tooltip=tooltip,
radius=1,
color=config.RESTAURANT_COLOR,
tooltip=tooltip,
)
return self.map

View file

@ -24,14 +24,17 @@ class Courier(meta.Base):
# Constraints
__table_args__ = (
sa.CheckConstraint(
"vehicle IN ('bicycle', 'motorcycle')", name='available_vehicle_types',
"vehicle IN ('bicycle', 'motorcycle')",
name='available_vehicle_types',
),
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',
@ -45,5 +48,6 @@ class Courier(meta.Base):
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}(#{courier_id})>'.format(
cls=self.__class__.__name__, courier_id=self.id,
cls=self.__class__.__name__,
courier_id=self.id,
)

View file

@ -22,7 +22,8 @@ class Customer(meta.Base):
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}(#{customer_id})>'.format(
cls=self.__class__.__name__, customer_id=self.id,
cls=self.__class__.__name__,
customer_id=self.id,
)
# Relationships
@ -43,7 +44,9 @@ class Customer(meta.Base):
return self.orders[0].pickup_address.city.map # noqa:WPS219
def draw( # noqa:C901,WPS210
self, restaurants: bool = True, order_counts: bool = False, # pragma: no cover
self,
restaurants: bool = True,
order_counts: bool = False, # pragma: no cover
) -> folium.Map:
"""Draw all the customer's delivery addresses on the `...city.map`.
@ -110,7 +113,8 @@ class Customer(meta.Base):
else:
address.draw(
radius=1, color=config.CUSTOMER_COLOR,
radius=1,
color=config.CUSTOMER_COLOR,
)
if restaurants:
@ -178,7 +182,9 @@ class Customer(meta.Base):
else:
address.draw( # noqa:WPS441
radius=1, color=config.RESTAURANT_COLOR, tooltip=tooltip,
radius=1,
color=config.RESTAURANT_COLOR,
tooltip=tooltip,
)
return self.map

View file

@ -46,7 +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(
"""
@ -63,7 +66,8 @@ class Forecast(meta.Base):
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',
@ -71,7 +75,8 @@ class Forecast(meta.Base):
),
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(
@ -124,7 +129,11 @@ class Forecast(meta.Base):
),
# 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',
),
)

View file

@ -23,7 +23,9 @@ class Grid(meta.Base):
# Columns
id = sa.Column( # noqa:WPS125
sa.SmallInteger, primary_key=True, autoincrement=True,
sa.SmallInteger,
primary_key=True,
autoincrement=True,
)
city_id = sa.Column(sa.SmallInteger, nullable=False)
side_length = sa.Column(sa.SmallInteger, nullable=False, unique=True)
@ -31,7 +33,10 @@ 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`.
@ -47,14 +52,15 @@ class Grid(meta.Base):
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}: {area} sqr. km>'.format(
cls=self.__class__.__name__, area=self.pixel_area,
cls=self.__class__.__name__,
area=self.pixel_area,
)
# Convenience properties
@property
def pixel_area(self) -> float:
"""The area of a `Pixel` on the grid in square kilometers."""
return round((self.side_length ** 2) / 1_000_000, 1)
return round((self.side_length**2) / 1_000_000, 1)
@classmethod
def gridify(cls, city: db.City, side_length: int) -> db.Grid: # noqa:WPS210

View file

@ -80,10 +80,16 @@ class Order(meta.Base): # noqa:WPS214
# 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'],
@ -259,7 +265,8 @@ class Order(meta.Base): # noqa:WPS214
),
*(
sa.CheckConstraint(
constraint, name='ordered_timestamps_{index}'.format(index=index),
constraint,
name='ordered_timestamps_{index}'.format(index=index),
)
for index, constraint in enumerate(
(
@ -434,7 +441,8 @@ class Order(meta.Base): # noqa:WPS214
Goes together with `.courier_late`.
"""
return max(
datetime.timedelta(), self.scheduled_pickup_at - self.reached_pickup_at,
datetime.timedelta(),
self.scheduled_pickup_at - self.reached_pickup_at,
)
@property
@ -448,7 +456,8 @@ class Order(meta.Base): # noqa:WPS214
Goes together with `.courier_early`.
"""
return max(
datetime.timedelta(), self.reached_pickup_at - self.scheduled_pickup_at,
datetime.timedelta(),
self.reached_pickup_at - self.scheduled_pickup_at,
)
@property
@ -542,7 +551,8 @@ class Order(meta.Base): # noqa:WPS214
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}(#{order_id})>'.format(
cls=self.__class__.__name__, order_id=self.id,
cls=self.__class__.__name__,
order_id=self.id,
)
def draw(self) -> folium.Map: # pragma: no cover

View file

@ -36,7 +36,10 @@ 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'),
@ -54,7 +57,9 @@ class Pixel(meta.Base):
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}: ({x}|{y})>'.format(
cls=self.__class__.__name__, x=self.n_x, y=self.n_y,
cls=self.__class__.__name__,
x=self.n_x,
y=self.n_y,
)
# Convenience properties
@ -81,7 +86,9 @@ class Pixel(meta.Base):
self.grid.city.southwest.northing + ((self.n_y + 1) * self.side_length),
)
latitude, longitude = utm.to_latlon(
easting, northing, *self.grid.city.southwest.zone_details,
easting,
northing,
*self.grid.city.southwest.zone_details,
)
location = utils.Location(latitude, longitude)
@ -101,7 +108,9 @@ class Pixel(meta.Base):
self.grid.city.southwest.northing + (self.n_y * self.side_length),
)
latitude, longitude = utm.to_latlon(
easting, northing, *self.grid.city.southwest.zone_details,
easting,
northing,
*self.grid.city.southwest.zone_details,
)
location = utils.Location(latitude, longitude)
@ -137,7 +146,9 @@ class Pixel(meta.Base):
return self.grid.city.map
def draw( # noqa:C901,WPS210
self, restaurants: bool = True, order_counts: bool = False, # pragma: no cover
self,
restaurants: bool = True,
order_counts: bool = False, # pragma: no cover
) -> folium.Map:
"""Draw the pixel on the `.grid.city.map`.
@ -248,7 +259,9 @@ class Pixel(meta.Base):
else:
address.draw(
radius=1, color=config.RESTAURANT_COLOR, tooltip=tooltip,
radius=1,
color=config.RESTAURANT_COLOR,
tooltip=tooltip,
)
return self.map

View file

@ -67,7 +67,10 @@ class ReplayedOrder(meta.Base):
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(
@ -262,7 +265,8 @@ class ReplayedOrder(meta.Base):
# in the actual `Order` model with an extra `restaurant_ready_at` column
# and the non-simulated columns removed.
sa.CheckConstraint(
constraint, name='ordered_timestamps_{index}'.format(index=index),
constraint,
name='ordered_timestamps_{index}'.format(index=index),
)
for index, constraint in enumerate(
(
@ -335,7 +339,8 @@ class ReplayedOrder(meta.Base):
def __repr__(self) -> str:
"""Non-literal text representation."""
return '<{cls}(#{order_id})>'.format(
cls=self.__class__.__name__, order_id=self.actual.id,
cls=self.__class__.__name__,
order_id=self.actual.id,
)
# Convenience properties

View file

@ -1,6 +1,5 @@
"""Provide the ORM's `ReplaySimulation` model for the replay simulations."""
import sqlalchemy as sa
from sqlalchemy import orm
@ -25,7 +24,10 @@ 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'),

View file

@ -23,7 +23,9 @@ class Restaurant(meta.Base):
# Columns
id = sa.Column( # noqa:WPS125
sa.SmallInteger, primary_key=True, autoincrement=False,
sa.SmallInteger,
primary_key=True,
autoincrement=False,
)
created_at = sa.Column(sa.DateTime, nullable=False)
name = sa.Column(sa.Unicode(length=45), nullable=False)
@ -33,7 +35,10 @@ 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',
@ -70,7 +75,9 @@ class Restaurant(meta.Base):
return self.address.city.map
def draw(
self, customers: bool = True, order_counts: bool = False, # pragma: no cover
self,
customers: bool = True,
order_counts: bool = False, # pragma: no cover
) -> folium.Map:
"""Draw the restaurant on the `.address.city.map`.
@ -95,7 +102,8 @@ class Restaurant(meta.Base):
for row in (
db.session.query(db.Address.primary_id) # noqa:WPS221
.join(
db.Order, db.Address.id == db.Order.delivery_address_id,
db.Order,
db.Address.id == db.Order.delivery_address_id,
)
.filter(db.Order.restaurant_id == self.id)
.distinct()
@ -136,7 +144,8 @@ class Restaurant(meta.Base):
else:
address.draw(
radius=1, color=config.CUSTOMER_COLOR,
radius=1,
color=config.CUSTOMER_COLOR,
)
self.address.draw(

View file

@ -7,7 +7,8 @@ from matplotlib import colors
def make_random_cmap(
n_colors: int, bright: bool = True, # pragma: no cover
n_colors: int,
bright: bool = True, # pragma: no cover
) -> colors.LinearSegmentedColormap:
"""Create a random `Colormap` with `n_colors` different colors.
@ -48,7 +49,9 @@ def make_random_cmap(
]
return colors.LinearSegmentedColormap.from_list(
'random_color_map', rgb_colors, N=n_colors,
'random_color_map',
rgb_colors,
N=n_colors,
)

View file

@ -43,7 +43,8 @@ def predict(
# Copy the data from Python to R.
robjects.globalenv['data'] = robjects.r['ts'](
pandas2ri.py2rpy(training_ts), frequency=frequency,
pandas2ri.py2rpy(training_ts),
frequency=frequency,
)
seasonal = 'TRUE' if bool(seasonal_fit) else 'FALSE'

View file

@ -165,7 +165,19 @@ def stl( # noqa:C901,WPS210,WPS211
# Call the STL function in R.
ts = robjects.r['ts'](pandas2ri.py2rpy(time_series), frequency=frequency)
result = robjects.r['stl'](
ts, ns, ds, nt, dt, nl, dl, js, jt, jl, robust, ni, no, # noqa:WPS221
ts,
ns,
ds,
nt,
dt,
nl,
dl,
js,
jt,
jl,
robust,
ni,
no, # noqa:WPS221
)
# Unpack the result to a `pd.DataFrame`.

View file

@ -44,7 +44,8 @@ def predict(
# Copy the data from Python to R.
robjects.globalenv['data'] = robjects.r['ts'](
pandas2ri.py2rpy(training_ts), frequency=frequency,
pandas2ri.py2rpy(training_ts),
frequency=frequency,
)
model = 'ZZZ' if bool(seasonal_fit) else 'ZZN'

View file

@ -5,7 +5,10 @@ from statsmodels.tsa import api as ts_stats
def predict(
training_ts: pd.Series, forecast_interval: pd.DatetimeIndex, *, frequency: int,
training_ts: pd.Series,
forecast_interval: pd.DatetimeIndex,
*,
frequency: int,
) -> pd.DataFrame:
"""Extrapolate a seasonal component with a linear model.

View file

@ -33,7 +33,10 @@ class ForecastingModelABC(abc.ABC):
@abc.abstractmethod
def predict(
self, pixel: db.Pixel, predict_at: dt.datetime, train_horizon: int,
self,
pixel: db.Pixel,
predict_at: dt.datetime,
train_horizon: int,
) -> pd.DataFrame:
"""Concrete implementation of how a `*Model` makes a prediction.
@ -52,7 +55,10 @@ class ForecastingModelABC(abc.ABC):
""" # noqa:DAR202
def make_forecast(
self, pixel: db.Pixel, predict_at: dt.datetime, train_horizon: int,
self,
pixel: db.Pixel,
predict_at: dt.datetime,
train_horizon: int,
) -> db.Forecast:
"""Make a forecast for the time step starting at `predict_at`.
@ -82,7 +88,7 @@ class ForecastingModelABC(abc.ABC):
.filter_by(train_horizon=train_horizon)
.filter_by(model=self.name)
.first()
) :
):
return cached_forecast
# Horizontal and real-time `*Model`s return a `pd.DataFrame` with one

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