Clean up the comments and lint the notebooks #22

Merged
alexander merged 19 commits from lint-cleanups into develop 2026-12-03 12:26:19 +01:00
72 changed files with 767 additions and 753 deletions

View file

@ -17,8 +17,7 @@ runs:
r-cran-zoo \ r-cran-zoo \
-y -y
# Built wheels (e.g., `rpy2`) and Python versions # Built wheels (e.g., `rpy2`) and Python versions, keyed by their pins
# => A new key whenever the pinned dependencies or Python versions change
# => Only the "lint" job in ci.yaml saves the cache # => Only the "lint" job in ci.yaml saves the cache
- name: Restore the `uv` cache - name: Restore the `uv` cache
id: uv-cache id: uv-cache

View file

@ -57,3 +57,36 @@ cf2534f41e9e535b8f68a38bb3e0ebadf3fb19b3
# Capitalize the explanations after "=>" # Capitalize the explanations after "=>"
0090145b654c098cc464aed757e6c1fdda7487bd 0090145b654c098cc464aed757e6c1fdda7487bd
# Remove periods from one-sentence comments
049a5f6f62e05f08ffdcb6ce90c1f07ec3042871
# Break multi-line comments before conjunctions
2f1afd459fe73c2ab4136acaa1f87ecf64212e9f
# Put identifiers in comments into backticks
ff7f705bc831734bbab63a43fd78a11121696bc5
# Reword the comments in `velofy.db`
1413d08ed9115501fa2757b97de23525581d9acf
# Reword the comments in `velofy.forecasts`
9b8fe8b8fd41e920954ce4cda5b2fd5e70b44185
# Reword the comments in the rest of `velofy`
0f6970922623a7bda82b78bb48d5fb05646e7d45
# Reword the comments in the test suite
bca4250b4d9512dde4f67996f21f4c4bc9c18387
# Reword the comments in the config files
51f68743e537a9ffa744f47e65313485b0ecd3c5
# Explain the "why" in a few more comments
f90f263dab12013cc1353381e6ee3258df5e9176
# Refer to sources with "See:" in comments
c18fc2ba59ed9286336da113604a98f423cbc32f
# Put the `ruff` per-file ignores on separate lines
47a22f9587f94fa5bc2705302a3e29dca3701dcf

View file

@ -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)

View file

@ -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",

View file

@ -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

View file

@ -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",

View file

@ -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",

View file

