Skip to main content

facloc

PyPI version Python versions CI License: MIT

Facility location-allocation for public-service planning.

facloc answers the classic planning questions behind schools, health centres, fire stations, libraries or parks: where should the next p facilities go, and who would each one serve? It implements the five textbook discrete location models:

Model Question Objective Source
p-median Where do p facilities minimise average travel? min sum of weight x distance Hakimi 1964; ReVelle & Swain 1970
p-center Where do p facilities minimise the worst-case distance? min max distance (optionally weighted) Hakimi 1964
MCLP Where do p facilities cover the most people within a standard S? max covered weight Church & ReVelle 1974
LSCP How few facilities put everyone within S? min number of sites Toregas et al. 1971
Capacitated p-median As p-median, but each facility has a capacity min weighted distance, single-source Mulvey & Beck 1984

Each model can be solved three ways:

  • method="heuristic" (default) - numpy-only: greedy ADD + Teitz-Bart vertex substitution (p-median), greedy + swap (p-center, MCLP), greedy set cover with redundancy removal (LSCP), regret assignment inside vertex substitution (capacitated). An optional Lagrangian lower bound tells you how far the p-median heuristic can be from optimal.
  • method="exact" - integer programme through PuLP with HiGHS (or CBC), via the optional exact extra.
  • method="brute" - full enumeration for small instances; the reference used in the tests.

Existing facilities can be fixed open, demand points carry weights (population, pupils, patients), the distance matrix is supplied (network distances, travel times) or computed (Euclidean, Manhattan or haversine). Results report chosen sites, allocations, coverage %, weighted mean distance, maximum distance, site loads and GeoJSON spider lines.

pip install facloc            # numpy only
pip install "facloc[exact]"   # + PuLP and highspy for exact MILP solving

Requires Python 3.9 or newer.


Quick start (Python)

import numpy as np
import facloc

lonlat = np.array([[29.01, 41.02], [29.03, 41.01], [29.05, 41.03], [29.10, 41.05],
                   [29.12, 41.04], [29.11, 41.07]])
population = [1200, 800, 950, 2100, 1700, 600]

problem = facloc.Problem.from_points(
    lonlat, metric="haversine",          # lon/lat in, metres out
    weights=population,
    fixed=[0],                           # an existing facility at point 0
)

sol = facloc.p_median(problem, p=2, radius=3000, bound=True)
print(sol.summary())
sol.sites                 # open sites (column indices), existing included
sol.allocation            # serving site for every demand point
sol.weighted_mean_distance, sol.max_distance, sol.coverage()   # coverage within 3 km
geojson = sol.to_geojson()                                     # spider lines + points

facloc.mclp(problem, p=2, radius=3000).coverage()   # best possible coverage with 2 sites
facloc.lscp(problem, radius=3000).objective         # new sites needed for full coverage
facloc.p_center(problem, p=2).objective             # minimal worst-case distance
facloc.p_median(problem, p=2, method="exact")       # needs facloc[exact]

With your own (e.g. road-network) distance matrix:

problem = facloc.Problem(
    distances,                 # (n_demand, n_sites); use np.inf for unreachable pairs
    weights=pupils,
    fixed=[3, 17],             # existing schools
    capacities=seats,          # only used by capacitated_p_median
    demand_ids=block_ids, site_ids=parcel_ids,
)
facloc.capacitated_p_median(problem, p=6)

examples/quickstart.py is a complete offline walk-through.

Quick start (command line)

facloc solve p-median -p 4 --demand blocks.csv --sites candidates.csv \
    --metric haversine --radius 1500 --bound \
    --json solution.json --geojson spider.geojson --allocations alloc.csv

