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

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

Expand horizontal window size with size of input text.

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