[fa81e94] | 1 | import sys |
---|
| 2 | import logging |
---|
| 3 | import pylab |
---|
| 4 | import numpy as np |
---|
| 5 | |
---|
| 6 | from PyQt5 import QtGui, QtCore, QtWidgets |
---|
| 7 | |
---|
| 8 | # sas-global |
---|
| 9 | import sas.qtgui.Utilities.GuiUtils as GuiUtils |
---|
| 10 | |
---|
| 11 | # pr inversion GUI elements |
---|
| 12 | from .InversionUtils import WIDGETS |
---|
| 13 | from .UI.TabbedInversionUI import Ui_PrInversion |
---|
| 14 | from .InversionLogic import InversionLogic |
---|
| 15 | |
---|
| 16 | # pr inversion calculation elements |
---|
| 17 | from sas.sascalc.pr.invertor import Invertor |
---|
| 18 | |
---|
| 19 | def is_float(value): |
---|
| 20 | """Converts text input values to floats. Empty strings throw ValueError""" |
---|
| 21 | try: |
---|
| 22 | return float(value) |
---|
| 23 | except ValueError: |
---|
| 24 | return 0.0 |
---|
| 25 | |
---|
[50bfab0] | 26 | NUMBER_OF_TERMS = 10 |
---|
| 27 | REGULARIZATION = 0.0001 |
---|
| 28 | BACKGROUND_INPUT = 0.0 |
---|
| 29 | MAX_DIST = 140.0 |
---|
[edd6720] | 30 | DICT_KEYS = ["Calculator", "PrPlot", "DataPlot"] |
---|
[47bf906] | 31 | |
---|
[fa81e94] | 32 | |
---|
| 33 | # TODO: Update help with batch capabilities |
---|
| 34 | # TODO: Method to export results in some meaningful way |
---|
[d4881f6a] | 35 | class InversionWindow(QtWidgets.QDialog, Ui_PrInversion): |
---|
[fa81e94] | 36 | """ |
---|
| 37 | The main window for the P(r) Inversion perspective. |
---|
| 38 | """ |
---|
| 39 | |
---|
| 40 | name = "Inversion" |
---|
[f1ec901] | 41 | estimateSignal = QtCore.pyqtSignal(tuple) |
---|
| 42 | estimateNTSignal = QtCore.pyqtSignal(tuple) |
---|
| 43 | calculateSignal = QtCore.pyqtSignal(tuple) |
---|
[fa81e94] | 44 | |
---|
| 45 | def __init__(self, parent=None, data=None): |
---|
| 46 | super(InversionWindow, self).__init__() |
---|
| 47 | self.setupUi(self) |
---|
| 48 | |
---|
| 49 | self.setWindowTitle("P(r) Inversion Perspective") |
---|
| 50 | |
---|
| 51 | self._manager = parent |
---|
| 52 | self.communicate = GuiUtils.Communicate() |
---|
| 53 | |
---|
| 54 | self.logic = InversionLogic() |
---|
| 55 | |
---|
| 56 | # The window should not close |
---|
| 57 | self._allow_close = False |
---|
| 58 | |
---|
[47bf906] | 59 | # Visible data set items |
---|
[fa81e94] | 60 | # current QStandardItem showing on the panel |
---|
| 61 | self._data = None |
---|
[47bf906] | 62 | # Reference to Dmax window for self._data |
---|
| 63 | self.dmaxWindow = None |
---|
| 64 | # p(r) calculator for self._data |
---|
[fa81e94] | 65 | self._calculator = Invertor() |
---|
[304e42f] | 66 | # Default to background estimate |
---|
| 67 | self._calculator.set_est_bck(True) |
---|
[47bf906] | 68 | # plots of self._data |
---|
| 69 | self.pr_plot = None |
---|
| 70 | self.data_plot = None |
---|
[e51e078] | 71 | # suggested nTerms |
---|
| 72 | self.nTermsSuggested = NUMBER_OF_TERMS |
---|
[47bf906] | 73 | |
---|
| 74 | # Calculation threads used by all data items |
---|
[fa81e94] | 75 | self.calc_thread = None |
---|
| 76 | self.estimation_thread = None |
---|
[edd6720] | 77 | self.estimation_thread_nt = None |
---|
[fa81e94] | 78 | |
---|
[47bf906] | 79 | # Mapping for all data items |
---|
| 80 | # list mapping data to all parameters |
---|
[fa81e94] | 81 | self._data_list = {} |
---|
| 82 | if not isinstance(data, list): |
---|
| 83 | data_list = [data] |
---|
| 84 | if data is not None: |
---|
| 85 | for datum in data_list: |
---|
[e51e078] | 86 | self.updateDataList(datum) |
---|
[f1ec901] | 87 | |
---|
[e51e078] | 88 | self.enableButtons() |
---|
[8f83719f] | 89 | |
---|
[fa81e94] | 90 | self.model = QtGui.QStandardItemModel(self) |
---|
| 91 | self.mapper = QtWidgets.QDataWidgetMapper(self) |
---|
[8f83719f] | 92 | |
---|
| 93 | # Add validators |
---|
| 94 | self.setupValidators() |
---|
[fa81e94] | 95 | # Link user interactions with methods |
---|
| 96 | self.setupLinks() |
---|
| 97 | # Set values |
---|
| 98 | self.setupModel() |
---|
| 99 | # Set up the Widget Map |
---|
| 100 | self.setupMapper() |
---|
| 101 | # Set base window state |
---|
| 102 | self.setupWindow() |
---|
| 103 | |
---|
| 104 | ###################################################################### |
---|
| 105 | # Base Perspective Class Definitions |
---|
| 106 | |
---|
| 107 | def communicator(self): |
---|
| 108 | return self.communicate |
---|
| 109 | |
---|
| 110 | def allowBatch(self): |
---|
| 111 | return True |
---|
| 112 | |
---|
| 113 | def setClosable(self, value=True): |
---|
| 114 | """ |
---|
| 115 | Allow outsiders close this widget |
---|
| 116 | """ |
---|
| 117 | assert isinstance(value, bool) |
---|
| 118 | self._allow_close = value |
---|
| 119 | |
---|
| 120 | def closeEvent(self, event): |
---|
| 121 | """ |
---|
| 122 | Overwrite QDialog close method to allow for custom widget close |
---|
| 123 | """ |
---|
| 124 | if self._allow_close: |
---|
| 125 | # reset the closability flag |
---|
| 126 | self.setClosable(value=False) |
---|
[d4881f6a] | 127 | # Tell the MdiArea to close the container |
---|
| 128 | self.parentWidget().close() |
---|
[fa81e94] | 129 | event.accept() |
---|
| 130 | else: |
---|
| 131 | event.ignore() |
---|
| 132 | # Maybe we should just minimize |
---|
| 133 | self.setWindowState(QtCore.Qt.WindowMinimized) |
---|
| 134 | |
---|
| 135 | ###################################################################### |
---|
| 136 | # Initialization routines |
---|
| 137 | |
---|
| 138 | def setupLinks(self): |
---|
| 139 | """Connect the use controls to their appropriate methods""" |
---|
| 140 | self.dataList.currentIndexChanged.connect(self.displayChange) |
---|
[f1ec901] | 141 | self.calculateAllButton.clicked.connect(self.startThreadAll) |
---|
| 142 | self.calculateThisButton.clicked.connect(self.startThread) |
---|
[fa81e94] | 143 | self.removeButton.clicked.connect(self.removeData) |
---|
| 144 | self.helpButton.clicked.connect(self.help) |
---|
| 145 | self.estimateBgd.toggled.connect(self.toggleBgd) |
---|
| 146 | self.manualBgd.toggled.connect(self.toggleBgd) |
---|
| 147 | self.regConstantSuggestionButton.clicked.connect(self.acceptAlpha) |
---|
| 148 | self.noOfTermsSuggestionButton.clicked.connect(self.acceptNoTerms) |
---|
| 149 | self.explorerButton.clicked.connect(self.openExplorerWindow) |
---|
[f1ec901] | 150 | |
---|
| 151 | self.backgroundInput.editingFinished.connect( |
---|
[441a03f] | 152 | lambda: self.set_background(is_float(self.backgroundInput.text()))) |
---|
[f1ec901] | 153 | self.minQInput.editingFinished.connect( |
---|
[8f83719f] | 154 | lambda: self._calculator.set_qmin(is_float(self.minQInput.text()))) |
---|
[f1ec901] | 155 | self.regularizationConstantInput.editingFinished.connect( |
---|
[8f83719f] | 156 | lambda: self._calculator.set_alpha(is_float(self.regularizationConstantInput.text()))) |
---|
[f1ec901] | 157 | self.maxDistanceInput.editingFinished.connect( |
---|
[8f83719f] | 158 | lambda: self._calculator.set_dmax(is_float(self.maxDistanceInput.text()))) |
---|
[f1ec901] | 159 | self.maxQInput.editingFinished.connect( |
---|
[8f83719f] | 160 | lambda: self._calculator.set_qmax(is_float(self.maxQInput.text()))) |
---|
[f1ec901] | 161 | self.slitHeightInput.editingFinished.connect( |
---|
[8f83719f] | 162 | lambda: self._calculator.set_slit_height(is_float(self.slitHeightInput.text()))) |
---|
[f1ec901] | 163 | self.slitWidthInput.editingFinished.connect( |
---|
[8f83719f] | 164 | lambda: self._calculator.set_slit_width(is_float(self.slitHeightInput.text()))) |
---|
[f1ec901] | 165 | |
---|
[fa81e94] | 166 | self.model.itemChanged.connect(self.model_changed) |
---|
[f1ec901] | 167 | self.estimateNTSignal.connect(self._estimateNTUpdate) |
---|
| 168 | self.estimateSignal.connect(self._estimateUpdate) |
---|
| 169 | self.calculateSignal.connect(self._calculateUpdate) |
---|
[fa81e94] | 170 | |
---|
| 171 | def setupMapper(self): |
---|
| 172 | # Set up the mapper. |
---|
| 173 | self.mapper.setOrientation(QtCore.Qt.Vertical) |
---|
| 174 | self.mapper.setModel(self.model) |
---|
| 175 | |
---|
| 176 | # Filename |
---|
| 177 | self.mapper.addMapping(self.dataList, WIDGETS.W_FILENAME) |
---|
| 178 | # Background |
---|
| 179 | self.mapper.addMapping(self.backgroundInput, WIDGETS.W_BACKGROUND_INPUT) |
---|
| 180 | self.mapper.addMapping(self.estimateBgd, WIDGETS.W_ESTIMATE) |
---|
| 181 | self.mapper.addMapping(self.manualBgd, WIDGETS.W_MANUAL_INPUT) |
---|
| 182 | |
---|
| 183 | # Qmin/Qmax |
---|
| 184 | self.mapper.addMapping(self.minQInput, WIDGETS.W_QMIN) |
---|
| 185 | self.mapper.addMapping(self.maxQInput, WIDGETS.W_QMAX) |
---|
| 186 | |
---|
| 187 | # Slit Parameter items |
---|
| 188 | self.mapper.addMapping(self.slitWidthInput, WIDGETS.W_SLIT_WIDTH) |
---|
| 189 | self.mapper.addMapping(self.slitHeightInput, WIDGETS.W_SLIT_HEIGHT) |
---|
| 190 | |
---|
| 191 | # Parameter Items |
---|
[8f83719f] | 192 | self.mapper.addMapping(self.regularizationConstantInput, WIDGETS.W_REGULARIZATION) |
---|
| 193 | self.mapper.addMapping(self.regConstantSuggestionButton, WIDGETS.W_REGULARIZATION_SUGGEST) |
---|
[fa81e94] | 194 | self.mapper.addMapping(self.explorerButton, WIDGETS.W_EXPLORE) |
---|
| 195 | self.mapper.addMapping(self.maxDistanceInput, WIDGETS.W_MAX_DIST) |
---|
| 196 | self.mapper.addMapping(self.noOfTermsInput, WIDGETS.W_NO_TERMS) |
---|
[8f83719f] | 197 | self.mapper.addMapping(self.noOfTermsSuggestionButton, WIDGETS.W_NO_TERMS_SUGGEST) |
---|
[fa81e94] | 198 | |
---|
| 199 | # Output |
---|
| 200 | self.mapper.addMapping(self.rgValue, WIDGETS.W_RG) |
---|
| 201 | self.mapper.addMapping(self.iQ0Value, WIDGETS.W_I_ZERO) |
---|
| 202 | self.mapper.addMapping(self.backgroundValue, WIDGETS.W_BACKGROUND_OUTPUT) |
---|
| 203 | self.mapper.addMapping(self.computationTimeValue, WIDGETS.W_COMP_TIME) |
---|
| 204 | self.mapper.addMapping(self.chiDofValue, WIDGETS.W_CHI_SQUARED) |
---|
| 205 | self.mapper.addMapping(self.oscillationValue, WIDGETS.W_OSCILLATION) |
---|
| 206 | self.mapper.addMapping(self.posFractionValue, WIDGETS.W_POS_FRACTION) |
---|
[8f83719f] | 207 | self.mapper.addMapping(self.sigmaPosFractionValue, WIDGETS.W_SIGMA_POS_FRACTION) |
---|
[fa81e94] | 208 | |
---|
| 209 | # Main Buttons |
---|
| 210 | self.mapper.addMapping(self.removeButton, WIDGETS.W_REMOVE) |
---|
[f1ec901] | 211 | self.mapper.addMapping(self.calculateAllButton, WIDGETS.W_CALCULATE_ALL) |
---|
[8f83719f] | 212 | self.mapper.addMapping(self.calculateThisButton, WIDGETS.W_CALCULATE_VISIBLE) |
---|
[fa81e94] | 213 | self.mapper.addMapping(self.helpButton, WIDGETS.W_HELP) |
---|
| 214 | |
---|
| 215 | self.mapper.toFirst() |
---|
| 216 | |
---|
| 217 | def setupModel(self): |
---|
| 218 | """ |
---|
| 219 | Update boxes with initial values |
---|
| 220 | """ |
---|
[50bfab0] | 221 | item = QtGui.QStandardItem(str(BACKGROUND_INPUT)) |
---|
[fa81e94] | 222 | self.model.setItem(WIDGETS.W_BACKGROUND_INPUT, item) |
---|
| 223 | item = QtGui.QStandardItem("") |
---|
| 224 | self.model.setItem(WIDGETS.W_QMIN, item) |
---|
| 225 | item = QtGui.QStandardItem("") |
---|
| 226 | self.model.setItem(WIDGETS.W_QMAX, item) |
---|
| 227 | item = QtGui.QStandardItem("") |
---|
| 228 | self.model.setItem(WIDGETS.W_SLIT_WIDTH, item) |
---|
| 229 | item = QtGui.QStandardItem("") |
---|
| 230 | self.model.setItem(WIDGETS.W_SLIT_HEIGHT, item) |
---|
[50bfab0] | 231 | item = QtGui.QStandardItem(str(NUMBER_OF_TERMS)) |
---|
[fa81e94] | 232 | self.model.setItem(WIDGETS.W_NO_TERMS, item) |
---|
[50bfab0] | 233 | item = QtGui.QStandardItem(str(REGULARIZATION)) |
---|
[fa81e94] | 234 | self.model.setItem(WIDGETS.W_REGULARIZATION, item) |
---|
[50bfab0] | 235 | item = QtGui.QStandardItem(str(MAX_DIST)) |
---|
[fa81e94] | 236 | self.model.setItem(WIDGETS.W_MAX_DIST, item) |
---|
| 237 | item = QtGui.QStandardItem("") |
---|
| 238 | self.model.setItem(WIDGETS.W_RG, item) |
---|
| 239 | item = QtGui.QStandardItem("") |
---|
| 240 | self.model.setItem(WIDGETS.W_I_ZERO, item) |
---|
| 241 | item = QtGui.QStandardItem("") |
---|
| 242 | self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT, item) |
---|
| 243 | item = QtGui.QStandardItem("") |
---|
| 244 | self.model.setItem(WIDGETS.W_COMP_TIME, item) |
---|
| 245 | item = QtGui.QStandardItem("") |
---|
| 246 | self.model.setItem(WIDGETS.W_CHI_SQUARED, item) |
---|
| 247 | item = QtGui.QStandardItem("") |
---|
| 248 | self.model.setItem(WIDGETS.W_OSCILLATION, item) |
---|
| 249 | item = QtGui.QStandardItem("") |
---|
| 250 | self.model.setItem(WIDGETS.W_POS_FRACTION, item) |
---|
| 251 | item = QtGui.QStandardItem("") |
---|
| 252 | self.model.setItem(WIDGETS.W_SIGMA_POS_FRACTION, item) |
---|
| 253 | |
---|
| 254 | def setupWindow(self): |
---|
| 255 | """Initialize base window state on init""" |
---|
| 256 | self.enableButtons() |
---|
| 257 | self.estimateBgd.setChecked(True) |
---|
| 258 | |
---|
[8f83719f] | 259 | def setupValidators(self): |
---|
| 260 | """Apply validators to editable line edits""" |
---|
| 261 | self.noOfTermsInput.setValidator(QtGui.QIntValidator()) |
---|
| 262 | self.regularizationConstantInput.setValidator(GuiUtils.DoubleValidator()) |
---|
| 263 | self.maxDistanceInput.setValidator(GuiUtils.DoubleValidator()) |
---|
| 264 | self.minQInput.setValidator(GuiUtils.DoubleValidator()) |
---|
| 265 | self.maxQInput.setValidator(GuiUtils.DoubleValidator()) |
---|
| 266 | self.slitHeightInput.setValidator(GuiUtils.DoubleValidator()) |
---|
| 267 | self.slitWidthInput.setValidator(GuiUtils.DoubleValidator()) |
---|
| 268 | |
---|
[fa81e94] | 269 | ###################################################################### |
---|
| 270 | # Methods for updating GUI |
---|
| 271 | |
---|
| 272 | def enableButtons(self): |
---|
| 273 | """ |
---|
| 274 | Enable buttons when data is present, else disable them |
---|
| 275 | """ |
---|
[8f83719f] | 276 | self.calculateAllButton.setEnabled(self.logic.data_is_loaded) |
---|
| 277 | self.calculateThisButton.setEnabled(self.logic.data_is_loaded) |
---|
[fa81e94] | 278 | self.removeButton.setEnabled(self.logic.data_is_loaded) |
---|
| 279 | self.explorerButton.setEnabled(self.logic.data_is_loaded) |
---|
[b685c7b] | 280 | self.regConstantSuggestionButton.setEnabled( |
---|
| 281 | self._calculator.suggested_alpha != self._calculator.alpha) |
---|
| 282 | self.noOfTermsSuggestionButton.setEnabled( |
---|
| 283 | self._calculator.nfunc != self.nTermsSuggested) |
---|
[fa81e94] | 284 | |
---|
| 285 | def populateDataComboBox(self, filename, data_ref): |
---|
| 286 | """ |
---|
| 287 | Append a new file name to the data combobox |
---|
| 288 | :param filename: data filename |
---|
| 289 | :param data_ref: QStandardItem reference for data set to be added |
---|
| 290 | """ |
---|
[6a3e1fe] | 291 | self.dataList.addItem(filename, data_ref) |
---|
[fa81e94] | 292 | |
---|
| 293 | def acceptNoTerms(self): |
---|
| 294 | """Send estimated no of terms to input""" |
---|
| 295 | self.model.setItem(WIDGETS.W_NO_TERMS, QtGui.QStandardItem( |
---|
| 296 | self.noOfTermsSuggestionButton.text())) |
---|
| 297 | |
---|
| 298 | def acceptAlpha(self): |
---|
| 299 | """Send estimated alpha to input""" |
---|
| 300 | self.model.setItem(WIDGETS.W_REGULARIZATION, QtGui.QStandardItem( |
---|
| 301 | self.regConstantSuggestionButton.text())) |
---|
| 302 | |
---|
[edd6720] | 303 | def displayChange(self, data_index=0): |
---|
[47bf906] | 304 | """Switch to another item in the data list""" |
---|
[edd6720] | 305 | self.updateDataList(self._data) |
---|
| 306 | self.setCurrentData(self.dataList.itemData(data_index)) |
---|
[fa81e94] | 307 | |
---|
| 308 | ###################################################################### |
---|
| 309 | # GUI Interaction Events |
---|
| 310 | |
---|
| 311 | def update_calculator(self): |
---|
| 312 | """Update all p(r) params""" |
---|
[edd6720] | 313 | self._calculator.set_x(self.logic.data.x) |
---|
| 314 | self._calculator.set_y(self.logic.data.y) |
---|
| 315 | self._calculator.set_err(self.logic.data.dy) |
---|
[441a03f] | 316 | self.set_background(self.backgroundInput.text()) |
---|
| 317 | |
---|
| 318 | def set_background(self, value): |
---|
| 319 | self._calculator.background = is_float(value) |
---|
[fa81e94] | 320 | |
---|
| 321 | def model_changed(self): |
---|
| 322 | """Update the values when user makes changes""" |
---|
| 323 | if not self.mapper: |
---|
| 324 | msg = "Unable to update P{r}. The connection between the main GUI " |
---|
| 325 | msg += "and P(r) was severed. Attempting to restart P(r)." |
---|
| 326 | logging.warning(msg) |
---|
| 327 | self.setClosable(True) |
---|
| 328 | self.close() |
---|
| 329 | InversionWindow.__init__(self.parent(), list(self._data_list.keys())) |
---|
| 330 | exit(0) |
---|
| 331 | if self.pr_plot is not None: |
---|
| 332 | title = self.pr_plot.name |
---|
[6a3e1fe] | 333 | GuiUtils.updateModelItemWithPlot(self._data, self.pr_plot, title) |
---|
[fa81e94] | 334 | if self.data_plot is not None: |
---|
| 335 | title = self.data_plot.name |
---|
[6a3e1fe] | 336 | GuiUtils.updateModelItemWithPlot(self._data, self.data_plot, title) |
---|
[8f83719f] | 337 | if self.dmaxWindow is not None: |
---|
[47bf906] | 338 | self.dmaxWindow.pr_state = self._calculator |
---|
| 339 | self.dmaxWindow.nfunc = self.getNFunc() |
---|
| 340 | self.dmaxWindow.modelChanged() |
---|
[edd6720] | 341 | self.mapper.toLast() |
---|
[fa81e94] | 342 | |
---|
| 343 | def help(self): |
---|
| 344 | """ |
---|
| 345 | Open the P(r) Inversion help browser |
---|
| 346 | """ |
---|
[e90988c] | 347 | tree_location = "/user/sasgui/perspectives/pr/pr_help.html" |
---|
[fa81e94] | 348 | |
---|
| 349 | # Actual file anchor will depend on the combo box index |
---|
| 350 | # Note that we can be clusmy here, since bad current_fitter_id |
---|
| 351 | # will just make the page displayed from the top |
---|
[e90988c] | 352 | self._manager.showHelp(tree_location) |
---|
[fa81e94] | 353 | |
---|
| 354 | def toggleBgd(self): |
---|
| 355 | """ |
---|
| 356 | Toggle the background between manual and estimated |
---|
| 357 | """ |
---|
[edd6720] | 358 | if self.estimateBgd.isChecked(): |
---|
| 359 | self.manualBgd.setChecked(False) |
---|
[fa81e94] | 360 | self.backgroundInput.setEnabled(False) |
---|
[304e42f] | 361 | self._calculator.set_est_bck = True |
---|
[edd6720] | 362 | elif self.manualBgd.isChecked(): |
---|
| 363 | self.estimateBgd.setChecked(False) |
---|
[fa81e94] | 364 | self.backgroundInput.setEnabled(True) |
---|
[304e42f] | 365 | self._calculator.set_est_bck = False |
---|
[441a03f] | 366 | else: |
---|
| 367 | pass |
---|
[fa81e94] | 368 | |
---|
| 369 | def openExplorerWindow(self): |
---|
| 370 | """ |
---|
| 371 | Open the Explorer window to see correlations between params and results |
---|
| 372 | """ |
---|
| 373 | from .DMaxExplorerWidget import DmaxWindow |
---|
| 374 | self.dmaxWindow = DmaxWindow(self._calculator, self.getNFunc(), self) |
---|
| 375 | self.dmaxWindow.show() |
---|
| 376 | |
---|
| 377 | ###################################################################### |
---|
| 378 | # Response Actions |
---|
| 379 | |
---|
| 380 | def setData(self, data_item=None, is_batch=False): |
---|
| 381 | """ |
---|
| 382 | Assign new data set(s) to the P(r) perspective |
---|
| 383 | Obtain a QStandardItem object and parse it to get Data1D/2D |
---|
| 384 | Pass it over to the calculator |
---|
| 385 | """ |
---|
| 386 | assert data_item is not None |
---|
| 387 | |
---|
| 388 | if not isinstance(data_item, list): |
---|
| 389 | msg = "Incorrect type passed to the P(r) Perspective" |
---|
[47bf906] | 390 | raise AttributeError(msg) |
---|
[fa81e94] | 391 | |
---|
| 392 | for data in data_item: |
---|
[8f83719f] | 393 | if data in self._data_list.keys(): |
---|
| 394 | # Don't add data if it's already in |
---|
[edd6720] | 395 | continue |
---|
[fa81e94] | 396 | # Create initial internal mappings |
---|
[edd6720] | 397 | self.logic.data = GuiUtils.dataFromItem(data) |
---|
[e51e078] | 398 | # Estimate q range |
---|
| 399 | qmin, qmax = self.logic.computeDataRange() |
---|
| 400 | self._calculator.set_qmin(qmin) |
---|
| 401 | self._calculator.set_qmax(qmax) |
---|
| 402 | self.updateDataList(data) |
---|
[edd6720] | 403 | self.populateDataComboBox(self.logic.data.filename, data) |
---|
| 404 | self.dataList.setCurrentIndex(len(self.dataList) - 1) |
---|
| 405 | self.setCurrentData(data) |
---|
[fa81e94] | 406 | |
---|
[47bf906] | 407 | def updateDataList(self, dataRef): |
---|
| 408 | """Save the current data state of the window into self._data_list""" |
---|
[e51e078] | 409 | if dataRef is None: |
---|
| 410 | return |
---|
[47bf906] | 411 | self._data_list[dataRef] = { |
---|
[e51e078] | 412 | DICT_KEYS[0]: self._calculator, |
---|
| 413 | DICT_KEYS[1]: self.pr_plot, |
---|
[edd6720] | 414 | DICT_KEYS[2]: self.data_plot |
---|
[47bf906] | 415 | } |
---|
| 416 | |
---|
[fa81e94] | 417 | def getNFunc(self): |
---|
| 418 | """Get the n_func value from the GUI object""" |
---|
[50bfab0] | 419 | try: |
---|
| 420 | nfunc = int(self.noOfTermsInput.text()) |
---|
| 421 | except ValueError: |
---|
[edd6720] | 422 | logging.error("Incorrect number of terms specified: %s" |
---|
| 423 | %self.noOfTermsInput.text()) |
---|
[50bfab0] | 424 | self.noOfTermsInput.setText(str(NUMBER_OF_TERMS)) |
---|
| 425 | nfunc = NUMBER_OF_TERMS |
---|
| 426 | return nfunc |
---|
[fa81e94] | 427 | |
---|
| 428 | def setCurrentData(self, data_ref): |
---|
[47bf906] | 429 | """Get the data by reference and display as necessary""" |
---|
[304e42f] | 430 | if data_ref is None: |
---|
| 431 | return |
---|
[fa81e94] | 432 | if not isinstance(data_ref, QtGui.QStandardItem): |
---|
| 433 | msg = "Incorrect type passed to the P(r) Perspective" |
---|
[e51e078] | 434 | raise AttributeError(msg) |
---|
[fa81e94] | 435 | # Data references |
---|
| 436 | self._data = data_ref |
---|
[edd6720] | 437 | self.logic.data = GuiUtils.dataFromItem(data_ref) |
---|
[47bf906] | 438 | self._calculator = self._data_list[data_ref].get(DICT_KEYS[0]) |
---|
| 439 | self.pr_plot = self._data_list[data_ref].get(DICT_KEYS[1]) |
---|
| 440 | self.data_plot = self._data_list[data_ref].get(DICT_KEYS[2]) |
---|
[edd6720] | 441 | self.performEstimate() |
---|
[e51e078] | 442 | |
---|
| 443 | def updateGuiValues(self): |
---|
| 444 | pr = self._calculator |
---|
| 445 | out = self._calculator.out |
---|
| 446 | cov = self._calculator.cov |
---|
| 447 | elapsed = self._calculator.elapsed |
---|
| 448 | alpha = self._calculator.suggested_alpha |
---|
| 449 | self.model.setItem(WIDGETS.W_QMIN, |
---|
| 450 | QtGui.QStandardItem("{:.4g}".format(pr.get_qmin()))) |
---|
| 451 | self.model.setItem(WIDGETS.W_QMAX, |
---|
| 452 | QtGui.QStandardItem("{:.4g}".format(pr.get_qmax()))) |
---|
| 453 | self.model.setItem(WIDGETS.W_BACKGROUND_INPUT, |
---|
[304e42f] | 454 | QtGui.QStandardItem("{:.3f}".format(pr.background))) |
---|
[e51e078] | 455 | self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT, |
---|
| 456 | QtGui.QStandardItem("{:.3g}".format(pr.background))) |
---|
| 457 | self.model.setItem(WIDGETS.W_COMP_TIME, |
---|
| 458 | QtGui.QStandardItem("{:.4g}".format(elapsed))) |
---|
[b685c7b] | 459 | self.regConstantSuggestionButton.setText("{:-3.2g}".format(alpha)) |
---|
| 460 | self.noOfTermsSuggestionButton.setText( |
---|
| 461 | "{:n}".format(self.nTermsSuggested)) |
---|
[e51e078] | 462 | self.model.setItem(WIDGETS.W_COMP_TIME, |
---|
| 463 | QtGui.QStandardItem("{:.2g}".format(elapsed))) |
---|
| 464 | |
---|
[304e42f] | 465 | if isinstance(pr.chi2, np.ndarray): |
---|
[e51e078] | 466 | self.model.setItem(WIDGETS.W_CHI_SQUARED, |
---|
| 467 | QtGui.QStandardItem("{:.3g}".format(pr.chi2[0]))) |
---|
| 468 | if out is not None: |
---|
| 469 | self.model.setItem(WIDGETS.W_RG, |
---|
| 470 | QtGui.QStandardItem("{:.3g}".format(pr.rg(out)))) |
---|
| 471 | self.model.setItem(WIDGETS.W_I_ZERO, |
---|
| 472 | QtGui.QStandardItem( |
---|
| 473 | "{:.3g}".format(pr.iq0(out)))) |
---|
| 474 | self.model.setItem(WIDGETS.W_OSCILLATION, QtGui.QStandardItem( |
---|
| 475 | "{:.3g}".format(pr.oscillations(out)))) |
---|
| 476 | self.model.setItem(WIDGETS.W_POS_FRACTION, QtGui.QStandardItem( |
---|
| 477 | "{:.3g}".format(pr.get_positive(out)))) |
---|
| 478 | if cov is not None: |
---|
| 479 | self.model.setItem(WIDGETS.W_SIGMA_POS_FRACTION, |
---|
| 480 | QtGui.QStandardItem( |
---|
| 481 | "{:.3g}".format( |
---|
| 482 | pr.get_pos_err(out, cov)))) |
---|
[b685c7b] | 483 | self.enableButtons() |
---|
[47bf906] | 484 | |
---|
| 485 | def removeData(self): |
---|
| 486 | """Remove the existing data reference from the P(r) Persepective""" |
---|
| 487 | if self.dmaxWindow is not None: |
---|
[edd6720] | 488 | self.dmaxWindow.close() |
---|
[47bf906] | 489 | self.dmaxWindow = None |
---|
| 490 | self.dataList.removeItem(self.dataList.currentIndex()) |
---|
| 491 | self._data_list.pop(self._data) |
---|
[e51e078] | 492 | # Last file removed |
---|
| 493 | if len(self._data_list) == 0: |
---|
[b685c7b] | 494 | self.pr_plot = None |
---|
| 495 | self.data_plot = None |
---|
[e51e078] | 496 | self._calculator = Invertor() |
---|
[edd6720] | 497 | self.logic.data = None |
---|
[b685c7b] | 498 | self.nTermsSuggested = NUMBER_OF_TERMS |
---|
| 499 | self.noOfTermsSuggestionButton.setText("{:n}".format( |
---|
| 500 | self.nTermsSuggested)) |
---|
| 501 | self.regConstantSuggestionButton.setText("{:-3.2g}".format( |
---|
| 502 | REGULARIZATION)) |
---|
[edd6720] | 503 | self.updateGuiValues() |
---|
[b685c7b] | 504 | self.setupModel() |
---|
[ba4e3ba] | 505 | else: |
---|
| 506 | self.dataList.setCurrentIndex(0) |
---|
| 507 | self.updateGuiValues() |
---|
[fa81e94] | 508 | |
---|
| 509 | ###################################################################### |
---|
| 510 | # Thread Creators |
---|
| 511 | def startThreadAll(self): |
---|
[e51e078] | 512 | for data_ref in self._data_list.keys(): |
---|
| 513 | self.setCurrentData(data_ref) |
---|
[fa81e94] | 514 | self.startThread() |
---|
| 515 | |
---|
| 516 | def startThread(self): |
---|
| 517 | """ |
---|
| 518 | Start a calculation thread |
---|
| 519 | """ |
---|
| 520 | from .Thread import CalcPr |
---|
| 521 | |
---|
| 522 | # Set data before running the calculations |
---|
| 523 | self.update_calculator() |
---|
| 524 | |
---|
| 525 | # If a thread is already started, stop it |
---|
| 526 | if self.calc_thread is not None and self.calc_thread.isrunning(): |
---|
| 527 | self.calc_thread.stop() |
---|
| 528 | pr = self._calculator.clone() |
---|
| 529 | nfunc = self.getNFunc() |
---|
| 530 | self.calc_thread = CalcPr(pr, nfunc, |
---|
| 531 | error_func=self._threadError, |
---|
[f1ec901] | 532 | completefn=self._calculateCompleted, |
---|
| 533 | updatefn=None) |
---|
[fa81e94] | 534 | self.calc_thread.queue() |
---|
| 535 | self.calc_thread.ready(2.5) |
---|
| 536 | |
---|
| 537 | def performEstimateNT(self): |
---|
| 538 | """ |
---|
[f1ec901] | 539 | Perform parameter estimation |
---|
[fa81e94] | 540 | """ |
---|
| 541 | from .Thread import EstimateNT |
---|
| 542 | |
---|
[edd6720] | 543 | self.update_calculator() |
---|
| 544 | |
---|
[fa81e94] | 545 | # If a thread is already started, stop it |
---|
[edd6720] | 546 | if (self.estimation_thread_nt is not None and |
---|
| 547 | self.estimation_thread_nt.isrunning()): |
---|
| 548 | self.estimation_thread_nt.stop() |
---|
[fa81e94] | 549 | pr = self._calculator.clone() |
---|
| 550 | # Skip the slit settings for the estimation |
---|
| 551 | # It slows down the application and it doesn't change the estimates |
---|
| 552 | pr.slit_height = 0.0 |
---|
| 553 | pr.slit_width = 0.0 |
---|
| 554 | nfunc = self.getNFunc() |
---|
[f1ec901] | 555 | |
---|
[edd6720] | 556 | self.estimation_thread_nt = EstimateNT(pr, nfunc, |
---|
[fa81e94] | 557 | error_func=self._threadError, |
---|
| 558 | completefn=self._estimateNTCompleted, |
---|
| 559 | updatefn=None) |
---|
[edd6720] | 560 | self.estimation_thread_nt.queue() |
---|
| 561 | self.estimation_thread_nt.ready(2.5) |
---|
[fa81e94] | 562 | |
---|
| 563 | def performEstimate(self): |
---|
| 564 | """ |
---|
| 565 | Perform parameter estimation |
---|
| 566 | """ |
---|
| 567 | from .Thread import EstimatePr |
---|
| 568 | |
---|
| 569 | # If a thread is already started, stop it |
---|
| 570 | if (self.estimation_thread is not None and |
---|
| 571 | self.estimation_thread.isrunning()): |
---|
| 572 | self.estimation_thread.stop() |
---|
[edd6720] | 573 | self.estimation_thread = EstimatePr(self._calculator.clone(), |
---|
| 574 | self.getNFunc(), |
---|
[fa81e94] | 575 | error_func=self._threadError, |
---|
| 576 | completefn=self._estimateCompleted, |
---|
| 577 | updatefn=None) |
---|
| 578 | self.estimation_thread.queue() |
---|
| 579 | self.estimation_thread.ready(2.5) |
---|
| 580 | |
---|
| 581 | ###################################################################### |
---|
| 582 | # Thread Complete |
---|
| 583 | |
---|
| 584 | def _estimateCompleted(self, alpha, message, elapsed): |
---|
[f1ec901] | 585 | ''' Send a signal to the main thread for model update''' |
---|
| 586 | self.estimateSignal.emit((alpha, message, elapsed)) |
---|
| 587 | |
---|
| 588 | def _estimateUpdate(self, output_tuple): |
---|
[fa81e94] | 589 | """ |
---|
| 590 | Parameter estimation completed, |
---|
| 591 | display the results to the user |
---|
| 592 | |
---|
| 593 | :param alpha: estimated best alpha |
---|
| 594 | :param elapsed: computation time |
---|
| 595 | """ |
---|
[f1ec901] | 596 | alpha, message, elapsed = output_tuple |
---|
[fa81e94] | 597 | if message: |
---|
| 598 | logging.info(message) |
---|
| 599 | self.performEstimateNT() |
---|
| 600 | |
---|
| 601 | def _estimateNTCompleted(self, nterms, alpha, message, elapsed): |
---|
[f1ec901] | 602 | ''' Send a signal to the main thread for model update''' |
---|
| 603 | self.estimateNTSignal.emit((nterms, alpha, message, elapsed)) |
---|
| 604 | |
---|
| 605 | def _estimateNTUpdate(self, output_tuple): |
---|
[fa81e94] | 606 | """ |
---|
| 607 | Parameter estimation completed, |
---|
| 608 | display the results to the user |
---|
| 609 | |
---|
| 610 | :param alpha: estimated best alpha |
---|
| 611 | :param nterms: estimated number of terms |
---|
| 612 | :param elapsed: computation time |
---|
| 613 | """ |
---|
[f1ec901] | 614 | nterms, alpha, message, elapsed = output_tuple |
---|
[e51e078] | 615 | self._calculator.elapsed = elapsed |
---|
| 616 | self._calculator.suggested_alpha = alpha |
---|
| 617 | self.nTermsSuggested = nterms |
---|
[fa81e94] | 618 | # Save useful info |
---|
[e51e078] | 619 | self.updateGuiValues() |
---|
[fa81e94] | 620 | if message: |
---|
| 621 | logging.info(message) |
---|
| 622 | |
---|
[f1ec901] | 623 | def _calculateCompleted(self, out, cov, pr, elapsed): |
---|
| 624 | ''' Send a signal to the main thread for model update''' |
---|
| 625 | self.calculateSignal.emit((out, cov, pr, elapsed)) |
---|
| 626 | |
---|
| 627 | def _calculateUpdate(self, output_tuple): |
---|
[fa81e94] | 628 | """ |
---|
| 629 | Method called with the results when the inversion is done |
---|
| 630 | |
---|
| 631 | :param out: output coefficient for the base functions |
---|
| 632 | :param cov: covariance matrix |
---|
| 633 | :param pr: Invertor instance |
---|
| 634 | :param elapsed: time spent computing |
---|
| 635 | """ |
---|
[f1ec901] | 636 | out, cov, pr, elapsed = output_tuple |
---|
[fa81e94] | 637 | # Save useful info |
---|
| 638 | cov = np.ascontiguousarray(cov) |
---|
| 639 | pr.cov = cov |
---|
| 640 | pr.out = out |
---|
| 641 | pr.elapsed = elapsed |
---|
| 642 | |
---|
| 643 | # Save Pr invertor |
---|
| 644 | self._calculator = pr |
---|
[f1ec901] | 645 | |
---|
[fa81e94] | 646 | # Create new P(r) and fit plots |
---|
| 647 | if self.pr_plot is None: |
---|
| 648 | self.pr_plot = self.logic.newPRPlot(out, self._calculator, cov) |
---|
| 649 | if self.data_plot is None: |
---|
| 650 | self.data_plot = self.logic.new1DPlot(out, self._calculator) |
---|
[e51e078] | 651 | self.updateDataList(self._data) |
---|
| 652 | self.updateGuiValues() |
---|
[fa81e94] | 653 | |
---|
| 654 | def _threadError(self, error): |
---|
| 655 | """ |
---|
| 656 | Call-back method for calculation errors |
---|
| 657 | """ |
---|
| 658 | logging.warning(error) |
---|