[f0d720b] | 1 | """ |
---|
| 2 | Utilities to manage models |
---|
| 3 | """ |
---|
| 4 | import wx |
---|
| 5 | import imp |
---|
| 6 | import os |
---|
| 7 | import sys |
---|
| 8 | import math |
---|
| 9 | import os.path |
---|
| 10 | # Time is needed by the log method |
---|
| 11 | import time |
---|
| 12 | import logging |
---|
| 13 | import py_compile |
---|
| 14 | import shutil |
---|
[f66d9d1] | 15 | from sas.sasgui.guiframe.events import StatusEvent |
---|
[f0d720b] | 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. |
---|
| 19 | from sas.models.pluginmodel import Model1DPlugin |
---|
| 20 | from sas.models.BaseComponent import BaseComponent |
---|
[d85c194] | 21 | from sas.sasgui.guiframe.CategoryInstaller import CategoryInstaller |
---|
[a0b355b] | 22 | from sasmodels import sasview_model,core |
---|
[f66d9d1] | 23 | |
---|
| 24 | |
---|
[f0d720b] | 25 | PLUGIN_DIR = 'plugin_models' |
---|
| 26 | |
---|
| 27 | def get_model_python_path(): |
---|
| 28 | """ |
---|
| 29 | Returns the python path for a model |
---|
| 30 | """ |
---|
| 31 | return os.path.dirname(__file__) |
---|
| 32 | |
---|
| 33 | |
---|
| 34 | def log(message): |
---|
| 35 | """ |
---|
| 36 | Log a message in a file located in the user's home directory |
---|
| 37 | """ |
---|
| 38 | dir = os.path.join(os.path.expanduser("~"), '.sasview', PLUGIN_DIR) |
---|
| 39 | out = open(os.path.join(dir, "plugins.log"), 'a') |
---|
| 40 | out.write("%10g: %s\n" % (time.clock(), message)) |
---|
| 41 | out.close() |
---|
| 42 | |
---|
| 43 | |
---|
| 44 | def _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 | log(msg) |
---|
| 58 | return None |
---|
| 59 | if model.__name__ != "Model": |
---|
| 60 | msg = "Plugin %s class name must be Model \n" % str(name) |
---|
| 61 | 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 | 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 | log(msg) |
---|
| 79 | return None |
---|
| 80 | else: |
---|
| 81 | msg = "Plugin %s needs a method called function \n" % str(name) |
---|
| 82 | log(msg) |
---|
| 83 | return None |
---|
| 84 | return model |
---|
| 85 | |
---|
| 86 | |
---|
| 87 | def 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 | |
---|
| 133 | class ReportProblem: |
---|
| 134 | """ |
---|
| 135 | Class to check for problems with specific values |
---|
| 136 | """ |
---|
| 137 | def __nonzero__(self): |
---|
| 138 | type, value, traceback = 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, traceback |
---|
| 142 | return 1 |
---|
| 143 | |
---|
| 144 | report_problem = ReportProblem() |
---|
| 145 | |
---|
| 146 | |
---|
| 147 | def 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 | |
---|
| 160 | def _findModels(dir): |
---|
| 161 | """ |
---|
| 162 | """ |
---|
| 163 | # List of plugin objects |
---|
| 164 | plugins = {} |
---|
| 165 | dir = find_plugins_dir() |
---|
| 166 | # Go through files in plug-in directory |
---|
| 167 | #always recompile the folder plugin |
---|
| 168 | if not os.path.isdir(dir): |
---|
| 169 | msg = "SasView couldn't locate Model plugin folder." |
---|
| 170 | msg += """ "%s" does not exist""" % dir |
---|
| 171 | logging.warning(msg) |
---|
| 172 | return plugins |
---|
| 173 | else: |
---|
| 174 | log("looking for models in: %s" % str(dir)) |
---|
| 175 | compile_file(dir) |
---|
| 176 | logging.info("plugin model dir: %s" % str(dir)) |
---|
| 177 | try: |
---|
| 178 | list = os.listdir(dir) |
---|
| 179 | for item in list: |
---|
| 180 | toks = os.path.splitext(os.path.basename(item)) |
---|
| 181 | if toks[1] == '.py' and not toks[0] == '__init__': |
---|
| 182 | name = toks[0] |
---|
| 183 | |
---|
| 184 | path = [os.path.abspath(dir)] |
---|
| 185 | file = None |
---|
| 186 | try: |
---|
| 187 | (file, path, info) = imp.find_module(name, path) |
---|
| 188 | module = imp.load_module(name, file, item, info) |
---|
| 189 | if hasattr(module, "Model"): |
---|
| 190 | try: |
---|
| 191 | if _check_plugin(module.Model, name) != None: |
---|
| 192 | plugins[name] = module.Model |
---|
| 193 | except: |
---|
| 194 | msg = "Error accessing Model" |
---|
| 195 | msg += "in %s\n %s %s\n" % (name, |
---|
| 196 | str(sys.exc_type), |
---|
| 197 | sys.exc_info()[1]) |
---|
| 198 | log(msg) |
---|
| 199 | except: |
---|
| 200 | msg = "Error accessing Model" |
---|
| 201 | msg += " in %s\n %s %s \n" % (name, |
---|
| 202 | str(sys.exc_type), |
---|
| 203 | sys.exc_info()[1]) |
---|
| 204 | log(msg) |
---|
| 205 | finally: |
---|
| 206 | |
---|
| 207 | if not file == None: |
---|
| 208 | file.close() |
---|
| 209 | except: |
---|
| 210 | # Don't deal with bad plug-in imports. Just skip. |
---|
| 211 | msg = "Could not import model plugin: %s" % sys.exc_info()[1] |
---|
| 212 | log(msg) |
---|
| 213 | return plugins |
---|
| 214 | |
---|
| 215 | |
---|
| 216 | class ModelList(object): |
---|
| 217 | """ |
---|
| 218 | Contains dictionary of model and their type |
---|
| 219 | """ |
---|
| 220 | def __init__(self): |
---|
| 221 | """ |
---|
| 222 | """ |
---|
| 223 | self.mydict = {} |
---|
| 224 | |
---|
| 225 | def set_list(self, name, mylist): |
---|
| 226 | """ |
---|
| 227 | :param name: the type of the list |
---|
| 228 | :param mylist: the list to add |
---|
| 229 | |
---|
| 230 | """ |
---|
| 231 | if name not in self.mydict.keys(): |
---|
| 232 | self.reset_list(name, mylist) |
---|
| 233 | |
---|
| 234 | def reset_list(self, name, mylist): |
---|
| 235 | """ |
---|
| 236 | :param name: the type of the list |
---|
| 237 | :param mylist: the list to add |
---|
| 238 | """ |
---|
| 239 | self.mydict[name] = mylist |
---|
| 240 | |
---|
| 241 | def get_list(self): |
---|
| 242 | """ |
---|
| 243 | return all the list stored in a dictionary object |
---|
| 244 | """ |
---|
| 245 | return self.mydict |
---|
| 246 | |
---|
| 247 | |
---|
| 248 | class ModelManagerBase: |
---|
| 249 | """ |
---|
| 250 | Base class for the model manager |
---|
| 251 | """ |
---|
| 252 | ## external dict for models |
---|
| 253 | model_combobox = ModelList() |
---|
| 254 | ## Dictionary of form factor models |
---|
| 255 | form_factor_dict = {} |
---|
| 256 | ## dictionary of structure factor models |
---|
| 257 | struct_factor_dict = {} |
---|
| 258 | ##list of structure factors |
---|
| 259 | struct_list = [] |
---|
| 260 | ##list of model allowing multiplication by a structure factor |
---|
| 261 | multiplication_factor = [] |
---|
| 262 | ##list of multifunctional shapes (i.e. that have user defined number of levels |
---|
| 263 | multi_func_list = [] |
---|
| 264 | ## list of added models -- currently python models found in the plugin dir. |
---|
| 265 | plugins = [] |
---|
| 266 | ## Event owner (guiframe) |
---|
| 267 | event_owner = None |
---|
| 268 | last_time_dir_modified = 0 |
---|
| 269 | |
---|
| 270 | def __init__(self): |
---|
| 271 | """ |
---|
| 272 | """ |
---|
| 273 | self.model_dictionary = {} |
---|
| 274 | self.stored_plugins = {} |
---|
| 275 | self._getModelList() |
---|
| 276 | |
---|
| 277 | def findModels(self): |
---|
| 278 | """ |
---|
| 279 | find plugin model in directory of plugin .recompile all file |
---|
| 280 | in the directory if file were modified |
---|
| 281 | """ |
---|
| 282 | temp = {} |
---|
| 283 | if self.is_changed(): |
---|
| 284 | return _findModels(dir) |
---|
| 285 | logging.info("plugin model : %s" % str(temp)) |
---|
| 286 | return temp |
---|
| 287 | |
---|
| 288 | def _getModelList(self): |
---|
| 289 | """ |
---|
| 290 | List of models we want to make available by default |
---|
| 291 | for this application |
---|
| 292 | |
---|
| 293 | :return: the next free event ID following the new menu events |
---|
| 294 | |
---|
| 295 | """ |
---|
| 296 | |
---|
| 297 | # regular model names only |
---|
[f66d9d1] | 298 | base_message = "Unable to load model {0}" |
---|
[f0d720b] | 299 | self.model_name_list = [] |
---|
| 300 | |
---|
| 301 | #Build list automagically from sasmodels package |
---|
[a0b355b] | 302 | for model in sasview_model.standard_models(): |
---|
| 303 | self.model_dictionary[model._model_info['name']] = model |
---|
| 304 | if model._model_info['structure_factor'] == True: |
---|
| 305 | self.struct_list.append(model) |
---|
| 306 | if model._model_info['variant_info'] is not None: |
---|
| 307 | self.multi_func_list.append(model) |
---|
| 308 | else: |
---|
| 309 | self.model_name_list.append(model._model_info['name']) |
---|
| 310 | if model._model_info['ER'] is not None: |
---|
| 311 | self.multiplication_factor.append(model) |
---|
| 312 | |
---|
[f0d720b] | 313 | |
---|
| 314 | #Looking for plugins |
---|
| 315 | self.stored_plugins = self.findModels() |
---|
| 316 | self.plugins = self.stored_plugins.values() |
---|
| 317 | for name, plug in self.stored_plugins.iteritems(): |
---|
| 318 | self.model_dictionary[name] = plug |
---|
| 319 | |
---|
| 320 | self._get_multifunc_models() |
---|
| 321 | |
---|
| 322 | return 0 |
---|
| 323 | |
---|
| 324 | def is_changed(self): |
---|
| 325 | """ |
---|
| 326 | check the last time the plugin dir has changed and return true |
---|
| 327 | is the directory was modified else return false |
---|
| 328 | """ |
---|
| 329 | is_modified = False |
---|
| 330 | plugin_dir = find_plugins_dir() |
---|
| 331 | if os.path.isdir(plugin_dir): |
---|
| 332 | temp = os.path.getmtime(plugin_dir) |
---|
| 333 | if self.last_time_dir_modified != temp: |
---|
| 334 | is_modified = True |
---|
| 335 | self.last_time_dir_modified = temp |
---|
| 336 | |
---|
| 337 | return is_modified |
---|
| 338 | |
---|
| 339 | def update(self): |
---|
| 340 | """ |
---|
| 341 | return a dictionary of model if |
---|
| 342 | new models were added else return empty dictionary |
---|
| 343 | """ |
---|
| 344 | new_plugins = self.findModels() |
---|
| 345 | if len(new_plugins) > 0: |
---|
| 346 | for name, plug in new_plugins.iteritems(): |
---|
| 347 | if name not in self.stored_plugins.keys(): |
---|
| 348 | self.stored_plugins[name] = plug |
---|
| 349 | self.plugins.append(plug) |
---|
| 350 | self.model_dictionary[name] = plug |
---|
| 351 | self.model_combobox.set_list("Customized Models", self.plugins) |
---|
| 352 | return self.model_combobox.get_list() |
---|
| 353 | else: |
---|
| 354 | return {} |
---|
| 355 | |
---|
[f66d9d1] | 356 | def plugins_reset(self): |
---|
[f0d720b] | 357 | """ |
---|
| 358 | return a dictionary of model |
---|
| 359 | """ |
---|
| 360 | self.plugins = [] |
---|
| 361 | new_plugins = _findModels(dir) |
---|
| 362 | for name, plug in new_plugins.iteritems(): |
---|
| 363 | for stored_name, stored_plug in self.stored_plugins.iteritems(): |
---|
| 364 | if name == stored_name: |
---|
| 365 | del self.stored_plugins[name] |
---|
| 366 | del self.model_dictionary[name] |
---|
| 367 | break |
---|
| 368 | self.stored_plugins[name] = plug |
---|
| 369 | self.plugins.append(plug) |
---|
| 370 | self.model_dictionary[name] = plug |
---|
| 371 | |
---|
| 372 | self.model_combobox.reset_list("Customized Models", self.plugins) |
---|
| 373 | return self.model_combobox.get_list() |
---|
| 374 | |
---|
| 375 | def _on_model(self, evt): |
---|
| 376 | """ |
---|
| 377 | React to a model menu event |
---|
| 378 | |
---|
| 379 | :param event: wx menu event |
---|
| 380 | |
---|
| 381 | """ |
---|
| 382 | if int(evt.GetId()) in self.form_factor_dict.keys(): |
---|
| 383 | from sas.models.MultiplicationModel import MultiplicationModel |
---|
| 384 | self.model_dictionary[MultiplicationModel.__name__] = MultiplicationModel |
---|
| 385 | model1, model2 = self.form_factor_dict[int(evt.GetId())] |
---|
| 386 | model = MultiplicationModel(model1, model2) |
---|
| 387 | else: |
---|
| 388 | model = self.struct_factor_dict[str(evt.GetId())]() |
---|
| 389 | |
---|
| 390 | |
---|
| 391 | def _get_multifunc_models(self): |
---|
| 392 | """ |
---|
| 393 | Get the multifunctional models |
---|
| 394 | """ |
---|
| 395 | for item in self.plugins: |
---|
| 396 | try: |
---|
| 397 | # check the multiplicity if any |
---|
| 398 | if item.multiplicity_info[0] > 1: |
---|
| 399 | self.multi_func_list.append(item) |
---|
| 400 | except: |
---|
| 401 | # pass to other items |
---|
| 402 | pass |
---|
| 403 | |
---|
| 404 | def get_model_list(self): |
---|
| 405 | """ |
---|
| 406 | return dictionary of models for fitpanel use |
---|
| 407 | |
---|
| 408 | """ |
---|
| 409 | ## Model_list now only contains attribute lists not category list. |
---|
| 410 | ## Eventually this should be in one master list -- read in category |
---|
| 411 | ## list then pull those models that exist and get attributes then add |
---|
| 412 | ## to list ..and if model does not exist remove from list as now |
---|
| 413 | ## and update json file. |
---|
| 414 | ## |
---|
| 415 | ## -PDB April 26, 2014 |
---|
| 416 | |
---|
| 417 | # self.model_combobox.set_list("Shapes", self.shape_list) |
---|
| 418 | # self.model_combobox.set_list("Shape-Independent", |
---|
| 419 | # self.shape_indep_list) |
---|
| 420 | self.model_combobox.set_list("Structure Factors", self.struct_list) |
---|
| 421 | self.model_combobox.set_list("Customized Models", self.plugins) |
---|
| 422 | self.model_combobox.set_list("P(Q)*S(Q)", self.multiplication_factor) |
---|
| 423 | self.model_combobox.set_list("multiplication", |
---|
| 424 | self.multiplication_factor) |
---|
| 425 | self.model_combobox.set_list("Multi-Functions", self.multi_func_list) |
---|
| 426 | return self.model_combobox.get_list() |
---|
| 427 | |
---|
| 428 | def get_model_name_list(self): |
---|
| 429 | """ |
---|
| 430 | return regular model name list |
---|
| 431 | """ |
---|
| 432 | return self.model_name_list |
---|
| 433 | |
---|
| 434 | def get_model_dictionary(self): |
---|
| 435 | """ |
---|
| 436 | return dictionary linking model names to objects |
---|
| 437 | """ |
---|
| 438 | return self.model_dictionary |
---|
| 439 | |
---|
| 440 | |
---|
| 441 | class ModelManager(object): |
---|
| 442 | """ |
---|
| 443 | implement model |
---|
| 444 | """ |
---|
| 445 | __modelmanager = ModelManagerBase() |
---|
| 446 | cat_model_list = [model_name for model_name \ |
---|
| 447 | in __modelmanager.model_dictionary.keys() \ |
---|
| 448 | if model_name not in __modelmanager.stored_plugins.keys()] |
---|
| 449 | |
---|
| 450 | CategoryInstaller.check_install(model_list=cat_model_list) |
---|
| 451 | def findModels(self): |
---|
| 452 | return self.__modelmanager.findModels() |
---|
| 453 | |
---|
| 454 | def _getModelList(self): |
---|
| 455 | return self.__modelmanager._getModelList() |
---|
| 456 | |
---|
| 457 | def is_changed(self): |
---|
| 458 | return self.__modelmanager.is_changed() |
---|
| 459 | |
---|
| 460 | def update(self): |
---|
| 461 | return self.__modelmanager.update() |
---|
| 462 | |
---|
[f66d9d1] | 463 | def plugins_reset(self): |
---|
| 464 | return self.__modelmanager.plugins_reset() |
---|
[f0d720b] | 465 | |
---|
| 466 | def populate_menu(self, modelmenu, event_owner): |
---|
| 467 | return self.__modelmanager.populate_menu(modelmenu, event_owner) |
---|
| 468 | |
---|
| 469 | def _on_model(self, evt): |
---|
| 470 | return self.__modelmanager._on_model(evt) |
---|
| 471 | |
---|
| 472 | def _get_multifunc_models(self): |
---|
| 473 | return self.__modelmanager._get_multifunc_models() |
---|
| 474 | |
---|
| 475 | def get_model_list(self): |
---|
| 476 | return self.__modelmanager.get_model_list() |
---|
| 477 | |
---|
| 478 | def get_model_name_list(self): |
---|
| 479 | return self.__modelmanager.get_model_name_list() |
---|
| 480 | |
---|
| 481 | def get_model_dictionary(self): |
---|
| 482 | return self.__modelmanager.get_model_dictionary() |
---|