Changeset 277257f in sasview
- Timestamp:
- Jul 5, 2017 5:28:55 PM (7 years ago)
- Branches:
- master, ESS_GUI, ESS_GUI_Docs, ESS_GUI_batch_fitting, ESS_GUI_bumps_abstraction, ESS_GUI_iss1116, ESS_GUI_iss879, ESS_GUI_iss959, ESS_GUI_opencl, ESS_GUI_ordering, ESS_GUI_sync_sascalc, magnetic_scatt, release-4.2.2, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
- Children:
- 1386b2f
- Parents:
- 251ef684
- Location:
- src/sas
- Files:
-
- 7 edited
- 1 moved
Legend:
- Unmodified
- Added
- Removed
-
src/sas/sascalc/fit/models.py
r65f3930 r277257f 16 16 17 17 from sasmodels.sasview_model import load_custom_model, load_standard_models 18 from sasmodels.sasview_model import MultiplicationModel 18 19 19 20 # Explicitly import from the pluginmodel module so that py2exe … … 21 22 # as the base class of plug-in models. 22 23 from .pluginmodel import Model1DPlugin 23 24 from sas.sasgui.guiframe.CategoryInstaller import CategoryInstaller25 24 26 25 logger = logging.getLogger(__name__) … … 92 91 The plugin directory is located in the user's home directory. 93 92 """ 94 dir = os.path.join(os.path.expanduser("~"), '.sasview', PLUGIN_DIR) 95 93 path = os.path.join(os.path.expanduser("~"), '.sasview', PLUGIN_DIR) 94 95 # TODO: initializing ~/.sasview/plugin_models doesn't belong in sascalc 96 96 # If the plugin directory doesn't exist, create it 97 if not os.path.isdir(dir): 98 os.makedirs(dir) 99 100 # Find paths needed 101 # TODO: remove unneeded try/except block 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 Exception: 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 136 class ReportProblem: 97 if not os.path.isdir(path): 98 os.makedirs(path) 99 # TODO: should we be checking for new default models every time? 100 initialize_plugins_dir(path) 101 return path 102 103 104 def initialize_plugins_dir(path): 105 # TODO: There are no default plugins 106 # TODO: Move default plugins beside sample data files 107 # TODO: Should not look for defaults above the root of the sasview install 108 109 # Walk up the tree looking for default plugin_models directory 110 base = os.path.abspath(os.path.dirname(__file__)) 111 for _ in range(12): 112 default_plugins_path = os.path.join(base, PLUGIN_DIR) 113 if os.path.isdir(default_plugins_path): 114 break 115 base, _ = os.path.split(base) 116 else: 117 logger.error("default plugins directory not found") 118 return 119 120 # Copy files from default plugins to the .sasview directory 121 # This may include c files, depending on the example. 122 # Note: files are never replaced, even if the default plugins are updated 123 for filename in os.listdir(default_plugins_path): 124 # skip __init__.py and all pyc files 125 if filename == "__init__.py" or filename.endswith('.pyc'): 126 continue 127 source = os.path.join(default_plugins_path, filename) 128 target = os.path.join(path, filename) 129 if os.path.isfile(source) and not os.path.isfile(target): 130 shutil.copy(source, target) 131 132 133 class ReportProblem(object): 137 134 """ 138 135 Class to check for problems with specific values … … 161 158 162 159 163 def _find_models():160 def find_plugin_models(): 164 161 """ 165 162 Find custom models 166 163 """ 167 164 # List of plugin objects 168 directory= find_plugins_dir()165 plugins_dir = find_plugins_dir() 169 166 # Go through files in plug-in directory 170 if not os.path.isdir( directory):171 msg = "SasView couldn't locate Model plugin folder %r." % directory167 if not os.path.isdir(plugins_dir): 168 msg = "SasView couldn't locate Model plugin folder %r." % plugins_dir 172 169 logger.warning(msg) 173 170 return {} 174 171 175 plugin_log("looking for models in: %s" % str(directory))176 # compile_file( directory) #always recompile the folder plugin177 logger.info("plugin model dir: %s", str(directory))172 plugin_log("looking for models in: %s" % plugins_dir) 173 # compile_file(plugins_dir) #always recompile the folder plugin 174 logger.info("plugin model dir: %s", plugins_dir) 178 175 179 176 plugins = {} 180 for filename in os.listdir( directory):177 for filename in os.listdir(plugins_dir): 181 178 name, ext = os.path.splitext(filename) 182 179 if ext == '.py' and not name == '__init__': 183 path = os.path.abspath(os.path.join( directory, filename))180 path = os.path.abspath(os.path.join(plugins_dir, filename)) 184 181 try: 185 182 model = load_custom_model(path) 186 model.name = PLUGIN_NAME_BASE + model.name 183 # TODO: add [plug-in] tag to model name in sasview_model 184 if not model.name.startswith(PLUGIN_NAME_BASE): 185 model.name = PLUGIN_NAME_BASE + model.name 187 186 plugins[model.name] = model 188 187 except Exception: … … 196 195 197 196 198 class ModelList(object): 199 """ 200 Contains dictionary of model and their type 201 """ 197 class ModelManagerBase(object): 198 """ 199 Base class for the model manager 200 """ 201 #: mutable dictionary of models, continually updated to reflect the 202 #: current set of plugins 203 model_dictionary = None # type: Dict[str, Model] 204 #: constant list of standard models 205 standard_models = None # type: Dict[str, Model] 206 #: list of plugin models reset each time the plugin directory is queried 207 plugin_models = None # type: Dict[str, Model] 208 #: timestamp on the plugin directory at the last plugin update 209 last_time_dir_modified = 0 # type: int 210 202 211 def __init__(self): 203 """ 204 """ 205 self.mydict = {} 206 207 def set_list(self, name, mylist): 208 """ 209 :param name: the type of the list 210 :param mylist: the list to add 211 212 """ 213 if name not in self.mydict.keys(): 214 self.reset_list(name, mylist) 215 216 def reset_list(self, name, mylist): 217 """ 218 :param name: the type of the list 219 :param mylist: the list to add 220 """ 221 self.mydict[name] = mylist 222 223 def get_list(self): 224 """ 225 return all the list stored in a dictionary object 226 """ 227 return self.mydict 228 229 230 class ModelManagerBase(object): 231 """ 232 Base class for the model manager 233 """ 234 ## external dict for models 235 model_combobox = ModelList() 236 ## Dictionary of form factor models 237 form_factor_dict = {} 238 ## dictionary of structure factor models 239 struct_factor_dict = {} 240 ##list of structure factors 241 struct_list = [] 242 ##list of model allowing multiplication by a structure factor 243 multiplication_factor = [] 244 ##list of multifunctional shapes (i.e. that have user defined number of levels 245 multi_func_list = [] 246 ## list of added models -- currently python models found in the plugin dir. 247 plugins = [] 248 ## Event owner (guiframe) 249 event_owner = None 250 last_time_dir_modified = 0 251 252 def __init__(self): 212 # the model dictionary is allocated at the start and updated to 213 # reflect the current list of models. Be sure to clear it rather 214 # than reassign to it. 253 215 self.model_dictionary = {} 254 self.stored_plugins = {}255 self._getModelList()256 257 def findModels(self):258 """259 find plugin model in directory of plugin .recompile all file260 in the directory if file were modified261 """262 temp = {}263 if self.is_changed():264 return _find_models()265 logger.info("plugin model : %s", str(temp))266 return temp267 268 def _getModelList(self):269 """270 List of models we want to make available by default271 for this application272 273 :return: the next free event ID following the new menu events274 275 """276 277 # regular model names only278 self.model_name_list = []279 216 280 217 #Build list automagically from sasmodels package 281 for model in load_standard_models(): 282 self.model_dictionary[model.name] = model 283 if model.is_structure_factor: 284 self.struct_list.append(model) 285 if model.is_form_factor: 286 self.multiplication_factor.append(model) 287 if model.is_multiplicity_model: 288 self.multi_func_list.append(model) 289 else: 290 self.model_name_list.append(model.name) 291 292 #Looking for plugins 293 self.stored_plugins = self.findModels() 294 self.plugins = self.stored_plugins.values() 295 for name, plug in self.stored_plugins.iteritems(): 296 self.model_dictionary[name] = plug 297 298 self._get_multifunc_models() 299 300 return 0 301 302 def is_changed(self): 218 self.standard_models = {model.name: model 219 for model in load_standard_models()} 220 # Look for plugins 221 self.plugins_reset() 222 223 def _is_plugin_dir_changed(self): 303 224 """ 304 225 check the last time the plugin dir has changed and return true … … 308 229 plugin_dir = find_plugins_dir() 309 230 if os.path.isdir(plugin_dir): 310 temp= os.path.getmtime(plugin_dir)311 if self.last_time_dir_modified != temp:231 mod_time = os.path.getmtime(plugin_dir) 232 if self.last_time_dir_modified != mod_time: 312 233 is_modified = True 313 self.last_time_dir_modified = temp234 self.last_time_dir_modified = mod_time 314 235 315 236 return is_modified 316 237 317 def update(self): 238 def composable_models(self): 239 """ 240 return list of standard models that can be used in sum/multiply 241 """ 242 # TODO: should scan plugin models in addition to standard models 243 # and update model_editor so that it doesn't add plugins to the list 244 return [model.name for model in self.standard_models.values() 245 if not model.is_multiplicity_model] 246 247 def plugins_update(self): 318 248 """ 319 249 return a dictionary of model if 320 250 new models were added else return empty dictionary 321 251 """ 322 new_plugins = self.findModels() 323 if len(new_plugins) > 0: 324 for name, plug in new_plugins.iteritems(): 325 if name not in self.stored_plugins.keys(): 326 self.stored_plugins[name] = plug 327 self.plugins.append(plug) 328 self.model_dictionary[name] = plug 329 self.model_combobox.set_list("Plugin Models", self.plugins) 330 return self.model_combobox.get_list() 331 else: 332 return {} 252 return self.plugins_reset() 253 #if self._is_plugin_dir_changed(): 254 # return self.plugins_reset() 255 #else: 256 # return {} 333 257 334 258 def plugins_reset(self): … … 336 260 return a dictionary of model 337 261 """ 338 self.plugins = [] 339 new_plugins = _find_models() 340 for name, plug in new_plugins.iteritems(): 341 for stored_name, stored_plug in self.stored_plugins.iteritems(): 342 if name == stored_name: 343 del self.stored_plugins[name] 344 del self.model_dictionary[name] 345 break 346 self.stored_plugins[name] = plug 347 self.plugins.append(plug) 348 self.model_dictionary[name] = plug 349 350 self.model_combobox.reset_list("Plugin Models", self.plugins) 351 return self.model_combobox.get_list() 352 353 def _on_model(self, evt): 354 """ 355 React to a model menu event 356 357 :param event: wx menu event 358 359 """ 360 if int(evt.GetId()) in self.form_factor_dict.keys(): 361 from sasmodels.sasview_model import MultiplicationModel 362 self.model_dictionary[MultiplicationModel.__name__] = MultiplicationModel 363 model1, model2 = self.form_factor_dict[int(evt.GetId())] 364 model = MultiplicationModel(model1, model2) 365 else: 366 model = self.struct_factor_dict[str(evt.GetId())]() 367 368 369 def _get_multifunc_models(self): 370 """ 371 Get the multifunctional models 372 """ 373 items = [item for item in self.plugins if item.is_multiplicity_model] 374 self.multi_func_list = items 262 self.plugin_models = find_plugin_models() 263 self.model_dictionary.clear() 264 self.model_dictionary.update(self.standard_models) 265 self.model_dictionary.update(self.plugin_models) 266 return self.get_model_list() 375 267 376 268 def get_model_list(self): 377 269 """ 378 return dictionary of models for fitpanel use 379 270 return dictionary of classified models 271 272 *Structure Factors* are the structure factor models 273 *Multi-Functions* are the multiplicity models 274 *Plugin Models* are the plugin models 275 276 Note that a model can be both a plugin and a structure factor or 277 multiplicity model. 380 278 """ 381 279 ## Model_list now only contains attribute lists not category list. … … 387 285 ## -PDB April 26, 2014 388 286 389 # self.model_combobox.set_list("Shapes", self.shape_list) 390 # self.model_combobox.set_list("Shape-Independent", 391 # self.shape_indep_list) 392 self.model_combobox.set_list("Structure Factors", self.struct_list) 393 self.model_combobox.set_list("Plugin Models", self.plugins) 394 self.model_combobox.set_list("P(Q)*S(Q)", self.multiplication_factor) 395 self.model_combobox.set_list("multiplication", 396 self.multiplication_factor) 397 self.model_combobox.set_list("Multi-Functions", self.multi_func_list) 398 return self.model_combobox.get_list() 399 400 def get_model_name_list(self): 401 """ 402 return regular model name list 403 """ 404 return self.model_name_list 405 406 def get_model_dictionary(self): 407 """ 408 return dictionary linking model names to objects 409 """ 410 return self.model_dictionary 287 288 # Classify models 289 structure_factors = [] 290 multiplicity_models = [] 291 for model in self.model_dictionary.values(): 292 # Old style models don't have is_structure_factor attribute 293 if getattr(model, 'is_structure_factor', False): 294 structure_factors.append(model) 295 if model.is_multiplicity_model: 296 multiplicity_models.append(model) 297 plugin_models = list(self.plugin_models.values()) 298 299 return { 300 "Structure Factors": structure_factors, 301 "Plugin Models": plugin_models, 302 "Multi-Functions": multiplicity_models, 303 } 411 304 412 305 413 306 class ModelManager(object): 414 307 """ 415 implement model308 manage the list of available models 416 309 """ 417 310 base = None # type: ModelManagerBase() … … 419 312 def __init__(self): 420 313 if ModelManager.base is None: 421 self.base = ModelManagerBase()314 ModelManager.base = ModelManagerBase() 422 315 423 316 def cat_model_list(self): 424 models = self.base.model_dictionary 425 retval = [model for model_name, model in models.items() 426 if model_name not in self.base.stored_plugins] 427 return retval 428 429 def findModels(self): 430 return self.base.findModels() 431 432 def _getModelList(self): 433 return self.base._getModelList() 434 435 def is_changed(self): 436 return self.base.is_changed() 317 return list(self.base.standard_models.values()) 437 318 438 319 def update(self): 439 return self.base. update()320 return self.base.plugins_update() 440 321 441 322 def plugins_reset(self): 442 323 return self.base.plugins_reset() 443 324 444 #def populate_menu(self, modelmenu, event_owner):445 # return self.base.populate_menu(modelmenu, event_owner)446 447 def _on_model(self, evt):448 return self.base._on_model(evt)449 450 def _get_multifunc_models(self):451 return self.base._get_multifunc_models()452 453 325 def get_model_list(self): 454 326 return self.base.get_model_list() 455 327 456 def get_model_name_list(self):457 return self.base. get_model_name_list()328 def composable_models(self): 329 return self.base.composable_models() 458 330 459 331 def get_model_dictionary(self): 460 return self.base. get_model_dictionary()332 return self.base.model_dictionary -
src/sas/sascalc/fit/pagestate.py
rba8d326 r277257f 225 225 # contains link between a model and selected parameters to fit 226 226 self.param_toFit = [] 227 # dictionary of model type and model class228 self.model_list_box = None229 227 # save the state of the context menu 230 228 self.saved_states = {} … … 288 286 obj.data_name = self.data_name 289 287 obj.is_data = self.is_data 290 obj.model_list_box = copy.deepcopy(self.model_list_box)291 288 292 289 obj.categorycombobox = self.categorycombobox … … 967 964 # Get file name 968 965 entry = get_content('ns:filename', node) 969 if entry is not None :966 if entry is not None and entry.text: 970 967 self.file = entry.text.strip() 968 else: 969 self.file = '' 971 970 972 971 # Get time stamp -
src/sas/sasgui/perspectives/calculator/model_editor.py
r65f3930 r277257f 31 31 import re 32 32 import logging 33 import datetime 34 33 35 from wx.py.editwindow import EditWindow 36 34 37 from sas.sasgui.guiframe.documentation_window import DocumentationWindow 38 35 39 from .pyconsole import show_model_output, check_model 36 40 37 41 logger = logging.getLogger(__name__) 38 39 42 40 43 if sys.platform.count("win32") > 0: … … 78 81 a Modal Dialog. 79 82 80 :TODO the buil din compiler currently balks at when it tries to import83 :TODO the built in compiler currently balks at when it tries to import 81 84 a model whose name contains spaces or symbols (such as + ... underscore 82 85 should be fine). Have fixed so the editor cannot save such a file name … … 336 339 list_fnames = os.listdir(self.plugin_dir) 337 340 # fake existing regular model name list 338 m_list = [model + ".py" for model in self.model_list]341 m_list = [model.name + ".py" for model in self.model_list] 339 342 list_fnames.append(m_list) 340 343 if t_fname in list_fnames and title != mname: … … 855 858 exec "float(math.%s)" % item 856 859 self.math_combo.Append(str(item)) 857 except :860 except Exception: 858 861 self.math_combo.Append(str(item) + "()") 859 862 self.math_combo.Bind(wx.EVT_COMBOBOX, self._on_math_select) … … 980 983 msg = "Name exists already." 981 984 982 # Prepare the messagebox985 # 983 986 if self.base is not None and not msg: 984 987 self.base.update_custom_combo() 985 # Passed exception in import test as it will fail for sasmodels.sasview_model class986 # Should add similar test for new style?987 Model = None988 try:989 exec "from %s import Model" % name990 except:991 logger.error(sys.exc_value)992 988 993 989 # Prepare the messagebox … … 1020 1016 :param func_str: content of func; Strings 1021 1017 """ 1022 try: 1023 out_f = open(fname, 'w') 1024 except: 1025 raise 1026 # Prepare the content of the function 1027 lines = CUSTOM_TEMPLATE.split('\n') 1028 1029 has_scipy = func_str.count("scipy.") 1030 if has_scipy: 1031 lines.insert(0, 'import scipy') 1032 1033 # Think about 2D later 1034 #self.is_2d = func_str.count("#self.ndim = 2") 1035 #line_2d = '' 1036 #if self.is_2d: 1037 # line_2d = CUSTOM_2D_TEMP.split('\n') 1038 1039 # Also think about test later 1040 #line_test = TEST_TEMPLATE.split('\n') 1041 #local_params = '' 1042 #spaces = ' '#8spaces 1043 spaces4 = ' '*4 1044 spaces13 = ' '*13 1045 spaces16 = ' '*16 1018 out_f = open(fname, 'w') 1019 1020 out_f.write(CUSTOM_TEMPLATE % { 1021 'name': name, 1022 'title': 'User model for ' + name, 1023 'description': desc_str, 1024 'date': datetime.datetime.now().strftime('%YYYY-%mm-%dd'), 1025 }) 1026 1027 # Write out parameters 1046 1028 param_names = [] # to store parameter names 1047 has_scipy = func_str.count("scipy.") 1048 if has_scipy: 1049 lines.insert(0, 'import scipy') 1050 1051 # write function here 1052 for line in lines: 1053 # The location where to put the strings is 1054 # hard-coded in the template as shown below. 1055 out_f.write(line + '\n') 1056 if line.count('#name'): 1057 out_f.write('name = "%s" \n' % name) 1058 elif line.count('#title'): 1059 out_f.write('title = "User model for %s"\n' % name) 1060 elif line.count('#description'): 1061 out_f.write('description = "%s"\n' % desc_str) 1062 elif line.count('#parameters'): 1063 out_f.write('parameters = [ \n') 1064 for param_line in param_str.split('\n'): 1065 p_line = param_line.lstrip().rstrip() 1066 if p_line: 1067 pname, pvalue = self.get_param_helper(p_line) 1068 param_names.append(pname) 1069 out_f.write("%s['%s', '', %s, [-numpy.inf, numpy.inf], '', ''],\n" % (spaces16, pname, pvalue)) 1070 for param_line in pd_param_str.split('\n'): 1071 p_line = param_line.lstrip().rstrip() 1072 if p_line: 1073 pname, pvalue = self.get_param_helper(p_line) 1074 param_names.append(pname) 1075 out_f.write("%s['%s', '', %s, [-numpy.inf, numpy.inf], 'volume', ''],\n" % (spaces16, pname, pvalue)) 1076 out_f.write('%s]\n' % spaces13) 1077 1078 # No form_volume or ER available in simple model editor 1079 out_f.write('def form_volume(*arg): \n') 1080 out_f.write(' return 1.0 \n') 1081 out_f.write('\n') 1082 out_f.write('def ER(*arg): \n') 1083 out_f.write(' return 1.0 \n') 1084 1085 # function to compute 1086 out_f.write('\n') 1087 out_f.write('def Iq(x ') 1088 for name in param_names: 1089 out_f.write(', %s' % name) 1090 out_f.write('):\n') 1029 pd_params = [] 1030 out_f.write('parameters = [ \n') 1031 out_f.write('# ["name", "units", default, [lower, upper], "type", "description"],\n') 1032 for pname, pvalue in self.get_param_helper(param_str): 1033 param_names.append(pname) 1034 out_f.write(" ['%s', '', %s, [-inf, inf], '', ''],\n" 1035 % (pname, pvalue)) 1036 for pname, pvalue in self.get_param_helper(pd_param_str): 1037 param_names.append(pname) 1038 pd_params.append(pname) 1039 out_f.write(" ['%s', '', %s, [-inf, inf], 'volume', ''],\n" 1040 % (pname, pvalue)) 1041 out_f.write(' ]\n') 1042 1043 # Write out function definition 1044 out_f.write('def Iq(%s):\n' % ', '.join(['x'] + param_names)) 1045 out_f.write(' """Absolute scattering"""\n') 1046 if "scipy." in func_str: 1047 out_f.write(' import scipy') 1048 if "numpy." in func_str: 1049 out_f.write(' import numpy') 1050 if "np." in func_str: 1051 out_f.write(' import numpy as np') 1091 1052 for func_line in func_str.split('\n'): 1092 1053 out_f.write('%s%s\n' % (spaces4, func_line)) 1093 1094 Iqxy_string = 'return Iq(numpy.sqrt(x**2+y**2) ' 1095 1054 out_f.write('## uncomment the following if Iq works for vector x\n') 1055 out_f.write('#Iq.vectorized = True\n') 1056 1057 # If polydisperse, create place holders for form_volume, ER and VR 1058 if pd_params: 1059 out_f.write('\n') 1060 out_f.write(CUSTOM_TEMPLATE_PD % {'args': ', '.join(pd_params)}) 1061 1062 # Create place holder for Iqxy 1096 1063 out_f.write('\n') 1097 out_f.write('def Iqxy(x, y ') 1098 for name in param_names: 1099 out_f.write(', %s' % name) 1100 Iqxy_string += ', ' + name 1101 out_f.write('):\n') 1102 Iqxy_string += ')' 1103 out_f.write('%s%s\n' % (spaces4, Iqxy_string)) 1064 out_f.write('#def Iqxy(%s):\n' % ', '.join(["x", "y"] + param_names)) 1065 out_f.write('# """Absolute scattering of oriented particles."""\n') 1066 out_f.write('# ...\n') 1067 out_f.write('# return oriented_form(x, y, args)\n') 1068 out_f.write('## uncomment the following if Iqxy works for vector x, y\n') 1069 out_f.write('#Iqxy.vectorized = True\n') 1104 1070 1105 1071 out_f.close() 1106 1072 1107 def get_param_helper(self, line): 1108 """ 1109 Get string in line to define the params dictionary 1110 1111 :param line: one line of string got from the param_str 1112 """ 1113 items = line.split(";") 1114 for item in items: 1115 name = item.split("=")[0].lstrip().rstrip() 1116 try: 1117 value = item.split("=")[1].lstrip().rstrip() 1118 float(value) 1119 except: 1120 value = 1.0 # default 1121 1122 return name, value 1073 def get_param_helper(self, param_str): 1074 """ 1075 yield a sequence of name, value pairs for the parameters in param_str 1076 1077 Parameters can be defined by one per line by name=value, or multiple 1078 on the same line by separating the pairs by semicolon or comma. The 1079 value is optional and defaults to "1.0". 1080 """ 1081 for line in param_str.replace(';', ',').split('\n'): 1082 for item in line.split(','): 1083 parts = item.plit('=') 1084 name = parts[0].strip() 1085 value = parts[1] if len(parts) > 0 else '1.0' 1086 if name: 1087 yield name, value 1123 1088 1124 1089 def set_function_helper(self, line): … … 1154 1119 running "file:///...." 1155 1120 1156 :param evt: Triggers on clicking the help button1157 """1121 :param evt: Triggers on clicking the help button 1122 """ 1158 1123 1159 1124 _TreeLocation = "user/sasgui/perspectives/fitting/fitting_help.html" … … 1198 1163 ## Templates for plugin models 1199 1164 1200 CUSTOM_TEMPLATE = """ 1165 CUSTOM_TEMPLATE = '''\ 1166 r""" 1167 Definition 1168 ---------- 1169 1170 Calculates %(name)s. 1171 1172 %(description)s 1173 1174 References 1175 ---------- 1176 1177 Authorship and Verification 1178 --------------------------- 1179 1180 * **Author:** --- **Date:** %(date)s 1181 * **Last Modified by:** --- **Date:** %(date)s 1182 * **Last Reviewed by:** --- **Date:** %(date)s 1183 """ 1184 1201 1185 from math import * 1202 import os 1203 import sys 1204 import numpy 1205 1206 #name 1207 1208 #title 1209 1210 #description 1211 1212 #parameters 1213 1214 """ 1215 1216 CUSTOM_2D_TEMP = """ 1217 def run(self, x=0.0, y=0.0): 1218 if x.__class__.__name__ == 'list': 1219 x_val = x[0] 1220 y_val = y[0]*0.0 1221 return self.function(x_val, y_val) 1222 elif x.__class__.__name__ == 'tuple': 1223 msg = "Tuples are not allowed as input to BaseComponent models" 1224 raise ValueError, msg 1225 else: 1226 return self.function(x, 0.0) 1227 def runXY(self, x=0.0, y=0.0): 1228 if x.__class__.__name__ == 'list': 1229 return self.function(x, y) 1230 elif x.__class__.__name__ == 'tuple': 1231 msg = "Tuples are not allowed as input to BaseComponent models" 1232 raise ValueError, msg 1233 else: 1234 return self.function(x, y) 1235 def evalDistribution(self, qdist): 1236 if qdist.__class__.__name__ == 'list': 1237 msg = "evalDistribution expects a list of 2 ndarrays" 1238 if len(qdist)!=2: 1239 raise RuntimeError, msg 1240 if qdist[0].__class__.__name__ != 'ndarray': 1241 raise RuntimeError, msg 1242 if qdist[1].__class__.__name__ != 'ndarray': 1243 raise RuntimeError, msg 1244 v_model = numpy.vectorize(self.runXY, otypes=[float]) 1245 iq_array = v_model(qdist[0], qdist[1]) 1246 return iq_array 1247 elif qdist.__class__.__name__ == 'ndarray': 1248 v_model = numpy.vectorize(self.runXY, otypes=[float]) 1249 iq_array = v_model(qdist) 1250 return iq_array 1251 """ 1252 TEST_TEMPLATE = """ 1253 ###################################################################### 1254 ## THIS IS FOR TEST. DO NOT MODIFY THE FOLLOWING LINES!!!!!!!!!!!!!!!! 1255 if __name__ == "__main__": 1256 m= Model() 1257 out1 = m.runXY(0.0) 1258 out2 = m.runXY(0.01) 1259 isfine1 = numpy.isfinite(out1) 1260 isfine2 = numpy.isfinite(out2) 1261 print "Testing the value at Q = 0.0:" 1262 print out1, " : finite? ", isfine1 1263 print "Testing the value at Q = 0.01:" 1264 print out2, " : finite? ", isfine2 1265 if isfine1 and isfine2: 1266 print "===> Simple Test: Passed!" 1267 else: 1268 print "===> Simple Test: Failed!" 1269 """ 1186 from numpy import inf 1187 1188 name = "%(name)s" 1189 title = "%(title)s" 1190 description = """%(description)s""" 1191 1192 ''' 1193 1194 CUSTOM_TEMPLATE_PD = '''\ 1195 def form_volume(%(args)s): 1196 """ 1197 Volume of the particles used to compute absolute scattering intensity 1198 and to weight polydisperse parameter contributions. 1199 """ 1200 return 0.0 1201 1202 def ER(%(args)s): 1203 """ 1204 Effective radius of particles to be used when computing structure factors. 1205 1206 Input parameters are vectors ranging over the mesh of polydispersity values. 1207 """ 1208 return 0.0 1209 1210 def VR(%(args)s): 1211 """ 1212 Volume ratio of particles to be used when computing structure factors. 1213 1214 Input parameters are vectors ranging over the mesh of polydispersity values. 1215 """ 1216 return 1.0 1217 ''' 1218 1270 1219 SUM_TEMPLATE = """ 1271 1220 # A sample of an experimental model function for Sum/Multiply(Pmodel1,Pmodel2) … … 1592 1541 main_app = wx.App() 1593 1542 main_frame = TextDialog(id=1, model_list=["SphereModel", "CylinderModel"], 1594 plugin_dir='../fitting/plugin_models')1543 plugin_dir='../fitting/plugin_models') 1595 1544 main_frame.ShowModal() 1596 1545 main_app.MainLoop() -
src/sas/sasgui/perspectives/fitting/basepage.py
r65f3930 r277257f 504 504 self.state.manager = manager 505 505 506 def populate_box(self, model_ dict):506 def populate_box(self, model_list_box): 507 507 """ 508 508 Store list of model 509 509 510 :param model_dict: dictionary containing list of models 511 512 """ 513 self.model_list_box = model_dict 514 self.state.model_list_box = self.model_list_box 510 :param model_list_box: dictionary containing categorized models 511 """ 512 self.model_list_box = model_list_box 515 513 self.initialize_combox() 516 514 517 def set_model_dictionary(self, model_dict ):515 def set_model_dictionary(self, model_dictionary): 518 516 """ 519 517 Store a dictionary linking model name -> model object 520 518 521 :param model_dict : dictionary containing list ofmodels522 """ 523 self.model_dict = model_dict519 :param model_dictionary: dictionary containing all models 520 """ 521 self.model_dictionary = model_dictionary 524 522 525 523 def initialize_combox(self): … … 527 525 put default value in the combo box 528 526 """ 529 if self.model_list_box is not None and len(self.model_list_box) > 0:527 if self.model_list_box: 530 528 self._populate_box(self.structurebox, 531 529 self.model_list_box["Structure Factors"]) … … 1218 1216 self.categorybox.Select(category_pos) 1219 1217 self._show_combox(None) 1220 if self.categorybox.GetValue() == CUSTOM_MODEL \1221 and PLUGIN_NAME_BASE not in state.formfactorcombobox :1218 if (self.categorybox.GetValue() == CUSTOM_MODEL 1219 and PLUGIN_NAME_BASE not in state.formfactorcombobox): 1222 1220 state.formfactorcombobox = \ 1223 1221 PLUGIN_NAME_BASE + state.formfactorcombobox 1224 1222 formfactor_pos = 0 1225 1223 for ind_form in range(self.formfactorbox.GetCount()): 1226 if self.formfactorbox.GetString(ind_form) == \1227 (state.formfactorcombobox):1224 if (self.formfactorbox.GetString(ind_form) 1225 == state.formfactorcombobox): 1228 1226 formfactor_pos = int(ind_form) 1229 1227 break … … 1235 1233 state.structurecombobox = unicode(state.structurecombobox) 1236 1234 for ind_struct in range(self.structurebox.GetCount()): 1237 if self.structurebox.GetString(ind_struct) == \1238 (state.structurecombobox):1235 if (self.structurebox.GetString(ind_struct) 1236 == state.structurecombobox): 1239 1237 structfactor_pos = int(ind_struct) 1240 1238 break … … 1840 1838 if mod_cat == CUSTOM_MODEL: 1841 1839 for model in self.model_list_box[mod_cat]: 1842 m_list.append(self.model_dict [model.name])1840 m_list.append(self.model_dictionary[model.name]) 1843 1841 else: 1844 1842 cat_dic = self.master_category_dict[mod_cat] 1845 for (model, enabled)in cat_dic:1843 for model, enabled in cat_dic: 1846 1844 if enabled: 1847 m_list.append(self.model_dict [model])1845 m_list.append(self.model_dictionary[model]) 1848 1846 except Exception: 1849 1847 msg = traceback.format_exc() … … 3497 3495 self.model_box.Clear() 3498 3496 3499 if category == 'Plugin Models':3497 if category == CUSTOM_MODEL: 3500 3498 for model in self.model_list_box[category]: 3501 3499 str_m = str(model).split(".")[0] -
src/sas/sasgui/perspectives/fitting/fitpage.py
r50fcb09 r277257f 1143 1143 self.model.name = "M" + str(self.index_model) 1144 1144 1145 def _on_select_model(self, event=None ):1145 def _on_select_model(self, event=None, keep_pars=False): 1146 1146 """ 1147 1147 call back for model selection 1148 1148 """ 1149 1149 self.Show(False) 1150 copy_flag = False1151 is_poly_enabled = None1152 1150 if event is not None: 1153 if (event.GetEventObject() == self.formfactorbox 1154 and self.structurebox.GetLabel() != 'None')\ 1155 or event.GetEventObject() == self.structurebox\ 1156 or event.GetEventObject() == self.multifactorbox: 1157 copy_flag = self.get_copy_params() 1158 is_poly_enabled = self.enable_disp.GetValue() 1151 control = event.GetEventObject() 1152 if ((control == self.formfactorbox 1153 and self.structurebox.GetLabel() != 'None') 1154 or control == self.structurebox 1155 or control == self.multifactorbox): 1156 keep_pars = True 1157 1158 if keep_pars: 1159 saved_pars = self.get_copy_params() 1160 is_poly_enabled = self.enable_disp.GetValue() 1161 else: 1162 saved_pars = None 1163 is_poly_enabled = None 1159 1164 1160 1165 self._on_select_model_helper() … … 1171 1176 try: 1172 1177 self.set_dispers_sizer() 1173 except :1178 except Exception: 1174 1179 pass 1175 1180 self.state.enable_disp = self.enable_disp.GetValue() … … 1232 1237 self.state.model.name = self.model.name 1233 1238 1239 # when select a model only from guictr/button 1240 if is_poly_enabled is not None: 1241 self.enable_disp.SetValue(is_poly_enabled) 1242 self.disable_disp.SetValue(not is_poly_enabled) 1243 self._set_dipers_Param(event=None) 1244 self.state.enable_disp = self.enable_disp.GetValue() 1245 self.state.disable_disp = self.disable_disp.GetValue() 1246 1247 # Keep the previous param values 1248 if saved_pars: 1249 self.get_paste_params(saved_pars) 1250 1234 1251 if event is not None: 1252 # update list of plugins if new plugin is available 1253 # mod_cat = self.categorybox.GetStringSelection() 1254 # if mod_cat == CUSTOM_MODEL: 1255 # temp = self.parent.update_model_list() 1256 # if temp: 1257 # self.model_list_box = temp 1258 # current_val = self.formfactorbox.GetLabel() 1259 # pos = self.formfactorbox.GetSelection() 1260 # self._show_combox_helper() 1261 # self.formfactorbox.SetStringSelection(current_val) 1262 # self.formfactorbox.SetValue(current_val) 1235 1263 # post state to fit panel 1236 1264 new_event = PageInfoEvent(page=self) 1237 1265 wx.PostEvent(self.parent, new_event) 1238 # update list of plugins if new plugin is available1239 custom_model = CUSTOM_MODEL1240 mod_cat = self.categorybox.GetStringSelection()1241 if mod_cat == custom_model:1242 temp = self.parent.update_model_list()1243 if temp:1244 self.model_list_box = temp1245 current_val = self.formfactorbox.GetLabel()1246 pos = self.formfactorbox.GetSelection()1247 self._show_combox_helper()1248 self.formfactorbox.SetSelection(pos)1249 self.formfactorbox.SetValue(current_val)1250 # when select a model only from guictr/button1251 if is_poly_enabled is not None:1252 self.enable_disp.SetValue(is_poly_enabled)1253 self.disable_disp.SetValue(not is_poly_enabled)1254 self._set_dipers_Param(event=None)1255 self.state.enable_disp = self.enable_disp.GetValue()1256 self.state.disable_disp = self.disable_disp.GetValue()1257 1258 # Keep the previous param values1259 if copy_flag:1260 self.get_paste_params(copy_flag)1261 1266 wx.CallAfter(self._onDraw, None) 1262 1267 … … 1709 1714 and not self.temp_multi_functional: 1710 1715 return None 1716 print("_set_fun_box_list", self.model.name) 1711 1717 # Get the func name list 1712 1718 list = self.model.fun_list … … 1716 1722 ind = 0 1717 1723 while(ind < len(list)): 1718 for key, val in list.ite ritems():1719 if (val == ind):1724 for key, val in list.items(): 1725 if val == ind: 1720 1726 fun_box.Append(key, val) 1721 1727 break -
src/sas/sasgui/perspectives/fitting/fitpanel.py
r65f3930 r277257f 114 114 """ 115 115 temp = self.menu_mng.update() 116 if len(temp):116 if temp: 117 117 self.model_list_box = temp 118 118 return temp … … 121 121 """ 122 122 """ 123 temp = self.menu_mng.plugins_reset() 124 if len(temp): 125 self.model_list_box = temp 126 return temp 123 self.model_list_box = self.menu_mng.plugins_reset() 124 return self.model_list_box 127 125 128 126 def get_page_by_id(self, uid): … … 298 296 self.model_list_box = dict 299 297 300 def set_model_dict (self, m_dict):298 def set_model_dictionary(self, model_dictionary): 301 299 """ 302 300 copy a dictionary of model name -> model object 303 301 304 :param m _dict: dictionary linking model name -> model object302 :param model_dictionary: dictionary linking model name -> model object 305 303 """ 306 304 … … 356 354 panel._set_save_flag(not panel.batch_on) 357 355 panel.set_model_dictionary(self.model_dictionary) 358 panel.populate_box(model_ dict=self.model_list_box)356 panel.populate_box(model_list_box=self.model_list_box) 359 357 panel.formfactor_combo_init() 360 358 panel.set_manager(self._manager) -
src/sas/sasgui/perspectives/fitting/fitting.py
r00f7ff1 r277257f 34 34 from sas.sascalc.fit.BumpsFitting import BumpsFit as Fit 35 35 from sas.sascalc.fit.pagestate import Reader, PageState, SimFitPageState 36 from sas.sascalc.fit import models 36 37 37 38 from sas.sasgui.guiframe.dataFitting import Data2D … … 60 61 from .resultpanel import ResultPanel, PlotResultEvent 61 62 from .gpu_options import GpuOptions 62 from . import models63 63 64 64 logger = logging.getLogger(__name__) … … 297 297 event_id = event.GetId() 298 298 model_manager = models.ModelManager() 299 model_list = model_manager. get_model_name_list()299 model_list = model_manager.composable_models() 300 300 plug_dir = models.find_plugins_dir() 301 301 textdial = TextDialog(None, self, wx.ID_ANY, 'Easy Sum/Multi(p1, p2) Editor', … … 337 337 self.set_edit_menu_helper(self.parent, self.edit_custom_model) 338 338 self.set_edit_menu_helper(self.parent, self.delete_custom_model) 339 temp = self.fit_panel.reset_pmodel_list() 340 if temp: 341 # Set the new plugin model list for all fit pages 342 for uid, page in self.fit_panel.opened_pages.iteritems(): 343 if hasattr(page, "formfactorbox"): 344 page.model_list_box = temp 345 current_val = page.formfactorbox.GetLabel() 346 #if page.plugin_rbutton.GetValue(): 347 mod_cat = page.categorybox.GetStringSelection() 348 if mod_cat == custom_model: 349 #pos = page.formfactorbox.GetSelection() 350 page._show_combox_helper() 351 new_val = page.formfactorbox.GetLabel() 352 if current_val != new_val and new_val != '': 353 page.formfactorbox.SetLabel(new_val) 354 else: 355 page.formfactorbox.SetLabel(current_val) 356 except: 339 new_pmodel_list = self.fit_panel.reset_pmodel_list() 340 if not new_pmodel_list: 341 return 342 # Set the new plugin model list for all fit pages 343 for uid, page in self.fit_panel.opened_pages.iteritems(): 344 if hasattr(page, "formfactorbox"): 345 page.model_list_box = new_pmodel_list 346 mod_cat = page.categorybox.GetStringSelection() 347 if mod_cat == custom_model: 348 box = page.formfactorbox 349 model_name = box.GetValue() 350 model = (box.GetClientData(box.GetCurrentSelection()) 351 if model_name else None) 352 page._show_combox_helper() 353 new_index = box.FindString(model_name) 354 new_model = (box.GetClientData(new_index) 355 if new_index >= 0 else None) 356 if new_index >= 0: 357 box.SetStringSelection(model_name) 358 else: 359 box.SetStringSelection('') 360 if model and new_model != model: 361 page._on_select_model(keep_pars=True) 362 except Exception: 357 363 logger.error("update_custom_combo: %s", sys.exc_value) 358 364 … … 364 370 #new_model_menu = wx.Menu() 365 371 self.edit_model_menu.Append(wx_id, 'New Plugin Model', 366 'Add a new model function')372 'Add a new model function') 367 373 wx.EVT_MENU(owner, wx_id, self.make_new_model) 368 374 … … 646 652 self.parent.add_data(data_list={data.id: data}) 647 653 wx.PostEvent(self.parent, NewPlotEvent(plot=data, 648 654 title=data.title)) 649 655 #need to be fix later make sure we are sendind guiframe.data 650 656 #to panel … … 657 663 self.parent.add_data(data_list={data.id: data}) 658 664 wx.PostEvent(self.parent, NewPlotEvent(plot=data, 659 665 title=data.title)) 660 666 page = self.add_fit_page([data]) 661 667 caption = page.window_caption 662 668 self.store_data(uid=page.uid, data_list=page.get_data_list(), 663 caption=caption)669 caption=caption) 664 670 self.mypanels.append(page) 665 671 … … 778 784 """ 779 785 if item.find(".") >= 0: 780 param_names = re.split( "\.", item)786 param_names = re.split(r"\.", item) 781 787 model_name = param_names[0] 782 788 ##Assume max len is 3; eg., M0.radius.width … … 881 887 882 888 self.draw_model(model=model, data=data, page_id=uid, smearer=smear, 883 enable1D=enable1D, enable2D=enable2D,884 qmin=qmin, qmax=qmax, weight=weight)889 enable1D=enable1D, enable2D=enable2D, 890 qmin=qmin, qmax=qmax, weight=weight) 885 891 886 892 def draw_model(self, model, page_id, data=None, smearer=None, … … 925 931 ## draw model 2D with no initial data 926 932 self._draw_model2D(model=model, 927 928 929 930 931 932 933 934 935 936 937 938 933 page_id=page_id, 934 data=data, 935 enable2D=enable2D, 936 smearer=smearer, 937 qmin=qmin, 938 qmax=qmax, 939 fid=fid, 940 weight=weight, 941 state=state, 942 toggle_mode_on=toggle_mode_on, 943 update_chisqr=update_chisqr, 944 source=source) 939 945 940 946 def onFit(self, uid): … … 945 951 :param uid: id related to the panel currently calling this fit function. 946 952 """ 947 if uid is None: raise RuntimeError("no page to fit") # Should never happen 953 if uid is None: 954 raise RuntimeError("no page to fit") # Should never happen 948 955 949 956 sim_page_uid = getattr(self.sim_page, 'uid', None) … … 979 986 page = self.fit_panel.get_page_by_id(page_id) 980 987 self.set_fit_weight(uid=page.uid, 981 flag=page.get_weight_flag(),982 is2d=page._is_2D())988 flag=page.get_weight_flag(), 989 is2d=page._is_2D()) 983 990 if not page.param_toFit: 984 991 msg = "No fitting parameters for %s" % page.window_caption … … 1004 1011 fitter = sim_fitter 1005 1012 self._add_problem_to_fit(fitproblem=fitproblem, 1006 pars=pars,1007 fitter=fitter,1008 fit_id=fit_id)1013 pars=pars, 1014 fitter=fitter, 1015 fit_id=fit_id) 1009 1016 fit_id += 1 1010 1017 list_page_id.append(page_id) … … 1053 1060 ## Perform more than 1 fit at the time 1054 1061 calc_fit = FitThread(handler=handler, 1055 1056 1057 1058 1059 1060 1062 fn=fitter_list, 1063 batch_inputs=batch_inputs, 1064 batch_outputs=batch_outputs, 1065 page_id=list_page_id, 1066 updatefn=handler.update_fit, 1067 completefn=self._fit_completed) 1061 1068 #self.fit_thread_list[current_page_id] = calc_fit 1062 1069 self.fit_thread_list[uid] = calc_fit … … 1119 1126 evt = StatusEvent(status=msg, info="warning") 1120 1127 wx.PostEvent(self.parent, evt) 1121 except :1128 except Exception: 1122 1129 msg = "Creating Fit page: %s" % sys.exc_value 1123 1130 wx.PostEvent(self.parent, StatusEvent(status=msg, info="error")) … … 1143 1150 group_id = str(page.uid) + " Model1D" 1144 1151 wx.PostEvent(self.parent, 1145 NewPlotEvent(group_id=group_id,1146 1152 NewPlotEvent(group_id=group_id, 1153 action="delete")) 1147 1154 self.parent.update_data(prev_data=theory_data, 1148 1155 new_data=data) 1149 1156 else: 1150 1157 if theory_data is not None: … … 1152 1159 data.group_id = theory_data.group_id 1153 1160 wx.PostEvent(self.parent, 1154 NewPlotEvent(group_id=group_id,1155 1161 NewPlotEvent(group_id=group_id, 1162 action="delete")) 1156 1163 self.parent.update_data(prev_data=theory_data, 1157 1164 new_data=data) 1158 1165 self.store_data(uid=page.uid, data_list=page.get_data_list(), 1159 1166 caption=page.window_caption) … … 1557 1564 except KeyboardInterrupt: 1558 1565 fit_msg += "\nSingular point: Fitting stopped." 1559 except :1566 except Exception: 1560 1567 fit_msg += "\nSingular point: Fitting error occurred." 1561 1568 if fit_msg: 1562 evt = StatusEvent(status=fit_msg, info="warning", type="stop")1563 wx.PostEvent(self.parent, evt)1564 1565 except :1569 evt = StatusEvent(status=fit_msg, info="warning", type="stop") 1570 wx.PostEvent(self.parent, evt) 1571 1572 except Exception: 1566 1573 msg = ("Fit completed but the following error occurred: %s" 1567 1574 % sys.exc_value) … … 1721 1728 fid=data.id) 1722 1729 self.parent.update_theory(data_id=data.id, theory=new_plot, 1723 1730 state=state) 1724 1731 return new_plot 1725 1732 … … 1775 1782 1776 1783 self.page_finder[page_id].set_theory_data(data=new_plot, 1777 1784 fid=data.id) 1778 1785 if toggle_mode_on: 1779 1786 wx.PostEvent(self.parent, 1780 1787 NewPlotEvent(group_id=str(page_id) + " Model2D", 1781 1788 action="Hide")) 1782 1789 else: 1783 1790 if update_chisqr: 1784 wx.PostEvent(current_pg, 1785 Chi2UpdateEvent(output=self._cal_chisqr( 1786 data=data, 1787 fid=fid, 1788 weight=weight, 1789 page_id=page_id, 1790 index=index))) 1791 output = self._cal_chisqr(data=data, 1792 fid=fid, 1793 weight=weight, 1794 page_id=page_id, 1795 index=index) 1796 wx.PostEvent(current_pg, Chi2UpdateEvent(output=output)) 1791 1797 else: 1792 1798 self._plot_residuals(page_id=page_id, data=data, fid=fid, … … 1796 1802 logger.error("Using the present parameters the model does not return any finite value. ") 1797 1803 msg = "Computing Error: Model did not return any finite value." 1798 wx.PostEvent(self.parent, StatusEvent(status =msg, info="error"))1804 wx.PostEvent(self.parent, StatusEvent(status=msg, info="error")) 1799 1805 else: 1800 1806 msg = "Computation completed!" … … 1821 1827 1822 1828 def _complete2D(self, image, data, model, page_id, elapsed, index, qmin, 1823 qmax, fid=None, weight=None, toggle_mode_on=False, state=None,1824 1829 qmax, fid=None, weight=None, toggle_mode_on=False, state=None, 1830 update_chisqr=True, source='model', plot_result=True): 1825 1831 """ 1826 1832 Complete get the result of modelthread and create model 2D … … 1863 1869 fid=data.id) 1864 1870 self.parent.update_theory(data_id=data.id, 1865 1866 1871 theory=new_plot, 1872 state=state) 1867 1873 current_pg = self.fit_panel.get_page_by_id(page_id) 1868 1874 title = new_plot.title 1869 1875 if not source == 'fit' and plot_result: 1870 wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, 1871 title=title)) 1876 wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, title=title)) 1872 1877 if toggle_mode_on: 1873 1878 wx.PostEvent(self.parent, 1874 1875 1879 NewPlotEvent(group_id=str(page_id) + " Model1D", 1880 action="Hide")) 1876 1881 else: 1877 1882 # Chisqr in fitpage 1878 1883 if update_chisqr: 1879 wx.PostEvent(current_pg,1880 Chi2UpdateEvent(output=self._cal_chisqr(data=data,1881 weight=weight,1882 fid=fid,1883 page_id=page_id,1884 index=index)))1884 output = self._cal_chisqr(data=data, 1885 weight=weight, 1886 fid=fid, 1887 page_id=page_id, 1888 index=index) 1889 wx.PostEvent(current_pg, Chi2UpdateEvent(output=output)) 1885 1890 else: 1886 1891 self._plot_residuals(page_id=page_id, data=data, fid=fid, 1887 1892 index=index, weight=weight) 1888 1893 1889 1894 if not number_finite: 1890 1895 logger.error("Using the present parameters the model does not return any finite value. ") 1891 1896 msg = "Computing Error: Model did not return any finite value." 1892 wx.PostEvent(self.parent, StatusEvent(status =msg, info="error"))1897 wx.PostEvent(self.parent, StatusEvent(status=msg, info="error")) 1893 1898 else: 1894 1899 msg = "Computation completed!" … … 1906 1911 weight=None, 1907 1912 toggle_mode_on=False, 1908 1913 update_chisqr=True, source='model'): 1909 1914 """ 1910 1915 draw model in 2D … … 1952 1957 def _draw_model1D(self, model, page_id, data, 1953 1958 qmin, qmax, smearer=None, 1954 state=None, 1955 weight=None, 1956 fid=None, 1957 toggle_mode_on=False, update_chisqr=True, source='model', 1958 enable1D=True): 1959 state=None, weight=None, fid=None, 1960 toggle_mode_on=False, update_chisqr=True, source='model', 1961 enable1D=True): 1959 1962 """ 1960 1963 Draw model 1D from loaded data1D
Note: See TracChangeset
for help on using the changeset viewer.