]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/utils/centroid.py
Merge pull request #3344 from lonvia/osm2pgsql-new-middle
[nominatim.git] / nominatim / utils / centroid.py
1 # SPDX-License-Identifier: GPL-2.0-only
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Functions for computation of centroids.
9 """
10 from typing import Tuple, Any
11 from collections.abc import Collection
12
13 class PointsCentroid:
14     """ Centroid computation from single points using an online algorithm.
15         More points may be added at any time.
16
17         Coordinates are internally treated as a 7-digit fixed-point float
18         (i.e. in OSM style).
19     """
20
21     def __init__(self) -> None:
22         self.sum_x = 0
23         self.sum_y = 0
24         self.count = 0
25
26     def centroid(self) -> Tuple[float, float]:
27         """ Return the centroid of all points collected so far.
28         """
29         if self.count == 0:
30             raise ValueError("No points available for centroid.")
31
32         return (float(self.sum_x/self.count)/10000000,
33                 float(self.sum_y/self.count)/10000000)
34
35
36     def __len__(self) -> int:
37         return self.count
38
39
40     def __iadd__(self, other: Any) -> 'PointsCentroid':
41         if isinstance(other, Collection) and len(other) == 2:
42             if all(isinstance(p, (float, int)) for p in other):
43                 x, y = other
44                 self.sum_x += int(x * 10000000)
45                 self.sum_y += int(y * 10000000)
46                 self.count += 1
47                 return self
48
49         raise ValueError("Can only add 2-element tuples to centroid.")