-
Notifications
You must be signed in to change notification settings - Fork 1
/
search.py
106 lines (74 loc) · 2.52 KB
/
search.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
from dd.autoref import BDD, Function
from typing import List
from graph import Graph, Vertex
def alg_search(graph: Graph, source: Vertex, target: Vertex):
dependencies = {v: set() for v in graph.vertices}
queue = [(source, source)]
visited = set()
while len(queue) > 0:
v, prev = queue.pop(0)
visited.add(v)
for n in v.neighbours:
if n == source or n == target or n == prev:
continue
if n not in visited:
queue.append((n, v))
# if v != source and v != target:
dependencies[n].add(v)
bdd = BDD()
edges = list(set([e for v in graph.vertices for e in v.edges]))
legend = {str(e): e for e in edges}
for e in edges:
bdd.declare(str(e))
def terminate(failed: List[Vertex]):
res = {}
for (v, deps) in dependencies.items():
if not deps:
continue
if v in failed:
continue
if not all([d in failed for d in deps]):
continue
failed = failed + [v]
res[v] = bdd.true
if res:
result, failed = terminate(failed)
for (k, v) in result.items():
res[k] = v
return res, failed
def compute(v: Vertex, failed: List[Vertex]) -> dict[Vertex, Function]:
failed = failed + [v]
bdds, failed = terminate(failed)
bdds[v] = bdd.true
for n in v.neighbours:
if n in failed:
continue
edge = bdd.var(str(v.get_edge(n)))
res = compute(n, failed)
for (k, tree) in res.items():
if k in bdds.keys() and bdds[k] != bdd.true:
bdds[k] = bdds[k] | (edge & tree)
else:
bdds[k] = edge & tree
return bdds
cache = {}
def evaluate(tree: Function):
if tree == bdd.true:
return 1.0
if tree in cache.keys():
return cache[tree]
edge = legend[tree.var]
hi = 1.0 if tree.high == bdd.true else evaluate(tree.high)
lo = 0.0 if tree.low == bdd.false else evaluate(tree.low)
res = edge.weight * hi + (1.0 - edge.weight) * lo
cache[tree] = res
return res
trees = compute(target, [])
influence = 0.0
rates = {}
# bdd.collect_garbage()
for (v, tree) in trees.items():
rates[v] = evaluate(tree)
influence += rates[v] * v.households
cache = {}
return influence, rates