Metadata-Version: 2.4
Name: facloc
Version: 0.1.2
Summary: 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.
Author-email: Yusuf Eminoğlu <geospacephilo@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://gitlab.com/geophilo1/facloc_sdk
Project-URL: Repository, https://gitlab.com/geophilo1/facloc_sdk
Project-URL: Documentation, https://gitlab.com/geophilo1/facloc_sdk#readme
Project-URL: Issues, https://gitlab.com/geophilo1/facloc_sdk/-/work_items
Project-URL: Changelog, https://gitlab.com/geophilo1/facloc_sdk/-/blob/main/CHANGELOG.md
Project-URL: SDK dashboard, https://geophilo.com/sdk-dashboard/
Project-URL: DOI, https://doi.org/10.5281/zenodo.24122215
Keywords: facility-location,location-allocation,p-median,p-center,maximal-covering-location-problem,mclp,location-set-covering,lscp,capacitated-p-median,teitz-bart,operations-research,public-services,service-coverage,urban-planning,gis
Classifier: Development Status :: 4 - Beta
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Classifier: Environment :: Console
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Education
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.21
Provides-Extra: exact
Requires-Dist: pulp>=2.9; extra == "exact"
Requires-Dist: highspy>=1.7; extra == "exact"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Dynamic: license-file

<p align="center">
  <a href="https://geophilo.com/sdk-dashboard/"><img src="https://geophilo.com/assets/sdk_icons/facloc_sdk.svg" width="120" height="120" alt="facloc icon"></a>
</p>

# facloc

[![PyPI version](https://img.shields.io/pypi/v/facloc.svg)](https://pypi.org/project/facloc/)
[![Python versions](https://img.shields.io/pypi/pyversions/facloc.svg)](https://pypi.org/project/facloc/)
[![pipeline status](https://gitlab.com/geophilo1/facloc_sdk/badges/main/pipeline.svg)](https://gitlab.com/geophilo1/facloc_sdk/-/pipelines)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://gitlab.com/geophilo1/facloc_sdk/-/blob/main/LICENSE)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.24122215.svg)](https://doi.org/10.5281/zenodo.24122215)
[![Downloads](https://static.pepy.tech/badge/facloc/month)](https://pepy.tech/project/facloc)

**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**.

```bash
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)

```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:

```python
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`](https://gitlab.com/geophilo1/facloc_sdk/-/blob/main/examples/quickstart.py) is a complete offline walk-through.

## Quick start (command line)

```bash
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 and the demand file's `capacity` and `existing` columns apply to it. With
  `--matrix` and no `--sites`, the demand file supplies site attributes only when the
  matrix columns are the demand ids.
- **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

- Chvatal, V. (1979). A greedy heuristic for the set-covering problem. *Mathematics of
  Operations Research*, 4(3), 233-235. https://doi.org/10.1287/moor.4.3.233
- Church, R., & ReVelle, C. (1974). The maximal covering location problem. *Papers of the
  Regional Science Association*, 32(1), 101-118. https://doi.org/10.1007/BF01942293
- Cornuejols, G., Fisher, M. L., & Nemhauser, G. L. (1977). Location of bank accounts to
  optimize float: An analytic study of exact and approximate algorithms. *Management
  Science*, 23(8), 789-810. https://doi.org/10.1287/mnsc.23.8.789
- Hakimi, S. L. (1964). Optimum locations of switching centers and the absolute centers and
  medians of a graph. *Operations Research*, 12(3), 450-459.
  https://doi.org/10.1287/opre.12.3.450
- Held, M., Wolfe, P., & Crowder, H. P. (1974). Validation of subgradient optimization.
  *Mathematical Programming*, 6, 62-88. https://doi.org/10.1007/BF01580223
- Moritz, H. (2000). Geodetic Reference System 1980. *Journal of Geodesy*, 74(1), 128-133.
  https://doi.org/10.1007/s001900050278
- Mulvey, J. M., & Beck, M. P. (1984). Solving capacitated clustering problems. *European
  Journal of Operational Research*, 18(3), 339-348.
  https://doi.org/10.1016/0377-2217(84)90155-3
- ReVelle, C. S., & Swain, R. W. (1970). Central facilities location. *Geographical
  Analysis*, 2(1), 30-42. https://doi.org/10.1111/j.1538-4632.1970.tb00142.x
- Teitz, M. B., & Bart, P. (1968). Heuristic methods for estimating the generalized vertex
  median of a weighted graph. *Operations Research*, 16(5), 955-961.
  https://doi.org/10.1287/opre.16.5.955
- Toregas, C., Swain, R., ReVelle, C., & Bergman, L. (1971). The location of emergency
  service facilities. *Operations Research*, 19(6), 1363-1373.
  https://doi.org/10.1287/opre.19.6.1363

## 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.

### 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

```bibtex
@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`](https://gitlab.com/geophilo1/facloc_sdk/-/blob/main/CITATION.cff).

## Related Geophilo SDKs

- [routematrix](https://pypi.org/project/routematrix/): origin-destination travel-time and distance matrices from OSRM, Valhalla, GraphHopper and openrouteservice.
- [planx-sdk](https://pypi.org/project/planx-sdk/): urban planning analytics: 2SFCA accessibility, space syntax, MCDA (AHP/TOPSIS) and resilience indices.
- [retailgravity](https://pypi.org/project/retailgravity/): Huff, MCI and gravity models for retail catchments and site analysis.
- [tr-donati](https://pypi.org/project/tr-donati/): social and technical infrastructure (donatı) area standards for Turkish spatial plans.
- [openwalkscore](https://pypi.org/project/openwalkscore/): open walkability scores (0-100) from OpenStreetMap amenity access.

## License

MIT - see [LICENSE](https://gitlab.com/geophilo1/facloc_sdk/-/blob/main/LICENSE).
