source: sasview/src/sas/sasgui/perspectives/fitting/models.py @ 68669da

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 68669da was 5de7f69, checked in by mathieu, 8 years ago

Prepend [plug-in] to custom models.

  • Property mode set to 100644
File size: 14.0 KB
Line 
1"""
2    Utilities to manage models
3"""
4import traceback
5import os
6import sys
7import os.path
8# Time is needed by the log method
9import time
10import datetime
11import logging
12import py_compile
13import shutil
14# Explicitly import from the pluginmodel module so that py2exe
15# places it in the distribution. The Model1DPlugin class is used
16# as the base class of plug-in models.
17from sas.sascalc.fit.pluginmodel import Model1DPlugin
18from sas.sasgui.guiframe.CategoryInstaller import CategoryInstaller
19from sasmodels.sasview_model import load_custom_model, load_standard_models
20
21
22PLUGIN_DIR = 'plugin_models'
23PLUGIN_LOG = os.path.join(os.path.expanduser("~"), '.sasview', PLUGIN_DIR,
24                          "plugins.log")
25
26def get_model_python_path():
27    """
28    Returns the python path for a model
29    """
30    return os.path.dirname(__file__)
31
32
33def plugin_log(message):
34    """
35    Log a message in a file located in the user's home directory
36    """
37    out = open(PLUGIN_LOG, 'a')
38    now = time.time()
39    stamp = datetime.datetime.fromtimestamp(now).strftime('%Y-%m-%d %H:%M:%S')
40    out.write("%s: %s\n" % (stamp, message))
41    out.close()
42
43
44def _check_plugin(model, name):
45    """
46    Do some checking before model adding plugins in the list
47
48    :param model: class model to add into the plugin list
49    :param name:name of the module plugin
50
51    :return model: model if valid model or None if not valid
52
53    """
54    #Check if the plugin is of type Model1DPlugin
55    if not issubclass(model, Model1DPlugin):
56        msg = "Plugin %s must be of type Model1DPlugin \n" % str(name)
57        plugin_log(msg)
58        return None
59    if model.__name__ != "Model":
60        msg = "Plugin %s class name must be Model \n" % str(name)
61        plugin_log(msg)
62        return None
63    try:
64        new_instance = model()
65    except:
66        msg = "Plugin %s error in __init__ \n\t: %s %s\n" % (str(name),
67                                                             str(sys.exc_type),
68                                                             sys.exc_info()[1])
69        plugin_log(msg)
70        return None
71
72    if hasattr(new_instance, "function"):
73        try:
74            value = new_instance.function()
75        except:
76            msg = "Plugin %s: error writing function \n\t :%s %s\n " % \
77                    (str(name), str(sys.exc_type), sys.exc_info()[1])
78            plugin_log(msg)
79            return None
80    else:
81        msg = "Plugin  %s needs a method called function \n" % str(name)
82        plugin_log(msg)
83        return None
84    return model
85
86
87def find_plugins_dir():
88    """
89    Find path of the plugins directory.
90    The plugin directory is located in the user's home directory.
91    """
92    dir = os.path.join(os.path.expanduser("~"), '.sasview', PLUGIN_DIR)
93
94    # If the plugin directory doesn't exist, create it
95    if not os.path.isdir(dir):
96        os.makedirs(dir)
97
98    # Find paths needed
99    try:
100        # For source
101        if os.path.isdir(os.path.dirname(__file__)):
102            p_dir = os.path.join(os.path.dirname(__file__), PLUGIN_DIR)
103        else:
104            raise
105    except:
106        # Check for data path next to exe/zip file.
107        #Look for maximum n_dir up of the current dir to find plugins dir
108        n_dir = 12
109        p_dir = None
110        f_dir = os.path.join(os.path.dirname(__file__))
111        for i in range(n_dir):
112            if i > 1:
113                f_dir, _ = os.path.split(f_dir)
114            plugin_path = os.path.join(f_dir, PLUGIN_DIR)
115            if os.path.isdir(plugin_path):
116                p_dir = plugin_path
117                break
118        if not p_dir:
119            raise
120    # Place example user models as needed
121    if os.path.isdir(p_dir):
122        for file in os.listdir(p_dir):
123            file_path = os.path.join(p_dir, file)
124            if os.path.isfile(file_path):
125                if file.split(".")[-1] == 'py' and\
126                    file.split(".")[0] != '__init__':
127                    if not os.path.isfile(os.path.join(dir, file)):
128                        shutil.copy(file_path, dir)
129
130    return dir
131
132
133class ReportProblem:
134    """
135    Class to check for problems with specific values
136    """
137    def __nonzero__(self):
138        type, value, tb = sys.exc_info()
139        if type is not None and issubclass(type, py_compile.PyCompileError):
140            print "Problem with", repr(value)
141            raise type, value, tb
142        return 1
143
144report_problem = ReportProblem()
145
146
147def compile_file(dir):
148    """
149    Compile a py file
150    """
151    try:
152        import compileall
153        compileall.compile_dir(dir=dir, ddir=dir, force=1,
154                               quiet=report_problem)
155    except:
156        return sys.exc_info()[1]
157    return None
158
159
160def _findModels(dir):
161    """
162    Find custom models
163    """
164    # List of plugin objects
165    dir = find_plugins_dir()
166    # Go through files in plug-in directory
167    if not os.path.isdir(dir):
168        msg = "SasView couldn't locate Model plugin folder %r." % dir
169        logging.warning(msg)
170        return {}
171
172    plugin_log("looking for models in: %s" % str(dir))
173    #compile_file(dir)  #always recompile the folder plugin
174    logging.info("plugin model dir: %s" % str(dir))
175
176    plugins = {}
177    for filename in os.listdir(dir):
178        name, ext = os.path.splitext(filename)
179        if ext == '.py' and not name == '__init__':
180            path = os.path.abspath(os.path.join(dir, filename))
181            try:
182                model = load_custom_model(path)
183                model.name = "[plug-in] "+model.name
184                plugins[model.name] = model
185            except Exception:
186                msg = traceback.format_exc()
187                msg += "\nwhile accessing model in %r" % path
188                plugin_log(msg)
189                logging.warning("Failed to load plugin %r. See %s for details"
190                                % (path, PLUGIN_LOG))
191           
192    return plugins
193
194
195class ModelList(object):
196    """
197    Contains dictionary of model and their type
198    """
199    def __init__(self):
200        """
201        """
202        self.mydict = {}
203
204    def set_list(self, name, mylist):
205        """
206        :param name: the type of the list
207        :param mylist: the list to add
208
209        """
210        if name not in self.mydict.keys():
211            self.reset_list(name, mylist)
212
213    def reset_list(self, name, mylist):
214        """
215        :param name: the type of the list
216        :param mylist: the list to add
217        """
218        self.mydict[name] = mylist
219
220    def get_list(self):
221        """
222        return all the list stored in a dictionary object
223        """
224        return self.mydict
225
226
227class ModelManagerBase:
228    """
229    Base class for the model manager
230    """
231    ## external dict for models
232    model_combobox = ModelList()
233    ## Dictionary of form factor models
234    form_factor_dict = {}
235    ## dictionary of structure factor models
236    struct_factor_dict = {}
237    ##list of structure factors
238    struct_list = []
239    ##list of model allowing multiplication by a structure factor
240    multiplication_factor = []
241    ##list of multifunctional shapes (i.e. that have user defined number of levels
242    multi_func_list = []
243    ## list of added models -- currently python models found in the plugin dir.
244    plugins = []
245    ## Event owner (guiframe)
246    event_owner = None
247    last_time_dir_modified = 0
248
249    def __init__(self):
250        self.model_dictionary = {}
251        self.stored_plugins = {}
252        self._getModelList()
253
254    def findModels(self):
255        """
256        find  plugin model in directory of plugin .recompile all file
257        in the directory if file were modified
258        """
259        temp = {}
260        if self.is_changed():
261            return  _findModels(dir)
262        logging.info("plugin model : %s" % str(temp))
263        return temp
264
265    def _getModelList(self):
266        """
267        List of models we want to make available by default
268        for this application
269
270        :return: the next free event ID following the new menu events
271
272        """
273
274        # regular model names only
275        self.model_name_list = []
276
277        #Build list automagically from sasmodels package
278        for model in load_standard_models():
279            self.model_dictionary[model.name] = model
280            if model.is_structure_factor:
281                self.struct_list.append(model)
282            if model.is_form_factor:
283                self.multiplication_factor.append(model)
284            if model.is_multiplicity_model:
285                self.multi_func_list.append(model)
286            else:
287                self.model_name_list.append(model.name)
288
289        #Looking for plugins
290        self.stored_plugins = self.findModels()
291        self.plugins = self.stored_plugins.values()
292        for name, plug in self.stored_plugins.iteritems():
293            self.model_dictionary[name] = plug
294       
295        self._get_multifunc_models()
296
297        return 0
298
299    def is_changed(self):
300        """
301        check the last time the plugin dir has changed and return true
302        is the directory was modified else return false
303        """
304        is_modified = False
305        plugin_dir = find_plugins_dir()
306        if os.path.isdir(plugin_dir):
307            temp = os.path.getmtime(plugin_dir)
308            if  self.last_time_dir_modified != temp:
309                is_modified = True
310                self.last_time_dir_modified = temp
311
312        return is_modified
313
314    def update(self):
315        """
316        return a dictionary of model if
317        new models were added else return empty dictionary
318        """
319        new_plugins = self.findModels()
320        if len(new_plugins) > 0:
321            for name, plug in  new_plugins.iteritems():
322                if name not in self.stored_plugins.keys():
323                    self.stored_plugins[name] = plug
324                    self.plugins.append(plug)
325                    self.model_dictionary[name] = plug
326            self.model_combobox.set_list("Customized Models", self.plugins)
327            return self.model_combobox.get_list()
328        else:
329            return {}
330
331    def plugins_reset(self):
332        """
333        return a dictionary of model
334        """
335        self.plugins = []
336        new_plugins = _findModels(dir)
337        for name, plug in  new_plugins.iteritems():
338            for stored_name, stored_plug in self.stored_plugins.iteritems():
339                if name == stored_name:
340                    del self.stored_plugins[name]
341                    del self.model_dictionary[name]
342                    break
343            self.stored_plugins[name] = plug
344            self.plugins.append(plug)
345            self.model_dictionary[name] = plug
346
347        self.model_combobox.reset_list("Customized Models", self.plugins)
348        return self.model_combobox.get_list()
349
350    def _on_model(self, evt):
351        """
352        React to a model menu event
353
354        :param event: wx menu event
355
356        """
357        if int(evt.GetId()) in self.form_factor_dict.keys():
358            from sas.sascalc.fit.MultiplicationModel import MultiplicationModel
359            self.model_dictionary[MultiplicationModel.__name__] = MultiplicationModel
360            model1, model2 = self.form_factor_dict[int(evt.GetId())]
361            model = MultiplicationModel(model1, model2)
362        else:
363            model = self.struct_factor_dict[str(evt.GetId())]()
364
365
366    def _get_multifunc_models(self):
367        """
368        Get the multifunctional models
369        """
370        items = [item for item in self.plugins if item.is_multiplicity_model]
371        self.multi_func_list = items
372
373    def get_model_list(self):
374        """
375        return dictionary of models for fitpanel use
376
377        """
378        ## Model_list now only contains attribute lists not category list.
379        ## Eventually this should be in one master list -- read in category
380        ## list then pull those models that exist and get attributes then add
381        ## to list ..and if model does not exist remove from list as now
382        ## and update json file.
383        ##
384        ## -PDB   April 26, 2014
385
386#        self.model_combobox.set_list("Shapes", self.shape_list)
387#        self.model_combobox.set_list("Shape-Independent",
388#                                     self.shape_indep_list)
389        self.model_combobox.set_list("Structure Factors", self.struct_list)
390        self.model_combobox.set_list("Customized Models", self.plugins)
391        self.model_combobox.set_list("P(Q)*S(Q)", self.multiplication_factor)
392        self.model_combobox.set_list("multiplication",
393                                     self.multiplication_factor)
394        self.model_combobox.set_list("Multi-Functions", self.multi_func_list)
395        return self.model_combobox.get_list()
396
397    def get_model_name_list(self):
398        """
399        return regular model name list
400        """
401        return self.model_name_list
402
403    def get_model_dictionary(self):
404        """
405        return dictionary linking model names to objects
406        """
407        return self.model_dictionary
408
409
410class ModelManager(object):
411    """
412    implement model
413    """
414    __modelmanager = ModelManagerBase()
415    cat_model_list = [__modelmanager.model_dictionary[model_name] for model_name \
416                      in __modelmanager.model_dictionary.keys() \
417                      if model_name not in __modelmanager.stored_plugins.keys()]
418
419    CategoryInstaller.check_install(model_list=cat_model_list)
420    def findModels(self):
421        return self.__modelmanager.findModels()
422
423    def _getModelList(self):
424        return self.__modelmanager._getModelList()
425
426    def is_changed(self):
427        return self.__modelmanager.is_changed()
428
429    def update(self):
430        return self.__modelmanager.update()
431
432    def plugins_reset(self):
433        return self.__modelmanager.plugins_reset()
434
435    def populate_menu(self, modelmenu, event_owner):
436        return self.__modelmanager.populate_menu(modelmenu, event_owner)
437
438    def _on_model(self, evt):
439        return self.__modelmanager._on_model(evt)
440
441    def _get_multifunc_models(self):
442        return self.__modelmanager._get_multifunc_models()
443
444    def get_model_list(self):
445        return self.__modelmanager.get_model_list()
446
447    def get_model_name_list(self):
448        return self.__modelmanager.get_model_name_list()
449
450    def get_model_dictionary(self):
451        return self.__modelmanager.get_model_dictionary()
Note: See TracBrowser for help on using the repository browser.