Changeset 6fe5100 in sasview
- Timestamp:
- Apr 6, 2014 7:29:59 AM (11 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, costrafo411, magnetic_scatt, release-4.1.1, release-4.1.2, release-4.2.2, release_4.0.1, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
- Children:
- 95d58d3
- Parents:
- 960fdbb
- Files:
-
- 1 added
- 17 edited
Legend:
- Unmodified
- Added
- Removed
-
run.py
rbbd97e5 r6fe5100 8 8 Usage: 9 9 10 ./run.py [args] 10 ./run.py [(module|script) args...] 11 12 Without arguments run.py runs sasview. With arguments, run.py will run 13 the given module or script. 11 14 """ 12 15 … … 122 125 123 126 if __name__ == "__main__": 124 # start sasview125 #import multiprocessing126 #multiprocessing.freeze_support()127 127 prepare() 128 from sans.sansview.sansview import SasView129 SasView()128 from sans.sansview.sansview import run 129 run() -
sansview/sansview.py
re2271c5 r6fe5100 36 36 PLUGIN_MODEL_DIR = 'plugin_models' 37 37 APP_NAME = 'SasView' 38 def run(): 39 sys.path.append(os.path.join("..","..","..")) 40 from multiprocessing import freeze_support 41 freeze_support() 42 sasview = SasView() 43 38 44 39 class SasViewApp(gui_manager.ViewApp): 45 40 """ … … 113 108 self.gui.clean_plugin_models(PLUGIN_MODEL_DIR) 114 109 # Start the main loop 115 self.gui.MainLoop() 116 110 self.gui.MainLoop() 117 111 118 112 119 if __name__ == "__main__": 113 def run(): 120 114 from multiprocessing import freeze_support 121 115 freeze_support() 122 #Process(target=SasView).start() 123 sasview = SasView() 116 if len(sys.argv) > 1: 117 thing_to_run = sys.argv[1] 118 sys.argv = sys.argv[1:] 119 import runpy 120 if os.path.exists(thing_to_run): 121 runpy.run_path(thing_to_run) 122 else: 123 runpy.run_module(thing_to_run) 124 else: 125 SasView() 124 126 125 127 if __name__ == "__main__": 128 run() 129 -
sansview/setup_exe.py
r27b7acc r6fe5100 319 319 'reportlab.platypus', 320 320 ]) 321 packages.append('IPython') 321 322 includes = ['site'] 322 323 -
setup.py
r968aa6e r6fe5100 69 69 70 70 71 enable_openmp = True71 enable_openmp = False 72 72 73 73 if sys.platform =='darwin': -
src/sans/fit/AbstractFitEngine.py
r6c00702 r6fe5100 3 3 #import logging 4 4 import sys 5 import math 5 6 import numpy 6 import math 7 import park 7 8 8 from sans.dataloader.data_info import Data1D 9 9 from sans.dataloader.data_info import Data2D 10 _SMALLVALUE = 1.0e-10 11 12 class SansParameter(park.Parameter): 13 """ 14 SANS model parameters for use in the PARK fitting service. 15 The parameter attribute value is redirected to the underlying 16 parameter value in the SANS model. 17 """ 18 def __init__(self, name, model, data): 19 """ 20 :param name: the name of the model parameter 21 :param model: the sans model to wrap as a park model 22 """ 23 park.Parameter.__init__(self, name) 24 self._model, self._name = model, name 25 self.data = data 26 self.model = model 27 #set the value for the parameter of the given name 28 self.set(model.getParam(name)) 29 30 def _getvalue(self): 31 """ 32 override the _getvalue of park parameter 33 34 :return value the parameter associates with self.name 35 36 """ 37 return self._model.getParam(self.name) 38 39 def _setvalue(self, value): 40 """ 41 override the _setvalue pf park parameter 42 43 :param value: the value to set on a given parameter 44 45 """ 46 self._model.setParam(self.name, value) 47 48 value = property(_getvalue, _setvalue) 49 50 def _getrange(self): 51 """ 52 Override _getrange of park parameter 53 return the range of parameter 54 """ 55 #if not self.name in self._model.getDispParamList(): 56 lo, hi = self._model.details[self.name][1:3] 57 if lo is None: lo = -numpy.inf 58 if hi is None: hi = numpy.inf 59 if lo > hi: 60 raise ValueError, "wrong fit range for parameters" 61 62 return lo, hi 63 64 def get_name(self): 65 """ 66 """ 67 return self._getname() 68 69 def _setrange(self, r): 70 """ 71 override _setrange of park parameter 72 73 :param r: the value of the range to set 74 75 """ 76 self._model.details[self.name][1:3] = r 77 range = property(_getrange, _setrange) 78 79 80 class Model(park.Model): 81 """ 82 PARK wrapper for SANS models. 10 _SMALLVALUE = 1.0e-10 11 12 # Note: duplicated from park 13 class FitHandler(object): 14 """ 15 Abstract interface for fit thread handler. 16 17 The methods in this class are called by the optimizer as the fit 18 progresses. 19 20 Note that it is up to the optimizer to call the fit handler correctly, 21 reporting all status changes and maintaining the 'done' flag. 22 """ 23 done = False 24 """True when the fit job is complete""" 25 result = None 26 """The current best result of the fit""" 27 28 def improvement(self): 29 """ 30 Called when a result is observed which is better than previous 31 results from the fit. 32 33 result is a FitResult object, with parameters, #calls and fitness. 34 """ 35 def error(self, msg): 36 """ 37 Model had an error; print traceback 38 """ 39 def progress(self, current, expected): 40 """ 41 Called each cycle of the fit, reporting the current and the 42 expected amount of work. The meaning of these values is 43 optimizer dependent, but they can be converted into a percent 44 complete using (100*current)//expected. 45 46 Progress is updated each iteration of the fit, whatever that 47 means for the particular optimization algorithm. It is called 48 after any calls to improvement for the iteration so that the 49 update handler can control I/O bandwidth by suppressing 50 intermediate improvements until the fit is complete. 51 """ 52 def finalize(self): 53 """ 54 Fit is complete; best results are reported 55 """ 56 def abort(self): 57 """ 58 Fit was aborted. 59 """ 60 61 class Model: 62 """ 63 Fit wrapper for SANS models. 83 64 """ 84 65 def __init__(self, sans_model, sans_data=None, **kw): 85 66 """ 86 67 :param sans_model: the sans model to wrap using park interface 87 88 """ 89 park.Model.__init__(self, **kw) 68 69 """ 90 70 self.model = sans_model 91 71 self.name = sans_model.name 92 72 self.data = sans_data 93 #list of parameters names 94 self.sansp = sans_model.getParamList() 95 #list of park parameter 96 self.parkp = [SansParameter(p, sans_model, sans_data) for p in self.sansp] 97 #list of parameter set 98 self.parameterset = park.ParameterSet(sans_model.name, pars=self.parkp) 99 self.pars = [] 100 73 101 74 def get_params(self, fitparams): 102 75 """ 103 76 return a list of value of paramter to fit 104 77 105 78 :param fitparams: list of paramaters name to fit 106 107 """ 108 list_params = [] 109 self.pars = [] 110 self.pars = fitparams 111 for item in fitparams: 112 for element in self.parkp: 113 if element.name == str(item): 114 list_params.append(element.value) 115 return list_params 116 79 80 """ 81 return [self.model.getParam(k) for k in fitparams] 82 117 83 def set_params(self, paramlist, params): 118 84 """ 119 85 Set value for parameters to fit 120 86 121 87 :param params: list of value for parameters to fit 122 123 """ 124 try: 125 for i in range(len(self.parkp)): 126 for j in range(len(paramlist)): 127 if self.parkp[i].name == paramlist[j]: 128 self.parkp[i].value = params[j] 129 self.model.setParam(self.parkp[i].name, params[j]) 130 except: 131 raise 132 88 89 """ 90 for k,v in zip(paramlist, params): 91 self.model.setParam(k,v) 92 93 def set(self, **kw): 94 self.set_params(*zip(*kw.items())) 95 133 96 def eval(self, x): 134 97 """ 135 98 Override eval method of park model. 136 99 137 100 :param x: the x value used to compute a function 138 101 """ … … 141 104 except: 142 105 raise 143 106 144 107 def eval_derivs(self, x, pars=[]): 145 108 """ … … 154 117 instead of calling eval. 155 118 """ 156 return [] 157 158 119 raise NotImplementedError('no derivatives available') 120 121 def __call__(self, x): 122 return self.eval(x) 123 159 124 class FitData1D(Data1D): 160 125 """ … … 185 150 """ 186 151 Data1D.__init__(self, x=x, y=y, dx=dx, dy=dy) 152 self.num_points = len(x) 187 153 self.sans_data = data 188 154 self.smearer = smearer … … 298 264 """ 299 265 self.res_err_image = [] 266 self.num_points = data.size 300 267 self.idx = [] 301 268 self.qmin = None … … 409 376 410 377 411 class SansAssembly: 412 """ 413 Sans Assembly class a class wrapper to be call in optimizer.leastsq method 414 """ 415 def __init__(self, paramlist, model=None, data=None, fitresult=None, 416 handler=None, curr_thread=None, msg_q=None): 417 """ 418 :param Model: the model wrapper fro sans -model 419 :param Data: the data wrapper for sans data 420 421 """ 422 self.model = model 423 self.data = data 424 self.paramlist = paramlist 425 self.msg_q = msg_q 426 self.curr_thread = curr_thread 427 self.handler = handler 428 self.fitresult = fitresult 429 self.res = [] 430 self.true_res = [] 431 self.func_name = "Functor" 432 self.theory = None 433 434 def chisq(self): 435 """ 436 Calculates chi^2 437 438 :param params: list of parameter values 439 440 :return: chi^2 441 442 """ 443 total = 0 444 for item in self.true_res: 445 total += item * item 446 if len(self.true_res) == 0: 447 return None 448 return total / len(self.true_res) 449 450 def __call__(self, params): 451 """ 452 Compute residuals 453 :param params: value of parameters to fit 454 """ 455 #import thread 456 self.model.set_params(self.paramlist, params) 457 #print "params", params 458 self.true_res, theory = self.data.residuals(self.model.eval) 459 self.theory = copy.deepcopy(theory) 460 # check parameters range 461 if self.check_param_range(): 462 # if the param value is outside of the bound 463 # just silent return res = inf 464 return self.res 465 self.res = self.true_res 466 467 if self.fitresult is not None: 468 self.fitresult.set_model(model=self.model) 469 self.fitresult.residuals = self.true_res 470 self.fitresult.iterations += 1 471 self.fitresult.theory = theory 472 473 #fitness = self.chisq(params=params) 474 fitness = self.chisq() 475 self.fitresult.pvec = params 476 self.fitresult.set_fitness(fitness=fitness) 477 if self.msg_q is not None: 478 self.msg_q.put(self.fitresult) 479 480 if self.handler is not None: 481 self.handler.set_result(result=self.fitresult) 482 self.handler.update_fit() 483 484 if self.curr_thread != None: 485 try: 486 self.curr_thread.isquit() 487 except: 488 #msg = "Fitting: Terminated... Note: Forcing to stop " 489 #msg += "fitting may cause a 'Functor error message' " 490 #msg += "being recorded in the log file....." 491 #self.handler.stop(msg) 492 raise 493 494 return self.res 495 496 def check_param_range(self): 497 """ 498 Check the lower and upper bound of the parameter value 499 and set res to the inf if the value is outside of the 500 range 501 :limitation: the initial values must be within range. 502 """ 503 504 #time.sleep(0.01) 505 is_outofbound = False 506 # loop through the fit parameters 507 for p in self.model.parameterset: 508 param_name = p.get_name() 509 if param_name in self.paramlist: 510 511 # if the range was defined, check the range 512 if numpy.isfinite(p.range[0]): 513 if p.value == 0: 514 # This value works on Scipy 515 # Do not change numbers below 516 value = _SMALLVALUE 517 else: 518 value = p.value 519 # For leastsq, it needs a bit step back from the boundary 520 val = p.range[0] - value * _SMALLVALUE 521 if p.value < val: 522 self.res *= 1e+6 523 524 is_outofbound = True 525 break 526 if numpy.isfinite(p.range[1]): 527 # This value works on Scipy 528 # Do not change numbers below 529 if p.value == 0: 530 value = _SMALLVALUE 531 else: 532 value = p.value 533 # For leastsq, it needs a bit step back from the boundary 534 val = p.range[1] + value * _SMALLVALUE 535 if p.value > val: 536 self.res *= 1e+6 537 is_outofbound = True 538 break 539 540 return is_outofbound 541 542 378 543 379 class FitEngine: 544 380 def __init__(self): … … 754 590 755 591 756 IS_MAC = True757 if sys.platform.count("win32") > 0:758 IS_MAC = False759 760 761 592 class FResult(object): 762 593 """ … … 777 608 self.index = [] 778 609 self.parameters = None 779 self.is_mac = IS_MAC780 610 self.model = model 781 611 self.data = data … … 803 633 if self.pvec == None and self.model is None and self.param_list is None: 804 634 return "No results" 805 n = len(self.model.parameterset) 806 807 result_param = zip(xrange(n), self.model.parameterset) 808 msg1 = ["[Iteration #: %s ]" % self.iterations] 809 msg3 = ["=== goodness of fit: %s ===" % (str(self.fitness))] 810 if not self.is_mac: 811 msg2 = ["P%-3d %s......|.....%s" % \ 812 (p[0], p[1], p[1].value)\ 813 for p in result_param if p[1].name in self.param_list] 814 msg = msg1 + msg3 + msg2 815 else: 816 msg = msg1 + msg3 817 msg = "\n".join(msg) 818 return msg 635 636 pars = enumerate(self.model.model.getParamList()) 637 msg1 = "[Iteration #: %s ]" % self.iterations 638 msg3 = "=== goodness of fit: %s ===" % (str(self.fitness)) 639 msg2 = ["P%-3d %s......|.....%s" % (i, v, self.model.model.getParam(v)) 640 for i,v in pars if v in self.param_list] 641 msg = [msg1, msg3] + msg2 642 return "\n".join(msg) 819 643 820 644 def print_summary(self): -
src/sans/fit/Fitting.py
r5777106 r6fe5100 8 8 from sans.fit.ScipyFitting import ScipyFit 9 9 from sans.fit.ParkFitting import ParkFit 10 from sans.fit.BumpsFitting import BumpsFit 10 11 12 ENGINES={ 13 'scipy': ScipyFit, 14 'park': ParkFit, 15 'bumps': BumpsFit, 16 } 11 17 12 18 class Fit(object): … … 59 65 60 66 """ 61 if word == "scipy": 62 self._engine = ScipyFit() 63 elif word == "park": 64 self._engine = ParkFit() 65 else: 66 raise ValueError, "enter the keyword scipy or park" 67 try: 68 self._engine = ENGINES[word]() 69 except KeyError, exc: 70 raise KeyError("fit engine should be one of scipy, park or bumps") 67 71 68 72 def fit(self, msg_q=None, q=None, handler=None, -
src/sans/fit/Loader.py
r5777106 r6fe5100 8 8 This class is loading values from given file or value giving by the user 9 9 """ 10 11 10 def __init__(self, x=None, y=None, dx=None, dy=None): 11 raise NotImplementedError("a code search shows that this code is not active, and you are not seeing this message") 12 12 # variable to store loaded values 13 13 self.x = x -
src/sans/fit/ParkFitting.py
r9d6d5ba r6fe5100 24 24 from sans.fit.AbstractFitEngine import FitEngine 25 25 from sans.fit.AbstractFitEngine import FResult 26 26 27 class SansParameter(park.Parameter): 28 """ 29 SANS model parameters for use in the PARK fitting service. 30 The parameter attribute value is redirected to the underlying 31 parameter value in the SANS model. 32 """ 33 def __init__(self, name, model, data): 34 """ 35 :param name: the name of the model parameter 36 :param model: the sans model to wrap as a park model 37 """ 38 park.Parameter.__init__(self, name) 39 self._model, self._name = model, name 40 self.data = data 41 self.model = model 42 #set the value for the parameter of the given name 43 self.set(model.getParam(name)) 44 45 def _getvalue(self): 46 """ 47 override the _getvalue of park parameter 48 49 :return value the parameter associates with self.name 50 51 """ 52 return self._model.getParam(self.name) 53 54 def _setvalue(self, value): 55 """ 56 override the _setvalue pf park parameter 57 58 :param value: the value to set on a given parameter 59 60 """ 61 self._model.setParam(self.name, value) 62 63 value = property(_getvalue, _setvalue) 64 65 def _getrange(self): 66 """ 67 Override _getrange of park parameter 68 return the range of parameter 69 """ 70 #if not self.name in self._model.getDispParamList(): 71 lo, hi = self._model.details[self.name][1:3] 72 if lo is None: lo = -numpy.inf 73 if hi is None: hi = numpy.inf 74 if lo > hi: 75 raise ValueError, "wrong fit range for parameters" 76 77 return lo, hi 78 79 def get_name(self): 80 """ 81 """ 82 return self._getname() 83 84 def _setrange(self, r): 85 """ 86 override _setrange of park parameter 87 88 :param r: the value of the range to set 89 90 """ 91 self._model.details[self.name][1:3] = r 92 range = property(_getrange, _setrange) 93 94 95 class Model(park.Model): 96 """ 97 PARK wrapper for SANS models. 98 """ 99 def __init__(self, sans_model, sans_data=None, **kw): 100 """ 101 :param sans_model: the sans model to wrap using park interface 102 103 """ 104 park.Model.__init__(self, **kw) 105 self.model = sans_model 106 self.name = sans_model.name 107 self.data = sans_data 108 #list of parameters names 109 self.sansp = sans_model.getParamList() 110 #list of park parameter 111 self.parkp = [SansParameter(p, sans_model, sans_data) for p in self.sansp] 112 #list of parameter set 113 self.parameterset = park.ParameterSet(sans_model.name, pars=self.parkp) 114 self.pars = [] 115 116 def get_params(self, fitparams): 117 """ 118 return a list of value of paramter to fit 119 120 :param fitparams: list of paramaters name to fit 121 122 """ 123 list_params = [] 124 self.pars = [] 125 self.pars = fitparams 126 for item in fitparams: 127 for element in self.parkp: 128 if element.name == str(item): 129 list_params.append(element.value) 130 return list_params 131 132 def set_params(self, paramlist, params): 133 """ 134 Set value for parameters to fit 135 136 :param params: list of value for parameters to fit 137 138 """ 139 try: 140 for i in range(len(self.parkp)): 141 for j in range(len(paramlist)): 142 if self.parkp[i].name == paramlist[j]: 143 self.parkp[i].value = params[j] 144 self.model.setParam(self.parkp[i].name, params[j]) 145 except: 146 raise 147 148 def eval(self, x): 149 """ 150 Override eval method of park model. 151 152 :param x: the x value used to compute a function 153 """ 154 try: 155 return self.model.evalDistribution(x) 156 except: 157 raise 158 159 def eval_derivs(self, x, pars=[]): 160 """ 161 Evaluate the model and derivatives wrt pars at x. 162 163 pars is a list of the names of the parameters for which derivatives 164 are desired. 165 166 This method needs to be specialized in the model to evaluate the 167 model function. Alternatively, the model can implement is own 168 version of residuals which calculates the residuals directly 169 instead of calling eval. 170 """ 171 return [] 172 173 27 174 class SansFitResult(fitresult.FitResult): 28 175 def __init__(self, *args, **kwrds): … … 383 530 def fit(self, msg_q=None, 384 531 q=None, handler=None, curr_thread=None, 385 532 ftol=1.49012e-8, reset_flag=False): 386 533 """ 387 534 Performs fit with park.fit module.It can perform fit with one model -
src/sans/fit/ScipyFitting.py
r5777106 r6fe5100 1 2 3 1 """ 4 2 ScipyFitting module contains FitArrange , ScipyFit, … … 6 4 simple fit with scipy optimizer. 7 5 """ 6 import sys 7 import copy 8 8 9 9 import numpy 10 import sys11 12 10 13 11 from sans.fit.AbstractFitEngine import FitEngine 14 from sans.fit.AbstractFitEngine import SansAssembly 15 from sans.fit.AbstractFitEngine import FitAbort 16 from sans.fit.AbstractFitEngine import Model 17 from sans.fit.AbstractFitEngine import FResult 12 from sans.fit.AbstractFitEngine import FResult 13 14 class SansAssembly: 15 """ 16 Sans Assembly class a class wrapper to be call in optimizer.leastsq method 17 """ 18 def __init__(self, paramlist, model=None, data=None, fitresult=None, 19 handler=None, curr_thread=None, msg_q=None): 20 """ 21 :param Model: the model wrapper fro sans -model 22 :param Data: the data wrapper for sans data 23 24 """ 25 self.model = model 26 self.data = data 27 self.paramlist = paramlist 28 self.msg_q = msg_q 29 self.curr_thread = curr_thread 30 self.handler = handler 31 self.fitresult = fitresult 32 self.res = [] 33 self.true_res = [] 34 self.func_name = "Functor" 35 self.theory = None 36 37 def chisq(self): 38 """ 39 Calculates chi^2 40 41 :param params: list of parameter values 42 43 :return: chi^2 44 45 """ 46 total = 0 47 for item in self.true_res: 48 total += item * item 49 if len(self.true_res) == 0: 50 return None 51 return total / len(self.true_res) 52 53 def __call__(self, params): 54 """ 55 Compute residuals 56 :param params: value of parameters to fit 57 """ 58 #import thread 59 self.model.set_params(self.paramlist, params) 60 #print "params", params 61 self.true_res, theory = self.data.residuals(self.model.eval) 62 self.theory = copy.deepcopy(theory) 63 # check parameters range 64 if self.check_param_range(): 65 # if the param value is outside of the bound 66 # just silent return res = inf 67 return self.res 68 self.res = self.true_res 69 70 if self.fitresult is not None: 71 self.fitresult.set_model(model=self.model) 72 self.fitresult.residuals = self.true_res 73 self.fitresult.iterations += 1 74 self.fitresult.theory = theory 75 76 #fitness = self.chisq(params=params) 77 fitness = self.chisq() 78 self.fitresult.pvec = params 79 self.fitresult.set_fitness(fitness=fitness) 80 if self.msg_q is not None: 81 self.msg_q.put(self.fitresult) 82 83 if self.handler is not None: 84 self.handler.set_result(result=self.fitresult) 85 self.handler.update_fit() 86 87 if self.curr_thread != None: 88 try: 89 self.curr_thread.isquit() 90 except: 91 #msg = "Fitting: Terminated... Note: Forcing to stop " 92 #msg += "fitting may cause a 'Functor error message' " 93 #msg += "being recorded in the log file....." 94 #self.handler.stop(msg) 95 raise 96 97 return self.res 98 99 def check_param_range(self): 100 """ 101 Check the lower and upper bound of the parameter value 102 and set res to the inf if the value is outside of the 103 range 104 :limitation: the initial values must be within range. 105 """ 106 107 #time.sleep(0.01) 108 is_outofbound = False 109 # loop through the fit parameters 110 model = self.model.model 111 for p in self.paramlist: 112 value = model.getParam(p) 113 low,high = model.details[p][1:3] 114 if low is not None and numpy.isfinite(low): 115 if p.value == 0: 116 # This value works on Scipy 117 # Do not change numbers below 118 value = _SMALLVALUE 119 # For leastsq, it needs a bit step back from the boundary 120 val = low - value * _SMALLVALUE 121 if value < val: 122 self.res *= 1e+6 123 is_outofbound = True 124 break 125 if high is not None and numpy.isfinite(high): 126 # This value works on Scipy 127 # Do not change numbers below 128 if value == 0: 129 value = _SMALLVALUE 130 # For leastsq, it needs a bit step back from the boundary 131 val = high + value * _SMALLVALUE 132 if value > val: 133 self.res *= 1e+6 134 is_outofbound = True 135 break 136 137 return is_outofbound 18 138 19 139 class ScipyFit(FitEngine): … … 50 170 """ 51 171 FitEngine.__init__(self) 52 self.fit_arrange_dict = {}53 self.param_list = []54 172 self.curr_thread = None 55 173 #def fit(self, *args, **kw): … … 68 186 msg = "Scipy can't fit more than a single fit problem at a time." 69 187 raise RuntimeError, msg 70 return 71 elif len(fitproblem) == 0 : 188 elif len(fitproblem) == 0 : 72 189 raise RuntimeError, "No Assembly scheduled for Scipy fitting." 73 return74 190 model = fitproblem[0].get_model() 75 191 if reset_flag: … … 87 203 88 204 # Check the initial value if it is within range 89 self._check_param_range(model)205 _check_param_range(model.model, self.param_list) 90 206 91 207 result = FResult(model=model, data=data, param_list=self.param_list) … … 94 210 if handler is not None: 95 211 handler.set_result(result=result) 212 functor = SansAssembly(paramlist=self.param_list, 213 model=model, 214 data=data, 215 handler=handler, 216 fitresult=result, 217 curr_thread=curr_thread, 218 msg_q=msg_q) 96 219 try: 97 220 # This import must be here; otherwise it will be confused when more … … 99 222 from scipy import optimize 100 223 101 functor = SansAssembly(paramlist=self.param_list,102 model=model,103 data=data,104 handler=handler,105 fitresult=result,106 curr_thread=curr_thread,107 msg_q=msg_q)108 224 out, cov_x, _, mesg, success = optimize.leastsq(functor, 109 225 model.get_params(self.param_list), 110 111 226 ftol=ftol, 227 full_output=1) 112 228 except: 113 229 if hasattr(sys, 'last_type') and sys.last_type == KeyboardInterrupt: … … 142 258 143 259 144 def _check_param_range(self, model): 145 """ 146 Check parameter range and set the initial value inside 147 if it is out of range. 148 149 : model: park model object 150 """ 151 is_outofbound = False 152 # loop through parameterset 153 for p in model.parameterset: 154 param_name = p.get_name() 155 # proceed only if the parameter name is in the list of fitting 156 if param_name in self.param_list: 157 # if the range was defined, check the range 158 if numpy.isfinite(p.range[0]): 159 if p.value <= p.range[0]: 160 # 10 % backing up from the border if not zero 161 # for Scipy engine to work properly. 162 shift = self._get_zero_shift(p.range[0]) 163 new_value = p.range[0] + shift 164 p.value = new_value 165 is_outofbound = True 166 if numpy.isfinite(p.range[1]): 167 if p.value >= p.range[1]: 168 shift = self._get_zero_shift(p.range[1]) 169 # 10 % backing up from the border if not zero 170 # for Scipy engine to work properly. 171 new_value = p.range[1] - shift 172 # Check one more time if the new value goes below 173 # the low bound, If so, re-evaluate the value 174 # with the mean of the range. 175 if numpy.isfinite(p.range[0]): 176 if new_value < p.range[0]: 177 new_value = (p.range[0] + p.range[1]) / 2.0 178 # Todo: 179 # Need to think about when both min and max are same. 180 p.value = new_value 181 is_outofbound = True 182 183 return is_outofbound 184 185 def _get_zero_shift(self, range): 186 """ 187 Get 10% shift of the param value = 0 based on the range value 188 189 : param range: min or max value of the bounds 190 """ 191 if range == 0: 192 shift = 0.1 193 else: 194 shift = 0.1 * range 195 196 return shift 197 260 def _check_param_range(model, param_list): 261 """ 262 Check parameter range and set the initial value inside 263 if it is out of range. 264 265 : model: park model object 266 """ 267 # loop through parameterset 268 for p in param_list: 269 value = model.getParam(p) 270 low,high = model.details[p][1:3] 271 # if the range was defined, check the range 272 if low is not None and value <= low: 273 value = low + _get_zero_shift(low) 274 if high is not None and value > high: 275 value = high - _get_zero_shift(high) 276 # Check one more time if the new value goes below 277 # the low bound, If so, re-evaluate the value 278 # with the mean of the range. 279 if low is not None and value < low: 280 value = 0.5 * (low+high) 281 model.setParam(p, value) 282 283 def _get_zero_shift(limit): 284 """ 285 Get 10% shift of the param value = 0 based on the range value 286 287 : param range: min or max value of the bounds 288 """ 289 return 0.1 (limit if limit != 0.0 else 1.0) 290 198 291 199 292 #def profile(fn, *args, **kw): -
src/sans/fit/__init__.py
r5777106 r6fe5100 1 from .AbstractFitEngine import FitHandler -
src/sans/perspectives/fitting/basepage.py
r27b7acc r6fe5100 808 808 infor = "warning" 809 809 else: 810 msg = "Error was occured"811 msg += " :No valid parameter values to paste from the clipboard..."810 msg = "Error occured: " 811 msg += "No valid parameter values to paste from the clipboard..." 812 812 infor = "error" 813 813 wx.PostEvent(self._manager.parent, … … 2149 2149 else: 2150 2150 tcrtl.SetBackgroundColour("pink") 2151 msg = "Model Error: wrong value entered: %s" % sys.exc_value2151 msg = "Model Error: wrong value entered: %s" % sys.exc_value 2152 2152 wx.PostEvent(self.parent, StatusEvent(status=msg)) 2153 2153 return 2154 2154 except: 2155 2155 tcrtl.SetBackgroundColour("pink") 2156 msg = "Model Error: wrong value entered: %s" % sys.exc_value2156 msg = "Model Error: wrong value entered: %s" % sys.exc_value 2157 2157 wx.PostEvent(self.parent, StatusEvent(status=msg)) 2158 2158 return … … 2165 2165 #is_modified = True 2166 2166 else: 2167 msg = "Cannot Plot :No npts in that Qrange!!! "2167 msg = "Cannot plot: No points in Q range!!! " 2168 2168 wx.PostEvent(self.parent, StatusEvent(status=msg)) 2169 2169 else: 2170 2170 tcrtl.SetBackgroundColour("pink") 2171 msg = "Model Error: wrong value entered!!!"2171 msg = "Model Error: wrong value entered!!!" 2172 2172 wx.PostEvent(self.parent, StatusEvent(status=msg)) 2173 2173 self.save_current_state() … … 2206 2206 else: 2207 2207 tcrtl.SetBackgroundColour("pink") 2208 msg = "Model Error: wrong value entered: %s" % sys.exc_value2208 msg = "Model Error: wrong value entered: %s" % sys.exc_value 2209 2209 wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) 2210 2210 return 2211 2211 except: 2212 2212 tcrtl.SetBackgroundColour("pink") 2213 msg = "Model Error: wrong value entered: %s" % sys.exc_value2213 msg = "Model Error: wrong value entered: %s" % sys.exc_value 2214 2214 wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) 2215 2215 return … … 2222 2222 is_modified = True 2223 2223 else: 2224 msg = "Cannot Plot :No npts in that Qrange!!! "2224 msg = "Cannot Plot: No points in Q range!!! " 2225 2225 wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) 2226 2226 else: 2227 2227 tcrtl.SetBackgroundColour("pink") 2228 msg = "Model Error: wrong value entered!!!"2228 msg = "Model Error: wrong value entered!!!" 2229 2229 wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) 2230 2230 self.save_current_state() … … 2397 2397 self.qmax.SetBackgroundColour("pink") 2398 2398 self.qmax.Refresh() 2399 msg = " Npts of Data Error :"2400 msg += " No or too little npts of%s." % data.name2399 msg = "Data Error: " 2400 msg += "Too few points in %s." % data.name 2401 2401 wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) 2402 2402 self.fitrange = False … … 2432 2432 self.qmax.SetBackgroundColour("pink") 2433 2433 self.qmax.Refresh() 2434 msg = " Npts of Data Error :"2435 msg += " No or too little npts of%s." % data.name2434 msg = "Data Error: " 2435 msg += "Too few points in %s." % data.name 2436 2436 wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) 2437 2437 self.fitrange = False … … 2484 2484 2485 2485 except: 2486 msg = "Wrong Fit parameter range entered"2486 msg = "Wrong fit parameter range entered" 2487 2487 wx.PostEvent(self._manager.parent, 2488 2488 StatusEvent(status=msg)) -
src/sans/perspectives/fitting/console.py
r5777106 r6fe5100 5 5 import time 6 6 import wx 7 import park 8 from park.fitresult import FitHandler 7 from sans.fit import FitHandler 9 8 10 9 class ConsoleUpdate(FitHandler): -
src/sans/perspectives/fitting/fitting.py
r767514a r6fe5100 111 111 self.scipy_id = wx.NewId() 112 112 self.park_id = wx.NewId() 113 self.bumps_id = wx.NewId() 113 114 self.menu1 = None 114 115 self.new_model_frame = None … … 198 199 wx.EVT_MENU(owner, self.park_id, self._onset_engine_park) 199 200 201 bumps_help = "Bumps: fitting and uncertainty analysis. More in Help window...." 202 self.menu1.AppendCheckItem(self.bumps_id, "Bumps fit", 203 bumps_help) 204 wx.EVT_MENU(owner, self.bumps_id, self._onset_engine_bumps) 205 200 206 self.menu1.FindItemById(self.scipy_id).Check(True) 201 207 self.menu1.FindItemById(self.park_id).Check(False) 208 self.menu1.FindItemById(self.bumps_id).Check(False) 202 209 self.menu1.AppendSeparator() 203 210 self.id_tol = wx.NewId() … … 207 214 ftol_help) 208 215 wx.EVT_MENU(owner, self.id_tol, self.show_ftol_dialog) 216 217 self.id_bumps_options = wx.NewId() 218 bopts_help = "Bumps fitting options" 219 self.menu1.Append(self.id_bumps_options, 'Bumps &Options', bopts_help) 220 wx.EVT_MENU(owner, self.id_bumps_options, self.on_bumps_options) 221 self.bumps_options_menu = self.menu1.FindItemById(self.id_bumps_options) 222 self.bumps_options_menu.Enable(True) 209 223 self.menu1.AppendSeparator() 210 224 … … 819 833 dialog.Destroy() 820 834 835 def on_bumps_options(self, event=None): 836 from bumps.gui.fit_dialog import OpenFitOptions 837 OpenFitOptions() 838 821 839 def stop_fit(self, uid): 822 840 """ … … 959 977 self._gui_engine = self._return_engine_type() 960 978 self.fitproblem_count = fitproblem_count 961 if self._fit_engine == "park":979 if self._fit_engine in ("park","bumps"): 962 980 engineType = "Simultaneous Fit" 963 981 else: … … 1682 1700 self._on_change_engine('scipy') 1683 1701 1702 def _onset_engine_bumps(self, event): 1703 """ 1704 set engine to bumps 1705 """ 1706 self._on_change_engine('bumps') 1707 1684 1708 def _on_slicer_event(self, event): 1685 1709 """ … … 1733 1757 self.menu1.FindItemById(self.park_id).Check(True) 1734 1758 self.menu1.FindItemById(self.scipy_id).Check(False) 1759 self.menu1.FindItemById(self.bumps_id).Check(False) 1760 elif engine == "scipy": 1761 self.menu1.FindItemById(self.park_id).Check(False) 1762 self.menu1.FindItemById(self.scipy_id).Check(True) 1763 self.menu1.FindItemById(self.bumps_id).Check(False) 1735 1764 else: 1736 1765 self.menu1.FindItemById(self.park_id).Check(False) 1737 self.menu1.FindItemById(self.scipy_id).Check(True) 1766 self.menu1.FindItemById(self.scipy_id).Check(False) 1767 self.menu1.FindItemById(self.bumps_id).Check(True) 1738 1768 ## post a message to status bar 1739 1769 msg = "Engine set to: %s" % self._fit_engine -
test/park_integration/test/test_fit_line.py
rda5d8e8 r6fe5100 4 4 """ 5 5 import unittest 6 import math 6 7 7 8 from sans.fit.AbstractFitEngine import Model … … 11 12 from sans.models.Constant import Constant 12 13 13 import math14 14 class testFitModule(unittest.TestCase): 15 15 """ test fitting """ … … 21 21 data.name = data.filename 22 22 #Importing the Fit module 23 fitter = Fit('scipy') 23 from bumps import fitters 24 fitters.FIT_DEFAULT = 'dream' 25 print fitters.FIT_OPTIONS['dream'].__dict__ 26 fitter = Fit('bumps') 24 27 # Receives the type of model for the fitting 25 28 model1 = LineModel() … … 44 47 self.assertTrue( result1.fitness/len(data.x) < 2 ) 45 48 49 return 46 50 #fit with park test 47 51 fitter = Fit('park') … … 103 107 assert str(msg)=="Scipy can't fit more than a single fit problem at a time." 104 108 else: raise AssertionError,"No error raised for scipy fitting with more than 2 models" 105 109 110 return 106 111 #fit with park test 107 112 fitter = Fit('park') … … 121 126 def test3(self): 122 127 """ fit 2 data and 2 model with 1 constrainst""" 128 return 123 129 #load data 124 130 l = Loader() … … 189 195 190 196 result1, = fitter.fit() 197 #print(result1) 191 198 self.assert_(result1) 192 199 … … 194 201 self.assertTrue( math.fabs(result1.pvec[1]-2.5)/3 <= result1.stderr[1]) 195 202 self.assertTrue( result1.fitness/len(data1.x) < 2 ) 196 203 204 return 197 205 #fit with park test 198 206 fitter = Fit('park') … … 213 221 self.assertAlmostEquals( result1.stderr[1],result2.stderr[1] ) 214 222 self.assertTrue( result2.fitness/(len(data2.x)+len(data1.x)) < 2 ) 215 216 223 224 225 if __name__ == "__main__": 226 unittest.main() 217 227 218 -
test/pr_inversion/test/test_output.txt
r6c00702 r6fe5100 3 3 #alpha=0.0007 4 4 #chi2=836.797 5 #elapsed=0.000 9999285 #elapsed=0.000168085 6 6 #qmin=None 7 7 #qmax=None -
test/run_one.py
r6c00702 r6fe5100 1 #!/usr/bin/env python 2 1 3 import os 2 4 import sys … … 12 14 #print "\n".join(sys.path) 13 15 test_path,test_file = splitpath(sys.argv[1]) 14 print " test file",sys.argv[1]16 print "=== testing:",sys.argv[1] 15 17 #print test_path, test_file 16 18 sys.argv = [sys.argv[0]] … … 19 21 test = imp.load_source('tests',test_file) 20 22 unittest.main(test, testRunner=xmlrunner.XMLTestRunner(output='logs')) 21 -
test/utest_sansview.py
r6c00702 r6fe5100 1 #!/usr/bin/env python 1 2 import os 2 3 import subprocess
Note: See TracChangeset
for help on using the changeset viewer.