Coverage for graphica/gui/dialogs/analysis.py: 75.8%

887 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-25 19:22 +0000

1"""解析のダイアログ。呼び出し側は `from graphica.gui.dialogs import X` で参照する。""" 

2 

3import logging 

4 

5import numpy as np 

6from PySide6.QtWidgets import ( 

7 QApplication, 

8 QCheckBox, 

9 QComboBox, 

10 QDialog, 

11 QDialogButtonBox, 

12 QDoubleSpinBox, 

13 QFormLayout, 

14 QHBoxLayout, 

15 QLabel, 

16 QLineEdit, 

17 QPlainTextEdit, 

18 QPushButton, 

19 QSpinBox, 

20 QStackedWidget, 

21 QTableWidget, 

22 QTableWidgetItem, 

23 QVBoxLayout, 

24 QWidget, 

25) 

26from PySide6.QtCore import QTimer, Qt 

27from PySide6.QtGui import QFont 

28from graphica.gui import notify 

29from graphica.gui import dialog_dirs 

30from graphica.gui.theme import apply_form_spacing 

31 

32logger = logging.getLogger(__name__) 

33 

34 

35class FitDialog(QDialog): 

36 """フィットのモデルと条件を選ぶ。""" 

37 

38 def __init__(self, parent=None, x_min=None, x_max=None): 

39 """x_min / x_max はフィット範囲の欄の初期値(ふつうはデータの X の範囲)。""" 

40 super().__init__(parent) 

41 self.setWindowTitle("曲線フィット") 

42 

43 layout = QVBoxLayout(self) 

44 

45 layout.addWidget(QLabel("フィットする関数の種類を選択してください:")) 

46 

47 self.fit_type_combo = QComboBox() 

48 # scipy を読み込むので、ダイアログを開くときまで遅らせる 

49 from graphica.core.analysis import get_plugin_fit_type_names 

50 from graphica.core.fit_models import CUSTOM_FORMULA_LABEL, builtin_menu_labels 

51 # プラグインのフィット関数は、組み込みと「カスタム数式...」の間に入れる 

52 self.fit_type_combo.addItems(builtin_menu_labels()) 

53 self.fit_type_combo.addItems(get_plugin_fit_type_names()) 

54 self.fit_type_combo.addItem(CUSTOM_FORMULA_LABEL) 

55 self.fit_type_combo.currentTextChanged.connect(self._on_fit_type_changed) 

56 layout.addWidget(self.fit_type_combo) 

57 

58 self.custom_formula_label = QLabel("数式 (xとパラメータ名を使って入力、例: a*exp(-b*x)+c)") 

59 self.custom_formula_edit = QLineEdit() 

60 self.custom_formula_edit.setPlaceholderText("a*exp(-b*x)+c") 

61 self.custom_formula_label.setVisible(False) 

62 self.custom_formula_edit.setVisible(False) 

63 layout.addWidget(self.custom_formula_label) 

64 layout.addWidget(self.custom_formula_edit) 

65 

66 self.weighted_checkbox = QCheckBox("Y誤差列を重みとして使用する(設定されている場合)") 

67 self.weighted_checkbox.setToolTip( 

68 "誤差が大きい点ほどフィットへの影響を小さくする(scipy.optimize.curve_fitのsigma)。\n" 

69 "対象データセットにY誤差列が設定されていない場合はチェックしても効果がありません。" 

70 ) 

71 layout.addWidget(self.weighted_checkbox) 

72 

73 loss_form = QFormLayout() 

74 self.loss_combo = QComboBox() 

75 self.loss_combo.addItem("通常の最小二乗(既定)", "linear") 

76 self.loss_combo.addItem("ロバスト(Soft L1)", "soft_l1") 

77 self.loss_combo.addItem("ロバスト(Huber)", "huber") 

78 self.loss_combo.setToolTip( 

79 "外れ値に引きずられにくい損失関数に切り替える(scipy.optimize.least_squares)。\n" 

80 "Soft L1/Huberはいずれも外れ値の寄与を線形二乗より抑える点で似ているが、\n" 

81 "Huberの方が正常値付近では通常の最小二乗に近い挙動になる。" 

82 ) 

83 loss_form.addRow("損失関数", self.loss_combo) 

84 layout.addLayout(loss_form) 

85 

86 self.range_checkbox = QCheckBox("フィット範囲を指定する") 

87 layout.addWidget(self.range_checkbox) 

88 

89 range_form = QFormLayout() 

90 self.range_min_spinbox = QDoubleSpinBox() 

91 self.range_min_spinbox.setRange(-1e12, 1e12) 

92 self.range_min_spinbox.setDecimals(6) 

93 self.range_min_spinbox.setEnabled(False) 

94 if x_min is not None: 

95 self.range_min_spinbox.setValue(x_min) 

96 range_form.addRow("最小X", self.range_min_spinbox) 

97 

98 self.range_max_spinbox = QDoubleSpinBox() 

99 self.range_max_spinbox.setRange(-1e12, 1e12) 

100 self.range_max_spinbox.setDecimals(6) 

101 self.range_max_spinbox.setEnabled(False) 

102 if x_max is not None: 

103 self.range_max_spinbox.setValue(x_max) 

104 range_form.addRow("最大X", self.range_max_spinbox) 

105 layout.addLayout(range_form) 

106 

107 self.range_checkbox.toggled.connect(self.range_min_spinbox.setEnabled) 

108 self.range_checkbox.toggled.connect(self.range_max_spinbox.setEnabled) 

109 

110 layout.addWidget(QLabel("パラメータごとの初期値・固定・範囲拘束(収束しない場合に指定してください):")) 

111 self.param_table = QTableWidget(0, 6) 

112 self.param_table.setHorizontalHeaderLabels( 

113 ["パラメータ", "初期値/固定値", "固定", "範囲拘束", "最小", "最大"] 

114 ) 

115 self.param_table.verticalHeader().setVisible(False) 

116 self.param_table.setMaximumHeight(180) 

117 layout.addWidget(self.param_table) 

118 

119 self.fit_type_combo.currentTextChanged.connect(self._rebuild_param_table) 

120 # 入力途中でもパラメータの数が変わるので、1文字ごとに作り直す(解釈できなければ0行になるだけ) 

121 self.custom_formula_edit.textChanged.connect(self._rebuild_param_table) 

122 

123 band_form = QFormLayout() 

124 self.band_combo = QComboBox() 

125 self.band_combo.addItems(["表示しない", "信頼帯 (95%)", "予測帯 (95%)"]) 

126 self.band_combo.setToolTip( 

127 "信頼帯: 真の回帰曲線が収まると考えられる範囲(パラメータの不確かさのみ)。\n" 

128 "予測帯: 次に測定する新しい1点が収まると考えられる範囲\n" 

129 "(パラメータの不確かさに加え、観測ノイズの分散も加味するため信頼帯より広くなる)。" 

130 ) 

131 band_form.addRow("信頼帯/予測帯", self.band_combo) 

132 layout.addLayout(band_form) 

133 

134 button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | 

135 QDialogButtonBox.StandardButton.Cancel) 

136 button_box.accepted.connect(self.accept) 

137 button_box.rejected.connect(self.reject) 

138 layout.addWidget(button_box) 

139 

140 self._rebuild_param_table() 

141 

142 def _on_fit_type_changed(self, text): 

143 from graphica.core.fit_models import is_custom_formula_type 

144 is_custom = is_custom_formula_type(text) 

145 self.custom_formula_label.setVisible(is_custom) 

146 self.custom_formula_edit.setVisible(is_custom) 

147 

148 def _rebuild_param_table(self, *_args): 

149 """フィットの種類か数式が変わるたびにパラメータの行を作り直す。まだ決まらない間は0行。 

150 

151 値の欄は、「固定」が外れていれば初期値(触った行だけ p0_overrides に入る)、入っていれば固定値。 

152 固定したパラメータには範囲拘束を付けられない。 

153 """ 

154 from graphica.core.fit_models import is_custom_formula_type 

155 fit_type = self.fit_type_combo.currentText() 

156 custom_formula = self.custom_formula_edit.text().strip() if is_custom_formula_type(fit_type) else None 

157 try: 