@ -97,6 +97,9 @@ PACKAGE_LOCATION = "src/"
DOCS_BUILD = ".cache/docs/" DOCS_BUILD = ".cache/docs/"
DOCS_LOCATION = "docs/" DOCS_LOCATION = "docs/"
# Only `ruff` lints the notebooks because the formatters would rewrite them
NOTEBOOKS_LOCATION = "research/"
SCRIPTS_LOCATION = "scripts/" SCRIPTS_LOCATION = "scripts/"
TESTS_LOCATION = "tests/" TESTS_LOCATION = "tests/"
@ -266,6 +269,8 @@ def lint_code(session: nox.Session) -> None:
# Interpret extra arguments as `locations` of source files # Interpret extra arguments as `locations` of source files
locations = session.posargs or SRC_LOCATIONS locations = session.posargs or SRC_LOCATIONS
ruff_locations = session.posargs or (*SRC_LOCATIONS, NOTEBOOKS_LOCATION)
# `flake8` reads the "[tool.flake8]" section in pyproject.toml # `flake8` reads the "[tool.flake8]" section in pyproject.toml
# only with the `flake8-pyproject` plugin installed # only with the `flake8-pyproject` plugin installed
session.run("flake8", "--version") session.run("flake8", "--version")
@ -275,7 +280,7 @@ def lint_code(session: nox.Session) -> None:
session.run("isort", "--check-only", *locations) session.run("isort", "--check-only", *locations)
session.run("ruff", "--version") session.run("ruff", "--version")
session.run("ruff", "check", *locations) session.run("ruff", "check", *ruff_locations)
session.run("mypy", "--version") session.run("mypy", "--version")
session.run("mypy", *TYPECHECK_LOCATIONS) session.run("mypy", *TYPECHECK_LOCATIONS)
@ -299,9 +304,8 @@ def test_code(session: nox.Session) -> None:
session.run("pytest", "--version") session.run("pytest", "--version")
pytest_default_args = ( pytest_default_args = (
# See "[tool.coverage]" in pyproject.toml for `coverage` settings, # See "[tool.coverage]" in pyproject.toml for the branch coverage,
# for example, branch coverage and report format, # the report format, and the mapping to src/
# and "[tool.coverage.paths]" mapping `coverage` to src/
"--cov", "--cov",
"--no-cov-on-fail", "--no-cov-on-fail",
"--cov-fail-under=100", "--cov-fail-under=100",
@ -478,10 +482,8 @@ def lock_dependencies(session: nox.Session) -> None:
""" """
do_not_accept_arguments(session) do_not_accept_arguments(session)
# Little hack: Create a flag in the env(ironment) # `session.notify()` would start a new `nox.Session` without the flag
# and call `upgrade_dependencies()` directly # => Set the flag in the env(ironment) and call `upgrade_dependencies()` directly
# because `session.notify()` starts sessions with a new
# `nox.Session` object that does not have the flag set
session.env["_lock_only"] = "true" session.env["_lock_only"] = "true"
upgrade_dependencies(session) upgrade_dependencies(session)

View file

@ -26,9 +26,8 @@ license = "MIT"
readme = "README.md" readme = "README.md"
classifiers = [ classifiers = [
# All `SUPPORTED_PYTHONS` listed here are automatically # `nox` loads all `SUPPORTED_PYTHONS` listed here
# loaded by `nox`, our task runner, and made available # => The test suite runs with each of them in isolated environments
# for testing in isolated environments
"Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14", "Programming Language :: Python :: 3.14",
"Programming Language :: Python :: 3.15", "Programming Language :: Python :: 3.15",
@ -151,7 +150,7 @@ verify-db = [
[tool.autoflake] [tool.autoflake]
# Source: https://github.com/PyCQA/autoflake#configuration # See: https://github.com/PyCQA/autoflake#configuration
in-place = true in-place = true
recursive = true recursive = true
@ -172,7 +171,7 @@ line-length = 88
[tool.coverage] [tool.coverage]
# Source: https://coverage.readthedocs.io/en/latest/config.html # See: https://coverage.readthedocs.io/en/latest/config.html
[tool.coverage.paths] [tool.coverage.paths]
@ -202,10 +201,10 @@ source = ["velofy"]
[tool.flake8] [tool.flake8]
# Source: https://flake8.pycqa.org/en/latest/user/configuration.html # See: 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
@ -318,8 +317,7 @@ select = [
# "UP", # "UP",
] ]
# By default, flake8 ignores some errors. # flake8 ignores some errors by default => Ignore nothing
# Instead, do not ignore anything.
ignore = [] ignore = []
# If --ignore is passed on the command # If --ignore is passed on the command
@ -327,56 +325,53 @@ 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 # See: 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 = [
# Top-levels of a sub-packages are intended to import a lot. # Type annotations are not strictly enforced
"**/__init__.py:F401",
# 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",
] ]
# Explicitly set mccabe's maximum complexity to 10 as recommended by # 10 as recommended by Thomas McCabe, the metric's inventor, and the NIST
# Thomas McCabe, the inventor of the McCabe complexity, and the NIST. # See: https://en.wikipedia.org/wiki/Cyclomatic_complexity#Limiting_complexity_during_development
# Source: https://en.wikipedia.org/wiki/Cyclomatic_complexity#Limiting_complexity_during_development
max-complexity = 10 max-complexity = 10
# Comply with black's style. # Comply with black's style
# Source: https://github.com/psf/black/blob/master/docs/the_black_code_style.md#line-length # See: 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
@ -387,7 +382,7 @@ check-yield-types = false
# flake8-docstrings # flake8-docstrings
docstring-convention = "google" docstring-convention = "google"
# flake8-quotes # flake8-quotes
# Source: https://github.com/zheller/flake8-quotes#configuration # See: https://github.com/zheller/flake8-quotes#configuration
avoid-escape = true avoid-escape = true
docstring-quotes = "double" docstring-quotes = "double"
inline-quotes = "double" inline-quotes = "double"
@ -398,7 +393,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]))
@ -409,7 +404,7 @@ pytest-parametrize-values-type = "list"
[tool.isort] [tool.isort]
# Source: https://pycqa.github.io/isort/docs/configuration/options.html # See: https://pycqa.github.io/isort/docs/configuration/options.html
atomic = true atomic = true
case_sensitive = false # Implied by "force_alphabetical_sort_within_sections" case_sensitive = false # Implied by "force_alphabetical_sort_within_sections"
@ -419,7 +414,7 @@ lines_after_imports = 2
remove_redundant_aliases = true remove_redundant_aliases = true
# Comply with black's style # Comply with black's style
# Source: https://github.com/psf/black/blob/master/docs/compatible_configs.md#isort # See: https://github.com/psf/black/blob/master/docs/compatible_configs.md#isort
ensure_newline_before_comments = true ensure_newline_before_comments = true
force_grid_wrap = 0 force_grid_wrap = 0
include_trailing_comma = true include_trailing_comma = true
@ -429,13 +424,13 @@ use_parentheses = true
# Comply with Google's Python Style Guide # Comply with Google's Python Style Guide
# => All imports go on a single line # => All imports go on a single line
# Source: https://google.github.io/styleguide/pyguide.html#313-imports-formatting # See: https://google.github.io/styleguide/pyguide.html#313-imports-formatting
force_single_line = true force_single_line = true
[tool.mypy] [tool.mypy]
# Source: https://mypy.readthedocs.io/en/stable/config_file.html # See: https://mypy.readthedocs.io/en/stable/config_file.html
cache_dir = ".cache/mypy" cache_dir = ".cache/mypy"
@ -529,7 +524,7 @@ ignore_missing_imports = true
[tool.pyright] [tool.pyright]
# Source: https://microsoft.github.io/pyright/#/configuration # See: https://microsoft.github.io/pyright/#/configuration
# Check against the oldest supported Python version, not the one running `pyright` # Check against the oldest supported Python version, not the one running `pyright`
pythonVersion = "3.13" pythonVersion = "3.13"
@ -540,7 +535,7 @@ useLibraryCodeForTypes = false
[tool.pytest.ini_options] [tool.pytest.ini_options]
# Source: https://docs.pytest.org/en/stable/reference/reference.html#ini-options-ref # See: https://docs.pytest.org/en/stable/reference/reference.html#ini-options-ref
cache_dir = ".cache/pytest" cache_dir = ".cache/pytest"
@ -576,7 +571,7 @@ markers = [
[tool.ruff] [tool.ruff]
# Source: https://docs.astral.sh/ruff/ # See: https://docs.astral.sh/ruff/
cache-dir = ".cache/ruff" cache-dir = ".cache/ruff"
@ -707,19 +702,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",
] ]
@ -733,24 +728,41 @@ external = [
[tool.ruff.lint.per-file-ignores] [tool.ruff.lint.per-file-ignores]
# Top-levels of a sub-packages are intended to import a lot. "migrations/env.py" = [
"**/__init__.py" = ["F401"] "ANN0", "ANN2", # Type annotations are not strictly enforced
# Type annotations are not strictly enforced. ]
"migrations/env.py" = ["ANN0", "ANN2"]
# - ANN0, ANN2 => Type annotations are not strictly enforced. "migrations/versions/*.py" = [
# - S608 => Do not worry about SQL injection here. "ANN0", "ANN2", # Type annotations are not strictly enforced
"migrations/versions/*.py" = ["ANN0", "ANN2", "S608"] "S608", # Do not worry about SQL injection here
# Type annotations are not strictly enforced. ]
"noxfile.py" = ["ANN0", "ANN2"]
# `print()` is ok in ad-hoc scripts "noxfile.py" = [
"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.
# - PLR0913, PLR0917 => `pytest` passes fixtures as arguments. "research/*.ipynb" = [
# - S101 => `assert` statements are ok in the test suite. "ANN0", "ANN2", # Type annotations are not strictly enforced
# - S311 => The `random` module is not used for cryptography. "E501", # Exploratory cells read better unwrapped
# - SLF001 => Tests may set up and inspect private members. "E712", # `== True` filters `pandas` columns element-wise
"tests/**/*.py" = ["ANN0", "ANN2", "D106", "PLR0913", "PLR0917", "S101", "S311", "SLF001"] "PTH", # Paths stay `str`s as in the stored outputs
"S101", # `assert` statements document expectations
"S605", "S608", # No untrusted input
"T20", # `print()` shows results
]
"scripts/**" = [
"T20", # `print()` is ok in ad-hoc scripts
]
"tests/**/*.py" = [
"ANN0", "ANN2", # Type annotations are not strictly enforced
"D106", # The `Meta` class inside the factory_boy models do not need a docstring
"PLR0913", "PLR0917", # `pytest` passes fixtures as arguments
"S101", # `assert` statements are ok in the test suite
"S311", # The `random` module is not used for cryptography
"SLF001", # Tests may set up and inspect private members
]
[tool.ruff.lint.flake8-pytest-style] # aligned with [tool.flake8] above [tool.ruff.lint.flake8-pytest-style] # aligned with [tool.flake8] above
@ -814,7 +826,7 @@ convention = "google"
[tool.uv] [tool.uv]
# Source: https://docs.astral.sh/uv/reference/settings/ # See: https://docs.astral.sh/uv/reference/settings/
required-version = ">=0.13.10,<0.14.0" # Same range as "uv_build" above required-version = ">=0.13.10,<0.14.0" # Same range as "uv_build" above

