source: sasview/src/sas/qtgui/Perspectives/Fitting/ComplexConstraint.py @ 0764593

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 0764593 was 0764593, checked in by Piotr Rozyczko <rozyczko@…>, 6 years ago

Minor fixes to the complex constraint widget

  • Property mode set to 100644
File size: 7.2 KB
Line 
1"""
2Widget for multi-model constraints.
3"""
4import os
5from numpy import *
6
7from PyQt5 import QtCore
8from PyQt5 import QtGui
9from PyQt5 import QtWidgets
10import webbrowser
11
12import sas.qtgui.Utilities.GuiUtils as GuiUtils
13ALLOWED_OPERATORS = ['=','<','>','>=','<=']
14
15# Local UI
16from sas.qtgui.Perspectives.Fitting.UI.ComplexConstraintUI import Ui_ComplexConstraintUI
17from sas.qtgui.Perspectives.Fitting.Constraints import Constraint
18
19class ComplexConstraint(QtWidgets.QDialog, Ui_ComplexConstraintUI):
20    def __init__(self, parent=None, tabs=None):
21        super(ComplexConstraint, self).__init__()
22
23        self.setupUi(self)
24        #self.setFixedSize(self.minimumSizeHint())
25        self.setModal(True)
26
27        # Useful globals
28        self.tabs = tabs
29        self.params = None
30        self.tab_names = None
31        self.operator = '='
32
33        self.setupData()
34        self.setupWidgets()
35        self.setupSignals()
36        #self.setupTooltip()
37
38        self.setFixedSize(self.minimumSizeHint())
39
40    def setupData(self):
41        """
42        Digs into self.tabs and pulls out relevant info
43        """
44        self.tab_names = [tab.kernel_module.name for tab in self.tabs]
45        self.params = [tab.getParamNames() for tab in self.tabs]
46        pass
47
48    def setupSignals(self):
49        """
50        Signals from various elements
51        """
52        self.cmdOK.clicked.connect(self.accept)
53        self.cmdHelp.clicked.connect(self.onHelp)
54        self.cmdRevert.clicked.connect(self.onRevert)
55        self.txtConstraint.editingFinished.connect(self.validateFormula)
56
57        self.cbParam1.currentIndexChanged.connect(self.onParamIndexChange)
58        self.cbParam2.currentIndexChanged.connect(self.onParamIndexChange)
59        self.cbOperator.currentIndexChanged.connect(self.onOperatorChange)
60
61    def setupWidgets(self):
62        """
63        Setup widgets based on current parameters
64        """
65        self.txtName1.setText(self.tab_names[0])
66        self.txtName2.setText(self.tab_names[1])
67
68        # Show only parameters not already constrained
69        self.cbParam1.clear()
70        items = [param for i,param in enumerate(self.params[0]) if not self.tabs[0].rowHasConstraint(i)]
71        self.cbParam1.addItems(items)
72        self.cbParam2.clear()
73        items = [param for i,param in enumerate(self.params[1]) if not self.tabs[1].rowHasConstraint(i)]
74        self.cbParam2.addItems(items)
75
76        self.txtParam.setText(self.tab_names[0] + ":" + self.cbParam1.currentText())
77
78        self.cbOperator.clear()
79        self.cbOperator.addItems(ALLOWED_OPERATORS)
80        self.txtOperator.setText(self.cbOperator.currentText())
81
82        self.txtConstraint.setText(self.tab_names[1]+"."+self.cbParam2.currentText())
83
84    def setupTooltip(self):
85        """
86        Tooltip for txtConstraint
87        """
88        tooltip = "E.g.\n%s = 2.0 * (%s)\n" %(self.params[0], self.params[1])
89        tooltip += "%s = sqrt(%s) + 5"%(self.params[0], self.params[1])
90        self.txtConstraint.setToolTip(tooltip)
91
92    def onParamIndexChange(self, index):
93        """
94        Respond to parameter combo box changes
95        """
96        # Find out the signal source
97        source = self.sender().objectName()
98        if source == "cbParam1":
99            self.txtParam.setText(self.tab_names[0] + ":" + self.cbParam1.currentText())
100        else:
101            self.txtConstraint.setText(self.tab_names[1] + "." + self.cbParam2.currentText())
102        pass
103
104    def onOperatorChange(self, index):
105        """
106        Respond to operator combo box changes
107        """
108        self.txtOperator.setText(self.cbOperator.currentText())
109
110    def onRevert(self):
111        """
112        switch M1 <-> M2
113        """
114        # Switch parameters
115        self.params[1], self.params[0] = self.params[0], self.params[1]
116        self.tab_names[1], self.tab_names[0] = self.tab_names[0], self.tab_names[1]
117        self.tabs[1], self.tabs[0] = self.tabs[0], self.tabs[1]
118        # Try to swap parameter names in the line edit
119        current_text = self.txtConstraint.text()
120        new_text = current_text.replace(self.cbParam1.currentText(), self.cbParam2.currentText())
121        self.txtConstraint.setText(new_text)
122        # Update labels and tooltips
123        index1 = self.cbParam1.currentIndex()
124        index2 = self.cbParam2.currentIndex()
125        indexOp = self.cbOperator.currentIndex()
126        self.setupWidgets()
127
128        # Original indices
129        self.cbParam1.setCurrentIndex(index2)
130        self.cbParam2.setCurrentIndex(index1)
131        self.cbOperator.setCurrentIndex(indexOp)
132        #self.setupTooltip()
133
134    def validateFormula(self):
135        """
136        Add visual cues when formula is incorrect
137        """
138        formula_is_valid = False
139        formula_is_valid = self.validateConstraint(self.txtConstraint.text())
140        if not formula_is_valid:
141            self.cmdOK.setEnabled(False)
142            self.txtConstraint.setStyleSheet("QLineEdit {background-color: red;}")
143        else:
144            self.cmdOK.setEnabled(True)
145            self.txtConstraint.setStyleSheet("QLineEdit {background-color: white;}")
146
147    def validateConstraint(self, constraint_text):
148        """
149        Ensure the constraint has proper form
150        """
151        # 0. none or empty
152        if not constraint_text or not isinstance(constraint_text, str):
153            return False
154
155        # M1.scale  --> model_str='M1', constraint_text='scale'
156        param_str = self.cbParam2.currentText()
157        constraint_text = constraint_text.strip()
158        model_str = self.txtName2.text()
159
160        # 0. Has to contain the model name
161        if model_str != self.txtName2.text():
162            return False
163
164        # Remove model name from constraint
165        constraint_text = constraint_text.replace(model_str+".",'')
166
167        # 1. just the parameter
168        if param_str == constraint_text:
169            return True
170
171        # 2. ensure the text contains parameter name
172        parameter_string_start = constraint_text.find(param_str)
173        if parameter_string_start < 0:
174            return False
175        parameter_string_end = parameter_string_start + len(param_str)
176
177        # 3. replace parameter name with "1" and try to evaluate the expression
178        try:
179            expression_to_evaluate = constraint_text.replace(param_str, "1.0")
180            eval(expression_to_evaluate)
181        except Exception:
182            # Too many cases to cover individually, just a blanket
183            # Exception should be sufficient
184            # Note that in current numpy things like sqrt(-1) don't
185            # raise but just return warnings
186            return False
187
188        return True
189
190    def constraint(self):
191        """
192        Return the generated constraint as tuple (model1, param1, operator, constraint)
193        """
194        return (self.txtName1.text(), self.cbParam1.currentText(), self.cbOperator.currentText(), self.txtConstraint.text())
195
196    def onHelp(self):
197        """
198        Display related help section
199        """
200        try:
201            help_location = GuiUtils.HELP_DIRECTORY_LOCATION + \
202            "/user/sasgui/perspectives/fitting/fitting_help.html#simultaneous-fits-with-constraints"
203            webbrowser.open('file://' + os.path.realpath(help_location))
204        except AttributeError:
205            # No manager defined - testing and standalone runs
206            pass
207
208
209
Note: See TracBrowser for help on using the repository browser.