Skip to content

Commit af4a4de

Browse files
committed
Fix CI: apply ruff lint + format on src/ and app/
- Replace if/else with ternary (SIM108) in render_score_card. - Use contextlib.suppress(Exception) instead of try/except/pass (SIM105) in Visualize / Compare page re-theming helpers. - Rename ambiguous `l` to `lens_feasible` in TSP.score_summary (E741). - Sort imports in src/qqa/problems/__init__.py (I001). - Apply `ruff format` across 7 files that drifted. No behavioural changes; pytest 51 passed / 1 skipped.
1 parent 3d30d5f commit af4a4de

8 files changed

Lines changed: 108 additions & 93 deletions

File tree

app/_common.py

Lines changed: 29 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def loss_fn(s):
5454
"border": "#e4e1d6",
5555
"text": "#0f172a",
5656
"muted": "#64748b",
57-
"accent": "#0f766e", # deep teal
57+
"accent": "#0f766e", # deep teal
5858
"accent2": "#be5a3c", # warm terracotta
5959
"grid": "#e5e7eb",
6060
"palette": ["#0f766e", "#be5a3c", "#1e3a8a", "#b45309", "#6d28d9", "#047857"],
@@ -112,15 +112,16 @@ def plotly_layout(theme: str | None = None, **overrides) -> dict:
112112
"template": "plotly_white" if (theme or get_theme()) == "light" else "plotly_dark",
113113
"paper_bgcolor": "rgba(0,0,0,0)",
114114
"plot_bgcolor": "rgba(0,0,0,0)",
115-
"font": {"family": "Inter, -apple-system, sans-serif", "size": 13,
116-
"color": p["text"]},
117-
"title_font": {"family": "'Source Serif 4', Georgia, serif",
118-
"size": 17, "color": p["text"]},
115+
"font": {"family": "Inter, -apple-system, sans-serif", "size": 13, "color": p["text"]},
116+
"title_font": {
117+
"family": "'Source Serif 4', Georgia, serif",
118+
"size": 17,
119+
"color": p["text"],
120+
},
119121
"colorway": p["palette"],
120122
"xaxis": {"gridcolor": p["grid"], "linecolor": p["border"], "zerolinecolor": p["grid"]},
121123
"yaxis": {"gridcolor": p["grid"], "linecolor": p["border"], "zerolinecolor": p["grid"]},
122-
"legend": {"bgcolor": "rgba(0,0,0,0)", "bordercolor": p["border"],
123-
"borderwidth": 0.5},
124+
"legend": {"bgcolor": "rgba(0,0,0,0)", "bordercolor": p["border"], "borderwidth": 0.5},
124125
"margin": {"l": 50, "r": 20, "t": 48, "b": 46},
125126
}
126127
base.update(overrides)
@@ -137,13 +138,13 @@ def apply_theme() -> None:
137138
<style>
138139
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Source+Serif+4:opsz,wght@8..60,400;8..60,600;8..60,700&display=swap');
139140
:root {{
140-
--qqa-bg: {p['bg']};
141-
--qqa-card: {p['bg_card']};
142-
--qqa-border: {p['border']};
143-
--qqa-text: {p['text']};
144-
--qqa-muted: {p['muted']};
145-
--qqa-accent: {p['accent']};
146-
--qqa-accent2: {p['accent2']};
141+
--qqa-bg: {p["bg"]};
142+
--qqa-card: {p["bg_card"]};
143+
--qqa-border: {p["border"]};
144+
--qqa-text: {p["text"]};
145+
--qqa-muted: {p["muted"]};
146+
--qqa-accent: {p["accent"]};
147+
--qqa-accent2: {p["accent2"]};
147148
}}
148149
html, body, [class*="css"] {{
149150
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
@@ -156,7 +157,7 @@ def apply_theme() -> None:
156157
color: var(--qqa-text);
157158
}}
158159
section[data-testid="stSidebar"] {{
159-
background: {p['bg_sidebar']};
160+
background: {p["bg_sidebar"]};
160161
border-right: 1px solid var(--qqa-border);
161162
}}
162163
h1, h2, h3, h4 {{
@@ -286,13 +287,13 @@ def apply_theme() -> None:
286287
<style>
287288
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Source+Serif+4:opsz,wght@8..60,400;8..60,600;8..60,700&display=swap');
288289
:root {{
289-
--qqa-bg: {p['bg']};
290-
--qqa-card: {p['bg_card']};
291-
--qqa-border: {p['border']};
292-
--qqa-text: {p['text']};
293-
--qqa-muted: {p['muted']};
294-
--qqa-accent: {p['accent']};
295-
--qqa-accent2: {p['accent2']};
290+
--qqa-bg: {p["bg"]};
291+
--qqa-card: {p["bg_card"]};
292+
--qqa-border: {p["border"]};
293+
--qqa-text: {p["text"]};
294+
--qqa-muted: {p["muted"]};
295+
--qqa-accent: {p["accent"]};
296+
--qqa-accent2: {p["accent2"]};
296297
}}
297298
html, body, [class*="css"] {{ font-family: 'Inter', sans-serif; }}
298299
.stApp {{
@@ -303,7 +304,7 @@ def apply_theme() -> None:
303304
color: var(--qqa-text);
304305
}}
305306
section[data-testid="stSidebar"] {{
306-
background: {p['bg_sidebar']};
307+
background: {p["bg_sidebar"]};
307308
backdrop-filter: blur(14px);
308309
border-right: 1px solid var(--qqa-border);
309310
}}
@@ -408,15 +409,10 @@ def render_score_card(score: dict, raw_loss: float | None = None) -> None:
408409
else '<span class="qqa-badge warn">infeasible</span>'
409410
)
410411
value = score.get("value", "-")
411-
if isinstance(value, float):
412-
value_s = f"{value:.4g}"
413-
else:
414-
value_s = str(value)
412+
value_s = f"{value:.4g}" if isinstance(value, float) else str(value)
415413
unit = score.get("unit", "")
416414
unit_html = f'<span class="unit">{unit}</span>' if unit else ""
417-
raw_html = (
418-
f'<div class="raw">raw loss = {raw_loss:.4g}</div>' if raw_loss is not None else ""
419-
)
415+
raw_html = f'<div class="raw">raw loss = {raw_loss:.4g}</div>' if raw_loss is not None else ""
420416
value_cls = "value" if feas else "value infeasible"
421417
st.markdown(
422418
f'<div class="qqa-score">'
@@ -584,7 +580,7 @@ def _graph_preview(g: nx.Graph, title: str) -> None:
584580
yaxis={"visible": False},
585581
height=380,
586582
)
587-
st.plotly_chart(fig, width='stretch')
583+
st.plotly_chart(fig, width="stretch")
588584

589585

590586
def _coupling_preview(J: np.ndarray, title: str) -> None:
@@ -595,7 +591,7 @@ def _coupling_preview(J: np.ndarray, title: str) -> None:
595591
plot_bgcolor="rgba(0,0,0,0)",
596592
height=400,
597593
)
598-
st.plotly_chart(fig, width='stretch')
594+
st.plotly_chart(fig, width="stretch")
599595

