source: sasview/src/sas/sascalc/fit/models.py @ 69363c7

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 69363c7 was 69363c7, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

Merge branch 'master' into ticket-853-fit-gui-to-calc

  • Property mode set to 100644
File size: 11.0 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#?? from copy import copy
17
18from sasmodels.sasview_model import load_custom_model, load_standard_models
19from sasmodels.sasview_model import MultiplicationModel
20#?? from sas.sasgui.perspectives.fitting.fitpage import CUSTOM_MODEL
21
22# Explicitly import from the pluginmodel module so that py2exe
23# places it in the distribution. The Model1DPlugin class is used
24# as the base class of plug-in models.
25from .pluginmodel import Model1DPlugin
26
27logger = logging.getLogger(__name__)
28
29
30PLUGIN_DIR = 'plugin_models'
31PLUGIN_LOG = os.path.join(os.path.expanduser("~"), '.sasview', PLUGIN_DIR,
32                          "plugins.log")
33PLUGIN_NAME_BASE = '[plug-in] '
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 Exception:
69        msg = "Plugin %s error in __init__ \n\t: %s %s\n" % (str(name),
70                                                             str(sys.exc_type),
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 Exception:
79            msg = "Plugin %s: error writing function \n\t :%s %s\n " % \
80                    (str(name), str(sys.exc_type), sys.exc_info()[1])
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    path = os.path.join(os.path.expanduser("~"), '.sasview', PLUGIN_DIR)
96
97    # TODO: initializing ~/.sasview/plugin_models doesn't belong in sascalc
98    # If the plugin directory doesn't exist, create it
99    if not os.path.isdir(path):
100        os.makedirs(path)
101    # TODO: should we be checking for new default models every time?
102    initialize_plugins_dir(path)
103    return path
104
105
106def initialize_plugins_dir(path):
107    # TODO: There are no default plugins
108    # TODO: Move default plugins beside sample data files
109    # TODO: Should not look for defaults above the root of the sasview install
110
111    # Walk up the tree looking for default plugin_models directory
112    base = os.path.abspath(os.path.dirname(__file__))
113    for _ in range(12):
114        default_plugins_path = os.path.join(base, PLUGIN_DIR)
115        if os.path.isdir(default_plugins_path):
116            break
117        base, _ = os.path.split(base)
118    else:
119        logger.error("default plugins directory not found")
120        return
121
122    # Copy files from default plugins to the .sasview directory
123    # This may include c files, depending on the example.
124    # Note: files are never replaced, even if the default plugins are updated
125    for filename in os.listdir(default_plugins_path):
126        # skip __init__.py and all pyc files
127        if filename == "__init__.py" or filename.endswith('.pyc'):
128            continue
129        source = os.path.join(default_plugins_path, filename)
130        target = os.path.join(path, filename)
131        if os.path.isfile(source) and not os.path.isfile(target):
132            shutil.copy(source, target)
133
134
135class ReportProblem(object):
136    """
137    Class to check for problems with specific values
138    """
139    def __nonzero__(self):
140        type, value, tb = sys.exc_info()
141        if type is not None and issubclass(type, py_compile.PyCompileError):
142            print("Problem with", repr(value))
143            raise type, value, tb
144        return 1
145
146report_problem = ReportProblem()
147
148
149def compile_file(dir):
150    """
151    Compile a py file
152    """
153    try:
154        import compileall
155        compileall.compile_dir(dir=dir, ddir=dir, force=0,
156                               quiet=report_problem)
157    except Exception:
158        return sys.exc_info()[1]
159    return None
160
161
162def find_plugin_models():
163    """
164    Find custom models
165    """
166    # List of plugin objects
167    plugins_dir = find_plugins_dir()
168    # Go through files in plug-in directory
169    if not os.path.isdir(plugins_dir):
170        msg = "SasView couldn't locate Model plugin folder %r." % plugins_dir
171        logger.warning(msg)
172        return {}
173
174    plugin_log("looking for models in: %s" % plugins_dir)
175    # compile_file(plugins_dir)  #always recompile the folder plugin
176    logger.info("plugin model dir: %s", plugins_dir)
177
178    plugins = {}
179    for filename in os.listdir(plugins_dir):
180        name, ext = os.path.splitext(filename)
181        if ext == '.py' and not name == '__init__':
182            path = os.path.abspath(os.path.join(plugins_dir, filename))
183            try:
184                model = load_custom_model(path)
185                # TODO: add [plug-in] tag to model name in sasview_model
186                if not model.name.startswith(PLUGIN_NAME_BASE):
187                    model.name = PLUGIN_NAME_BASE + model.name
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                logger.warning("Failed to load plugin %r. See %s for details",
194                               path, PLUGIN_LOG)
195
196    return plugins
197
198
199class ModelManagerBase(object):
200    """
201    Base class for the model manager
202    """
203    #: mutable dictionary of models, continually updated to reflect the
204    #: current set of plugins
205    model_dictionary = None  # type: Dict[str, Model]
206    #: constant list of standard models
207    standard_models = None  # type: Dict[str, Model]
208    #: list of plugin models reset each time the plugin directory is queried
209    plugin_models = None  # type: Dict[str, Model]
210    #: timestamp on the plugin directory at the last plugin update
211    last_time_dir_modified = 0  # type: int
212
213    def __init__(self):
214        # the model dictionary is allocated at the start and updated to
215        # reflect the current list of models.  Be sure to clear it rather
216        # than reassign to it.
217        self.model_dictionary = {}
218
219        #Build list automagically from sasmodels package
220        self.standard_models = {model.name: model
221                                for model in load_standard_models()}
222        # Look for plugins
223        self.plugins_reset()
224
225    def _is_plugin_dir_changed(self):
226        """
227        check the last time the plugin dir has changed and return true
228        is the directory was modified else return false
229        """
230        is_modified = False
231        plugin_dir = find_plugins_dir()
232        if os.path.isdir(plugin_dir):
233            mod_time = os.path.getmtime(plugin_dir)
234            if  self.last_time_dir_modified != mod_time:
235                is_modified = True
236                self.last_time_dir_modified = mod_time
237
238        return is_modified
239
240    def composable_models(self):
241        """
242        return list of standard models that can be used in sum/multiply
243        """
244        # TODO: should scan plugin models in addition to standard models
245        # and update model_editor so that it doesn't add plugins to the list
246        return [model.name for model in self.standard_models.values()
247                if not model.is_multiplicity_model]
248
249    def plugins_update(self):
250        """
251        return a dictionary of model if
252        new models were added else return empty dictionary
253        """
254        return self.plugins_reset()
255        #if self._is_plugin_dir_changed():
256        #    return self.plugins_reset()
257        #else:
258        #    return {}
259
260    def plugins_reset(self):
261        """
262        return a dictionary of model
263        """
264        self.plugin_models = find_plugin_models()
265        self.model_dictionary.clear()
266        self.model_dictionary.update(self.standard_models)
267        self.model_dictionary.update(self.plugin_models)
268        return self.get_model_list()
269
270    def get_model_list(self):
271        """
272        return dictionary of classified models
273
274        *Structure Factors* are the structure factor models
275        *Multi-Functions* are the multiplicity models
276        *Plugin Models* are the plugin models
277
278        Note that a model can be both a plugin and a structure factor or
279        multiplicity model.
280        """
281        ## Model_list now only contains attribute lists not category list.
282        ## Eventually this should be in one master list -- read in category
283        ## list then pull those models that exist and get attributes then add
284        ## to list ..and if model does not exist remove from list as now
285        ## and update json file.
286        ##
287        ## -PDB   April 26, 2014
288
289
290        # Classify models
291        structure_factors = []
292        form_factors = []
293        multiplicity_models = []
294        for model in self.model_dictionary.values():
295            # Old style models don't have is_structure_factor attribute
296            if getattr(model, 'is_structure_factor', False):
297                structure_factors.append(model)
298            if getattr(model, 'is_form_factor', False):
299                form_factors.append(model)
300            if model.is_multiplicity_model:
301                multiplicity_models.append(model)
302        plugin_models = list(self.plugin_models.values())
303
304        return {
305            "Structure Factors": structure_factors,
306            "Form Factors": form_factors,
307            "Plugin Models": plugin_models,
308            "Multi-Functions": multiplicity_models,
309        }
310
311
312class ModelManager(object):
313    """
314    manage the list of available models
315    """
316    base = None  # type: ModelManagerBase()
317
318    def __init__(self):
319        if ModelManager.base is None:
320            ModelManager.base = ModelManagerBase()
321
322    def cat_model_list(self):
323        return list(self.base.standard_models.values())
324
325    def update(self):
326        return self.base.plugins_update()
327
328    def plugins_reset(self):
329        return self.base.plugins_reset()
330
331    def get_model_list(self):
332        return self.base.get_model_list()
333
334    def composable_models(self):
335        return self.base.composable_models()
336
337    def get_model_dictionary(self):
338        return self.base.model_dictionary
Note: See TracBrowser for help on using the repository browser.