Merge branch 'rework-nox' into develop
All checks were successful
CI / Checks (Python 3.13) (push) Successful in 1m31s

This commit is contained in:
Alexander Hess 2026-11-27 13:47:25 +01:00
commit 0ce8840bed
Signed by: alexander
GPG key ID: B46EDB4DFC26805D
10 changed files with 4515 additions and 6107 deletions

View file

@ -14,8 +14,8 @@ defaults:
jobs: jobs:
test: checks:
name: Tests (Python 3.13) name: Checks (Python 3.13)
runs-on: debian-13 runs-on: debian-13
# Throwaway database, reachable from the job as host `postgres` # Throwaway database, reachable from the job as host `postgres`
@ -26,19 +26,26 @@ jobs:
POSTGRES_USER: user POSTGRES_USER: user
POSTGRES_PASSWORD: password POSTGRES_PASSWORD: password
POSTGRES_DB: db POSTGRES_DB: db
# Start the steps only once the database accepts connections
options: >-
--health-cmd "pg_isready --username=user --dbname=db"
--health-interval 2s
--health-timeout 5s
--health-retries 15
# Same variables as in `.env` on `nehemiah`, the main development machine # Same variables as in `.env` on `nehemiah`, the main development machine
env: env:
DATABASE_URI: postgresql://user:password@postgres:5432/db DATABASE_URI: postgresql://user:password@postgres:5432/db
GOOGLE_MAPS_API_KEY: AIzaDummyKeyForTests # Fake key to mock the Google API GOOGLE_MAPS_API_KEY: AIzaDummyKeyForTests # Fake key to mock the Google API
R_LIBS: /usr/lib/R/site-library R_LIBS: /usr/lib/R/site-library
UV_PYTHON_PREFERENCE: only-managed # Only uv's Python has the headers to build `rpy2`
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v6
- name: Install system packages (R) - name: Install R via system packages
run: | run: |
apt-get update apt-get update
apt-get install --no-install-recommends \ apt-get install --no-install-recommends \
@ -47,18 +54,24 @@ jobs:
r-cran-zoo \ r-cran-zoo \
-y -y
- name: Install development tool chain (Python, uv, poetry) # Same `uv` version as pinned in pyproject.toml
- name: Install `uv` and `python3.13`
run: | run: |
curl -LsSf https://astral.sh/uv/install.sh | sh curl -LsSf https://astral.sh/uv/0.13.10/install.sh | sh
echo "$HOME/.local/bin" >> "$GITHUB_PATH" echo "$HOME/.local/bin" >> "$GITHUB_PATH"
"$HOME/.local/bin/uv" python install 3.13 "$HOME/.local/bin/uv" python install 3.13
"$HOME/.local/bin/uv" tool install --python 3.13 'poetry>=2'
- name: Install the project - name: Install `velofy` and its dependencies
run: | run: uv sync --locked
uv venv --python 3.13 --seed .venv
poetry sync --no-interaction - name: Ensure `nox -s format` changes nothing
run: uv run nox -s format && git diff --exit-code
- name: Lint the source files
run: uv run nox -s lint
# `TESTING=true` comes from `pyproject.toml`
- name: Run the test suite - name: Run the test suite
run: poetry run pytest -q run: uv run nox -s test
- name: Run the doctests
run: uv run nox -s doctest

View file

