1 | import sys |
---|
2 | import json |
---|
3 | import os |
---|
4 | import numpy |
---|
5 | from collections import defaultdict |
---|
6 | |
---|
7 | import logging |
---|
8 | import traceback |
---|
9 | from twisted.internet import threads |
---|
10 | |
---|
11 | from PyQt4 import QtGui |
---|
12 | from PyQt4 import QtCore |
---|
13 | |
---|
14 | from sasmodels import generate |
---|
15 | from sasmodels import modelinfo |
---|
16 | from sasmodels.sasview_model import load_standard_models |
---|
17 | |
---|
18 | from sas.sasgui.guiframe.CategoryInstaller import CategoryInstaller |
---|
19 | from sas.sasgui.guiframe.dataFitting import Data1D |
---|
20 | from sas.sasgui.guiframe.dataFitting import Data2D |
---|
21 | import sas.qtgui.GuiUtils as GuiUtils |
---|
22 | from sas.sasgui.perspectives.fitting.model_thread import Calc1D |
---|
23 | from sas.sasgui.perspectives.fitting.model_thread import Calc2D |
---|
24 | |
---|
25 | from UI.FittingWidgetUI import Ui_FittingWidgetUI |
---|
26 | from sas.qtgui.Perspectives.Fitting.FittingLogic import FittingLogic |
---|
27 | from sas.qtgui.Perspectives.Fitting import FittingUtilities |
---|
28 | |
---|
29 | TAB_MAGNETISM = 4 |
---|
30 | TAB_POLY = 3 |
---|
31 | CATEGORY_DEFAULT = "Choose category..." |
---|
32 | CATEGORY_STRUCTURE = "Structure Factor" |
---|
33 | STRUCTURE_DEFAULT = "None" |
---|
34 | QMIN_DEFAULT = 0.0005 |
---|
35 | QMAX_DEFAULT = 0.5 |
---|
36 | NPTS_DEFAULT = 50 |
---|
37 | |
---|
38 | class FittingWidget(QtGui.QWidget, Ui_FittingWidgetUI): |
---|
39 | """ |
---|
40 | Main widget for selecting form and structure factor models |
---|
41 | """ |
---|
42 | def __init__(self, parent=None, data=None, id=1): |
---|
43 | |
---|
44 | super(FittingWidget, self).__init__() |
---|
45 | |
---|
46 | # Necessary globals |
---|
47 | self.parent = parent |
---|
48 | # SasModel is loaded |
---|
49 | self.model_is_loaded = False |
---|
50 | # Data[12]D passed and set |
---|
51 | self.data_is_loaded = False |
---|
52 | # Current SasModel in view |
---|
53 | self.kernel_module = None |
---|
54 | # Current SasModel view dimension |
---|
55 | self.is2D = False |
---|
56 | # Current SasModel is multishell |
---|
57 | self.model_has_shells = False |
---|
58 | # Utility variable to enable unselectable option in category combobox |
---|
59 | self._previous_category_index = 0 |
---|
60 | # Utility variable for multishell display |
---|
61 | self._last_model_row = 0 |
---|
62 | # Dictionary of {model name: model class} for the current category |
---|
63 | self.models = {} |
---|
64 | |
---|
65 | # Which tab is this widget displayed in? |
---|
66 | self.tab_id = id |
---|
67 | |
---|
68 | # Which shell is being currently displayed? |
---|
69 | self.current_shell_displayed = 0 |
---|
70 | |
---|
71 | # Range parameters |
---|
72 | self.q_range_min = QMIN_DEFAULT |
---|
73 | self.q_range_max = QMAX_DEFAULT |
---|
74 | self.npts = NPTS_DEFAULT |
---|
75 | |
---|
76 | # Main Data[12]D holder |
---|
77 | self.logic = FittingLogic(data=data) |
---|
78 | |
---|
79 | # Main GUI setup up |
---|
80 | self.setupUi(self) |
---|
81 | self.setWindowTitle("Fitting") |
---|
82 | self.communicate = self.parent.communicate |
---|
83 | |
---|
84 | # Define bold font for use in various controls |
---|
85 | self.boldFont=QtGui.QFont() |
---|
86 | self.boldFont.setBold(True) |
---|
87 | |
---|
88 | # Set data label |
---|
89 | self.label.setFont(self.boldFont) |
---|
90 | self.label.setText("No data loaded") |
---|
91 | self.lblFilename.setText("") |
---|
92 | |
---|
93 | # Set the main models |
---|
94 | # We can't use a single model here, due to restrictions on flattening |
---|
95 | # the model tree with subclassed QAbstractProxyModel... |
---|
96 | self._model_model = QtGui.QStandardItemModel() |
---|
97 | self._poly_model = QtGui.QStandardItemModel() |
---|
98 | self._magnet_model = QtGui.QStandardItemModel() |
---|
99 | |
---|
100 | # Param model displayed in param list |
---|
101 | self.lstParams.setModel(self._model_model) |
---|
102 | self.readCategoryInfo() |
---|
103 | self.model_parameters = None |
---|
104 | self.lstParams.setAlternatingRowColors(True) |
---|
105 | |
---|
106 | # Poly model displayed in poly list |
---|
107 | self.lstPoly.setModel(self._poly_model) |
---|
108 | self.setPolyModel() |
---|
109 | self.setTableProperties(self.lstPoly) |
---|
110 | |
---|
111 | # Magnetism model displayed in magnetism list |
---|
112 | self.lstMagnetic.setModel(self._magnet_model) |
---|
113 | self.setMagneticModel() |
---|
114 | self.setTableProperties(self.lstMagnetic) |
---|
115 | |
---|
116 | # Defaults for the structure factors |
---|
117 | self.setDefaultStructureCombo() |
---|
118 | |
---|
119 | # Make structure factor and model CBs disabled |
---|
120 | self.disableModelCombo() |
---|
121 | self.disableStructureCombo() |
---|
122 | |
---|
123 | # Generate the category list for display |
---|
124 | category_list = sorted(self.master_category_dict.keys()) |
---|
125 | self.cbCategory.addItem(CATEGORY_DEFAULT) |
---|
126 | self.cbCategory.addItems(category_list) |
---|
127 | self.cbCategory.addItem(CATEGORY_STRUCTURE) |
---|
128 | self.cbCategory.setCurrentIndex(0) |
---|
129 | |
---|
130 | self._index = None |
---|
131 | if data is not None: |
---|
132 | self.data = data |
---|
133 | |
---|
134 | # Connect signals to controls |
---|
135 | self.initializeSignals() |
---|
136 | |
---|
137 | # Initial control state |
---|
138 | self.initializeControls() |
---|
139 | |
---|
140 | @property |
---|
141 | def data(self): |
---|
142 | return self.logic.data |
---|
143 | |
---|
144 | @data.setter |
---|
145 | def data(self, value): |
---|
146 | """ data setter """ |
---|
147 | assert isinstance(value[0], QtGui.QStandardItem) |
---|
148 | # _index contains the QIndex with data |
---|
149 | self._index = value |
---|
150 | |
---|
151 | # Update logics with data items |
---|
152 | self.logic.data = GuiUtils.dataFromItem(value[0]) |
---|
153 | |
---|
154 | self.data_is_loaded = True |
---|
155 | # Tag along functionality |
---|
156 | self.label.setText("Data loaded from: ") |
---|
157 | self.lblFilename.setText(self.logic.data.filename) |
---|
158 | self.updateQRange() |
---|
159 | self.cmdFit.setEnabled(True) |
---|
160 | |
---|
161 | def acceptsData(self): |
---|
162 | """ Tells the caller this widget can accept new dataset """ |
---|
163 | return not self.data_is_loaded |
---|
164 | |
---|
165 | def disableModelCombo(self): |
---|
166 | """ Disable the combobox """ |
---|
167 | self.cbModel.setEnabled(False) |
---|
168 | self.lblModel.setEnabled(False) |
---|
169 | |
---|
170 | def enableModelCombo(self): |
---|
171 | """ Enable the combobox """ |
---|
172 | self.cbModel.setEnabled(True) |
---|
173 | self.lblModel.setEnabled(True) |
---|
174 | |
---|
175 | def disableStructureCombo(self): |
---|
176 | """ Disable the combobox """ |
---|
177 | self.cbStructureFactor.setEnabled(False) |
---|
178 | self.lblStructure.setEnabled(False) |
---|
179 | |
---|
180 | def enableStructureCombo(self): |
---|
181 | """ Enable the combobox """ |
---|
182 | self.cbStructureFactor.setEnabled(True) |
---|
183 | self.lblStructure.setEnabled(True) |
---|
184 | |
---|
185 | def updateQRange(self): |
---|
186 | """ |
---|
187 | Updates Q Range display |
---|
188 | """ |
---|
189 | if self.data_is_loaded: |
---|
190 | self.q_range_min, self.q_range_max, self.npts = self.logic.computeDataRange() |
---|
191 | # set Q range labels on the main tab |
---|
192 | self.lblMinRangeDef.setText(str(self.q_range_min)) |
---|
193 | self.lblMaxRangeDef.setText(str(self.q_range_max)) |
---|
194 | # set Q range labels on the options tab |
---|
195 | self.txtMaxRange.setText(str(self.q_range_max)) |
---|
196 | self.txtMinRange.setText(str(self.q_range_min)) |
---|
197 | self.txtNpts.setText(str(self.npts)) |
---|
198 | |
---|
199 | def initializeControls(self): |
---|
200 | """ |
---|
201 | Set initial control enablement |
---|
202 | """ |
---|
203 | self.cmdFit.setEnabled(False) |
---|
204 | self.cmdPlot.setEnabled(True) |
---|
205 | self.chkPolydispersity.setEnabled(True) |
---|
206 | self.chkPolydispersity.setCheckState(False) |
---|
207 | self.chk2DView.setEnabled(True) |
---|
208 | self.chk2DView.setCheckState(False) |
---|
209 | self.chkMagnetism.setEnabled(False) |
---|
210 | self.chkMagnetism.setCheckState(False) |
---|
211 | # Tabs |
---|
212 | self.tabFitting.setTabEnabled(TAB_POLY, False) |
---|
213 | self.tabFitting.setTabEnabled(TAB_MAGNETISM, False) |
---|
214 | self.lblChi2Value.setText("---") |
---|
215 | # Update Q Ranges |
---|
216 | self.updateQRange() |
---|
217 | |
---|
218 | def initializeSignals(self): |
---|
219 | """ |
---|
220 | Connect GUI element signals |
---|
221 | """ |
---|
222 | # Comboboxes |
---|
223 | self.cbStructureFactor.currentIndexChanged.connect(self.onSelectStructureFactor) |
---|
224 | self.cbCategory.currentIndexChanged.connect(self.onSelectCategory) |
---|
225 | self.cbModel.currentIndexChanged.connect(self.onSelectModel) |
---|
226 | # Checkboxes |
---|
227 | self.chk2DView.toggled.connect(self.toggle2D) |
---|
228 | self.chkPolydispersity.toggled.connect(self.togglePoly) |
---|
229 | self.chkMagnetism.toggled.connect(self.toggleMagnetism) |
---|
230 | # Buttons |
---|
231 | self.cmdFit.clicked.connect(self.onFit) |
---|
232 | self.cmdPlot.clicked.connect(self.onPlot) |
---|
233 | # Line edits |
---|
234 | self.txtNpts.textChanged.connect(self.onNpts) |
---|
235 | self.txtMinRange.textChanged.connect(self.onMinRange) |
---|
236 | self.txtMaxRange.textChanged.connect(self.onMaxRange) |
---|
237 | |
---|
238 | # Respond to change in parameters from the UI |
---|
239 | self._model_model.itemChanged.connect(self.updateParamsFromModel) |
---|
240 | self._poly_model.itemChanged.connect(self.onPolyModelChange) |
---|
241 | # TODO after the poly_model prototype accepted |
---|
242 | #self._magnet_model.itemChanged.connect(self.onMagneticModelChange) |
---|
243 | |
---|
244 | def setDefaultStructureCombo(self): |
---|
245 | """ |
---|
246 | Fill in the structure factors combo box with defaults |
---|
247 | """ |
---|
248 | structure_factor_list = self.master_category_dict.pop(CATEGORY_STRUCTURE) |
---|
249 | factors = [factor[0] for factor in structure_factor_list] |
---|
250 | factors.insert(0, STRUCTURE_DEFAULT) |
---|
251 | self.cbStructureFactor.clear() |
---|
252 | self.cbStructureFactor.addItems(sorted(factors)) |
---|
253 | |
---|
254 | def onSelectCategory(self): |
---|
255 | """ |
---|
256 | Select Category from list |
---|
257 | """ |
---|
258 | category = str(self.cbCategory.currentText()) |
---|
259 | # Check if the user chose "Choose category entry" |
---|
260 | if category == CATEGORY_DEFAULT: |
---|
261 | # if the previous category was not the default, keep it. |
---|
262 | # Otherwise, just return |
---|
263 | if self._previous_category_index != 0: |
---|
264 | # We need to block signals, or else state changes on perceived unchanged conditions |
---|
265 | self.cbCategory.blockSignals(True) |
---|
266 | self.cbCategory.setCurrentIndex(self._previous_category_index) |
---|
267 | self.cbCategory.blockSignals(False) |
---|
268 | return |
---|
269 | |
---|
270 | if category == CATEGORY_STRUCTURE: |
---|
271 | self.disableModelCombo() |
---|
272 | self.enableStructureCombo() |
---|
273 | self._model_model.clear() |
---|
274 | return |
---|
275 | |
---|
276 | # Safely clear and enable the model combo |
---|
277 | self.cbModel.blockSignals(True) |
---|
278 | self.cbModel.clear() |
---|
279 | self.cbModel.blockSignals(False) |
---|
280 | self.enableModelCombo() |
---|
281 | self.disableStructureCombo() |
---|
282 | |
---|
283 | self._previous_category_index = self.cbCategory.currentIndex() |
---|
284 | # Retrieve the list of models |
---|
285 | model_list = self.master_category_dict[category] |
---|
286 | models = [] |
---|
287 | # Populate the models combobox |
---|
288 | self.cbModel.addItems(sorted([model for (model, _) in model_list])) |
---|
289 | |
---|
290 | def createDefaultDataset(self): |
---|
291 | """ |
---|
292 | Generate default Dataset 1D/2D for the given model |
---|
293 | """ |
---|
294 | # Create default datasets if no data passed |
---|
295 | if self.is2D: |
---|
296 | qmax = self.q_range_max/numpy.sqrt(2) |
---|
297 | qstep = self.npts |
---|
298 | self.logic.createDefault2dData(qmax, qstep, self.tab_id) |
---|
299 | else: |
---|
300 | interval = numpy.linspace(start=self.q_range_min, stop=self.q_range_max, |
---|
301 | num=self.npts, endpoint=True) |
---|
302 | self.logic.createDefault1dData(interval, self.tab_id) |
---|
303 | |
---|
304 | def onSelectModel(self): |
---|
305 | """ |
---|
306 | Respond to select Model from list event |
---|
307 | """ |
---|
308 | model = str(self.cbModel.currentText()) |
---|
309 | |
---|
310 | # Reset structure factor |
---|
311 | self.cbStructureFactor.setCurrentIndex(0) |
---|
312 | |
---|
313 | # SasModel -> QModel |
---|
314 | self.SASModelToQModel(model) |
---|
315 | |
---|
316 | if self._index is None: |
---|
317 | # Create default datasets if no data passed |
---|
318 | self.createDefaultDataset() |
---|
319 | else: |
---|
320 | self.calculateQGridForModel() |
---|
321 | |
---|
322 | def onSelectStructureFactor(self): |
---|
323 | """ |
---|
324 | Select Structure Factor from list |
---|
325 | """ |
---|
326 | model = str(self.cbModel.currentText()) |
---|
327 | category = str(self.cbCategory.currentText()) |
---|
328 | structure = str(self.cbStructureFactor.currentText()) |
---|
329 | if category == CATEGORY_STRUCTURE: |
---|
330 | model = None |
---|
331 | self.SASModelToQModel(model, structure_factor=structure) |
---|
332 | |
---|
333 | def readCategoryInfo(self): |
---|
334 | """ |
---|
335 | Reads the categories in from file |
---|
336 | """ |
---|
337 | self.master_category_dict = defaultdict(list) |
---|
338 | self.by_model_dict = defaultdict(list) |
---|
339 | self.model_enabled_dict = defaultdict(bool) |
---|
340 | |
---|
341 | categorization_file = CategoryInstaller.get_user_file() |
---|
342 | if not os.path.isfile(categorization_file): |
---|
343 | categorization_file = CategoryInstaller.get_default_file() |
---|
344 | with open(categorization_file, 'rb') as cat_file: |
---|
345 | self.master_category_dict = json.load(cat_file) |
---|
346 | self.regenerateModelDict() |
---|
347 | |
---|
348 | # Load the model dict |
---|
349 | models = load_standard_models() |
---|
350 | for model in models: |
---|
351 | self.models[model.name] = model |
---|
352 | |
---|
353 | def regenerateModelDict(self): |
---|
354 | """ |
---|
355 | Regenerates self.by_model_dict which has each model name as the |
---|
356 | key and the list of categories belonging to that model |
---|
357 | along with the enabled mapping |
---|
358 | """ |
---|
359 | self.by_model_dict = defaultdict(list) |
---|
360 | for category in self.master_category_dict: |
---|
361 | for (model, enabled) in self.master_category_dict[category]: |
---|
362 | self.by_model_dict[model].append(category) |
---|
363 | self.model_enabled_dict[model] = enabled |
---|
364 | |
---|
365 | def addBackgroundToModel(self, model): |
---|
366 | """ |
---|
367 | Adds background parameter with default values to the model |
---|
368 | """ |
---|
369 | assert isinstance(model, QtGui.QStandardItemModel) |
---|
370 | checked_list = ['background', '0.001', '-inf', 'inf', '1/cm'] |
---|
371 | FittingUtilities.addCheckedListToModel(model, checked_list) |
---|
372 | |
---|
373 | def addScaleToModel(self, model): |
---|
374 | """ |
---|
375 | Adds scale parameter with default values to the model |
---|
376 | """ |
---|
377 | assert isinstance(model, QtGui.QStandardItemModel) |
---|
378 | checked_list = ['scale', '1.0', '0.0', 'inf', ''] |
---|
379 | FittingUtilities.addCheckedListToModel(model, checked_list) |
---|
380 | |
---|
381 | def SASModelToQModel(self, model_name, structure_factor=None): |
---|
382 | """ |
---|
383 | Setting model parameters into table based on selected category |
---|
384 | """ |
---|
385 | # TODO - modify for structure factor-only choice |
---|
386 | |
---|
387 | # Crete/overwrite model items |
---|
388 | self._model_model.clear() |
---|
389 | |
---|
390 | kernel_module = generate.load_kernel_module(model_name) |
---|
391 | self.model_parameters = modelinfo.make_parameter_table(getattr(kernel_module, 'parameters', [])) |
---|
392 | |
---|
393 | # Instantiate the current sasmodel |
---|
394 | self.kernel_module = self.models[model_name]() |
---|
395 | |
---|
396 | # Explicitly add scale and background with default values |
---|
397 | self.addScaleToModel(self._model_model) |
---|
398 | self.addBackgroundToModel(self._model_model) |
---|
399 | |
---|
400 | # Update the QModel |
---|
401 | FittingUtilities.addParametersToModel(self.model_parameters, self._model_model) |
---|
402 | # Update the counter used for multishell display |
---|
403 | self._last_model_row = self._model_model.rowCount() |
---|
404 | |
---|
405 | FittingUtilities.addHeadersToModel(self._model_model) |
---|
406 | |
---|
407 | # Add structure factor |
---|
408 | if structure_factor is not None and structure_factor != "None": |
---|
409 | structure_module = generate.load_kernel_module(structure_factor) |
---|
410 | structure_parameters = modelinfo.make_parameter_table(getattr(structure_module, 'parameters', [])) |
---|
411 | FittingUtilities.addSimpleParametersToModel(structure_parameters, self._model_model) |
---|
412 | # Update the counter used for multishell display |
---|
413 | self._last_model_row = self._model_model.rowCount() |
---|
414 | else: |
---|
415 | self.addStructureFactor() |
---|
416 | |
---|
417 | # Multishell models need additional treatment |
---|
418 | self.addExtraShells() |
---|
419 | |
---|
420 | # Add polydispersity to the model |
---|
421 | self.setPolyModel() |
---|
422 | # Add magnetic parameters to the model |
---|
423 | self.setMagneticModel() |
---|
424 | |
---|
425 | # Adjust the table cells width |
---|
426 | self.lstParams.resizeColumnToContents(0) |
---|
427 | self.lstParams.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Expanding) |
---|
428 | |
---|
429 | # Now we claim the model has been loaded |
---|
430 | self.model_is_loaded = True |
---|
431 | |
---|
432 | # Update Q Ranges |
---|
433 | self.updateQRange() |
---|
434 | |
---|
435 | def onPolyModelChange(self, item): |
---|
436 | """ |
---|
437 | Callback method for updating the main model and sasmodel |
---|
438 | parameters with the GUI values in the polydispersity view |
---|
439 | """ |
---|
440 | model_column = item.column() |
---|
441 | model_row = item.row() |
---|
442 | name_index = self._poly_model.index(model_row, 0) |
---|
443 | # Extract changed value. Assumes proper validation by QValidator/Delegate |
---|
444 | # Checkbox in column 0 |
---|
445 | if model_column == 0: |
---|
446 | value = item.checkState() |
---|
447 | else: |
---|
448 | try: |
---|
449 | value = float(item.text()) |
---|
450 | except ValueError: |
---|
451 | # Can't be converted properly, bring back the old value and exit |
---|
452 | return |
---|
453 | |
---|
454 | parameter_name = str(self._poly_model.data(name_index).toPyObject()) # "distribution of sld" etc. |
---|
455 | if "Distribution of" in parameter_name: |
---|
456 | parameter_name = parameter_name[16:] |
---|
457 | property_name = str(self._poly_model.headerData(model_column, 1).toPyObject()) # Value, min, max, etc. |
---|
458 | # print "%s(%s) => %d" % (parameter_name, property_name, value) |
---|
459 | |
---|
460 | # Update the sasmodel |
---|
461 | #self.kernel_module.params[parameter_name] = value |
---|
462 | |
---|
463 | # Reload the main model - may not be required if no variable is shown in main view |
---|
464 | #model = str(self.cbModel.currentText()) |
---|
465 | #self.SASModelToQModel(model) |
---|
466 | |
---|
467 | pass # debug anchor |
---|
468 | |
---|
469 | def updateParamsFromModel(self, item): |
---|
470 | """ |
---|
471 | Callback method for updating the sasmodel parameters with the GUI values |
---|
472 | """ |
---|
473 | model_column = item.column() |
---|
474 | model_row = item.row() |
---|
475 | name_index = self._model_model.index(model_row, 0) |
---|
476 | |
---|
477 | if model_column == 0: |
---|
478 | # Assure we're dealing with checkboxes |
---|
479 | if not item.isCheckable(): |
---|
480 | return |
---|
481 | status = item.checkState() |
---|
482 | # If multiple rows selected - toggle all of them |
---|
483 | rows = [s.row() for s in self.lstParams.selectionModel().selectedRows()] |
---|
484 | |
---|
485 | # Switch off signaling from the model to avoid multiple calls |
---|
486 | self._model_model.blockSignals(True) |
---|
487 | # Convert to proper indices and set requested enablement |
---|
488 | items = [self._model_model.item(row, 0).setCheckState(status) for row in rows] |
---|
489 | self._model_model.blockSignals(False) |
---|
490 | return |
---|
491 | |
---|
492 | # Extract changed value. Assumes proper validation by QValidator/Delegate |
---|
493 | value = float(item.text()) |
---|
494 | parameter_name = str(self._model_model.data(name_index).toPyObject()) # sld, background etc. |
---|
495 | property_name = str(self._model_model.headerData(1, model_column).toPyObject()) # Value, min, max, etc. |
---|
496 | |
---|
497 | # print "%s(%s) => %d" % (parameter_name, property_name, value) |
---|
498 | self.kernel_module.params[parameter_name] = value |
---|
499 | |
---|
500 | # min/max to be changed in self.kernel_module.details[parameter_name] = ['Ang', 0.0, inf] |
---|
501 | |
---|
502 | # magnetic params in self.kernel_module.details['M0:parameter_name'] = value |
---|
503 | # multishell params in self.kernel_module.details[??] = value |
---|
504 | |
---|
505 | |
---|
506 | def createTheoryIndex(self): |
---|
507 | """ |
---|
508 | Create a QStandardModelIndex containing default model data |
---|
509 | """ |
---|
510 | name = self.kernel_module.name |
---|
511 | if self.is2D: |
---|
512 | name += "2d" |
---|
513 | name = "M%i [%s]" % (self.tab_id, name) |
---|
514 | new_item = GuiUtils.createModelItemWithPlot(QtCore.QVariant(self.data), name=name) |
---|
515 | # Notify the GUI manager so it can update the theory model in DataExplorer |
---|
516 | self.communicate.updateTheoryFromPerspectiveSignal.emit(new_item) |
---|
517 | |
---|
518 | def onFit(self): |
---|
519 | """ |
---|
520 | Perform fitting on the current data |
---|
521 | """ |
---|
522 | #self.calculate1DForModel() |
---|
523 | pass |
---|
524 | |
---|
525 | def onPlot(self): |
---|
526 | """ |
---|
527 | Plot the current set of data |
---|
528 | """ |
---|
529 | # TODO: reimplement basepage.py/_update_paramv_on_fit |
---|
530 | if self.data is None or not self.data.is_data: |
---|
531 | self.createDefaultDataset() |
---|
532 | self.calculateQGridForModel() |
---|
533 | |
---|
534 | def onNpts(self, text): |
---|
535 | """ |
---|
536 | Callback for number of points line edit update |
---|
537 | """ |
---|
538 | # assumes type/value correctness achieved with QValidator |
---|
539 | try: |
---|
540 | self.npts = int(text) |
---|
541 | except ValueError: |
---|
542 | # TODO |
---|
543 | # This will return the old value to model/view and return |
---|
544 | # notifying the user about format available. |
---|
545 | pass |
---|
546 | |
---|
547 | def onMinRange(self, text): |
---|
548 | """ |
---|
549 | Callback for minimum range of points line edit update |
---|
550 | """ |
---|
551 | # assumes type/value correctness achieved with QValidator |
---|
552 | try: |
---|
553 | self.q_range_min = float(text) |
---|
554 | except ValueError: |
---|
555 | # TODO |
---|
556 | # This will return the old value to model/view and return |
---|
557 | # notifying the user about format available. |
---|
558 | return |
---|
559 | # set Q range labels on the main tab |
---|
560 | self.lblMinRangeDef.setText(str(self.q_range_min)) |
---|
561 | |
---|
562 | def onMaxRange(self, text): |
---|
563 | """ |
---|
564 | Callback for maximum range of points line edit update |
---|
565 | """ |
---|
566 | # assumes type/value correctness achieved with QValidator |
---|
567 | try: |
---|
568 | self.q_range_max = float(text) |
---|
569 | except: |
---|
570 | pass |
---|
571 | # set Q range labels on the main tab |
---|
572 | self.lblMaxRangeDef.setText(str(self.q_range_max)) |
---|
573 | |
---|
574 | def methodCalculateForData(self): |
---|
575 | '''return the method for data calculation''' |
---|
576 | return Calc1D if isinstance(self.data, Data1D) else Calc2D |
---|
577 | |
---|
578 | def methodCompleteForData(self): |
---|
579 | '''return the method for result parsin on calc complete ''' |
---|
580 | return self.complete1D if isinstance(self.data, Data1D) else self.complete2D |
---|
581 | |
---|
582 | def calculateQGridForModel(self): |
---|
583 | """ |
---|
584 | Prepare the fitting data object, based on current ModelModel |
---|
585 | """ |
---|
586 | # Awful API to a backend method. |
---|
587 | method = self.methodCalculateForData()(data=self.data, |
---|
588 | model=self.kernel_module, |
---|
589 | page_id=0, |
---|
590 | qmin=self.q_range_min, |
---|
591 | qmax=self.q_range_max, |
---|
592 | smearer=None, |
---|
593 | state=None, |
---|
594 | weight=None, |
---|
595 | fid=None, |
---|
596 | toggle_mode_on=False, |
---|
597 | completefn=None, |
---|
598 | update_chisqr=True, |
---|
599 | exception_handler=self.calcException, |
---|
600 | source=None) |
---|
601 | |
---|
602 | calc_thread = threads.deferToThread(method.compute) |
---|
603 | calc_thread.addCallback(self.methodCompleteForData()) |
---|
604 | |
---|
605 | def complete1D(self, return_data): |
---|
606 | """ |
---|
607 | Plot the current 1D data |
---|
608 | """ |
---|
609 | self.logic.new1DPlot(return_data) |
---|
610 | self.createTheoryIndex() |
---|
611 | |
---|
612 | #output=self._cal_chisqr(data=data, |
---|
613 | # fid=fid, |
---|
614 | # weight=weight, |
---|
615 | # page_id=page_id, |
---|
616 | # index=index) |
---|
617 | |
---|
618 | def complete2D(self, return_data): |
---|
619 | """ |
---|
620 | Plot the current 2D data |
---|
621 | """ |
---|
622 | self.logic.new2DPlot(return_data) |
---|
623 | self.createTheoryIndex() |
---|
624 | |
---|
625 | #output=self._cal_chisqr(data=data, |
---|
626 | # weight=weight, |
---|
627 | # fid=fid, |
---|
628 | # page_id=page_id, |
---|
629 | # index=index) |
---|
630 | # self._plot_residuals(page_id=page_id, data=data, fid=fid, |
---|
631 | # index=index, weight=weight) |
---|
632 | |
---|
633 | def calcException(self, etype, value, tb): |
---|
634 | """ |
---|
635 | Something horrible happened in the deferred. |
---|
636 | """ |
---|
637 | logging.error("".join(traceback.format_exception(etype, value, tb))) |
---|
638 | |
---|
639 | def setTableProperties(self, table): |
---|
640 | """ |
---|
641 | Setting table properties |
---|
642 | """ |
---|
643 | # Table properties |
---|
644 | table.verticalHeader().setVisible(False) |
---|
645 | table.setAlternatingRowColors(True) |
---|
646 | table.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Expanding) |
---|
647 | table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) |
---|
648 | table.resizeColumnsToContents() |
---|
649 | |
---|
650 | # Header |
---|
651 | header = table.horizontalHeader() |
---|
652 | header.setResizeMode(QtGui.QHeaderView.ResizeToContents) |
---|
653 | |
---|
654 | header.ResizeMode(QtGui.QHeaderView.Interactive) |
---|
655 | # Resize column 0 and 6 to content |
---|
656 | header.setResizeMode(0, QtGui.QHeaderView.ResizeToContents) |
---|
657 | header.setResizeMode(6, QtGui.QHeaderView.ResizeToContents) |
---|
658 | |
---|
659 | def setPolyModel(self): |
---|
660 | """ |
---|
661 | Set polydispersity values |
---|
662 | """ |
---|
663 | if not self.model_parameters: |
---|
664 | return |
---|
665 | self._poly_model.clear() |
---|
666 | for row, param in enumerate(self.model_parameters.form_volume_parameters): |
---|
667 | # Counters should not be included |
---|
668 | if not param.polydisperse: |
---|
669 | continue |
---|
670 | |
---|
671 | # Potential multishell params |
---|
672 | checked_list = ["Distribution of "+param.name, str(param.default), |
---|
673 | str(param.limits[0]), str(param.limits[1]), |
---|
674 | "35", "3", ""] |
---|
675 | FittingUtilities.addCheckedListToModel(self._poly_model, checked_list) |
---|
676 | |
---|
677 | #TODO: Need to find cleaner way to input functions |
---|
678 | func = QtGui.QComboBox() |
---|
679 | func.addItems(['rectangle', 'array', 'lognormal', 'gaussian', 'schulz',]) |
---|
680 | func_index = self.lstPoly.model().index(row, 6) |
---|
681 | self.lstPoly.setIndexWidget(func_index, func) |
---|
682 | |
---|
683 | FittingUtilities.addPolyHeadersToModel(self._poly_model) |
---|
684 | |
---|
685 | def setMagneticModel(self): |
---|
686 | """ |
---|
687 | Set magnetism values on model |
---|
688 | """ |
---|
689 | if not self.model_parameters: |
---|
690 | return |
---|
691 | self._magnet_model.clear() |
---|
692 | for param in self.model_parameters.call_parameters: |
---|
693 | if param.type != "magnetic": |
---|
694 | continue |
---|
695 | checked_list = [param.name, |
---|
696 | str(param.default), |
---|
697 | str(param.limits[0]), |
---|
698 | str(param.limits[1]), |
---|
699 | param.units] |
---|
700 | FittingUtilities.addCheckedListToModel(self._magnet_model, checked_list) |
---|
701 | |
---|
702 | FittingUtilities.addHeadersToModel(self._magnet_model) |
---|
703 | |
---|
704 | def addStructureFactor(self): |
---|
705 | """ |
---|
706 | Add structure factors to the list of parameters |
---|
707 | """ |
---|
708 | if self.kernel_module.is_form_factor: |
---|
709 | self.enableStructureCombo() |
---|
710 | else: |
---|
711 | self.disableStructureCombo() |
---|
712 | |
---|
713 | def addExtraShells(self): |
---|
714 | """ |
---|
715 | Add a combobox for multiple shell display |
---|
716 | """ |
---|
717 | param_name, param_length = FittingUtilities.getMultiplicity(self.model_parameters) |
---|
718 | |
---|
719 | if param_length == 0: |
---|
720 | return |
---|
721 | |
---|
722 | # cell 1: variable name |
---|
723 | item1 = QtGui.QStandardItem(param_name) |
---|
724 | |
---|
725 | func = QtGui.QComboBox() |
---|
726 | # Available range of shells displayed in the combobox |
---|
727 | func.addItems([str(i) for i in xrange(param_length+1)]) |
---|
728 | |
---|
729 | # Respond to index change |
---|
730 | func.currentIndexChanged.connect(self.modifyShellsInList) |
---|
731 | |
---|
732 | # cell 2: combobox |
---|
733 | item2 = QtGui.QStandardItem() |
---|
734 | self._model_model.appendRow([item1, item2]) |
---|
735 | |
---|
736 | # Beautify the row: span columns 2-4 |
---|
737 | shell_row = self._model_model.rowCount() |
---|
738 | shell_index = self._model_model.index(shell_row-1, 1) |
---|
739 | |
---|
740 | self.lstParams.setIndexWidget(shell_index, func) |
---|
741 | self._last_model_row = self._model_model.rowCount() |
---|
742 | |
---|
743 | # Set the index to the state-kept value |
---|
744 | func.setCurrentIndex(self.current_shell_displayed |
---|
745 | if self.current_shell_displayed < func.count() else 0) |
---|
746 | |
---|
747 | def modifyShellsInList(self, index): |
---|
748 | """ |
---|
749 | Add/remove additional multishell parameters |
---|
750 | """ |
---|
751 | # Find row location of the combobox |
---|
752 | last_row = self._last_model_row |
---|
753 | remove_rows = self._model_model.rowCount() - last_row |
---|
754 | |
---|
755 | if remove_rows > 1: |
---|
756 | self._model_model.removeRows(last_row, remove_rows) |
---|
757 | |
---|
758 | FittingUtilities.addShellsToModel(self.model_parameters, self._model_model, index) |
---|
759 | self.current_shell_displayed = index |
---|
760 | |
---|
761 | def togglePoly(self, isChecked): |
---|
762 | """ |
---|
763 | Enable/disable the polydispersity tab |
---|
764 | """ |
---|
765 | self.tabFitting.setTabEnabled(TAB_POLY, isChecked) |
---|
766 | |
---|
767 | def toggleMagnetism(self, isChecked): |
---|
768 | """ |
---|
769 | Enable/disable the magnetism tab |
---|
770 | """ |
---|
771 | self.tabFitting.setTabEnabled(TAB_MAGNETISM, isChecked) |
---|
772 | |
---|
773 | def toggle2D(self, isChecked): |
---|
774 | """ |
---|
775 | Enable/disable the controls dependent on 1D/2D data instance |
---|
776 | """ |
---|
777 | self.chkMagnetism.setEnabled(isChecked) |
---|
778 | self.is2D = isChecked |
---|
779 | |
---|