-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo_interface.py
More file actions
725 lines (656 loc) · 29 KB
/
Copy pathdemo_interface.py
File metadata and controls
725 lines (656 loc) · 29 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
# Copyright 2026 D-Wave
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This file stores the Dash HTML layout for the app."""
from __future__ import annotations
from enum import EnumMeta
from pathlib import Path
import dash_mantine_components as dmc
import plotly.graph_objects as go
from dash import dcc, html
from demo_configs import (
DESCRIPTION,
INPUT_LABELS,
MAIN_HEADER,
RUNS,
SOLVER_TIME,
THUMBNAIL,
)
from src.demo_enums import SolverType
THEME_COLOR = "#2d4376"
def slider(label: str, id: str, config: dict) -> html.Div:
"""Slider element for value selection.
Args:
label: The title that goes above the slider.
id: A unique selector for this element.
config: A dictionary of slider configurations, see dmc.Slider Dash Mantine docs.
"""
return html.Div(
className="slider-wrapper",
children=[
html.Label(label, htmlFor=id),
dmc.Slider(
id=id,
className="slider",
**config,
marks=[
{"value": config["min"], "label": f'{config["min"]}'},
{"value": config["max"], "label": f'{config["max"]}'},
],
labelAlwaysOn=True,
thumbLabel=f"{label} slider",
color=THEME_COLOR,
),
],
)
def range_slider(label: str, id: str, config: dict) -> html.Div:
"""Range slider element for value selection.
Args:
label: The title that goes above the range slider.
id: A unique selector for this element.
config: A dictionary of range slider configurations, see dmc.RangeSlider Dash Mantine docs.
"""
return html.Div(
className="rangeslider-wrapper",
children=[
html.Label(label, htmlFor=id),
dmc.RangeSlider(
id=id,
className="slider",
**config,
marks=[
{"value": config["min"], "label": f'{config["min"]}'},
{"value": config["max"], "label": f'{config["max"]}'},
],
labelAlwaysOn=True,
thumbFromLabel=f"{label} slider start",
thumbToLabel=f"{label} slider end",
color=THEME_COLOR,
),
],
)
def dropdown(label: str, id: str, options: list, value: str | None = None) -> html.Div:
"""Dropdown element for option selection.
Args:
label: The title that goes above the dropdown.
id: A unique selector for this element.
options: A list of dictionaries of labels and values.
value: Optional selected value.
"""
return html.Div(
className="dropdown-wrapper",
children=[
html.Label(label, htmlFor=id),
dmc.Select(
id=id,
data=options,
value=value if value is not None else options[0]["value"],
allowDeselect=False,
),
],
)
def checklist(label: str, id: str, options: list, values: list, inline: bool = True) -> html.Div:
"""Checklist element for option selection.
Args:
label: The title that goes above the checklist.
id: A unique selector for this element.
options: A list of dictionaries of labels and values.
values: A list of values that should be preselected in the checklist.
inline: Whether the options of the checklist are displayed beside or below each other.
"""
return html.Div(
className="checklist-wrapper",
children=[
dmc.CheckboxGroup(
id=id,
className=f"checklist{' checklist--inline' if inline else ''}",
label=label,
value=values,
children=dmc.Group(
[
dmc.Checkbox(
label=option["label"], value=option["value"], color=THEME_COLOR
)
for option in options
],
),
),
],
)
def checkbox(label: str, id: str, checked: bool) -> html.Div:
"""Checkbox element.
Args:
label: The title that goes above the checkbox.
id: A unique selector for this element.
checked: Whether the checkbox is checked or not.
"""
return html.Div(
className="checkbox-wrapper",
children=[
dmc.Checkbox(
id=id,
label=label,
checked=checked,
color=THEME_COLOR,
)
],
)
def radio(label: str, id: str, options: list, value: str, inline: bool = True) -> html.Div:
"""Radio element for option selection.
Args:
label: The title that goes above the radio.
id: A unique selector for this element.
options: A list of dictionaries of labels and values.
value: The value of the radio that should be preselected.
inline: Whether the options are displayed beside or below each other.
"""
return html.Div(
className="radio-wrapper",
children=[
dmc.RadioGroup(
id=id,
className=f"radio{' radio--inline' if inline else ''}",
label=label,
value=value,
children=dmc.Group(
[
dmc.Radio(option["label"], value=option["value"], color=THEME_COLOR)
for option in options
]
),
),
],
)
def input(label: str, id: str, configs: dict, type: str = "number") -> html.Div:
"""Input element for either text or number input.
Args:
label: The title that goes above the input.
id: A unique selector for this element.
configs: A dictionary of configurations for the input element.
type: The type of input, either "number" or "text".
"""
return html.Div(
className="input-wrapper",
children=[
html.Label(label, htmlFor=id),
(
dmc.TextInput(
id=id,
**configs,
)
if type == "text"
else dmc.NumberInput(
id=id,
**configs,
)
),
],
)
def generate_options(options: list | EnumMeta | dict) -> list[dict]:
"""Format options for dropdowns, checklists, radios, etc.
Args:
options: A list, EnumMeta, or dictionary of options to format.
Returns:
A list of dictionaries with "label" and "value" keys for each option.
"""
if isinstance(options, EnumMeta):
return [{"label": option.label, "value": f"{option.value}"} for option in options]
if isinstance(options, dict):
return [{"label": f"{key}", "value": f"{value}"} for key, value in options.items()]
return [{"label": f"{option}", "value": f"{option}"} for option in options]
def generate_settings_form() -> html.Div:
"""Generate settings for selecting the scenario, model, and solver.
Returns:
A Div containing the settings for selecting the scenario, model, and solver.
"""
solver_options = generate_options(SolverType)
input_dir = Path("input")
file_options = sorted(
[
{"label": INPUT_LABELS.get(str(path), str(path.name)), "value": str(path)}
for path in input_dir.glob("*")
if path.is_file()
],
key=lambda option: option["label"],
)
return html.Div(
className="settings",
children=[
dropdown(
"Scenario",
"input-file-select",
file_options,
value=file_options[0]["value"],
),
slider(
"Runs Per Solver",
"runs",
RUNS,
),
checklist(
"Solvers",
"solver-selection",
sorted(solver_options, key=lambda op: op["value"]),
[option["value"] for option in solver_options],
inline=False,
),
input(
"Solver Time Limit (seconds)",
"solver-time-limit",
SOLVER_TIME,
),
],
)
def generate_run_buttons() -> html.Div:
"""Generate run and cancel buttons to run the optimization."""
return html.Div(
id="button-group",
children=[
html.Button("Run Optimization", id="run-button", className="button"),
html.Button(
"Cancel Optimization",
id="cancel-button",
className="button",
style={"display": "none"},
),
],
)
def solver_not_selected_panel(solver_name: str) -> html.Div:
"""Placeholder content for a solver tab when the solver was not selected.
Args:
solver_name: Human-readable name of the solver (e.g. ``"HiGHS"``).
Returns:
An html.Div containing a short explanatory message.
"""
return html.Div([html.P(f"{solver_name} was not selected.")])
def solver_solution_panel(has_solution: bool, figure: go.Figure, solver_index: str) -> dcc.Graph | html.P:
"""Return a graph of the solver's best solution, or a 'no solution' message.
Args:
has_solution: Whether the solver produced a feasible schedule.
figure: A Plotly figure to display when ``has_solution`` is ``True``.
solver_index: Short key identifying this solver (e.g. ``"highs"``), used
as the ``index`` of the pattern-matching graph ID.
Returns:
A dcc.Graph wrapping the figure, or an html.P placeholder if no solution
was found within the time limit.
"""
if has_solution:
return dcc.Graph(
id={"type": "solver-graph", "index": solver_index},
figure=figure,
config={"displayModeBar": False},
responsive=True,
clear_on_unhover=True,
)
return html.H2(
"No solution found within the given time limit.",
className="placeholder-text",
)
def waiting_panel() -> html.Div:
"""Placeholder shown on the Results tab while solvers are still running.
Returns:
An html.Div containing a short status message.
"""
return html.Div([html.P("Waiting for solvers to finish...")])
def comparison_panel(figure: go.Figure | None) -> dcc.Graph | html.H4:
"""Wrap the comparison Plotly figure in a dcc.Graph, or show a fallback message.
Args:
figure: A Plotly figure to display, or ``None`` if no solutions are available.
Returns:
A dcc.Graph wrapping the figure, or an html.H4 placeholder if ``figure`` is
``None``.
"""
if figure is None:
return html.H4(
"No solutions found to compare.",
className="placeholder-text",
)
return dcc.Graph(figure=figure, config={"displayModeBar": False}, responsive=True)
def comparison_summary_table(
summary_rows: list[dict],
min_energy: int | float | None,
known_optimal: int | float | None,
solver_peaks: dict[str, tuple[int, int]] | None = None,
mech_rate: int = 100,
tech_rate: int = 51,
) -> html.Table:
"""Build the highlighted Comparison Summary table.
Rows with 0 OK runs are highlighted red; the row with the lowest best
energy is highlighted teal; known-optimal values are annotated.
Args:
summary_rows: Aggregated result rows as returned by ``summarize_runs``.
min_energy: The lowest best-energy value across all solvers, used for
row highlighting. Pass ``None`` if no feasible solutions exist.
known_optimal: The known optimal objective value for the instance, or
``None`` if unknown.
solver_peaks: Mapping of formulation label → ``(peak_mechanics, peak_technicians)``
used to render the cost breakdown columns. Pass ``None`` to omit.
mech_rate: Cost per mechanic (default 100).
tech_rate: Cost per technician (default 51).
Returns:
An html.Table with styled rows and an ``(optimal)`` annotation where
applicable.
"""
def fmt_energy(val: object) -> str:
if val is None:
return "n/a"
s = str(val)
if known_optimal is not None and val == known_optimal:
return f"{s} (optimal)"
return s
def row_class(row: dict) -> str:
if row["ok_runs"] == 0:
return "row-highlight-fail"
if min_energy is not None and row["best_energy"] == min_energy:
return "row-highlight-best"
return ""
def fmt_peak(formulation: str, idx: int, rate: int) -> str:
if solver_peaks is None:
return "–"
peaks = solver_peaks.get(formulation)
if peaks is None:
return "–"
count = peaks[idx]
return f"{count * rate}"
headers = [
"Formulation",
"Runs",
"OK Runs",
"Mechanics Cost",
"Technicians Cost",
"Best Energy",
"Avg Energy",
]
return html.Table(
className="problem-details-table",
children=[
html.Thead(html.Tr([html.Th(h) for h in headers])),
html.Tbody(
[
html.Tr(
className=row_class(row),
children=[
html.Td(str(row["formulation"])),
html.Td(str(row["runs"])),
html.Td(str(row["ok_runs"])),
html.Td(fmt_peak(row["formulation"], 0, mech_rate)),
html.Td(fmt_peak(row["formulation"], 1, tech_rate)),
html.Td(fmt_energy(row["best_energy"])),
html.Td(str(row["avg_energy"])),
],
)
for row in summary_rows
]
),
],
)
def results_layout(comparison_element: dcc.Graph | html.H4, summary_table: html.Table) -> html.Div:
"""Build the Results tab content with a comparison graph and summary table.
Args:
comparison_element: A dcc.Graph or placeholder element for the comparison
chart, displayed on the left.
summary_table: The html.Table built by ``comparison_summary_table``,
displayed on the right.
Returns:
An html.Div with a flex layout containing the comparison element and table.
"""
return html.Div(
className="results-layout",
children=[
html.Div(
className="results-layout__table",
children=[
summary_table,
],
),
html.Div(
className="results-layout__graph",
children=comparison_element,
),
],
)
def create_interface() -> html.Div:
"""Create the main application interface."""
return html.Div(
id="app-container",
children=[
html.A( # Skip link for accessibility
"Skip to main content",
href="#main-content",
id="skip-to-main",
className="skip-link",
tabIndex=1,
),
# Below are any temporary storage items, e.g., for sharing data between callbacks.
dcc.Store(id="run-in-progress", data=False), # Indicates whether run is in progress
dcc.Store(id="running-highs", data=False),
dcc.Store(id="running-scip", data=False),
dcc.Store(id="running-stride", data=False),
dcc.Store(id="highs-store", data={}),
dcc.Store(id="scip-store", data={}),
dcc.Store(id="stride-store", data={}),
# Settings and results columns
html.Main(
className="columns-main",
id="main-content",
children=[
# Left column
html.Div(
id={"type": "to-collapse-class", "index": 0},
className="left-column",
children=[
html.Div(
className="left-column-layer-1", # Fixed width Div to collapse
children=[
html.Div(
className="left-column-layer-2", # Padding and content wrapper
children=[
html.Div(
[
html.H1(MAIN_HEADER),
html.P(DESCRIPTION),
],
className="title-section",
),
html.Div(
[
html.Div(
html.Div(
[
generate_settings_form(),
generate_run_buttons(),
],
className="settings-and-buttons",
),
className="settings-and-buttons-wrapper",
),
# Left column collapse button
html.Div(
html.Button(
id={
"type": "collapse-trigger",
"index": 0,
},
className="left-column-collapse",
title="Collapse sidebar",
children=[
html.Div(className="collapse-arrow")
],
**{"aria-expanded": "true"},
),
),
],
className="form-section",
),
],
)
],
),
],
),
# Right column
html.Div(
className="right-column",
children=[
dmc.Tabs(
id="tabs",
value="input-tab",
color="white",
children=[
html.Header(
className="banner",
children=[
html.Nav(
[
dmc.TabsList(
[
dmc.TabsTab("Input", value="input-tab"),
dmc.TabsTab(
"Results",
value="results-tab",
id="results-tab",
disabled=True,
),
dmc.TabsTab(
"HiGHS",
value="highs-tab",
id="highs-tab",
disabled=True,
),
dmc.TabsTab(
"SCIP",
value="scip-tab",
id="scip-tab",
disabled=True,
),
dmc.TabsTab(
"Stride",
value="stride-tab",
id="stride-tab",
disabled=True,
),
]
),
]
),
html.Img(src=THUMBNAIL, alt="D-Wave logo"),
],
),
dmc.TabsPanel(
value="input-tab",
tabIndex="12",
children=[
html.Div(
className="tab-content-wrapper",
children=[
dcc.Loading(
parent_className="input",
type="circle",
color=THEME_COLOR,
delay_show=700,
# A Dash callback (in app.py) will generate content in the Div below
children=html.Div(
id="input",
children=dcc.Graph(
id="input-graph",
config={"displayModeBar": False},
responsive=True,
clear_on_unhover=True,
),
),
),
],
)
],
),
dmc.TabsPanel(
value="results-tab",
tabIndex="13",
children=[
html.Div(
className="tab-content-wrapper",
children=[
dcc.Loading(
parent_className="results",
type="circle",
color=THEME_COLOR,
delay_show=300,
# A Dash callback will generate content in the Div below
children=html.Div(id="results"),
),
],
)
],
),
dmc.TabsPanel(
value="highs-tab",
tabIndex="14",
children=[
html.Div(
className="tab-content-wrapper",
children=[
dcc.Loading(
parent_className="results",
type="circle",
color=THEME_COLOR,
delay_show=700,
children=html.Div(id="highs-results"),
),
],
)
],
),
dmc.TabsPanel(
value="scip-tab",
tabIndex="15",
children=[
html.Div(
className="tab-content-wrapper",
children=[
dcc.Loading(
parent_className="results",
type="circle",
color=THEME_COLOR,
delay_show=700,
children=html.Div(id="scip-results"),
),
],
)
],
),
dmc.TabsPanel(
value="stride-tab",
tabIndex="16",
children=[
html.Div(
className="tab-content-wrapper",
children=[
dcc.Loading(
parent_className="results",
type="circle",
color=THEME_COLOR,
delay_show=700,
children=html.Div(id="stride-results"),
),
],
)
],
),
],
)
],
),
],
),
],
)