Merge branch 'upgrade-dev-tools-py38' into develop
All checks were successful
CI / Tests (Python 3.8) (push) Successful in 1m24s

This commit is contained in:
Alexander Hess 2026-11-25 11:04:24 +01:00
commit 34da92102f
Signed by: alexander
GPG key ID: B46EDB4DFC26805D
56 changed files with 2214 additions and 1031 deletions

View file

@ -78,7 +78,8 @@ def upgrade():
name=op.f('ck_couriers_on_realistic_pay_per_order'), name=op.f('ck_couriers_on_realistic_pay_per_order'),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'0 <= speed AND speed <= 30', name=op.f('ck_couriers_on_realistic_speed'), '0 <= speed AND speed <= 30',
name=op.f('ck_couriers_on_realistic_speed'),
), ),
sa.PrimaryKeyConstraint('id', name=op.f('pk_couriers')), sa.PrimaryKeyConstraint('id', name=op.f('pk_couriers')),
*( *(
@ -124,7 +125,8 @@ def upgrade():
name=op.f('ck_addresses_on_latitude_between_90_degrees'), name=op.f('ck_addresses_on_latitude_between_90_degrees'),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'0 <= floor AND floor <= 40', name=op.f('ck_addresses_on_realistic_floor'), '0 <= floor AND floor <= 40',
name=op.f('ck_addresses_on_realistic_floor'),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'30000 <= zip_code AND zip_code <= 99999', '30000 <= zip_code AND zip_code <= 99999',
@ -378,7 +380,8 @@ def upgrade():
name=op.f('ck_orders_on_ordered_timestamps_19'), name=op.f('ck_orders_on_ordered_timestamps_19'),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'cancelled_at > pickup_at', name=op.f('ck_orders_on_ordered_timestamps_18'), 'cancelled_at > pickup_at',
name=op.f('ck_orders_on_ordered_timestamps_18'),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'cancelled_at > reached_delivery_at', 'cancelled_at > reached_delivery_at',
@ -457,7 +460,8 @@ def upgrade():
name=op.f('ck_orders_on_ordered_timestamps_29'), name=op.f('ck_orders_on_ordered_timestamps_29'),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'dispatch_at < pickup_at', name=op.f('ck_orders_on_ordered_timestamps_28'), 'dispatch_at < pickup_at',
name=op.f('ck_orders_on_ordered_timestamps_28'),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'dispatch_at < reached_delivery_at', 'dispatch_at < reached_delivery_at',
@ -484,7 +488,8 @@ def upgrade():
name=op.f('ck_orders_on_ordered_timestamps_50'), name=op.f('ck_orders_on_ordered_timestamps_50'),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'pickup_at < delivery_at', name=op.f('ck_orders_on_ordered_timestamps_49'), 'pickup_at < delivery_at',
name=op.f('ck_orders_on_ordered_timestamps_49'),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'pickup_at < left_pickup_at', 'pickup_at < left_pickup_at',
@ -495,7 +500,8 @@ def upgrade():
name=op.f('ck_orders_on_ordered_timestamps_48'), name=op.f('ck_orders_on_ordered_timestamps_48'),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'placed_at < cancelled_at', name=op.f('ck_orders_on_ordered_timestamps_2'), 'placed_at < cancelled_at',
name=op.f('ck_orders_on_ordered_timestamps_2'),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'placed_at < courier_accepted_at', 'placed_at < courier_accepted_at',
@ -506,10 +512,12 @@ def upgrade():
name=op.f('ck_orders_on_ordered_timestamps_6'), name=op.f('ck_orders_on_ordered_timestamps_6'),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'placed_at < delivery_at', name=op.f('ck_orders_on_ordered_timestamps_11'), 'placed_at < delivery_at',
name=op.f('ck_orders_on_ordered_timestamps_11'),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'placed_at < dispatch_at', name=op.f('ck_orders_on_ordered_timestamps_5'), 'placed_at < dispatch_at',
name=op.f('ck_orders_on_ordered_timestamps_5'),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'placed_at < first_estimated_delivery_at', 'placed_at < first_estimated_delivery_at',

View file

@ -37,7 +37,9 @@ def upgrade():
ondelete='RESTRICT', ondelete='RESTRICT',
), ),
sa.UniqueConstraint( sa.UniqueConstraint(
'city_id', 'side_length', name=op.f('uq_grids_on_city_id_side_length'), 'city_id',
'side_length',
name=op.f('uq_grids_on_city_id_side_length'),
), ),
# This `UniqueConstraint` is needed by the `addresses_pixels` table below. # This `UniqueConstraint` is needed by the `addresses_pixels` table below.
sa.UniqueConstraint('id', 'city_id', name=op.f('uq_grids_on_id_city_id')), sa.UniqueConstraint('id', 'city_id', name=op.f('uq_grids_on_id_city_id')),
@ -61,7 +63,10 @@ def upgrade():
), ),
sa.PrimaryKeyConstraint('id', name=op.f('pk_pixels')), sa.PrimaryKeyConstraint('id', name=op.f('pk_pixels')),
sa.UniqueConstraint( sa.UniqueConstraint(
'grid_id', 'n_x', 'n_y', name=op.f('uq_pixels_on_grid_id_n_x_n_y'), 'grid_id',
'n_x',
'n_y',
name=op.f('uq_pixels_on_grid_id_n_x_n_y'),
), ),
sa.UniqueConstraint('id', 'grid_id', name=op.f('uq_pixels_on_id_grid_id')), sa.UniqueConstraint('id', 'grid_id', name=op.f('uq_pixels_on_id_grid_id')),
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
@ -134,7 +139,9 @@ def upgrade():
ondelete='RESTRICT', ondelete='RESTRICT',
), ),
sa.PrimaryKeyConstraint( sa.PrimaryKeyConstraint(
'address_id', 'pixel_id', name=op.f('pk_addresses_pixels'), 'address_id',
'pixel_id',
name=op.f('pk_addresses_pixels'),
), ),
sa.UniqueConstraint( sa.UniqueConstraint(
'address_id', 'address_id',
@ -155,13 +162,19 @@ def downgrade():
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.drop_index( op.drop_index(
op.f('ix_pixels_on_n_y'), table_name='pixels', schema=config.CLEAN_SCHEMA, op.f('ix_pixels_on_n_y'),
table_name='pixels',
schema=config.CLEAN_SCHEMA,
) )
op.drop_index( op.drop_index(
op.f('ix_pixels_on_n_x'), table_name='pixels', schema=config.CLEAN_SCHEMA, op.f('ix_pixels_on_n_x'),
table_name='pixels',
schema=config.CLEAN_SCHEMA,
) )
op.drop_index( op.drop_index(
op.f('ix_pixels_on_grid_id'), table_name='pixels', schema=config.CLEAN_SCHEMA, op.f('ix_pixels_on_grid_id'),
table_name='pixels',
schema=config.CLEAN_SCHEMA,
) )
op.drop_table('pixels', schema=config.CLEAN_SCHEMA) op.drop_table('pixels', schema=config.CLEAN_SCHEMA)
op.drop_table('grids', schema=config.CLEAN_SCHEMA) op.drop_table('grids', schema=config.CLEAN_SCHEMA)

View file

@ -64,7 +64,8 @@ def upgrade():
name=op.f('ck_forecasts_on_start_at_allows_no_seconds'), name=op.f('ck_forecasts_on_start_at_allows_no_seconds'),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'time_step > 0', name=op.f('ck_forecasts_on_time_step_must_be_positive'), 'time_step > 0',
name=op.f('ck_forecasts_on_time_step_must_be_positive'),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'training_horizon > 0', 'training_horizon > 0',

View file

@ -25,7 +25,10 @@ config = configuration.make_config('testing' if os.getenv('TESTING') else 'produ
def upgrade(): def upgrade():
"""Upgrade to revision 26711cd3f9b9.""" """Upgrade to revision 26711cd3f9b9."""
op.alter_column( op.alter_column(
'forecasts', 'method', new_column_name='model', schema=config.CLEAN_SCHEMA, 'forecasts',
'method',
new_column_name='model',
schema=config.CLEAN_SCHEMA,
) )
op.add_column( op.add_column(
'forecasts', 'forecasts',
@ -108,17 +111,28 @@ def upgrade():
def downgrade(): def downgrade():
"""Downgrade to revision e40623e10405.""" """Downgrade to revision e40623e10405."""
op.alter_column( op.alter_column(
'forecasts', 'model', new_column_name='method', schema=config.CLEAN_SCHEMA, 'forecasts',
'model',
new_column_name='method',
schema=config.CLEAN_SCHEMA,
) )
op.drop_column( op.drop_column(
'forecasts', 'low80', schema=config.CLEAN_SCHEMA, 'forecasts',
'low80',
schema=config.CLEAN_SCHEMA,
) )
op.drop_column( op.drop_column(
'forecasts', 'high80', schema=config.CLEAN_SCHEMA, 'forecasts',
'high80',
schema=config.CLEAN_SCHEMA,
) )
op.drop_column( op.drop_column(
'forecasts', 'low95', schema=config.CLEAN_SCHEMA, 'forecasts',
'low95',
schema=config.CLEAN_SCHEMA,
) )
op.drop_column( op.drop_column(
'forecasts', 'high95', schema=config.CLEAN_SCHEMA, 'forecasts',
'high95',
schema=config.CLEAN_SCHEMA,
) )

View file

@ -113,7 +113,9 @@ def upgrade():
sa.Column('reached_delivery_at', sa.DateTime), sa.Column('reached_delivery_at', sa.DateTime),
sa.Column('delivery_at', sa.DateTime), sa.Column('delivery_at', sa.DateTime),
sa.PrimaryKeyConstraint( sa.PrimaryKeyConstraint(
'simulation_id', 'actual_order_id', name=op.f('pk_replayed_orders'), 'simulation_id',
'actual_order_id',
name=op.f('pk_replayed_orders'),
), ),
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['simulation_id'], ['simulation_id'],
@ -296,7 +298,8 @@ def upgrade():
), ),
*( *(
sa.CheckConstraint( sa.CheckConstraint(
constraint, name='ordered_timestamps_{index}'.format(index=index), constraint,
name='ordered_timestamps_{index}'.format(index=index),
) )
for index, constraint in enumerate( for index, constraint in enumerate(
( (
@ -390,7 +393,10 @@ def downgrade():
op.drop_table('replayed_orders', schema=config.CLEAN_SCHEMA) op.drop_table('replayed_orders', schema=config.CLEAN_SCHEMA)
op.drop_table('replay_simulations', schema=config.CLEAN_SCHEMA) op.drop_table('replay_simulations', schema=config.CLEAN_SCHEMA)
op.drop_constraint( op.drop_constraint(
'uq_orders_on_id_ad_hoc', 'orders', type_=None, schema=config.CLEAN_SCHEMA, 'uq_orders_on_id_ad_hoc',
'orders',
type_=None,
schema=config.CLEAN_SCHEMA,
) )
op.execute( op.execute(
f""" f"""

View file

@ -205,7 +205,10 @@ def test(session):
# test cases that require the slow installation of R and some packages. # test cases that require the slow installation of R and some packages.
if session.env.get('_slow_ci_tests'): if session.env.get('_slow_ci_tests'):
session.run( session.run(
'pytest', '-m', 'r and not db', PYTEST_LOCATION, 'pytest',
'-m',
'r and not db',
PYTEST_LOCATION,
) )
# In the "ci-tests-slow" session, we do not run any test tool # In the "ci-tests-slow" session, we do not run any test tool
@ -273,7 +276,10 @@ def safety(session):
external=True, external=True,
) )
session.run( session.run(
'safety', 'check', f'--file={requirements_txt.name}', '--full-report', 'safety',
'check',
f'--file={requirements_txt.name}',
'--full-report',
) )
@ -434,7 +440,8 @@ def fix_branch_references(session): # noqa:WPS210
# the staged files passed in by pre-commit in most cases. # the staged files passed in by pre-commit in most cases.
if session.posargs and len(session.posargs) == 1: if session.posargs and len(session.posargs) == 1:
match = re.match( match = re.match(
pattern=r'^--branch=([\w\.-]+)$', string=session.posargs[0].strip(), pattern=r'^--branch=([\w\.-]+)$',
string=session.posargs[0].strip(),
) )
if match: if match:
branch = match.groups()[0] branch = match.groups()[0]
@ -582,7 +589,9 @@ def _install_packages(session: Session, *packages_or_pip_args: str, **kwargs) ->
external=True, external=True,
) )
session.install( session.install(
f'--constraint={requirements_txt.name}', *packages_or_pip_args, **kwargs, f'--constraint={requirements_txt.name}',
*packages_or_pip_args,
**kwargs,
) )

1996
poetry.lock generated

File diff suppressed because it is too large Load diff

View file

@ -81,19 +81,19 @@ skip-string-normalization = true # `wemake-python-styleguide` enforces single q
[tool.poetry.group.dev.dependencies] [tool.poetry.group.dev.dependencies]
# Task Runners # Task Runners
nox = "^2020.5.24" nox = ">=2020.5.24"
pre-commit = "^2.6.0" pre-commit = ">=2.6.0"
# Code Formatters # Code Formatters
autoflake = "^1.3.1" autoflake = ">=1.3.1"
black = "^19.10b0" black = ">=19.10b0"
isort = "^4.3.21" # TODO (isort): Not ^5.5.4 due to `wemake-python-styleguide` isort = ">=4.3.21"
# Code Analyzers # Code Analyzers
flake8 = ">=3.8.3" flake8 = ">=3.8.3"
flake8-annotations = "^2.3.0" flake8-annotations = ">=2.3.0"
flake8-black = "^0.2.1" flake8-black = ">=0.2.1"
flake8-pytest-style = "^1.2.2" flake8-pytest-style = ">=1.2.2"
mypy = ">=0.782" mypy = ">=0.782"
wemake-python-styleguide = ">=0.14.1" # `flake8` plug-in wemake-python-styleguide = ">=0.14.1" # `flake8` plug-in
@ -109,5 +109,5 @@ pytest-mock = ">=3.5.1"
xdoctest = { version=">=0.13.0", extras=["optional"] } xdoctest = { version=">=0.13.0", extras=["optional"] }
# Documentation # Documentation
sphinx = "^3.1.2" sphinx = ">=3.1.2"
sphinx-autodoc-typehints = "^1.11.0" sphinx-autodoc-typehints = ">=1.11.0"

View file

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

View file

@ -4,8 +4,7 @@ import functools
import os import os
import subprocess # noqa:S404 import subprocess # noqa:S404
import sys import sys
from typing import Any from typing import Any, Callable
from typing import Callable
import click import click

View file

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

View file

@ -37,13 +37,20 @@ class Address(meta.Base):
# Constraints # Constraints
__table_args__ = ( __table_args__ = (
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['primary_id'], ['addresses.id'], onupdate='RESTRICT', ondelete='RESTRICT', ['primary_id'],
['addresses.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
), ),
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['city_id'], ['cities.id'], onupdate='RESTRICT', ondelete='RESTRICT', ['city_id'],
['cities.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
), ),
sa.CheckConstraint( sa.CheckConstraint(
'-90 <= latitude AND latitude <= 90', name='latitude_between_90_degrees', '-90 <= latitude AND latitude <= 90',
name='latitude_between_90_degrees',
), ),
sa.CheckConstraint( sa.CheckConstraint(
'-180 <= longitude AND longitude <= 180', '-180 <= longitude AND longitude <= 180',
@ -52,7 +59,8 @@ class Address(meta.Base):
# Needed by a `ForeignKeyConstraint` in `AddressPixelAssociation`. # Needed by a `ForeignKeyConstraint` in `AddressPixelAssociation`.
sa.UniqueConstraint('id', 'city_id'), sa.UniqueConstraint('id', 'city_id'),
sa.CheckConstraint( 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'),
) )
@ -75,7 +83,9 @@ class Address(meta.Base):
def __repr__(self) -> str: def __repr__(self) -> str:
"""Non-literal text representation.""" """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, cls=self.__class__.__name__,
street=self.street,
city=self.city_name,
) )
@hybrid.hybrid_property @hybrid.hybrid_property

View file

@ -5,8 +5,7 @@ from __future__ import annotations
import functools import functools
import itertools import itertools
import json import json
from typing import List from typing import List, Tuple
from typing import Tuple
import folium import folium
import googlemaps as gm import googlemaps as gm
@ -73,14 +72,16 @@ class Path(meta.Base):
name='distances_are_symmetric_for_bicycles', name='distances_are_symmetric_for_bicycles',
), ),
sa.CheckConstraint( 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( sa.CheckConstraint(
'bicycle_distance < 25000', # `.bicycle_distance` may not be negative 'bicycle_distance < 25000', # `.bicycle_distance` may not be negative
name='realistic_bicycle_distance', # due to the constraint below. name='realistic_bicycle_distance', # due to the constraint below.
), ),
sa.CheckConstraint( sa.CheckConstraint(
'air_distance <= bicycle_distance', name='air_distance_is_shortest', 'air_distance <= bicycle_distance',
name='air_distance_is_shortest',
), ),
sa.CheckConstraint( sa.CheckConstraint(
'0 <= bicycle_duration AND bicycle_duration <= 3600', '0 <= bicycle_duration AND bicycle_duration <= 3600',
@ -90,7 +91,8 @@ class Path(meta.Base):
# Relationships # Relationships
first_address = orm.relationship( 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( second_address = orm.relationship(
'Address', 'Address',
@ -100,7 +102,9 @@ class Path(meta.Base):
@classmethod @classmethod
def from_addresses( def from_addresses(
cls, *addresses: db.Address, google_maps: bool = False, cls,
*addresses: db.Address,
google_maps: bool = False,
) -> List[Path]: ) -> List[Path]:
"""Calculate pair-wise paths for `Address` objects. """Calculate pair-wise paths for `Address` objects.
@ -138,7 +142,8 @@ class Path(meta.Base):
# ... create a new one. # ... create a new one.
if path is None: if path is None:
air_distance = geo_distance.great_circle( air_distance = geo_distance.great_circle(
first.location.lat_lng, second.location.lat_lng, first.location.lat_lng,
second.location.lat_lng,
) )
path = cls( path = cls(
@ -174,7 +179,9 @@ class Path(meta.Base):
path path
""" """
return cls.from_addresses( 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] )[0]
def sync_with_google_maps(self) -> None: def sync_with_google_maps(self) -> None:

View file

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

View file

@ -24,14 +24,17 @@ class Courier(meta.Base):
# Constraints # Constraints
__table_args__ = ( __table_args__ = (
sa.CheckConstraint( 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 <= speed AND speed <= 30', name='realistic_speed'),
sa.CheckConstraint( sa.CheckConstraint(
'0 <= capacity AND capacity <= 200', name='capacity_under_200_liters', '0 <= capacity AND capacity <= 200',
name='capacity_under_200_liters',
), ),
sa.CheckConstraint( 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( sa.CheckConstraint(
'0 <= pay_per_order AND pay_per_order <= 650', '0 <= pay_per_order AND pay_per_order <= 650',
@ -45,5 +48,6 @@ class Courier(meta.Base):
def __repr__(self) -> str: def __repr__(self) -> str:
"""Non-literal text representation.""" """Non-literal text representation."""
return '<{cls}(#{courier_id})>'.format( 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: def __repr__(self) -> str:
"""Non-literal text representation.""" """Non-literal text representation."""
return '<{cls}(#{customer_id})>'.format( return '<{cls}(#{customer_id})>'.format(
cls=self.__class__.__name__, customer_id=self.id, cls=self.__class__.__name__,
customer_id=self.id,
) )
# Relationships # Relationships
@ -43,7 +44,9 @@ class Customer(meta.Base):
return self.orders[0].pickup_address.city.map # noqa:WPS219 return self.orders[0].pickup_address.city.map # noqa:WPS219
def draw( # noqa:C901,WPS210 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: ) -> folium.Map:
"""Draw all the customer's delivery addresses on the `...city.map`. """Draw all the customer's delivery addresses on the `...city.map`.
@ -110,7 +113,8 @@ class Customer(meta.Base):
else: else:
address.draw( address.draw(
radius=1, color=config.CUSTOMER_COLOR, radius=1,
color=config.CUSTOMER_COLOR,
) )
if restaurants: if restaurants:
@ -178,7 +182,9 @@ class Customer(meta.Base):
else: else:
address.draw( # noqa:WPS441 address.draw( # noqa:WPS441
radius=1, color=config.RESTAURANT_COLOR, tooltip=tooltip, radius=1,
color=config.RESTAURANT_COLOR,
tooltip=tooltip,
) )
return self.map return self.map

View file

@ -46,7 +46,10 @@ class Forecast(meta.Base):
# Constraints # Constraints
__table_args__ = ( __table_args__ = (
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['pixel_id'], ['pixels.id'], onupdate='RESTRICT', ondelete='RESTRICT', ['pixel_id'],
['pixels.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
), ),
sa.CheckConstraint( sa.CheckConstraint(
""" """
@ -63,7 +66,8 @@ class Forecast(meta.Base):
name='start_at_minutes_must_be_quarters_of_the_hour', name='start_at_minutes_must_be_quarters_of_the_hour',
), ),
sa.CheckConstraint( 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( sa.CheckConstraint(
'CAST(EXTRACT(MICROSECONDS FROM start_at) AS INTEGER) % 1000000 = 0', '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('time_step > 0', name='time_step_must_be_positive'),
sa.CheckConstraint( 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( sa.CheckConstraint(
@ -124,7 +129,11 @@ class Forecast(meta.Base):
), ),
# There can be only one prediction per forecasting setting. # There can be only one prediction per forecasting setting.
sa.UniqueConstraint( 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 # Columns
id = sa.Column( # noqa:WPS125 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) city_id = sa.Column(sa.SmallInteger, nullable=False)
side_length = sa.Column(sa.SmallInteger, nullable=False, unique=True) side_length = sa.Column(sa.SmallInteger, nullable=False, unique=True)
@ -31,7 +33,10 @@ class Grid(meta.Base):
# Constraints # Constraints
__table_args__ = ( __table_args__ = (
sa.ForeignKeyConstraint( 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`, # Each `Grid`, characterized by its `.side_length`,
# may only exists once for a given `.city`. # may only exists once for a given `.city`.
@ -47,14 +52,15 @@ class Grid(meta.Base):
def __repr__(self) -> str: def __repr__(self) -> str:
"""Non-literal text representation.""" """Non-literal text representation."""
return '<{cls}: {area} sqr. km>'.format( return '<{cls}: {area} sqr. km>'.format(
cls=self.__class__.__name__, area=self.pixel_area, cls=self.__class__.__name__,
area=self.pixel_area,
) )
# Convenience properties # Convenience properties
@property @property
def pixel_area(self) -> float: def pixel_area(self) -> float:
"""The area of a `Pixel` on the grid in square kilometers.""" """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 @classmethod
def gridify(cls, city: db.City, side_length: int) -> db.Grid: # noqa:WPS210 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 # Constraints
__table_args__ = ( __table_args__ = (
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['customer_id'], ['customers.id'], onupdate='RESTRICT', ondelete='RESTRICT', ['customer_id'],
['customers.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
), ),
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['courier_id'], ['couriers.id'], onupdate='RESTRICT', ondelete='RESTRICT', ['courier_id'],
['couriers.id'],
onupdate='RESTRICT',
ondelete='RESTRICT',
), ),
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['pickup_address_id'], ['pickup_address_id'],
@ -259,7 +265,8 @@ class Order(meta.Base): # noqa:WPS214
), ),
*( *(
sa.CheckConstraint( sa.CheckConstraint(
constraint, name='ordered_timestamps_{index}'.format(index=index), constraint,
name='ordered_timestamps_{index}'.format(index=index),
) )
for index, constraint in enumerate( for index, constraint in enumerate(
( (
@ -434,7 +441,8 @@ class Order(meta.Base): # noqa:WPS214
Goes together with `.courier_late`. Goes together with `.courier_late`.
""" """
return max( return max(
datetime.timedelta(), self.scheduled_pickup_at - self.reached_pickup_at, datetime.timedelta(),
self.scheduled_pickup_at - self.reached_pickup_at,
) )
@property @property
@ -448,7 +456,8 @@ class Order(meta.Base): # noqa:WPS214
Goes together with `.courier_early`. Goes together with `.courier_early`.
""" """
return max( return max(
datetime.timedelta(), self.reached_pickup_at - self.scheduled_pickup_at, datetime.timedelta(),
self.reached_pickup_at - self.scheduled_pickup_at,
) )
@property @property
@ -542,7 +551,8 @@ class Order(meta.Base): # noqa:WPS214
def __repr__(self) -> str: def __repr__(self) -> str:
"""Non-literal text representation.""" """Non-literal text representation."""
return '<{cls}(#{order_id})>'.format( 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 def draw(self) -> folium.Map: # pragma: no cover

View file

@ -36,7 +36,10 @@ class Pixel(meta.Base):
# Constraints # Constraints
__table_args__ = ( __table_args__ = (
sa.ForeignKeyConstraint( 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_x', name='n_x_is_positive'),
sa.CheckConstraint('0 <= n_y', name='n_y_is_positive'), sa.CheckConstraint('0 <= n_y', name='n_y_is_positive'),
@ -54,7 +57,9 @@ class Pixel(meta.Base):
def __repr__(self) -> str: def __repr__(self) -> str:
"""Non-literal text representation.""" """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, cls=self.__class__.__name__,
x=self.n_x,
y=self.n_y,
) )
# Convenience properties # Convenience properties
@ -81,7 +86,9 @@ class Pixel(meta.Base):
self.grid.city.southwest.northing + ((self.n_y + 1) * self.side_length), self.grid.city.southwest.northing + ((self.n_y + 1) * self.side_length),
) )
latitude, longitude = utm.to_latlon( 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) location = utils.Location(latitude, longitude)
@ -101,7 +108,9 @@ class Pixel(meta.Base):
self.grid.city.southwest.northing + (self.n_y * self.side_length), self.grid.city.southwest.northing + (self.n_y * self.side_length),
) )
latitude, longitude = utm.to_latlon( 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) location = utils.Location(latitude, longitude)
@ -137,7 +146,9 @@ class Pixel(meta.Base):
return self.grid.city.map return self.grid.city.map
def draw( # noqa:C901,WPS210 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: ) -> folium.Map:
"""Draw the pixel on the `.grid.city.map`. """Draw the pixel on the `.grid.city.map`.
@ -248,7 +259,9 @@ class Pixel(meta.Base):
else: else:
address.draw( address.draw(
radius=1, color=config.RESTAURANT_COLOR, tooltip=tooltip, radius=1,
color=config.RESTAURANT_COLOR,
tooltip=tooltip,
) )
return self.map return self.map

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