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,159 @@
1
+ {
2
+ "jobs": [
3
+ {
4
+ "mode": "P_ADO",
5
+ "label": "Synthetic P_ADO",
6
+ "target": {
7
+ "spin_initial": 5.0,
8
+ "spin_final": 4.0,
9
+ "multipoles": [
10
+ "M1",
11
+ "E2"
12
+ ]
13
+ },
14
+ "observations": {
15
+ "P": {
16
+ "value": -0.8765882708591118,
17
+ "err_minus": 0.04,
18
+ "err_plus": 0.04
19
+ },
20
+ "R_ADO": {
21
+ "value": 0.514138873717746,
22
+ "err_minus": 0.04,
23
+ "err_plus": 0.04
24
+ }
25
+ },
26
+ "geometry": {
27
+ "theta_a_deg": 90.0,
28
+ "theta_b_deg": 30.0,
29
+ "theta_p_deg": 90.0,
30
+ "relative_phi_deg": 0.0,
31
+ "phi_p_deg": 0.0,
32
+ "theta_gate_p_deg": 90.0,
33
+ "phi_gate_p_deg": 0.0
34
+ },
35
+ "grid": {
36
+ "xi_min_rad": -1.56,
37
+ "xi_max_rad": 1.56,
38
+ "xi_points": 3121,
39
+ "sigma_min": null,
40
+ "sigma_max": null,
41
+ "sigma_points": 201
42
+ },
43
+ "output": {
44
+ "directory": "pdm-results",
45
+ "full_csv": false
46
+ }
47
+ },
48
+ {
49
+ "mode": "P_DCO",
50
+ "label": "Synthetic P_DCO",
51
+ "target": {
52
+ "spin_initial": 5.0,
53
+ "spin_final": 4.0,
54
+ "multipoles": [
55
+ "M1",
56
+ "E2"
57
+ ]
58
+ },
59
+ "observations": {
60
+ "P": {
61
+ "value": -0.8765882708591118,
62
+ "err_minus": 0.04,
63
+ "err_plus": 0.04
64
+ },
65
+ "R_DCO": {
66
+ "value": 0.7412356817486342,
67
+ "err_minus": 0.04,
68
+ "err_plus": 0.04
69
+ }
70
+ },
71
+ "geometry": {
72
+ "theta_a_deg": 90.0,
73
+ "theta_b_deg": 30.0,
74
+ "theta_p_deg": 90.0,
75
+ "relative_phi_deg": 0.0,
76
+ "phi_p_deg": 0.0,
77
+ "theta_gate_p_deg": 90.0,
78
+ "phi_gate_p_deg": 0.0
79
+ },
80
+ "grid": {
81
+ "xi_min_rad": -1.56,
82
+ "xi_max_rad": 1.56,
83
+ "xi_points": 3121,
84
+ "sigma_min": null,
85
+ "sigma_max": null,
86
+ "sigma_points": 201
87
+ },
88
+ "output": {
89
+ "directory": "pdm-results",
90
+ "full_csv": false
91
+ },
92
+ "gate": {
93
+ "spin_initial": 4.0,
94
+ "spin_final": 2.0,
95
+ "multipoles": [
96
+ "E2"
97
+ ],
98
+ "delta": 0.0
99
+ },
100
+ "target_first": true,
101
+ "intermediates": []
102
+ },
103
+ {
104
+ "mode": "PDCO",
105
+ "label": "Synthetic PDCO",
106
+ "target": {
107
+ "spin_initial": 5.0,
108
+ "spin_final": 4.0,
109
+ "multipoles": [
110
+ "M1",
111
+ "E2"
112
+ ]
113
+ },
114
+ "observations": {
115
+ "P": {
116
+ "value": 0.523967979251427,
117
+ "err_minus": 0.04,
118
+ "err_plus": 0.04
119
+ },
120
+ "R_DCO": {
121
+ "value": 3.4895433362026465,
122
+ "err_minus": 0.1,
123
+ "err_plus": 0.1
124
+ }
125
+ },
126
+ "geometry": {
127
+ "theta_a_deg": 90.0,
128
+ "theta_b_deg": 30.0,
129
+ "theta_p_deg": 90.0,
130
+ "relative_phi_deg": 0.0,
131
+ "phi_p_deg": 0.0,
132
+ "theta_gate_p_deg": 90.0,
133
+ "phi_gate_p_deg": 0.0
134
+ },
135
+ "grid": {
136
+ "xi_min_rad": -1.56,
137
+ "xi_max_rad": 1.56,
138
+ "xi_points": 3121,
139
+ "sigma_min": null,
140
+ "sigma_max": null,
141
+ "sigma_points": 201
142
+ },
143
+ "output": {
144
+ "directory": "pdm-results",
145
+ "full_csv": false
146
+ },
147
+ "gate": {
148
+ "spin_initial": 4.0,
149
+ "spin_final": 2.0,
150
+ "multipoles": [
151
+ "E2"
152
+ ],
153
+ "delta": 0.0
154
+ },
155
+ "target_first": true,
156
+ "intermediates": []
157
+ }
158
+ ]
159
+ }
@@ -0,0 +1,191 @@
1
+ """Scrollable, zoomable scientific preview independent of disk completion."""
2
+
3
+ from pathlib import Path
4
+ from concurrent.futures import ThreadPoolExecutor
5
+ from queue import Queue, Empty
6
+
7
+ from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg, NavigationToolbar2QT
8
+ from PySide6.QtCore import QTimer, Signal
9
+ from PySide6.QtWidgets import (
10
+ QFileDialog,
11
+ QLabel,
12
+ QPlainTextEdit,
13
+ QPushButton,
14
+ QScrollArea,
15
+ QVBoxLayout,
16
+ QHBoxLayout,
17
+ QWidget,
18
+ )
19
+
20
+
21
+ def summary_text(summary):
22
+ lines = []
23
+ for name, marginal in (
24
+ ("delta", summary.delta),
25
+ ("sigma/I_ref", summary.sigma_over_i),
26
+ ):
27
+ lines.append(f"{name}: median {marginal.median:.5g}; mode {marginal.mode:.5g}")
28
+ for interval in marginal.intervals:
29
+ pieces = " U ".join(f"[{a:.5g}, {b:.5g}]" for a, b in interval.hdi)
30
+ lines.append(
31
+ f" {100 * interval.mass:g}% ETI [{interval.eti[0]:.5g}, {interval.eti[1]:.5g}]; HDI {pieces}"
32
+ )
33
+ return "\n".join(lines)
34
+
35
+
36
+ class PreviewToolbar(NavigationToolbar2QT):
37
+ toolitems = tuple(
38
+ item for item in NavigationToolbar2QT.toolitems if item[3] != "save_figure"
39
+ )
40
+
41
+
42
+ class ResultsWindow(QWidget):
43
+ closed = Signal(object)
44
+
45
+ def __init__(self, result, summary, directory, parent=None):
46
+ from multipolepdm.plotting.overview import make_preview
47
+ from multipolepdm.plotting.style import GUI_STYLE
48
+
49
+ super().__init__(parent)
50
+ self.setWindowTitle(f"PDM results - {result.job.label}")
51
+ self.resize(1050, 900)
52
+ self.result, self.summary, self.directory = result, summary, Path(directory)
53
+ self.export_events = Queue()
54
+ self.exporter = ThreadPoolExecutor(
55
+ max_workers=1, thread_name_prefix="pdm-figure-export"
56
+ )
57
+ self.export_timer = QTimer(self)
58
+ self.export_timer.timeout.connect(self.process_exports)
59
+ self.export_timer.start(100)
60
+ self.preview = make_preview(result, summary, style=GUI_STYLE)
61
+ outer = QVBoxLayout(self)
62
+ self.status = QLabel(f"Calculation ready; data saving to {directory}")
63
+ self.status.setWordWrap(True)
64
+ self.status.setTextInteractionFlags(
65
+ __import__("PySide6.QtCore", fromlist=["Qt"]).Qt.TextSelectableByMouse
66
+ )
67
+ outer.addWidget(self.status)
68
+ self.retry_button = QPushButton("Retry data save...")
69
+ self.retry_button.hide()
70
+ outer.addWidget(self.retry_button)
71
+ scroll = QScrollArea()
72
+ scroll.setWidgetResizable(True)
73
+ outer.addWidget(scroll)
74
+ content = QWidget()
75
+ layout = QVBoxLayout(content)
76
+ scroll.setWidget(content)
77
+ self.canvas = FigureCanvasQTAgg(self.preview.figure)
78
+ self.canvas.setMinimumSize(760, 600)
79
+ self.toolbar = PreviewToolbar(self.canvas, self)
80
+ self.toolbar.setToolTip("Preview navigation")
81
+ outer.addWidget(self.toolbar)
82
+ layout.addWidget(self.canvas)
83
+ view_controls = QHBoxLayout()
84
+ layout.addLayout(view_controls)
85
+ focus = QPushButton("Focus delta (95% intervals)")
86
+ focus.clicked.connect(self.focus_delta)
87
+ view_controls.addWidget(focus)
88
+ reset = QPushButton("Show full delta range")
89
+ reset.clicked.connect(self.full_delta)
90
+ view_controls.addWidget(reset)
91
+ buttons = QHBoxLayout()
92
+ layout.addLayout(buttons)
93
+ for index, label in enumerate(
94
+ (
95
+ "Save overview",
96
+ "Save observation",
97
+ "Save parameters",
98
+ "Save delta",
99
+ "Save sigma/I",
100
+ )
101
+ ):
102
+ button = QPushButton(label)
103
+ button.setToolTip("Export the scientific figure from the computed data.")
104
+ button.clicked.connect(lambda checked=False, n=index: self.save_plot(n))
105
+ buttons.addWidget(button)
106
+ stats = QPlainTextEdit(
107
+ f"Gaussian reference spin I_ref = {result.response.reference_spin:g}; "
108
+ "delta convention: KS/Droste.\n" + summary_text(summary)
109
+ )
110
+ stats.setReadOnly(True)
111
+ stats.setMinimumHeight(110)
112
+ stats.setMaximumHeight(160)
113
+ outer.addWidget(stats)
114
+ if result.warnings:
115
+ warning = QLabel("\n".join(result.warnings))
116
+ warning.setWordWrap(True)
117
+ layout.addWidget(warning)
118
+ self.canvas.draw()
119
+
120
+ def show_data_state(self, state, directory, error=""):
121
+ self.directory = Path(directory)
122
+ self.status.setText(
123
+ f"{state}: {directory}" + (f" | {error}" if error else "")
124
+ )
125
+ self.retry_button.setVisible(state == "save_failed")
126
+
127
+ def focus_delta(self):
128
+ interval = min(self.summary.delta.intervals, key=lambda x: abs(x.mass - 0.95))
129
+ ends = [*interval.eti, *[x for pair in interval.hdi for x in pair]]
130
+ lo, hi = min(ends), max(ends)
131
+ pad = max((hi - lo) * 0.1, 1e-6)
132
+ self.preview.axes[2].set_xlim(lo - pad, hi + pad)
133
+ self.preview.axes[2].set_title(
134
+ f"Display: {interval.mass:.0%} interval envelope", fontsize=9
135
+ )
136
+ self.canvas.draw_idle()
137
+
138
+ def full_delta(self):
139
+ self.preview.axes[2].set_xlim(
140
+ self.summary.delta.coordinate[0], self.summary.delta.coordinate[-1]
141
+ )
142
+ self.preview.axes[2].set_title("Display: full computed delta range", fontsize=9)
143
+ self.canvas.draw_idle()
144
+
145
+ def process_exports(self):
146
+ while True:
147
+ try:
148
+ message = self.export_events.get_nowait()
149
+ except Empty:
150
+ break
151
+ self.status.setText(message)
152
+
153
+ def save_plot(self, index):
154
+ from multipolepdm.plotting.export import supported_formats
155
+
156
+ filters = "Figures (" + " ".join("*." + x for x in supported_formats()) + ")"
157
+ path, _ = QFileDialog.getSaveFileName(
158
+ self,
159
+ "Save scientific figure",
160
+ str(self.directory / ("overview" if index == 0 else f"panel-{index}"))
161
+ + ".pdf",
162
+ filters,
163
+ )
164
+ if not path:
165
+ return
166
+ self.status.setText("Export queued: " + path)
167
+ # Worker closures must not own Qt widgets: their final reference could
168
+ # otherwise be released on a worker thread during window teardown.
169
+ result, summary, events = self.result, self.summary, self.export_events
170
+
171
+ def save():
172
+ try:
173
+ if index == 0:
174
+ from multipolepdm.plotting.export import save_overview
175
+
176
+ save_overview(result, summary, path)
177
+ else:
178
+ from multipolepdm.plotting.export import save_panel
179
+
180
+ save_panel(result, summary, "abcd"[index - 1], path)
181
+ events.put("Figure saved: " + path)
182
+ except Exception as exc:
183
+ events.put("Figure export failed: " + str(exc))
184
+
185
+ self.exporter.submit(save)
186
+
187
+ def closeEvent(self, event):
188
+ self.export_timer.stop()
189
+ self.exporter.shutdown(wait=False)
190
+ event.accept()
191
+ self.closed.emit(self)
@@ -0,0 +1,89 @@
1
+ """Packaged GUI smoke test, usable with offscreen Qt or a virtual X11 display."""
2
+
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import platform
7
+ import time
8
+ import uuid
9
+
10
+ from PySide6.QtWidgets import QApplication
11
+
12
+ from multipolepdm.gui.window import MainWindow
13
+ from multipolepdm.plotting.export import save_overview, save_panel
14
+
15
+
16
+ def run_self_test(report_path):
17
+ report_path = Path(report_path).resolve()
18
+ report_path.parent.mkdir(parents=True, exist_ok=True)
19
+ artifacts = report_path.parent / (report_path.stem + "-" + uuid.uuid4().hex[:8])
20
+ artifacts.mkdir()
21
+ report = {
22
+ "kind": "real Qt packaged smoke test",
23
+ "system": platform.system(),
24
+ "platform_plugin": os.environ.get("QT_QPA_PLATFORM", "platform default"),
25
+ "native_windows_macos_tested": False,
26
+ "status": "running",
27
+ "cases": [],
28
+ }
29
+ app = QApplication.instance() or QApplication([])
30
+ window = MainWindow()
31
+ window.show()
32
+ try:
33
+ window.file_mode.setChecked(True)
34
+ assert not window.manual.isEnabled()
35
+ window.file_mode.setChecked(False)
36
+ for mode in ("P_ADO", "P_DCO", "PDCO"):
37
+ window.mode.setCurrentText(mode)
38
+ window.load_example()
39
+ window.fields["xi_points"].setValue(301)
40
+ window.fields["sigma_points"].setValue(81)
41
+ window.output_path.setText(str(artifacts / "data"))
42
+ window.calculate_button.click()
43
+ assert window.manual.isEnabled()
44
+ identifier = list(window.manager.handles)[-1]
45
+ deadline = time.monotonic() + 120
46
+ while time.monotonic() < deadline:
47
+ app.processEvents()
48
+ state = window.manager.handles[identifier].state
49
+ if state in ("calculation_failed", "save_failed", "cancelled"):
50
+ raise RuntimeError(f"{mode}: {state}")
51
+ if state == "saved" and identifier in window.result_windows:
52
+ break
53
+ time.sleep(0.01)
54
+ else:
55
+ raise RuntimeError(f"{mode}: smoke-test timeout")
56
+ result_window = window.result_windows[identifier]
57
+ assert len(result_window.preview.axes) == 4
58
+ result_window.grab().save(str(artifacts / f"{mode}-results.png"))
59
+ window.grab().save(str(artifacts / f"{mode}-inputs.png"))
60
+ save_overview(
61
+ result_window.result, result_window.summary, artifacts / f"{mode}.pdf"
62
+ )
63
+ for panel in "abcd":
64
+ save_panel(
65
+ result_window.result,
66
+ result_window.summary,
67
+ panel,
68
+ artifacts / f"{mode}-{panel}.svg",
69
+ )
70
+ report["cases"].append(
71
+ {
72
+ "mode": mode,
73
+ "status": state,
74
+ "directory": str(window.manager.handles[identifier].directory),
75
+ "four_panels": True,
76
+ "manual_editor_enabled": True,
77
+ }
78
+ )
79
+ report["status"] = "passed"
80
+ except Exception as exc:
81
+ report["status"] = "failed"
82
+ report["error"] = str(exc)
83
+ finally:
84
+ window.manager.shutdown(wait=True, cancel=True)
85
+ window.close()
86
+ app.processEvents()
87
+ report["artifacts"] = str(artifacts)
88
+ report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
89
+ return 0 if report["status"] == "passed" else 1