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

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

Writting to settings file

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