optiwindnet 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. optiwindnet/MILP/__init__.py +0 -0
  2. optiwindnet/MILP/core.py +55 -0
  3. optiwindnet/MILP/ortools.py +328 -0
  4. optiwindnet/MILP/pyomo.py +383 -0
  5. optiwindnet/__init__.py +23 -0
  6. optiwindnet/augmentation.py +404 -0
  7. optiwindnet/baselines/__init__.py +51 -0
  8. optiwindnet/baselines/hgs.py +207 -0
  9. optiwindnet/baselines/lkh.py +264 -0
  10. optiwindnet/crossings.py +373 -0
  11. optiwindnet/data/Albatros.osm.pbf +0 -0
  12. optiwindnet/data/Amrumbank West.osm.pbf +0 -0
  13. optiwindnet/data/Anholt.yaml +132 -0
  14. optiwindnet/data/Arkona.osm.pbf +0 -0
  15. optiwindnet/data/BARD Offshore 1.osm.pbf +0 -0
  16. optiwindnet/data/Baltic 2.osm.pbf +0 -0
  17. optiwindnet/data/Baltic Eagle.osm.pbf +0 -0
  18. optiwindnet/data/Beatrice.osm.pbf +0 -0
  19. optiwindnet/data/Belwind.osm.pbf +0 -0
  20. optiwindnet/data/Borkum Riffgrund 1.yaml +106 -0
  21. optiwindnet/data/Borkum Riffgrund 2.yaml +102 -0
  22. optiwindnet/data/Borssele.yaml +214 -0
  23. optiwindnet/data/Butendiek.yaml +119 -0
  24. optiwindnet/data/CECEP Yangjiang Nanpeng Island.osm.pbf +0 -0
  25. optiwindnet/data/CGN Rudong Demonstration.osm.pbf +0 -0
  26. optiwindnet/data/Cazzaro-2022.yaml +20 -0
  27. optiwindnet/data/Cazzaro-2022G-140.yaml +64 -0
  28. optiwindnet/data/Cazzaro-2022G-210.yaml +81 -0
  29. optiwindnet/data/DanTysk.yaml +126 -0
  30. optiwindnet/data/Deutsche Bucht.osm.pbf +0 -0
  31. optiwindnet/data/Dogger Bank A.yaml +122 -0
  32. optiwindnet/data/Dudgeon.yaml +92 -0
  33. optiwindnet/data/East Anglia ONE.yaml +136 -0
  34. optiwindnet/data/Fecamp.osm.pbf +0 -0
  35. optiwindnet/data/Galloper Inner.osm.pbf +0 -0
  36. optiwindnet/data/Gemini 1.osm.pbf +0 -0
  37. optiwindnet/data/Gemini 2.osm.pbf +0 -0
  38. optiwindnet/data/Global Tech 1.osm.pbf +0 -0
  39. optiwindnet/data/Gode Wind 1.yaml +83 -0
  40. optiwindnet/data/Greater Gabbard Inner.yaml +181 -0
  41. optiwindnet/data/Gwynt y Mor.yaml +199 -0
  42. optiwindnet/data/Hohe See.osm.pbf +0 -0
  43. optiwindnet/data/Horns Rev 1.yaml +107 -0
  44. optiwindnet/data/Horns Rev 2.yaml +137 -0
  45. optiwindnet/data/Horns Rev 3.yaml +75 -0
  46. optiwindnet/data/Hornsea One.yaml +232 -0
  47. optiwindnet/data/Hornsea Two West.yaml +146 -0
  48. optiwindnet/data/Humber Gateway.osm.pbf +0 -0
  49. optiwindnet/data/Kaskasi.osm.pbf +0 -0
  50. optiwindnet/data/Kriegers Flak A.osm.pbf +0 -0
  51. optiwindnet/data/Kriegers Flak B.osm.pbf +0 -0
  52. optiwindnet/data/Laoting Bodhi Island.osm.pbf +0 -0
  53. optiwindnet/data/Lillgrund.osm.pbf +0 -0
  54. optiwindnet/data/Lincs.osm.pbf +0 -0
  55. optiwindnet/data/London Array.yaml +202 -0
  56. optiwindnet/data/Luchterduinen.osm.pbf +0 -0
  57. optiwindnet/data/Meerwind.osm.pbf +0 -0
  58. optiwindnet/data/Merkur.osm.pbf +0 -0
  59. optiwindnet/data/Mermaid.osm.pbf +0 -0
  60. optiwindnet/data/Moray East.yaml +145 -0
  61. optiwindnet/data/Moray West.yaml +95 -0
  62. optiwindnet/data/Neart na Gaoithe.osm.pbf +0 -0
  63. optiwindnet/data/Nordsee One.osm.pbf +0 -0
  64. optiwindnet/data/Nordsee Ost.osm.pbf +0 -0
  65. optiwindnet/data/Norther.osm.pbf +0 -0
  66. optiwindnet/data/Northwind.osm.pbf +0 -0
  67. optiwindnet/data/Nysted.osm.pbf +0 -0
  68. optiwindnet/data/Ormonde.yaml +51 -0
  69. optiwindnet/data/Princess Amalia.osm.pbf +0 -0
  70. optiwindnet/data/Race Bank.yaml +121 -0
  71. optiwindnet/data/Rampion.yaml +147 -0
  72. optiwindnet/data/Rentel.osm.pbf +0 -0
  73. optiwindnet/data/Riffgat.osm.pbf +0 -0
  74. optiwindnet/data/Robin Rigg.osm.pbf +0 -0
  75. optiwindnet/data/Rudong H10.osm.pbf +0 -0
  76. optiwindnet/data/Rudong H6.osm.pbf +0 -0
  77. optiwindnet/data/Rudong H8.osm.pbf +0 -0
  78. optiwindnet/data/R/303/270dsand 2.yaml" +145 -0
  79. optiwindnet/data/SPIC Binhai North H2.osm.pbf +0 -0
  80. optiwindnet/data/Saint-Brieuc.osm.pbf +0 -0
  81. optiwindnet/data/Saint-Nazaire.osm.pbf +0 -0
  82. optiwindnet/data/Sandbank.osm.pbf +0 -0
  83. optiwindnet/data/Seagreen.osm.pbf +0 -0
  84. optiwindnet/data/Shengsi 2.osm.pbf +0 -0
  85. optiwindnet/data/Sheringham Shoal.osm.pbf +0 -0
  86. optiwindnet/data/Taylor-2023.yaml +162 -0
  87. optiwindnet/data/Thanet.yaml +123 -0
  88. optiwindnet/data/Trianel Windpark Borkum.osm.pbf +0 -0
  89. optiwindnet/data/Triton Knoll.yaml +114 -0
  90. optiwindnet/data/Veja Mate.osm.pbf +0 -0
  91. optiwindnet/data/Walney 1.yaml +74 -0
  92. optiwindnet/data/Walney 2.yaml +78 -0
  93. optiwindnet/data/Walney Extension.yaml +129 -0
  94. optiwindnet/data/West of Duddon Sands.yaml +132 -0
  95. optiwindnet/data/Westermost Rough.osm.pbf +0 -0
  96. optiwindnet/data/Wikinger.osm.pbf +0 -0
  97. optiwindnet/data/Yi-2019.yaml +65 -0
  98. optiwindnet/data/Zhejiang Jiaxing 1.osm.pbf +0 -0
  99. optiwindnet/db/__init__.py +0 -0
  100. optiwindnet/db/modelv0.py +93 -0
  101. optiwindnet/db/modelv1.py +94 -0
  102. optiwindnet/db/modelv2.py +112 -0
  103. optiwindnet/db/storagev0.py +251 -0
  104. optiwindnet/db/storagev1.py +310 -0
  105. optiwindnet/db/storagev2.py +402 -0
  106. optiwindnet/geometric.py +1135 -0
  107. optiwindnet/heuristics/ClassicEsauWilliams.py +387 -0
  108. optiwindnet/heuristics/CrossingPreventingEW.py +593 -0
  109. optiwindnet/heuristics/EW_presolver.py +334 -0
  110. optiwindnet/heuristics/NonBranchingEW.py +631 -0
  111. optiwindnet/heuristics/ObstacleBypassingEW.py +1279 -0
  112. optiwindnet/heuristics/__init__.py +8 -0
  113. optiwindnet/heuristics/priorityqueue.py +46 -0
  114. optiwindnet/importer.py +406 -0
  115. optiwindnet/interarraylib.py +844 -0
  116. optiwindnet/interface.py +309 -0
  117. optiwindnet/mesh.py +1368 -0
  118. optiwindnet/pathfinding.py +729 -0
  119. optiwindnet/plotting.py +349 -0
  120. optiwindnet/repair.py +380 -0
  121. optiwindnet/svg.py +306 -0
  122. optiwindnet/synthetic.py +178 -0
  123. optiwindnet/utils.py +80 -0
  124. optiwindnet/version.py +21 -0
  125. optiwindnet/weighting.py +19 -0
  126. optiwindnet-0.0.2.dist-info/METADATA +88 -0
  127. optiwindnet-0.0.2.dist-info/RECORD +130 -0
  128. optiwindnet-0.0.2.dist-info/WHEEL +5 -0
  129. optiwindnet-0.0.2.dist-info/licenses/LICENSE +21 -0
  130. optiwindnet-0.0.2.dist-info/top_level.txt +1 -0
File without changes
@@ -0,0 +1,55 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # https://gitlab.windenergy.dtu.dk/TOPFARM/OptiWindNet/
3
+
4
+ import abc
5
+ import networkx as nx
6
+ import logging
7
+
8
+ from ..interarraylib import G_from_S
9
+ from ..pathfinding import PathFinder
10
+
11
+
12
+ logger = logging.getLogger(__name__)
13
+ info = logger.info
14
+
15
+
16
+ class PoolHandler(abc.ABC):
17
+ num_solutions: int
18
+
19
+ @abc.abstractmethod
20
+ def objective_at(self, index: int) -> float:
21
+ 'Get objective value from solution pool at position `index`'
22
+ pass
23
+
24
+ @abc.abstractmethod
25
+ def S_from_pool(self) -> nx.Graph:
26
+ 'Build S from the pool solution at the last requested position'
27
+ pass
28
+
29
+ def investigate_pool(P: nx.PlanarEmbedding, A: nx.Graph, pool: PoolHandler
30
+ ) -> nx.Graph:
31
+ '''Go through the CpSat's solutions checking which has the shortest length
32
+ after applying the detours with PathFinder.'''
33
+ Λ = float('inf')
34
+ num_solutions = pool.num_solutions
35
+ info(f'Solution pool has {num_solutions} solutions.')
36
+ for i in range(num_solutions):
37
+ λ = pool.objective_at(i)
38
+ # print(f'λ[{i}] = {λ}')
39
+ if λ > Λ:
40
+ info(f'Pool investigation over - next best undetoured length: {λ:.3f}')
41
+ break
42
+ S = pool.S_from_pool()
43
+ G = G_from_S(S, A)
44
+ Hʹ = PathFinder(G, planar=P, A=A).create_detours()
45
+ Λʹ = Hʹ.size(weight='length')
46
+ if Λʹ < Λ:
47
+ H, Λ = Hʹ, Λʹ
48
+ pool_index = i
49
+ pool_objective = λ
50
+ info(f'Incumbent has (detoured) length: {Λ:.3f}')
51
+ H.graph['pool_count'] = num_solutions
52
+ if pool_index > 0:
53
+ H.graph['pool_entry'] = pool_index, pool_objective
54
+ return H
55
+
@@ -0,0 +1,328 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # https://gitlab.windenergy.dtu.dk/TOPFARM/OptiWindNet/
3
+
4
+ import math
5
+ import logging
6
+ from collections import defaultdict
7
+ from itertools import chain
8
+ import networkx as nx
9
+
10
+ from ortools.sat.python import cp_model
11
+
12
+ from .core import PoolHandler
13
+ from ..crossings import edgeset_edgeXing_iter, gateXing_iter
14
+ from ..interarraylib import fun_fingerprint
15
+
16
+ logger = logging.getLogger(__name__)
17
+ info = logger.info
18
+
19
+
20
+ class _SolutionStore(cp_model.CpSolverSolutionCallback):
21
+ '''Ad hoc implementation of a callback that stores solutions to a pool.'''
22
+ solutions: list[tuple[float, dict]]
23
+
24
+ def __init__(self, model: cp_model.CpModel):
25
+ super().__init__()
26
+ self.solutions = []
27
+ int_lits = []
28
+ bool_lits = []
29
+ for var in model._CpModel__var_list._VariableList__var_list:
30
+ if var.is_boolean:
31
+ bool_lits.append(var)
32
+ elif var.is_integer():
33
+ int_lits.append(var)
34
+ self.bool_lits = bool_lits
35
+ self.int_lits = int_lits
36
+
37
+ def on_solution_callback(self):
38
+ solution = {var.index: self.boolean_value(var) for var in self.bool_lits}
39
+ solution |= {var.index: self.value(var) for var in self.int_lits}
40
+ self.solutions.append((self.objective_value, solution))
41
+
42
+
43
+ class CpSat(PoolHandler, cp_model.CpSolver):
44
+ '''OR-Tools CpSolver wrapper.
45
+
46
+ This class wraps and changes the behavior of CpSolver in order to save all
47
+ solutions found to a pool. Meant to be used with `investigate_pool()`.
48
+ '''
49
+ solution_pool: list[tuple[float, dict]]
50
+
51
+ def solve(self, model: cp_model.CpModel) -> cp_model.cp_model_pb2.CpSolverStatus:
52
+ '''Wrapper for CpSolver.solve() that saves all solutions.
53
+
54
+ This method uses a custom CpSolverSolutionCallback to fill a solution
55
+ pool stored in the attribute self.solutions.
56
+ '''
57
+ self.model = model
58
+ storer = _SolutionStore(model)
59
+ result = super().solve(model, storer)
60
+ storer.solutions.reverse()
61
+ self.solution_pool = storer.solutions
62
+ _, self._value_map = storer.solutions[0]
63
+ self.num_solutions = len(storer.solutions)
64
+ return result
65
+
66
+ def load_solution(self, i: int) -> None:
67
+ '''Select solution at position `i` in the pool.
68
+
69
+ Indices start from 0 (last, aka best) and are ordered by increasing
70
+ objective function value.
71
+ It *only* affects methods `value()` and `boolean_value()` and
72
+ attribute `objective_value`.
73
+ '''
74
+ self._objective_value, self._value_map = self.solution_pool[i]
75
+
76
+ def boolean_value(self, literal: cp_model.IntVar) -> bool:
77
+ return self._value_map[literal.index]
78
+
79
+ def value(self, literal: cp_model.IntVar) -> int:
80
+ return self._value_map[literal.index]
81
+
82
+ def objective_at(self, index:int) -> float:
83
+ objective_value, self._value_map = self.solution_pool[index]
84
+ return objective_value
85
+
86
+ def S_from_pool(self) -> nx.Graph:
87
+ return S_from_solution(self.model, solver=self)
88
+
89
+
90
+ def make_min_length_model(A: nx.Graph, capacity: int, *,
91
+ gateXings_constraint: bool = False,
92
+ gates_limit: bool | int = False,
93
+ branching: bool = True) -> cp_model.CpModel:
94
+ '''
95
+ Build ILP CP OR-tools model for the collector system length minimization.
96
+ `A` is the graph with the available edges to choose from.
97
+
98
+ `capacity`: cable capacity
99
+
100
+ `gateXing_constraint`: if gates and edges are forbidden to cross.
101
+
102
+ `gates_limit`: if True, use the minimum feasible number of gates
103
+ (total for all roots); if False, no limit is imposed; if a number,
104
+ use it as the limit.
105
+
106
+ `branching`: if root branches are paths (False) or can be trees (True).
107
+ '''
108
+ R = A.graph['R']
109
+ T = A.graph['T']
110
+ d2roots = A.graph['d2roots']
111
+ A_nodes = nx.subgraph_view(A, filter_node=lambda n: n >= 0)
112
+ W = sum(w for _, w in A_nodes.nodes(data='power', default=1))
113
+
114
+ # Sets
115
+ _T = range(T)
116
+ _R = range(-R, 0)
117
+
118
+ E = tuple(((u, v) if u < v else (v, u))
119
+ for u, v in A_nodes.edges())
120
+ # using directed node-node links -> create the reversed tuples
121
+ Eʹ = tuple((v, u) for u, v in E)
122
+ # set of feeders to all roots
123
+ stars = tuple((t, r) for t in _T for r in _R)
124
+ linkset = E + Eʹ + stars
125
+
126
+ # Create model
127
+ m = cp_model.CpModel()
128
+
129
+ ##############
130
+ # Parameters #
131
+ ##############
132
+
133
+ k = capacity
134
+ weight_ = (2*tuple(A[u][v]['length'] for u, v in E)
135
+ + tuple(d2roots[t, r] for t, r in stars))
136
+
137
+ #############
138
+ # Variables #
139
+ #############
140
+
141
+ link_ = {e: m.new_bool_var(f'link_{e}') for e in linkset}
142
+ flow_ = {e: m.new_int_var(0, k - 1, f'flow_{e}') for e in chain(E, Eʹ)}
143
+ flow_ |= {e: m.new_int_var(0, k, f'flow_{e}') for e in stars}
144
+
145
+ ###############
146
+ # Constraints #
147
+ ###############
148
+
149
+ # total number of edges must be equal to number of terminal nodes
150
+ m.add(sum(link_.values()) == T)
151
+
152
+ # enforce a single directed edge between each node pair
153
+ for u, v in E:
154
+ m.add_at_most_one(link_[(u, v)], link_[(v, u)])
155
+
156
+ # gate-edge crossings
157
+ if gateXings_constraint:
158
+ for (u, v), tr in gateXing_iter(A):
159
+ m.add_at_most_one(link_[(u, v)], link_[(v, u)], link_[tr])
160
+
161
+ # edge-edge crossings
162
+ for Xing in edgeset_edgeXing_iter(A.graph['diagonals']):
163
+ m.add_at_most_one(sum(((link_[u, v], link_[v, u]) for u, v in Xing), ()))
164
+
165
+ # bind flow to link activation
166
+ for t, n in linkset:
167
+ m.add(flow_[t, n] == 0).only_enforce_if(link_[t, n].Not())
168
+ # m.add(flow_[t, n] <= link_[t, n]*(k if n < 0 else (k - 1)))
169
+ m.add(flow_[t, n] > 0).only_enforce_if(link_[t, n])
170
+ # m.add(flow_[t, n] >= link_[t, n])
171
+
172
+ # flow conservation with possibly non-unitary node power
173
+ for t in _T:
174
+ m.add(sum((flow_[t, n] - flow_[n, t]) for n in A_nodes.neighbors(t))
175
+ + sum(flow_[t, r] for r in _R)
176
+ == A.nodes[t].get('power', 1))
177
+
178
+ # gates limit
179
+ min_gates = math.ceil(T/k)
180
+ all_gate_vars_sum = sum(link_[t, r] for r in _R for t in _T)
181
+ if gates_limit:
182
+ if isinstance(gates_limit, bool) or gates_limit == min_gates:
183
+ # fixed number of gates
184
+ m.add(all_gate_vars_sum == min_gates)
185
+ else:
186
+ assert min_gates < gates_limit, (
187
+ f'Infeasible: T/k > gates_limit (T = {T}, k = {k},'
188
+ f' gates_limit = {gates_limit}).')
189
+ # number of gates within range
190
+ m.add_linear_constraint(all_gate_vars_sum, min_gates, gates_limit)
191
+ else:
192
+ # valid inequality: number of gates is at least the minimum
193
+ m.add(all_gate_vars_sum >= min_gates)
194
+
195
+ # non-branching
196
+ if not branching:
197
+ for t in _T:
198
+ m.add(sum(link_[n, t] for n in A_nodes.neighbors(t)) <= 1)
199
+
200
+ # assert all nodes are connected to some root
201
+ m.add(sum(flow_[t, r] for r in _R for t in _T) == W)
202
+
203
+ # valid inequalities
204
+ for t in _T:
205
+ # incoming flow limit
206
+ m.add(sum(flow_[n, t] for n in A_nodes.neighbors(t))
207
+ <= k - A.nodes[t].get('power', 1))
208
+ # only one out-edge per terminal
209
+ m.add(sum(link_[t, n] for n in chain(A_nodes.neighbors(t), _R)) == 1)
210
+
211
+ #############
212
+ # Objective #
213
+ #############
214
+
215
+ m.minimize(cp_model.LinearExpr.WeightedSum(tuple(link_.values()), weight_))
216
+
217
+ # save data structure as model attributes
218
+ m.link_, m.linkset, m.flow_, m.R, m.T, m.k = link_, linkset, flow_, R, T, k
219
+
220
+ ##################
221
+ # Store metadata #
222
+ ##################
223
+
224
+ m.handle = A.graph['handle']
225
+ m.name = A.graph.get('name', 'unnamed')
226
+ m.method_options = dict(gateXings_constraint=gateXings_constraint,
227
+ gates_limit=gates_limit,
228
+ branching=branching)
229
+ m.fun_fingerprint = fun_fingerprint()
230
+ m.warmed_by = None
231
+ return m
232
+
233
+
234
+ def warmup_model(model: cp_model.CpModel, S: nx.Graph) -> cp_model.CpModel:
235
+ '''
236
+ Changes `model` in-place.
237
+ '''
238
+ R, T = model.R, model.T
239
+ model.ClearHints()
240
+ for u, v in model.linkset[:(len(model.linkset) - R*T)//2]:
241
+ edgeD = S.edges.get((u, v))
242
+ if edgeD is None:
243
+ model.add_hint(model.link_[u, v], False)
244
+ model.add_hint(model.flow_[u, v], 0)
245
+ model.add_hint(model.link_[v, u], False)
246
+ model.add_hint(model.flow_[v, u], 0)
247
+ else:
248
+ u, v = (u, v) if ((u < v) == edgeD['reverse']) else (v, u)
249
+ model.add_hint(model.link_[u, v], True)
250
+ model.add_hint(model.flow_[u, v], edgeD['load'])
251
+ model.add_hint(model.link_[v, u], False)
252
+ model.add_hint(model.flow_[v, u], 0)
253
+ for t, r in model.linkset[-R*T:]:
254
+ edgeD = S.edges.get((t, r))
255
+ model.add_hint(model.link_[t, r], edgeD is not None)
256
+ model.add_hint(model.flow_[t, r], 0 if edgeD is None else edgeD['load'])
257
+ model.warmed_by = S.graph['creator']
258
+ return model
259
+
260
+
261
+ def S_from_solution(model: cp_model.CpModel,
262
+ solver: cp_model.CpSolver, result: int = 0) -> nx.Graph:
263
+ '''Create a topology `S` from the OR-tools solution to the MILP model.
264
+
265
+ Args:
266
+ model: passed to the solver.
267
+ solver: used to solve the model.
268
+ result: irrelevant, exists only to mirror the Pyomo alternative.
269
+ Returns:
270
+ Graph topology from the solution.
271
+ '''
272
+ # the solution is in the solver object not in the model
273
+
274
+ # Metadata
275
+ R, T = model.R, model.T
276
+ solver_name = 'ortools'
277
+ bound = solver.best_objective_bound
278
+ objective = solver.objective_value
279
+ S = nx.Graph(
280
+ R=R, T=T,
281
+ handle=model.handle,
282
+ capacity=model.k,
283
+ objective=objective,
284
+ bound=bound,
285
+ runtime=solver.wall_time,
286
+ termination=solver.status_name(),
287
+ gap=1. - bound/objective,
288
+ creator='MILP.' + solver_name,
289
+ has_loads=True,
290
+ method_options=dict(
291
+ solver_name=solver_name,
292
+ mipgap=solver.parameters.relative_gap_limit,
293
+ timelimit=solver.parameters.max_time_in_seconds,
294
+ fun_fingerprint=model.fun_fingerprint,
295
+ **model.method_options,
296
+ ),
297
+ solver_details=dict(
298
+ strategy=solver.solution_info(),
299
+ )
300
+ )
301
+
302
+ if model.warmed_by is not None:
303
+ S.graph['warmstart'] = model.warmed_by
304
+
305
+ # Graph data
306
+ # Get active links and if flow is reversed (i.e. from small to big)
307
+ rev_from_link = {(u, v): u < v
308
+ for (u, v), use in model.link_.items()
309
+ if solver.boolean_value(use)}
310
+ S.add_weighted_edges_from(
311
+ ((u, v, solver.value(model.flow_[u, v]))
312
+ for (u, v) in rev_from_link.keys()), weight='load'
313
+ )
314
+ # set the 'reverse' edge attribute
315
+ nx.set_edge_attributes(S, rev_from_link, name='reverse')
316
+ # propagate loads from edges to nodes
317
+ subtree = -1
318
+ for r in range(-R, 0):
319
+ for u, v in nx.edge_dfs(S, r):
320
+ S.nodes[v]['load'] = S[u][v]['load']
321
+ if u == r:
322
+ subtree += 1
323
+ S.nodes[v]['subtree'] = subtree
324
+ rootload = 0
325
+ for nbr in S.neighbors(r):
326
+ rootload += S.nodes[nbr]['load']
327
+ S.nodes[r]['load'] = rootload
328
+ return S