source: sasview/src/sas/qtgui/Perspectives/Fitting/GPUOptions.py @ 37be27f

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 37be27f was 37be27f, checked in by krzywon, 7 years ago

Code cleanup on OpenCL Qt dialog.

  • Property mode set to 100644
File size: 8.0 KB
Line 
1# global
2import os
3import sys
4import sasmodels
5import json
6import platform
7
8from PyQt4 import QtGui, QtCore, QtWebKit
9from sas.qtgui.Perspectives.Fitting.UI.GPUOptionsUI import Ui_GPUOptions
10from sas.qtgui.Perspectives.Fitting.UI.GPUTestResultsUI import Ui_GPUTestResults
11
12try:
13    _fromUtf8 = QtCore.QString.fromUtf8
14except AttributeError:
15    def _fromUtf8(s):
16        return s
17
18try:
19    _encoding = QtGui.QApplication.UnicodeUTF8
20    def _translate(context, text, disambig):
21        return QtGui.QApplication.translate(context, text, disambig, _encoding)
22except AttributeError:
23    def _translate(context, text, disambig):
24        return QtGui.QApplication.translate(context, text, disambig)
25
26
27class GPUOptions(QtGui.QDialog, Ui_GPUOptions):
28    """
29    OpenCL Dialog to select the desired OpenCL driver
30    """
31
32    clicked = False
33    sas_open_cl = None
34
35    def __init__(self, parent=None):
36        super(GPUOptions, self).__init__(parent)
37        self.parent = parent
38        self.setupUi(self)
39        self.addOpenCLOptions()
40        self.createLinks()
41
42    def addOpenCLOptions(self):
43        """
44        Populate the window with a list of OpenCL options
45        """
46        # Get list of openCL options and add to GUI
47        cl_tuple = _get_clinfo()
48        i = 0
49        self.sas_open_cl = os.environ.get("SAS_OPENCL", "")
50        for title, descr in cl_tuple:
51            # Create an list item for each openCL option
52            check_box = QtGui.QCheckBox(self.openCLCheckBoxGroup)
53            check_box.setGeometry(20, 20 + i, 351, 30)
54            check_box.setObjectName(_fromUtf8(descr))
55            check_box.setText(_translate("GPUOptions", descr, None))
56            if (descr == self.sas_open_cl) or (
57                            title == "None" and not self.clicked):
58                check_box.click()
59                self.clicked = True
60
61            # Expand group and shift items down as more are added
62            self.openCLCheckBoxGroup.resize(391, 60 + i)
63            self.label.setGeometry(QtCore.QRect(20, 90 + i, 391, 37))
64            self.okButton.setGeometry(QtCore.QRect(20, 127 + i, 93, 28))
65            self.resetButton.setGeometry(QtCore.QRect(120, 127 + i, 93, 28))
66            self.testButton.setGeometry(QtCore.QRect(220, 127 + i, 93, 28))
67            self.helpButton.setGeometry(QtCore.QRect(320, 127 + i, 93, 28))
68            self.resize(440, 167 + i)
69            i += 30
70
71    def createLinks(self):
72        """
73        Link user interactions to function calls
74        """
75        self.testButton.clicked.connect(lambda: self.testButtonClicked())
76        self.helpButton.clicked.connect(lambda: self.helpButtonClicked())
77        for item in self.openCLCheckBoxGroup.findChildren(QtGui.QCheckBox):
78            item.clicked.connect(lambda: self.checked())
79
80    def checked(self):
81        """
82        Only allow a single check box to be selected. Uncheck others.
83        """
84        checked = None
85        for box in self.openCLCheckBoxGroup.findChildren(QtGui.QCheckBox):
86            if box.isChecked() and (str(box.text()) == self.sas_open_cl or (
87                    str(box.text()) == "No OpenCL" and self.sas_open_cl == "")):
88                box.setChecked(False)
89            elif box.isChecked():
90                checked = box
91        if hasattr(checked, "text"):
92            self.sas_open_cl = str(checked.text())
93        else:
94            self.sas_open_cl = None
95
96    def set_sas_open_cl(self):
97        """
98        Set SAS_OPENCL value when tests run or OK button clicked
99        """
100        no_opencl_msg = False
101        if self.sas_open_cl:
102            os.environ["SAS_OPENCL"] = self.sas_open_cl
103            if self.sas_open_cl.lower() == "none":
104                no_opencl_msg = True
105        else:
106            if "SAS_OPENCL" in os.environ:
107                del os.environ["SAS_OPENCL"]
108        # Sasmodels kernelcl doesn't exist when initiated with None
109        if 'sasmodels.kernelcl' in sys.modules:
110            sasmodels.kernelcl.ENV = None
111        reload(sasmodels.core)
112        return no_opencl_msg
113
114    def testButtonClicked(self):
115        """
116        Run sasmodels check from here and report results from
117        """
118
119        no_opencl_msg = self.set_sas_open_cl()
120
121        # Only import when tests are run
122        from sasmodels.model_test import model_tests
123
124        try:
125            from sasmodels.kernelcl import environment
126            env = environment()
127            clinfo = [(ctx.devices[0].platform.vendor,
128                       ctx.devices[0].platform.version,
129                       ctx.devices[0].vendor,
130                       ctx.devices[0].name,
131                       ctx.devices[0].version)
132                      for ctx in env.context]
133        except ImportError:
134            clinfo = None
135
136        failures = []
137        tests_completed = 0
138        for test in model_tests():
139            try:
140                test()
141            except Exception:
142                failures.append(test.description)
143
144            tests_completed += 1
145
146        info = {
147            'version': sasmodels.__version__,
148            'platform': platform.uname(),
149            'opencl': clinfo,
150            'failing tests': failures,
151        }
152
153        msg_info = 'OpenCL tests results'
154
155        msg = str(tests_completed) + ' tests completed.\n'
156        if len(failures) > 0:
157            msg += str(len(failures)) + ' tests failed.\n'
158            msg += 'Failing tests: '
159            msg += json.dumps(info['failing tests'])
160            msg += "\n"
161        else:
162            msg += "All tests passed!\n"
163
164        msg += "\nPlatform Details:\n\n"
165        msg += "Sasmodels version: "
166        msg += info['version'] + "\n"
167        msg += "\nPlatform used: "
168        msg += json.dumps(info['platform']) + "\n"
169        if no_opencl_msg:
170            msg += "\nOpenCL driver: None"
171        else:
172            msg += "\nOpenCL driver: "
173            msg += json.dumps(info['opencl']) + "\n"
174        GPUTestResults(self, msg, msg_info)
175
176    def helpButtonClicked(self):
177        """
178        Open the help menu when the help button is clicked
179        """
180        tree_location = "user/sasgui/perspectives/fitting/gpu_setup.html"
181        anchor = "#device-selection"
182        self.helpView = QtWebKit.QWebView()
183        help_location = tree_location + anchor
184        self.helpView.load(QtCore.QUrl(help_location))
185        self.helpView.show()
186
187    def reject(self):
188        """
189        Close the window without modifying SAS_OPENCL
190        """
191        self.closeEvent(None)
192        self.parent.gpu_options_widget.open()
193
194    def accept(self):
195        """
196        Close the window after modifying the SAS_OPENCL value
197        """
198        self.set_sas_open_cl()
199        self.closeEvent(None)
200
201    def closeEvent(self, event):
202        """
203        Overwrite QDialog close method to allow for custom widget close
204        """
205        self.close()
206        self.parent.gpu_options_widget = GPUOptions(self.parent)
207
208
209class GPUTestResults(QtGui.QDialog, Ui_GPUTestResults):
210    """
211    OpenCL Dialog to modify the OpenCL options
212    """
213    def __init__(self, parent, msg, title):
214        super(GPUTestResults, self).__init__(parent)
215        self.setupUi(self)
216        self.resultsText.setText(_translate("GPUTestResults", msg, None))
217        self.open()
218
219
220def _get_clinfo():
221    """
222    Read in information about available OpenCL infrastructure
223    """
224    clinfo = []
225    platforms = []
226    try:
227        import pyopencl as cl
228        platforms = cl.get_platforms()
229    except ImportError:
230        print("pyopencl import failed. Using only CPU computations")
231
232    p_index = 0
233    for platform in platforms:
234        d_index = 0
235        devices = platform.get_devices()
236        for device in devices:
237            if len(devices) > 1 and len(platforms) > 1:
238                combined_index = ":".join([str(p_index), str(d_index)])
239            elif len(platforms) > 1:
240                combined_index = str(p_index)
241            else:
242                combined_index = str(d_index)
243            clinfo.append((combined_index, ":".join([platform.name,
244                                                     device.name])))
245            d_index += 1
246        p_index += 1
247
248    clinfo.append(("None", "No OpenCL"))
249    return clinfo
Note: See TracBrowser for help on using the repository browser.