158 from graphica.core.analysis import get_fit_param_names 

159 param_names = get_fit_param_names(fit_type, custom_formula) 

160 except ValueError: 

161 param_names = [] 

162 

163 self.param_table.setRowCount(0) 

164 self.param_table.setRowCount(len(param_names)) 

165 for row, name in enumerate(param_names): 

166 name_item = QTableWidgetItem(name) 

167 name_item.setFlags(name_item.flags() & ~Qt.ItemFlag.ItemIsEditable) 

168 self.param_table.setItem(row, 0, name_item) 

169 

170 value_spin = QDoubleSpinBox() 

171 value_spin.setRange(-1e12, 1e12) 

172 value_spin.setDecimals(6) 

173 value_spin.blockSignals(True) 

174 value_spin.setValue(1.0) 

175 value_spin.blockSignals(False) 

176 # 触った行だけ初期値を上書きする(触らなければ種類ごとの自動推定のまま)。 

177 # 自動推定の値はデータが要るので、このダイアログでは出せない 

178 value_spin.setProperty("_user_overridden", False) 

179 value_spin.valueChanged.connect( 

180 lambda _v, w=value_spin: w.setProperty("_user_overridden", True) 

181 ) 

182 self.param_table.setCellWidget(row, 1, value_spin) 

183 

184 fixed_check = QCheckBox() 

185 self.param_table.setCellWidget(row, 2, fixed_check) 

186 

187 range_check = QCheckBox() 

188 self.param_table.setCellWidget(row, 3, range_check) 

189 

190 min_spin = QDoubleSpinBox() 

191 min_spin.setRange(-1e12, 1e12) 

192 min_spin.setDecimals(6) 

193 min_spin.setValue(-1e12) 

194 min_spin.setEnabled(False) 

195 self.param_table.setCellWidget(row, 4, min_spin) 

196 

197 max_spin = QDoubleSpinBox() 

198 max_spin.setRange(-1e12, 1e12) 

199 max_spin.setDecimals(6) 

200 max_spin.setValue(1e12) 

201 max_spin.setEnabled(False) 

202 self.param_table.setCellWidget(row, 5, max_spin) 

203 

204 fixed_check.toggled.connect( 

205 lambda checked, rc=range_check, mn=min_spin, mx=max_spin: 

206 self._on_param_fixed_toggled(checked, rc, mn, mx) 

207 ) 

208 range_check.toggled.connect( 

209 lambda checked, mn=min_spin, mx=max_spin: (mn.setEnabled(checked), mx.setEnabled(checked)) 

210 ) 

211 

212 self.param_table.resizeColumnsToContents() 

213 

214 @staticmethod 

215 def _on_param_fixed_toggled(checked, range_check, min_spin, max_spin): 

216 """固定したパラメータは最適化されないので、範囲拘束の欄を無効にする。""" 

217 range_check.setEnabled(not checked) 

218 min_spin.setEnabled((not checked) and range_check.isChecked()) 

219 max_spin.setEnabled((not checked) and range_check.isChecked()) 

220 

221 def get_param_settings(self): 

222 """calculate_curve_fit() に渡す (p0_overrides, fixed_params, bounds)。何も変えなければ空の dict。""" 

223 p0_overrides, fixed_params, bounds = {}, {}, {} 

224 for row in range(self.param_table.rowCount()): 

225 name = self.param_table.item(row, 0).text() 

226 value_spin = self.param_table.cellWidget(row, 1) 

227 fixed_check = self.param_table.cellWidget(row, 2) 

228 range_check = self.param_table.cellWidget(row, 3) 

229 min_spin = self.param_table.cellWidget(row, 4) 

230 max_spin = self.param_table.cellWidget(row, 5) 

231 

232 if fixed_check.isChecked(): 

233 fixed_params[name] = value_spin.value() 

234 continue 

235 

236 if value_spin.property("_user_overridden"): 

237 p0_overrides[name] = value_spin.value() 

238 

239 if range_check.isChecked(): 

240 bounds[name] = (min_spin.value(), max_spin.value()) 

241 

242 return p0_overrides, fixed_params, bounds 

243 

244 def get_band_type(self): 

245 """"confidence" / "prediction" / None(表示しない)。""" 

246 text = self.band_combo.currentText() 

247 if "信頼帯" in text: 247 ↛ 248line 247 didn't jump to line 248 because the condition on line 247 was never true

248 return "confidence" 

249 if "予測帯" in text: 

250 return "prediction" 

251 return None 

252 

253 def get_weighted(self): 

254 return self.weighted_checkbox.isChecked() 

255 

256 def get_loss(self): 

257 """'linear' / 'soft_l1' / 'huber'。""" 

258 return self.loss_combo.currentData() 

259 

260 def get_x_range(self): 

261 """指定があれば (最小X, 最大X)、無ければ None。""" 

262 if not self.range_checkbox.isChecked(): 

263 return None 

264 return (self.range_min_spinbox.value(), self.range_max_spinbox.value()) 

265 

266 @staticmethod 

267 def get_fit_type(parent=None, x_min=None, x_max=None): 

268 """OK なら (種類, 数式, 重み付け, 範囲, p0_overrides, fixed_params, bounds, band_type, loss)。 

269 

270 キャンセルなら (None, None, False, None, {}, {}, {}, None, 'linear')。 

271 """ 

272 dialog = FitDialog(parent, x_min=x_min, x_max=x_max) 

273 if dialog.exec() == QDialog.DialogCode.Accepted: 

274 from graphica.core.fit_models import is_custom_formula_type 

275 fit_type = dialog.fit_type_combo.currentText() 

276 custom_formula = dialog.custom_formula_edit.text().strip() if is_custom_formula_type(fit_type) else None 

277 p0_overrides, fixed_params, bounds = dialog.get_param_settings() 

278 return (fit_type, custom_formula, dialog.get_weighted(), dialog.get_x_range(), 

279 p0_overrides, fixed_params, bounds, dialog.get_band_type(), dialog.get_loss()) 

280 return None, None, False, None, {}, {}, {}, None, 'linear' 

281 

282 

283class MultiPeakFitDialog(QDialog): 

284 """多峰分離の設定。各ピークの初期値の行は、手で、ピーク検出から、またはキャンバスのクリックで入れる。""" 

285 

286 COMPONENT_TYPES = [ 

287 ('gaussian', 'ガウシアン'), 

288 ('lorentzian', 'ローレンツ'), 

289 ('pseudo_voigt', '擬似フォークト'), 

290 ('voigt', 'フォークト'), 

291 ] 

292 BASELINE_TYPES = [ 

293 ('none', 'なし'), 

294 ('constant', '定数'), 

295 ('linear', '1次'), 

296 ] 

297 

298 def __init__(self, parent=None, x_data=None, y_data=None, initial_guesses=None): 

299 """x_data / y_data が無ければ「ピーク検出から自動配置」を無効にする。initial_guesses はクリックで集めた初期値。""" 

300 super().__init__(parent) 

301 self.setWindowTitle("多峰分離フィット") 

302 self._x_data = x_data 

303 self._y_data = y_data 

304 

305 layout = QVBoxLayout(self) 

306 

307 form = QFormLayout() 

308 self.component_combo = QComboBox() 

309 for key, label in self.COMPONENT_TYPES: 

310 self.component_combo.addItem(label, key) 

311 form.addRow("成分タイプ(全ピーク共通)", self.component_combo) 

312 

313 self.baseline_combo = QComboBox() 

314 for key, label in self.BASELINE_TYPES: 

315 self.baseline_combo.addItem(label, key) 

316 self.baseline_combo.setCurrentIndex(1) # 定数 

317 form.addRow("ベースライン", self.baseline_combo) 

318 layout.addLayout(form) 

319 

320 layout.addWidget(QLabel( 

321 "各ピークの初期値(中心X・高さ・おおよその幅[FWHM]):" 

322 )) 

323 self.guess_table = QTableWidget(0, 3) 

324 self.guess_table.setHorizontalHeaderLabels(["中心 (X)", "高さ", "幅 (FWHM)"]) 

325 self.guess_table.verticalHeader().setVisible(False) 

326 self.guess_table.setMaximumHeight(200) 

327 layout.addWidget(self.guess_table) 

