]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/utils/grid.py
BDD: make sure randomly generated names always contain a letter
[nominatim.git] / test / bdd / utils / grid.py
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2025 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 A grid describing node placement in an area.
9 Useful for visually describing geometries.
10 """
11 import re
12
13
14 class Grid:
15
16     def __init__(self, table, step, origin):
17         if step is None:
18             step = 0.00001
19         if origin is None:
20             origin = (0.0, 0.0)
21         self.grid = {}
22
23         y = origin[1]
24         for line in table:
25             x = origin[0]
26             for pt_id in line:
27                 if pt_id:
28                     self.grid[pt_id] = (x, y)
29                 x += step
30             y += step
31
32     def get(self, nodeid):
33         """ Get the coordinates for the given grid node.
34         """
35         return self.grid.get(nodeid)
36
37     def parse_point(self, value):
38         """ Get the coordinates for either a grid node or a full coordinate.
39         """
40         value = value.strip()
41         if ' ' in value:
42             return [float(v) for v in value.split(' ', 1)]
43
44         return self.grid.get(value)
45
46     def parse_line(self, value):
47         return [self.parse_point(p) for p in value.split(',')]
48
49     def geometry_to_wkt(self, value):
50         """ Parses the given value into a geometry and returns the WKT.
51
52             The value can either be a WKT already or a geometry shortcut
53             with coordinates or grid points.
54         """
55         if re.fullmatch(r'([A-Z]+)\((.*)\)', value) is not None:
56             return value  # already a WKT
57
58         # points
59         if ',' not in value:
60             x, y = self.parse_point(value)
61             return f"POINT({x} {y})"
62
63         # linestring
64         if '(' not in value:
65             coords = ','.join(' '.join(f"{p:.7f}" for p in pt)
66                               for pt in self.parse_line(value))
67             return f"LINESTRING({coords})"
68
69         # simple polygons
70         coords = ','.join(' '.join(f"{p:.7f}" for p in pt)
71                           for pt in self.parse_line(value[1:-1]))
72         return f"POLYGON(({coords}))"