facloc solve mclp -p 4 --radius 1500 --demand blocks.csv --sites candidates.csv
facloc solve lscp --radius 1500 --demand blocks.csv --sites candidates.csv
facloc solve p-center -p 4 --demand blocks.csv --method exact
facloc solve capacitated -p 4 --demand blocks.csv --sites candidates.csv
facloc solve p-median -p 3 --matrix od_matrix.csv --demand blocks.csv --existing S07
facloc evaluate --open S01,S07 --radius 1500 --demand blocks.csv --sites candidates.csv

Input CSVs have a header row; the delimiter (, ; or tab) is detected.

  • demand: id, x, y, weight (weight optional, default 1).
  • sites: id, x, y, capacity, existing (capacity and existing optional; existing is truthy for 1/true/yes/y/x). Without --sites, every demand point is a candidate site.
  • matrix: first row is a corner label followed by site ids; each further row a demand id followed by distances. Empty, inf or NA cells mean unreachable.

Column names can be changed with --id-col, --x-col, --y-col, --weight-col, --capacity-col, --existing-col. facloc solve --help lists every option.

API overview

Object Purpose
Problem(distances, weights, fixed, capacities, demand_ids, site_ids, demand_xy, site_xy) instance container
Problem.from_points(demand_xy, site_xy=None, metric=...) build from coordinates
p_median(problem, p, method, radius, bound, restarts, seed) p-median
p_center(problem, p, method, weighted) vertex p-center
mclp(problem, p, radius, method) maximal covering
lscp(problem, radius, method) location set covering
capacitated_p_median(problem, p, method) capacitated p-median (single source)
pmedian_lower_bound(problem, p) Lagrangian lower bound
evaluate(problem, sites, radius) measure any given set of open sites
Solution .sites, .new_sites, .allocation, .objective, .optimal, .lower_bound, .gap, .weighted_mean_distance, .max_distance, .coverage(r), .loads(), .to_dict(), .to_json(), .to_geojson(), .summary()
distance_matrix, euclidean_matrix, haversine_matrix, manhattan_matrix distance helpers
solver_available() is the exact extra usable?

Conventions:

  • p is the total number of open facilities, existing ones included: p=5 with two fixed sites places three new ones.
  • Uncapacitated models allocate each demand point to its nearest open site.
  • Demand points with zero weight do not influence the optimisation but are still allocated.
  • objective is the model's own objective: total weighted distance (p-median, capacitated), maximum (weighted) distance (p-center), covered weight (MCLP), number of new sites (LSCP).

Method and sources

Distances. Euclidean and Manhattan in input units (use projected coordinates); haversine on a sphere of radius 6 371 008.8 m (the IUGG mean radius R1, Moritz 2000), returning metres. For real accessibility studies a network distance or travel-time matrix is better; compute it elsewhere and pass it in.

p-median heuristic. Greedy ADD builds a first solution; Teitz & Bart (1968) vertex substitution then cycles through the sites not in the solution and makes the best exchange with an open (non-fixed) site whenever it lowers total weighted distance, until no single swap improves it. Exchanges are evaluated in a vectorised way using each demand point's nearest and second-nearest open site. The greedy solution is refined both by first- improvement (the original rule) and by steepest descent, and restarts (default 10, seed=0 for reproducibility) random starts are added; the best local optimum is returned. The same engine, with a different key, serves the p-center (max distance, ties broken by a power mean of distances) and the MCLP (uncovered weight, ties broken by total weighted distance). The p-center heuristic also starts from the smallest radius whose greedy set cover needs at most p sites.

Lagrangian bound. Relaxing the assignment constraints gives the bound L(lambda) = sum_i lambda_i + min over p sites of sum_j min(0, w_i d_ij - lambda_i) (Cornuejols, Fisher & Nemhauser 1977), maximised by subgradient optimisation (Held, Wolfe & Crowder 1974). Solution.gap is then a certificate: the heuristic is at most that far from the optimum.

LSCP heuristic. Greedy set covering (Chvatal 1979) with two selection rules, followed by removal of redundant sites and 2-for-1 replacements.