328 

329 row_button_layout = QHBoxLayout() 

330 add_row_button = QPushButton("行を追加") 

331 add_row_button.clicked.connect(lambda: self._add_guess_row()) 

332 remove_row_button = QPushButton("選択行を削除") 

333 remove_row_button.clicked.connect(self._remove_selected_rows) 

334 self.auto_detect_button = QPushButton("ピーク検出から自動配置...") 

335 self.auto_detect_button.clicked.connect(self._on_auto_detect) 

336 self.auto_detect_button.setEnabled(x_data is not None and y_data is not None) 

337 row_button_layout.addWidget(add_row_button) 

338 row_button_layout.addWidget(remove_row_button) 

339 row_button_layout.addWidget(self.auto_detect_button) 

340 row_button_layout.addStretch() 

341 layout.addLayout(row_button_layout) 

342 

343 for guess in (initial_guesses or []): 

344 self._add_guess_row( 

345 center=guess.get('center', 0.0), 

346 height=guess.get('height', 0.0), 

347 width=guess.get('width', 1.0), 

348 ) 

349 

350 button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | 

351 QDialogButtonBox.StandardButton.Cancel) 

352 button_box.accepted.connect(self._on_accept) 

353 button_box.rejected.connect(self.reject) 

354 layout.addWidget(button_box) 

355 

356 def _add_guess_row(self, center=0.0, height=0.0, width=1.0): 

357 row = self.guess_table.rowCount() 

358 self.guess_table.insertRow(row) 

359 for col, value in enumerate((center, height, width)): 

360 spin = QDoubleSpinBox() 

361 spin.setRange(-1e12, 1e12) 

362 spin.setDecimals(6) 

363 spin.setValue(float(value)) 

364 self.guess_table.setCellWidget(row, col, spin) 

365 

366 def _remove_selected_rows(self): 

367 rows = sorted({idx.row() for idx in self.guess_table.selectedIndexes()}, reverse=True) 

368 for row in rows: 

369 self.guess_table.removeRow(row) 

370 

371 def _on_auto_detect(self): 

372 """ピーク検出の結果(中心・高さ・FWHM)を行に足す。既にある行は消さない(クリックでの配置と併用できる)。""" 

373 settings = PeakSettingsDialog.get_peak_settings(self) 

374 if settings is None: 

375 return 

376 from graphica.core.analysis import calculate_peak_quantification 

377 try: 

378 result = calculate_peak_quantification( 

379 self._x_data, self._y_data, settings['peak_type'], settings 

380 ) 

381 except Exception as e: 

382 logger.exception("ピークの自動検出に失敗しました") 

383 notify.warning(self, "ピーク検出", f"ピーク検出に失敗しました:\n{e}") 

384 return 

385 if len(result['peak_x']) == 0: 

386 notify.information(self, "ピーク検出", "条件に一致するピークが見つかりませんでした。") 

387 return 

388 for x, y, fwhm in zip(result['peak_x'], result['peak_y'], result['fwhm']): 

389 self._add_guess_row(center=float(x), height=float(y), width=float(fwhm) or 1.0) 

390 

391 def _on_accept(self): 

392 if self.guess_table.rowCount() == 0: 

393 notify.warning(self, "多峰分離フィット", "少なくとも1つのピークの初期値が必要です。") 

394 return 

395 self.accept() 

396 

397 def get_component_type(self): 

398 return self.component_combo.currentData() 

399 

400 def get_baseline_type(self): 

401 return self.baseline_combo.currentData() 

402 

403 def get_initial_guesses(self): 

404 """calculate_multi_peak_fit() に渡す [{'center', 'height', 'width'}, ...]。""" 

405 guesses = [] 

406 for row in range(self.guess_table.rowCount()): 

407 center = self.guess_table.cellWidget(row, 0).value() 

408 height = self.guess_table.cellWidget(row, 1).value() 

409 width = self.guess_table.cellWidget(row, 2).value() 

410 guesses.append({'center': center, 'height': height, 'width': width}) 

411 return guesses 

412 

413 @staticmethod 

414 def get_multi_peak_fit_settings(parent=None, x_data=None, y_data=None, initial_guesses=None): 

415 """OK なら (component_type, baseline_type, initial_guesses)、キャンセルなら (None, None, None)。""" 

416 dialog = MultiPeakFitDialog(parent, x_data=x_data, y_data=y_data, initial_guesses=initial_guesses) 

417 if dialog.exec() == QDialog.DialogCode.Accepted: 

418 return dialog.get_component_type(), dialog.get_baseline_type(), dialog.get_initial_guesses() 

419 return None, None, None 

420 

421 

422class PeakSettingsDialog(QDialog): 

423 """ピーク/谷検出(scipy.signal.find_peaks)の height・distance・prominence を入力する。""" 

424 

425 # height の最小値を「なし」(高さで絞らない)として表示する。 

426 _HEIGHT_NONE = -1e12 

427 

428 def __init__(self, parent=None): 

429 super().__init__(parent) 

430 self.setWindowTitle("ピーク検出 設定") 

431 layout = QFormLayout(self) 

432 

433 self.type_combo = QComboBox() 

434 self.type_combo.addItems(["上に凸 (Peaks)", "下に凸 (Valleys)"]) 

435 layout.addRow("検出タイプ", self.type_combo) 

436 

437 # 既定を 0 にすると、Y<0 の山や Y>0 の谷が1つも見つからない。 

438 self.height_spinbox = QDoubleSpinBox() 

439 self.height_spinbox.setToolTip("検出するピーク/谷の最小高さ (Y値)。「なし」は高さで絞らない。\n例: 5 を指定すると Y > 5 のピークのみ検出。\n例: -10 を指定すると Y < -10 の谷のみ検出。") 

440 self.height_spinbox.setDecimals(4) 

441 self.height_spinbox.setRange(self._HEIGHT_NONE, 1e12) 

442 self.height_spinbox.setSpecialValueText("なし") 

443 self.height_spinbox.setValue(self._HEIGHT_NONE) 

444 

445 self.distance_spinbox = QDoubleSpinBox() 

446 self.distance_spinbox.setToolTip("隣接するピーク/谷の間の最小距離 (X軸の値)。\n近すぎるピーク/谷を間引きます。") 

447 self.distance_spinbox.setDecimals(4) 

448 self.distance_spinbox.setRange(0.0001, np.inf) 

449 self.distance_spinbox.setValue(1.0) 

450 

451 self.prominence_spinbox = QDoubleSpinBox() 

452 self.prominence_spinbox.setToolTip("ピーク/谷の突出度 (周囲のデータからの際立ち)。\nノイズのような小さなピーク/谷を除去するのに有効です。") 

453 self.prominence_spinbox.setDecimals(4) 

454 self.prominence_spinbox.setRange(0.0, np.inf) 

455 self.prominence_spinbox.setValue(0.0) 

456 

457 layout.addRow("Y値の閾値 (Height)", self.height_spinbox) 

458 layout.addRow("最小X距離 (Distance)", self.distance_spinbox) 

459 layout.addRow("最小突出度 (Prominence)", self.prominence_spinbox) 

460 

461 button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | 

462 QDialogButtonBox.StandardButton.Cancel) 

463 button_box.accepted.connect(self.accept) 

464 button_box.rejected.connect(self.reject) 

465 layout.addRow(button_box) 

466 

467 apply_form_spacing(self) 

468 

469 def get_settings(self): 

470 """distance_x は X の値のまま(点の数への換算は core.analysis)。height と prominence は無効なら None。""" 

471 height = self.height_spinbox.value() 

472 prominence = self.prominence_spinbox.value() 

473 return { 

474 "peak_type": self.type_combo.currentText(), 

475 "height": None if height == self._HEIGHT_NONE else height, 

476 "distance_x": self.distance_spinbox.value(), 

477 "prominence": prominence if prominence > 0 else None, 

478 } 

479 

480 @staticmethod 

481 def get_peak_settings(parent=None): 

482 """モーダルで開き、OK なら設定の辞書、キャンセルなら None を返す。""" 

483 dialog = PeakSettingsDialog(parent) 

484 if dialog.exec() == QDialog.DialogCode.Accepted: 

485 return dialog.get_settings() 

486 return None 

487 

488 

489class ResultDialog(QDialog): 

490 """結果の文章をスクロールできる欄で見せる(ピークが多いと QMessageBox は画面からはみ出す)。""" 

491 

492 def __init__(self, title, text, parent=None, csv_data=None, residual_x=None, residual_y=None): 

493 """csv_data を渡すと「CSVとして保存」を出す。residual_x と residual_y を両方渡すと残差の図も出す。""" 

494 super().__init__(parent) 

495 self.setWindowTitle(title) 

496 self.resize(480, 420) 

497 self.csv_data = csv_data 

498 

499 layout = QVBoxLayout(self) 

500 

501 self.text_edit = QPlainTextEdit() 

502 self.text_edit.setReadOnly(True) 

503 self.text_edit.setPlainText(text) 

504 # タブ区切りの桁が揃う 

505 mono_font = QFont("Consolas") 

506 mono_font.setStyleHint(QFont.StyleHint.Monospace) 

507 self.text_edit.setFont(mono_font) 

508 layout.addWidget(self.text_edit) 

509 

510 if residual_x is not None and residual_y is not None and len(residual_x) > 0: 

511 self.resize(480, 620) 

512 layout.addWidget(QLabel("残差プロット (実測値 - フィット値)")) 

513 from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg 

514 from matplotlib.figure import Figure 

515 from graphica.gui import theme 

516 # 独立した Figure なのでキャンバスのダークモードの配色を継承しない。テーマの色を当てる 

517 _tokens = theme.current_tokens() 

518 fig = Figure(figsize=(4, 2.2), dpi=100, tight_layout=True, 

519 facecolor=_tokens['surface']) 

520 canvas = FigureCanvasQTAgg(fig) 

521 canvas.setFixedHeight(200) 

522 ax = fig.add_subplot(111) 

523 ax.set_facecolor(_tokens['surface']) 

524 ax.axhline(0, color=_tokens['border_strong'], linewidth=0.8, linestyle='--') 

525 ax.scatter(residual_x, residual_y, s=14, color='#1F6F78') 

526 ax.set_xlabel("X", fontsize=8, color=_tokens['text_primary']) 

527 # 日本語の見出しは既定のフォント(DejaVu Sans)では豆腐になる 

528 from graphica.gui.mathtext_preview import JP_CAPABLE_FONT_FAMILIES 

529 ax.set_ylabel("残差", fontsize=8, color=_tokens['text_primary'], fontfamily=JP_CAPABLE_FONT_FAMILIES) 

530 ax.tick_params(labelsize=7, colors=_tokens['text_primary']) 

531 for spine in ax.spines.values(): 

532 spine.set_color(_tokens['border_strong']) 

533 layout.addWidget(canvas) 

534 

535 button_layout = QHBoxLayout() 

536 

537 self.copy_button = QPushButton("コピー") 

538 self.copy_button.clicked.connect(self._on_copy) 

539 button_layout.addWidget(self.copy_button) 

540 

541 if csv_data is not None: 

542 save_csv_button = QPushButton("CSVとして保存...") 

543 save_csv_button.clicked.connect(self._on_save_csv) 

544 button_layout.addWidget(save_csv_button) 

545 

546 button_layout.addStretch() 

547 

548 close_button = QPushButton("閉じる") 

549 close_button.clicked.connect(self.reject) 

550 button_layout.addWidget(close_button) 

551 

552 layout.addLayout(button_layout) 

553 

554 def _on_copy(self): 

555 QApplication.clipboard().setText(self.text_edit.toPlainText()) 

556 original_text = self.copy_button.text() 

557 self.copy_button.setText("コピーしました ✓") 

558 self.copy_button.setEnabled(False) 

559 

560 def _restore(): 

561 self.copy_button.setText(original_text) 

562 self.copy_button.setEnabled(True) 

563 

564 QTimer.singleShot(1200, _restore) 

565 

566 def _on_save_csv(self): 

567 file_path, _ = dialog_dirs.get_save_file_name( 

568 self, dialog_dirs.TABLE, "CSVとして保存", "", "CSV Files (*.csv);;All Files (*)" 

569 ) 

570 if not file_path: 

571 return 

572 try: 

573 self.csv_data.to_csv(file_path, index=False, encoding='utf-8-sig') 

574 notify.information(self, "保存完了", f"CSVファイルとして保存しました:\n{file_path}") 

575 except Exception as e: 

576 logger.exception("結果の CSV 保存に失敗しました") 

577 notify.warning(self, "保存エラー", f"CSV保存中にエラーが発生しました:\n{e}") 

578 

579 

580class BaselineCorrectionDialog(QDialog): 

581 METHOD_ALS = "ALS(Asymmetric Least Squares)" 

582 METHOD_POLYNOMIAL = "多項式(反復フィット)" 

583 METHOD_RUBBERBAND = "ラバーバンド(下側凸包)" 

584 METHOD_MANUAL = "手動点" 

585 METHODS = [METHOD_ALS, METHOD_POLYNOMIAL, METHOD_RUBBERBAND, METHOD_MANUAL] 

586 

587 _MANUAL_LINEAR = "直線" 

588 _MANUAL_SPLINE = "3次スプライン" 

589 

590 def __init__(self, name, x_min=None, x_max=None, parent=None): 

591 super().__init__(parent) 

592 self.setWindowTitle("ベースライン補正") 

593 self.resize(420, 440) 

594 self._name = name 

595 

596 layout = QVBoxLayout(self) 

597 layout.addWidget(QLabel(f"対象: {name}")) 

598 

599 method_form = QFormLayout() 

600 self.method_combo = QComboBox() 

601 self.method_combo.addItems(self.METHODS) 

602 method_form.addRow("手法", self.method_combo) 

603 layout.addLayout(method_form) 

604 

605 self.stack = QStackedWidget() 

606 layout.addWidget(self.stack) 

607 

608 als_page = QWidget() 

609 als_form = QFormLayout(als_page) 

610 self.als_lam_spinbox = QDoubleSpinBox() 

611 self.als_lam_spinbox.setRange(1.0, 1e12) 

612 self.als_lam_spinbox.setDecimals(0) 

613 self.als_lam_spinbox.setValue(1e5) 

614 als_form.addRow("lam(平滑さ)", self.als_lam_spinbox) 

615 self.als_p_spinbox = QDoubleSpinBox() 

616 self.als_p_spinbox.setRange(0.0001, 0.9999) 

617 self.als_p_spinbox.setDecimals(4) 

618 self.als_p_spinbox.setSingleStep(0.001) 

619 self.als_p_spinbox.setValue(0.01) 

620 als_form.addRow("p(非対称重み)", self.als_p_spinbox) 

621 self.als_niter_spinbox = QSpinBox() 

622 self.als_niter_spinbox.setRange(1, 1000) 

623 self.als_niter_spinbox.setValue(10) 

624 als_form.addRow("反復回数", self.als_niter_spinbox) 

625 self.stack.addWidget(als_page) 

626 

627 poly_page = QWidget() 

628 poly_form = QFormLayout(poly_page) 

629 self.poly_degree_spinbox = QSpinBox() 

630 self.poly_degree_spinbox.setRange(0, 10) 

631 self.poly_degree_spinbox.setValue(3) 

632 poly_form.addRow("次数", self.poly_degree_spinbox) 

633 self.poly_iterations_spinbox = QSpinBox() 

634 self.poly_iterations_spinbox.setRange(1, 1000) 

635 self.poly_iterations_spinbox.setValue(10) 

636 poly_form.addRow("反復回数", self.poly_iterations_spinbox) 

637 self.stack.addWidget(poly_page) 

638 

639 rubberband_page = QWidget() 

640 rubberband_layout = QVBoxLayout(rubberband_page) 

641 rubberband_info = QLabel( 

642 "データ点群の下側凸包(convex hull)を結んだ曲線をベースラインとします。" 

643 "設定できるパラメータはありません。" 

644 ) 

645 rubberband_info.setWordWrap(True) 

646 rubberband_layout.addWidget(rubberband_info) 

647 rubberband_layout.addStretch() 

648 self.stack.addWidget(rubberband_page) 

649 

650 manual_page = QWidget() 

