facloc

Facility location-allocation in Python for schools, clinics and fire stations: p-median, p-center, maximal covering (MCLP), set covering (LSCP) and capacitated p-median, heuristic or exact MILP.

Version 0.1.2 · Python >=3.9 · MIT licence
pip install facloc
PyPISourceIssuesChangelogCite (DOI)

facloc

PyPI version Python versions pipeline status License: MIT DOI Downloads

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:

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.

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:

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

Related software

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.2},
  doi     = {10.5281/zenodo.24122215},
  url     = {https://gitlab.com/geophilo1/facloc_sdk}
}

See also CITATION.cff.

Related Geophilo SDKs

License

MIT - see LICENSE.

Other Geophilo SDKs