-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathFittingWidget.py
More file actions
3631 lines (3109 loc) · 142 KB
/
Copy pathFittingWidget.py
File metadata and controls
3631 lines (3109 loc) · 142 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import json
import logging
import os
import re
import traceback
from collections import defaultdict
from pathlib import Path
from typing import Any
import numpy as np
from PySide6 import QtCore, QtGui, QtWidgets
from twisted.internet import threads
from sasmodels import generate, modelinfo
from sasmodels.sasview_model import MultiplicationModel, SasviewModel, load_standard_models
import sas.qtgui.Utilities.GuiUtils as GuiUtils
from sas import config
from sas.qtgui.Perspectives.Fitting import FittingUtilities
from sas.qtgui.Perspectives.Fitting.ConsoleUpdate import ConsoleUpdate
from sas.qtgui.Perspectives.Fitting.Constraint import Constraint
from sas.qtgui.Perspectives.Fitting.ConstraintManager import ConstraintManager
from sas.qtgui.Perspectives.Fitting.FitPage import FitPage
from sas.qtgui.Perspectives.Fitting.FitThread import FitThread
from sas.qtgui.Perspectives.Fitting.FittingController import FittingController
from sas.qtgui.Perspectives.Fitting.FittingLogic import FittingLogic
from sas.qtgui.Perspectives.Fitting.FittingState import FittingState
from sas.qtgui.Perspectives.Fitting.MagnetismWidget import MagnetismWidget
from sas.qtgui.Perspectives.Fitting.ModelSelectorWidget import ModelSelectorWidget
from sas.qtgui.Perspectives.Fitting.ModelThread import Calc1D, Calc2D
from sas.qtgui.Perspectives.Fitting.OptionsWidget import OptionsWidget
from sas.qtgui.Perspectives.Fitting.OrderWidget import OrderWidget
from sas.qtgui.Perspectives.Fitting.ParameterListWidget import ParameterListWidget
from sas.qtgui.Perspectives.Fitting.PolydispersityWidget import PolydispersityWidget
from sas.qtgui.Perspectives.Fitting.ReportPageLogic import ReportPageLogic
from sas.qtgui.Perspectives.Fitting.SmearingWidget import SmearingWidget
from sas.qtgui.Perspectives.Fitting.UI.FittingWidgetUI import Ui_FittingWidgetUI
from sas.qtgui.Perspectives.Fitting.ViewDelegate import ModelViewDelegate
from sas.qtgui.Plotting.Plotter import PlotterWidget
from sas.qtgui.Plotting.PlotterData import Data1D, Data2D, DataRole
from sas.qtgui.Utilities.BackgroundColor import BG_DEFAULT, BG_ERROR
from sas.qtgui.Utilities.CategoryInstaller import CategoryInstaller
from sas.sascalc.fit import models
from sas.sascalc.fit.BumpsFitting import BumpsFit as Fit
from sas.system import HELP_SYSTEM
from sas.system.user import find_plugins_dir
TAB_MAGNETISM = 4
TAB_POLY = 3
TAB_ORDERING = 5
CATEGORY_DEFAULT = "Choose category..."
MODEL_DEFAULT = "Choose model..."
CATEGORY_STRUCTURE = "Structure Factor"
CATEGORY_CUSTOM = "Plugin Models"
STRUCTURE_DEFAULT = "None"
DEFAULT_POLYDISP_FUNCTION = 'gaussian'
# A list of models that are known to not work with how the GUI handles models from sasmodels
# NOTE: These models are correct when used directly through the sasmodels package, but how qtgui handles them is wrong
SUPPRESSED_MODELS = ['rpa']
# Layered models that have integer parameters are often treated differently. Maintain a list of these models.
LAYERED_MODELS = ['unified_power_Rg', 'core_multi_shell', 'onion', 'spherical_sld']
# CRUFT: remove when new release of sasmodels is available
# https://github.com/SasView/sasview/pull/181#discussion_r218135162
if not hasattr(SasviewModel, 'get_weights'):
def get_weights(self: Any, name: str) -> tuple[np.ndarray, np.ndarray]:
"""
Returns the polydispersity distribution for parameter *name* as *value* and *weight* arrays.
"""
_, x, w = self._get_weights(self._model_info.parameters[name])
return x, w
SasviewModel.get_weights = get_weights
logger = logging.getLogger(__name__)
class FittingWidget(QtWidgets.QWidget, Ui_FittingWidgetUI):
"""
Main widget for selecting form and structure factor models
"""
constraintAddedSignal = QtCore.Signal(list, str)
newModelSignal = QtCore.Signal()
fittingFinishedSignal = QtCore.Signal(tuple)
batchFittingFinishedSignal = QtCore.Signal(tuple)
Calc1DFinishedSignal = QtCore.Signal(dict)
Calc2DFinishedSignal = QtCore.Signal(dict)
keyPressedSignal = QtCore.Signal(QtCore.QEvent)
MAGNETIC_MODELS = ['sphere', 'core_shell_sphere', 'core_multi_shell', 'cylinder', 'parallelepiped']
def __init__(self, parent: QtWidgets.QWidget | None = None, data: Any | None = None, tab_id: int = 1) -> None:
super(FittingWidget, self).__init__()
# Necessary globals
self.parent = parent
self.process = None # Default empty value
# Which tab is this widget displayed in?
self.tab_id = tab_id
import sys
sys.excepthook = self.info
# Globals
self.initializeGlobals()
# data index for the batch set
self.data_index = 0
# Main Data[12]D holders
# Logics.data contains a single Data1D/Data2D object
self._logic = [FittingLogic()]
# Fitting controller for business logic
self.fitting_controller = FittingController(self)
# Constraint manager for constraint handling
self.constraint_manager = ConstraintManager(self)
# Shared state object for tab widgets
self.fitting_state = FittingState(
on_fit_ready_changed=lambda can_fit: self.cmdFit.setEnabled(can_fit)
)
# Main GUI setup up
self.setupUi(self)
self.setWindowTitle("Fitting")
# Set up tabs widgets
self.initializeWidgets()
# Set up models and views
self.initializeModels()
# Initialize ParameterListWidget for main parameter list
self.param_list_widget = ParameterListWidget(
parent=self,
tree_view=self.lstParams,
model=self._model_model,
model_key="standard"
)
self.param_list_widget.setCallbacks(
rowHasConstraint=self.constraint_manager.rowHasConstraint,
rowHasActiveConstraint=self.constraint_manager.rowHasActiveConstraint,
isCheckable=self.isCheckable,
onAddSimpleConstraint=self.addSimpleConstraint,
onDeleteConstraint=self.deleteConstraint,
onEditConstraint=self.editConstraint,
onShowMultiConstraint=self.showMultiConstraint,
onSelectParameters=self.selectParameters,
onDeselectParameters=self.deselectParameters,
onShowModelDescription=self.showModelDescription
)
# Initialize ModelSelectorWidget for category/model/structure selection
self.model_selector = ModelSelectorWidget(
parent=self,
category_combo=self.cbCategory,
model_combo=self.cbModel,
structure_combo=self.cbStructureFactor
)
# Defaults for the structure factors
self.setDefaultStructureCombo()
# Make structure factor and model CBs disabled
self.disableModelCombo()
self.disableStructureCombo()
# Generate the category list for display
self.initializeCategoryCombo()
# Initial control state
self.initializeControls()
QtWidgets.QApplication.processEvents()
# Connect signals to controls
self.initializeSignals()
if data is not None:
self.dataFromItems(data)
# New font to display angstrom symbol
new_font = 'font-family: -apple-system, "Helvetica Neue", "Ubuntu";'
self.label_17.setStyleSheet(new_font)
self.label_19.setStyleSheet(new_font)
def info(self, type: Any, value: Any, tb: Any) -> None:
logger.error("".join(traceback.format_exception(type, value, tb)))
@property
def logic(self) -> FittingLogic:
# make sure the logic contains at least one element
assert self._logic
# logic connected to the currently shown data
return self._logic[self.data_index]
@property
def data(self) -> Data1D | Data2D:
return self.logic.data
def dataFromItems(self, value: QtGui.QStandardItem | list[QtGui.QStandardItem]) -> None:
""" data setter """
# Value is either a list of indices for batch fitting or a simple index
# for standard fitting. Assure we have a list, regardless.
if isinstance(value, list):
self.is_batch_fitting = True
else:
value = [value]
assert isinstance(value[0], QtGui.QStandardItem)
# Keep reference to all datasets for batch
self.all_data = value
# Create logics with data items
# Logics.data contains only a single Data1D/Data2D object
if len(value) == 1:
# single data logic is already defined, update data on it
self._logic[0].data = GuiUtils.dataFromItem(value[0])
else:
# batch datasets
self._logic = []
for data_item in value:
logic = FittingLogic(data=GuiUtils.dataFromItem(data_item))
self._logic.append(logic)
# Option widget logic was destroyed - reestablish
self.options_widget.logic = self._logic[0]
# Ensure auxiliary widgets point at the new logic instance
self.polydispersity_widget.logic = self._logic[0]
self.magnetism_widget.logic = self._logic[0]
# update the ordering tab
self.order_widget.updateData(self.all_data)
# Overwrite data type descriptor
self.is2D = True if isinstance(self.logic.data, Data2D) else False
# Let others know we're full of data now
self.data_is_loaded = True
# Update FittingState
self.fitting_state.is2D = self.is2D
self.fitting_state.is_batch_fitting = self.is_batch_fitting
self.fitting_state.data_is_loaded = True
# Reset the smearer
self.smearing_widget.resetSmearer()
if self.data.isSesans:
self.onSesansData()
# Enable/disable UI components
self.setEnablementOnDataLoad()
# Reinitialize model list for constrained/simult fitting
self.newModelSignal.emit()
def initializeGlobals(self) -> None:
"""
Initialize global variables used in this class
"""
# SasModel is loaded
self.model_is_loaded = False
# Data[12]D passed and set
self.data_is_loaded = False
# Batch/single fitting
self.is_batch_fitting = False
self.is_chain_fitting = False
# Is the fit job running?
self.fit_started = False
# The current fit thread
self.calc_fit = None
# Current SasModel view dimension
self.is2D = False
# Current SasModel is multishell
self.model_has_shells = False
# Utility variable to enable unselectable option in category combobox
self._previous_category_index = 0
# Utility variables for multishell display
self._n_shells_row = -1
self._num_shell_params = -1
# Dictionary of {model name: model class} for the current category
self.models = {}
# Dictionary of QModels
self.model_dict = {}
self.lst_dict = {}
self.tabToList = {} # tab_id -> list widget
self.tabToKey = {} # tab_id -> model key
# Parameters to fit
self.main_params_to_fit = []
# Fit options
self.q_range_min = OptionsWidget.QMIN_DEFAULT
self.q_range_max = OptionsWidget.QMAX_DEFAULT
self.npts = OptionsWidget.NPTS_DEFAULT
self.log_points = True
self.weighting = 0
self.chi2 = None
# Does the control support UNDO/REDO
# temporarily off
self.undo_supported = False
self.page_stack = []
self.all_data = []
# custom plugin models
# {model.name:model}
self.custom_models = self.customModels()
# copy of current kernel model
self.kernel_module_copy = None
# dictionaries of current params
self.magnet_params = {}
# Page id for fitting
# To keep with previous SasView values, use 200 as the start offset
self.page_id = 200 + self.tab_id
# Data for chosen model
self.model_data = None
self._previous_model_index = 0
# List of all shell-unique parameters
self.shell_names = []
# Error column presence in parameter display
self.has_error_column = False
self.has_magnet_error_column = False
# Enablement of comboboxes
self.enabled_cbmodel = False
self.enabled_sfmodel = False
# If the widget generated theory item, save it
self.theory_item = None
# list column widths
self.lstParamHeaderSizes = {}
# Fitting just ran - don't recalculate chi2
self.fitResults = False
# Current parameters
self.page_parameters = None
# signal communicator
self.communicator = GuiUtils.communicator
def initializeWidgets(self) -> None:
"""
Initialize widgets for tabs
"""
# Options widget
layout = QtWidgets.QGridLayout()
self.options_widget = OptionsWidget(self, self.logic)
layout.addWidget(self.options_widget)
self.tabOptions.setLayout(layout)
self.options_widget.setLogScale(self.log_points)
# Smearing widget
layout = QtWidgets.QGridLayout()
self.smearing_widget = SmearingWidget(self)
layout.addWidget(self.smearing_widget)
self.tabResolution.setLayout(layout)
# Polydispersity widget
layout = QtWidgets.QGridLayout()
self.polydispersity_widget = PolydispersityWidget(parent=self)
layout.addWidget(self.polydispersity_widget)
self.tabPolydispersity.setLayout(layout)
self.lstPoly = self.polydispersity_widget.lstPoly
# magnetism widget
layout = QtWidgets.QGridLayout()
self.magnetism_widget = MagnetismWidget(parent=self)
layout.addWidget(self.magnetism_widget)
self.tabMagnetism.setLayout(layout)
self.lstMagnetic = self.magnetism_widget.lstMagnetic
# Order widget
layout = QtWidgets.QGridLayout()
# pass all data items to access multiple datasets
self.order_widget = OrderWidget(self, self.all_data)
layout.addWidget(self.order_widget)
self.tabOrder.setLayout(layout)
# Define bold font for use in various controls
self.boldFont = QtGui.QFont()
self.boldFont.setBold(True)
# Set data label
self.label.setFont(self.boldFont)
self.label.setText("No data loaded")
self.lblFilename.setText("")
def initializeModels(self) -> None:
"""
Set up models and views
"""
# Set the main models
# We can't use a single model here, due to restrictions on flattening
# the model tree with subclassed QAbstractProxyModel...
self._model_model = FittingUtilities.ToolTippedItemModel()
self.model_dict["standard"] = self._model_model
self.model_dict["poly"] = self.polydispersity_widget.poly_model
self.model_dict["magnet"] = self.magnetism_widget._magnet_model
self.lst_dict["standard"] = self.lstParams
self.lst_dict["poly"] = self.lstPoly
self.lst_dict["magnet"] = self.lstMagnetic
self.tabToList[0] = self.lstParams
self.tabToList[3] = self.polydispersity_widget.lstPoly
self.tabToList[4] = self.magnetism_widget.lstMagnetic
self.tabToKey[0] = "standard"
self.tabToKey[3] = "poly"
self.tabToKey[4] = "magnet"
# Param model displayed in param list
self.lstParams.setModel(self._model_model)
self.readCategoryInfo()
# Delegates for custom editing and display
self.lstParams.setItemDelegate(ModelViewDelegate(self))
self.lstParams.setAlternatingRowColors(True)
stylesheet = """
QTreeView {
paint-alternating-row-colors-for-empty-area:0;
}
QTreeView::item {
border: 1px;
padding: 2px 1px;
}
QTreeView::item:hover {
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #e7effd, stop: 1 #cbdaf1);
border: 1px solid #bfcde4;
}
QTreeView::item:selected {
border: 1px solid #567dbc;
}
QTreeView::item:selected:active{
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #6ea1f1, stop: 1 #567dbc);
}
QTreeView::item:selected:!active {
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #6b9be8, stop: 1 #577fbf);
}
"""
self.lstParams.setStyleSheet(stylesheet)
self.lstParams.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.lstParams.customContextMenuRequested.connect(self.showModelContextMenu)
self.lstParams.setAttribute(QtCore.Qt.WA_MacShowFocusRect, False)
# Column resize signals
self.lstParams.header().sectionResized.connect(self.onColumnWidthUpdate)
# Poly model displayed in poly list
self.polydispersity_widget.setPolyModel()
self.lstPoly.customContextMenuRequested.connect(self.showModelContextMenu)
# Magnetism model displayed in magnetism list
self.magnetism_widget.setMagneticModel()
self.lstMagnetic.customContextMenuRequested.connect(self.showModelContextMenu)
# Initial status of the ordering tab - invisible
self.tabFitting.removeTab(TAB_ORDERING)
def initializeCategoryCombo(self) -> None:
"""
Model category combo setup
"""
category_list = sorted(self.master_category_dict)
self.cbCategory.addItem(CATEGORY_DEFAULT)
self.cbCategory.addItems(category_list)
if CATEGORY_STRUCTURE not in category_list:
self.cbCategory.addItem(CATEGORY_STRUCTURE)
self.cbCategory.setCurrentIndex(0)
def setEnablementOnDataLoad(self) -> None:
"""
Enable/disable various UI elements based on data loaded
"""
# Tag along functionality
self.label.setText("Data loaded from: ")
if self.logic.data.name:
self.lblFilename.setText(self.logic.data.name)
else:
self.lblFilename.setText(self.logic.data.filename)
self.updateQRange()
# Switch off Data2D control
self.chk2DView.setEnabled(False)
self.chk2DView.setVisible(False)
self.chkMagnetism.setEnabled(self.canHaveMagnetism())
self.tabFitting.setTabEnabled(TAB_MAGNETISM, self.chkMagnetism.isChecked())
# Combo box or label for file name"
if self.is_batch_fitting:
self.lblFilename.setVisible(False)
for dataitem in self.all_data:
name = GuiUtils.dataFromItem(dataitem).name
self.cbFileNames.addItem(name)
self.cbFileNames.setVisible(True)
self.chkChainFit.setEnabled(True)
self.chkChainFit.setVisible(True)
# This panel is not designed to view individual fits, so disable plotting
self.cmdPlot.setVisible(False)
# Similarly on other tabs
self.options_widget.setEnablementOnDataLoad()
self.onSelectModel()
# Smearing tab
self.smearing_widget.updateData(self.data)
# Check if a model was already loaded when data is sent to the tab
self.cmdFit.setEnabled(self.haveParamsToFit())
def acceptsData(self) -> bool:
""" Tells the caller this widget can accept new dataset """
return not self.data_is_loaded
def disableModelCombo(self) -> None:
""" Disable the combobox """
self.cbModel.setEnabled(False)
self.lblModel.setEnabled(False)
self.enabled_cbmodel = False
def enableModelCombo(self) -> None:
""" Enable the combobox """
self.cbModel.setEnabled(True)
self.lblModel.setEnabled(True)
self.enabled_cbmodel = True
def disableStructureCombo(self) -> None:
""" Disable the combobox """
self.cbStructureFactor.setEnabled(False)
self.lblStructure.setEnabled(False)
self.enabled_sfmodel = False
def enableBackgroundParameter(self, set_value: float | None = None) -> None:
""" Enable the background parameter. Optionally set at a specified value. """
background_row = self.getRowFromName("background")
if background_row is not None:
self.setParamEditableByRow(background_row, True)
if set_value is not None:
self._model_model.item(background_row, 1).setText(GuiUtils.formatNumber(set_value, high=True))
def disableBackgroundParameter(self, set_value: float | None = None) -> None:
""" Disable the background parameter. Optionally set at a specified value. """
background_row = self.getRowFromName("background")
if background_row is not None:
self.setParamEditableByRow(background_row, False)
if set_value is not None:
self._model_model.item(background_row, 1).setText(GuiUtils.formatNumber(set_value, high=True))
def enableStructureCombo(self) -> None:
""" Enable the combobox """
self.cbStructureFactor.setEnabled(True)
self.lblStructure.setEnabled(True)
self.enabled_sfmodel = True
def togglePoly(self, isChecked: bool) -> None:
""" Enable/disable the polydispersity tab """
self.tabFitting.setTabEnabled(TAB_POLY, isChecked)
# Check if any parameters are ready for fitting
self.cmdFit.setEnabled(self.haveParamsToFit())
self.polydispersity_widget.togglePoly(isChecked)
def onPolyToggled(self, isChecked: bool) -> None:
"""
Handle polydispersity toggle signal from PolydispersityWidget.
Updates FittingState and tab enablement.
"""
self.fitting_state.poly_enabled = isChecked
self.tabFitting.setTabEnabled(TAB_POLY, isChecked)
self.cmdFit.setEnabled(self.haveParamsToFit())
def toggleMagnetism(self, isChecked: bool) -> None:
""" Enable/disable the magnetism tab """
self.tabFitting.setTabEnabled(TAB_MAGNETISM, isChecked)
# Check if any parameters are ready for fitting
self.cmdFit.setEnabled(self.haveParamsToFit())
self.magnetism_widget.isActive = isChecked
def onMagnetismToggled(self, isChecked: bool) -> None:
"""
Handle magnetism toggle signal from MagnetismWidget.
Updates FittingState and tab enablement.
"""
self.fitting_state.magnetism_enabled = isChecked
self.tabFitting.setTabEnabled(TAB_MAGNETISM, isChecked)
self.cmdFit.setEnabled(self.haveParamsToFit())
def toggleChainFit(self, isChecked: bool) -> None:
""" Enable/disable chain fitting """
self.is_chain_fitting = isChecked
# show/hide the ordering tab
if isChecked:
self.tabFitting.insertTab(TAB_ORDERING, self.tabOrder, "Order")
else:
self.tabFitting.removeTab(TAB_ORDERING)
def toggle2D(self, isChecked: bool) -> None:
""" Enable/disable the controls dependent on 1D/2D data instance """
self.chkMagnetism.setEnabled(isChecked)
self.is2D = isChecked
# Reload the current model
if self.logic.kernel_module:
self.onSelectModel()
@classmethod
def customModels(cls) -> dict[str, Any]:
""" Reads in file names in the custom plugin directory """
manager = models.ModelManager()
# TODO: Cache plugin models instead of scanning the directory each time.
manager.update()
# TODO: Define plugin_models property in ModelManager.
return manager.base.plugin_models
def initializeControls(self) -> None:
"""
Set initial control enablement
"""
self.cbFileNames.setVisible(False)
self.cmdFit.setEnabled(False)
self.cmdPlot.setEnabled(False)
self.chkPolydispersity.setEnabled(False)
self.chkPolydispersity.setChecked(False)
self.chk2DView.setEnabled(True)
self.chk2DView.setChecked(False)
self.chkMagnetism.setEnabled(False)
self.chkMagnetism.setChecked(False)
self.chkChainFit.setEnabled(False)
self.chkChainFit.setVisible(False)
# Tabs
self.tabFitting.setTabEnabled(TAB_POLY, False)
self.tabFitting.setTabEnabled(TAB_MAGNETISM, False)
self.lblChi2Value.setText("---")
# Smearing tab
self.smearing_widget.updateData(self.data)
# Line edits in the option tab
self.updateQRange()
def initializeSignals(self) -> None:
"""
Connect GUI element signals
"""
# Comboboxes
self.cbStructureFactor.currentIndexChanged.connect(self.onSelectStructureFactor)
self.cbCategory.currentIndexChanged.connect(self.onSelectCategory)
self.cbModel.currentIndexChanged.connect(self.onSelectModel)
self.cbFileNames.currentIndexChanged.connect(self.onSelectBatchFilename)
# Checkboxes
self.chk2DView.toggled.connect(self.toggle2D)
self.chkPolydispersity.toggled.connect(self.togglePoly)
self.chkMagnetism.toggled.connect(self.toggleMagnetism)
self.chkChainFit.toggled.connect(self.toggleChainFit)
# Buttons
self.cmdFit.clicked.connect(self.onFit)
self.cmdPlot.clicked.connect(self.onPlot)
self.cmdHelp.clicked.connect(self.onHelp)
# Respond to change in parameters from the UI
self._model_model.dataChanged.connect(self.onMainParamsChange)
self.lstParams.selectionModel().selectionChanged.connect(self.onSelectionChanged)
self.lstParams.installEventFilter(self)
# Local signals
self.batchFittingFinishedSignal.connect(self.batchFitComplete)
self.fittingFinishedSignal.connect(self.fitComplete)
self.Calc1DFinishedSignal.connect(self.complete1D)
self.Calc2DFinishedSignal.connect(self.complete2D)
# Signals from separate tabs asking for replot
self.options_widget.plot_signal.connect(self.onOptionsUpdate)
self.options_widget.txtMinRange.editingFinished.connect(self.options_widget.updateMinQ)
self.options_widget.txtMaxRange.editingFinished.connect(self.options_widget.updateMaxQ)
# Signals from other widgets
self.communicator.customModelDirectoryChanged.connect(self.onCustomModelChange)
self.smearing_widget.smearingChangedSignal.connect(self.onSmearingOptionsUpdate)
self.polydispersity_widget.cmdFitSignal.connect(lambda: self.cmdFit.setEnabled(self.haveParamsToFit()))
self.polydispersity_widget.updateDataSignal.connect(lambda: self.updateData())
self.polydispersity_widget.iterateOverModelSignal.connect(lambda: self.iterateOverModel(self.updateFunctionCaption))
self.polydispersity_widget.toggledSignal.connect(self.onPolyToggled)
self.magnetism_widget.cmdFitSignal.connect(lambda: self.cmdFit.setEnabled(self.haveParamsToFit()))
self.magnetism_widget.updateDataSignal.connect(lambda: self.updateData())
self.magnetism_widget.toggledSignal.connect(self.onMagnetismToggled)
# Communicator signal
self.communicator.updateModelCategoriesSignal.connect(self.onCategoriesChanged)
self.communicator.updateMaskedDataSignal.connect(self.onMaskedData)
# Catch all key press events
self.keyPressedSignal.connect(self.onKey)
def keyPressEvent(self, event: QtGui.QKeyEvent) -> None:
super(FittingWidget, self).keyPressEvent(event)
self.keyPressedSignal.emit(event)
def eventFilter(self, obj: QtCore.QObject, event: QtCore.QEvent) -> bool:
# Catch enter key presses when editing model params
if obj in [self.lstParams, self.polydispersity_widget.lstPoly, self.magnetism_widget.lstMagnetic]:
if event.type() == QtCore.QEvent.KeyPress and event.key() in [QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter]:
self.onKey(event)
return True
return False
def modelName(self) -> str:
"""
Returns model name, by default M<tab#>, e.g. M1, M2
"""
return "M%i" % self.tab_id
def nameForFittedData(self, name: str) -> str:
"""
Generate name for the current fit
"""
if self.is2D:
name += "2d"
name = "%s [%s]" % (self.modelName(), name)
return name
def showModelContextMenu(self, position: QtCore.QPoint) -> None:
"""
Show context specific menu in the parameter table.
When clicked on parameter(s): fitting/constraints options
When clicked on white space: model description
"""
# See which model we're dealing with by looking at the tab id
current_list = self.tabToList[self.tabFitting.currentIndex()]
model_key = self.tabToKey[self.tabFitting.currentIndex()]
rows = [s.row() for s in current_list.selectionModel().selectedRows()
if self.isCheckable(s.row(), model_key=model_key)]
menu = self.showModelDescription() if not rows else self.modelContextMenu(rows)
try:
menu.exec_(current_list.viewport().mapToGlobal(position))
except AttributeError as ex:
logger.error("Error generating context menu: %s" % ex)
return
def modelContextMenu(self, rows: list[int]) -> QtWidgets.QMenu:
"""
Create context menu for the parameter selection
"""
menu = QtWidgets.QMenu()
num_rows = len(rows)
if num_rows < 1:
return menu
current_list = self.tabToList[self.tabFitting.currentIndex()]
model_key = self.tabToKey[self.tabFitting.currentIndex()]
# Select for fitting
param_string = "parameter " if num_rows == 1 else "parameters "
to_string = "to its current value" if num_rows == 1 else "to their current values"
has_constraints = any([self.rowHasConstraint(i, model_key=model_key) for i in rows])
has_real_constraints = any([self.rowHasActiveConstraint(i, model_key=model_key) for i in rows])
self.actionSelect = QtGui.QAction(self)
self.actionSelect.setObjectName("actionSelect")
self.actionSelect.setText(QtCore.QCoreApplication.translate("self", "Select "+param_string+" for fitting"))
# Unselect from fitting
self.actionDeselect = QtGui.QAction(self)
self.actionDeselect.setObjectName("actionDeselect")
self.actionDeselect.setText(QtCore.QCoreApplication.translate("self", "De-select "+param_string+" from fitting"))
self.actionConstrain = QtGui.QAction(self)
self.actionConstrain.setObjectName("actionConstrain")
self.actionConstrain.setText(QtCore.QCoreApplication.translate("self", "Constrain "+param_string + to_string))
self.actionRemoveConstraint = QtGui.QAction(self)
self.actionRemoveConstraint.setObjectName("actionRemoveConstrain")
self.actionRemoveConstraint.setText(QtCore.QCoreApplication.translate("self", "Remove constraint"))
self.actionEditConstraint = QtGui.QAction(self)
self.actionEditConstraint.setObjectName("actionEditConstrain")
self.actionEditConstraint.setText(QtCore.QCoreApplication.translate("self", "Edit constraint"))
self.actionMultiConstrain = QtGui.QAction(self)
self.actionMultiConstrain.setObjectName("actionMultiConstrain")
self.actionMultiConstrain.setText(QtCore.QCoreApplication.translate("self", "Constrain selected parameters to their current values"))
self.actionMutualMultiConstrain = QtGui.QAction(self)
self.actionMutualMultiConstrain.setObjectName("actionMutualMultiConstrain")
self.actionMutualMultiConstrain.setText(QtCore.QCoreApplication.translate("self", "Mutual constrain of selected parameters..."))
menu.addAction(self.actionSelect)
menu.addAction(self.actionDeselect)
menu.addSeparator()
if has_constraints:
menu.addAction(self.actionRemoveConstraint)
if num_rows == 1 and has_real_constraints:
menu.addAction(self.actionEditConstraint)
else:
if num_rows == 2:
menu.addAction(self.actionMutualMultiConstrain)
else:
menu.addAction(self.actionConstrain)
# Define the callbacks
self.actionConstrain.triggered.connect(self.addSimpleConstraint)
self.actionRemoveConstraint.triggered.connect(self.deleteConstraint)
self.actionEditConstraint.triggered.connect(self.editConstraint)
self.actionMutualMultiConstrain.triggered.connect(lambda: self.showMultiConstraint(current_list=current_list))
self.actionSelect.triggered.connect(self.selectParameters)
self.actionDeselect.triggered.connect(self.deselectParameters)
return menu
def showMultiConstraint(self, current_list: QtWidgets.QTreeView | None = None) -> None:
"""
Show the constraint widget and receive the expression.
Delegated to ConstraintManager.
"""
self.constraint_manager.showMultiConstraint(current_list)
def getModelKeyFromName(self, name: str) -> str:
"""
Given parameter name, get the model index.
"""
if name in self.getParamNamesMain():
return "standard"
elif name in self.polydispersity_widget.getParamNamesPoly():
return "poly"
elif name in self.getParamNamesMagnet():
return "magnet"
else:
return "standard"
def getRowFromName(self, name: str) -> int | None:
"""
Given parameter name, get the row number in a model.
The model is the main _model_model by default
"""
model_key = self.getModelKeyFromName(name)
model = self.model_dict[model_key]
for row in range(model.rowCount()):
row_name = model.item(row).text()
if model_key == 'poly':
row_name = self.polydispersity_widget.polyNameToParam(row_name)
if row_name == name:
return row
return None
def getParamNames(self) -> list[str]:
"""
Return list of all active parameters for the current model
"""
main_model_params = self.getParamNamesMain()
poly_model_params = self.polydispersity_widget.getParamNamesPoly()
# magnet_model_params = self.getParamNamesMagnet()
return main_model_params + poly_model_params # + magnet_model_params
def getParamNamesMain(self) -> list[str]:
"""
Return list of main parameters for the current model
"""
main_model_params = [self._model_model.item(row).text()
for row in range(self._model_model.rowCount())
if self.isCheckable(row, model_key="standard")]
return main_model_params
def getParamNamesMagnet(self) -> list[str]:
"""
Return list of magnetic parameters for the current model
"""
if not self.chkMagnetism.isChecked():
return []
return self.magnetism_widget.getParamNamesMagnet()
def modifyViewOnRow(self, row: int, font: QtGui.QFont | None = None, brush: QtGui.QBrush | None = None, model_key: str = "standard") -> None:
"""
Change how the given row of the main model is shown
"""
model = self.model_dict[model_key]
fields_enabled = False
if font is None:
font = QtGui.QFont()
fields_enabled = True
if brush is None:
brush = QtGui.QBrush()
fields_enabled = True
model.blockSignals(True)
# Modify font and foreground of affected rows
for column in range(0, model.columnCount()):
model.item(row, column).setForeground(brush)
model.item(row, column).setFont(font)
# Allow the user to interact or not with the fields depending on
# whether the parameter is constrained or not
model.item(row, column).setEditable(fields_enabled)
# Force checkbox selection when parameter is constrained and disable
# checkbox interaction
if not fields_enabled and model.item(row, 0).isCheckable():
model.item(row, 0).setCheckState(QtCore.Qt.Checked)
model.item(row, 0).setEnabled(False)
else:
# Enable checkbox interaction
model.item(row, 0).setEnabled(True)
model.blockSignals(False)
def getModelKey(self, constraint: Constraint) -> str | None:
"""
Given parameter name get the model index.
"""
if constraint.param in self.getParamNamesMain():
return "standard"
elif constraint.param in self.polydispersity_widget.getParamNamesPoly():
return "poly"
elif constraint.param in self.getParamNamesMagnet():
return "magnet"
else:
return None
def addConstraintToRow(self, constraint: Constraint | None = None, row: int = 0, model_key: str = "standard") -> None:
"""
Add the constraint object to the requested row.
Delegated to ConstraintManager.
"""
self.constraint_manager.addConstraintToRow(constraint, row, model_key)
def addSimpleConstraint(self) -> None:
"""
Add a constraint on a single parameter.
Delegated to ConstraintManager.
"""
self.constraint_manager.addSimpleConstraint()
def editConstraint(self) -> None:
"""
Edit constraints for selected parameters.
Delegated to ConstraintManager.
"""
self.constraint_manager.editConstraint()
def deleteConstraint(self) -> None:
"""
Delete constraints from selected parameters.
Delegated to ConstraintManager.
"""
self.constraint_manager.deleteConstraint()
def deleteConstraintOnParameter(self, param: str | None = None, model_key: str = "standard") -> None:
"""
Delete the constraint on model parameter 'param'.
Delegated to ConstraintManager.
"""
self.constraint_manager.deleteConstraintOnParameter(param, model_key)
def getConstraintForRow(self, row: int, model_key: str = "standard") -> Constraint | None:
"""
For the given row, return its constraint, if any (otherwise None).
Delegated to ConstraintManager.
"""
return self.constraint_manager.getConstraintForRow(row, model_key)
def allParamNames(self) -> list[str]:
"""
Returns a list of all parameter names defined on the current model
"""
all_params = self.logic.kernel_module._model_info.parameters.kernel_parameters
all_params = list(self.logic.kernel_module.details)
# all_param_names = [param.name for param in all_params]
# Assure scale and background are always included
# if 'scale' not in all_param_names:
# all_param_names.append('scale')
# if 'background' not in all_param_names:
# all_param_names.append('background')
return all_params
def paramHasConstraint(self, param: str | None = None) -> bool:
"""
Find out if the given parameter in all the models has a constraint child.
Delegated to ConstraintManager.
"""
return self.constraint_manager.paramHasConstraint(param)
def rowHasConstraint(self, row: int, model_key: str = "standard") -> bool:
"""
Finds out if row of the main model has a constraint child.
Delegated to ConstraintManager.
"""
return self.constraint_manager.rowHasConstraint(row, model_key)