651 manual_layout = QVBoxLayout(manual_page) 

652 manual_layout.addWidget(QLabel("アンカー点のX座標をカンマ区切りで入力してください(2点以上):")) 

653 self.manual_anchor_edit = QPlainTextEdit() 

654 self.manual_anchor_edit.setPlaceholderText("例: 0, 20, 50, 80, 100") 

655 if x_min is not None and x_max is not None: 

656 self.manual_anchor_edit.setPlainText(f"{x_min:g}, {x_max:g}") 

657 self.manual_anchor_edit.setMaximumHeight(60) 

658 manual_layout.addWidget(self.manual_anchor_edit) 

659 manual_method_form = QFormLayout() 

660 self.manual_method_combo = QComboBox() 

661 self.manual_method_combo.addItems([self._MANUAL_LINEAR, self._MANUAL_SPLINE]) 

662 manual_method_form.addRow("補間方法", self.manual_method_combo) 

663 manual_layout.addLayout(manual_method_form) 

664 manual_info = QLabel( 

665 "各アンカー点のYは、指定したX位置での実データを線形補間して自動的に求めます" 

666 "(3次スプラインには3点以上必要です)。" 

667 ) 

668 manual_info.setWordWrap(True) 

669 manual_layout.addWidget(manual_info) 

670 manual_layout.addStretch() 

671 self.stack.addWidget(manual_page) 

672 

673 self.method_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) 

674 

675 form = QFormLayout() 

676 self.output_name_edit = QLineEdit(f"{name}_baseline_corrected") 

677 form.addRow("出力データセット名", self.output_name_edit) 

678 layout.addLayout(form) 

679 

680 self.add_baseline_checkbox = QCheckBox("推定したベースライン曲線も別データセットとして追加する") 

681 layout.addWidget(self.add_baseline_checkbox) 

682 

683 button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | 

684 QDialogButtonBox.StandardButton.Cancel) 

685 button_box.accepted.connect(self.accept) 

686 button_box.rejected.connect(self.reject) 

687 layout.addWidget(button_box) 

688 

689 apply_form_spacing(self) 

690 

691 def get_settings(self): 

692 """(手法, 手法の引数, 出力名, ベースラインも追加するか)。 

693 

694 "manual" の引数は anchor_x ではなく未解釈の anchor_x_text(書式の誤りは呼び出し側が知らせる)。 

695 """ 

696 method_text = self.method_combo.currentText() 

697 if method_text == self.METHOD_ALS: 

698 method = "als" 

699 params = { 

700 "lam": self.als_lam_spinbox.value(), 

701 "p": self.als_p_spinbox.value(), 

702 "niter": self.als_niter_spinbox.value(), 

703 } 

704 elif method_text == self.METHOD_POLYNOMIAL: 

705 method = "polynomial" 

706 params = { 

707 "degree": self.poly_degree_spinbox.value(), 

708 "iterations": self.poly_iterations_spinbox.value(), 

709 } 

710 elif method_text == self.METHOD_RUBBERBAND: 

711 method = "rubberband" 

712 params = {} 

713 else: 

714 method = "manual" 

715 params = { 

716 "anchor_x_text": self.manual_anchor_edit.toPlainText(), 

717 "method": "spline" if self.manual_method_combo.currentText() == self._MANUAL_SPLINE else "linear", 

718 } 

719 return method, params, self.output_name_edit.text().strip(), self.add_baseline_checkbox.isChecked() 

720 

721 

722class SavGolDialog(QDialog): 

723 MODE_SMOOTH = "平滑化" 

724 MODE_DERIV1 = "1次微分" 

725 MODE_DERIV2 = "2次微分" 

726 MODES = [MODE_SMOOTH, MODE_DERIV1, MODE_DERIV2] 

727 _DERIV_BY_MODE = {MODE_SMOOTH: 0, MODE_DERIV1: 1, MODE_DERIV2: 2} 

728 _SUFFIX_BY_MODE = {MODE_SMOOTH: "_smoothed", MODE_DERIV1: "_deriv1", MODE_DERIV2: "_deriv2"} 

729 

730 def __init__(self, name, max_window=None, parent=None): 

731 super().__init__(parent) 

732 self.setWindowTitle("Savitzky-Golayフィルタ") 

733 self.resize(380, 260) 

734 self._name = name 

735 

736 layout = QVBoxLayout(self) 

737 layout.addWidget(QLabel(f"対象: {name}")) 

738 

739 form = QFormLayout() 

740 self.mode_combo = QComboBox() 

741 self.mode_combo.addItems(self.MODES) 

742 form.addRow("種類", self.mode_combo) 

743 

744 self.window_spinbox = QSpinBox() 

745 self.window_spinbox.setRange(3, max_window if max_window else 999999) 

746 self.window_spinbox.setSingleStep(2) 

747 self.window_spinbox.setValue(min(5, max_window) if max_window else 5) 

748 form.addRow("窓幅(奇数)", self.window_spinbox) 

749 

750 self.polyorder_spinbox = QSpinBox() 

751 self.polyorder_spinbox.setRange(1, 10) 

752 self.polyorder_spinbox.setValue(2) 

753 form.addRow("多項式の次数", self.polyorder_spinbox) 

754 

755 self.output_name_edit = QLineEdit(f"{name}{self._SUFFIX_BY_MODE[self.MODE_SMOOTH]}") 

756 form.addRow("出力データセット名", self.output_name_edit) 

757 layout.addLayout(form) 

758 

759 self.mode_combo.currentTextChanged.connect(self._on_mode_changed) 

760 

761 info_label = QLabel( 

762 "窓幅は奇数かつ多項式の次数より大きい値を指定してください。\n" 

763 "微分はX軸の間隔が概ね等間隔であることを前提とします。" 

764 ) 

765 info_label.setWordWrap(True) 

766 layout.addWidget(info_label) 

767 

768 button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | 

769 QDialogButtonBox.StandardButton.Cancel) 

770 button_box.accepted.connect(self.accept) 

771 button_box.rejected.connect(self.reject) 

772 layout.addWidget(button_box) 

773 

774 apply_form_spacing(self) 

775 

776 def _on_mode_changed(self, mode): 

777 self.output_name_edit.setText(f"{self._name}{self._SUFFIX_BY_MODE[mode]}") 

778 

779 def get_settings(self): 

780 """(窓幅, 多項式の次数, 微分の階数, 出力名)""" 

781 mode = self.mode_combo.currentText() 

782 return ( 

783 self.window_spinbox.value(), 

784 self.polyorder_spinbox.value(), 

785 self._DERIV_BY_MODE[mode], 

786 self.output_name_edit.text().strip(), 

787 ) 

788 

789 

790class IntervalIntegralDialog(QDialog): 

791 """区間積分の設定。X の範囲はデータの範囲を初期値にする(そのまま OK で全体を積分)。""" 

792 

793 METHOD_TRAPEZOID = "台形則(Trapezoidal)" 

794 METHOD_SIMPSON = "Simpson則" 

795 METHODS = [METHOD_TRAPEZOID, METHOD_SIMPSON] 

796 _METHOD_KEY_BY_LABEL = {METHOD_TRAPEZOID: "trapezoid", METHOD_SIMPSON: "simpson"} 

797 

798 def __init__(self, name, x_min=None, x_max=None, parent=None): 

799 super().__init__(parent) 

800 self.setWindowTitle("区間積分") 

801 self.resize(380, 260) 

802 

803 layout = QVBoxLayout(self) 

804 layout.addWidget(QLabel(f"対象: {name}")) 

805 

806 form = QFormLayout() 

807 self.method_combo = QComboBox() 

808 self.method_combo.addItems(self.METHODS) 

809 form.addRow("積分方法", self.method_combo) 

810 

811 self.range_min_spinbox = QDoubleSpinBox() 

812 self.range_min_spinbox.setRange(-1e12, 1e12) 

813 self.range_min_spinbox.setDecimals(6) 

814 if x_min is not None: 

815 self.range_min_spinbox.setValue(x_min) 

816 form.addRow("最小X", self.range_min_spinbox) 

817 

818 self.range_max_spinbox = QDoubleSpinBox() 

819 self.range_max_spinbox.setRange(-1e12, 1e12) 

820 self.range_max_spinbox.setDecimals(6) 

821 if x_max is not None: 

822 self.range_max_spinbox.setValue(x_max) 

823 form.addRow("最大X", self.range_max_spinbox) 

824 layout.addLayout(form) 

825 

826 self.subtract_baseline_checkbox = QCheckBox( 

827 "ベースラインを差し引く(範囲の両端を結ぶ直線を差し引いてから積分)" 

828 ) 

829 self.subtract_baseline_checkbox.setToolTip( 

830 "積分範囲の両端のY値(実データを線形補間して求めた値)を結ぶ直線を\n" 

831 "ベースラインとしてYから差し引いてから積分します。\n" 

832 "スペクトルのピーク面積など「傾いた背景の上のピーク」を求める用途向けの\n" 

833 "簡易オプションです。ALS等の本格的なベースライン補正を使いたい場合は、\n" 

834 "先に「ベースライン補正...」で補正したデータセットに対してこの機能を\n" 

835 "使ってください。" 

836 ) 

837 layout.addWidget(self.subtract_baseline_checkbox) 

838 

839 info_label = QLabel( 

840 "台形則・Simpson則いずれもデータ点数の偶奇による制約はありません。" 

841 ) 

842 info_label.setWordWrap(True) 

843 layout.addWidget(info_label) 

844 

845 button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | 

846 QDialogButtonBox.StandardButton.Cancel) 

847 button_box.accepted.connect(self.accept) 

848 button_box.rejected.connect(self.reject) 

849 layout.addWidget(button_box) 

850 

851 apply_form_spacing(self) 

852 

853 def get_settings(self): 

854 """(積分の方法, (最小X, 最大X), ベースラインを引くか)""" 

855 method_text = self.method_combo.currentText() 

856 method = self._METHOD_KEY_BY_LABEL[method_text] 

857 x_range = (self.range_min_spinbox.value(), self.range_max_spinbox.value()) 

858 return method, x_range, self.subtract_baseline_checkbox.isChecked() 

859 

860 

861class CumulativeIntegralDialog(QDialog): 

862 METHOD_TRAPEZOID = "台形則(Trapezoidal)" 

863 METHOD_SIMPSON = "Simpson則" 

864 METHODS = [METHOD_TRAPEZOID, METHOD_SIMPSON] 

865 _METHOD_KEY_BY_LABEL = {METHOD_TRAPEZOID: "trapezoid", METHOD_SIMPSON: "simpson"} 

866 

867 def __init__(self, name, parent=None): 

868 super().__init__(parent) 

869 self.setWindowTitle("累積積分") 

870 self.resize(380, 200) 

871 

872 layout = QVBoxLayout(self) 

873 layout.addWidget(QLabel(f"対象: {name}")) 

874 

875 form = QFormLayout() 

876 self.method_combo = QComboBox() 

877 self.method_combo.addItems(self.METHODS) 

878 form.addRow("積分方法", self.method_combo) 

879 

880 self.output_name_edit = QLineEdit(f"{name}_cumsum") 

881 form.addRow("出力データセット名", self.output_name_edit) 

882 layout.addLayout(form) 

883 

884 info_label = QLabel( 

885 "Xの各点までの積分値 ∫[x_min, x_i] y dx を新しいデータセットとして追加します。\n" 

886 "範囲を絞りたい場合は「区間積分」を使ってください。" 

887 ) 

888 info_label.setWordWrap(True) 

889 layout.addWidget(info_label) 

890 

891 button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | 

892 QDialogButtonBox.StandardButton.Cancel) 

893 button_box.accepted.connect(self.accept) 

894 button_box.rejected.connect(self.reject) 

895 layout.addWidget(button_box) 

896 

897 apply_form_spacing(self) 

898 

899 def get_settings(self): 

900 """(積分の方法, 出力名)""" 

901 method_text = self.method_combo.currentText() 

902 method = self._METHOD_KEY_BY_LABEL[method_text] 

903 return method, self.output_name_edit.text().strip() 

904 

905 

906class NormalizeDatasetDialog(QDialog): 

907 """最大値か、指定した X での値を 1.0 にする。""" 

908 

909 MODE_MAX = "最大値基準" 

910 MODE_X_VALUE = "特定X値での強度基準" 

911 MODES = [MODE_MAX, MODE_X_VALUE] 

912 

913 def __init__(self, name, x_min=None, x_max=None, parent=None): 

914 super().__init__(parent) 

915 self.setWindowTitle("規格化(ノーマライズ)") 

916 self.resize(360, 220) 

917 

918 layout = QVBoxLayout(self) 

919 label = QLabel(f"対象: {name}") 

920 layout.addWidget(label) 

921 

922 form = QFormLayout() 

923 self.mode_combo = QComboBox() 

924 self.mode_combo.addItems(self.MODES) 

925 form.addRow("基準", self.mode_combo) 

926 

927 self.reference_x_spinbox = QDoubleSpinBox() 

928 self.reference_x_spinbox.setRange(-1e12, 1e12) 

929 self.reference_x_spinbox.setDecimals(6) 

930 self.reference_x_spinbox.setEnabled(False) 

931 if x_min is not None: 931 ↛ 933line 931 didn't jump to line 933 because the condition on line 931 was always true

932 self.reference_x_spinbox.setValue(x_min) 

933 form.addRow("基準X値", self.reference_x_spinbox) 

934 

935 self.output_name_edit = QLineEdit(f"{name}_normalized") 

936 form.addRow("出力データセット名", self.output_name_edit) 

937 layout.addLayout(form) 

938 

939 self.mode_combo.currentTextChanged.connect( 

940 lambda text: self.reference_x_spinbox.setEnabled(text == self.MODE_X_VALUE) 

941 ) 

942 

943 info_label = QLabel( 

944 "最大値基準: Yの最大値が1.0になるよう規格化します(マスク中の行は除外)。\n" 

945 "特定X値での強度基準: 指定したX値でのYを線形補間し、その値が1.0になるよう規格化します。" 

946 ) 

947 info_label.setWordWrap(True) 

948 layout.addWidget(info_label) 

949 

950 button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | 

951 QDialogButtonBox.StandardButton.Cancel) 

952 button_box.accepted.connect(self.accept) 

953 button_box.rejected.connect(self.reject) 

954 layout.addWidget(button_box) 

955 

956 apply_form_spacing(self) 

957 

958 def get_settings(self): 

959 """(基準の種類, 基準の X(MODE_X_VALUE のときだけ), 出力名)""" 

960 mode = self.mode_combo.currentText() 

961 reference_x = self.reference_x_spinbox.value() if mode == self.MODE_X_VALUE else None 

962 return mode, reference_x, self.output_name_edit.text().strip() 

963 

964 

965class ResampleDatasetDialog(QDialog): 

966 """ほかのデータセットの X か等間隔のグリッドに補間する。""" 

967 

968 SOURCE_DATASET = "他のデータセットのX格子" 

969 SOURCE_LINSPACE = "等間隔グリッド" 

970 SOURCES = [SOURCE_DATASET, SOURCE_LINSPACE] 

971 

972 METHOD_LINEAR = "線形補間" 

973 METHOD_CUBIC = "3次スプライン補間" 

974 METHODS = [METHOD_LINEAR, METHOD_CUBIC] 

975 _METHOD_KEY_BY_LABEL = {METHOD_LINEAR: "linear", METHOD_CUBIC: "cubic"} 

976 

977 def __init__(self, name, other_dataset_names, x_min=None, x_max=None, parent=None): 

978 super().__init__(parent) 

979 self.setWindowTitle("共通X格子へのリサンプリング/補間") 

980 self.resize(420, 380) 

981 self._name = name 

982 

983 layout = QVBoxLayout(self) 

984 layout.addWidget(QLabel(f"対象: {name}")) 

985 

986 source_form = QFormLayout() 

987 self.source_combo = QComboBox() 

988 self.source_combo.addItems(self.SOURCES) 

989 source_form.addRow("リサンプリング先の格子", self.source_combo) 

990 layout.addLayout(source_form) 

991 

992 self.stack = QStackedWidget() 

993 layout.addWidget(self.stack) 

994 

