Remove periods from one-sentence comments
This commit is contained in:
parent
454c2898a0
commit
049a5f6f62
60 changed files with 308 additions and 308 deletions
|
|
@ -10,13 +10,13 @@ from velofy import config as pkg_config
|
||||||
from velofy import db
|
from velofy import db
|
||||||
|
|
||||||
|
|
||||||
# Disable the --sql option, a.k.a, the "offline mode".
|
# Disable the --sql option, a.k.a, the "offline mode"
|
||||||
if context.is_offline_mode():
|
if context.is_offline_mode():
|
||||||
msg = "The --sql option is not implemented in this project"
|
msg = "The --sql option is not implemented in this project"
|
||||||
raise NotImplementedError(msg)
|
raise NotImplementedError(msg)
|
||||||
|
|
||||||
|
|
||||||
# Set up the default Python logger from the alembic.ini file.
|
# Set up the default Python logger from the alembic.ini file
|
||||||
log_config.fileConfig(context.config.config_file_name)
|
log_config.fileConfig(context.config.config_file_name)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,7 @@ def upgrade():
|
||||||
"side_length",
|
"side_length",
|
||||||
name=op.f("uq_grids_on_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")),
|
||||||
schema=config.CLEAN_SCHEMA,
|
schema=config.CLEAN_SCHEMA,
|
||||||
)
|
)
|
||||||
|
|
@ -90,7 +90,7 @@ def upgrade():
|
||||||
schema=config.CLEAN_SCHEMA,
|
schema=config.CLEAN_SCHEMA,
|
||||||
)
|
)
|
||||||
|
|
||||||
# This `UniqueConstraint` is needed by the `addresses_pixels` table below.
|
# This `UniqueConstraint` is needed by the `addresses_pixels` table below
|
||||||
op.create_unique_constraint(
|
op.create_unique_constraint(
|
||||||
"uq_addresses_on_id_city_id",
|
"uq_addresses_on_id_city_id",
|
||||||
"addresses",
|
"addresses",
|
||||||
|
|
|
||||||
|
|
@ -326,7 +326,7 @@ def upgrade():
|
||||||
""",
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
# 4) Ensure every `Restaurant` has only one `Order.pickup_address`.
|
# 4) Ensure every `Restaurant` has only one `Order.pickup_address`
|
||||||
op.execute(
|
op.execute(
|
||||||
f"""
|
f"""
|
||||||
UPDATE
|
UPDATE
|
||||||
|
|
|
||||||
|
|
@ -23,15 +23,15 @@ config = configuration.make_config("testing" if os.getenv("TESTING") else "produ
|
||||||
|
|
||||||
def upgrade():
|
def upgrade():
|
||||||
"""Upgrade to revision 81aa304d7a6e."""
|
"""Upgrade to revision 81aa304d7a6e."""
|
||||||
# Drop unnecessary check constraint.
|
# Drop unnecessary check constraint
|
||||||
op.execute( # `.delivery_at` is not set for `.cancelled` orders anyways.
|
op.execute( # `.delivery_at` is not set for `.cancelled` orders anyways
|
||||||
f"""
|
f"""
|
||||||
ALTER TABLE {config.CLEAN_SCHEMA}.orders
|
ALTER TABLE {config.CLEAN_SCHEMA}.orders
|
||||||
DROP CONSTRAINT ck_orders_on_ordered_timestamps_21;
|
DROP CONSTRAINT ck_orders_on_ordered_timestamps_21;
|
||||||
""",
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
# Add forgotten check constraints to the `orders` table.
|
# Add forgotten check constraints to the `orders` table
|
||||||
op.execute(
|
op.execute(
|
||||||
f"""
|
f"""
|
||||||
ALTER TABLE {config.CLEAN_SCHEMA}.orders
|
ALTER TABLE {config.CLEAN_SCHEMA}.orders
|
||||||
|
|
@ -57,7 +57,7 @@ def upgrade():
|
||||||
""",
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
# This `UniqueConstraint` is needed by the `replayed_orders` table below.
|
# This `UniqueConstraint` is needed by the `replayed_orders` table below
|
||||||
op.create_unique_constraint(
|
op.create_unique_constraint(
|
||||||
"uq_orders_on_id_ad_hoc",
|
"uq_orders_on_id_ad_hoc",
|
||||||
"orders",
|
"orders",
|
||||||
|
|
@ -125,7 +125,7 @@ def upgrade():
|
||||||
ondelete="RESTRICT",
|
ondelete="RESTRICT",
|
||||||
),
|
),
|
||||||
sa.ForeignKeyConstraint(
|
sa.ForeignKeyConstraint(
|
||||||
# Needs the `UniqueConstraint` from above.
|
# Needs the `UniqueConstraint` from above
|
||||||
["actual_order_id", "ad_hoc"],
|
["actual_order_id", "ad_hoc"],
|
||||||
[
|
[
|
||||||
f"{config.CLEAN_SCHEMA}.orders.id",
|
f"{config.CLEAN_SCHEMA}.orders.id",
|
||||||
|
|
|
||||||
|
|
@ -29,7 +29,7 @@ config = configuration.make_config("testing" if os.getenv("TESTING") else "produ
|
||||||
|
|
||||||
|
|
||||||
# The order matters: the "ordered_timestamps_N" constraints are shifted
|
# The order matters: the "ordered_timestamps_N" constraints are shifted
|
||||||
# by one from the top down such that every new name is free.
|
# by one from the top down such that every new name is free
|
||||||
RENAMES = (
|
RENAMES = (
|
||||||
(
|
(
|
||||||
"forecasts",
|
"forecasts",
|
||||||
|
|
|
||||||
|
|
@ -205,7 +205,7 @@ source = ["velofy"]
|
||||||
# Source: https://flake8.pycqa.org/en/latest/user/configuration.html
|
# Source: https://flake8.pycqa.org/en/latest/user/configuration.html
|
||||||
|
|
||||||
# Include error classes only explicitly
|
# Include error classes only explicitly
|
||||||
# to avoid forward compatibility issues.
|
# to avoid forward compatibility issues
|
||||||
select = [
|
select = [
|
||||||
# =============
|
# =============
|
||||||
# flake8's base
|
# flake8's base
|
||||||
|
|
@ -327,41 +327,41 @@ ignore = []
|
||||||
extend-ignore = [
|
extend-ignore = [
|
||||||
# `ruff`'s A003 does this better, as it only flags actual shadowing
|
# `ruff`'s A003 does this better, as it only flags actual shadowing
|
||||||
"A003",
|
"A003",
|
||||||
# Too long line => Duplicate with E501.
|
# Too long line => Duplicate with E501
|
||||||
"B950",
|
"B950",
|
||||||
# PEP 257 documents the arguments of `__init__()` in its own docstring.
|
# PEP 257 documents the arguments of `__init__()` in its own docstring
|
||||||
"DOC301",
|
"DOC301",
|
||||||
# Comply with black's style.
|
# Comply with black's style.
|
||||||
# Source: https://github.com/psf/black/blob/master/docs/compatible_configs.md#flake8
|
# Source: https://github.com/psf/black/blob/master/docs/compatible_configs.md#flake8
|
||||||
"E203", "W503",
|
"E203", "W503",
|
||||||
# `ruff`'s FBT003 does this better, as it allows builtins like `setattr()`.
|
# `ruff`'s FBT003 does this better, as it allows builtins like `setattr()`
|
||||||
"FBT003",
|
"FBT003",
|
||||||
# Every `.add()` looks like `pandas` to this rule (`ruff` omits it).
|
# Every `.add()` looks like `pandas` to this rule (`ruff` omits it)
|
||||||
"PD005",
|
"PD005",
|
||||||
# Let's not do `@pytest.mark.no_cover()` instead of `@pytest.mark.no_cover`.
|
# Let's not do `@pytest.mark.no_cover()` instead of `@pytest.mark.no_cover`
|
||||||
"PT023",
|
"PT023",
|
||||||
# Allow f-strings as the only type of string formatting.
|
# Allow f-strings as the only type of string formatting
|
||||||
"SFS301",
|
"SFS301",
|
||||||
# `bool()` around a comparison can be deliberate (`ruff` omits this rule).
|
# `bool()` around a comparison can be deliberate (`ruff` omits this rule)
|
||||||
"SIM901",
|
"SIM901",
|
||||||
# TODOs need neither an author nor an issue.
|
# TODOs need neither an author nor an issue
|
||||||
"T002", "T003",
|
"T002", "T003",
|
||||||
# Messages are written where the exceptions are raised.
|
# Messages are written where the exceptions are raised
|
||||||
"TRY003",
|
"TRY003",
|
||||||
]
|
]
|
||||||
|
|
||||||
per-file-ignores = [
|
per-file-ignores = [
|
||||||
# Type annotations are not strictly enforced.
|
# Type annotations are not strictly enforced
|
||||||
"migrations/env.py:ANN0,ANN2",
|
"migrations/env.py:ANN0,ANN2",
|
||||||
# - ANN0, ANN2 => Type annotations are not strictly enforced.
|
# - ANN0, ANN2 => Type annotations are not strictly enforced
|
||||||
# - S608 => Do not worry about SQL injection here.
|
# - S608 => Do not worry about SQL injection here
|
||||||
"migrations/versions/*.py:ANN0,ANN2,S608",
|
"migrations/versions/*.py:ANN0,ANN2,S608",
|
||||||
# Type annotations are not strictly enforced.
|
# Type annotations are not strictly enforced
|
||||||
"noxfile.py:ANN0,ANN2",
|
"noxfile.py:ANN0,ANN2",
|
||||||
# - ANN0, ANN2, DOC106, DOC107 => Type annotations are not strictly enforced.
|
# - ANN0, ANN2, DOC106, DOC107 => Type annotations are not strictly enforced
|
||||||
# - D106 => The `Meta` class inside the factory_boy models do not need a docstring.
|
# - D106 => The `Meta` class inside the factory_boy models do not need a docstring
|
||||||
# - S101 => `assert` statements are ok in the test suite.
|
# - S101 => `assert` statements are ok in the test suite
|
||||||
# - S311 => The `random` module is not used for cryptography.
|
# - S311 => The `random` module is not used for cryptography
|
||||||
"tests/*.py:ANN0,ANN2,D106,DOC106,DOC107,S101,S311",
|
"tests/*.py:ANN0,ANN2,D106,DOC106,DOC107,S101,S311",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -374,7 +374,7 @@ max-complexity = 10
|
||||||
# Source: https://github.com/psf/black/blob/master/docs/the_black_code_style.md#line-length
|
# Source: https://github.com/psf/black/blob/master/docs/the_black_code_style.md#line-length
|
||||||
max-line-length = 88
|
max-line-length = 88
|
||||||
|
|
||||||
# Preview the code lines that cause errors.
|
# Preview the code lines that cause errors
|
||||||
show-source = true
|
show-source = true
|
||||||
|
|
||||||
# pydoclint
|
# pydoclint
|
||||||
|
|
@ -396,7 +396,7 @@ unused-arguments-ignore-abstract-functions = true
|
||||||
# ==============================
|
# ==============================
|
||||||
# flake8-pytest-style's settings
|
# flake8-pytest-style's settings
|
||||||
# ==============================
|
# ==============================
|
||||||
# Prefer @pytest.fixture over @pytest.fixture().
|
# Prefer @pytest.fixture over @pytest.fixture()
|
||||||
pytest-fixture-no-parentheses = true
|
pytest-fixture-no-parentheses = true
|
||||||
# Prefer @pytest.mark.parametrize(['param1', 'param2'], [(1, 2), (3, 4)])
|
# Prefer @pytest.mark.parametrize(['param1', 'param2'], [(1, 2), (3, 4)])
|
||||||
# over @pytest.mark.parametrize(('param1', 'param2'), ([1, 2], [3, 4]))
|
# over @pytest.mark.parametrize(('param1', 'param2'), ([1, 2], [3, 4]))
|
||||||
|
|
@ -705,19 +705,19 @@ select = [
|
||||||
]
|
]
|
||||||
|
|
||||||
extend-ignore = [
|
extend-ignore = [
|
||||||
# Let the formatter handle trailing commas.
|
# Let the formatter handle trailing commas
|
||||||
"COM812",
|
"COM812",
|
||||||
# Thresholds like the ones in the maps read better as literals.
|
# Thresholds like the ones in the maps read better as literals
|
||||||
"PLR2004",
|
"PLR2004",
|
||||||
# Let's not do `@pytest.mark.no_cover()` instead of `@pytest.mark.no_cover`.
|
# Let's not do `@pytest.mark.no_cover()` instead of `@pytest.mark.no_cover`
|
||||||
"PT023",
|
"PT023",
|
||||||
# An `elif` after a `return` keeps a case distinction together.
|
# An `elif` after a `return` keeps a case distinction together
|
||||||
"RET505",
|
"RET505",
|
||||||
# Some "# noqa" comments are only for `flake8`, which `ruff` cannot know.
|
# Some "# noqa" comments are only for `flake8`, which `ruff` cannot know
|
||||||
"RUF100",
|
"RUF100",
|
||||||
# TODOs need neither an author nor an issue.
|
# TODOs need neither an author nor an issue
|
||||||
"TD002", "TD003",
|
"TD002", "TD003",
|
||||||
# Messages are written where the exceptions are raised.
|
# Messages are written where the exceptions are raised
|
||||||
"TRY003",
|
"TRY003",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -731,21 +731,21 @@ external = [
|
||||||
|
|
||||||
[tool.ruff.lint.per-file-ignores]
|
[tool.ruff.lint.per-file-ignores]
|
||||||
|
|
||||||
# Type annotations are not strictly enforced.
|
# Type annotations are not strictly enforced
|
||||||
"migrations/env.py" = ["ANN0", "ANN2"]
|
"migrations/env.py" = ["ANN0", "ANN2"]
|
||||||
# - ANN0, ANN2 => Type annotations are not strictly enforced.
|
# - ANN0, ANN2 => Type annotations are not strictly enforced
|
||||||
# - S608 => Do not worry about SQL injection here.
|
# - S608 => Do not worry about SQL injection here
|
||||||
"migrations/versions/*.py" = ["ANN0", "ANN2", "S608"]
|
"migrations/versions/*.py" = ["ANN0", "ANN2", "S608"]
|
||||||
# Type annotations are not strictly enforced.
|
# Type annotations are not strictly enforced
|
||||||
"noxfile.py" = ["ANN0", "ANN2"]
|
"noxfile.py" = ["ANN0", "ANN2"]
|
||||||
# `print()` is ok in ad-hoc scripts
|
# `print()` is ok in ad-hoc scripts
|
||||||
"scripts/**" = ["T20"]
|
"scripts/**" = ["T20"]
|
||||||
# - ANN0, ANN2 => Type annotations are not strictly enforced.
|
# - ANN0, ANN2 => Type annotations are not strictly enforced
|
||||||
# - D106 => The `Meta` class inside the factory_boy models do not need a docstring.
|
# - D106 => The `Meta` class inside the factory_boy models do not need a docstring
|
||||||
# - PLR0913, PLR0917 => `pytest` passes fixtures as arguments.
|
# - PLR0913, PLR0917 => `pytest` passes fixtures as arguments
|
||||||
# - S101 => `assert` statements are ok in the test suite.
|
# - S101 => `assert` statements are ok in the test suite
|
||||||
# - S311 => The `random` module is not used for cryptography.
|
# - S311 => The `random` module is not used for cryptography
|
||||||
# - SLF001 => Tests may set up and inspect private members.
|
# - SLF001 => Tests may set up and inspect private members
|
||||||
"tests/**/*.py" = ["ANN0", "ANN2", "D106", "PLR0913", "PLR0917", "S101", "S311", "SLF001"]
|
"tests/**/*.py" = ["ANN0", "ANN2", "D106", "PLR0913", "PLR0917", "S101", "S311", "SLF001"]
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ Example:
|
||||||
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
|
||||||
|
|
||||||
from importlib import metadata as _metadata
|
from importlib import metadata as _metadata
|
||||||
|
|
|
||||||
|
|
@ -27,14 +27,14 @@ class Config:
|
||||||
# Application-specific settings
|
# Application-specific settings
|
||||||
# -----------------------------
|
# -----------------------------
|
||||||
|
|
||||||
# Date after which the real-life data is discarded.
|
# Date after which the real-life data is discarded
|
||||||
CUTOFF_DAY = dt.datetime(2017, 2, 1)
|
CUTOFF_DAY = dt.datetime(2017, 2, 1)
|
||||||
|
|
||||||
# If a scheduled pre-order is made within this
|
# If a scheduled pre-order is made within this
|
||||||
# time horizon, we treat it as an ad-hoc order.
|
# time horizon, we treat it as an ad-hoc order
|
||||||
QUASI_AD_HOC_LIMIT = dt.timedelta(minutes=45)
|
QUASI_AD_HOC_LIMIT = dt.timedelta(minutes=45)
|
||||||
|
|
||||||
# Operating hours of the platform.
|
# Operating hours of the platform
|
||||||
SERVICE_START = 11
|
SERVICE_START = 11
|
||||||
SERVICE_END = 23
|
SERVICE_END = 23
|
||||||
|
|
||||||
|
|
@ -43,7 +43,7 @@ class Config:
|
||||||
GRID_SIDE_LENGTHS = (707, 1000, 1414)
|
GRID_SIDE_LENGTHS = (707, 1000, 1414)
|
||||||
|
|
||||||
# Time steps (in minutes) used to aggregate the
|
# Time steps (in minutes) used to aggregate the
|
||||||
# individual orders into time series.
|
# individual orders into time series
|
||||||
TIME_STEPS = (60,)
|
TIME_STEPS = (60,)
|
||||||
|
|
||||||
# Training horizons (in full weeks) used to train the forecasting models.
|
# Training horizons (in full weeks) used to train the forecasting models.
|
||||||
|
|
@ -51,10 +51,10 @@ class Config:
|
||||||
# a previous study (note:4f79e8fa).
|
# a previous study (note:4f79e8fa).
|
||||||
TRAIN_HORIZONS = (7, 8)
|
TRAIN_HORIZONS = (7, 8)
|
||||||
|
|
||||||
# The demand forecasting methods used in the simulations.
|
# The demand forecasting methods used in the simulations
|
||||||
FORECASTING_METHODS = ("hets", "rtarima")
|
FORECASTING_METHODS = ("hets", "rtarima")
|
||||||
|
|
||||||
# Colors for the visualizations ins `folium`.
|
# Colors for the visualizations ins `folium`
|
||||||
RESTAURANT_COLOR = "red"
|
RESTAURANT_COLOR = "red"
|
||||||
CUSTOMER_COLOR = "blue"
|
CUSTOMER_COLOR = "blue"
|
||||||
NEUTRAL_COLOR = "black"
|
NEUTRAL_COLOR = "black"
|
||||||
|
|
@ -65,10 +65,10 @@ class Config:
|
||||||
DATABASE_URI = os.getenv("DATABASE_URI")
|
DATABASE_URI = os.getenv("DATABASE_URI")
|
||||||
GOOGLE_MAPS_API_KEY = os.getenv("GOOGLE_MAPS_API_KEY")
|
GOOGLE_MAPS_API_KEY = os.getenv("GOOGLE_MAPS_API_KEY")
|
||||||
|
|
||||||
# The PostgreSQL schema that holds the tables with the original data.
|
# The PostgreSQL schema that holds the tables with the original data
|
||||||
ORIGINAL_SCHEMA = os.getenv("ORIGINAL_SCHEMA") or "public"
|
ORIGINAL_SCHEMA = os.getenv("ORIGINAL_SCHEMA") or "public"
|
||||||
|
|
||||||
# The PostgreSQL schema that holds the tables with the cleaned data.
|
# The PostgreSQL schema that holds the tables with the cleaned data
|
||||||
CLEAN_SCHEMA = os.getenv("CLEAN_SCHEMA") or "clean"
|
CLEAN_SCHEMA = os.getenv("CLEAN_SCHEMA") or "clean"
|
||||||
|
|
||||||
ALEMBIC_TABLE = "alembic_version"
|
ALEMBIC_TABLE = "alembic_version"
|
||||||
|
|
|
||||||
|
|
@ -65,7 +65,7 @@ def tactical_heuristic( # noqa:C901,D417,DOC001
|
||||||
|
|
||||||
TRAIN_HORIZON: length of the training horizon; defaults to `8`
|
TRAIN_HORIZON: length of the training horizon; defaults to `8`
|
||||||
""" # noqa:D412,D417 => Formatted as `click` help text
|
""" # noqa:D412,D417 => Formatted as `click` help text
|
||||||
# Input validation.
|
# Input validation
|
||||||
|
|
||||||
try:
|
try:
|
||||||
city_obj = db.session.scalars(
|
city_obj = db.session.scalars(
|
||||||
|
|
@ -96,11 +96,11 @@ def tactical_heuristic( # noqa:C901,D417,DOC001
|
||||||
f"time_step={time_step}, train_horizon={train_horizon}",
|
f"time_step={time_step}, train_horizon={train_horizon}",
|
||||||
)
|
)
|
||||||
|
|
||||||
# Load the historic order data.
|
# Load the historic order data
|
||||||
order_history = timify.OrderHistory(grid=grid, time_step=time_step)
|
order_history = timify.OrderHistory(grid=grid, time_step=time_step)
|
||||||
order_history.aggregate_orders()
|
order_history.aggregate_orders()
|
||||||
|
|
||||||
# Run the tactical heuristic.
|
# Run the tactical heuristic
|
||||||
|
|
||||||
for pixel in grid.pixels:
|
for pixel in grid.pixels:
|
||||||
# Important: this check may need to be adapted once further
|
# Important: this check may need to be adapted once further
|
||||||
|
|
@ -136,7 +136,7 @@ def tactical_heuristic( # noqa:C901,D417,DOC001
|
||||||
f"for {predict_day} with {model.name}",
|
f"for {predict_day} with {model.name}",
|
||||||
)
|
)
|
||||||
|
|
||||||
# Only loop over the time steps corresponding to working hours.
|
# Only loop over the time steps corresponding to working hours
|
||||||
predict_at = dt.datetime(
|
predict_at = dt.datetime(
|
||||||
predict_day.year,
|
predict_day.year,
|
||||||
predict_day.month,
|
predict_day.month,
|
||||||
|
|
|
||||||
|
|
@ -36,7 +36,7 @@ def gridify() -> None: # pragma: no cover note:b1f68d24
|
||||||
click.echo(f" -> created {len(grid.pixels)} pixels")
|
click.echo(f" -> created {len(grid.pixels)} pixels")
|
||||||
|
|
||||||
# Because the number of assigned addresses is the same across
|
# Because the number of assigned addresses is the same across
|
||||||
# different `side_length`s, we can take the last `grid` from the `city`.
|
# different `side_length`s, we can take the last `grid` from the `city`
|
||||||
last_grid_id = grid.id # type: ignore[possibly-undefined]
|
last_grid_id = grid.id # type: ignore[possibly-undefined]
|
||||||
n_assigned = db.session.execute(
|
n_assigned = db.session.execute(
|
||||||
sa.select(sa.func.count())
|
sa.select(sa.func.count())
|
||||||
|
|
|
||||||
|
|
@ -16,14 +16,14 @@ def show_version(
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Show the package's version."""
|
"""Show the package's version."""
|
||||||
# If --version / -V is NOT passed in,
|
# If --version / -V is NOT passed in,
|
||||||
# continue with the command.
|
# continue with the command
|
||||||
if not value or ctx.resilient_parsing:
|
if not value or ctx.resilient_parsing:
|
||||||
return
|
return
|
||||||
|
|
||||||
# Mimic the colors of `poetry version`.
|
# Mimic the colors of `poetry version`
|
||||||
pkg_name = click.style(velofy.__pkg_name__, fg="green")
|
pkg_name = click.style(velofy.__pkg_name__, fg="green")
|
||||||
version = click.style(velofy.__version__, fg="blue")
|
version = click.style(velofy.__version__, fg="blue")
|
||||||
# Include a warning for development versions.
|
# Include a warning for development versions
|
||||||
warning = click.style(" (development)", fg="red") if ".dev" in version else ""
|
warning = click.style(" (development)", fg="red") if ".dev" in version else ""
|
||||||
click.echo(f"{pkg_name}, version {version}{warning}")
|
click.echo(f"{pkg_name}, version {version}{warning}")
|
||||||
ctx.exit()
|
ctx.exit()
|
||||||
|
|
|
||||||
|
|
@ -95,7 +95,7 @@ class Address(meta.Base):
|
||||||
"-180 <= longitude AND longitude <= 180",
|
"-180 <= longitude AND longitude <= 180",
|
||||||
name="longitude_between_180_degrees",
|
name="longitude_between_180_degrees",
|
||||||
),
|
),
|
||||||
# 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",
|
"30000 <= zip_code AND zip_code <= 99999",
|
||||||
|
|
|
||||||
|
|
@ -48,7 +48,7 @@ class Path(meta.Base):
|
||||||
sa.SmallInteger,
|
sa.SmallInteger,
|
||||||
nullable=False,
|
nullable=False,
|
||||||
)
|
)
|
||||||
# Distances are measured in meters.
|
# Distances are measured in meters
|
||||||
air_distance: orm.Mapped[int] = orm.mapped_column(
|
air_distance: orm.Mapped[int] = orm.mapped_column(
|
||||||
sa.Integer,
|
sa.Integer,
|
||||||
nullable=False,
|
nullable=False,
|
||||||
|
|
@ -57,12 +57,12 @@ class Path(meta.Base):
|
||||||
sa.Integer,
|
sa.Integer,
|
||||||
nullable=True,
|
nullable=True,
|
||||||
)
|
)
|
||||||
# The duration is measured in seconds.
|
# The duration is measured in seconds
|
||||||
bicycle_duration: orm.Mapped[int | None] = orm.mapped_column(
|
bicycle_duration: orm.Mapped[int | None] = orm.mapped_column(
|
||||||
sa.Integer,
|
sa.Integer,
|
||||||
nullable=True,
|
nullable=True,
|
||||||
)
|
)
|
||||||
# An array of latitude-longitude pairs approximating a courier's way.
|
# An array of latitude-longitude pairs approximating a courier's way
|
||||||
_directions: orm.Mapped[list[list[float]] | None] = orm.mapped_column(
|
_directions: orm.Mapped[list[list[float]] | None] = orm.mapped_column(
|
||||||
"directions",
|
"directions",
|
||||||
psql.JSON,
|
psql.JSON,
|
||||||
|
|
@ -71,7 +71,7 @@ class Path(meta.Base):
|
||||||
|
|
||||||
# Constraints
|
# Constraints
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
# The two `Address` objects must be in the same `.city`.
|
# The two `Address` objects must be in the same `.city`
|
||||||
sa.ForeignKeyConstraint(
|
sa.ForeignKeyConstraint(
|
||||||
["first_address_id", "city_id"],
|
["first_address_id", "city_id"],
|
||||||
["addresses.id", "addresses.city_id"],
|
["addresses.id", "addresses.city_id"],
|
||||||
|
|
@ -84,7 +84,7 @@ class Path(meta.Base):
|
||||||
onupdate="RESTRICT",
|
onupdate="RESTRICT",
|
||||||
ondelete="RESTRICT",
|
ondelete="RESTRICT",
|
||||||
),
|
),
|
||||||
# Each `Address`-`Address` pair only has one distance.
|
# 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(
|
sa.CheckConstraint(
|
||||||
"first_address_id < second_address_id",
|
"first_address_id < second_address_id",
|
||||||
|
|
@ -96,7 +96,7 @@ class Path(meta.Base):
|
||||||
),
|
),
|
||||||
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",
|
"air_distance <= bicycle_distance",
|
||||||
|
|
@ -212,7 +212,7 @@ class Path(meta.Base):
|
||||||
https://developers.google.com/maps/documentation/directions
|
https://developers.google.com/maps/documentation/directions
|
||||||
"""
|
"""
|
||||||
# To save costs, we do not make an API call
|
# To save costs, we do not make an API call
|
||||||
# if we already have data from Google Maps.
|
# if we already have data from Google Maps
|
||||||
if self.bicycle_distance is not None:
|
if self.bicycle_distance is not None:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
@ -302,11 +302,11 @@ class Path(meta.Base):
|
||||||
`.map` for convenience in interactive usage
|
`.map` for convenience in interactive usage
|
||||||
"""
|
"""
|
||||||
# Without `self._directions` synced from Google Maps,
|
# Without `self._directions` synced from Google Maps,
|
||||||
# the `.waypoints` are not available.
|
# the `.waypoints` are not available
|
||||||
self.sync_with_google_maps()
|
self.sync_with_google_maps()
|
||||||
|
|
||||||
# First, plot the couriers' path between the start and
|
# First, plot the couriers' path between the start and
|
||||||
# end locations, so that it is below the `folium.Circle`s.
|
# end locations, so that it is below the `folium.Circle`s
|
||||||
line = folium.PolyLine(
|
line = folium.PolyLine(
|
||||||
locations=(
|
locations=(
|
||||||
self.first_address.location.lat_lng,
|
self.first_address.location.lat_lng,
|
||||||
|
|
@ -319,7 +319,7 @@ class Path(meta.Base):
|
||||||
line.add_to(self.map)
|
line.add_to(self.map)
|
||||||
|
|
||||||
# Draw the path's start and end locations, possibly reversed,
|
# Draw the path's start and end locations, possibly reversed,
|
||||||
# on top of the couriers' path.
|
# on top of the couriers' path
|
||||||
|
|
||||||
if reverse:
|
if reverse:
|
||||||
start, end = self.second_address, self.first_address
|
start, end = self.second_address, self.first_address
|
||||||
|
|
|
||||||
|
|
@ -53,9 +53,9 @@ class AddressPixelAssociation(meta.Base):
|
||||||
onupdate="RESTRICT",
|
onupdate="RESTRICT",
|
||||||
ondelete="RESTRICT",
|
ondelete="RESTRICT",
|
||||||
),
|
),
|
||||||
# Each `Address` can only be on a `Grid` once.
|
# 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.
|
# An association must reference an existing `Grid`-`Pixel` pair
|
||||||
sa.ForeignKeyConstraint(
|
sa.ForeignKeyConstraint(
|
||||||
["pixel_id", "grid_id"],
|
["pixel_id", "grid_id"],
|
||||||
["pixels.id", "pixels.grid_id"],
|
["pixels.id", "pixels.grid_id"],
|
||||||
|
|
|
||||||
|
|
@ -78,7 +78,7 @@ class City(meta.Base):
|
||||||
back_populates="city",
|
back_populates="city",
|
||||||
)
|
)
|
||||||
|
|
||||||
# We do not implement a `.__init__()` method and use SQLAlchemy's default.
|
# We do not implement a `.__init__()` method and use SQLAlchemy's default
|
||||||
|
|
||||||
def __repr__(self) -> str:
|
def __repr__(self) -> str:
|
||||||
"""Non-literal text representation."""
|
"""Non-literal text representation."""
|
||||||
|
|
@ -162,7 +162,7 @@ class City(meta.Base):
|
||||||
Returns:
|
Returns:
|
||||||
`.map` for convenience in interactive usage
|
`.map` for convenience in interactive usage
|
||||||
"""
|
"""
|
||||||
# Obtain all primary `Address`es in the city that host `Restaurant`s.
|
# Obtain all primary `Address`es in the city that host `Restaurant`s
|
||||||
addresses = db.session.scalars(
|
addresses = db.session.scalars(
|
||||||
sa.select(db.Address).where(
|
sa.select(db.Address).where(
|
||||||
db.Address.id.in_(
|
db.Address.id.in_(
|
||||||
|
|
@ -236,7 +236,7 @@ class City(meta.Base):
|
||||||
Returns:
|
Returns:
|
||||||
`.map` for convenience in interactive usage
|
`.map` for convenience in interactive usage
|
||||||
"""
|
"""
|
||||||
# First, create a color map with distinct colors for each zip code.
|
# First, create a color map with distinct colors for each zip code
|
||||||
all_zip_codes = sorted(
|
all_zip_codes = sorted(
|
||||||
row[0]
|
row[0]
|
||||||
for row in db.session.execute(
|
for row in db.session.execute(
|
||||||
|
|
@ -258,9 +258,9 @@ class City(meta.Base):
|
||||||
for index, code in enumerate(all_zip_codes)
|
for index, code in enumerate(all_zip_codes)
|
||||||
}
|
}
|
||||||
|
|
||||||
# Second, draw every address on the `.map.
|
# Second, draw every address on the `.map`
|
||||||
for address in self.addresses:
|
for address in self.addresses:
|
||||||
# Non-primary addresses are covered by primary ones anyway.
|
# Non-primary addresses are covered by primary ones anyway
|
||||||
if not address.is_primary:
|
if not address.is_primary:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,7 @@ def get_engine() -> sa.Engine:
|
||||||
|
|
||||||
# `scoped_session()` accepts any callable creating sessions
|
# `scoped_session()` accepts any callable creating sessions
|
||||||
# while its type stubs expect a `sessionmaker`
|
# while its type stubs expect a `sessionmaker`
|
||||||
# => The lambda defers creating the engine to first use.
|
# => The lambda defers creating the engine to first use
|
||||||
session: orm.scoped_session[orm.Session] = orm.scoped_session(
|
session: orm.scoped_session[orm.Session] = orm.scoped_session(
|
||||||
t.cast(
|
t.cast(
|
||||||
"orm.sessionmaker[orm.Session]",
|
"orm.sessionmaker[orm.Session]",
|
||||||
|
|
|
||||||
|
|
@ -70,7 +70,7 @@ class Customer(meta.Base):
|
||||||
# That is not true for `Restaurant`s after the data cleaning.
|
# That is not true for `Restaurant`s after the data cleaning.
|
||||||
|
|
||||||
# Obtain all primary `Address`es where
|
# Obtain all primary `Address`es where
|
||||||
# at least one delivery was made to `self`.
|
# at least one delivery was made to `self`
|
||||||
delivery_addresses = db.session.scalars(
|
delivery_addresses = db.session.scalars(
|
||||||
sa.select(db.Address).where(
|
sa.select(db.Address).where(
|
||||||
db.Address.id.in_(
|
db.Address.id.in_(
|
||||||
|
|
|
||||||
|
|
@ -63,7 +63,7 @@ class Forecast(meta.Base):
|
||||||
nullable=False,
|
nullable=False,
|
||||||
)
|
)
|
||||||
# The confidence intervals are treated like the `.prediction`s
|
# The confidence intervals are treated like the `.prediction`s
|
||||||
# but they may be nullable as some methods do not calculate them.
|
# but they may be nullable as some methods do not calculate them
|
||||||
low80: orm.Mapped[float | None] = orm.mapped_column(
|
low80: orm.Mapped[float | None] = orm.mapped_column(
|
||||||
psql.DOUBLE_PRECISION,
|
psql.DOUBLE_PRECISION,
|
||||||
nullable=True,
|
nullable=True,
|
||||||
|
|
@ -165,7 +165,7 @@ class Forecast(meta.Base):
|
||||||
""",
|
""",
|
||||||
name="ci95_must_be_wider_than_ci80",
|
name="ci95_must_be_wider_than_ci80",
|
||||||
),
|
),
|
||||||
# There can be only one prediction per forecasting setting.
|
# There can be only one prediction per forecasting setting
|
||||||
sa.UniqueConstraint(
|
sa.UniqueConstraint(
|
||||||
"pixel_id",
|
"pixel_id",
|
||||||
"start_at",
|
"start_at",
|
||||||
|
|
|
||||||
|
|
@ -43,9 +43,9 @@ class Grid(meta.Base):
|
||||||
ondelete="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`
|
||||||
sa.UniqueConstraint("city_id", "side_length"),
|
sa.UniqueConstraint("city_id", "side_length"),
|
||||||
# Needed by a `ForeignKeyConstraint` in `address_pixel_association`.
|
# Needed by a `ForeignKeyConstraint` in `address_pixel_association`
|
||||||
sa.UniqueConstraint("id", "city_id"),
|
sa.UniqueConstraint("id", "city_id"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -88,10 +88,10 @@ class Grid(meta.Base):
|
||||||
|
|
||||||
city.grids.append(grid)
|
city.grids.append(grid)
|
||||||
|
|
||||||
# `Pixel`s grouped by `.n_x`-`.n_y` coordinates.
|
# `Pixel`s grouped by `.n_x`-`.n_y` coordinates
|
||||||
pixels = {}
|
pixels = {}
|
||||||
|
|
||||||
# `.unique()` because the `JOIN` yields an `Address` once per `Order`.
|
# `.unique()` because the `JOIN` yields an `Address` once per `Order`
|
||||||
pickup_addresses = (
|
pickup_addresses = (
|
||||||
db.session.scalars(
|
db.session.scalars(
|
||||||
sa.select(db.Address)
|
sa.select(db.Address)
|
||||||
|
|
@ -123,7 +123,7 @@ class Grid(meta.Base):
|
||||||
|
|
||||||
pixel = pixels[(n_x, n_y)]
|
pixel = pixels[(n_x, n_y)]
|
||||||
|
|
||||||
# Create an association between the `address` and `pixel`.
|
# Create an association between the `address` and `pixel`
|
||||||
assoc = db.AddressPixelAssociation(address=address, pixel=pixel)
|
assoc = db.AddressPixelAssociation(address=address, pixel=pixel)
|
||||||
pixel.addresses.append(assoc)
|
pixel.addresses.append(assoc)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -275,7 +275,7 @@ class Order(meta.Base):
|
||||||
onupdate="RESTRICT",
|
onupdate="RESTRICT",
|
||||||
ondelete="RESTRICT",
|
ondelete="RESTRICT",
|
||||||
),
|
),
|
||||||
# Needed by a `ForeignKeyConstraint` in `ReplayedOrder`.
|
# Needed by a `ForeignKeyConstraint` in `ReplayedOrder`
|
||||||
sa.UniqueConstraint("id", "ad_hoc"),
|
sa.UniqueConstraint("id", "ad_hoc"),
|
||||||
sa.CheckConstraint(
|
sa.CheckConstraint(
|
||||||
"""
|
"""
|
||||||
|
|
@ -789,7 +789,7 @@ class Order(meta.Base):
|
||||||
customer_tooltip = f"Customer #{self.customer.id}"
|
customer_tooltip = f"Customer #{self.customer.id}"
|
||||||
|
|
||||||
# Because the underlying distance matrix is symmetric (i.e., a DB constraint),
|
# 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.
|
# we must check if the `.pickup_address` is the couriers' `Path`'s start
|
||||||
if path.first_address is self.pickup_address:
|
if path.first_address is self.pickup_address:
|
||||||
reverse = False
|
reverse = False
|
||||||
start_tooltip, end_tooltip = restaurant_tooltip, customer_tooltip
|
start_tooltip, end_tooltip = restaurant_tooltip, customer_tooltip
|
||||||
|
|
@ -797,7 +797,7 @@ class Order(meta.Base):
|
||||||
reverse = True
|
reverse = True
|
||||||
start_tooltip, end_tooltip = customer_tooltip, restaurant_tooltip
|
start_tooltip, end_tooltip = customer_tooltip, restaurant_tooltip
|
||||||
|
|
||||||
# This triggers `Path.sync_with_google_maps()` behind the scenes.
|
# This triggers `Path.sync_with_google_maps()` behind the scenes
|
||||||
return path.draw(
|
return path.draw(
|
||||||
reverse=reverse,
|
reverse=reverse,
|
||||||
start_tooltip=start_tooltip,
|
start_tooltip=start_tooltip,
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue