multipolePDM 0.1.0__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 (43) hide show
  1. multipolepdm/__init__.py +3 -0
  2. multipolepdm/__main__.py +32 -0
  3. multipolepdm/cli.py +127 -0
  4. multipolepdm/config/common.py +7 -0
  5. multipolepdm/config/p_ado.py +3 -0
  6. multipolepdm/config/p_dco.py +10 -0
  7. multipolepdm/config/pdco.py +13 -0
  8. multipolepdm/contracts.py +222 -0
  9. multipolepdm/examples/README.md +56 -0
  10. multipolepdm/examples/example.json +45 -0
  11. multipolepdm/examples/example_PDCO.json +55 -0
  12. multipolepdm/examples/example_P_DCO.json +55 -0
  13. multipolepdm/examples/example_batch.json +159 -0
  14. multipolepdm/gui/results.py +191 -0
  15. multipolepdm/gui/self_test.py +89 -0
  16. multipolepdm/gui/window.py +560 -0
  17. multipolepdm/io/export.py +255 -0
  18. multipolepdm/io/input.py +115 -0
  19. multipolepdm/jobs/manager.py +186 -0
  20. multipolepdm/jobs/workers.py +26 -0
  21. multipolepdm/models/p_ado.py +5 -0
  22. multipolepdm/models/p_dco.py +5 -0
  23. multipolepdm/models/pdco.py +5 -0
  24. multipolepdm/models/registry.py +88 -0
  25. multipolepdm/pdm/mapping.py +200 -0
  26. multipolepdm/pdm/observations.py +63 -0
  27. multipolepdm/pdm/statistics.py +229 -0
  28. multipolepdm/physics/amplitudes.py +99 -0
  29. multipolepdm/physics/joint.py +131 -0
  30. multipolepdm/physics/populations.py +52 -0
  31. multipolepdm/physics/propagation.py +43 -0
  32. multipolepdm/physics/symmetries.py +34 -0
  33. multipolepdm/plotting/__init__.py +16 -0
  34. multipolepdm/plotting/export.py +86 -0
  35. multipolepdm/plotting/intervals.py +199 -0
  36. multipolepdm/plotting/overview.py +229 -0
  37. multipolepdm/plotting/style.py +94 -0
  38. multipolepdm-0.1.0.dist-info/METADATA +40 -0
  39. multipolepdm-0.1.0.dist-info/RECORD +43 -0
  40. multipolepdm-0.1.0.dist-info/WHEEL +5 -0
  41. multipolepdm-0.1.0.dist-info/entry_points.txt +3 -0
  42. multipolepdm-0.1.0.dist-info/licenses/LICENSE +21 -0
  43. multipolepdm-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,560 @@
1
+ """Compact editor with independent calculation, preview and save lifecycles."""
2
+
3
+ from dataclasses import replace
4
+ import json
5
+ from queue import Empty
6
+ from collections import deque
7
+ from threading import Thread
8
+
9
+ from PySide6.QtCore import QTimer
10
+ from PySide6.QtWidgets import (
11
+ QCheckBox,
12
+ QComboBox,
13
+ QDoubleSpinBox,
14
+ QFileDialog,
15
+ QFormLayout,
16
+ QGroupBox,
17
+ QHBoxLayout,
18
+ QLabel,
19
+ QLineEdit,
20
+ QMainWindow,
21
+ QMessageBox,
22
+ QPlainTextEdit,
23
+ QProgressBar,
24
+ QPushButton,
25
+ QScrollArea,
26
+ QSpinBox,
27
+ QVBoxLayout,
28
+ QWidget,
29
+ )
30
+
31
+ from multipolepdm.contracts import (
32
+ Geometry,
33
+ GridSpec,
34
+ JobRequest,
35
+ Measurement,
36
+ OutputSpec,
37
+ Transition,
38
+ )
39
+ from multipolepdm.io.input import example_data, job_from_dict, load_jobs, save_input
40
+ from multipolepdm.jobs.manager import JobManager, QueueFull
41
+ from multipolepdm.models.registry import MODE_CONFIGS
42
+
43
+
44
+ class MainWindow(QMainWindow):
45
+ def __init__(self, manager=None):
46
+ super().__init__()
47
+ self.setWindowTitle("PDM")
48
+ self.resize(800, 900)
49
+ self.manager = manager or JobManager()
50
+ self.result_windows = {}
51
+ self.opening_job = None
52
+ self.task_rows = {}
53
+ self.fields = {}
54
+ self.pending_jobs = deque()
55
+ root = QWidget()
56
+ self.setCentralWidget(root)
57
+ layout = QVBoxLayout(root)
58
+ title = QLabel("PDM | Nuclear multipole mixing")
59
+ title.setStyleSheet("font-size: 20px; font-weight: 600;")
60
+ layout.addWidget(title)
61
+ self.mode = QComboBox()
62
+ self.mode.addItems(MODE_CONFIGS)
63
+ layout.addWidget(self.mode)
64
+ self.description = QLabel()
65
+ layout.addWidget(self.description)
66
+ source = QHBoxLayout()
67
+ layout.addLayout(source)
68
+ self.file_mode = QCheckBox("Input JSON file")
69
+ source.addWidget(self.file_mode)
70
+ self.file_path = QLineEdit()
71
+ self.file_path.setPlaceholderText("Single job or batch JSON")
72
+ source.addWidget(self.file_path)
73
+ choose = QPushButton("Browse")
74
+ choose.clicked.connect(self.choose_file)
75
+ source.addWidget(choose)
76
+ scroll = QScrollArea()
77
+ scroll.setWidgetResizable(True)
78
+ layout.addWidget(scroll, 1)
79
+ body = QWidget()
80
+ scroll.setWidget(body)
81
+ body_layout = QVBoxLayout(body)
82
+ self.manual = QWidget()
83
+ body_layout.addWidget(self.manual)
84
+ form = QFormLayout(self.manual)
85
+ self.label = QLineEdit("Transition")
86
+ form.addRow("Label", self.label)
87
+ target = QHBoxLayout()
88
+ for key in ("target_initial", "target_final"):
89
+ target.addWidget(self.number(key, 0, 100, 0.5))
90
+ form.addRow("Target spin: initial / final", target)
91
+ self.multipoles = QComboBox()
92
+ self.multipoles.addItems(["M1 + E2"])
93
+ form.addRow("Target multipoles", self.multipoles)
94
+ for obs in ("P", "ratio"):
95
+ line = QHBoxLayout()
96
+ for part in ("value", "err_minus", "err_plus"):
97
+ key = f"{obs}_{part}"
98
+ line.addWidget(
99
+ self.number(
100
+ key, -10000 if part == "value" else 0.000001, 10000, 0.01
101
+ )
102
+ )
103
+ label = QLabel(
104
+ "P: value / -error / +error"
105
+ if obs == "P"
106
+ else "R_ADO: value / -error / +error"
107
+ )
108
+ form.addRow(label, line)
109
+ if obs == "ratio":
110
+ self.ratio_label = label
111
+ for key, label in (
112
+ ("theta_a_deg", "Ratio numerator target angle (deg)"),
113
+ ("theta_b_deg", "Ratio denominator target angle (deg)"),
114
+ ("theta_p_deg", "Polarization target angle (deg)"),
115
+ ):
116
+ form.addRow(label, self.number(key, 0, 180, 1))
117
+ self.gate_box = QGroupBox("DCO path")
118
+ gate_form = QFormLayout(self.gate_box)
119
+ form.addRow(self.gate_box)
120
+ self.target_first = QComboBox()
121
+ self.target_first.addItems(
122
+ ["Target first, gate later", "Gate first, target later"]
123
+ )
124
+ gate_form.addRow("Emission order", self.target_first)
125
+ gate_spins = QHBoxLayout()
126
+ for key in ("gate_initial", "gate_final"):
127
+ gate_spins.addWidget(self.number(key, 0, 100, 0.5))
128
+ gate_form.addRow("Gate spin: initial / final", gate_spins)
129
+ self.gate_multipoles = QComboBox()
130
+ self.gate_multipoles.addItems(["E2", "M1", "E1", "M2", "M1 + E2"])
131
+ gate_form.addRow("Gate multipoles", self.gate_multipoles)
132
+ gate_form.addRow(
133
+ "Gate delta (mixed gate only)",
134
+ self.number("gate_delta", -10000, 10000, 0.1),
135
+ )
136
+ gate_form.addRow(
137
+ "Relative azimuth (deg)", self.number("relative_phi_deg", -360, 360, 1)
138
+ )
139
+ gate_form.addRow(
140
+ self.azimuth_average(
141
+ "ratio_azimuth_average",
142
+ "Average DCO azimuth (full rings)",
143
+ "relative_phi_deg",
144
+ )
145
+ )
146
+ self.pgate_box = QGroupBox("Polarization direction gate")
147
+ pgate = QFormLayout(self.pgate_box)
148
+ gate_form.addRow(self.pgate_box)
149
+ pgate.addRow(
150
+ "Gate polar angle (deg)", self.number("theta_gate_p_deg", 0, 180, 1)
151
+ )
152
+ pgate.addRow("Gate azimuth (deg)", self.number("phi_gate_p_deg", -360, 360, 1))
153
+ pgate.addRow(
154
+ self.azimuth_average(
155
+ "polarization_gate_azimuth_average",
156
+ "Average P-gate azimuth (fixed polar angle)",
157
+ "phi_gate_p_deg",
158
+ )
159
+ )
160
+ advanced = QGroupBox("Advanced parameters")
161
+ advanced.setCheckable(True)
162
+ advanced.setChecked(False)
163
+ self.advanced = advanced
164
+ advanced_layout = QVBoxLayout(advanced)
165
+ advanced_content = QWidget()
166
+ advanced_layout.addWidget(advanced_content)
167
+ advanced_form = QFormLayout(advanced_content)
168
+ form.addRow(advanced)
169
+ advanced_content.setVisible(False)
170
+ advanced.toggled.connect(advanced_content.setVisible)
171
+ advanced_form.addRow(
172
+ "Target P azimuth (deg)", self.number("phi_p_deg", -360, 360, 1)
173
+ )
174
+ for key, label, lo, hi, step in (
175
+ ("xi_min_rad", "xi minimum (rad)", -1.570795, 1.570795, 0.01),
176
+ ("xi_max_rad", "xi maximum (rad)", -1.570795, 1.570795, 0.01),
177
+ ("sigma_min", "sigma minimum", 0.00001, 100, 0.05),
178
+ ("sigma_max", "sigma maximum", 0.00001, 100, 0.1),
179
+ ):
180
+ advanced_form.addRow(label, self.number(key, lo, hi, step))
181
+ for key, label, default in (
182
+ ("xi_points", "xi grid points", 3121),
183
+ ("sigma_points", "sigma grid points", 201),
184
+ ):
185
+ spin = QSpinBox()
186
+ spin.setRange(3, 100001)
187
+ spin.setValue(default)
188
+ self.fields[key] = spin
189
+ advanced_form.addRow(label, spin)
190
+ self.intermediates = QPlainTextEdit("[]")
191
+ self.intermediates.setMaximumHeight(75)
192
+ self.intermediates.setPlaceholderText(
193
+ "Intermediate transitions as JSON array; [] for adjacent lines"
194
+ )
195
+ advanced_form.addRow("Unobserved intermediate path", self.intermediates)
196
+ destination = QHBoxLayout()
197
+ layout.addLayout(destination)
198
+ self.output_path = QLineEdit("pdm-results")
199
+ destination.addWidget(QLabel("Output folder"))
200
+ destination.addWidget(self.output_path)
201
+ out_button = QPushButton("Browse")
202
+ out_button.clicked.connect(self.choose_output)
203
+ destination.addWidget(out_button)
204
+ self.full_csv = QCheckBox("Also export full grid CSV (larger and slower)")
205
+ layout.addWidget(self.full_csv)
206
+ actions = QHBoxLayout()
207
+ layout.addLayout(actions)
208
+ self.example_button = QPushButton("Load example")
209
+ self.example_button.clicked.connect(self.load_example)
210
+ actions.addWidget(self.example_button)
211
+ self.save_button = QPushButton("Save input JSON")
212
+ self.save_button.clicked.connect(self.save_json)
213
+ actions.addWidget(self.save_button)
214
+ self.calculate_button = QPushButton("Calculate")
215
+ self.calculate_button.clicked.connect(self.calculate)
216
+ actions.addWidget(self.calculate_button)
217
+ self.progress = QProgressBar()
218
+ layout.addWidget(self.progress)
219
+ self.status = QLabel(
220
+ "Ready. Select a mode and enter final measured quantities."
221
+ )
222
+ self.status.setWordWrap(True)
223
+ layout.addWidget(self.status)
224
+ self.task_list = QComboBox()
225
+ layout.addWidget(self.task_list)
226
+ self.open_button = QPushButton("Open selected result")
227
+ self.open_button.clicked.connect(self.open_selected_result)
228
+ layout.addWidget(self.open_button)
229
+ cancel = QPushButton("Cancel selected task")
230
+ cancel.clicked.connect(self.cancel_task)
231
+ layout.addWidget(cancel)
232
+ self.mode.currentTextChanged.connect(self.update_mode)
233
+ self.file_mode.toggled.connect(self.update_source)
234
+ for key in ("target_initial", "gate_initial"):
235
+ self.fields[key].valueChanged.connect(self.refresh_sigma_defaults)
236
+ self.target_first.currentIndexChanged.connect(self.refresh_sigma_defaults)
237
+ self.timer = QTimer(self)
238
+ self.timer.timeout.connect(self.process_events)
239
+ self.timer.start(50)
240
+ self.load_example()
241
+ self.update_source()
242
+
243
+ def number(self, key, lo, hi, step):
244
+ box = QDoubleSpinBox()
245
+ box.setDecimals(6)
246
+ box.setRange(lo, hi)
247
+ box.setSingleStep(step)
248
+ self.fields[key] = box
249
+ return box
250
+
251
+ def azimuth_average(self, key, label, angle):
252
+ checkbox = QCheckBox(label)
253
+ checkbox.toggled.connect(self.fields[angle].setDisabled)
254
+ self.fields[key] = checkbox
255
+ return checkbox
256
+
257
+ def update_mode(self, *args):
258
+ mode = self.mode.currentText()
259
+ self.description.setText(MODE_CONFIGS[mode].DESCRIPTION)
260
+ self.gate_box.setVisible(mode != "P_ADO")
261
+ self.pgate_box.setVisible(mode == "PDCO")
262
+ self.ratio_label.setText(
263
+ ("R_ADO" if mode == "P_ADO" else "R_DCO") + ": value / -error / +error"
264
+ )
265
+ self.refresh_sigma_defaults()
266
+
267
+ def refresh_sigma_defaults(self, *args):
268
+ if self.advanced.isChecked():
269
+ return
270
+ ref = (
271
+ self.fields["target_initial"].value()
272
+ if self.mode.currentText() == "P_ADO"
273
+ or self.target_first.currentIndex() == 0
274
+ else self.fields["gate_initial"].value()
275
+ )
276
+ self.fields["sigma_min"].setValue(0.15 if ref % 1 == 0 else 0.20)
277
+ self.fields["sigma_max"].setValue(ref)
278
+
279
+ def update_source(self, *args):
280
+ from_file = self.file_mode.isChecked()
281
+ self.manual.setEnabled(not from_file)
282
+ self.file_path.setEnabled(from_file)
283
+ self.mode.setEnabled(not from_file)
284
+ self.example_button.setEnabled(not from_file)
285
+ self.save_button.setEnabled(not from_file)
286
+
287
+ def load_example(self):
288
+ job = job_from_dict(example_data(self.mode.currentText()))
289
+ self.label.setText(job.label)
290
+ values = {
291
+ "target_initial": job.target.spin_initial,
292
+ "target_final": job.target.spin_final,
293
+ "sigma_min": 0.15 if job.reference_spin % 1 == 0 else 0.2,
294
+ "sigma_max": job.reference_spin,
295
+ "xi_min_rad": job.grid.xi_min_rad,
296
+ "xi_max_rad": job.grid.xi_max_rad,
297
+ "xi_points": job.grid.xi_points,
298
+ "sigma_points": job.grid.sigma_points,
299
+ "ratio_azimuth_average": False,
300
+ "polarization_gate_azimuth_average": False,
301
+ }
302
+ for name, obs in (("P", job.polarization), ("ratio", job.angular_ratio)):
303
+ for part in ("value", "err_minus", "err_plus"):
304
+ values[f"{name}_{part}"] = getattr(obs, part)
305
+ values.update(vars(job.geometry))
306
+ gate = job.gate or Transition(4, 2, ("E2",))
307
+ values.update(
308
+ gate_initial=gate.spin_initial,
309
+ gate_final=gate.spin_final,
310
+ gate_delta=gate.delta,
311
+ )
312
+ for key, value in values.items():
313
+ field = self.fields[key]
314
+ if isinstance(field, QCheckBox):
315
+ field.setChecked(value)
316
+ else:
317
+ field.setValue(value)
318
+ self.gate_multipoles.setCurrentText(" + ".join(gate.multipoles))
319
+ self.target_first.setCurrentIndex(0 if job.target_first else 1)
320
+ self.intermediates.setPlainText("[]")
321
+ self.update_mode()
322
+
323
+ def read_job(self):
324
+ def value(key):
325
+ field = self.fields[key]
326
+ return field.isChecked() if isinstance(field, QCheckBox) else field.value()
327
+
328
+ mode = self.mode.currentText()
329
+ obs = lambda name: Measurement(
330
+ *(value(f"{name}_{p}") for p in ("value", "err_minus", "err_plus"))
331
+ )
332
+ gate = (
333
+ None
334
+ if mode == "P_ADO"
335
+ else Transition(
336
+ value("gate_initial"),
337
+ value("gate_final"),
338
+ tuple(self.gate_multipoles.currentText().split(" + ")),
339
+ value("gate_delta"),
340
+ )
341
+ )
342
+ intermediates = (
343
+ ()
344
+ if mode == "P_ADO"
345
+ else tuple(
346
+ Transition(**t) for t in json.loads(self.intermediates.toPlainText())
347
+ )
348
+ )
349
+ job = JobRequest(
350
+ mode,
351
+ Transition(value("target_initial"), value("target_final")),
352
+ obs("P"),
353
+ obs("ratio"),
354
+ label=self.label.text(),
355
+ gate=gate,
356
+ target_first=self.target_first.currentIndex() == 0,
357
+ intermediates=intermediates,
358
+ geometry=Geometry(**{k: value(k) for k in Geometry.__dataclass_fields__}),
359
+ grid=GridSpec(**{k: value(k) for k in GridSpec.__dataclass_fields__}),
360
+ output=OutputSpec(self.output_path.text(), self.full_csv.isChecked()),
361
+ )
362
+ job.grid.axes(job.reference_spin)
363
+ return job
364
+
365
+ def choose_file(self):
366
+ path, _ = QFileDialog.getOpenFileName(self, "Input jobs", "", "JSON (*.json)")
367
+ if path:
368
+ self.file_path.setText(path)
369
+ self.file_mode.setChecked(True)
370
+
371
+ def choose_output(self):
372
+ path = QFileDialog.getExistingDirectory(
373
+ self, "Output folder", self.output_path.text()
374
+ )
375
+ if path:
376
+ self.output_path.setText(path)
377
+
378
+ def save_json(self):
379
+ try:
380
+ job = self.read_job()
381
+ path, _ = QFileDialog.getSaveFileName(
382
+ self, "Save input", "example.json", "JSON (*.json)"
383
+ )
384
+ if path:
385
+ save_input(job, path)
386
+ except Exception as exc:
387
+ QMessageBox.warning(self, "Check inputs", str(exc))
388
+
389
+ def calculate(self):
390
+ try:
391
+ jobs = (
392
+ load_jobs(self.file_path.text())
393
+ if self.file_mode.isChecked()
394
+ else (self.read_job(),)
395
+ )
396
+ # The file owns all scientific fields; only the visible destination overrides output.
397
+ for job in jobs:
398
+ job = replace(
399
+ job,
400
+ output=OutputSpec(
401
+ self.output_path.text(), self.full_csv.isChecked()
402
+ ),
403
+ )
404
+ self.pending_jobs.append(job)
405
+ self.status.setText(
406
+ f"Queued {len(jobs)} job(s). You can edit and submit another."
407
+ )
408
+ self.submit_pending()
409
+ except Exception as exc:
410
+ QMessageBox.warning(self, "Check inputs", str(exc))
411
+
412
+ def submit_pending(self):
413
+ while self.pending_jobs:
414
+ job = self.pending_jobs[0]
415
+ try:
416
+ identifier = self.manager.submit(job)
417
+ except QueueFull:
418
+ break
419
+ except Exception as exc:
420
+ self.pending_jobs.popleft()
421
+ self.task_list.addItem(job.label + " | submission failed")
422
+ self.status.setText("Submission failed: " + str(exc))
423
+ continue
424
+ self.pending_jobs.popleft()
425
+ self.task_list.addItem(job.label + " | queued", identifier)
426
+ self.task_rows[identifier] = self.task_list.count() - 1
427
+
428
+ def cancel_task(self):
429
+ identifier = self.task_list.currentData()
430
+ if identifier:
431
+ self.manager.cancel(identifier)
432
+
433
+ def open_selected_result(self):
434
+ identifier = self.task_list.currentData()
435
+ if not identifier or self.opening_job is not None:
436
+ return
437
+ window = self.result_windows.get(identifier)
438
+ if window is not None:
439
+ window.showNormal()
440
+ window.raise_()
441
+ window.activateWindow()
442
+ return
443
+ try:
444
+ self.manager.open_saved(identifier)
445
+ except RuntimeError as exc:
446
+ self.status.setText(str(exc))
447
+ return
448
+ self.opening_job = identifier
449
+ self.open_button.setEnabled(False)
450
+ self.status.setText("Opening saved result...")
451
+
452
+ def retry_data_save(self, identifier):
453
+ window = self.result_windows[identifier]
454
+ destination = QFileDialog.getExistingDirectory(
455
+ window, "Choose output folder", str(window.directory.parent)
456
+ )
457
+ if not destination or self.result_windows.get(identifier) is not window:
458
+ return
459
+ try:
460
+ self.manager.retry_save(
461
+ identifier, window.result, window.summary, destination
462
+ )
463
+ except Exception as exc:
464
+ window.show_data_state("save_failed", window.directory, str(exc))
465
+ return
466
+ window.show_data_state("queued", self.manager.handles[identifier].directory)
467
+
468
+ def forget_result(self, identifier, window):
469
+ if self.result_windows.get(identifier) is window:
470
+ self.result_windows.pop(identifier)
471
+
472
+ def show_result(self, identifier, event, saved=False):
473
+ try:
474
+ from multipolepdm.gui.results import ResultsWindow
475
+
476
+ window = ResultsWindow(event["result"], event["summary"], event["directory"])
477
+ window.closed.connect(
478
+ lambda closed: self.forget_result(identifier, closed)
479
+ )
480
+ window.retry_button.clicked.connect(lambda: self.retry_data_save(identifier))
481
+ if saved:
482
+ window.show_data_state("saved", event["directory"])
483
+ if len(self.result_windows) >= 3:
484
+ oldest = next(
485
+ (
486
+ job_id
487
+ for job_id in self.result_windows
488
+ if self.manager.handles[job_id].state in ("saved", "cancelled")
489
+ ),
490
+ next(iter(self.result_windows)),
491
+ )
492
+ self.result_windows.pop(oldest).close()
493
+ self.result_windows[identifier] = window
494
+ window.show()
495
+ except Exception as exc:
496
+ self.status.setText("Could not display result: " + str(exc))
497
+
498
+ def process_events(self):
499
+ self.submit_pending()
500
+ while True:
501
+ try:
502
+ event = self.manager.events.get_nowait()
503
+ except Empty:
504
+ break
505
+ identifier, state = event["job_id"], event["state"]
506
+ if state in ("opened", "open_failed"):
507
+ self.opening_job = None
508
+ self.open_button.setEnabled(True)
509
+ if state == "opened":
510
+ self.status.setText("Opened saved result: " + event["directory"])
511
+ self.show_result(identifier, event, saved=True)
512
+ else:
513
+ self.status.setText("Could not open saved result: " + event["error"])
514
+ continue
515
+ label = self.manager.handles[identifier].job.label
516
+ if identifier in self.task_rows:
517
+ self.task_list.setItemText(
518
+ self.task_rows[identifier], label + " | " + state
519
+ )
520
+ if "percent" in event:
521
+ self.progress.setValue(round(event["percent"]))
522
+ self.status.setText(
523
+ label
524
+ + " | "
525
+ + state
526
+ + " | "
527
+ + event["directory"]
528
+ + (" | " + event["error"] if "error" in event else "")
529
+ )
530
+ if state == "ready":
531
+ self.show_result(identifier, event)
532
+ elif identifier in self.result_windows:
533
+ self.result_windows[identifier].show_data_state(
534
+ state, event["directory"], event.get("error", "")
535
+ )
536
+
537
+ def closeEvent(self, event):
538
+ active = bool(self.pending_jobs) or any(
539
+ h.state not in ("saved", "cancelled", "save_failed", "calculation_failed")
540
+ for h in self.manager.handles.values()
541
+ )
542
+ if active:
543
+ answer = QMessageBox.question(
544
+ self,
545
+ "Tasks active",
546
+ "Cancel pending work and close? Completed previews and saved files are kept.",
547
+ )
548
+ if answer != QMessageBox.StandardButton.Yes:
549
+ event.ignore()
550
+ return
551
+ self.timer.stop()
552
+ self.pending_jobs.clear()
553
+ for window in list(self.result_windows.values()):
554
+ window.close()
555
+ Thread(
556
+ target=self.manager.shutdown,
557
+ kwargs={"wait": True, "cancel": True},
558
+ daemon=False,
559
+ ).start()
560
+ event.accept()