source: sasview/src/sas/qtgui/Calculators/SldPanel.py @ 85487ebd

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 85487ebd was b0c5e8c, checked in by Piotr Rozyczko <rozyczko@…>, 7 years ago

Unit tests for fitting options dialog SASVIEW-514

  • Property mode set to 100644
File size: 8.1 KB
Line 
1# global
2import logging
3from PyQt4 import QtGui, QtCore
4
5from periodictable import formula as Formula
6from periodictable.xsf import xray_energy, xray_sld_from_atoms
7from periodictable.nsf import neutron_scattering
8
9import sas.qtgui.Utilities.GuiUtils as GuiUtils
10
11from sas.qtgui.UI import main_resources_rc
12
13# Local UI
14from sas.qtgui.Calculators.UI.SldPanel import Ui_SldPanel
15
16def enum(*sequential, **named):
17    enums = dict(zip(sequential, range(len(sequential))), **named)
18    return type('Enum', (), enums)
19
20MODEL = enum(
21    'MOLECULAR_FORMULA',
22    'MASS_DENSITY',
23    'WAVELENGTH',
24    'NEUTRON_SLD_REAL',
25    'NEUTRON_SLD_IMAG',
26    'CU_KA_SLD_REAL',
27    'CU_KA_SLD_IMAG',
28    'MO_KA_SLD_REAL',
29    'MO_KA_SLD_IMAG',
30    'NEUTRON_INC_XS',
31    'NEUTRON_ABS_XS',
32    'NEUTRON_LENGTH',
33)
34
35class SldResult(object):
36    def __init__(self, molecular_formula, mass_density, wavelength,
37        neutron_sld_real, neutron_sld_imag,
38        cu_ka_sld_real, cu_ka_sld_imag,
39        mo_ka_sld_real, mo_ka_sld_imag,
40        neutron_inc_xs, neutron_abs_xs, neutron_length):
41
42        self.molecular_formula = molecular_formula
43        self.mass_density = mass_density
44        self.wavelength = wavelength
45        self.neutron_sld_real = neutron_sld_real
46        self.neutron_sld_imag = neutron_sld_imag
47        self.cu_ka_sld_real = cu_ka_sld_real
48        self.cu_ka_sld_imag = cu_ka_sld_imag
49        self.mo_ka_sld_real = mo_ka_sld_real
50        self.mo_ka_sld_imag = mo_ka_sld_imag
51        self.neutron_inc_xs = neutron_inc_xs
52        self.neutron_abs_xs = neutron_abs_xs
53        self.neutron_length = neutron_length
54
55def sldAlgorithm(molecular_formula, mass_density, wavelength):
56
57    sld_formula = Formula(molecular_formula, density=mass_density)
58
59    def calculate_sld(formula):
60        if len(formula.atoms) != 1:
61            raise NotImplementedError()
62        energy = xray_energy(formula.atoms.keys()[0].K_alpha)
63        return xray_sld_from_atoms(
64            sld_formula.atoms,
65            density=mass_density,
66            energy=energy)
67
68    cu_real, cu_imag = calculate_sld(Formula("Cu"))
69    mo_real, mo_imag = calculate_sld(Formula("Mo"))
70
71    (sld_real, sld_imag, _), (_, neutron_abs_xs, neutron_inc_xs), neutron_length = \
72        neutron_scattering(
73            compound=molecular_formula,
74            density=mass_density,
75            wavelength=wavelength)
76
77    SCALE = 1e-6
78
79    # neutron sld
80    neutron_sld_real = SCALE * sld_real
81    neutron_sld_imag = SCALE * abs(sld_imag)
82
83    # Cu sld
84    cu_ka_sld_real = SCALE * cu_real
85    cu_ka_sld_imag = SCALE * abs(cu_imag)
86
87    # Mo sld
88    mo_ka_sld_real = SCALE * mo_real
89    mo_ka_sld_imag = SCALE * abs(mo_imag)
90
91    return SldResult(
92        molecular_formula, mass_density, wavelength,
93        neutron_sld_real, neutron_sld_imag,
94        cu_ka_sld_real, cu_ka_sld_imag,
95        mo_ka_sld_real, mo_ka_sld_imag,
96        neutron_inc_xs, neutron_abs_xs, neutron_length)
97
98
99class SldPanel(QtGui.QDialog):
100
101    def __init__(self, parent=None):
102        super(SldPanel, self).__init__()
103
104        self.manager = parent
105
106        self.setupUi()
107        self.setupModel()
108        self.setupMapper()
109
110    def _getOutputs(self):
111        return {
112            MODEL.NEUTRON_SLD_REAL: self.ui.editNeutronSldReal,
113            MODEL.NEUTRON_SLD_IMAG: self.ui.editNeutronSldImag,
114            MODEL.CU_KA_SLD_REAL: self.ui.editCuKaSldReal,
115            MODEL.CU_KA_SLD_IMAG: self.ui.editCuKaSldImag,
116            MODEL.MO_KA_SLD_REAL: self.ui.editMoKaSldReal,
117            MODEL.MO_KA_SLD_IMAG: self.ui.editMoKaSldImag,
118            MODEL.NEUTRON_INC_XS: self.ui.editNeutronIncXs,
119            MODEL.NEUTRON_ABS_XS: self.ui.editNeutronAbsXs,
120            MODEL.NEUTRON_LENGTH: self.ui.editNeutronLength
121        }
122
123    def setupUi(self):
124        self.ui = Ui_SldPanel()
125        self.ui.setupUi(self)
126
127        # set validators
128        self.ui.editMolecularFormula.setValidator(GuiUtils.FormulaValidator(self.ui.editMolecularFormula))
129
130        rx = QtCore.QRegExp("[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?")
131        self.ui.editMassDensity.setValidator(QtGui.QRegExpValidator(rx, self.ui.editMassDensity))
132        self.ui.editWavelength.setValidator(QtGui.QRegExpValidator(rx, self.ui.editWavelength))
133
134        # signals
135        self.ui.buttonBox.button(QtGui.QDialogButtonBox.Reset).clicked.connect(self.modelReset)
136        self.ui.buttonBox.button(QtGui.QDialogButtonBox.Help).clicked.connect(self.displayHelp)
137
138    def setupModel(self):
139        self.model = QtGui.QStandardItemModel(self)
140        self.model.setItem(MODEL.MOLECULAR_FORMULA, QtGui.QStandardItem())
141        self.model.setItem(MODEL.MASS_DENSITY     , QtGui.QStandardItem())
142        self.model.setItem(MODEL.WAVELENGTH       , QtGui.QStandardItem())
143
144        for key in self._getOutputs().keys():
145            self.model.setItem(key, QtGui.QStandardItem())
146
147        QtCore.QObject.connect(
148            self.model,
149            QtCore.SIGNAL("dataChanged(QModelIndex,QModelIndex)"),
150            self.dataChanged)
151
152        self.modelReset()
153
154    def setupMapper(self):
155        self.mapper = QtGui.QDataWidgetMapper(self)
156        self.mapper.setModel(self.model)
157        self.mapper.setOrientation(QtCore.Qt.Vertical)
158
159        self.mapper.addMapping(self.ui.editMolecularFormula, MODEL.MOLECULAR_FORMULA)
160        self.mapper.addMapping(self.ui.editMassDensity     , MODEL.MASS_DENSITY)
161        self.mapper.addMapping(self.ui.editWavelength      , MODEL.WAVELENGTH)
162
163        for key, edit in self._getOutputs().iteritems():
164            self.mapper.addMapping(edit, key)
165
166        self.mapper.toFirst()
167
168    def dataChanged(self, top, bottom):
169        update = False
170        for index in xrange(top.row(), bottom.row() + 1):
171            if (index == MODEL.MOLECULAR_FORMULA) or (index == MODEL.MASS_DENSITY) or (index == MODEL.WAVELENGTH):
172                update = True
173
174        # calcualtion
175        if update:
176            formula = self.model.item(MODEL.MOLECULAR_FORMULA).text()
177            density = self.model.item(MODEL.MASS_DENSITY).text()
178            wavelength = self.model.item(MODEL.WAVELENGTH).text()
179            if len(formula) > 0 and len(density) > 0 and len(wavelength) > 0:
180                try:
181                    results = sldAlgorithm(str(formula), float(density), float(wavelength))
182
183                    def format(value):
184                        return ("%-5.3g" % value).strip()
185
186                    self.model.item(MODEL.NEUTRON_SLD_REAL).setText(format(results.neutron_sld_real))
187                    self.model.item(MODEL.NEUTRON_SLD_IMAG).setText(format(results.neutron_sld_imag))
188
189                    self.model.item(MODEL.CU_KA_SLD_REAL).setText(format(results.cu_ka_sld_real))
190                    self.model.item(MODEL.CU_KA_SLD_IMAG).setText(format(results.cu_ka_sld_imag))
191
192                    self.model.item(MODEL.MO_KA_SLD_REAL).setText(format(results.mo_ka_sld_real))
193                    self.model.item(MODEL.MO_KA_SLD_IMAG).setText(format(results.mo_ka_sld_imag))
194
195                    self.model.item(MODEL.NEUTRON_INC_XS).setText(format(results.neutron_inc_xs))
196                    self.model.item(MODEL.NEUTRON_ABS_XS).setText(format(results.neutron_abs_xs))
197                    self.model.item(MODEL.NEUTRON_LENGTH).setText(format(results.neutron_length))
198
199                    return
200           
201                except Exception as e:
202                    pass
203
204            for key in self._getOutputs().keys():
205                self.model.item(key).setText("")
206
207    def modelReset(self):
208        #self.model.beginResetModel()
209        try:
210            self.model.item(MODEL.MOLECULAR_FORMULA).setText("H2O")
211            self.model.item(MODEL.MASS_DENSITY     ).setText("1")
212            self.model.item(MODEL.WAVELENGTH       ).setText("6")
213        finally:
214            pass
215            #self.model.endResetModel()
216
217    def displayHelp(self):
218        try:
219            location = GuiUtils.HELP_DIRECTORY_LOCATION + \
220                "/user/sasgui/perspectives/calculator/sld_calculator_help.html"
221            self.manager._helpView.load(QtCore.QUrl(location))
222            self.manager._helpView.show()
223        except AttributeError:
224            # No manager defined - testing and standalone runs
225            pass
226
Note: See TracBrowser for help on using the repository browser.