@ -16,16 +16,16 @@ that iteratively build on each other.
### Data Cleaning ### Data Cleaning
The UDP provided its raw data as a PostgreSQL dump. The UDP provided its raw data as a PostgreSQL dump.
This [notebook](https://code.webartifex.de/alexander/velofy/src/branch/develop/research/01_clean_data.ipynb) This [notebook](research/01_clean_data.ipynb)
cleans the data extensively cleans the data extensively
and maps them onto the [ORM models](https://code.webartifex.de/alexander/velofy/src/branch/develop/src/velofy/db) and maps them onto the [ORM models](src/velofy/db)
defined in the `velofy` package defined in the `velofy` package
that is developed in the [src/](https://code.webartifex.de/alexander/velofy/src/branch/develop/src) folder that is developed in the [src/](src) folder
and contains all source code to drive the analyses. and contains all source code to drive the analyses.
Due to a non-disclosure agreement with the UDP, Due to a non-disclosure agreement with the UDP,
neither the raw nor the cleaned data are published as of now. neither the raw nor the cleaned data are published as of now.
However, previews of the data can be seen throughout the [research/](https://code.webartifex.de/alexander/velofy/src/branch/develop/research) folder. However, previews of the data can be seen throughout the [research/](research) folder.
### Tactical Demand Forecasting ### Tactical Demand Forecasting
@ -34,9 +34,9 @@ Before any optimizations of the UDP's operations are done,
a **demand forecasting** system for *tactical* purposes is implemented. a **demand forecasting** system for *tactical* purposes is implemented.
To achieve that, the cities first undergo a **gridification** step To achieve that, the cities first undergo a **gridification** step
where each *pickup* location is assigned into a pixel on a "checker board"-like grid. where each *pickup* location is assigned into a pixel on a "checker board"-like grid.
The main part of the source code that implements that is in this [file](https://code.webartifex.de/alexander/velofy/src/branch/develop/src/velofy/db/grids.py#L60). The main part of the source code that implements that is in this [file](src/velofy/db/grids.py#L60).
Visualizations of the various grids can be found in the [visualizations/](https://code.webartifex.de/alexander/velofy/src/branch/develop/research/visualizations) folder Visualizations of the various grids can be found in the [visualizations/](research/visualizations) folder
and in this [notebook](https://code.webartifex.de/alexander/velofy/src/branch/develop/research/03_grid_visualizations.ipynb). and in this [notebook](research/03_grid_visualizations.ipynb).
Then, demand is aggregated on a per-pixel level Then, demand is aggregated on a per-pixel level
and different kinds of order time series are generated. and different kinds of order time series are generated.
@ -47,7 +47,7 @@ The details of how this works can be found in the first academic paper
published in the context of this research project published in the context of this research project
and titled "*Real-time Demand Forecasting for an Urban Delivery Platform*" and titled "*Real-time Demand Forecasting for an Urban Delivery Platform*"
(cf., the [repository](https://code.webartifex.de/alexander/velofy-forecasting) with the LaTeX files). (cf., the [repository](https://code.webartifex.de/alexander/velofy-forecasting) with the LaTeX files).
All demand forecasting related code is in the [forecasts/](https://code.webartifex.de/alexander/velofy/src/branch/develop/src/velofy/forecasts) sub-package. All demand forecasting related code is in the [forecasts/](src/velofy/forecasts) sub-package.
### Predictive Routing ### Predictive Routing
@ -62,20 +62,20 @@ you can clone the project with [git](https://git-scm.com/)
and install the contained `velofy` package and install the contained `velofy` package
and all its dependencies and all its dependencies
in a [virtual environment](https://docs.python.org/3/tutorial/venv.html) in a [virtual environment](https://docs.python.org/3/tutorial/venv.html)
with [poetry](https://python-poetry.org/docs/): with [uv](https://docs.astral.sh/uv/):
`git clone ssh://git@git.webartifex.de/alexander/velofy.git` `git clone ssh://git@git.webartifex.de/alexander/velofy.git`
and and
`poetry install --extras research` `uv sync --extra research`
The `--extras` option is necessary as the non-develop dependencies The `--extra` option is necessary as the non-develop dependencies
are structured in the [pyproject.toml](https://code.webartifex.de/alexander/velofy/src/branch/develop/pyproject.toml) file are structured in the [pyproject.toml](pyproject.toml) file
into dependencies related to only the `velofy` source code package into dependencies related to only the `velofy` source code package
and dependencies used to run the [Jupyter](https://jupyter.org/) environment and dependencies used to run the [Jupyter](https://jupyter.org/) environment
with the analyses. with the analyses.
Contributions are welcome. Contributions are welcome.
Use the [issues](https://code.webartifex.de/alexander/velofy/issues) tab. Use the [issues](https://code.webartifex.de/alexander/velofy/issues) tab.
The project is licensed under the [MIT license](https://code.webartifex.de/alexander/velofy/src/branch/develop/LICENSE.txt). The project is licensed under the [MIT license](LICENSE.txt).

File diff suppressed because it is too large Load diff

5590
poetry.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,8 @@
[build-system] [build-system]
build-backend = "poetry.core.masonry.api" build-backend = "uv_build"
requires = ["poetry-core>=2.0.0,<3.0.0"]
requires = ["uv_build (>=0.13.10,<0.14.0)"] # Same range as in "[tool.uv]" below
@ -24,25 +25,32 @@ license = "MIT"
readme = "README.md" readme = "README.md"
classifiers = [
# All `SUPPORTED_PYTHONS` listed here are automatically
# loaded by `nox`, our task runner, and made available
# for testing in isolated environments
"Programming Language :: Python :: 3.13",
]
requires-python = ">=3.13,<4.0" requires-python = ">=3.13,<4.0"
# Package => Code developed in *.py files and packaged under src/velofy # Package => Code developed in *.py files and packaged under src/velofy
dependencies = [ dependencies = [
"Shapely>=2.2.0,<3", "Shapely (>=2.2.0,<3.0.0)",
"alembic>=1.20.1,<2", "alembic (>=1.20.1,<2.0.0)",
"click>=8.5.1,<9", "click (>=8.5.1,<9.0.0)",
"folium>=1.0.0,<2", "folium (>=1.0.0,<2.0.0)",
"geopy>=2.5.0,<3", "geopy (>=2.5.0,<3.0.0)",
"googlemaps>=4.10.0,<5", "googlemaps (>=4.10.0,<5.0.0)",
"matplotlib>=3.11.2,<4", "matplotlib (>=3.11.2,<4.0.0)",
"ordered-set>=4.1.0,<5", "ordered-set (>=4.1.0,<5.0.0)",
"pandas>=3.1.1,<4", "pandas (>=3.1.1,<4.0.0)",
"psycopg[binary]>=3.3.9,<4", # Adapter for PostgreSQL "psycopg[binary] (>=3.3.9,<4.0.0)", # Adapter for PostgreSQL
"rpy2>=3.6.9,<4", "rpy2 (>=3.6.9,<4.0.0)",
"sqlalchemy>=2.1.9,<3", "sqlalchemy (>=2.1.9,<3.0.0)",
"statsmodels>=0.15.0,<0.16", "statsmodels (>=0.15.0,<0.16.0)",
"utm>=0.9.0,<0.10", "utm (>=0.9.0,<0.10.0)",
] ]
@ -50,9 +58,9 @@ dependencies = [
# `jupyter lab` => Notebooks with analyses using the developed package # `jupyter lab` => Notebooks with analyses using the developed package
research = [ research = [
"jupyterlab>=4.6.6,<5", "jupyterlab (>=4.6.6,<5.0.0)",
"numpy>=2.5.5,<3", "numpy (>=2.5.5,<3.0.0)",
"pytz>=2026.6", "pytz (>=2026.6)",
] ]
@ -68,6 +76,58 @@ repository = "https://code.webartifex.de/alexander/velofy"
[dependency-groups]
dev = [
# Task Runners
"nox (>=2026.10.20)",
"pre-commit (>=4.7.0,<5.0.0)",
# Code Formatters
"autoflake (>=2.4.0,<3.0.0)",
"black (>=25.12.0,<26.0.0)",
"isort (>=9.0.2,<10.0.0)",
# Code Analyzers
"flake8 (>=7.5.0,<8.0.0)",
"flake8-annotations (>=3.3.1,<4.0.0)",
"flake8-black (>=0.5.0,<0.6.0)",
"flake8-pyproject (>=1.2.4,<2.0.0)",
"flake8-pytest-style (>=2.2.0,<3.0.0)",
"mypy (>=2.4.1,<3.0.0)",
]
test = [
"factory-boy (>=3.3.3,<4.0.0)",
"Faker (>=40.63.0,<41.0.0)",
"packaging (>=26.4)", # Used to test the packaged version
"pytest-cov (>=7.1.0,<8.0.0)",
"pytest-env (>=1.8.8,<2.0.0)",
"pytest-mock (>=3.17.0,<4.0.0)",
"pytest (>=9.2.0,<10.0.0)",
"xdoctest[colors] (>=1.3.2,<2.0.0)",
]
docs = [
"sphinx (>=9.2.0,<10.0.0)",
"sphinx-autodoc-typehints (>=3.17.7,<4.0.0)",
]
[tool.autoflake]
# Source: https://github.com/PyCQA/autoflake#configuration
in-place = true
recursive = true
expand-star-imports = true
remove-all-unused-imports = true
ignore-init-module-imports = true # modifies "remove-all-unused-imports"
remove-duplicate-keys = true
remove-unused-variables = true
[tool.black] [tool.black]
target-version = ["py313"] target-version = ["py313"]
@ -387,50 +447,26 @@ ignore_missing_imports = true
[tool.poetry.group.dev.dependencies]
# Task Runners
nox = ">=2026.10.20"
pre-commit = ">=4.7.0,<5"
# Code Formatters
autoflake = ">=2.4.0,<3"
black = ">=25.12.0,<26"
isort = ">=9.0.2,<10"
# Code Analyzers
flake8 = ">=7.5.0,<8"
flake8-annotations = ">=3.3.1,<4"
flake8-black = ">=0.5.0,<0.6"
flake8-pyproject = ">=1.2.4,<2"
flake8-pytest-style = ">=2.2.0,<3"
mypy = ">=2.4.1,<3"
# Test Suite
Faker = ">=40.63.0,<41"
factory-boy = ">=3.3.3,<4"
packaging = ">=26.4" # Used to test the packaged version
pytest = ">=9.2.0,<10"
pytest-cov = ">=7.1.0,<8"
pytest-env = ">=1.8.8,<2"
pytest-mock = ">=3.17.0,<4"
xdoctest = { version=">=1.3.2,<2", extras=["optional"] }
# Documentation
sphinx = ">=9.2.0,<10"
sphinx-autodoc-typehints = ">=3.17.7,<4"
[tool.pytest.ini_options] [tool.pytest.ini_options]
# Source: https://docs.pytest.org/en/stable/reference/reference.html#ini-options-ref # Source: https://docs.pytest.org/en/stable/reference/reference.html#ini-options-ref
cache_dir = ".cache/pytest" cache_dir = ".cache/pytest"
addopts = "--strict-markers" testpaths = ["tests"]
# "-ra" => Summarize skipped and `xfailed tests at the end
addopts = "-ra --strict-config --strict-markers"
console_output_style = "count" console_output_style = "count"
xfail_strict = true
required_plugins = [
"pytest-cov",
"pytest-env",
"pytest-mock",
]
env = [ env = [
"TESTING=true", "TESTING=true",
] ]
@ -444,3 +480,21 @@ markers = [
"e2e: non-db and non-r integration tests", "e2e: non-db and non-r integration tests",
"r: (integration) tests using rpy2", "r: (integration) tests using rpy2",
] ]
[tool.uv]
# Source: https://docs.astral.sh/uv/reference/settings/
required-version = ">=0.13.10,<0.14.0" # Same range as "uv_build" above
# `uv sync` installs all [dependency-groups] into the local develop environment
# whereas the `nox` sessions install only the groups they need
default-groups = "all"
# Rebuild the package when its source files change;
# by default, `uv` only watches the pyproject.toml file
cache-keys = [
{ file = "pyproject.toml" },
{ file = "src/**/*.py" },
]

View file

@ -19,7 +19,7 @@
"- numeric columns are checked for plausibility\n", "- numeric columns are checked for plausibility\n",
"- foreign key relationships are strictly enforced\n", "- foreign key relationships are strictly enforced\n",
"\n", "\n",
"The structure of the data can be viewed at the [ORM layer](https://code.webartifex.de/alexander/velofy/src/branch/develop/src/velofy/db) in the package." "The structure of the data can be viewed at the [ORM layer](../src/velofy/db) in the package."
] ]
}, },
{ {

View file

@ -621,7 +621,7 @@
"id": "fb6a035d", "id": "fb6a035d",
"metadata": {}, "metadata": {},
"source": [ "source": [
"In the application's code base, the above API calls and the related data are modeled as `Path` objects connecting two `Address` objects (cf. [Path class](https://code.webartifex.de/alexander/velofy/src/branch/develop/src/velofy/db/addresses_addresses.py) in the code).\n", "In the application's code base, the above API calls and the related data are modeled as `Path` objects connecting two `Address` objects (cf. [Path class](../src/velofy/db/addresses_addresses.py) in the code).\n",
"\n", "\n",
"Let's look at two examples addresses, one from a `Restaurant` and one from a `Customer`." "Let's look at two examples addresses, one from a `Restaurant` and one from a `Customer`."
] ]

View file

@ -0,0 +1,184 @@
#!/usr/bin/env python3
"""Show the latest version and age of all dependencies.
This script helps us keep an overview of which dependencies pinned in the
uv.lock file are out-of-date and how long ago releases were published.
It is run as part of the "deps-upgrade-check" `nox` session.
"""
import datetime
import http.client
import json
import pathlib
import textwrap
import tomllib
PKG_CONSIDERED_OLD = 2 # years after release when a package is considered "old"
PROJECT_ROOT = pathlib.Path(__file__).resolve().parent.parent
REPORT_FILE = PROJECT_ROOT / ".cache/dependencies_checked.txt"
def get_direct_dependencies(lock_file: dict) -> dict[str, str]:
"""Map the direct dependencies to "main" or their extra or group.
`lock_file` is a mapping as returned from `load_lock_file()`.
"""
root = next(
pkg for pkg in lock_file["package"] if "editable" in pkg.get("source", {})
)
labels = {dep["name"]: "main" for dep in root.get("dependencies", [])}
for kind in ("optional-dependencies", "dev-dependencies"):
for label, deps in root.get(kind, {}).items():
for dep in deps:
labels.setdefault(dep["name"], label)
return labels
def get_pinned_packages(lock_file: dict) -> dict[str, str]:
"""Map all packages from PyPI to their versions.
`lock_file` is a mapping as returned from `load_lock_file()`.
"""
return {
pkg["name"]: pkg["version"]
for pkg in lock_file["package"]
if "registry" in pkg.get("source", {})
}
def get_years_since_release(
package_name: str,
pinned_version: str,
) -> tuple[float | None, str | None]:
"""Get the years since the pinned release and the latest version."""
conn = http.client.HTTPSConnection("pypi.org")
conn.request("GET", f"/pypi/{package_name}/json")
response = conn.getresponse()
if response.status != 200:
return None, None
data = json.loads(response.read().decode())
all_releases_on_pypi = data.get("releases", {})
infos_for_pinned_release = all_releases_on_pypi.get(pinned_version, [])
if not infos_for_pinned_release:
return None, None
latest_version = data["info"]["version"]
release_date = infos_for_pinned_release[0]["upload_time"]
release_date = datetime.datetime.fromisoformat(release_date.replace("Z", "+00:00"))
years_since_release = (datetime.datetime.now() - release_date).days / 365.25
return round(years_since_release, 1), latest_version
def load_lock_file() -> dict:
"""Load the uv.lock file."""
return tomllib.loads((PROJECT_ROOT / "uv.lock").read_text())
def make_comment(
pinned_version: str,
years_since_release: float | None,
latest_version: str | None,
) -> tuple[str, bool]:
"""Describe a pinned package and decide if it is shown on the CLI."""
if years_since_release is None:
return "no info on PyPI", True
is_latest = pinned_version == latest_version
if is_latest:
comment = "up-to-date"
else:
comment = f"< {latest_version:<8}"
if years_since_release > PKG_CONSIDERED_OLD:
comment += f" {years_since_release} years ago"
print_to_cli = not is_latest or years_since_release > PKG_CONSIDERED_OLD
return comment.strip(), print_to_cli
def write_report(lines: list[tuple[str, bool]]) -> None:
"""Write all lines to the report file and the noteworthy ones to the CLI."""
header = f"""
# Created on: {datetime.date.today()}
#
# The versions pinned in the uv.lock file are amended with information
# regarding the latest available version on PyPI and the no. of years
# that have passed since the pinned version was released on PyPI,
# if > {PKG_CONSIDERED_OLD} year(s).
#
# The purpose of these information is to judge whether
# time should be invested to upgrade further dependencies,
# which likely requires rewriting some of the code.
#
#
"""
titles = (
f"# {'Package (pinned)':<40} {'Direct':<10}"
f"{'PyPI (latest)':<17}Released (pinned)"
)
header = (
textwrap.dedent(header)[1:] + titles + "\n#" + "=" * (len(titles) - 1) + "\n"
)
REPORT_FILE.parent.mkdir(exist_ok=True)
with REPORT_FILE.open("w") as f:
f.write(header)
print(header, end="")
for line, print_to_cli in lines:
f.write(line)
if print_to_cli:
print(line, end="")
def check_all_pinned_packages() -> None:
"""Check all packages from PyPI that are pinned in the uv.lock file."""
lock_file = load_lock_file()
direct_dependencies = get_direct_dependencies(lock_file)
lines = []
for package, pinned_version in sorted(get_pinned_packages(lock_file).items()):
years_since_release, latest_version = get_years_since_release(
package,
pinned_version,
)
comment, print_to_cli = make_comment(
pinned_version,
years_since_release,
latest_version,
)
requirement = f"{package}=={pinned_version}"
direct = direct_dependencies.get(package, "")
lines.append((f"{requirement:<40} # {direct:<10}{comment}\n", print_to_cli))
write_report(lines)
if __name__ == "__main__":
check_all_pinned_packages()

View file

@ -47,7 +47,8 @@ class Location: # noqa:WPS214
Convention is {ZONE} {EASTING} {NORTHING}. Convention is {ZONE} {EASTING} {NORTHING}.
Example: Example:
`<Location: 17T 630084 4833438>'` >>> Location(43.6532, -79.3832)
<Location: 17T 630378 4834625>
""" """
return f'<Location: {self.zone} {self.easting} {self.northing}>' # noqa:WPS221 return f'<Location: {self.zone} {self.easting} {self.northing}>' # noqa:WPS221

3733
uv.lock generated Normal file

File diff suppressed because it is too large Load diff