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