995 dataset_page = QWidget() 

996 dataset_form = QFormLayout(dataset_page) 

997 self.other_dataset_combo = QComboBox() 

998 self.other_dataset_combo.addItems(other_dataset_names) 

999 dataset_form.addRow("データセット", self.other_dataset_combo) 

1000 if not other_dataset_names: 

1001 # ほかにデータセットが無いので、空のまま OK されないよう無効にする 

1002 self.other_dataset_combo.setEnabled(False) 

1003 no_dataset_label = QLabel("(他に読み込まれているデータセットがありません)") 

1004 no_dataset_label.setWordWrap(True) 

1005 dataset_form.addRow(no_dataset_label) 

1006 self.stack.addWidget(dataset_page) 

1007 

1008 linspace_page = QWidget() 

1009 linspace_form = QFormLayout(linspace_page) 

1010 self.linspace_start_spinbox = QDoubleSpinBox() 

1011 self.linspace_start_spinbox.setRange(-1e12, 1e12) 

1012 self.linspace_start_spinbox.setDecimals(6) 

1013 if x_min is not None: 

1014 self.linspace_start_spinbox.setValue(x_min) 

1015 linspace_form.addRow("開始X", self.linspace_start_spinbox) 

1016 

1017 self.linspace_stop_spinbox = QDoubleSpinBox() 

1018 self.linspace_stop_spinbox.setRange(-1e12, 1e12) 

1019 self.linspace_stop_spinbox.setDecimals(6) 

1020 if x_max is not None: 

1021 self.linspace_stop_spinbox.setValue(x_max) 

1022 linspace_form.addRow("終了X", self.linspace_stop_spinbox) 

1023 

1024 self.linspace_num_points_spinbox = QSpinBox() 

1025 self.linspace_num_points_spinbox.setRange(2, 1_000_000) 

1026 self.linspace_num_points_spinbox.setValue(100) 

1027 linspace_form.addRow("点数", self.linspace_num_points_spinbox) 

1028 self.stack.addWidget(linspace_page) 

1029 

1030 self.source_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) 

1031 if not other_dataset_names: 

1032 self.source_combo.setCurrentText(self.SOURCE_LINSPACE) 

1033 

1034 method_form = QFormLayout() 

1035 self.method_combo = QComboBox() 

1036 self.method_combo.addItems(self.METHODS) 

1037 method_form.addRow("補間方法", self.method_combo) 

1038 layout.addLayout(method_form) 

1039 

1040 self.extrapolate_checkbox = QCheckBox("範囲外を外挿する(既定はNaNにする)") 

1041 self.extrapolate_checkbox.setToolTip( 

1042 "元データのX範囲外にある格子点の扱いです。\n" 

1043 "オフ(既定): 範囲外はNaNになります(安全側)。\n" 

1044 "オン: 線形補間は両端の傾きで、3次スプラインはscipy標準の\n" 

1045 "区間多項式の延長で外挿します(いずれも範囲から離れるほど\n" 

1046 "不正確になりうる点に注意してください)。" 

1047 ) 

1048 layout.addWidget(self.extrapolate_checkbox) 

1049 

1050 output_form = QFormLayout() 

1051 self.output_name_edit = QLineEdit(f"{name}_resampled") 

1052 output_form.addRow("出力データセット名", self.output_name_edit) 

1053 layout.addLayout(output_form) 

1054 

1055 button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | 

1056 QDialogButtonBox.StandardButton.Cancel) 

1057 button_box.accepted.connect(self.accept) 

1058 button_box.rejected.connect(self.reject) 

1059 layout.addWidget(button_box) 

1060 

1061 apply_form_spacing(self) 

1062 

1063 def get_settings(self): 

1064 """(グリッドの元, 元ごとの引数, 補間の方法, 外挿するか, 出力名)。 

1065 

1066 引数は "dataset" なら {"dataset_name"}、"linspace" なら {"start", "stop", "num_points"}。 

1067 """ 

1068 source_text = self.source_combo.currentText() 

1069 if source_text == self.SOURCE_DATASET: 

1070 source = "dataset" 

1071 params = {"dataset_name": self.other_dataset_combo.currentText()} 

1072 else: 

1073 source = "linspace" 

1074 params = { 

1075 "start": self.linspace_start_spinbox.value(), 

1076 "stop": self.linspace_stop_spinbox.value(), 

1077 "num_points": self.linspace_num_points_spinbox.value(), 

1078 } 

1079 method_text = self.method_combo.currentText() 

1080 method = self._METHOD_KEY_BY_LABEL[method_text] 

1081 return ( 

1082 source, params, method, 

1083 self.extrapolate_checkbox.isChecked(), 

1084 self.output_name_edit.text().strip(), 

1085 ) 

1086 

1087 

1088class OutlierDetectionDialog(QDialog): 

1089 """外れ値の検出の設定。マスクに適用するかは別のチェック(既定はオフ、結果を見てから決められる)。""" 

1090 

1091 METHOD_ZSCORE = "Z-score" 

1092 METHOD_IQR = "IQR(四分位範囲)" 

1093 METHODS = [METHOD_ZSCORE, METHOD_IQR] 

1094 _METHOD_KEY_BY_LABEL = {METHOD_ZSCORE: "zscore", METHOD_IQR: "iqr"} 

1095 

1096 def __init__(self, name, parent=None): 

1097 super().__init__(parent) 

1098 self.setWindowTitle("外れ値検出") 

1099 self.resize(420, 280) 

1100 

1101 layout = QVBoxLayout(self) 

1102 layout.addWidget(QLabel(f"対象: {name}(Y値をもとに検出します)")) 

1103 

1104 form = QFormLayout() 

1105 self.method_combo = QComboBox() 

1106 self.method_combo.addItems(self.METHODS) 

1107 form.addRow("検出方法", self.method_combo) 

1108 layout.addLayout(form) 

1109 

1110 self.stack = QStackedWidget() 

1111 

1112 zscore_page = QWidget() 

1113 zscore_form = QFormLayout(zscore_page) 

1114 self.threshold_spinbox = QDoubleSpinBox() 

1115 self.threshold_spinbox.setRange(0.1, 100.0) 

1116 self.threshold_spinbox.setDecimals(2) 

1117 self.threshold_spinbox.setValue(3.0) 

1118 zscore_form.addRow("しきい値(|Z| >)", self.threshold_spinbox) 

1119 self.stack.addWidget(zscore_page) 

1120 

1121 iqr_page = QWidget() 

1122 iqr_form = QFormLayout(iqr_page) 

1123 self.multiplier_spinbox = QDoubleSpinBox() 

1124 self.multiplier_spinbox.setRange(0.1, 100.0) 

1125 self.multiplier_spinbox.setDecimals(2) 

1126 self.multiplier_spinbox.setValue(1.5) 

1127 iqr_form.addRow("係数(IQR ×)", self.multiplier_spinbox) 

1128 self.stack.addWidget(iqr_page) 

1129 

1130 layout.addWidget(self.stack) 

1131 self.method_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) 

1132 

1133 self.apply_mask_checkbox = QCheckBox("検出した外れ値をマスク(除外)に適用する") 

1134 self.apply_mask_checkbox.setToolTip( 

1135 "チェックを外すと検出結果を表示するだけでマスクは変更しません。\n" 

1136 "マスクは非破壊で、いつでも解除できます。" 

1137 ) 

1138 layout.addWidget(self.apply_mask_checkbox) 

1139 

1140 button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | 

1141 QDialogButtonBox.StandardButton.Cancel) 

1142 button_box.accepted.connect(self.accept) 

1143 button_box.rejected.connect(self.reject) 

1144 layout.addWidget(button_box) 

1145 

1146 apply_form_spacing(self) 

1147 

1148 def get_settings(self): 

1149 """(方法, しきい値か係数, マスクに適用するか)""" 

1150 method = self._METHOD_KEY_BY_LABEL[self.method_combo.currentText()] 

1151 value = self.threshold_spinbox.value() if method == "zscore" else self.multiplier_spinbox.value() 

1152 return method, value, self.apply_mask_checkbox.isChecked() 

1153 

1154 

1155class HistogramKDEDialog(QDialog): 