600596

601597
def preview_problem(problem: Any, cfg: dict) -> None:
@@ -619,7 +615,7 @@ def preview_problem(problem: Any, cfg: dict) -> None:
619615
plot_bgcolor="rgba(0,0,0,0)",
620616
height=400,
621617
)
622-
st.plotly_chart(fig, width='stretch')
618+
st.plotly_chart(fig, width="stretch")
623619
return
624620
if kind == "custom":
625621
import torch

app/pages/1_Solve.py

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ def on_epoch_end(self, state: CallbackState) -> None:
148148
legend={"x": 0.01, "y": 0.02, "bgcolor": "rgba(255,255,255,0.6)"},
149149
)
150150
)
151-
self.chart_holder.plotly_chart(fig, width='stretch')
151+
self.chart_holder.plotly_chart(fig, width="stretch")
152152

153153
# --- Population heatmap: replicas sorted by best-so-far --------
154154
pop = np.stack(self.pop, axis=1) # (sol_size, T)
@@ -186,13 +186,15 @@ def on_epoch_end(self, state: CallbackState) -> None:
186186
xaxis_title="Epoch",
187187
yaxis_title="Replica (sorted by best-so-far)",
188188
yaxis2={
189-
"overlaying": "y", "side": "right", "showgrid": False,
189+
"overlaying": "y",
190+
"side": "right",
191+
"showgrid": False,
190192
"title": "best loss",
191193
},
192194
legend={"x": 0.01, "y": 0.99, "bgcolor": "rgba(255,255,255,0.6)"},
193195
)
194196
)
195-
self.pop_holder.plotly_chart(pop_fig, width='stretch')
197+
self.pop_holder.plotly_chart(pop_fig, width="stretch")
196198

