-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo_interface.py
More file actions
508 lines (464 loc) · 21.5 KB
/
demo_interface.py
File metadata and controls
508 lines (464 loc) · 21.5 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
# Copyright 2024 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
import dash_mantine_components as dmc
from dash import dcc, html
from dwave.cloud import Client
from demo_configs import (
DEFAULT_ADVANTAGE,
DEFAULT_ADVANTAGE2,
DESCRIPTION,
MAIN_HEADER,
PRECISION_DEFAULT,
PRECISION_OPTIONS,
THUMBNAIL,
)
from src.demo_enums import AnnealType, SchemeType
THEME_COLOR = "#2d4376"
ANNEAL_TIME_RANGES = {}
# Initialize: available QPUs
try:
client = Client.from_config(client="qpu")
qpu_names = []
for qpu in client.get_solvers():
if "internal" not in qpu.name:
ANNEAL_TIME_RANGES[qpu.name] = {
"fast": qpu.properties["fast_anneal_time_range"],
"standard": qpu.properties["annealing_time_range"],
}
qpu_names.append(qpu.name)
ADVANTAGE_SOLVERS = [solver for solver in qpu_names if solver.split("_")[0] == "Advantage"]
ADVANTAGE2_SOLVERS = [solver for solver in qpu_names if solver.split("_")[0] == "Advantage2"]
if not len(ADVANTAGE_SOLVERS) or not len(ADVANTAGE2_SOLVERS):
raise Exception
except Exception:
ADVANTAGE_SOLVERS = ADVANTAGE2_SOLVERS = ["No Leap Access"]
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 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: The value of the dropdown that should be preselected.
"""
return html.Div(
className="dropdown-wrapper",
children=[
html.Label(label, htmlFor=id),
dmc.Select(
id=id,
data=options,
value=value if value else options[0]["value"],
allowDeselect=False,
),
],
)
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 generate_options(options: list | EnumMeta) -> list[dict]:
"""Generates options for dropdowns, checklists, radios, etc."""
if isinstance(options, EnumMeta):
return [{"label": option.label, "value": f"{option.value}"} for option in options]
return [{"label": f"{option}", "value": f"{option}"} for option in options]
def generate_settings_form() -> html.Div:
"""This function generates settings for selecting the scenario, model, and solver.
Returns:
html.Div: A Div containing the settings for selecting the scenario, model, and solver.
"""
radio_options_anneal = generate_options(AnnealType)
radio_options_scheme = generate_options(SchemeType)
advantage_options = generate_options(ADVANTAGE_SOLVERS)
advantage2_options = generate_options(ADVANTAGE2_SOLVERS)
precision_options = generate_options(PRECISION_OPTIONS)
advantage = (
DEFAULT_ADVANTAGE if DEFAULT_ADVANTAGE in ADVANTAGE_SOLVERS else ADVANTAGE_SOLVERS[0]
)
advantage2 = (
DEFAULT_ADVANTAGE2 if DEFAULT_ADVANTAGE2 in ADVANTAGE2_SOLVERS else ADVANTAGE2_SOLVERS[0]
)
min_anneal = max_anneal = 0
if advantage.split("_")[0] == "Advantage" and advantage2.split("_")[0] == "Advantage2":
min_anneal = max(
ANNEAL_TIME_RANGES[advantage]["standard"][0],
ANNEAL_TIME_RANGES[advantage2]["standard"][0],
)
max_anneal = min(
ANNEAL_TIME_RANGES[advantage]["standard"][1],
ANNEAL_TIME_RANGES[advantage2]["standard"][1],
)
return html.Div(
className="settings",
children=[
html.H6("Comparison Systems"),
html.Div(
[
dropdown(
"Advantage2",
"advantage2-setting",
sorted(advantage2_options, key=lambda op: op["value"]),
value=advantage2,
),
dropdown(
"Advantage",
"advantage-setting",
sorted(advantage_options, key=lambda op: op["value"]),
value=advantage,
),
],
className="settings-flex no-margin-label",
),
html.H6("Optimization Problem"),
radio(
"Weight Distribution",
"scheme-type-setting",
sorted(radio_options_scheme, key=lambda op: op["value"]),
"1",
),
html.Div(
[
dropdown(
"Weight Precision",
"precision-setting",
precision_options,
value=PRECISION_DEFAULT,
),
html.Div(
[
html.Label("Weight Random Seed", htmlFor="random-seed-setting"),
dmc.NumberInput(
id="random-seed-setting",
type="number",
),
]
),
],
className="settings-flex",
),
html.H6("Annealing Protocol"),
radio(
"Anneal Type",
"anneal-type-setting",
sorted(radio_options_anneal, key=lambda op: op["value"]),
"0",
),
html.Label("Annealing Time (microseconds)", htmlFor="annealing-time-setting"),
dmc.NumberInput(
id="annealing-time-setting",
type="number",
min=min_anneal,
max=max_anneal,
value=500,
),
html.P(id="anneal-time-help", **{"role": "presentation"}),
],
)
def generate_run_buttons() -> html.Div:
"""Run and cancel buttons to run the optimization."""
return html.Div(
id="button-group",
children=[
html.Button("Run Job", id="run-button", className="button"),
html.Button(
"Cancel Job",
id="cancel-button",
className="button",
style={"display": "none"},
),
],
)
def generate_problem_details_table(info: dict[str, dict]) -> list[html.Thead, html.Tbody]:
"""Generates table for the problem details table.
Args:
info: Dictionary of system keys and timing details dictionaries.
Returns:
list[html.Thead, html.Tbody]: The table header and body for the problem details table.
"""
table_rows = [[key, *list(timing.values())] for key, timing in info.items()]
table_headers = ["System"]
for time_key in info[table_rows[0][0]].keys():
time_key = [t.capitalize() for t in time_key.split("_")]
if time_key[0] == "Qpu":
time_key = time_key[1:]
table_headers.append(" ".join(time_key))
return [
html.Thead([html.Tr([html.Th(header) for header in table_headers])]),
html.Tbody([html.Tr([html.Td(cell) for cell in row]) for row in table_rows]),
]
def problem_details(index: int) -> html.Div:
"""Generate the problem details section.
Args:
index: Unique element id to differentiate matching elements.
Must be different from left column collapse button.
Returns:
html.Div: Div containing a collapsable table.
"""
return html.Div(
id={"type": "to-collapse-class", "index": index},
className="details-collapse-wrapper collapsed",
children=[
# Problem details collapsible button and header
html.Button(
id={"type": "collapse-trigger", "index": index},
className="details-collapse",
children=[
html.H5("Problem Details"),
html.Div(className="collapse-arrow"),
],
**{"aria-expanded": "true"},
),
html.Div(
className="details-to-collapse",
id="problem-details",
),
],
)
def create_interface():
"""Set the application HTML."""
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="pegasus-qpu"),
dcc.Store(id="zephyr-qpu"),
dcc.Store(id="chimera-g"),
dcc.Store(id="best-mapping"),
# 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,
),
]
),
]
),
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,
children=[
html.Div(
className="graph-wrapper",
children=[
html.Div(
dcc.Graph(
id="advantage-graph",
responsive=True,
config={
"displayModeBar": False
},
),
className="graph",
),
html.Div(
dcc.Graph(
id="advantage2-graph",
responsive=True,
config={
"displayModeBar": False
},
),
className="graph",
),
],
),
],
)
],
)
],
),
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,
children=html.Div(
html.Div(
dcc.Graph(
id="results-graph",
responsive=True,
config={
"displayModeBar": False
},
),
className="graph",
),
className="graph-wrapper",
),
),
# Problem details dropdown
html.Div([html.Hr(), problem_details(1)]),
],
)
],
),
],
)
],
),
],
),
],
)