1156 """ヒストグラムか KDE。対象の列は Y に限らない(分布を見たいのは Y とは限らない)。""" 

1157 

1158 MODE_HISTOGRAM = "ヒストグラム" 

1159 MODE_KDE = "カーネル密度推定(KDE)" 

1160 MODES = [MODE_HISTOGRAM, MODE_KDE] 

1161 

1162 def __init__(self, name, column_names, default_column=None, parent=None): 

1163 super().__init__(parent) 

1164 self.setWindowTitle("ヒストグラム / KDE") 

1165 self.resize(420, 320) 

1166 self._name = name 

1167 

1168 layout = QVBoxLayout(self) 

1169 layout.addWidget(QLabel(f"対象: {name}")) 

1170 

1171 form = QFormLayout() 

1172 self.column_combo = QComboBox() 

1173 self.column_combo.addItems(column_names) 

1174 if default_column and default_column in column_names: 1174 ↛ 1176line 1174 didn't jump to line 1176 because the condition on line 1174 was always true

1175 self.column_combo.setCurrentText(default_column) 

1176 form.addRow("対象列", self.column_combo) 

1177 

1178 self.mode_combo = QComboBox() 

1179 self.mode_combo.addItems(self.MODES) 

1180 form.addRow("モード", self.mode_combo) 

1181 layout.addLayout(form) 

1182 

1183 self.stack = QStackedWidget() 

1184 

1185 hist_page = QWidget() 

1186 hist_form = QFormLayout(hist_page) 

1187 self.auto_bins_checkbox = QCheckBox("ビン数を自動決定") 

1188 self.auto_bins_checkbox.setChecked(True) 

1189 hist_form.addRow(self.auto_bins_checkbox) 

1190 self.bins_spinbox = QSpinBox() 

1191 self.bins_spinbox.setRange(2, 500) 

1192 self.bins_spinbox.setValue(10) 

1193 self.bins_spinbox.setEnabled(False) 

1194 hist_form.addRow("ビン数", self.bins_spinbox) 

1195 self.auto_bins_checkbox.toggled.connect(lambda checked: self.bins_spinbox.setEnabled(not checked)) 

1196 self.density_checkbox = QCheckBox("確率密度で正規化する(合計面積 = 1)") 

1197 hist_form.addRow(self.density_checkbox) 

1198 self.stack.addWidget(hist_page) 

1199 

1200 kde_page = QWidget() 

1201 kde_form = QFormLayout(kde_page) 

1202 self.kde_points_spinbox = QSpinBox() 

1203 self.kde_points_spinbox.setRange(10, 2000) 

1204 self.kde_points_spinbox.setValue(200) 

1205 kde_form.addRow("評価点数", self.kde_points_spinbox) 

1206 self.stack.addWidget(kde_page) 

1207 

1208 layout.addWidget(self.stack) 

1209 self.mode_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) 

1210 

1211 output_form = QFormLayout() 

1212 self.output_name_edit = QLineEdit(f"{name}_hist") 

1213 output_form.addRow("出力データセット名", self.output_name_edit) 

1214 layout.addLayout(output_form) 

1215 self.mode_combo.currentTextChanged.connect(self._update_default_output_name) 

1216 

1217 button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | 

1218 QDialogButtonBox.StandardButton.Cancel) 

1219 button_box.accepted.connect(self.accept) 

1220 button_box.rejected.connect(self.reject) 

1221 layout.addWidget(button_box) 

1222 

1223 apply_form_spacing(self) 

1224 

1225 def _update_default_output_name(self, mode_text): 

1226 # 利用者が書き換えた名前は上書きしない 

1227 current = self.output_name_edit.text() 

1228 if current not in (f"{self._name}_hist", f"{self._name}_kde"): 1228 ↛ 1229line 1228 didn't jump to line 1229 because the condition on line 1228 was never true

1229 return 

1230 suffix = "_hist" if mode_text == self.MODE_HISTOGRAM else "_kde" 

1231 self.output_name_edit.setText(f"{self._name}{suffix}") 

1232 

1233 def get_settings(self): 

1234 """{'mode', 'column', 'output_name'} と、histogram なら 'bins' / 'density'、kde なら 'n_points'。""" 

1235 mode = "histogram" if self.mode_combo.currentText() == self.MODE_HISTOGRAM else "kde" 

1236 settings = { 

1237 'mode': mode, 

1238 'column': self.column_combo.currentText(), 

1239 'output_name': self.output_name_edit.text().strip(), 

1240 } 

1241 if mode == "histogram": 

1242 settings['bins'] = 'auto' if self.auto_bins_checkbox.isChecked() else self.bins_spinbox.value() 

1243 settings['density'] = self.density_checkbox.isChecked() 

1244 else: 

1245 settings['n_points'] = self.kde_points_spinbox.value() 

1246 return settings 

1247 

1248 

1249class DatasetArithmeticDialog(QDialog): 

1250 """A と B の演算。X が揃わないので、呼び出し側が B を A の X に補間してから計算する。""" 

1251 

1252 OPERATIONS = ["A - B", "B - A", "A + B", "A × B", "A ÷ B", "B ÷ A"] 

1253 

1254 def __init__(self, name_a, name_b, parent=None): 

1255 super().__init__(parent) 

1256 self.setWindowTitle("データセット間演算") 

1257 self.resize(360, 200) 

1258 

1259 layout = QVBoxLayout(self) 

1260 label = QLabel(f"A: {name_a}\nB: {name_b}") 

1261 layout.addWidget(label) 

1262 

1263 form = QFormLayout() 

1264 self.operation_combo = QComboBox() 

1265 self.operation_combo.addItems(self.OPERATIONS) 

1266 form.addRow("演算", self.operation_combo) 

1267 

1268 self.output_name_edit = QLineEdit(f"{name_a} vs {name_b}") 

1269 form.addRow("出力データセット名", self.output_name_edit) 

1270 layout.addLayout(form) 

1271 

1272 info_label = QLabel( 

1273 "B側のY値を、A側のX値に線形補間してから演算します。" 

1274 "2つのデータセットのX軸の値が重なる範囲のみが対象になります。" 

1275 ) 

1276 info_label.setWordWrap(True) 

1277 layout.addWidget(info_label) 

1278 

1279 button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | 

1280 QDialogButtonBox.StandardButton.Cancel) 

1281 button_box.accepted.connect(self.accept) 

1282 button_box.rejected.connect(self.reject) 

1283 layout.addWidget(button_box) 

1284 

1285 apply_form_spacing(self) 

1286 

1287 def get_settings(self): 

1288 """(演算の種類, 出力名)""" 

1289 return self.operation_combo.currentText(), self.output_name_edit.text().strip() 

1290 

1291 

1292class XAxisAlignmentDialog(QDialog): 

1293 """B(動かす側)を A に重ねる。シフト量は自動で求めるので、出力名だけ尋ねる。""" 

1294 

1295 def __init__(self, name_a, name_b, parent=None): 

1296 super().__init__(parent) 

1297 self.setWindowTitle("X軸アライメント(相互相関)") 

1298 self.resize(380, 200) 

1299 

1300 layout = QVBoxLayout(self) 

1301 label = QLabel(f"基準(移動しない): {name_a}\n位置合わせ対象(移動する): {name_b}") 

1302 layout.addWidget(label) 

1303 

1304 form = QFormLayout() 

1305 self.output_name_edit = QLineEdit(f"{name_b}_aligned") 

1306 form.addRow("出力データセット名", self.output_name_edit) 

1307 layout.addLayout(form) 

1308 

1309 info_label = QLabel( 

1310 "2つのデータセットの相互相関が最大になるよう、位置合わせ対象のX値を" 

1311 "シフトした新しいデータセットを作成します(元のデータセットは変更しません)。" 

1312 ) 

1313 info_label.setWordWrap(True) 

1314 layout.addWidget(info_label) 

1315 

1316 button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | 

1317 QDialogButtonBox.StandardButton.Cancel) 

1318 button_box.accepted.connect(self.accept) 

1319 button_box.rejected.connect(self.reject) 

1320 layout.addWidget(button_box) 

1321 

1322 apply_form_spacing(self) 

1323 

1324 def get_settings(self): 

1325 return self.output_name_edit.text().strip()