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

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 146c669 was 146c669, checked in by krzywon, 7 years ago

Resolved a merge conflict with a method name change.

  • 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
22from sas.sasgui.perspectives.fitting.fitpage import CUSTOM_MODEL
23
24logger = logging.getLogger(__name__)
25
26
27PLUGIN_DIR = 'plugin_models'
28PLUGIN_LOG = os.path.join(os.path.expanduser("~"), '.sasview', PLUGIN_DIR,
29                          "plugins.log")
30PLUGIN_NAME_BASE = '[plug-in] '
31
32def get_model_python_path():
33    """
34    Returns the python path for a model
35    """
36    return os.path.dirname(__file__)
37
38
39def plugin_log(message):
40    """
41    Log a message in a file located in the user's home directory
42    """
43    out = open(PLUGIN_LOG, 'a')
44    now = time.time()
45    stamp = datetime.datetime.fromtimestamp(now).strftime('%Y-%m-%d %H:%M:%S')
46    out.write("%s: %s\n" % (stamp, message))
47    out.close()
48
49
50def _check_plugin(model, name):
51    """
52    Do some checking before model adding plugins in the list
53
54    :param model: class model to add into the plugin list
55    :param name:name of the module plugin
56
57    :return model: model if valid model or None if not valid
58
59    """
60    #Check if the plugin is of type Model1DPlugin
61    if not issubclass(model, Model1DPlugin):
62        msg = "Plugin %s must be of type Model1DPlugin \n" % str(name)
63        plugin_log(msg)
64        return None
65    if model.__name__ != "Model":
66        msg = "Plugin %s class name must be Model \n" % str(name)
67        plugin_log(msg)
68        return None
69    try:
70        new_instance = model()
71    except:
72        msg = "Plugin %s error in __init__ \n\t: %s %s\n" % (str(name),
73                                                             str(sys.exc_type),
74                                                             sys.exc_info()[1])
75        plugin_log(msg)
76        return None
77
78    if hasattr(new_instance, "function"):
79        try:
80            value = new_instance.function()
81        except:
82            msg = "Plugin %s: error writing function \n\t :%s %s\n " % \
83                    (str(name), str(sys.exc_type), sys.exc_info()[1])
84            plugin_log(msg)
85            return None
86    else:
87        msg = "Plugin  %s needs a method called function \n" % str(name)
88        plugin_log(msg)
89        return None
90    return model
91
92
93def find_plugins_dir():
94    """
95    Find path of the plugins directory.
96    The plugin directory is located in the user's home directory.
97    """
98    dir = os.path.join(os.path.expanduser("~"), '.sasview', PLUGIN_DIR)
99
100    # If the plugin directory doesn't exist, create it
101    if not os.path.isdir(dir):
102        os.makedirs(dir)
103
104    # Find paths needed
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:
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:
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:
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            temp =  _find_models()
268            self.last_time_dir_modified = time.time()
269            return temp
270        logger.info("plugin model : %s" % str(temp))
271        return temp
272
273    def _getModelList(self):
274        """
275        List of models we want to make available by default
276        for this application
277
278        :return: the next free event ID following the new menu events
279
280        """
281
282        # regular model names only
283        self.model_name_list = []
284
285        #Build list automagically from sasmodels package
286        for model in load_standard_models():
287            self.model_dictionary[model.name] = model
288            if model.is_structure_factor:
289                self.struct_list.append(model)
290            if model.is_form_factor:
291                self.multiplication_factor.append(model)
292            if model.is_multiplicity_model:
293                self.multi_func_list.append(model)
294            else:
295                self.model_name_list.append(model.name)
296
297        #Looking for plugins
298        self.stored_plugins = self.findModels()
299        self.plugins = self.stored_plugins.values()
300        for name, plug in self.stored_plugins.iteritems():
301            self.model_dictionary[name] = plug
302       
303        self._get_multifunc_models()
304
305        return 0
306
307    def is_changed(self):
308        """
309        check the last time the plugin dir has changed and return true
310        is the directory was modified else return false
311        """
312        is_modified = False
313        plugin_dir = find_plugins_dir()
314        if os.path.isdir(plugin_dir):
315            temp = os.path.getmtime(plugin_dir)
316            if  self.last_time_dir_modified < temp:
317                is_modified = True
318                self.last_time_dir_modified = temp
319
320        return is_modified
321
322    def update(self):
323        """
324        return a dictionary of model if
325        new models were added else return empty dictionary
326        """
327        self.plugins = []
328        new_plugins = self.findModels()
329        if new_plugins:
330            for name, plug in  new_plugins.items():
331                self.stored_plugins[name] = plug
332                self.plugins.append(plug)
333                self.model_dictionary[name] = plug
334            self.model_combobox.set_list(CUSTOM_MODEL, self.plugins)
335            return self.model_combobox.get_list()
336        else:
337            return {}
338
339    def plugins_reset(self):
340        """
341        return a dictionary of model
342        """
343        self.plugins = []
344        new_plugins = _find_models()
345        for name, plug in  new_plugins.iteritems():
346            for stored_name, stored_plug in self.stored_plugins.iteritems():
347                if name == stored_name:
348                    del self.stored_plugins[name]
349                    del self.model_dictionary[name]
350                    break
351            self.stored_plugins[name] = plug
352            self.plugins.append(plug)
353            self.model_dictionary[name] = plug
354
355        self.model_combobox.reset_list("Plugin Models", self.plugins)
356        return self.model_combobox.get_list()
357
358    def _on_model(self, evt):
359        """
360        React to a model menu event
361
362        :param event: wx menu event
363
364        """
365        if int(evt.GetId()) in self.form_factor_dict.keys():
366            from sasmodels.sasview_model import MultiplicationModel
367            self.model_dictionary[MultiplicationModel.__name__] = MultiplicationModel
368            model1, model2 = self.form_factor_dict[int(evt.GetId())]
369            model = MultiplicationModel(model1, model2)
370        else:
371            model = self.struct_factor_dict[str(evt.GetId())]()
372
373
374    def _get_multifunc_models(self):
375        """
376        Get the multifunctional models
377        """
378        items = [item for item in self.plugins if item.is_multiplicity_model]
379        self.multi_func_list = items
380
381    def get_model_list(self):
382        """
383        return dictionary of models for fitpanel use
384
385        """
386        ## Model_list now only contains attribute lists not category list.
387        ## Eventually this should be in one master list -- read in category
388        ## list then pull those models that exist and get attributes then add
389        ## to list ..and if model does not exist remove from list as now
390        ## and update json file.
391        ##
392        ## -PDB   April 26, 2014
393
394#        self.model_combobox.set_list("Shapes", self.shape_list)
395#        self.model_combobox.set_list("Shape-Independent",
396#                                     self.shape_indep_list)
397        self.model_combobox.set_list("Structure Factors", self.struct_list)
398        self.model_combobox.set_list("Plugin Models", self.plugins)
399        self.model_combobox.set_list("P(Q)*S(Q)", self.multiplication_factor)
400        self.model_combobox.set_list("multiplication",
401                                     self.multiplication_factor)
402        self.model_combobox.set_list("Multi-Functions", self.multi_func_list)
403        return self.model_combobox.get_list()
404
405    def get_model_name_list(self):
406        """
407        return regular model name list
408        """
409        return self.model_name_list
410
411    def get_model_dictionary(self):
412        """
413        return dictionary linking model names to objects
414        """
415        return self.model_dictionary
416
417
418class ModelManager(object):
419    """
420    implement model
421    """
422    __modelmanager = ModelManagerBase()
423    cat_model_list = [__modelmanager.model_dictionary[model_name] for model_name \
424                      in __modelmanager.model_dictionary.keys() \
425                      if model_name not in __modelmanager.stored_plugins.keys()]
426
427    CategoryInstaller.check_install(model_list=cat_model_list)
428    def findModels(self):
429        return self.__modelmanager.findModels()
430
431    def _getModelList(self):
432        return self.__modelmanager._getModelList()
433
434    def is_changed(self):
435        return self.__modelmanager.is_changed()
436
437    def update(self):
438        return self.__modelmanager.update()
439
440    def plugins_reset(self):
441        return self.__modelmanager.plugins_reset()
442
443    def populate_menu(self, modelmenu, event_owner):
444        return self.__modelmanager.populate_menu(modelmenu, event_owner)
445
446    def _on_model(self, evt):
447        return self.__modelmanager._on_model(evt)
448
449    def _get_multifunc_models(self):
450        return self.__modelmanager._get_multifunc_models()
451
452    def get_model_list(self):
453        return self.__modelmanager.get_model_list()
454
455    def get_model_name_list(self):
456        return self.__modelmanager.get_model_name_list()
457
458    def get_model_dictionary(self):
459        return self.__modelmanager.get_model_dictionary()
Note: See TracBrowser for help on using the repository browser.