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

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

Writting to settings file

  • Property mode set to 100644
File size: 8.3 KB
RevLine 
[f78c7d2]1'''
[8f02f7f]2Module provides dialog for setting SAS_OPENCL variable, which defines
3device choice for OpenCL calculation
4
[16c1297]5Created on Nov 29, 2016
[f78c7d2]6
[16c1297]7@author: wpotrzebowski
[f78c7d2]8'''
9
[6a569b3]10import os
11import warnings
[f78c7d2]12import wx
[6af411b]13import logging
[16c1297]14from sas.sasgui.guiframe.documentation_window import DocumentationWindow
[62243ae]15import imp
[16c1297]16
[f78c7d2]17class GpuOptions(wx.Dialog):
18    """
[8f02f7f]19    "OpenCL options" Dialog Box
[f78c7d2]20
[8f02f7f]21    Provides dialog for setting SAS_OPENCL variable, which defines
22    device choice for OpenCL calculation
[f78c7d2]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
[16c1297]31        clinfo = self._get_clinfo()
[9fdf302]32
[f78c7d2]33        self.panel1 = wx.Panel(self, -1)
[16c1297]34        static_box1 = wx.StaticBox(self.panel1, -1, "Available OpenCL Options:")
[f78c7d2]35
[9fdf302]36        boxsizer = wx.BoxSizer(orient=wx.VERTICAL)
[c2cb772]37        self.option_button = {}
[bacc04b]38        self.buttons = []
[6af411b]39        #Check if SAS_OPENCL is already set as enviromental variable
[62243ae]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
[6af411b]43
[ebaaf05]44        for clopt in clinfo:
45            button = wx.CheckBox(self.panel1, -1, label=clopt[1], name=clopt[1])
[71ac835]46
[a9279cc]47            if clopt != "No OpenCL":
[ebaaf05]48                self.option_button[clopt[1]] = clopt[0]
49                if self.sas_opencl == clopt[0]:
[71ac835]50                    button.SetValue(1)
[c2cb772]51            else:
[a9279cc]52                self.option_button[clopt] = "None"
[62243ae]53                if self.sas_opencl.lower() == "none":
[71ac835]54                    button.SetValue(1)
55
[8f02f7f]56            self.Bind(wx.EVT_CHECKBOX, self.on_check, id=button.GetId())
[bacc04b]57            self.buttons.append(button)
[9fdf302]58            boxsizer.Add(button, 0, 0)
[f78c7d2]59
60        fit_hsizer = wx.StaticBoxSizer(static_box1, orient=wx.VERTICAL)
[9fdf302]61        fit_hsizer.Add(boxsizer, 0, wx.ALL, 5)
[f78c7d2]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)
[c2cb772]67
68        accept_btn = wx.Button(self, wx.ID_OK)
[71ac835]69        accept_btn.SetToolTipString("Accept new OpenCL settings. This will"
[7feb69d]70                                    " overwrite SAS_OPENCL variable if set")
[c2cb772]71
[075c460]72        help_id = wx.NewId()
73        help_btn = wx.Button(self, help_id, 'Help')
[c2cb772]74        help_btn.SetToolTipString("Help on the GPU options")
75
[71ac835]76        reset_id = wx.NewId()
77        reset_btn = wx.Button(self, reset_id, 'Reset')
78        reset_btn.SetToolTipString("Restore initial settings")
79
[bd55e15]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
[8f02f7f]84        self.Bind(wx.EVT_BUTTON, self.on_OK, accept_btn)
[bd55e15]85        self.Bind(wx.EVT_BUTTON, self.on_test, test_btn)
[71ac835]86        self.Bind(wx.EVT_BUTTON, self.on_reset, reset_btn)
[6a569b3]87        self.Bind(wx.EVT_BUTTON, self.on_help, help_btn)
[c2cb772]88
[bd55e15]89
[c2cb772]90        btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
[6a569b3]91        btn_sizer.Add((10, 20), 1) # stretchable whitespace
[c2cb772]92        btn_sizer.Add(accept_btn, 0)
[6a569b3]93        btn_sizer.Add((10, 20), 0) # non-stretchable whitespace
[bd55e15]94        btn_sizer.Add(test_btn, 0)
95        btn_sizer.Add((10, 20), 0) # non-stretchable whitespace
[71ac835]96        btn_sizer.Add(reset_btn, 0)
97        btn_sizer.Add((10, 20), 0) # non-stretchable whitespace
[c2cb772]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)
[7feb69d]105        self.SetTitle("OpenCL options")
[c2cb772]106        self.Centre()
[f78c7d2]107
[16c1297]108    def _get_clinfo(self):
[7feb69d]109        """
110        Reading in information about available OpenCL infrastructure
111        :return:
112        """
[95f0cbb]113        clinfo = []
[16c1297]114        try:
115            import pyopencl as cl
[ebaaf05]116            platforms = cl.get_platforms()
117            p_index = 0
118            for platform in platforms:
119                d_index = 0
[9010f5f]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)
[ebaaf05]130                    clinfo.append((combined_index, ":".join([platform.name,device.name])))
[9010f5f]131                    d_index += 1
132                p_index += 1
[6a569b3]133        except ImportError:
[4139147]134            warnings.warn("pyopencl import failed. Using only CPU computations")
[95f0cbb]135
[ebaaf05]136        clinfo.append(("None","No OpenCL"))
[16c1297]137        return clinfo
[f78c7d2]138
[6c6aa83]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
[8f02f7f]159    def on_check(self, event):
[6a569b3]160        """
161        Action triggered when button is selected
162        :param event:
163        :return:
164        """
[bacc04b]165        selected_button = event.GetEventObject()
166        for btn in self.buttons:
167            if btn != selected_button:
168                btn.SetValue(0)
[7feb69d]169        if selected_button.GetValue():
170            self.sas_opencl = self.option_button[selected_button.Name]
171        else:
172            self.sas_opencl = None
[c2cb772]173
[8f02f7f]174    def on_OK(self, event):
[c2cb772]175        """
[9fdf302]176        Close window on accpetance
[c2cb772]177        """
[8f02f7f]178        import sasmodels
[71ac835]179        #If statement added to handle Reset
180        if self.sas_opencl:
181            os.environ["SAS_OPENCL"] = self.sas_opencl
[62243ae]182        else:
[71ac835]183            if "SAS_OPENCL" in os.environ:
184                del(os.environ["SAS_OPENCL"])
[62243ae]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
[6af411b]194
[8f02f7f]195        #Need to reload sasmodels.core module to account SAS_OPENCL = "None"
196        reload(sasmodels.core)
[c2cb772]197        event.Skip()
198
[71ac835]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
[bd55e15]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
[c027106e]243    def on_help(self, event):
[c2cb772]244        """
[9fdf302]245        Provide help on opencl options.
[c2cb772]246        """
[6a569b3]247        TreeLocation = "user/gpu_computations.html"
248        anchor = "#device-selection"
[16c1297]249        DocumentationWindow(self, -1,
[6a569b3]250                            TreeLocation, anchor, "OpenCL Options Help")
Note: See TracBrowser for help on using the repository browser.