197199
# --- Diversity curve: std across replicas vs epoch --------------
198200
div_fig = go.Figure()
@@ -216,7 +218,7 @@ def on_epoch_end(self, state: CallbackState) -> None:
216218
showlegend=False,
217219
)
218220
)
219-
self.diversity_holder.plotly_chart(div_fig, width='stretch')
221+
self.diversity_holder.plotly_chart(div_fig, width="stretch")
220222

221223

222224
run = st.button("▶ Run QQA", type="primary")
@@ -236,8 +238,13 @@ def on_epoch_end(self, state: CallbackState) -> None:
236238
diversity_holder = st.empty()
237239

238240
cb = StreamlitCallback(
239-
progress, metrics, chart, pop_holder, diversity_holder,
240-
sol_size=sol_size, update_every=update_every,
241+
progress,
242+
metrics,
243+
chart,
244+
pop_holder,
245+
diversity_holder,
246+
sol_size=sol_size,
247+
update_every=update_every,
241248
)
242249
pop_tracker = PopulationTracker(stride=max(1, update_every), record_x=True)
243250

@@ -262,8 +269,10 @@ def on_epoch_end(self, state: CallbackState) -> None:
262269

263270
# Clear the "still running" progress bar and display the polished result.
264271
progress.empty()
265-
raw = result.best_obj if isinstance(result.best_obj, float) else float(
266-
__import__("numpy").asarray(result.best_obj).mean()
272+
raw = (
273+
result.best_obj
274+
if isinstance(result.best_obj, float)
275+
else float(__import__("numpy").asarray(result.best_obj).mean())
267276
)
268277
with score_holder.container():
269278
render_score_card(result.score, raw_loss=raw)

app/pages/2_Visualize.py

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import contextlib
56
import sys
67
from pathlib import Path
78

@@ -58,22 +59,21 @@
5859
]
5960
)
6061

62+
6163
def _retheme(fig):
6264
"""Reskin a Plotly figure produced by ``viz`` to the current theme."""
63-
try:
65+
with contextlib.suppress(Exception):
6466
fig.update_layout(**plotly_layout())
65-
except Exception:
66-
pass
6767
return fig
6868

6969

7070
with tab_hist:
7171
fig = viz.plot_history(result, backend="plotly", show=False)
72-
st.plotly_chart(_retheme(fig), width='stretch')
72+
st.plotly_chart(_retheme(fig), width="stretch")
7373

7474
with tab_best:
7575
fig = viz.plot_best_trajectory(result, backend="plotly", show=False)
76-
st.plotly_chart(_retheme(fig), width='stretch')
76+
st.plotly_chart(_retheme(fig), width="stretch")
7777

7878
with tab_sched:
7979
if result.history and "bg" in result.history:
@@ -97,12 +97,12 @@ def _retheme(fig):
9797
height=400,
9898
)
9999
)
100-
st.plotly_chart(fig, width='stretch')
100+
st.plotly_chart(fig, width="stretch")
101101

102102
with tab_sol:
103103
try:
104104
fig = viz.plot_solution_heatmap(result, problem=problem, backend="plotly", show=False)
105-
st.plotly_chart(_retheme(fig), width='stretch')
105+
st.plotly_chart(_retheme(fig), width="stretch")
106106
except Exception as e:
107107
st.info(f"No solution heatmap available: {e}")
108108

