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

ESS_GUI
Last change on this file since d76beb4 was 33c0561, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 5 years ago

Replace Apply button menu driven functionality with additional button.
Removed Cancel.
Removed the window system context help button from all affected widgets.
SASVIEW-1239

  • Property mode set to 100644
File size: 8.5 KB
Line 
1# global
2import os
3import sys
4import json
5import platform
6import webbrowser
7import logging
8
9import sasmodels
10import sasmodels.model_test
11import sasmodels.kernelcl
12
13import sas.qtgui.Utilities.GuiUtils as GuiUtils
14from PyQt5 import QtGui, QtCore, QtWidgets
15from sas.qtgui.Perspectives.Fitting.UI.GPUOptionsUI import Ui_GPUOptions
16from sas.qtgui.Perspectives.Fitting.UI.GPUTestResultsUI import Ui_GPUTestResults
17
18try:
19    _fromUtf8 = QtCore.QString.fromUtf8
20except AttributeError:
21    def _fromUtf8(s):
22        return s
23
24try:
25    _encoding = QtWidgets.QApplication.UnicodeUTF8
26    def _translate(context, text, disambig):
27        return QtWidgets.QApplication.translate(context, text, disambig, _encoding)
28except AttributeError:
29    def _translate(context, text, disambig):
30        return QtWidgets.QApplication.translate(context, text, disambig)
31
32logger = logging.getLogger(__name__)
33
34class GPUOptions(QtWidgets.QDialog, Ui_GPUOptions):
35    """
36    OpenCL Dialog to select the desired OpenCL driver
37    """
38
39    clicked = False
40    sas_open_cl = None
41    cl_options = None
42
43    def __init__(self, parent=None):
44        super(GPUOptions, self).__init__(parent)
45        self.parent = parent
46        self.setupUi(self)
47        # disable the context help icon
48        self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint)
49        self.addOpenCLOptions()
50        self.createLinks()
51
52    def addOpenCLOptions(self):
53        """
54        Populate the window with a list of OpenCL options
55        """
56        # Get list of openCL options and add to GUI
57        cl_tuple = _get_clinfo()
58        self.sas_open_cl = os.environ.get("SAS_OPENCL", "")
59
60        # Keys are the names in the form "platform: device". Corresponding values are the combined indices, e.g.
61        # "0:1", for setting the SAS_OPENCL env.
62        self.cl_options = {}
63
64        for title, descr in cl_tuple:
65            # Create an item for each openCL option
66            check_box = QtWidgets.QCheckBox()
67            check_box.setObjectName(_fromUtf8(descr))
68            check_box.setText(_translate("GPUOptions", descr, None))
69            self.optionsLayout.addWidget(check_box)
70            if (title == self.sas_open_cl) or (
71                            title == "None" and not self.clicked):
72                check_box.click()
73                self.clicked = True
74            self.cl_options[descr] = title
75        self.openCLCheckBoxGroup.setMinimumWidth(self.optionsLayout.sizeHint().width()+10)
76
77    def createLinks(self):
78        """
79        Link user interactions to function calls
80        """
81        self.testButton.clicked.connect(self.testButtonClicked)
82        self.helpButton.clicked.connect(self.helpButtonClicked)
83        for item in self.openCLCheckBoxGroup.findChildren(QtWidgets.QCheckBox):
84            item.clicked.connect(self.checked)
85
86    def checked(self):
87        """
88        Only allow a single check box to be selected. Uncheck others.
89        """
90        checked = None
91        for box in self.openCLCheckBoxGroup.findChildren(QtWidgets.QCheckBox):
92            if box.isChecked() and (self.cl_options[str(box.text())] == self.sas_open_cl or (
93                    str(box.text()) == "No OpenCL" and self.sas_open_cl == "")):
94                box.setChecked(False)
95            elif box.isChecked():
96                checked = box
97        if hasattr(checked, "text"):
98            self.sas_open_cl = self.cl_options[str(checked.text())]
99        else:
100            self.sas_open_cl = None
101
102    def set_sas_open_cl(self):
103        """
104        Set SAS_OPENCL value when tests run or OK button clicked
105        """
106        no_opencl_msg = False
107        if self.sas_open_cl:
108            os.environ["SAS_OPENCL"] = self.sas_open_cl
109            if self.sas_open_cl.lower() == "none":
110                no_opencl_msg = True
111        else:
112            if "SAS_OPENCL" in os.environ:
113                del os.environ["SAS_OPENCL"]
114        # Sasmodels kernelcl doesn't exist when initiated with None
115        sasmodels.kernelcl.reset_environment()
116        return no_opencl_msg
117
118    def testButtonClicked(self):
119        """
120        Run sasmodels check from here and report results from
121        """
122
123        no_opencl_msg = self.set_sas_open_cl()
124
125        # Only import when tests are run
126        from sasmodels.model_test import model_tests
127
128        try:
129            env = sasmodels.kernelcl.environment()
130            clinfo = [(ctx.devices[0].platform.vendor,
131                       ctx.devices[0].platform.version,
132                       ctx.devices[0].vendor,
133                       ctx.devices[0].name,
134                       ctx.devices[0].version)
135                      for ctx in env.context]
136        except Exception:
137            clinfo = None
138
139        failures = []
140        tests_completed = 0
141        for test in model_tests():
142            try:
143                test()
144            except Exception:
145                failures.append(test.description)
146
147            tests_completed += 1
148
149        info = {
150            'version': sasmodels.__version__,
151            'platform': platform.uname(),
152            'opencl': clinfo,
153            'failing tests': failures,
154        }
155
156        msg = str(tests_completed) + ' tests completed.\n'
157        if len(failures) > 0:
158            msg += str(len(failures)) + ' tests failed.\n'
159            msg += 'Failing tests: '
160            msg += json.dumps(info['failing tests'])
161            msg += "\n"
162        else:
163            msg += "All tests passed!\n"
164
165        msg += "\nPlatform Details:\n\n"
166        msg += "Sasmodels version: "
167        msg += info['version'] + "\n"
168        msg += "\nPlatform used: "
169        msg += json.dumps(info['platform']) + "\n"
170        if no_opencl_msg:
171            msg += "\nOpenCL driver: None"
172        else:
173            msg += "\nOpenCL driver: "
174            msg += json.dumps(info['opencl']) + "\n"
175        GPUTestResults(self, msg)
176
177    def helpButtonClicked(self):
178        """
179        Open the help menu when the help button is clicked
180        """
181        help_location = GuiUtils.HELP_DIRECTORY_LOCATION
182        help_location += "/user/qtgui/Perspectives/Fitting/gpu_setup.html"
183        help_location += "#device-selection"
184        # Display the page in default browser
185        webbrowser.open('file://' + os.path.realpath(help_location))
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(QtWidgets.QDialog, Ui_GPUTestResults):
210    """
211    OpenCL Dialog to modify the OpenCL options
212    """
213    def __init__(self, parent, msg):
214        super(GPUTestResults, self).__init__(parent)
215        self.setupUi(self)
216        self.resultsText.setText(_translate("GPUTestResults", msg, None))
217        #self.setFixedSize(self.size())
218        self.open()
219
220
221def _get_clinfo():
222    """
223    Read in information about available OpenCL infrastructure
224    """
225    clinfo = []
226    cl_platforms = []
227
228    try:
229        import pyopencl as cl
230    except ImportError:
231        cl = None
232
233    if cl is None:
234        logger.warn("Unable to import the pyopencl package.  It may not "
235                    "have been installed.  If you wish to use OpenCL, try "
236                    "running pip install --user pyopencl")
237    else:
238        try:
239            cl_platforms = cl.get_platforms()
240        except cl.LogicError as err:
241            logger.warn("Unable to fetch the OpenCL platforms.  This likely "
242                        "means that the opencl drivers for your system are "
243                        "not installed.")
244            logger.warn(err)
245
246    p_index = 0
247    for cl_platform in cl_platforms:
248        d_index = 0
249        cl_devices = cl_platform.get_devices()
250        for cl_device in cl_devices:
251            if len(cl_platforms) > 1 and len(cl_devices) > 1:
252                combined_index = ":".join([str(p_index), str(d_index)])
253            elif len(cl_platforms) > 1:
254                combined_index = str(p_index)
255            else:
256                combined_index = str(d_index)
257            clinfo.append((combined_index, ": ".join([cl_platform.name,
258                                                     cl_device.name])))
259            d_index += 1
260        p_index += 1
261
262    clinfo.append(("None", "No OpenCL"))
263    return clinfo
Note: See TracBrowser for help on using the repository browser.