Debian Codegraph @

gavo/utils/algotricks.py

raw
1 """
2 Some fundamental algorithms not found in the standard library.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import itertools
12
13 from gavo.utils.dachstypes import (Any, Callable, Dict, FrozenSet,
14 Generic, Iterator, Hashable, List, Sequence, Set, Tuple, TypeVar, Union)
15
16
17 # A node within an IndexedGraph
18 IgNode = TypeVar("IgNode")
19 # A Generic for "local" use
20 T = TypeVar("T")
21
22
23 class IndexedGraph(Generic[IgNode]):
24 """A graph that is indexed by both incoming and outgoing edges.
25
26 The constructor argument edges is an iterable of (from, to)-tuples,
27 where both from and to must be hashable.
28
29 The class keeps a set rootNodes of "root nodes" (i.e. those with
30 no incoming edges).
31
32 To find leaf nodes, you'd have to compute allNodes-set(outgoingIndex).
33
34 You may access allNodes, rootNodes, incomingIndex, and outgoingIndex
35 reading, but any external change to them will wreak havoc.
36 """
37 def __init__(self, edges:List[Tuple[IgNode,IgNode]]):
38 self.allNodes: Set[IgNode] = set()
39 self.rootNodes = self.allNodes.copy()
40 self.incomingIndex: Dict[IgNode, Set[IgNode]] = {}
41 self.outgoingIndex: Dict[IgNode, Set[IgNode]] = {}
42 for comeFrom, goTo in edges:
43 self.addEdge(comeFrom, goTo)
44
45 def __bool__(self):
46 return not not self.incomingIndex
47
48 def addEdge(self, comeFrom:IgNode, goTo:IgNode) -> None:
49 self.incomingIndex.setdefault(goTo, set()).add(comeFrom)
50 self.outgoingIndex.setdefault(comeFrom, set()).add(goTo)
51 self.allNodes.add(goTo)
52 self.allNodes.add(comeFrom)
53 if comeFrom not in self.incomingIndex:
54 self.rootNodes.add(comeFrom)
55 self.rootNodes.discard(goTo)
56
57 def removeEdge(self, comeFrom:IgNode, goTo:IgNode) -> None:
58 if (comeFrom not in self.outgoingIndex or
59 goTo not in self.outgoingIndex[comeFrom]):
60 raise KeyError("No edge %s->%s"%(comeFrom, goTo))
61 self.outgoingIndex[comeFrom].remove(goTo)
62 self.incomingIndex[goTo].remove(comeFrom)
63 if not self.outgoingIndex[comeFrom]:
64 del self.outgoingIndex[comeFrom]
65 if comeFrom not in self.incomingIndex:
66 self.allNodes.remove(comeFrom)
67 self.rootNodes.discard(comeFrom)
68 if not self.incomingIndex[goTo]:
69 del self.incomingIndex[goTo]
70 self.rootNodes.add(goTo)
71 if goTo not in self.outgoingIndex:
72 self.allNodes.remove(goTo)
73 self.rootNodes.discard(goTo)
74
75 def getEdge(self) -> Tuple[IgNode, IgNode]:
76 """returns a random edge.
77
78 It raises an IndexError if the graph is empty.
79 """
80 comeFrom = next(iter(self.incomingIndex.keys()))
81 goTo = self.incomingIndex[comeFrom].pop()
82 self.incomingIndex[comeFrom].add(goTo)
83 return comeFrom, goTo
84
85 def getSomeRootNode(self) -> IgNode:
86 """returns an arbitrary element of rootNodes.
87
88 This will raise a KeyError if no root nodes are left.
89 """
90 el = self.rootNodes.pop()
91 self.rootNodes.add(el)
92 return el
93
94
95 def topoSort(edges:List[Tuple[IgNode, IgNode]]) -> List[IgNode]:
96 """returns a list with the nodes in the graph edges sorted topologically.
97
98 edges is a sequence of (from, to)-tuples, where both from and to must
99 be hashable.
100
101 A ValueError is raised if the graph is not acyclic.
102 """
103 res = []
104 emptySet: FrozenSet[IgNode] = frozenset()
105 graph = IndexedGraph(edges)
106 while graph.rootNodes:
107 comeFrom: IgNode = graph.getSomeRootNode()
108 res.append(comeFrom)
109 outgoingFromCur = graph.outgoingIndex.get(comeFrom, emptySet).copy()
110 for goTo in outgoingFromCur:
111 graph.removeEdge(comeFrom, goTo)
112 if goTo not in graph.allNodes:
113 res.append(goTo)
114 if graph:
115 raise ValueError("Graph not acyclic, cycle: %s->%s"%graph.getEdge())
116 return res
117
118
119 def pathSort(paths:Sequence[str]) -> List[str]:
120 """returns paths sorted in a way that parents are in front of their
121 children. Missing parents are inserted.
122
123 >>> pathSort(["a/b/c"])
124 ['a', 'a/b', 'a/b/c']
125
126 >>> pathSort(["/a/b/c", "/x/y", "/a/b/x", "/a/c"])
127 ['', '/a', '/a/b', '/a/b/c', '/a/b/x', '/a/c', '/x', '/x/y']
128 """
129 withParents = set()
130 for path in paths:
131 withParents.add(path)
132
133 spos = path.find("/")
134 while spos!=-1:
135 withParents.add(path[:spos])
136 spos = path.find("/", spos+1)
137
138 return list(sorted(withParents))
139
140
141 class _Deferred:
142 """A helper class for DeferringDict encapsulating the function call
143 to actualise a value.
144 """
145 def __init__(self,
146 callable: Callable,
147 args: Sequence=(),
148 kwargs: Dict={}):
149 self.callable, self.args, self.kwargs = callable, args, kwargs
150
151 def actualize(self) -> Any:
152 return self.callable(*self.args, **self.kwargs)
153
154
155 class DeferringDict(dict):
156 """A dictionary that stores tuples of a callable and its
157 arguments and will, on the first access, do the calls.
158
159 This is used below to defer the construction of instances in the class
160 resolver to when they are actually used. This is important with
161 interface classes in the registry code,, since they usually need the entire
162 system up before they can sensibly be built.
163
164 You can assign either a single function or a tuple of a callable
165 and its positional and keyword arguments to each key.
166 """
167 def __setitem__(self,
168 key: str,
169 value: Union[Callable, Tuple[Callable, ...]]) -> None:
170 if isinstance(value, tuple):
171 dict.__setitem__(self, key, _Deferred(*value)) # type: ignore
172 else:
173 dict.__setitem__(self, key, _Deferred(value))
174
175 def __getitem__(self, key: str) -> Any:
176 val = dict.__getitem__(self, key)
177 if isinstance(val, _Deferred):
178 val = val.actualize()
179 dict.__setitem__(self, key, val)
180 return val
181
182 def iteritems(self) -> Iterator[Tuple[str, Any]]:
183 for key in self:
184 yield key, self[key]
185
186
187 def commonPrefixLength(t1: Sequence[T], t2: Sequence[T]) -> int:
188 """returns the length of the common prefix of the sequences t1, t2.
189 """
190 try:
191 for prefixLength in itertools.count():
192 if t1[prefixLength]!=t2[prefixLength]:
193 return prefixLength
194 except IndexError: # seqs are identical up to the shorter one's length
195 return prefixLength
196 # the following line is shutting up mypy...
197 return 0 #pragma: no cover
198
199
200 def chunk(items: List[T],
201 getChunkTitle: Callable[[T], str],
202 getKey: Callable=lambda a: a[0]
203 ) -> List[Tuple[str, List[T]]]:
204 """returns items in a chunked form.
205
206 getChunkTitle(item)->chunk title is a function returning the chunk title,
207 getKey(chunk)->sort key a function returning a sort key for the
208 chunks (default is just the chunk title, i.e., chunk[0]
209
210 The chunked form is a sequence of pairs of a chunk key and a sequence
211 of items belonging to that chunk.
212
213 The internal order within each chunk is not disturbed, so you should sort
214 items as desired before passing things in.
215
216 This is supposed to work like this:
217
218 >>> chunk(["abakus", "Analysis", "knopf", "Kasper", "kohl"],
219 ... lambda item: item[0].lower())
220 [('a', ['abakus', 'Analysis']), ('k', ['knopf', 'Kasper', 'kohl'])]
221 """
222 chunks: Dict[str, List[T]] = {}
223 for item in items:
224 chunkKey = getChunkTitle(item)
225 chunks.setdefault(chunkKey, []).append(item)
226 return sorted(list(chunks.items()), key=getKey)
227
228
229 def identity(val:T) -> T:
230 return val
231
232
233 def uniqueItems(seq:Sequence[Hashable]) -> List[Hashable]:
234 """returns a list of the unique items in seq as they appear in seq.
235
236 Execept for order and return type, this is essentially like set(seq).
237 """
238 seenItems, result = set(), []
239 for item in seq:
240 if item not in seenItems:
241 result.append(item)
242 seenItems.add(item)
243 return result
244
245
246 if __name__=="__main__": #pragma: no cover
247 import doctest
248 doctest.testmod()