View file

@ -19,6 +19,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"import contextlib\n",
"import getpass\n", "import getpass\n",
"import os\n", "import os\n",
"import shutil" "import shutil"
@ -110,10 +111,8 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"# Create a fresh folder for the R dependencies.\n", "# Create a fresh folder for the R dependencies.\n",
"try:\n", "with contextlib.suppress(FileNotFoundError):\n",
" shutil.rmtree(r_libs_path)\n", " shutil.rmtree(r_libs_path)\n",
"except FileNotFoundError:\n",
" pass\n",
"os.makedirs(r_libs_path)" "os.makedirs(r_libs_path)"
] ]
}, },
@ -1840,7 +1839,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"from velofy import init_r" "from velofy import init_r # noqa: F401"
] ]
} }
], ],

File diff suppressed because it is too large Load diff

View file

@ -46,7 +46,8 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"from velofy import config, db" "from velofy import config as pkg_config\n",
"from velofy import db"
] ]
}, },
{ {
@ -105,7 +106,7 @@
} }
], ],
"source": [ "source": [
"config.GRID_SIDE_LENGTHS # choose one of these values" "pkg_config.GRID_SIDE_LENGTHS # choose one of these values"
] ]
}, },
{ {

View file

@ -45,7 +45,7 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"import datetime as dt\n", "import datetime as dt\n",
"import matplotlib\n", "\n",
"import matplotlib.pyplot as plt" "import matplotlib.pyplot as plt"
] ]
}, },
@ -55,8 +55,11 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"from velofy import config, db\n", "from velofy import config as pkg_config\n",
"from velofy.forecasts import methods, models, timify\n", "from velofy import db\n",
"from velofy.forecasts import methods\n",
"from velofy.forecasts import models\n",
"from velofy.forecasts import timify\n",
"from velofy.forecasts.methods import decomposition" "from velofy.forecasts.methods import decomposition"
] ]
}, },
@ -75,7 +78,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"matplotlib.style.use(\"ggplot\")" "plt.style.use(\"ggplot\")"
] ]
}, },
{ {
@ -125,7 +128,7 @@
} }
], ],
"source": [ "source": [
"config.GRID_SIDE_LENGTHS # possible values" "pkg_config.GRID_SIDE_LENGTHS # possible values"
] ]
}, },
{ {
@ -154,7 +157,7 @@
} }
], ],
"source": [ "source": [
"config.TIME_STEPS # possible values" "pkg_config.TIME_STEPS # possible values"
] ]
}, },
{ {

View file

@ -51,7 +51,8 @@
"source": [ "source": [
"import googlemaps as gm\n", "import googlemaps as gm\n",
"\n", "\n",
"from velofy import config, db" "from velofy import config as pkg_config\n",
"from velofy import db"
] ]
}, },
{ {
@ -297,7 +298,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"client = gm.Client(config.GOOGLE_MAPS_API_KEY)" "client = gm.Client(pkg_config.GOOGLE_MAPS_API_KEY)"
] ]
}, },
{ {

View file

@ -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

View file

@ -27,34 +27,33 @@ 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
# Side lengths (in meters) for which pixel grids are created. # Side lengths (in meters) of the pixel grids
# They are the basis for the aggregated demand forecasts. # => They are the basis for the aggregated demand forecasts
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) for the forecasting models
# For now, we only use 7 and 8 weeks as that was the best performing in # => 7 and 8 weeks performed best in 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 +64,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"
@ -118,19 +117,16 @@ def make_config(env: str = "production") -> Config:
msg = "Must be either 'production' or 'testing'" msg = "Must be either 'production' or 'testing'"
raise ValueError(msg) raise ValueError(msg)
# Without a PostgreSQL database the package cannot work. # pytest sets `TESTING` and fails all "db" tests without a database anyway
# As pytest sets the "TESTING" environment variable explicitly, # => Warn only outside pytest
# the warning is only emitted if the code is not run by pytest.
# We see the bad configuration immediately as all "db" tests fail.
if config.DATABASE_URI is None and not os.getenv("TESTING"): if config.DATABASE_URI is None and not os.getenv("TESTING"):
warnings.warn( warnings.warn(
"Bad configuration: no DATABASE_URI set in the environment", "Bad configuration: no DATABASE_URI set in the environment",
stacklevel=2, stacklevel=2,
) )
# Some functionalities require R and some packages installed. # The R packages live in a project-local folder for isolation and reproducibility
# To ensure isolation and reproducibility, the projects keeps the R dependencies # => Its path must be set in the environment
# in a project-local folder that must be set in the environment.
if config.R_LIBS_PATH is None and not os.getenv("TESTING"): if config.R_LIBS_PATH is None and not os.getenv("TESTING"):
warnings.warn( warnings.warn(
"Bad configuration: no R_LIBS set in the environment", "Bad configuration: no R_LIBS set in the environment",

View file

@ -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,16 +96,15 @@ 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 # Continue on the day of the last prediction ...
# commands are added the make `Forecast`s without the heuristic! # (assuming that no other command makes `Forecast`s)
# Continue with forecasting on the day the last prediction was made ...
last_predict_at = db.session.scalar( last_predict_at = db.session.scalar(
sa.select(sa.func.max(db.Forecast.start_at)) sa.select(sa.func.max(db.Forecast.start_at))
.join(db.Pixel, db.Forecast.pixel_id == db.Pixel.id) .join(db.Pixel, db.Forecast.pixel_id == db.Pixel.id)
@ -116,7 +115,7 @@ def tactical_heuristic( # noqa:C901,D417,DOC001
.where(db.Forecast.train_horizon == train_horizon), .where(db.Forecast.train_horizon == train_horizon),
) )
# ... or start `train_horizon` weeks after the first `Order` # ... or start `train_horizon` weeks after the first `Order`
# if no `Forecast`s are in the database yet. # if no `Forecast`s are in the database yet
if last_predict_at is None: if last_predict_at is None:
predict_day = order_history.first_order_at(pixel_id=pixel.id).date() predict_day = order_history.first_order_at(pixel_id=pixel.id).date()
predict_day += dt.timedelta(weeks=train_horizon) predict_day += dt.timedelta(weeks=train_horizon)
@ -125,7 +124,7 @@ def tactical_heuristic( # noqa:C901,D417,DOC001
# Go over all days in chronological order ... # Go over all days in chronological order ...
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, pixel_id=pixel.id,
predict_day=predict_day, predict_day=predict_day,
@ -136,7 +135,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,

View file

@ -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())

View file

@ -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()

View file

@ -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",

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