@@ -111,7 +111,7 @@ def _retheme(fig):
111111
st.info("No population snapshots recorded for this run.")
112112
else:
113113
fig = viz.plot_population_evolution(pop_tracker, backend="plotly", show=False)
114-
st.plotly_chart(_retheme(fig), width='stretch')
114+
st.plotly_chart(_retheme(fig), width="stretch")
115115
st.caption(
116116
"Each row is one of the `sol_size` replicas (sorted by final loss). "
117117
"Colour encodes per-replica loss."
@@ -123,7 +123,7 @@ def _retheme(fig):
123123
else:
124124
try:
125125
fig = viz.plot_population_embedding(pop_tracker, backend="plotly", show=False)
126-
st.plotly_chart(_retheme(fig), width='stretch')
126+
st.plotly_chart(_retheme(fig), width="stretch")
127127
st.caption(
128128
"2D PCA projection of the entire continuous-variable population over time. "
129129
"Each faint grey line is one replica's trajectory; markers are coloured by epoch."
@@ -153,16 +153,20 @@ def _retheme(fig):
153153
base = -k * 1.15
154154
fig.add_trace(
155155
go.Scatter(
156-
x=centres, y=base + dens, mode="lines",
156+
x=centres,
157+
y=base + dens,
158+
mode="lines",
157159
line={"color": p["palette"][k % len(p["palette"])], "width": 1.2},
158160
fill="tonexty" if k > 0 else None,
159161
name=f"epoch {epochs[i]}",
160162
showlegend=False,
161163
)
162164
)
163165
fig.add_annotation(
164-
x=centres.min(), y=base + 0.05,
165-
text=f"ep {epochs[i]}", showarrow=False,
166+
x=centres.min(),
167+
y=base + 0.05,
168+
text=f"ep {epochs[i]}",
169+
showarrow=False,
166170
font={"size": 10, "color": p["muted"]},
167171
xanchor="left",
168172
)
@@ -173,11 +177,16 @@ def _retheme(fig):
173177
yaxis_title="",
174178
height=max(420, 28 * len(idx)),
175179
showlegend=False,
176-
yaxis={"showticklabels": False, "showgrid": False, "zeroline": False,
177-
"gridcolor": palette()["grid"], "linecolor": palette()["border"]},
180+
yaxis={
181+
"showticklabels": False,
182+
"showgrid": False,
183+
"zeroline": False,
184+
"gridcolor": palette()["grid"],
185+
"linecolor": palette()["border"],
186+
},
178187
)
179188
)
180-
st.plotly_chart(fig, width='stretch')
189+
st.plotly_chart(fig, width="stretch")
181190
st.caption("Stacked loss distributions. Early rows (top) → late rows (bottom).")
182191

183192
with tab_fate:
@@ -216,7 +225,7 @@ def _retheme(fig):
216225
height=460,
217226
)
218227
)
219-
st.plotly_chart(fig, width='stretch')
228+
st.plotly_chart(fig, width="stretch")
220229
st.caption(
221230
"Top-ranked replicas are drawn in the primary accent, lower-ranked "
222231
"ones fade toward the secondary accent."

app/pages/3_Compare.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import contextlib
56
import itertools
67
import sys
78
from pathlib import Path
@@ -21,12 +22,11 @@
2122

2223

2324
def _retheme(fig):
24-
try:
25+
with contextlib.suppress(Exception):
2526
fig.update_layout(**plotly_layout())
26-
except Exception:
27-
pass
2827
return fig
2928

29+
3030
st.set_page_config(page_title="Compare — QQA", page_icon="⚛️", layout="wide")
3131
theme_toggle_in_sidebar()
3232
apply_theme()
@@ -87,18 +87,18 @@ def _retheme(fig):
8787

8888
st.success("Sweep complete.")
8989
st.subheader("Results table")
90-
st.dataframe(rows, width='stretch')
90+
st.dataframe(rows, width="stretch")
9191

9292
try:
9393
import pandas as pd
9494

9595
df = pd.DataFrame(rows)
9696
fig = viz.plot_parallel_coordinates(df, objective="best_obj", backend="plotly", show=False)
9797
st.subheader("Parallel coordinates")
98-
st.plotly_chart(_retheme(fig), width='stretch')
98+
st.plotly_chart(_retheme(fig), width="stretch")
9999
except Exception as e:
100100
st.info(f"Parallel-coordinates unavailable: {e}")
101101

102102
st.subheader("Run comparison")
103103
fig2 = viz.plot_run_comparison(results, labels=labels, backend="plotly", show=False)
104-
st.plotly_chart(_retheme(fig2), width='stretch')
104+
st.plotly_chart(_retheme(fig2), width="stretch")

src/qqa/annealing.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -246,8 +246,13 @@ def anneal(
246246
try:
247247
score = problem.score_summary(best_sol)
248248
except Exception as exc: # noqa: BLE001 - surface but never abort
249-
score = {"label": "loss", "value": float(best_obj), "unit": "",
250-
"feasible": True, "extra": {"error": str(exc)}}
249+
score = {
250+
"label": "loss",
251+
"value": float(best_obj),
252+
"unit": "",
253+
"feasible": True,
254+
"extra": {"error": str(exc)},
255+
}
251256

252257
return AnnealResult(
253258
best_sol=best_sol,

0 commit comments

Comments
 (0)