source: sasview/src/sas/qtgui/Perspectives/Fitting/ModelUtilities.py @ 441a03f

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 441a03f was 3b3b40b, checked in by Piotr Rozyczko <rozyczko@…>, 7 years ago

Merging feature branches

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