Files
BD_Fresnel_GUI/set_params_dialog.py
T
2026-09-23 01:16:19 +00:00

192 lines
7.6 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# BD Fresnel - mechanism parameter dialog
#
# Copyright (C) 2019-2026 Manuel R. Ferdinandus
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
set_params_dialog.py
=====================
Tkinter port of set_params_GUI.m / set_params_GUI.fig -- a small modal
dialog for entering the numeric parameters of whichever mechanism is
currently selected in one of the seven mechanism slots of the main
BD_Fresnel_GUI window.
Behavior matched against the original:
* The dialog's title and header both read "<mechanism name>
parameters", exactly as MATLAB's `st_mechanism_parameters` label.
* Only as many parameter rows are shown as that mechanism actually
uses (0 for "None (both)" up to 10 for the ESA/triplet mechanism);
the rest are hidden entirely, matching the original's
show/hide-unused-input-boxes logic.
* If you re-open the dialog for the SAME mechanism it was last set
to, the previously entered values are restored. If you've changed
mechanisms, all fields reset to 0 -- matching set_params_GUI's
"restore previous settings if required" check.
* Each field is validated as a real number on edit; an invalid
entry is rejected (reverted to its last valid value) with a
message printed to the console, mirroring the original's
str2double() validation and disp() logging.
One intentional behavior change from the original: MATLAB's dialog had
no Cancel button and no handled window-close action (only the OK
button called uiresume), so closing it via the window's [X] button
would leave the caller's uiwait() blocked forever. Here, closing the
window via [X] is treated the same as pressing OK (whatever is
currently entered is accepted) rather than hanging the application --
a deliberate usability improvement, not a fidelity gap in the physics.
Usage:
from set_params_dialog import open_set_params_dialog
new_mechanism = open_set_params_dialog(parent, "Collisional (NLR)",
previous_mechanism=old_mech)
"""
import math
import tkinter as tk
from tkinter import ttk
from bd_fresnel_core import Mechanism, MECHANISM_PARAM_SPECS
class SetParamsDialog(tk.Toplevel):
def __init__(self, parent, mechanism_name: str, previous_mechanism: Mechanism = None):
super().__init__(parent)
self.mechanism_name = mechanism_name
self.result: Mechanism = None
self.title(f"{mechanism_name} parameters")
self.resizable(False, False)
specs = MECHANISM_PARAM_SPECS.get(mechanism_name, [])
# Restore previous values only if this is the same mechanism
# as before; otherwise every field starts at 0 -- matches
# set_params_GUI_OpeningFcn's restore-if-same-mechanism check.
if previous_mechanism is not None and previous_mechanism.name == mechanism_name:
prev_values = list(previous_mechanism.param)
else:
prev_values = []
prev_values = (prev_values + [0.0] * 10)[:10]
header = ttk.Label(self, text=f"{mechanism_name} parameters",
font=("TkDefaultFont", 10, "bold"))
header.grid(row=0, column=0, columnspan=2, padx=10, pady=(10, 6), sticky="w")
self._vars = []
self._entries = []
self._last_valid = list(prev_values)
row = 1
for i in range(10):
if i < len(specs):
name, units = specs[i]
ttk.Label(self, text=f"{name} ({units})", width=22, anchor="w").grid(
row=row, column=0, padx=(10, 4), pady=3, sticky="w"
)
var = tk.StringVar(value=self._format(prev_values[i]))
entry = ttk.Entry(self, textvariable=var, width=14, justify="right")
entry.grid(row=row, column=1, padx=(0, 10), pady=3, sticky="e")
entry.bind("<FocusOut>", lambda e, idx=i: self._validate(idx))
entry.bind("<Return>", lambda e, idx=i: self._validate(idx))
self._vars.append(var)
self._entries.append(entry)
row += 1
else:
self._vars.append(None)
self._entries.append(None)
button_row = ttk.Frame(self)
button_row.grid(row=row, column=0, columnspan=2, pady=(8, 10))
ttk.Button(button_row, text="OK", command=self._on_ok, width=10).pack()
self.protocol("WM_DELETE_WINDOW", self._on_ok)
self.transient(parent)
self.grab_set()
if self._entries and self._entries[0] is not None:
self.after(10, self._entries[0].focus_set)
@staticmethod
def _parse(text: str) -> float:
"""float(), but rejecting what it accepts and no parameter can
take: "nan", "inf", and overflows such as "1e999". Letting those
through also crashed _format, which calls int() on the value."""
value = float(text)
if not math.isfinite(value):
raise ValueError(f"{text!r} is not finite")
return value
@staticmethod
def _format(value: float) -> str:
# MATLAB's num2str-equivalent-enough default formatting.
if value == int(value):
return str(int(value))
return repr(float(value))
def _validate(self, idx):
var = self._vars[idx]
if var is None:
return
try:
value = self._parse(var.get())
except ValueError:
name = MECHANISM_PARAM_SPECS[self.mechanism_name][idx][0]
print(f"set_params_dialog: '{name}' must be a finite real number; reverting.")
value = self._last_valid[idx]
self._last_valid[idx] = value
var.set(self._format(value))
def _on_ok(self):
values = [0.0] * 10
for i, var in enumerate(self._vars):
if var is None:
continue
try:
values[i] = self._parse(var.get())
except ValueError:
values[i] = self._last_valid[i]
self.result = Mechanism(name=self.mechanism_name, param=values)
self.grab_release()
self.destroy()
def open_set_params_dialog(parent, mechanism_name: str,
previous_mechanism: Mechanism = None) -> Mechanism:
"""Opens the dialog modally (blocks the caller until it's closed)
and returns the resulting Mechanism."""
dialog = SetParamsDialog(parent, mechanism_name, previous_mechanism)
parent.wait_window(dialog)
return dialog.result
if __name__ == "__main__":
# Small standalone demo/harness.
root = tk.Tk()
root.title("set_params_dialog demo")
result_var = tk.StringVar(value="(no result yet)")
ttk.Label(root, textvariable=result_var, padding=20).pack()
last_mech = [Mechanism(name="Collisional (NLR)", param=[5, 100, 500] + [0] * 7)]
def launch():
mech = open_set_params_dialog(root, "Collisional (NLR)", last_mech[0])
last_mech[0] = mech
result_var.set(f"name={mech.name!r} param={mech.param}")
ttk.Button(root, text="Open Collisional (NLR) params...", command=launch).pack(pady=10)
root.mainloop()