Compare commits
162 changed files with 6014 additions and 651795 deletions
|
|
@ -1,52 +0,0 @@
|
|||
name: Set up `velofy`
|
||||
description: Install R, `uv`, `nox`, and `pre-commit`
|
||||
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
|
||||
steps:
|
||||
|
||||
- name: Install R via system packages
|
||||
shell: bash
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install --no-install-recommends \
|
||||
r-base-dev \
|
||||
r-cran-forecast \
|
||||
r-cran-zoo \
|
||||
-y
|
||||
|
||||
# Built wheels (e.g., `rpy2`) and Python versions, keyed by their pins
|
||||
# => Only the "lint" job in ci.yaml saves the cache
|
||||
- name: Restore the `uv` cache
|
||||
id: uv-cache
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cache/uv
|
||||
~/.local/share/uv/python
|
||||
key: uv-${{ runner.os }}-${{ hashFiles('uv.lock', 'pyproject.toml') }}
|
||||
restore-keys: uv-${{ runner.os }}-
|
||||
|
||||
# Tell the "lint" job in ci.yaml the key and if it must save the cache
|
||||
- name: Remember the `uv` cache key and if it was restored exactly
|
||||
shell: bash
|
||||
run: |
|
||||
echo "UV_CACHE_KEY=${{ steps.uv-cache.outputs.cache-primary-key }}" >> "$FORGEJO_ENV"
|
||||
echo "UV_CACHE_HIT=${{ steps.uv-cache.outputs.cache-hit }}" >> "$FORGEJO_ENV"
|
||||
|
||||
# All `SUPPORTED_PYTHONS` from the "classifiers" in pyproject.toml
|
||||
# => `nox` would otherwise pick the system's Python without headers
|
||||
- name: Install `uv` and all supported Python versions
|
||||
shell: bash
|
||||
run: |
|
||||
curl -LsSf https://astral.sh/uv/0.13.10/install.sh | sh
|
||||
echo "$HOME/.local/bin" >> "$FORGEJO_PATH"
|
||||
"$HOME/.local/bin/uv" python install $(grep -oP 'Programming Language :: Python :: \K3\.\d+' pyproject.toml)
|
||||
|
||||
# The jobs only use `nox` and `pre-commit` from the develop environment
|
||||
# => The `nox` sessions install `velofy` and its dependencies themselves
|
||||
- name: Install `nox` and `pre-commit`
|
||||
shell: bash
|
||||
run: '"$HOME/.local/bin/uv" sync --locked --only-group dev'
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
Merge branch '${HeadBranch}' into ${BaseBranch}
|
||||
${ReviewedOn}
|
||||
|
|
@ -1,117 +0,0 @@
|
|||
name: CI
|
||||
|
||||
|
||||
# Run on every push, which also covers pull requests from this repository
|
||||
on:
|
||||
push:
|
||||
|
||||
|
||||
# Use `bash` instead of the container's default `sh`
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
|
||||
|
||||
# Same variables as in `.env` on `nehemiah`, the main development machine
|
||||
env:
|
||||
DATABASE_URI: postgresql://user:password@postgres:5432/db
|
||||
GOOGLE_MAPS_API_KEY: AIzaDummyKeyForTests # Fake key to mock the Google API
|
||||
R_LIBS: /usr/lib/R/site-library
|
||||
UV_NO_SYNC: "1" # Keep `uv run` from installing all groups (see the setup action)
|
||||
UV_PYTHON_PREFERENCE: only-managed # Only uv's Python has the headers to build `rpy2`
|
||||
|
||||
|
||||
jobs:
|
||||
|
||||
lint:
|
||||
name: Lint
|
||||
runs-on: debian-13
|
||||
|
||||
# Stop hanging jobs (e.g., a test waiting for a database lock)
|
||||
timeout-minutes: 20
|
||||
|
||||
# Throwaway database, reachable from the job as host `postgres`
|
||||
services: &database
|
||||
postgres:
|
||||
image: postgres:17
|
||||
env:
|
||||
POSTGRES_USER: user
|
||||
POSTGRES_PASSWORD: password
|
||||
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
|
||||
|
||||
steps:
|
||||
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0 # Fetch all branches with their history for the next step
|
||||
|
||||
- name: Ensure feature branches contain no merge commits
|
||||
if: forgejo.ref_name != 'develop' && forgejo.ref_name != 'main'
|
||||
run: "! git rev-list --merges origin/develop..HEAD | grep ."
|
||||
|
||||
- uses: ./.forgejo/actions/setup
|
||||
|
||||
- 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
|
||||
|
||||
- name: Test the code snippets in the docstrings with `xdoctest`
|
||||
run: uv run nox -s test-docstrings
|
||||
|
||||
- name: Run the `pre-commit` hooks not covered by `nox`
|
||||
run: uv run pre-commit run --all-files --show-diff-on-failure
|
||||
env:
|
||||
SKIP: local-format,local-lint,local-test,local-test-docstrings,local-test-types,no-commit-to-branch
|
||||
|
||||
# Only this job saves the `uv` cache that ./.forgejo/actions/setup restores
|
||||
# => Keep only what is expensive to rebuild, not wheels that are cheap to download
|
||||
- name: Shrink the `uv` cache
|
||||
if: env.UV_CACHE_HIT != 'true'
|
||||
run: uv cache prune --ci
|
||||
|
||||
- name: Save the `uv` cache
|
||||
if: env.UV_CACHE_HIT != 'true'
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cache/uv
|
||||
~/.local/share/uv/python
|
||||
key: ${{ env.UV_CACHE_KEY }}
|
||||
|
||||
|
||||
tests:
|
||||
name: Tests (${{ matrix.session }})
|
||||
runs-on: debian-13
|
||||
|
||||
# Stop hanging jobs (e.g., a test waiting for a database lock)
|
||||
timeout-minutes: 20
|
||||
|
||||
# Run the sessions in parallel, each with its own database
|
||||
strategy:
|
||||
matrix:
|
||||
session:
|
||||
- test
|
||||
- test-types
|
||||
# One job per non-main Python version listed in the "classifiers"
|
||||
# in pyproject.toml => Keep in sync manually
|
||||
- test-with-3.15
|
||||
|
||||
# Same database as in the "lint" job
|
||||
services: *database
|
||||
|
||||
steps:
|
||||
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: ./.forgejo/actions/setup
|
||||
|
||||
- name: Run the `nox` session
|
||||
run: uv run nox -s ${{ matrix.session }}
|
||||
|
|
@ -1,92 +0,0 @@
|
|||
# Mechanical commits that `git blame` skips
|
||||
# => Enable locally with `git config blame.ignoreRevsFile .git-blame-ignore-revs`
|
||||
|
||||
# Use double quotes
|
||||
ea8f1a13e34bfce01ea66951311e5f5fb5ab967f
|
||||
|
||||
# Use the `sa` alias for `sqlalchemy` everywhere
|
||||
e30b3efbe8fc719f7d1d5bef32c69df67884f4d7
|
||||
|
||||
# Use `sa.func` instead of importing `func`
|
||||
78e052b668d029204daeb17d0ded3938156f1f2b
|
||||
|
||||
# Import the `postgresql` dialect as `psql`
|
||||
9d3af5e44719c88e4115c429d38e9e795de5bf05
|
||||
|
||||
# Import `sqlalchemy.ext.hybrid` as `sa_hybrid`
|
||||
0b2a1197a2b089120f66ae2c8c365fac983192f4
|
||||
|
||||
# Use builtin generics and `X | None`
|
||||
c6518f6b39386a7c803d0c2792fdae6d61436064
|
||||
|
||||
# Import `typing` as `t` ...
|
||||
9c3b52befb51f91026accb9d4d3e0874ef6c3d23
|
||||
|
||||
# Use the `nox` module import
|
||||
f0c617955bc8e9d46cd4126e0a334f1a28cc7849
|
||||
|
||||
# Import `datetime` as `dt` everywhere
|
||||
5ca16ae47c63c06ac67b11908f813a544c377670
|
||||
|
||||
# Import `googlemaps` as `gm` everywhere
|
||||
d660f0cc4ed6d9e62d0fe7c6d618322d57a1b049
|
||||
|
||||
# Import `geopy.distance` as `geo_distance` everywhere
|
||||
07660ecff980932d082f82c43575fbfafc1172fe
|
||||
|
||||
# Import `click.testing` as `cli_testing`
|
||||
07e90b7851e3c585270edf84b94fbb2998e51c46
|
||||
|
||||
# Import `statsmodels.tsa.api` as `tsa`
|
||||
9b844b16e777ef643ea20f93f9fe415ecc51ff20
|
||||
|
||||
# Import `rpy2.rinterface_lib.callbacks` as `r_callbacks`
|
||||
8bca30c83630a7136cba9c427d6bcc1dbffb2b7a
|
||||
|
||||
# Import `rpy2.robjects.packages` as `r_packages`
|
||||
e9743eaa013362cd4e79b19dd7dd0c25ede11e73
|
||||
|
||||
# Import `alembic.command` as `alembic_cmd`
|
||||
dc45c689c40ccfe98c2148f9ba08612612121083
|
||||
|
||||
# Import `alembic.config` as `alembic_config`
|
||||
de5e49b497cc8f5904637fa5d913e2f8b331f2e8
|
||||
|
||||
# Import `velofy.config` as `pkg_config` everywhere
|
||||
cf2534f41e9e535b8f68a38bb3e0ebadf3fb19b3
|
||||
|
||||
# Capitalize the explanations after "=>"
|
||||
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
|
||||
14
.github/workflows/tests.yml
vendored
Normal file
14
.github/workflows/tests.yml
vendored
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
name: CI
|
||||
on: push
|
||||
jobs:
|
||||
tests:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-python@v1
|
||||
with:
|
||||
python-version: 3.8
|
||||
architecture: x64
|
||||
- run: pip install nox==2020.5.24
|
||||
- run: pip install poetry==1.0.10
|
||||
- run: nox
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -1,7 +1,6 @@
|
|||
.cache/
|
||||
**/*.egg-info/
|
||||
.env
|
||||
.idea/
|
||||
**/.ipynb_checkpoints/
|
||||
.python-version
|
||||
.venv/
|
||||
|
|
|
|||
3
.gitmodules
vendored
3
.gitmodules
vendored
|
|
@ -1,3 +0,0 @@
|
|||
[submodule "research/papers/demand-forecasting"]
|
||||
path = research/papers/demand-forecasting
|
||||
url = ssh://git@git.webartifex.de/alexander/velofy-forecasting.git
|
||||
|
|
@ -1,109 +1,50 @@
|
|||
# Hooks run by `git commit` and `git merge`,
|
||||
# installed with `uv run nox -s init-project`
|
||||
|
||||
# Used by a plain `pre-commit install`
|
||||
default_install_hook_types:
|
||||
- pre-commit
|
||||
- pre-merge-commit
|
||||
|
||||
# Used if a hook does not specify stages
|
||||
default_stages:
|
||||
- pre-commit
|
||||
|
||||
default_stages: [commit] # only used if a hook does not specify stages
|
||||
fail_fast: true
|
||||
|
||||
|
||||
repos:
|
||||
|
||||
# Format, lint, and test with the `nox` sessions
|
||||
- repo: local
|
||||
hooks:
|
||||
|
||||
# `require_serial: true`
|
||||
# => Parallel runs would recreate the same `nox` environment
|
||||
|
||||
- id: local-format
|
||||
name: Format the source files
|
||||
entry: uv run nox -s format --
|
||||
language: unsupported
|
||||
stages: [pre-commit]
|
||||
types: [python]
|
||||
require_serial: true
|
||||
|
||||
- id: local-lint
|
||||
name: Lint the source files
|
||||
entry: uv run nox -s lint --
|
||||
language: unsupported
|
||||
stages: [pre-commit]
|
||||
types: [python]
|
||||
require_serial: true
|
||||
|
||||
- id: local-test
|
||||
name: Run the test suite
|
||||
entry: uv run nox -s test
|
||||
language: unsupported
|
||||
stages: [pre-merge-commit]
|
||||
pass_filenames: false # => No `--` at the end of the "entry"
|
||||
always_run: true
|
||||
require_serial: true
|
||||
|
||||
- id: local-test-docstrings
|
||||
name: Run the doctests
|
||||
entry: uv run nox -s test-docstrings
|
||||
language: unsupported
|
||||
stages: [pre-merge-commit]
|
||||
pass_filenames: false # => No `--` at the end of the "entry"
|
||||
always_run: true
|
||||
require_serial: true
|
||||
|
||||
- id: local-test-types
|
||||
name: Check the type annotations at runtime
|
||||
entry: uv run nox -s test-types
|
||||
language: unsupported
|
||||
stages: [pre-merge-commit]
|
||||
pass_filenames: false # => No `--` at the end of the "entry"
|
||||
always_run: true
|
||||
require_serial: true
|
||||
|
||||
# Keep requirements.txt in sync with uv.lock
|
||||
- repo: https://github.com/astral-sh/uv-pre-commit
|
||||
rev: 0.13.10
|
||||
hooks:
|
||||
|
||||
- id: uv-export
|
||||
args:
|
||||
- --extra=research
|
||||
- --no-default-groups
|
||||
- --no-emit-project
|
||||
- --frozen
|
||||
- --quiet
|
||||
- --output-file=requirements.txt
|
||||
|
||||
# Generic checks that the "local" tools can not cover
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v6.0.0
|
||||
hooks:
|
||||
|
||||
- id: check-added-large-files
|
||||
args: [--maxkb=100]
|
||||
exclude: ^requirements\.txt$ # Large because of the hashes
|
||||
|
||||
- id: check-builtin-literals
|
||||
|
||||
- id: check-case-conflict
|
||||
|
||||
- id: check-merge-conflict
|
||||
|
||||
- id: check-toml
|
||||
|
||||
- id: check-yaml
|
||||
|
||||
- id: end-of-file-fixer
|
||||
|
||||
- id: mixed-line-ending
|
||||
args: [--fix=no]
|
||||
|
||||
- id: no-commit-to-branch
|
||||
args: [--branch, main]
|
||||
|
||||
- id: trailing-whitespace
|
||||
# Run the local formatting, linting, and testing tool chains.
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: local-fix-branch-references
|
||||
name: Check for wrong branch references
|
||||
entry: poetry run nox -s fix-branch-references --
|
||||
language: system
|
||||
stages: [commit]
|
||||
types: [text]
|
||||
- id: local-format
|
||||
name: Format the source files
|
||||
entry: poetry run nox -s format --
|
||||
language: system
|
||||
stages: [commit]
|
||||
types: [python]
|
||||
- id: local-lint
|
||||
name: Lint the source files
|
||||
entry: poetry run nox -s lint --
|
||||
language: system
|
||||
stages: [commit]
|
||||
types: [python]
|
||||
- id: local-test-suite
|
||||
name: Run the entire test suite
|
||||
entry: poetry run nox -s test-suite --
|
||||
language: system
|
||||
stages: [merge-commit]
|
||||
types: [text]
|
||||
# Enable hooks provided by the pre-commit project to
|
||||
# enforce rules that local tools could not that easily.
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v3.2.0
|
||||
hooks:
|
||||
- id: check-added-large-files
|
||||
args: [--maxkb=100]
|
||||
- id: check-case-conflict
|
||||
- id: check-builtin-literals
|
||||
- id: check-merge-conflict
|
||||
- id: check-toml
|
||||
- id: check-yaml
|
||||
- id: end-of-file-fixer
|
||||
stages: [commit] # overwrite the default
|
||||
- id: mixed-line-ending
|
||||
args: [--fix=no]
|
||||
- id: no-commit-to-branch
|
||||
args: [--branch, main]
|
||||
- id: trailing-whitespace
|
||||
stages: [commit] # overwrite the default
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
Copyright (c) 2020 Alexander Hess [alexander@webartifex.de]
|
||||
Copyright (c) 2020 Alexander Hess [alexander@webartifex.biz]
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
|
|
|||
60
README.md
60
README.md
|
|
@ -1,7 +1,7 @@
|
|||
# Urban Meal Delivery
|
||||
|
||||
This repository holds code
|
||||
analyzing the data of an undisclosed urban meal delivery platform (UDP)
|
||||
analyzing the data of an undisclosed urban meal delivery platform
|
||||
operating in France from January 2016 to January 2017.
|
||||
The goal is to
|
||||
optimize the platform's delivery process involving independent couriers.
|
||||
|
|
@ -9,46 +9,10 @@ optimize the platform's delivery process involving independent couriers.
|
|||
|
||||
## Structure
|
||||
|
||||
The analysis is structured into the following stages
|
||||
The analysis is structured into three aspects
|
||||
that iteratively build on each other.
|
||||
|
||||
|
||||
### Data Cleaning
|
||||
|
||||
The UDP provided its raw data as a PostgreSQL dump.
|
||||
This [notebook](research/01_clean_data.ipynb)
|
||||
cleans the data extensively
|
||||
and maps them onto the [ORM models](src/velofy/db)
|
||||
defined in the `velofy` package
|
||||
that is developed in the [src/](src) folder
|
||||
and contains all source code to drive the analyses.
|
||||
|
||||
Due to a non-disclosure agreement with the UDP,
|
||||
neither the raw nor the cleaned data are published as of now.
|
||||
However, previews of the data can be seen throughout the [research/](research) folder.
|
||||
|
||||
|
||||
### Tactical Demand Forecasting
|
||||
|
||||
Before any optimizations of the UDP's operations are done,
|
||||
a **demand forecasting** system for *tactical* purposes is implemented.
|
||||
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.
|
||||
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/](research/visualizations) folder
|
||||
and in this [notebook](research/03_grid_visualizations.ipynb).
|
||||
|
||||
Then, demand is aggregated on a per-pixel level
|
||||
and different kinds of order time series are generated.
|
||||
The latter are the input to different kinds of forecasting `*Model`s.
|
||||
They all have in common that they predict demand into the *short-term* future (e.g., one hour)
|
||||
and are thus used for tactical purposes, in particular predictive routing (cf., next section).
|
||||
The details of how this works can be found in the first academic paper
|
||||
published in the context of this research project
|
||||
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).
|
||||
All demand forecasting related code is in the [forecasts/](src/velofy/forecasts) sub-package.
|
||||
|
||||
### Real-time Demand Forecasting
|
||||
|
||||
### Predictive Routing
|
||||
|
||||
|
|
@ -59,23 +23,23 @@ All demand forecasting related code is in the [forecasts/](src/velofy/forecasts)
|
|||
|
||||
To play with the code developed for the analyses,
|
||||
you can clone the project with [git](https://git-scm.com/)
|
||||
and install the contained `velofy` package
|
||||
and install the contained `urban-meal-delivery` package
|
||||
and all its dependencies
|
||||
in a [virtual environment](https://docs.python.org/3/tutorial/venv.html)
|
||||
with [uv](https://docs.astral.sh/uv/):
|
||||
with [poetry](https://python-poetry.org/docs/):
|
||||
|
||||
`git clone ssh://git@git.webartifex.de/alexander/velofy.git`
|
||||
`git clone https://github.com/webartifex/urban-meal-delivery.git`
|
||||
|
||||
and
|
||||
|
||||
`uv sync --extra research`
|
||||
`poetry install --extras research`
|
||||
|
||||
The `--extra` option is necessary as the non-develop dependencies
|
||||
are structured in the [pyproject.toml](pyproject.toml) file
|
||||
into dependencies related to only the `velofy` source code package
|
||||
The `--extras` option is necessary as the non-develop dependencies
|
||||
are structured in the [pyproject.toml](https://github.com/webartifex/urban-meal-delivery/blob/main/pyproject.toml) file
|
||||
into dependencies related to only the `urban-meal-delivery` source code package
|
||||
and dependencies used to run the [Jupyter](https://jupyter.org/) environment
|
||||
with the analyses.
|
||||
|
||||
Contributions are welcome.
|
||||
Use the [issues](https://code.webartifex.de/alexander/velofy/issues) tab.
|
||||
The project is licensed under the [MIT license](LICENSE.txt).
|
||||
Use the [issues](https://github.com/webartifex/urban-meal-delivery/issues) tab.
|
||||
The project is licensed under the [MIT license](https://github.com/webartifex/urban-meal-delivery/blob/main/LICENSE.txt).
|
||||
|
|
|
|||
16
docs/conf.py
16
docs/conf.py
|
|
@ -1,15 +1,15 @@
|
|||
"""Configure sphinx."""
|
||||
|
||||
import velofy
|
||||
import urban_meal_delivery as umd
|
||||
|
||||
|
||||
project = velofy.__pkg_name__
|
||||
author = velofy.__author__
|
||||
project_copyright = f"2020, {author}"
|
||||
version = release = velofy.__version__
|
||||
project = umd.__pkg_name__
|
||||
author = umd.__author__
|
||||
copyright = f'2020, {author}' # pylint:disable=redefined-builtin
|
||||
version = release = umd.__version__
|
||||
|
||||
extensions = [
|
||||
"sphinx.ext.autodoc",
|
||||
"sphinx.ext.napoleon",
|
||||
"sphinx_autodoc_typehints",
|
||||
'sphinx.ext.autodoc',
|
||||
'sphinx.ext.napoleon',
|
||||
'sphinx_autodoc_typehints',
|
||||
]
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ Urban Meal Delivery
|
|||
reference
|
||||
|
||||
|
||||
This is the documentation for the `velofy` package
|
||||
This is the documentation for the `urban-meal-delivery` package
|
||||
that contains all the source code
|
||||
used in a research project
|
||||
residing in this `repository`_.
|
||||
|
|
@ -25,13 +25,13 @@ All other software is automatically installed (cf., next section).
|
|||
Installation
|
||||
------------
|
||||
|
||||
The `velofy` package is installed
|
||||
The `urban-meal-delivery` package is installed
|
||||
only after cloning the `repository`_.
|
||||
It is *not* available on `PyPI`_ via `pip`_.
|
||||
|
||||
.. code-block:: console
|
||||
|
||||
$ git clone ssh://git@git.webartifex.de/alexander/velofy.git
|
||||
$ git clone https://github.com/webartifex/urban-meal-delivery.git
|
||||
|
||||
Use `poetry`_ to install the package
|
||||
with its dependencies into a `virtual environment`_,
|
||||
|
|
@ -91,5 +91,5 @@ You can use them to choose among the different tasks you want to achieve.
|
|||
.. _poetry: https://python-poetry.org/docs/
|
||||
.. _pypi: https://pypi.org/
|
||||
.. _python: https://docs.python.org/3/
|
||||
.. _repository: https://code.webartifex.de/alexander/velofy
|
||||
.. _repository: https://github.com/webartifex/urban-meal-delivery
|
||||
.. _virtual environment: https://docs.python.org/3/tutorial/venv.html
|
||||
|
|
|
|||
|
|
@ -6,41 +6,39 @@ from logging import config as log_config
|
|||
import sqlalchemy as sa
|
||||
from alembic import context
|
||||
|
||||
from velofy import config as pkg_config
|
||||
from velofy import db
|
||||
from urban_meal_delivery import config as umd_config
|
||||
from urban_meal_delivery 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():
|
||||
msg = "The --sql option is not implemented in this project"
|
||||
raise NotImplementedError(msg)
|
||||
raise NotImplementedError('The --sql option is not implemented in this project')
|
||||
|
||||
|
||||
# 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)
|
||||
|
||||
|
||||
def include_object(obj, _name, type_, _reflected, _compare_to):
|
||||
"""Only include the clean schema into --autogenerate migrations."""
|
||||
return not (
|
||||
type_ in {"table", "column"}
|
||||
and hasattr(obj, "schema") # => Fix for rare edge case
|
||||
and obj.schema != pkg_config.CLEAN_SCHEMA
|
||||
)
|
||||
if type_ in {'table', 'column'} and obj.schema != umd_config.DATABASE_SCHEMA:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
# Without a `pool`, the `connection` really closes after the migrations
|
||||
engine = sa.create_engine(pkg_config.DATABASE_URI, poolclass=sa.pool.NullPool)
|
||||
|
||||
test_schema = f"_{pkg_config.CLEAN_SCHEMA}" if os.getenv("TESTING") else ""
|
||||
engine = sa.create_engine(umd_config.DATABASE_URI)
|
||||
|
||||
with engine.connect() as connection:
|
||||
context.configure(
|
||||
connection=connection,
|
||||
include_object=include_object,
|
||||
target_metadata=db.Base.metadata,
|
||||
version_table=f"{pkg_config.ALEMBIC_TABLE}{test_schema}",
|
||||
version_table_schema=pkg_config.ALEMBIC_TABLE_SCHEMA,
|
||||
version_table='{alembic_table}{test_schema}'.format(
|
||||
alembic_table=umd_config.ALEMBIC_TABLE,
|
||||
test_schema=(f'_{umd_config.CLEAN_SCHEMA}' if os.getenv('TESTING') else ''),
|
||||
),
|
||||
version_table_schema=umd_config.ALEMBIC_TABLE_SCHEMA,
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
"""${message}."""
|
||||
"""${message}.
|
||||
|
||||
Revision: # ${up_revision} at ${create_date}
|
||||
Revises: # ${down_revision | comma,n}
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
|
|
@ -6,8 +10,7 @@ import sqlalchemy as sa
|
|||
from alembic import op
|
||||
${imports if imports else ""}
|
||||
|
||||
from velofy import configuration
|
||||
|
||||
from urban_meal_delivery import configuration
|
||||
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
|
|
@ -15,14 +18,14 @@ branch_labels = ${repr(branch_labels)}
|
|||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
config = configuration.make_config("testing" if os.getenv("TESTING") else "production")
|
||||
config = configuration.make_config('testing' if os.getenv('TESTING') else 'production')
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""Upgrade to the next revision."""
|
||||
"""Upgrade to revision ${up_revision}."""
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""Downgrade to the previous revision."""
|
||||
"""Downgrade to revision ${down_revision}."""
|
||||
${downgrades if downgrades else "pass"}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,176 +0,0 @@
|
|||
"""Add pixel grid."""
|
||||
|
||||
import os
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
from velofy import configuration
|
||||
|
||||
|
||||
revision = "888e352d7526"
|
||||
down_revision = "f11cd76d2f45"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
config = configuration.make_config("testing" if os.getenv("TESTING") else "production")
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""Upgrade to the next revision."""
|
||||
op.create_table(
|
||||
"grids",
|
||||
sa.Column("id", sa.SmallInteger(), autoincrement=True, nullable=False),
|
||||
sa.Column("city_id", sa.SmallInteger(), nullable=False),
|
||||
sa.Column("side_length", sa.SmallInteger(), nullable=True),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_grids")),
|
||||
sa.ForeignKeyConstraint(
|
||||
["city_id"],
|
||||
[f"{config.CLEAN_SCHEMA}.cities.id"],
|
||||
name=op.f("fk_grids_to_cities_via_city_id"),
|
||||
onupdate="RESTRICT",
|
||||
ondelete="RESTRICT",
|
||||
),
|
||||
sa.UniqueConstraint(
|
||||
"city_id",
|
||||
"side_length",
|
||||
name=op.f("uq_grids_on_city_id_side_length"),
|
||||
),
|
||||
# This `UniqueConstraint` is needed by the `addresses_pixels` table below
|
||||
sa.UniqueConstraint("id", "city_id", name=op.f("uq_grids_on_id_city_id")),
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
"pixels",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("grid_id", sa.SmallInteger(), nullable=False),
|
||||
sa.Column("n_x", sa.SmallInteger(), nullable=False),
|
||||
sa.Column("n_y", sa.SmallInteger(), nullable=False),
|
||||
sa.CheckConstraint("0 <= n_x", name=op.f("ck_pixels_on_n_x_is_positive")),
|
||||
sa.CheckConstraint("0 <= n_y", name=op.f("ck_pixels_on_n_y_is_positive")),
|
||||
sa.ForeignKeyConstraint(
|
||||
["grid_id"],
|
||||
[f"{config.CLEAN_SCHEMA}.grids.id"],
|
||||
name=op.f("fk_pixels_to_grids_via_grid_id"),
|
||||
onupdate="RESTRICT",
|
||||
ondelete="RESTRICT",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_pixels")),
|
||||
sa.UniqueConstraint(
|
||||
"grid_id",
|
||||
"n_x",
|
||||
"n_y",
|
||||
name=op.f("uq_pixels_on_grid_id_n_x_n_y"),
|
||||
),
|
||||
sa.UniqueConstraint("id", "grid_id", name=op.f("uq_pixels_on_id_grid_id")),
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
|
||||
op.create_index(
|
||||
op.f("ix_pixels_on_grid_id"),
|
||||
"pixels",
|
||||
["grid_id"],
|
||||
unique=False,
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.create_index(
|
||||
op.f("ix_pixels_on_n_x"),
|
||||
"pixels",
|
||||
["n_x"],
|
||||
unique=False,
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.create_index(
|
||||
op.f("ix_pixels_on_n_y"),
|
||||
"pixels",
|
||||
["n_y"],
|
||||
unique=False,
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
|
||||
# This `UniqueConstraint` is needed by the `addresses_pixels` table below
|
||||
op.create_unique_constraint(
|
||||
"uq_addresses_on_id_city_id",
|
||||
"addresses",
|
||||
["id", "city_id"],
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
"addresses_pixels",
|
||||
sa.Column("address_id", sa.Integer(), nullable=False),
|
||||
sa.Column("city_id", sa.SmallInteger(), nullable=False),
|
||||
sa.Column("grid_id", sa.SmallInteger(), nullable=False),
|
||||
sa.Column("pixel_id", sa.Integer(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["address_id", "city_id"],
|
||||
[
|
||||
f"{config.CLEAN_SCHEMA}.addresses.id",
|
||||
f"{config.CLEAN_SCHEMA}.addresses.city_id",
|
||||
],
|
||||
name=op.f("fk_addresses_pixels_to_addresses_via_address_id_city_id"),
|
||||
onupdate="RESTRICT",
|
||||
ondelete="RESTRICT",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["grid_id", "city_id"],
|
||||
[
|
||||
f"{config.CLEAN_SCHEMA}.grids.id",
|
||||
f"{config.CLEAN_SCHEMA}.grids.city_id",
|
||||
],
|
||||
name=op.f("fk_addresses_pixels_to_grids_via_grid_id_city_id"),
|
||||
onupdate="RESTRICT",
|
||||
ondelete="RESTRICT",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["pixel_id", "grid_id"],
|
||||
[
|
||||
f"{config.CLEAN_SCHEMA}.pixels.id",
|
||||
f"{config.CLEAN_SCHEMA}.pixels.grid_id",
|
||||
],
|
||||
name=op.f("fk_addresses_pixels_to_pixels_via_pixel_id_grid_id"),
|
||||
onupdate="RESTRICT",
|
||||
ondelete="RESTRICT",
|
||||
),
|
||||
sa.PrimaryKeyConstraint(
|
||||
"address_id",
|
||||
"pixel_id",
|
||||
name=op.f("pk_addresses_pixels"),
|
||||
),
|
||||
sa.UniqueConstraint(
|
||||
"address_id",
|
||||
"grid_id",
|
||||
name=op.f("uq_addresses_pixels_on_address_id_grid_id"),
|
||||
),
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""Downgrade to the previous revision."""
|
||||
op.drop_table("addresses_pixels", schema=config.CLEAN_SCHEMA)
|
||||
op.drop_constraint(
|
||||
"uq_addresses_on_id_city_id",
|
||||
"addresses",
|
||||
type_=None,
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.drop_index(
|
||||
op.f("ix_pixels_on_n_y"),
|
||||
table_name="pixels",
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.drop_index(
|
||||
op.f("ix_pixels_on_n_x"),
|
||||
table_name="pixels",
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.drop_index(
|
||||
op.f("ix_pixels_on_grid_id"),
|
||||
table_name="pixels",
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.drop_table("pixels", schema=config.CLEAN_SCHEMA)
|
||||
op.drop_table("grids", schema=config.CLEAN_SCHEMA)
|
||||
|
|
@ -1,93 +0,0 @@
|
|||
"""Add demand forecasting."""
|
||||
|
||||
import os
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql as psql
|
||||
|
||||
from velofy import configuration
|
||||
|
||||
|
||||
revision = "e40623e10405"
|
||||
down_revision = "888e352d7526"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
config = configuration.make_config("testing" if os.getenv("TESTING") else "production")
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""Upgrade to the next revision."""
|
||||
op.create_table(
|
||||
"forecasts",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("pixel_id", sa.Integer(), nullable=False),
|
||||
sa.Column("start_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("time_step", sa.SmallInteger(), nullable=False),
|
||||
sa.Column("training_horizon", sa.SmallInteger(), nullable=False),
|
||||
sa.Column("method", sa.Unicode(length=20), nullable=False),
|
||||
sa.Column("prediction", psql.DOUBLE_PRECISION(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_forecasts")),
|
||||
sa.ForeignKeyConstraint(
|
||||
["pixel_id"],
|
||||
[f"{config.CLEAN_SCHEMA}.pixels.id"],
|
||||
name=op.f("fk_forecasts_to_pixels_via_pixel_id"),
|
||||
onupdate="RESTRICT",
|
||||
ondelete="RESTRICT",
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"""
|
||||
NOT (
|
||||
EXTRACT(HOUR FROM start_at) < 11
|
||||
OR
|
||||
EXTRACT(HOUR FROM start_at) > 22
|
||||
)
|
||||
""",
|
||||
name=op.f("ck_forecasts_on_start_at_must_be_within_operating_hours"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"CAST(EXTRACT(MINUTES FROM start_at) AS INTEGER) % 15 = 0",
|
||||
name=op.f("ck_forecasts_on_start_at_minutes_must_be_quarters_of_the_hour"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"CAST(EXTRACT(MICROSECONDS FROM start_at) AS INTEGER) % 1000000 = 0",
|
||||
name=op.f("ck_forecasts_on_start_at_allows_no_microseconds"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"EXTRACT(SECONDS FROM start_at) = 0",
|
||||
name=op.f("ck_forecasts_on_start_at_allows_no_seconds"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"time_step > 0",
|
||||
name=op.f("ck_forecasts_on_time_step_must_be_positive"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"training_horizon > 0",
|
||||
name=op.f("ck_forecasts_on_training_horizon_must_be_positive"),
|
||||
),
|
||||
sa.UniqueConstraint(
|
||||
"pixel_id",
|
||||
"start_at",
|
||||
"time_step",
|
||||
"training_horizon",
|
||||
"method",
|
||||
name=op.f(
|
||||
"uq_forecasts_on_pixel_id_start_at_time_step_training_horizon_method",
|
||||
),
|
||||
),
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.create_index(
|
||||
op.f("ix_forecasts_on_pixel_id"),
|
||||
"forecasts",
|
||||
["pixel_id"],
|
||||
unique=False,
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""Downgrade to the previous revision."""
|
||||
op.drop_table("forecasts", schema=config.CLEAN_SCHEMA)
|
||||
|
|
@ -1,134 +0,0 @@
|
|||
"""Add confidence intervals to forecasts."""
|
||||
|
||||
import os
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql as psql
|
||||
|
||||
from velofy import configuration
|
||||
|
||||
|
||||
revision = "26711cd3f9b9"
|
||||
down_revision = "e40623e10405"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
config = configuration.make_config("testing" if os.getenv("TESTING") else "production")
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""Upgrade to the next revision."""
|
||||
op.alter_column(
|
||||
"forecasts",
|
||||
"method",
|
||||
new_column_name="model",
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.add_column(
|
||||
"forecasts",
|
||||
sa.Column("low80", psql.DOUBLE_PRECISION(), nullable=True),
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.add_column(
|
||||
"forecasts",
|
||||
sa.Column("high80", psql.DOUBLE_PRECISION(), nullable=True),
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.add_column(
|
||||
"forecasts",
|
||||
sa.Column("low95", psql.DOUBLE_PRECISION(), nullable=True),
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.add_column(
|
||||
"forecasts",
|
||||
sa.Column("high95", psql.DOUBLE_PRECISION(), nullable=True),
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.create_check_constraint(
|
||||
op.f("ck_forecasts_on_ci_upper_and_lower_bounds"),
|
||||
"forecasts",
|
||||
"""
|
||||
NOT (
|
||||
low80 IS NULL AND high80 IS NOT NULL
|
||||
OR
|
||||
low80 IS NOT NULL AND high80 IS NULL
|
||||
OR
|
||||
low95 IS NULL AND high95 IS NOT NULL
|
||||
OR
|
||||
low95 IS NOT NULL AND high95 IS NULL
|
||||
)
|
||||
""",
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.create_check_constraint(
|
||||
op.f("prediction_must_be_within_ci"),
|
||||
"forecasts",
|
||||
"""
|
||||
NOT (
|
||||
prediction < low80
|
||||
OR
|
||||
prediction < low95
|
||||
OR
|
||||
prediction > high80
|
||||
OR
|
||||
prediction > high95
|
||||
)
|
||||
""",
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.create_check_constraint(
|
||||
op.f("ci_upper_bound_greater_than_lower_bound"),
|
||||
"forecasts",
|
||||
"""
|
||||
NOT (
|
||||
low80 > high80
|
||||
OR
|
||||
low95 > high95
|
||||
)
|
||||
""",
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.create_check_constraint(
|
||||
op.f("ci95_must_be_wider_than_ci80"),
|
||||
"forecasts",
|
||||
"""
|
||||
NOT (
|
||||
low80 < low95
|
||||
OR
|
||||
high80 > high95
|
||||
)
|
||||
""",
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""Downgrade to the previous revision."""
|
||||
op.alter_column(
|
||||
"forecasts",
|
||||
"model",
|
||||
new_column_name="method",
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.drop_column(
|
||||
"forecasts",
|
||||
"low80",
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.drop_column(
|
||||
"forecasts",
|
||||
"high80",
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.drop_column(
|
||||
"forecasts",
|
||||
"low95",
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.drop_column(
|
||||
"forecasts",
|
||||
"high95",
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
|
|
@ -1,398 +0,0 @@
|
|||
"""Remove orders from restaurants with invalid location ...
|
||||
|
||||
... and also de-duplicate a couple of redundant addresses.
|
||||
|
||||
Revision: #e86290e7305e at 2021-01-23 15:56:59
|
||||
Revises: #26711cd3f9b9
|
||||
|
||||
1) Remove orders
|
||||
|
||||
Some restaurants have orders to be picked up at an address that
|
||||
not their primary address. That is ok if that address is the location
|
||||
of a second franchise. However, for a small number of restaurants
|
||||
there is only exactly one order at that other address that often is
|
||||
located far away from the restaurant's primary location. It looks
|
||||
like a restaurant signed up with some invalid location that was then
|
||||
corrected into the primary one.
|
||||
|
||||
Use the following SQL statement to obtain a list of these locations
|
||||
before this migration is run:
|
||||
|
||||
SELECT
|
||||
orders.pickup_address_id,
|
||||
COUNT(*) AS n_orders,
|
||||
MIN(placed_at) as first_order_at,
|
||||
MAX(placed_at) as last_order_at
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.orders
|
||||
LEFT OUTER JOIN
|
||||
{config.CLEAN_SCHEMA}.restaurants
|
||||
ON orders.restaurant_id = restaurants.id
|
||||
WHERE
|
||||
orders.pickup_address_id <> restaurants.address_id
|
||||
GROUP BY
|
||||
pickup_address_id;
|
||||
|
||||
50 orders with such weird pickup addresses are removed with this migration.
|
||||
|
||||
|
||||
2) De-duplicate addresses
|
||||
|
||||
Five restaurants have two pickup addresses that are actually the same location.
|
||||
|
||||
The following SQL statement shows them before this migration is run:
|
||||
|
||||
SELECT
|
||||
orders.restaurant_id,
|
||||
restaurants.name,
|
||||
restaurants.address_id AS primary_address_id,
|
||||
addresses.id AS address_id,
|
||||
addresses.street,
|
||||
COUNT(*) AS n_orders
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.orders
|
||||
LEFT OUTER JOIN
|
||||
{config.CLEAN_SCHEMA}.addresses ON orders.pickup_address_id = addresses.id
|
||||
LEFT OUTER JOIN
|
||||
{config.CLEAN_SCHEMA}.restaurants ON orders.restaurant_id = restaurants.id
|
||||
WHERE
|
||||
orders.restaurant_id IN (
|
||||
SELECT
|
||||
restaurant_id
|
||||
FROM (
|
||||
SELECT DISTINCT
|
||||
restaurant_id,
|
||||
pickup_address_id
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.orders
|
||||
) AS restaurant_locations
|
||||
GROUP BY
|
||||
restaurant_id
|
||||
HAVING
|
||||
COUNT(pickup_address_id) > 1
|
||||
)
|
||||
GROUP BY
|
||||
orders.restaurant_id,
|
||||
restaurants.name,
|
||||
restaurants.address_id,
|
||||
addresses.id,
|
||||
addresses.street
|
||||
ORDER BY
|
||||
orders.restaurant_id,
|
||||
restaurants.name,
|
||||
restaurants.address_id,
|
||||
addresses.id,
|
||||
addresses.street;
|
||||
|
||||
|
||||
3) Remove addresses without any association
|
||||
|
||||
After steps 1) and 2) some addresses are not associated with a restaurant any more.
|
||||
|
||||
The following SQL statement lists them before this migration is run:
|
||||
|
||||
SELECT
|
||||
id,
|
||||
street,
|
||||
zip_code,
|
||||
city
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.addresses
|
||||
WHERE
|
||||
id NOT IN (
|
||||
SELECT DISTINCT
|
||||
pickup_address_id AS id
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.orders
|
||||
UNION
|
||||
SELECT DISTINCT
|
||||
delivery_address_id AS id
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.orders
|
||||
UNION
|
||||
SELECT DISTINCT
|
||||
address_id AS id
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.restaurants
|
||||
);
|
||||
|
||||
4) Ensure every `Restaurant` has exactly one `Address`.
|
||||
|
||||
Replace the current `ForeignKeyConstraint` to from `Order` to `Restaurant`
|
||||
with one that also includes the `Order.pickup_address_id`.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
|
||||
from velofy import configuration
|
||||
|
||||
|
||||
revision = "e86290e7305e"
|
||||
down_revision = "26711cd3f9b9"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
config = configuration.make_config("testing" if os.getenv("TESTING") else "production")
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""Upgrade to revision e86290e7305e."""
|
||||
# 1) Remove orders
|
||||
op.execute(
|
||||
f"""
|
||||
DELETE
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.orders
|
||||
WHERE pickup_address_id IN (
|
||||
SELECT
|
||||
orders.pickup_address_id
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.orders
|
||||
LEFT OUTER JOIN
|
||||
{config.CLEAN_SCHEMA}.restaurants
|
||||
ON orders.restaurant_id = restaurants.id
|
||||
WHERE
|
||||
orders.pickup_address_id <> restaurants.address_id
|
||||
GROUP BY
|
||||
orders.pickup_address_id
|
||||
HAVING
|
||||
COUNT(*) = 1
|
||||
);
|
||||
""",
|
||||
)
|
||||
|
||||
# 2) De-duplicate addresses
|
||||
op.execute(
|
||||
f"""
|
||||
UPDATE
|
||||
{config.CLEAN_SCHEMA}.orders
|
||||
SET
|
||||
pickup_address_id = 353
|
||||
WHERE
|
||||
pickup_address_id = 548916;
|
||||
""",
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
UPDATE
|
||||
{config.CLEAN_SCHEMA}.orders
|
||||
SET
|
||||
pickup_address_id = 4850
|
||||
WHERE
|
||||
pickup_address_id = 6415;
|
||||
""",
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
UPDATE
|
||||
{config.CLEAN_SCHEMA}.orders
|
||||
SET
|
||||
pickup_address_id = 16227
|
||||
WHERE
|
||||
pickup_address_id = 44627;
|
||||
""",
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
UPDATE
|
||||
{config.CLEAN_SCHEMA}.orders
|
||||
SET
|
||||
pickup_address_id = 44458
|
||||
WHERE
|
||||
pickup_address_id = 534543;
|
||||
""",
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
UPDATE
|
||||
{config.CLEAN_SCHEMA}.orders
|
||||
SET
|
||||
pickup_address_id = 289997
|
||||
WHERE
|
||||
pickup_address_id = 309525;
|
||||
""",
|
||||
)
|
||||
|
||||
# 3) Remove addresses
|
||||
op.execute(
|
||||
f"""
|
||||
DELETE
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.addresses_pixels
|
||||
WHERE
|
||||
address_id NOT IN (
|
||||
SELECT DISTINCT
|
||||
pickup_address_id AS id
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.orders
|
||||
UNION
|
||||
SELECT DISTINCT
|
||||
delivery_address_id AS id
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.orders
|
||||
UNION
|
||||
SELECT DISTINCT
|
||||
address_id AS id
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.restaurants
|
||||
);
|
||||
""",
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
UPDATE
|
||||
{config.CLEAN_SCHEMA}.addresses
|
||||
SET
|
||||
primary_id = 302883
|
||||
WHERE
|
||||
primary_id = 43526;
|
||||
""",
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
UPDATE
|
||||
{config.CLEAN_SCHEMA}.addresses
|
||||
SET
|
||||
primary_id = 47597
|
||||
WHERE
|
||||
primary_id = 43728;
|
||||
""",
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
UPDATE
|
||||
{config.CLEAN_SCHEMA}.addresses
|
||||
SET
|
||||
primary_id = 159631
|
||||
WHERE
|
||||
primary_id = 43942;
|
||||
""",
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
UPDATE
|
||||
{config.CLEAN_SCHEMA}.addresses
|
||||
SET
|
||||
primary_id = 275651
|
||||
WHERE
|
||||
primary_id = 44759;
|
||||
""",
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
UPDATE
|
||||
{config.CLEAN_SCHEMA}.addresses
|
||||
SET
|
||||
primary_id = 156685
|
||||
WHERE
|
||||
primary_id = 50599;
|
||||
""",
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
UPDATE
|
||||
{config.CLEAN_SCHEMA}.addresses
|
||||
SET
|
||||
primary_id = 480206
|
||||
WHERE
|
||||
primary_id = 51774;
|
||||
""",
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
DELETE
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.addresses
|
||||
WHERE
|
||||
id NOT IN (
|
||||
SELECT DISTINCT
|
||||
pickup_address_id AS id
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.orders
|
||||
UNION
|
||||
SELECT DISTINCT
|
||||
delivery_address_id AS id
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.orders
|
||||
UNION
|
||||
SELECT DISTINCT
|
||||
address_id AS id
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.restaurants
|
||||
);
|
||||
""",
|
||||
)
|
||||
|
||||
# 4) Ensure every `Restaurant` has only one `Order.pickup_address`
|
||||
op.execute(
|
||||
f"""
|
||||
UPDATE
|
||||
{config.CLEAN_SCHEMA}.orders
|
||||
SET
|
||||
pickup_address_id = 53733
|
||||
WHERE
|
||||
pickup_address_id = 54892;
|
||||
""",
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
DELETE
|
||||
FROM
|
||||
{config.CLEAN_SCHEMA}.addresses
|
||||
WHERE
|
||||
id = 54892;
|
||||
""",
|
||||
)
|
||||
op.create_unique_constraint(
|
||||
"uq_restaurants_on_id_address_id",
|
||||
"restaurants",
|
||||
["id", "address_id"],
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.create_foreign_key(
|
||||
op.f("fk_orders_to_restaurants_via_restaurant_id_pickup_address_id"),
|
||||
"orders",
|
||||
"restaurants",
|
||||
["restaurant_id", "pickup_address_id"],
|
||||
["id", "address_id"],
|
||||
source_schema=config.CLEAN_SCHEMA,
|
||||
referent_schema=config.CLEAN_SCHEMA,
|
||||
onupdate="RESTRICT",
|
||||
ondelete="RESTRICT",
|
||||
)
|
||||
op.drop_constraint(
|
||||
"fk_orders_to_restaurants_via_restaurant_id",
|
||||
"orders",
|
||||
type_="foreignkey",
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""Downgrade to revision 26711cd3f9b9."""
|
||||
op.create_foreign_key(
|
||||
op.f("fk_orders_to_restaurants_via_restaurant_id"),
|
||||
"orders",
|
||||
"restaurants",
|
||||
["restaurant_id"],
|
||||
["id"],
|
||||
source_schema=config.CLEAN_SCHEMA,
|
||||
referent_schema=config.CLEAN_SCHEMA,
|
||||
onupdate="RESTRICT",
|
||||
ondelete="RESTRICT",
|
||||
)
|
||||
op.drop_constraint(
|
||||
"fk_orders_to_restaurants_via_restaurant_id_pickup_address_id",
|
||||
"orders",
|
||||
type_="foreignkey",
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.drop_constraint(
|
||||
"uq_restaurants_on_id_address_id",
|
||||
"restaurants",
|
||||
type_="unique",
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
"""Store actuals with forecast.
|
||||
|
||||
Revision: #c2af85bada01 at 2021-01-29 11:13:15
|
||||
Revises: #e86290e7305e
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
from velofy import configuration
|
||||
|
||||
|
||||
revision = "c2af85bada01"
|
||||
down_revision = "e86290e7305e"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
config = configuration.make_config("testing" if os.getenv("TESTING") else "production")
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""Upgrade to revision c2af85bada01."""
|
||||
op.add_column(
|
||||
"forecasts",
|
||||
sa.Column("actual", sa.SmallInteger(), nullable=False),
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
op.create_check_constraint(
|
||||
op.f("ck_forecasts_on_actuals_must_be_non_negative"),
|
||||
"forecasts",
|
||||
"actual >= 0",
|
||||
schema=config.CLEAN_SCHEMA,
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""Downgrade to revision e86290e7305e."""
|
||||
op.drop_column("forecasts", "actual", schema=config.CLEAN_SCHEMA)
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue