Skip to content

Commit 2adb290

Browse files
committed
chore: format code
1 parent 6abc39f commit 2adb290

File tree

16 files changed

+107
-39
lines changed

16 files changed

+107
-39
lines changed

src/ssspx/__init__.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,8 @@
33
from __future__ import annotations
44

55
from .dijkstra import dijkstra_reference
6-
from .exceptions import (
7-
AlgorithmError,
8-
ConfigError,
9-
GraphError,
10-
GraphFormatError,
11-
InputError,
12-
NotSupportedError,
13-
)
6+
from .exceptions import (AlgorithmError, ConfigError, GraphError,
7+
GraphFormatError, InputError, NotSupportedError)
148
from .graph import Graph
159

1610
try: # pragma: no cover

src/ssspx/bench.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,15 +117,21 @@ def main(argv: List[str] | None = None) -> None:
117117
argv: Optional argument list for testing.
118118
"""
119119
parser = argparse.ArgumentParser(description=__doc__)
120-
parser.add_argument("--trials", type=int, default=1, help="Number of trials per configuration")
120+
parser.add_argument(
121+
"--trials", type=int, default=1, help="Number of trials per configuration"
122+
)
121123
parser.add_argument(
122124
"--sizes",
123125
nargs="+",
124126
default=["10,20", "20,40"],
125127
help="Size pairs as n,m (e.g. 1000,5000). Defaults to a small demo.",
126128
)
127-
parser.add_argument("--seed-base", type=int, default=0, help="Base seed for random graphs")
128-
parser.add_argument("--out-csv", type=Path, help="Optional path to write per-trial CSV data")
129+
parser.add_argument(
130+
"--seed-base", type=int, default=0, help="Base seed for random graphs"
131+
)
132+
parser.add_argument(
133+
"--out-csv", type=Path, help="Optional path to write per-trial CSV data"
134+
)
129135
parser.add_argument(
130136
"--mem",
131137
action="store_true",

src/ssspx/cli.py

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010
from pathlib import Path
1111
from typing import List, Optional, Tuple
1212

13-
from .exceptions import ConfigError, GraphFormatError, InputError, NotSupportedError, SSSPXError
13+
from .exceptions import (ConfigError, GraphFormatError, InputError,
14+
NotSupportedError, SSSPXError)
1415
from .export import export_dag_graphml, export_dag_json
1516
from .graph import Graph
1617
from .io import read_graph
@@ -104,16 +105,26 @@ def main(argv: Optional[List[str]] = None) -> int:
104105
default=None,
105106
help="Comma-separated list of source vertex ids",
106107
)
107-
p.add_argument("--target", type=int, default=None, help="Target vertex id for path output")
108+
p.add_argument(
109+
"--target", type=int, default=None, help="Target vertex id for path output"
110+
)
108111

109-
p.add_argument("--no-transform", action="store_true", help="Disable outdegree transform")
110-
p.add_argument("--target-outdeg", type=int, default=4, help="Outdegree cap when transforming")
112+
p.add_argument(
113+
"--no-transform", action="store_true", help="Disable outdegree transform"
114+
)
115+
p.add_argument(
116+
"--target-outdeg", type=int, default=4, help="Outdegree cap when transforming"
117+
)
111118
p.add_argument("--frontier", choices=["block", "heap"], default="block")
112119

113120
# Profiling + export
114121
p.add_argument("--profile", action="store_true", help="Enable cProfile")
115-
p.add_argument("--profile-out", type=str, default=None, help="Dump .prof file to this path")
116-
p.add_argument("--export-json", type=str, default=None, help="Write shortest-path DAG as JSON")
122+
p.add_argument(
123+
"--profile-out", type=str, default=None, help="Dump .prof file to this path"
124+
)
125+
p.add_argument(
126+
"--export-json", type=str, default=None, help="Write shortest-path DAG as JSON"
127+
)
117128
p.add_argument(
118129
"--export-graphml",
119130
type=str,
@@ -149,7 +160,9 @@ def main(argv: Optional[List[str]] = None) -> int:
149160
)
150161

151162
stream = sys.stdout if args.log_json else sys.stderr
152-
level = "info" if args.log_json and args.log_level == "warning" else args.log_level
163+
level = (
164+
"info" if args.log_json and args.log_level == "warning" else args.log_level
165+
)
153166
logger = StdLogger(level=level, json_fmt=args.log_json, stream=stream)
154167

155168
if args.sources is not None:
@@ -176,11 +189,15 @@ def main(argv: Optional[List[str]] = None) -> int:
176189
t0 = time.perf_counter()
177190
if args.profile:
178191
with ProfileSession(dump_path=args.profile_out) as prof:
179-
solver = SSSPSolver(G, sources[0], config=cfg, logger=logger, sources=sources)
192+
solver = SSSPSolver(
193+
G, sources[0], config=cfg, logger=logger, sources=sources
194+
)
180195
res = solver.solve()
181196
sys.stderr.write(prof.report().to_text(lines=40))
182197
else:
183-
solver = SSSPSolver(G, sources[0], config=cfg, logger=logger, sources=sources)
198+
solver = SSSPSolver(
199+
G, sources[0], config=cfg, logger=logger, sources=sources
200+
)
184201
res = solver.solve()
185202
wall_ms = (time.perf_counter() - t0) * 1000.0
186203
_, peak = tracemalloc.get_traced_memory()
@@ -190,11 +207,15 @@ def main(argv: Optional[List[str]] = None) -> int:
190207
t0 = time.perf_counter()
191208
if args.profile:
192209
with ProfileSession(dump_path=args.profile_out) as prof:
193-
solver = SSSPSolver(G, sources[0], config=cfg, logger=logger, sources=sources)
210+
solver = SSSPSolver(
211+
G, sources[0], config=cfg, logger=logger, sources=sources
212+
)
194213
res = solver.solve()
195214
sys.stderr.write(prof.report().to_text(lines=40))
196215
else:
197-
solver = SSSPSolver(G, sources[0], config=cfg, logger=logger, sources=sources)
216+
solver = SSSPSolver(
217+
G, sources[0], config=cfg, logger=logger, sources=sources
218+
)
198219
res = solver.solve()
199220
wall_ms = (time.perf_counter() - t0) * 1000.0
200221
peak_mib = None

src/ssspx/frontier.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,9 @@ def pull(self) -> Tuple[Set[Vertex], Float]:
186186

187187
got = self._consume_block_prefix(self._d0, self.M, chosen, pulled_keys)
188188
if got < self.M:
189-
got += self._consume_block_prefix(self._d1, self.M - got, chosen, pulled_keys)
189+
got += self._consume_block_prefix(
190+
self._d1, self.M - got, chosen, pulled_keys
191+
)
190192
new_bounds: List[Float] = []
191193
for blk in self._d1:
192194
if blk:

src/ssspx/graph_numpy.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,9 @@ def __post_init__(self) -> None:
2525
"""Validate initialization arguments and allocate adjacency storage."""
2626
if not isinstance(self.n, int) or self.n <= 0:
2727
raise InputError("Graph.n must be a positive integer.")
28-
self.adj: List[np.ndarray] = [np.zeros((0, 2), dtype=float) for _ in range(self.n)]
28+
self.adj: List[np.ndarray] = [
29+
np.zeros((0, 2), dtype=float) for _ in range(self.n)
30+
]
2931

3032
def add_edge(self, u: Vertex, v: Vertex, w: Float) -> None:
3133
"""Add a directed edge from ``u`` to ``v``."""

src/ssspx/io.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,11 @@ def _read_graphml(path: Path) -> Tuple[int, EdgeList]:
135135
w_attr = edge.attrib.get("weight")
136136
if w_attr is None:
137137
data = edge.find(f"{ns}data[@key='w']")
138-
w = float(data.text) if (data is not None and data.text is not None) else 1.0
138+
w = (
139+
float(data.text)
140+
if (data is not None and data.text is not None)
141+
else 1.0
142+
)
139143
else:
140144
w = float(w_attr)
141145
edges.append((u, v, w))

src/ssspx/logger.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,9 @@ def __init__(
5050
def _enabled(self, level: str) -> bool: # pragma: no cover - thin wrapper
5151
return self._levels[level] >= self._levels.get(self.level, 20)
5252

53-
def log(self, level: str, event: str, **fields: Any) -> None: # pragma: no cover - simple I/O
53+
def log(
54+
self, level: str, event: str, **fields: Any
55+
) -> None: # pragma: no cover - simple I/O
5456
"""Emit a log ``event`` at ``level`` with additional ``fields``."""
5557
if not self._enabled(level):
5658
return
@@ -67,6 +69,8 @@ def info(self, event: str, **fields: Any) -> None: # pragma: no cover - passthr
6769
"""Emit an ``INFO`` event."""
6870
self.log("info", event, **fields)
6971

70-
def debug(self, event: str, **fields: Any) -> None: # pragma: no cover - passthrough
72+
def debug(
73+
self, event: str, **fields: Any
74+
) -> None: # pragma: no cover - passthrough
7175
"""Emit a ``DEBUG`` event."""
7276
self.log("debug", event, **fields)

src/ssspx/path.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,12 @@ def reconstruct_path_basic(
3131
if source == target:
3232
return [source]
3333

34-
if target < 0 or target >= len(predecessors) or source < 0 or source >= len(predecessors):
34+
if (
35+
target < 0
36+
or target >= len(predecessors)
37+
or source < 0
38+
or source >= len(predecessors)
39+
):
3540
raise ValueError("source/target out of range.")
3641

3742
# Walk backwards from target to source

src/ssspx/solver.py

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,11 @@ def _find_pivots(self, B: Float, S: Set[Vertex]) -> Tuple[Set[Vertex], Set[Verte
265265
children: Dict[Vertex, List[Vertex]] = {u: [] for u in W}
266266
for v in W:
267267
p = self.pred[v]
268-
if p is not None and p in W and self.dhat[p] + self._weight(p, v) == self.dhat[v]:
268+
if (
269+
p is not None
270+
and p in W
271+
and self.dhat[p] + self._weight(p, v) == self.dhat[v]
272+
):
269273
children[p].append(v)
270274

271275
P: Set[Vertex] = set()
@@ -333,7 +337,9 @@ def _bmssp(self, level: int, B: Float, S: Set[Vertex]) -> Tuple[Float, Set[Verte
333337
elif B_i_prime <= val < B_i:
334338
K_pairs.append((v, val))
335339

336-
extra_pairs = [(x, self.dhat[x]) for x in S_i if B_i_prime <= self.dhat[x] < B_i]
340+
extra_pairs = [
341+
(x, self.dhat[x]) for x in S_i if B_i_prime <= self.dhat[x] < B_i
342+
]
337343
if K_pairs or extra_pairs:
338344
D.batch_prepend(K_pairs + extra_pairs)
339345

@@ -356,7 +362,11 @@ def solve(self) -> SSSPResult:
356362
_Bprime, _U = self._bmssp(top_level, B, S0)
357363

358364
# If we transformed, compress distances back to original vertices (predecessors omitted).
359-
if self.cfg.use_transform and self._mapping is not None and self._clone2orig is not None:
365+
if (
366+
self.cfg.use_transform
367+
and self._mapping is not None
368+
and self._clone2orig is not None
369+
):
360370
comp: List[Float] = [math.inf] * self._G_orig.n
361371
best_clone: List[int] = [-1] * self._G_orig.n
362372
for u_orig, clones in self._mapping.items():
@@ -395,7 +405,11 @@ def path(self, target_original: Vertex) -> List[Vertex]:
395405
raise AlgorithmError("Call solve() before requesting paths.")
396406

397407
# No transform: reconstruct directly in original space
398-
if not self.cfg.use_transform or self._mapping is None or self._clone2orig is None:
408+
if (
409+
not self.cfg.use_transform
410+
or self._mapping is None
411+
or self._clone2orig is None
412+
):
399413
src = self.root[target_original]
400414
if src < 0:
401415
return []
@@ -406,7 +420,9 @@ def path(self, target_original: Vertex) -> List[Vertex]:
406420
raise AlgorithmError("target out of range for original graph.")
407421

408422
if self._best_clone_for_orig is None:
409-
raise AlgorithmError("Internal state missing best-clone cache. Call solve() first.")
423+
raise AlgorithmError(
424+
"Internal state missing best-clone cache. Call solve() first."
425+
)
410426

411427
start_clone = self._best_clone_for_orig[target_original]
412428
if start_clone < 0:

src/ssspx/transform.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
from .graph import Float, Graph, Vertex
99

1010

11-
def constant_outdegree_transform(G: Graph, delta: int) -> Tuple[Graph, Dict[Vertex, List[Vertex]]]:
11+
def constant_outdegree_transform(
12+
G: Graph, delta: int
13+
) -> Tuple[Graph, Dict[Vertex, List[Vertex]]]:
1214
"""Split vertices so that every vertex has out-degree at most ``delta``.
1315
1416
The transformation replaces a vertex with a chain of clones. Each clone

0 commit comments

Comments
 (0)