]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tokenizer/token_analysis/generic_mutation.py
fix timeout use for replication timeout
[nominatim.git] / nominatim / tokenizer / token_analysis / generic_mutation.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 Creator for mutation variants for the generic token analysis.
9 """
10 from typing import Sequence, Iterable, Iterator, Tuple
11 import itertools
12 import logging
13 import re
14
15 from nominatim.errors import UsageError
16
17 LOG = logging.getLogger()
18
19 def _zigzag(outer: Iterable[str], inner: Iterable[str]) -> Iterator[str]:
20     return itertools.chain.from_iterable(itertools.zip_longest(outer, inner, fillvalue=''))
21
22
23 class MutationVariantGenerator:
24     """ Generates name variants by applying a regular expression to the name
25         and replacing it with one or more variants. When the regular expression
26         matches more than once, each occurrence is replaced with all replacement
27         patterns.
28     """
29
30     def __init__(self, pattern: str, replacements: Sequence[str]):
31         self.pattern = re.compile(pattern)
32         self.replacements = replacements
33
34         if self.pattern.groups > 0:
35             LOG.fatal("The mutation pattern %s contains a capturing group. "
36                       "This is not allowed.", pattern)
37             raise UsageError("Bad mutation pattern in configuration.")
38
39
40     def generate(self, names: Iterable[str]) -> Iterator[str]:
41         """ Generator function for the name variants. 'names' is an iterable
42             over a set of names for which the variants are to be generated.
43         """
44         for name in names:
45             parts = self.pattern.split(name)
46             if len(parts) == 1:
47                 yield name
48             else:
49                 for seps in self._fillers(len(parts)):
50                     yield ''.join(_zigzag(parts, seps))
51
52
53     def _fillers(self, num_parts: int) -> Iterator[Tuple[str, ...]]:
54         """ Returns a generator for strings to join the given number of string
55             parts in all possible combinations.
56         """
57         return itertools.product(self.replacements, repeat=num_parts - 1)