source: sasview/src/sas/sasgui/perspectives/fitting/gpu_options.py @ bd55e15

Last change on this file since bd55e15 was bd55e15, checked in by wojciech, 7 years ago

Added test button - currently outputs to console

  • Property mode set to 100644
File size: 7.0 KB
Line 
1'''
2Module provides dialog for setting SAS_OPENCL variable, which defines
3device choice for OpenCL calculation
4
5Created on Nov 29, 2016
6
7@author: wpotrzebowski
8'''
9
10import os
11import warnings
12import wx
13
14from sas.sasgui.guiframe.documentation_window import DocumentationWindow
15
16class GpuOptions(wx.Dialog):
17    """
18    "OpenCL options" Dialog Box
19
20    Provides dialog for setting SAS_OPENCL variable, which defines
21    device choice for OpenCL calculation
22
23    """
24
25    def __init__(self, *args, **kwds):
26
27        kwds["style"] = wx.DEFAULT_DIALOG_STYLE
28        wx.Dialog.__init__(self, *args, **kwds)
29
30        clinfo = self._get_clinfo()
31
32        self.panel1 = wx.Panel(self, -1)
33        static_box1 = wx.StaticBox(self.panel1, -1, "Available OpenCL Options:")
34
35        boxsizer = wx.BoxSizer(orient=wx.VERTICAL)
36        self.option_button = {}
37        self.buttons = []
38        #Check if SAS_OPENCL is already set
39        self.sas_opencl = os.environ.get("SAS_OPENCL","")
40        for clopt in clinfo:
41            button = wx.CheckBox(self.panel1, -1, label=clopt[1], name=clopt[1])
42
43            if clopt != "No OpenCL":
44                self.option_button[clopt[1]] = clopt[0]
45                if self.sas_opencl == clopt[0]:
46                    button.SetValue(1)
47            else:
48                self.option_button[clopt] = "None"
49                if self.sas_opencl.lower() == "none" :
50                    button.SetValue(1)
51
52            self.Bind(wx.EVT_CHECKBOX, self.on_check, id=button.GetId())
53            self.buttons.append(button)
54            boxsizer.Add(button, 0, 0)
55
56        fit_hsizer = wx.StaticBoxSizer(static_box1, orient=wx.VERTICAL)
57        fit_hsizer.Add(boxsizer, 0, wx.ALL, 5)
58
59        self.panel1.SetSizer(fit_hsizer)
60
61        self.vbox = wx.BoxSizer(wx.VERTICAL)
62        self.vbox.Add(self.panel1, 0, wx.ALL, 10)
63
64        accept_btn = wx.Button(self, wx.ID_OK)
65        accept_btn.SetToolTipString("Accept new OpenCL settings. This will"
66                                    " overwrite SAS_OPENCL variable if set")
67
68        help_id = wx.NewId()
69        help_btn = wx.Button(self, help_id, 'Help')
70        help_btn.SetToolTipString("Help on the GPU options")
71
72        reset_id = wx.NewId()
73        reset_btn = wx.Button(self, reset_id, 'Reset')
74        reset_btn.SetToolTipString("Restore initial settings")
75
76        test_id = wx.NewId()
77        test_btn = wx.Button(self, test_id, 'Test')
78        test_btn.SetToolTipString("Test if models compile on the given infrastructure")
79
80        self.Bind(wx.EVT_BUTTON, self.on_OK, accept_btn)
81        self.Bind(wx.EVT_BUTTON, self.on_test, test_btn)
82        self.Bind(wx.EVT_BUTTON, self.on_reset, reset_btn)
83        self.Bind(wx.EVT_BUTTON, self.on_help, help_btn)
84
85
86        btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
87        btn_sizer.Add((10, 20), 1) # stretchable whitespace
88        btn_sizer.Add(accept_btn, 0)
89        btn_sizer.Add((10, 20), 0) # non-stretchable whitespace
90        btn_sizer.Add(test_btn, 0)
91        btn_sizer.Add((10, 20), 0) # non-stretchable whitespace
92        btn_sizer.Add(reset_btn, 0)
93        btn_sizer.Add((10, 20), 0) # non-stretchable whitespace
94        btn_sizer.Add(help_btn, 0)
95
96        # Add the button sizer to the main sizer.
97        self.vbox.Add(btn_sizer, 0, wx.EXPAND|wx.ALL, 10)
98
99        self.SetSizer(self.vbox)
100        self.vbox.Fit(self)
101        self.SetTitle("OpenCL options")
102        self.Centre()
103
104    def _get_clinfo(self):
105        """
106        Reading in information about available OpenCL infrastructure
107        :return:
108        """
109        clinfo = []
110        try:
111            import pyopencl as cl
112            platforms = cl.get_platforms()
113            p_index = 0
114            for platform in platforms:
115                d_index = 0
116                devices = platform.get_devices()
117                for device in devices:
118                    if len(devices) > 1 and len(platforms) > 1:
119                        combined_index = ":".join([str(p_index),str(d_index)])
120                    elif len(platforms) > 1:
121                        combined_index = str(p_index)
122                    else:
123                        combined_index = str(d_index)
124                    #combined_index = ":".join([str(p_index),str(d_index)]) \
125                    #    if len(platforms) > 1 else str(d_index)
126                    clinfo.append((combined_index, ":".join([platform.name,device.name])))
127                    d_index += 1
128                p_index += 1
129        except ImportError:
130            warnings.warn("pyopencl import failed. Using only CPU computations")
131
132        clinfo.append(("None","No OpenCL"))
133        return clinfo
134
135    def on_check(self, event):
136        """
137        Action triggered when button is selected
138        :param event:
139        :return:
140        """
141        selected_button = event.GetEventObject()
142        for btn in self.buttons:
143            if btn != selected_button:
144                btn.SetValue(0)
145        if selected_button.GetValue():
146            self.sas_opencl = self.option_button[selected_button.Name]
147        else:
148            self.sas_opencl = None
149
150    def on_OK(self, event):
151        """
152        Close window on accpetance
153        """
154        import sasmodels
155        #If statement added to handle Reset
156        if self.sas_opencl:
157            os.environ["SAS_OPENCL"] = self.sas_opencl
158        else:
159            if "SAS_OPENCL" in os.environ:
160                del(os.environ["SAS_OPENCL"])
161        sasmodels.kernelcl.ENV = None
162        #Need to reload sasmodels.core module to account SAS_OPENCL = "None"
163        reload(sasmodels.core)
164        event.Skip()
165
166    def on_reset(self, event):
167        """
168        Close window on accpetance
169        """
170        for btn in self.buttons:
171            btn.SetValue(0)
172        self.sas_opencl=None
173
174    def on_test(self, event):
175        """
176        Run sasmodels check from here and report results from
177        """
178        import json
179        import platform
180
181        import sasmodels
182        from sasmodels.model_test import model_tests
183        try:
184            from sasmodels.kernelcl import environment
185            env = environment()
186            clinfo = [(ctx.devices[0].platform.vendor,
187                      ctx.devices[0].platform.version,
188                      ctx.devices[0].vendor,
189                      ctx.devices[0].name,
190                      ctx.devices[0].version)
191                    for ctx in env.context]
192        except ImportError:
193            clinfo = None
194
195        failures = []
196        for test in model_tests():
197            try:
198                test()
199            except Exception:
200                failures.append(test.description)
201
202        info = {
203            'version':  sasmodels.__version__,
204            'platform': platform.uname(),
205            'opencl': clinfo,
206            'failing tests': failures,
207        }
208        print(json.dumps(info['failing tests']))
209
210    def on_help(self, event):
211        """
212        Provide help on opencl options.
213        """
214        TreeLocation = "user/gpu_computations.html"
215        anchor = "#device-selection"
216        DocumentationWindow(self, -1,
217                            TreeLocation, anchor, "OpenCL Options Help")
Note: See TracBrowser for help on using the repository browser.