Capacitated p-median. Single-source allocation: each demand point is served by one facility and loads may not exceed capacities. For a given set of open sites, demand is assigned by maximum regret and improved by shift and swap moves; vertex substitution over sites uses this evaluation (screening each candidate's exchanges by their uncapacitated cost first), starting from the uncapacitated solution, the largest-capacity sites and random starts.

Exact models. Standard integer programmes (ReVelle & Swain 1970 for the p-median, Church & ReVelle 1974 for the MCLP, Toregas et al. 1971 for the LSCP, a min-max programme for the p-center, Mulvey & Beck 1984 for the capacitated p-median) built with PuLP and solved with HiGHS (preferred) or CBC. Both the PuLP 2.x/3.x and the PuLP 4 APIs are handled.

Tests. Worked examples with hand-computed optima, and every heuristic is checked against the brute-force optimum on small random instances (and the exact MILPs against brute force when the extra is installed).

References

Limitations

  • Heuristics return good local optima, not proven optima. Use bound=True (p-median) or method="exact" when you need a certificate. More restarts trade time for quality.
  • Only vertex (discrete candidate) problems: facilities sit on given candidate sites, not anywhere in the plane or on network edges (absolute centres/medians are not covered).
  • The capacitated model is single-source; split demand is not modelled. Its heuristic can fail to find a feasible allocation on very tight instances (raising InfeasibleError); the exact solver settles feasibility.
  • Distance-matrix size grows with n_demand x n_sites; the uncapacitated heuristics are comfortable up to a few thousand demand points and hundreds of candidates (about 15 s for 3000 x 300, p = 10, on a laptop). The capacitated heuristic is much slower, since every candidate exchange re-solves the assignment (about 20 s for 150 x 60, p = 8). Exact MILPs grow faster still.
  • Straight-line and haversine distances ignore the street network, barriers and travel mode.
  • GeoJSON (RFC 7946) is defined for WGS 84 lon/lat; for projected coordinates assign the CRS in your GIS.

For a fuller toolkit - more model variants, network integration with PySAL, GeoPandas input - see spopt (Feng et al. 2022, JOSS 7(74), 3330, https://doi.org/10.21105/joss.03330), part of PySAL. facloc is deliberately small: numpy only by default, a solver only when you ask for exact answers, plus a CLI and spider-line output for quick planning studies.

Academic citation

@software{eminoglu_facloc,
  author  = {Eminoğlu, Yusuf},
  title   = {facloc},
  year    = {2026},
  version = {0.1.1},
  url     = {https://github.com/YusufEminoglu/facloc_sdk}
}

License

MIT - see LICENSE.

Metadata

Release files for facloc 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for facloc 0.1.1
File Size Uploaded Provenance Actions
facloc-0.1.1.tar.gz 49.3 kB With provenance Details for facloc-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for facloc 0.1.1
File Interpreter ABI Platform Actions
facloc-0.1.1-py3-none-any.whl Python 3 none any Details for facloc-0.1.1-py3-none-any.whl

Total release size: 89.7 kB

Release files / facloc-0.1.1.tar.gz

Download URL facloc-0.1.1.tar.gz
Size 49.3 kB
Tags Source
SHA-256 checksum
How to use checksums
7882b16ee6d16cc8f0fbd8a9f32e5df359e28c53469d2e3d01c5d6e74dc2909e
BLAKE2b-256 checksum
How to use checksums
472d44c3b87eebf3e761fdec7918e341769d532523f9c1f50ef35f03db3f0139
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.

Transparency log

Release files / facloc-0.1.1-py3-none-any.whl

Download URL facloc-0.1.1-py3-none-any.whl
Size 40.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
47b4f6138cc692aeac9291aef233eccf165a300a3d6dd59784eece5bd9af38e4
BLAKE2b-256 checksum
How to use checksums
1c95b65df86119b585247cc23dd0440910366a5a8e963cfdff2bfe36645279db
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.

Transparency log

Security for facloc 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for facloc-0.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page