Python 3.14 evaluates annotations lazily (PEP 649),
so forward references need no quotes.
We make the tool targets, the lock files,
and the CI matrix follow the new minimum.
In order to use the new features,
we must drop support for Python 3.13
All jobs restore built wheels (e.g., `rpy2`) and the Python versions
instead of building or fetching them again.
Only the "lint" job saves the cache, pruned to what is expensive to rebuild,
and only when its key changed; so, five jobs do not compress the same archive
in parallel, and unchanged runs skip the 15s of packing.
The test sessions run as a matrix, each with its own database.
This also adds the "test-with" sessions to CI;
so, the setup installs all `SUPPORTED_PYTHONS` via `uv`,
as `nox` would otherwise pick the system Python 3.13,
which lacks the headers to build `rpy2`.
The version in the name broke the required status check
when 3.14 became the `MAIN_PYTHON`.
The timeout ensures the CI server stays ready
even when something goes badly wrong.
Without a configured version, `mypy` and `pyright`
check against the Python that runs them.
With `MAIN_PYTHON` at 3.14, they would accept
`stdlib` APIs and `typing` features new in 3.14.
Yet, `requires-python` promises 3.13;
so, the type checkers must flag such code.
`black` and `ruff` already target 3.13 for the same reason.
In the "sequentially" variant of the test database,
`current_db_revision()` must return the head of the migrations;
in the "all_at_once" variant, there is no version table.
The `@db_revision` decorator no longer runs `alembic current` in a subprocess,
which only worked from the project folder and reported any failure as a wrong revision.
Also, its docstring now explains that it locks completed stages of the data pipeline.
The column is of type `JSON`,
but the code stored a JSON-encoded string in it;
so, the data was encoded twice.
A later data migration converts the existing rows.
The global `db.session` is now a `scoped_session`,
like, for example, in Flask-SQLAlchemy.
Importing the package no longer creates an engine;
so, the placeholder for the tests is obsolete.
The `db_session` fixture replaces `db.session` with `monkeypatch`
such that it is reset after each test.
Tests without the fixture get a placeholder that fails loudly
instead of opening a real session,
which would block the `DROP SCHEMA` at the end of the test run.
`Session.query()` is the legacy API in SQLAlchemy 2.x.
`.one_or_none()` expresses that the unique constraint
on the five filtered columns allows at most one cached `Forecast`.
`Session.query()` is the legacy API in SQLAlchemy 2.x.
The addresses with restaurants are now selected with a subquery in one statement.
The `_restaurants_mock` fixture mocks the new call chain.
`Session.query()` is the legacy API in SQLAlchemy 2.x.
Unlike `Query`, `select()` does not deduplicate single entities from a `JOIN`;
so, `Grid.gridify()` calls `.unique()` explicitly.
The `addresses_mock` fixtures mock the new call chain.
The migrations create foreign keys from the `CLEAN_SCHEMA`
into the `ORIGINAL_SCHEMA` to ensure the cleaned data still
refer to the original data.
The ORM models do not know the original tables.
Also, print the `diff` as indented JSON.
Before version 14, PostgreSQL stored `EXTRACT(...)` as `date_part(...)`,
and the rendering of `IN (...)` changed as well.
The checks created in 2021 express the same rules as the ORM models
but render differently. See the docstring of the migration for details.
Earlier migrations named some constraints without `op.f()`,
a column rename did not rename the unique constraint containing the column,
and the "ordered_timestamps_N" checks in "orders" were shifted by one
compared to the ORM.
See the docstring of the migration for details.
`ReplaySimulation`, `ReplayedOrder`, and `Forecast` accessed
relationships in their `.__repr__()`, which emits queries
or fails for detached instances.
They now use the foreign key columns.
The ORM always defined `Grid.side_length` with `nullable=False`,
but the migration that created the "grids" table did not; the
live database contains no `NULL`s.
The "Revision" and "Revises" lines and the revision hashes in `upgrade()`
and `downgrade()` repeated the `revision` and `down_revision` variables;
the creation date is in the file name.
The `unique=True` on `Grid.side_length`
made the side length unique across all cities.
The intended rule is the `UniqueConstraint("city_id", "side_length")`,
which the migrations already implement; so, no migration is needed.
The new "verify-db-objects" session creates the ORM objects
with `.create_all()` in a temporary database and compares
them with the `CLEAN_SCHEMA` of a "live" database using `sqlalchemy-diff`
The query then runs in the same transaction as the `db.session`
For that, `addresses_mock` now replaces only `session.query()`
instead of the whole `db.session`.
It needs the dependencies of `velofy` installed,
and it now also reports "# type: ignore" comments without an error code
or that are not needed anymore
`ruff format` adds parentheses around multi-line lambda bodies
and removes blank lines after block openers,
both of which `black` accepts.
Lines with `# type:ignore` are shortened
because `black` counts pragma comments toward the line length
and `ruff` does not.
`ruff` runs alongside `flake8` and `isort`,
with the rules aligned to theirs:
- `noqa` comments go where both tools expect them
- `import`s stay sorted case-insensitively,
now stated explicitly in both tools
- `print()` in the "docs" session became `session.log()`
- Request fixtures only needed for their side effects
via `@pytest.mark.usefixtures()` instead of as arguments
- Remove fixtures that a test does not use at all
- Exempt abstract methods because their arguments define an interface
... and use relative links in the docs from now on.
Forgejo resolves relative links against the branch being viewed.
So, rewriting absolute links per branch is no longer necessary.
`safety check` is deprecated.
We use `pip-audit` instead, fed with the hashed dependencies
exported from uv.lock.
We ignore the known vulnerabilities in `black` v25 for now.
Make `uv` the backend for the virtual environments,
and install the packages with the versions pinned in uv.lock,
exported into a constraints file with `uv export`,
instead of `poetry export` and `poetry install`.
Also, use `uv run` instead of `poetry run`.
Use the PEP 735 "[dependency-groups]" (here: "dev", "test", "docs")
instead of Poetry's "dev" group, and `uv_build` as the build backend.
Replace poetry.lock with uv.lock.
Also, adapt CI and the README.
Use ">=installed,<next major" as the version range,
the minor version for 0.x packages, and only
a lower bound for calendar-versioned packages.
`black` stays below v26 to keep 2 lines after the `import`s.
Also, remove the redundant `geopy` entry in the "dev" group.
`sqlalchemy` v2.1 uses `psycopg` v3 as the default PostgreSQL driver.
So, we replace `psycopg2` with `psycopg`,
using its binary wheel that bundles `libpq`,
so CI no longer needs `libpq-dev` from `apt`.
No 0.x release of `wemake-python-styleguide` runs on Python 3.12+.
The current version pins `flake8-commas` to v2.x,
which crashes on the new f-string tokenizer.
The 1.x releases no longer bundle the `flake8` plug-ins this project uses.
The plug-ins are added back explicitly, one by one, on a separate branch.
The dependencies stay in the same series as on Python 3.8
where those support 3.13.
Only the unavoidable upgrades are taken:
- `matplotlib` to v3.9
- `numpy` to v2.1
- `pandas` to v2.2
- `scipy` (via statsmodels)
Required code changes:
- `numpy` v2.1 prints its scalars as `np.float64(...)`,
which `psycopg2` then writes into the SQL
=> Adjust `Forecast.from_dataframe()` to convert the
rounded values into plain `float`s
- Python 3.12 no longer accepts `float`s in `random.randint()`
=> The test factories now pass the seconds as `int`s
CI and `nox` use a `u`v-managed Python, which ships the C headers
needed to build `psycopg2` and `rpy2`.
`flake8` v4 does not run on Python 3.12+
and is upgraded in a future commit.
The sessions in `noxfile.py` do not work since the migration to
Poetry 2: they use `poetry install --no-dev` and `poetry export`,
which Poetry 2 removed or moved into a plugin. The sessions are
reworked together with the other development tools.
... and two flake8 plugins
On Python 3.8, the three packages stay at the newest versions that work
with `flake8` v4, which `wemake-python-styleguide` v0.17 requires.
The lock file now also records their newer releases for newer Python versions.
The actual upgrade follows together with the switch to Python 3.13.
`isort` v5 honors the `single_line_exclusions = typing` setting in
`setup.cfg`, which `isort` v4 ignored.
So, the `typing` imports that were split onto separate lines to satisfy
`isort` v4 are combined again, as the configuration originally intended.
- so far, the check constraints were untested
+ the tests mirror the tests for the `ReplayedOrder` model
with some variations
- shorten some import names
- fix some typos
- add new ORM models `ReplaySimulation` and `ReplayedOrder`
to store the data generated by the routing simulations
- add migrations script to create the corresponding database tables
+ create "replay_simulations" and "replayed_orders" tables
+ add missing check constraints to "orders" table
+ add unique constraint to "orders" table to enable compound key
+ drop unnecessary check constraints from the "orders" table
- add tests for the new ORM models
+ add `simulation`, `replayed_order`, `make_replay_order()`, and
`pre_order` fixtures
+ add `ReplayedOrderFactor` faker class
- fix some typos
- show an example order's path from the restaurant to the customer's
delivery address as it is travelled by a courier
- explain how to use the Google Maps API directly
- show how the API is integrated into the data model
- `Order.draw()` plots a `Courier`'s path from the
`Order.pickup_address` to the `Order.delivery_address`
- `Path.draw()` plots a `Courier`'s path between any two
`Address` objects
- a `Path` is a better description for an instance of the model
- the `Location`s en route are renamed into `.waypoints`
- generic `assoc` is renamed into `path` in the test suite
Adapt code to prevent new warnings and errors (as of SQLAlchemy 1.4):
- Overlapping foreign key columns could be set in a conflicting way
=> This is prevented by the application logic
=> Ignore the warning by setting a `overlaps` flag
- Transaction already rolled back
=> This only happens when tests cause an `IntegrityError` on purpose
=> Filter away the corresponding warning in the fixture
- Query returns `Row` objects and not scalars
=> Add genexpr to pull out `primary_id`
... from the dev dependencies.
Longer queries in SQLAlchemy get flagged even though they are not
complicated. Other expressions are generally not that complicated.
- as of September 2021, PyCharm is used to write some of the code
- PyCharm's built-in code styler, linter, and type checker issued
some warnings that are resolved in this commit
+ spelling mistakes
+ all instance attributes must be specified explicitly
in a class's __init__() method
=> use `functools.cached_property` for caching
+ make `tuple`s explicit with `(...)`
+ one test failed randomly although everything is ok
=> adjust the fixture's return value (stub for Google Directions API)
+ reformulate SQL so that PyCharm can understand the symbols
- problem: because of the randomization of test cases, every once in a
while, the schema holding the test db already exists and cannot be
created a second time (background: we run all tests against a db
created with `metadate.create_all()` by SQLAlchemy at once and
a db created by running all incremental Alchemy migration scripts)
- quick fix: possible, we could find a way to run all tests against
one of the two test db's in random order and then against the other
=> in the interest of time, we simply do not randomize the test cases
- `DistanceMatrix.from_addresses()` takes a variable number of
`Address` objects and creates distance matrix entries for them
- as a base measure, the air distance between two `Address`
objects is calculated
- in addition, an integration with the Google Maps Directions API is
implemented that provides a more realistic measure of the distance
and duration a rider on a bicycle would need to travel between two
`Address` objects
- add a `Location.lat_lng` convenience property that provides the
`.latitude` and `.longitude` of an `Address` as a 2-`tuple`
- the class stores the data of a distance matrix between all addresses
+ air distances
+ bicycle distances
- in addition, the "path" returned by the Google Directions API are
also stored as a JSON serialized sequence of latitude-longitude pairs
- we assume a symmetric graph
- the first notebook runs the tactical-forecasts command
- the second notebook describes the tactical demand forecasting process
+ demand aggregation on a per-pixel level
+ time series generation: horizontal, vertical, and real-time time series
+ STL decomposition into seasonal, trend, and residual components
+ choosing the most promising forecasting model
+ predicting demand with various models
- fix where to re-start the forecasting process after it was interrupted
- enable the heuristic for choosing the most promising model
to also work for 7 training weeks
- the two notebook files are helpful in visualizing all relevant
pickup (red) or delivery (blue) locations from the point of view
of either e restaurant or a customer
- add notebook that runs the plotting code
- add three visualizations per city:
+ all addresses, colored by zip code
+ all restaurants, incl. the number of received orders
+ all restaurants on a grid with pixel side length of 1000m
- the model applies a simple moving average on horizontal time series
- refactor `db.Forecast.from_dataframe()` to correctly convert
`float('NaN')` values into `None`; otherwise, SQLAlchemy complains
- the method implements a heuristic from the first research paper
that chooses the most promising forecasting `*Model` based on
the average daily demand in a `Pixel` for a given `train_horizon`
- adjust the test scenario => `LONG_TRAIN_HORIZON` becomes `8`
as that is part of the rule implemented in the heuristic
- `*Model`s use the `methods.*.predict()` functions to predict demand
given an order time series generated by `timify.OrderHistory`
- `models.base.ForecastingModelABC` unifies how all `*Model`s work
and implements a caching strategy
- implement three `*Model`s for tactical forecasting, based on the
hets, varima, and rtarima models described in the first research paper
- add overall documentation for `urban_meal_delivery.forecasts` package
- move the fixtures in `tests.forecasts.timify.conftest` to
`tests.forecasts.conftest` and adjust the horizon of the test horizon
from two to three weeks
- the function implements a forecasting "method" similar to the
seasonal naive method
=> instead of simply taking the last observation given a seasonal lag,
it linearly extrapolates all observations of the same seasonal lag
from the past into the future; conceptually, it is like the
seasonal naive method with built-in smoothing
- the function is tested just like the `arima.predict()` and
`ets.predict()` functions
+ rename the `tests.forecasts.methods.test_ts_methods` module
into `tests.forecasts.methods.test_predictions`
- re-organize some constants in the `tests` package
- streamline some docstrings
- move the module
- unify the corresponding tests in `tests.forecasts.methods` sub-package
- make all `predict()` and the `stl()` function round results
- streamline documentation
- ensure a `Restaurant` only has one unique `Order.pickup_address`
- rework `Grid.gridify()` so that only pickup addresses are assigned
into `Pixel`s
- include database migrations to ensure the data adhere to these
tighter constraints
- add `.low80`, `.high80`, `.low95`, and `.high95` columns
- add check contraints for the confidence intervals
- rename the `.method` column into `.model` for consistency
- add a Jupyter notebook that allows to install all project-external
dependencies regarding R and R packages
- adjust the GitHub Action workflow to also install R and the R packages
used within the project
- add a `init_r` module that initializes all R packages globally
once the `urban_meal_delivery` package is imported
- the main purpose of this class is to manage querying the order totals
from the database and slice various kinds of time series out of the
data
- the class holds the former `aggregate_orders()` function as a method
- modularize the corresponding tests
- add `tests.config` with globals used when testing to provide a
single source of truth for various settings
- the function queries the database and aggregates the ad-hoc orders
by pixel and time steps into a demand time series
- implement "heavy" integration tests for `aggregate_orders()`
- make `pandas` a package dependency
- streamline the `Config`
- reorganize `urban_meal_delivery.console` into a sub-package
- move `tests.db.conftest` fixtures into `tests.conftest`
=> some integration tests regarding CLI scripts need a database
- add `urban_meal_delivery.console.decorators.db_revision` decorator
to ensure the database is at a certain state before a CLI script runs
- refactor the `urban_meal_delivery.db.grids.Grid.gridify()` constructor:
- bug fix: even empty `Pixel`s end up in the database temporarily
=> create `Pixel` objects only if an `Address` is to be assigned
to it
- streamline code and docstring
- add further test cases
- the purpose of this constructor method is to generate all `Pixel`s
for a `Grid` that have at least one `Address` assigned to them
- fix missing `UniqueConstraint` in `Grid` class => it was not possible
to create two `Grid`s with the same `.side_length` in different cities
- change the `City.viewport` property into two separate `City.southwest`
and `City.northeast` properties; also add `City.total_x` and
`City.total_y` properties for convenience
- the old `UTMCoordinate` class becomes the new `Location` class
- its main purpose is to represent locations in both lat-long
coordinates as well as in the UTM system
- remove `Address.__init__()` and `City.__init__()` methods as they
are not executed for entries retrieved from the database
- simplfiy the `Location.__init__()` => remove `relative_to` argument
- remove the factory functions for creating engines and sessions
- define global engine, connection, and session objects to be used
everywhere in the urban_meal_delivery package
- add Grid, Pixel, and AddressPixelAssociation ORM models
- each Grid belongs to a City an is characterized by the side_length
of all the square Pixels contained in it
- Pixels aggregate Addresses => many-to-many relationship (that is
modeled with SQLAlchemy's Association Pattern to implement a couple
of constraints)
- the Address.x and Address.y properties use the UTMCoordinate class
behind the scenes
- x and y are simple coordinates in an x-y plane
- the (0, 0) origin is the southwest corner of Address.city.viewport
- the class is a utility to abstract working with latitude-longitude
coordinates in their UTM representation (~ "cartesian plane")
- the class's .x and .y properties enable working with simple x-y
coordinates where the (0, 0) origin is the lower-left of a city's
viewport
- create `*Factory` classes with fakerboy and faker that generate
randomized instances of the ORM models
- add new pytest marker: "db" are the integration tests involving the
database whereas "e2e" will be all other integration tests
- streamline the docstrings in the ORM models
As a lot of the integration tests populate the database with test data,
it is deemed safer to run the tests in random order to uncover potential
dependencies between distinct test cases.
Because of how the `db_session` fixture is designed, this should already
be taken care of.
- clean the raw data given by the undisclosed meal delivery platform:
+ keep data only for the three target citis:
* Bordeaux
* Lyon
* Paris
+ merge duplicates
* it appears as redundant addresses were created
for each order by the same customer
=> significant reduction in the number of addresses
* propagate the merges to the other tables
that reference records merged away
+ cast data types and keep their scopes narrow
+ normalize the data
+ remove obvious outliers
+ adjust/discard unplausible values
- map the cleaned data onto the ORM models
- store the cleaned data in a new database schema
- change references to temporary branches (e.g., "release-*" and
"publish") to point to the 'main' branch
- add --branch=BRANCH_NAME option to the nox session so that
one can pass in a target branch to make all references point to
- run "fix-branch-references" as the first pre-commit hook
as it fails the fastest
- bug fix: allow dots in branch references (e.g., "release-0.1.0")
- dependencies used to run the Jupyter Lab environment that are not
required by the `urban-meal-delivery` package itself are put into
an installation extra called "research"
- this allows to NOT install the requirements, for example, when
testing the package in an isolated environment
- run "format" and "lint" separately
=> remove the nox session "pre-commit"
- execute the entire "test-suite" before merges
+ rename "pre-merge" into "test-suite"
+ do not "format" and "lint" here any more
+ do not execute this before pushes
* allow branches with <100% test coverage to exist on GitHub
(they cannot be merged into 'main' until 100% coverage)
* GitHub Actions executes the test suite
- many *.py and *.ipynb files will contain links to resources on
GitHub or nbviewer that have branch references in them
- add a pre-commit hook implemented as the nox session
"fix-branch-references" that goes through these files and
changes all the branch labels to the current one
- use Alembic to migrate the PostgreSQL database
+ create initial migration script to set up the database,
as an alternative to db.Base.metadata.create_all()
+ integrate Alembic into the test suite; the db_engine fixture
now has two modes:
* create the latest version of tables all at once
* invoke `alembic upgrade head`
=> the "e2e" tests are all run twice, once in each mode; this
ensures that the migration scripts re-create the same database
schema as db.Base.metadata.create_all() would
* in both modes, a temporary PostgreSQL schema is used to create the
tables in
=> could now run "e2e" tests against production database and still
have isolation
- make the configuration module public (to be used by Alembic)
- adjust linting rules for Alembic
- use SQLAlchemy (and PostgreSQL) to model the ORM layer
- add the following models:
+ Address => modelling all kinds of addresses
+ City => model the three target cities
+ Courier => model the UDP's couriers
+ Customer => model the UDP's customers
+ Order => model the orders received by the UDP
+ Restaurant => model the restaurants active on the UDP
- so far, the emphasis lies on expression the Foreign Key
and Check Constraints that are used to validate the assumptions
inherent to the cleanded data
- provide database-independent unit tests with 100% coverage
- provide additional integration tests ("e2e") that commit data to
a PostgreSQL instance to validate that the constraints work
- adapt linting rules a bit
- add the following file:
+ src/urban_meal_delivery/_config.py
- a config module is created holding two sets of configurations:
+ production => against the real database
+ testing => against a database with test data
- the module is "protected" (i.e., underscore) and imported at the
top level via a proxy-like object `config` that detects in which of
the two environments the package is being run
"(cancelled_at IS NULL AND cancelled_at_corrected IS NULL) OR (cancelled_at IS NULL AND cancelled_at_corrected IS TRUE) OR (cancelled_at IS NOT NULL AND cancelled_at_corrected IS NOT NULL)",# noqa:E501
"(courier_accepted_at IS NULL AND courier_accepted_at_corrected IS NULL) OR (courier_accepted_at IS NULL AND courier_accepted_at_corrected IS TRUE) OR (courier_accepted_at IS NOT NULL AND courier_accepted_at_corrected IS NOT NULL)",# noqa:E501
"(courier_notified_at IS NULL AND courier_notified_at_corrected IS NULL) OR (courier_notified_at IS NULL AND courier_notified_at_corrected IS TRUE) OR (courier_notified_at IS NOT NULL AND courier_notified_at_corrected IS NOT NULL)",# noqa:E501
"(delivery_at IS NULL AND delivery_at_corrected IS NULL) OR (delivery_at IS NULL AND delivery_at_corrected IS TRUE) OR (delivery_at IS NOT NULL AND delivery_at_corrected IS NOT NULL)",# noqa:E501
"(dispatch_at IS NULL AND dispatch_at_corrected IS NULL) OR (dispatch_at IS NULL AND dispatch_at_corrected IS TRUE) OR (dispatch_at IS NOT NULL AND dispatch_at_corrected IS NOT NULL)",# noqa:E501
"(estimated_prep_duration IS NULL AND estimated_prep_duration_corrected IS NULL) OR (estimated_prep_duration IS NULL AND estimated_prep_duration_corrected IS TRUE) OR (estimated_prep_duration IS NOT NULL AND estimated_prep_duration_corrected IS NOT NULL)",# noqa:E501
"(left_pickup_at IS NULL AND left_pickup_at_corrected IS NULL) OR (left_pickup_at IS NULL AND left_pickup_at_corrected IS TRUE) OR (left_pickup_at IS NOT NULL AND left_pickup_at_corrected IS NOT NULL)",# noqa:E501
"(pickup_at IS NULL AND pickup_at_corrected IS NULL) OR (pickup_at IS NULL AND pickup_at_corrected IS TRUE) OR (pickup_at IS NOT NULL AND pickup_at_corrected IS NOT NULL)",# noqa:E501
"(restaurant_confirmed_at IS NULL AND restaurant_confirmed_at_corrected IS NULL) OR (restaurant_confirmed_at IS NULL AND restaurant_confirmed_at_corrected IS TRUE) OR (restaurant_confirmed_at IS NOT NULL AND restaurant_confirmed_at_corrected IS NOT NULL)",# noqa:E501
"(restaurant_notified_at IS NULL AND restaurant_notified_at_corrected IS NULL) OR (restaurant_notified_at IS NULL AND restaurant_notified_at_corrected IS TRUE) OR (restaurant_notified_at IS NOT NULL AND restaurant_notified_at_corrected IS NOT NULL)",# noqa:E501
"(scheduled_delivery_at IS NULL AND scheduled_delivery_at_corrected IS NULL) OR (scheduled_delivery_at IS NULL AND scheduled_delivery_at_corrected IS TRUE) OR (scheduled_delivery_at IS NOT NULL AND scheduled_delivery_at_corrected IS NOT NULL)",# noqa:E501
"NOT (ad_hoc IS FALSE AND ((EXTRACT(HOUR FROM scheduled_delivery_at) <= 11 AND NOT (EXTRACT(HOUR FROM scheduled_delivery_at) = 11 AND EXTRACT(MINUTE FROM scheduled_delivery_at) = 45)) OR EXTRACT(HOUR FROM scheduled_delivery_at) > 22))",# noqa:E501