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

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalcmagnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since ba8d326 was ba8d326, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

code cleanup

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