Changeset 89f3b66 in sasview
- Timestamp:
- Oct 19, 2010 9:02:08 PM (14 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:
- 4ddb7a4
- Parents:
- 74b1770
- Location:
- park_integration
- Files:
-
- 6 edited
Legend:
- Unmodified
- Added
- Removed
-
park_integration/AbstractFitEngine.py
r189be4e r89f3b66 1 1 2 3 import logging, sys 4 import park,numpy,math, copy 2 import copy 3 import logging 4 import sys 5 import numpy 6 import math 7 import park 5 8 from DataLoader.data_info import Data1D 6 9 from DataLoader.data_info import Data2D … … 18 21 19 22 """ 20 self._model, self._name = model, name23 self._model, self._name = model, name 21 24 #set the value for the parameter of the given name 22 25 self.set(model.getParam(name)) … … 31 34 return self._model.getParam(self.name) 32 35 33 def _setvalue(self, value):36 def _setvalue(self, value): 34 37 """ 35 38 override the _setvalue pf park parameter … … 48 51 """ 49 52 #if not self.name in self._model.getDispParamList(): 50 lo, hi = self._model.details[self.name][1:3]53 lo, hi = self._model.details[self.name][1:3] 51 54 if lo is None: lo = -numpy.inf 52 55 if hi is None: hi = numpy.inf … … 58 61 raise ValueError,"wrong fit range for parameters" 59 62 60 return lo, hi61 62 def _setrange(self, r):63 return lo, hi 64 65 def _setrange(self, r): 63 66 """ 64 67 override _setrange of park parameter … … 68 71 """ 69 72 self._model.details[self.name][1:3] = r 70 range = property(_getrange, _setrange)73 range = property(_getrange, _setrange) 71 74 72 75 class Model(park.Model): … … 87 90 self.parkp = [SansParameter(p,sans_model) for p in self.sansp] 88 91 #list of parameterset 89 self.parameterset = park.ParameterSet(sans_model.name, pars=self.parkp)90 self.pars =[]92 self.parameterset = park.ParameterSet(sans_model.name, pars=self.parkp) 93 self.pars = [] 91 94 92 def getParams(self, fitparams):95 def getParams(self, fitparams): 93 96 """ 94 97 return a list of value of paramter to fit … … 97 100 98 101 """ 99 list =[]100 self.pars =[]101 self.pars =fitparams102 list = [] 103 self.pars = [] 104 self.pars = fitparams 102 105 for item in fitparams: 103 106 for element in self.parkp: 104 if element.name == str(item):107 if element.name == str(item): 105 108 list.append(element.value) 106 109 return list 107 110 108 def setParams(self, paramlist, params):111 def setParams(self, paramlist, params): 109 112 """ 110 113 Set value for parameters to fit … … 116 119 for i in range(len(self.parkp)): 117 120 for j in range(len(paramlist)): 118 if self.parkp[i].name ==paramlist[j]:121 if self.parkp[i].name == paramlist[j]: 119 122 self.parkp[i].value = params[j] 120 self.model.setParam(self.parkp[i].name, params[j])123 self.model.setParam(self.parkp[i].name, params[j]) 121 124 except: 122 125 raise 123 126 124 def eval(self, x):127 def eval(self, x): 125 128 """ 126 129 override eval method of park model. … … 141 144 a way to get residuals from data. 142 145 """ 143 def __init__(self,x, y,dx= None, dy=None, smearer=None): 144 Data1D.__init__(self, x=numpy.array(x), y=numpy.array(y), dx=dx, dy=dy) 146 def __init__(self, x, y, dx=None, dy=None, smearer=None): 145 147 """ 146 148 :param smearer: is an object of class QSmearer or SlitSmearer … … 162 164 163 165 """ 166 Data1D.__init__(self, x=x, y=y, dx=dx, dy=dy) 167 164 168 self.smearer = smearer 165 169 166 170 # Check error bar; if no error bar found, set it constant(=1) 167 171 # TODO: Should provide an option for users to set it like percent, constant, or dy data 168 if dy == None or dy==[] or dy.all()==0:169 self.dy = numpy.ones(len(y))172 if dy == None or dy == [] or dy.all() == 0: 173 self.dy = numpy.ones(len(y)) 170 174 else: 171 self.dy = numpy.asarray(dy).copy()175 self.dy = numpy.asarray(dy).copy() 172 176 173 177 ## Min Q-value 174 178 #Skip the Q=0 point, especially when y(q=0)=None at x[0]. 175 if min (self.x) ==0.0 and self.x[0]==0 and not numpy.isfinite(self.y[0]): 179 if min (self.x) == 0.0 and self.x[0] == 0 and\ 180 not numpy.isfinite(self.y[0]): 176 181 self.qmin = min(self.x[self.x!=0]) 177 182 else: 178 self.qmin = min(self.x)183 self.qmin = min(self.x) 179 184 ## Max Q-value 180 self.qmax = max 185 self.qmax = max(self.x) 181 186 182 187 # Range used for input to smearing … … 184 189 self._qmax_unsmeared = self.qmax 185 190 # Identify the bin range for the unsmeared and smeared spaces 186 self.idx = (self.x>=self.qmin) & (self.x <= self.qmax) 187 self.idx_unsmeared = (self.x>=self._qmin_unsmeared) & (self.x <= self._qmax_unsmeared) 191 self.idx = (self.x >= self.qmin) & (self.x <= self.qmax) 192 self.idx_unsmeared = (self.x >= self._qmin_unsmeared) \ 193 & (self.x <= self._qmax_unsmeared) 188 194 189 190 191 def setFitRange(self,qmin=None,qmax=None): 195 def setFitRange(self, qmin=None, qmax=None): 192 196 """ to set the fit range""" 193 197 # Skip Q=0 point, (especially for y(q=0)=None at x[0]). 194 198 # ToDo: Find better way to do it. 195 if qmin ==0.0 and not numpy.isfinite(self.y[qmin]):196 self.qmin = min(self.x[self.x !=0])197 elif qmin !=None:199 if qmin == 0.0 and not numpy.isfinite(self.y[qmin]): 200 self.qmin = min(self.x[self.x != 0]) 201 elif qmin != None: 198 202 self.qmin = qmin 199 200 if qmax !=None: 203 if qmax != None: 201 204 self.qmax = qmax 202 203 205 # Determine the range needed in unsmeared-Q to cover 204 206 # the smeared Q range … … 207 209 208 210 self._first_unsmeared_bin = 0 209 self._last_unsmeared_bin = len(self.x) -1211 self._last_unsmeared_bin = len(self.x) - 1 210 212 211 213 if self.smearer!=None: 212 self._first_unsmeared_bin, self._last_unsmeared_bin = self.smearer.get_bin_range(self.qmin, self.qmax) 214 self._first_unsmeared_bin, self._last_unsmeared_bin = \ 215 self.smearer.get_bin_range(self.qmin, self.qmax) 213 216 self._qmin_unsmeared = self.x[self._first_unsmeared_bin] 214 217 self._qmax_unsmeared = self.x[self._last_unsmeared_bin] 215 218 216 219 # Identify the bin range for the unsmeared and smeared spaces 217 self.idx = (self.x>=self.qmin) & (self.x <= self.qmax) 218 self.idx = self.idx & (self.dy!=0) ## zero error can not participate for fitting 219 self.idx_unsmeared = (self.x>=self._qmin_unsmeared) & (self.x <= self._qmax_unsmeared) 220 self.idx = (self.x >= self.qmin) & (self.x <= self.qmax) 221 ## zero error can not participate for fitting 222 self.idx = self.idx & (self.dy != 0) 223 self.idx_unsmeared = (self.x >= self._qmin_unsmeared) \ 224 & (self.x <= self._qmax_unsmeared) 220 225 221 222 226 def getFitRange(self): 223 227 """ … … 239 243 """ 240 244 # Compute theory data f(x) 241 fx = numpy.zeros(len(self.x))245 fx = numpy.zeros(len(self.x)) 242 246 fx[self.idx_unsmeared] = fn(self.x[self.idx_unsmeared]) 243 247 244 248 ## Smear theory data 245 249 if self.smearer is not None: 246 fx = self.smearer(fx, self._first_unsmeared_bin, self._last_unsmeared_bin)247 250 fx = self.smearer(fx, self._first_unsmeared_bin, 251 self._last_unsmeared_bin) 248 252 ## Sanity check 249 if numpy.size(self.dy) != numpy.size(fx):250 raise RuntimeError, "FitData1D: invalid error array %d <> %d" % (numpy.shape(self.dy),251 numpy.size(fx))252 253 return (self.y[self.idx] -fx[self.idx])/self.dy[self.idx]253 if numpy.size(self.dy) != numpy.size(fx): 254 msg = "FitData1D: invalid error array " 255 msg += "%d <> %d" % (numpy.shape(self.dy), numpy.size(fx)) 256 raise RuntimeError, msg 257 return (self.y[self.idx] - fx[self.idx]) / self.dy[self.idx] 254 258 255 259 def residuals_deriv(self, model, pars=[]): … … 262 266 return [] 263 267 264 265 268 class FitData2D(Data2D): 266 269 """ Wrapper class for SANS data """ 267 def __init__(self, sans_data2d ,data=None, err_data=None):268 Data2D.__init__(self, data= 270 def __init__(self, sans_data2d, data=None, err_data=None): 271 Data2D.__init__(self, data=data, err_data= err_data) 269 272 """ 270 273 Data can be initital with a data (sans plottable) 271 274 or with vectors. 272 275 """ 273 self.res_err_image =[]274 self.index_model =[]275 self.qmin = None276 self.qmax = None276 self.res_err_image = [] 277 self.index_model = [] 278 self.qmin = None 279 self.qmax = None 277 280 self.smearer = None 278 self.set_data(sans_data2d 279 280 281 def set_data(self, sans_data2d, qmin=None, qmax=None 281 self.set_data(sans_data2d) 282 283 284 def set_data(self, sans_data2d, qmin=None, qmax=None): 282 285 """ 283 286 Determine the correct qx_data and qy_data within range to fit 284 287 """ 285 self.data 288 self.data = sans_data2d.data 286 289 self.err_data = sans_data2d.err_data 287 290 self.qx_data = sans_data2d.qx_data 288 291 self.qy_data = sans_data2d.qy_data 289 self.mask 292 self.mask = sans_data2d.mask 290 293 291 294 x_max = max(math.fabs(sans_data2d.xmin), math.fabs(sans_data2d.xmax)) … … 296 299 self.qmin = 1e-16 297 300 if qmax == None: 298 self.qmax = math.sqrt(x_max *x_max +y_max*y_max)301 self.qmax = math.sqrt(x_max * x_max + y_max * y_max) 299 302 ## new error image for fitting purpose 300 if self.err_data == None or self.err_data ==[]:301 self.res_err_data = numpy.ones(len(self.data))303 if self.err_data == None or self.err_data == []: 304 self.res_err_data = numpy.ones(len(self.data)) 302 305 else: 303 306 self.res_err_data = copy.deepcopy(self.err_data) 304 307 #self.res_err_data[self.res_err_data==0]=1 305 308 306 self.radius = numpy.sqrt(self.qx_data**2 + self.qy_data**2)309 self.radius = numpy.sqrt(self.qx_data**2 + self.qy_data**2) 307 310 308 311 # Note: mask = True: for MASK while mask = False for NOT to mask 309 self.index_model = ((self.qmin <= self.radius)&(self.radius<= self.qmax)) 312 self.index_model = ((self.qmin <= self.radius)&\ 313 (self.radius <= self.qmax)) 310 314 self.index_model = (self.index_model) & (self.mask) 311 315 self.index_model = (self.index_model) & (numpy.isfinite(self.data)) … … 321 325 self.smearer.get_data() 322 326 323 def setFitRange(self, qmin=None,qmax=None):327 def setFitRange(self, qmin=None, qmax=None): 324 328 """ to set the fit range""" 325 if qmin ==0.0:329 if qmin == 0.0: 326 330 self.qmin = 1e-16 327 elif qmin !=None:331 elif qmin != None: 328 332 self.qmin = qmin 329 if qmax!=None: 330 self.qmax= qmax 331 self.radius= numpy.sqrt(self.qx_data**2 + self.qy_data**2) 332 self.index_model = ((self.qmin <= self.radius)&(self.radius<= self.qmax)) 333 if qmax != None: 334 self.qmax = qmax 335 self.radius = numpy.sqrt(self.qx_data**2 + self.qy_data**2) 336 self.index_model = ((self.qmin <= self.radius)&\ 337 (self.radius <= self.qmax)) 333 338 self.index_model = (self.index_model) &(self.mask) 334 339 self.index_model = (self.index_model) & (numpy.isfinite(self.data)) … … 352 357 gn = fn.get_value() 353 358 else: 354 gn = fn([self.qx_data[self.index_model],self.qy_data[self.index_model]]) 359 gn = fn([self.qx_data[self.index_model], 360 self.qy_data[self.index_model]]) 355 361 # use only the data point within ROI range 356 res=(self.data[self.index_model] - gn)/self.res_err_data[self.index_model] 362 res = (self.data[self.index_model] - gn)/\ 363 self.res_err_data[self.index_model] 357 364 return res 358 365 … … 418 425 #import thread 419 426 self.model.setParams(self.paramlist,params) 420 self.res = self.data.residuals(self.model.eval)427 self.res = self.data.residuals(self.model.eval) 421 428 if self.fitresult is not None and self.handler is not None: 422 429 self.fitresult.set_model(model=self.model) … … 450 457 :param listdata: list of data 451 458 452 :return Data: Data is wrapper class for sans plottable. it is created with all parameters453 459 :return Data: Data is wrapper class for sans plottable. 460 it is created with all parameters of data concatenanted 454 461 455 462 :raise: if listdata is empty will return None 456 :raise: if data in listdata don't contain dy field , will create an error457 463 :raise: if data in listdata don't contain dy field , 464 will create an error during fitting 458 465 459 466 """ … … 467 474 #return listdata[0] 468 475 469 if listdata ==[]:476 if listdata == []: 470 477 raise ValueError, " data list missing" 471 478 else: 472 xtemp =[]473 ytemp =[]474 dytemp =[]475 self.mini =None476 self.maxi =None479 xtemp = [] 480 ytemp = [] 481 dytemp = [] 482 self.mini = None 483 self.maxi = None 477 484 478 485 for item in listdata: 479 data =item.data480 mini, maxi=data.getFitRange()481 if self.mini ==None and self.maxi==None:482 self.mini =mini483 self.maxi =maxi486 data = item.data 487 mini, maxi = data.getFitRange() 488 if self.mini == None and self.maxi == None: 489 self.mini = mini 490 self.maxi = maxi 484 491 else: 485 492 if mini < self.mini: 486 self.mini =mini493 self.mini = mini 487 494 if self.maxi < maxi: 488 self.maxi=maxi 489 490 495 self.maxi = maxi 491 496 for i in range(len(data.x)): 492 497 xtemp.append(data.x[i]) 493 498 ytemp.append(data.y[i]) 494 if data.dy is not None and len(data.dy) ==len(data.y):499 if data.dy is not None and len(data.dy) == len(data.y): 495 500 dytemp.append(data.dy[i]) 496 501 else: 497 raise RuntimeError, "Fit._concatenateData: y-errors missing" 498 data= Data(x=xtemp,y=ytemp,dy=dytemp) 502 msg = "Fit._concatenateData: y-errors missing" 503 raise RuntimeError, msg 504 data = Data(x=xtemp, y=ytemp, dy=dytemp) 499 505 data.setFitRange(self.mini, self.maxi) 500 506 return data … … 525 531 raise ValueError, "AbstractFitEngine: Need to set model to fit" 526 532 527 new_model = model533 new_model = model 528 534 if not issubclass(model.__class__, Model): 529 new_model = Model(model)530 531 if len(constraints) >0:535 new_model = Model(model) 536 537 if len(constraints) > 0: 532 538 for constraint in constraints: 533 539 name, value = constraint 534 540 try: 535 new_model.parameterset[ str(name)].set( str(value))541 new_model.parameterset[str(name)].set(str(value)) 536 542 except: 537 msg = "Fit Engine: Error occurs when setting the constraint"543 msg = "Fit Engine: Error occurs when setting the constraint" 538 544 msg += " %s for parameter %s "%(value, name) 539 545 raise ValueError, msg 540 546 541 if len(pars) > 0:542 temp =[]547 if len(pars) > 0: 548 temp = [] 543 549 for item in pars: 544 550 if item in new_model.model.getParamList(): … … 547 553 else: 548 554 549 msg = "wrong parameter %s used"%str(item) 550 msg += "to set model %s. Choose"%str(new_model.model.name) 551 msg += "parameter name within %s"%str(new_model.model.getParamList()) 552 raise ValueError,msg 555 msg = "wrong parameter %s used" % str(item) 556 msg += "to set model %s. Choose" % str(new_model.model.name) 557 msg += "parameter name within %s" % \ 558 str(new_model.model.getParamList()) 559 raise ValueError, msg 553 560 554 561 #A fitArrange is already created but contains dList only at Uid 555 562 if self.fitArrangeDict.has_key(Uid): 556 563 self.fitArrangeDict[Uid].set_model(new_model) 557 self.fitArrangeDict[Uid].pars = pars564 self.fitArrangeDict[Uid].pars = pars 558 565 else: 559 566 #no fitArrange object has been create with this Uid 560 567 fitproblem = FitArrange() 561 568 fitproblem.set_model(new_model) 562 fitproblem.pars = pars569 fitproblem.pars = pars 563 570 self.fitArrangeDict[Uid] = fitproblem 564 571 … … 566 573 raise ValueError, "park_integration:missing parameters" 567 574 568 def set_data(self, data,Uid,smearer=None,qmin=None,qmax=None):575 def set_data(self, data, Uid, smearer=None, qmin=None, qmax=None): 569 576 """ 570 577 Receives plottable, creates a list of data to fit,set data … … 576 583 577 584 """ 578 if data.__class__.__name__=='Data2D': 579 fitdata=FitData2D(sans_data2d=data, data=data.data, err_data= data.err_data) 585 if data.__class__.__name__ == 'Data2D': 586 fitdata = FitData2D(sans_data2d=data, data=data.data, 587 err_data=data.err_data) 580 588 else: 581 fitdata=FitData1D(x=data.x, y=data.y , dx= data.dx,dy=data.dy,smearer=smearer) 589 fitdata = FitData1D(x=data.x, y=data.y , 590 dx=data.dx, dy=data.dy, smearer=smearer) 582 591 583 fitdata.setFitRange(qmin=qmin, qmax=qmax)592 fitdata.setFitRange(qmin=qmin, qmax=qmax) 584 593 #A fitArrange is already created but contains model only at Uid 585 594 if self.fitArrangeDict.has_key(Uid): … … 587 596 else: 588 597 #no fitArrange object has been create with this Uid 589 fitproblem = FitArrange()598 fitproblem = FitArrange() 590 599 fitproblem.add_data(fitdata) 591 self.fitArrangeDict[Uid] =fitproblem600 self.fitArrangeDict[Uid] = fitproblem 592 601 593 def get_model(self, Uid):602 def get_model(self, Uid): 594 603 """ 595 604 … … 605 614 return None 606 615 607 def remove_Fit_Problem(self, Uid):616 def remove_Fit_Problem(self, Uid): 608 617 """remove fitarrange in Uid""" 609 618 if self.fitArrangeDict.has_key(Uid): 610 619 del self.fitArrangeDict[Uid] 611 620 612 def select_problem_for_fit(self, Uid,value):621 def select_problem_for_fit(self, Uid, value): 613 622 """ 614 623 select a couple of model and data at the Uid position in dictionary … … 620 629 """ 621 630 if self.fitArrangeDict.has_key(Uid): 622 self.fitArrangeDict[Uid].set_to_fit( 631 self.fitArrangeDict[Uid].set_to_fit(value) 623 632 624 def get_problem_to_fit(self, Uid):633 def get_problem_to_fit(self, Uid): 625 634 """ 626 635 return the self.selected value of the fit problem of Uid … … 644 653 """ 645 654 self.model = None 646 self.dList = []647 self.pars =[]655 self.dList = [] 656 self.pars = [] 648 657 #self.selected is zero when this fit problem is not schedule to fit 649 658 #self.selected is 1 when schedule to fit 650 659 self.selected = 0 651 660 652 def set_model(self, model):661 def set_model(self, model): 653 662 """ 654 663 set_model save a copy of the model … … 659 668 self.model = model 660 669 661 def add_data(self, data):670 def add_data(self, data): 662 671 """ 663 672 add_data fill a self.dList with data to fit … … 686 695 return self.dList[0] 687 696 688 def remove_data(self, data):697 def remove_data(self, data): 689 698 """ 690 699 Remove one element from the list … … 703 712 704 713 """ 705 self.selected = value714 self.selected = value 706 715 707 716 def get_to_fit(self): -
park_integration/Fitting.py
raa36f96 r89f3b66 5 5 """ 6 6 7 from scipy import optimize7 #from scipy import optimize 8 8 from ScipyFitting import ScipyFit 9 9 from ParkFitting import ParkFit … … 33 33 self.set_engine(engine) 34 34 35 def set_engine(self, word):35 def set_engine(self, word): 36 36 """ 37 37 Select the type of Fit … … 43 43 44 44 """ 45 if word =="scipy":46 self._engine =ScipyFit()47 elif word =="park":45 if word == "scipy": 46 self._engine = ScipyFit() 47 elif word == "park": 48 48 self._engine=ParkFit() 49 49 else: … … 53 53 """Perform the fit """ 54 54 try: 55 return self._engine.fit(q,handler, curr_thread= 55 return self._engine.fit(q,handler, curr_thread=curr_thread) 56 56 except: 57 57 raise 58 58 59 def set_model(self, model,Uid,pars=[],constraints=[]):59 def set_model(self, model, Uid, pars=[], constraints=[]): 60 60 """ 61 61 store a model model to fit at the position Uid of the fit engine 62 62 """ 63 self._engine.set_model(model, Uid,pars,constraints)63 self._engine.set_model(model, Uid, pars, constraints) 64 64 65 66 def set_data(self,data,Uid,smearer=None,qmin=None, qmax=None): 65 def set_data(self, data, Uid, smearer=None, qmin=None, qmax=None): 67 66 """ 68 67 Store data to fit at the psotion Uid of the fit engine … … 74 73 75 74 """ 76 self._engine.set_data(data, Uid,smearer,qmin, qmax)75 self._engine.set_data(data, Uid, smearer, qmin, qmax) 77 76 78 79 def get_model(self,Uid): 77 def get_model(self, Uid): 80 78 """ return list of data""" 81 79 self._engine.get_model(Uid) 82 80 83 81 84 def remove_Fit_Problem(self, Uid):82 def remove_Fit_Problem(self, Uid): 85 83 """remove fitarrange in Uid""" 86 84 self._engine.remove_Fit_Problem(Uid) 87 85 88 89 def select_problem_for_fit(self,Uid,value): 86 def select_problem_for_fit(self, Uid, value): 90 87 """ 91 88 select a couple of model and data at the Uid position in dictionary … … 95 92 can only have the value one or zero 96 93 """ 97 self._engine.select_problem_for_fit(Uid, value)94 self._engine.select_problem_for_fit(Uid, value) 98 95 99 100 def get_problem_to_fit(self,Uid): 96 def get_problem_to_fit(self, Uid): 101 97 """ 102 98 return the self.selected value of the fit problem of Uid -
park_integration/Loader.py
raa36f96 r89f3b66 1 1 # class Loader to load any king of file 2 import wx 3 import string,numpy 2 #import wx 3 #import string 4 import numpy 4 5 class Load: 5 6 """ … … 7 8 """ 8 9 9 def _init_(self, x=None,y=None,dx=None,dy=None):10 def _init_(self, x=None, y=None, dx=None, dy=None): 10 11 # variable to store loaded values 11 12 self.x = x … … 15 16 self.filename = None 16 17 17 def set_filename(self, path=None):18 def set_filename(self, path=None): 18 19 """ 19 20 Store path into a variable.If the user doesn't give a path as a parameter a pop-up … … 25 26 self.filename = path 26 27 27 28 28 def get_filename(self): 29 29 """ return the file's path""" … … 33 33 """ Store the values loaded from file in local variables""" 34 34 if not self.filename == None: 35 input_f = open(self.filename, 'r')35 input_f = open(self.filename, 'r') 36 36 buff = input_f.read() 37 37 lines = buff.split('\n') 38 self.x =[]39 self.y =[]38 self.x = [] 39 self.y = [] 40 40 self.dx = [] 41 self.dy =[]41 self.dy = [] 42 42 for line in lines: 43 43 try: … … 64 64 def get_values(self): 65 65 """ Return x, y, dx, dy""" 66 return self.x, self.y,self.dx,self.dy66 return self.x, self.y, self.dx, self.dy 67 67 68 def load_data(self, data):68 def load_data(self, data): 69 69 """ Return plottable""" 70 70 #load data … … 72 72 data.y = self.y 73 73 data.dx = self.dx 74 data.dy = self.dy74 data.dy = self.dy 75 75 #Load its View class 76 76 #plottable.reset_view() … … 78 78 79 79 if __name__ == "__main__": 80 load = Load()80 load = Load() 81 81 load.set_filename("testdata_line.txt") 82 82 print load.get_filename() -
park_integration/ParkFitting.py
raa36f96 r89f3b66 7 7 simple fit with park optimizer. 8 8 """ 9 import time10 import numpy9 #import time 10 #import numpy 11 11 import park 12 from park import fit, fitresult12 from park import fit, fitresult 13 13 from park import assembly 14 14 from park.fitmc import FitSimplex, FitMC … … 52 52 with Uid as keys 53 53 """ 54 self.fitArrangeDict ={}55 self.paramList =[]54 self.fitArrangeDict = {} 55 self.paramList = [] 56 56 57 57 def createAssembly(self): … … 61 61 create an assembly self.problem= park.Assembly([(parkmodel,parkdata)]) 62 62 """ 63 mylist =[]64 listmodel =[]65 i =066 fitproblems =[]67 for id 68 if fproblem.get_to_fit() ==1:63 mylist = [] 64 listmodel = [] 65 i = 0 66 fitproblems = [] 67 for id,fproblem in self.fitArrangeDict.iteritems(): 68 if fproblem.get_to_fit() == 1: 69 69 fitproblems.append(fproblem) 70 71 if len(fitproblems)==0 : 70 if len(fitproblems) == 0: 72 71 raise RuntimeError, "No Assembly scheduled for Park fitting." 73 72 return … … 76 75 for p in parkmodel.parameterset: 77 76 ## does not allow status change for constraint parameters 78 if p.status != 'computed':77 if p.status != 'computed': 79 78 if p._getname()in item.pars: 80 79 ## make parameters selected for fit will be between boundaries 81 p.set( p.range ) 82 80 p.set(p.range) 83 81 else: 84 p.status= 'fixed' 85 86 i+=1 87 Ldata=item.get_data() 82 p.status = 'fixed' 83 i += 1 84 Ldata = item.get_data() 88 85 #parkdata=self._concatenateData(Ldata) 89 parkdata =Ldata90 fitness =(parkmodel,parkdata)86 parkdata = Ldata 87 fitness = (parkmodel, parkdata) 91 88 mylist.append(fitness) 89 self.problem = park.Assembly(mylist) 92 90 93 self.problem = park.Assembly(mylist) 94 95 def fit(self,q=None,handler=None, curr_thread= None): 91 def fit(self, q=None, handler=None, curr_thread=None): 96 92 """ 97 93 Performs fit with park.fit module.It can perform fit with one model … … 112 108 """ 113 109 self.createAssembly() 114 115 110 localfit = FitSimplex() 116 111 localfit.ftol = 1e-8 … … 119 114 fitter = FitMC(localfit=localfit, start_points=1) 120 115 if handler == None: 121 handler= fitresult.ConsoleUpdate(improvement_delta=0.1) 122 123 116 handler = fitresult.ConsoleUpdate(improvement_delta=0.1) 124 117 result = fit.fit(self.problem, 125 118 fitter=fitter, 126 handler= 119 handler=handler) 127 120 self.problem.all_results(result) 128 if result != None:129 if q != None:121 if result != None: 122 if q != None: 130 123 q.put(result) 131 124 return q -
park_integration/ScipyFitting.py
raa36f96 r89f3b66 10 10 from scipy import optimize 11 11 12 from AbstractFitEngine import FitEngine, SansAssembly, FitAbort12 from AbstractFitEngine import FitEngine, SansAssembly, FitAbort 13 13 14 14 class fitresult(object): … … 17 17 """ 18 18 def __init__(self, model=None, paramList=None): 19 self.calls 20 self.fitness 21 self.chisqr 22 self.pvec 23 self.cov 24 self.info 25 self.mesg 26 self.success 27 self.stderr 19 self.calls = None 20 self.fitness = None 21 self.chisqr = None 22 self.pvec = None 23 self.cov = None 24 self.info = None 25 self.mesg = None 26 self.success = None 27 self.stderr = None 28 28 self.parameters = None 29 29 self.model = model … … 48 48 49 49 result_param = zip(xrange(n), self.model.parameterset) 50 L = ["P%-3d %s......|.....%s"%(p[0], p[1], p[1].value) for p in result_param if p[1].name in self.paramList ] 51 L.append("=== goodness of fit: %s"%(str(self.fitness))) 50 L = ["P%-3d %s......|.....%s"%(p[0], p[1], p[1].value)\ 51 for p in result_param if p[1].name in self.paramList] 52 L.append("=== goodness of fit: %s" % (str(self.fitness))) 52 53 return "\n".join(L) 53 54 … … 89 90 with Uid as keys 90 91 """ 91 self.fitArrangeDict ={}92 self.paramList =[]92 self.fitArrangeDict = {} 93 self.paramList = [] 93 94 #def fit(self, *args, **kw): 94 95 # return profile(self._fit, *args, **kw) … … 97 98 """ 98 99 """ 99 fitproblem =[]100 for id ,fproblem in self.fitArrangeDict.iteritems():101 if fproblem.get_to_fit() ==1:100 fitproblem = [] 101 for id, fproblem in self.fitArrangeDict.iteritems(): 102 if fproblem.get_to_fit() == 1: 102 103 fitproblem.append(fproblem) 103 if len(fitproblem) >1 :104 if len(fitproblem) > 1 : 104 105 msg = "Scipy can't fit more than a single fit problem at a time." 105 106 raise RuntimeError, msg 106 107 return 107 elif len(fitproblem) ==0 :108 elif len(fitproblem) == 0 : 108 109 raise RuntimeError, "No Assembly scheduled for Scipy fitting." 109 110 return 110 111 111 listdata =[]112 listdata = [] 112 113 model = fitproblem[0].get_model() 113 114 listdata = fitproblem[0].get_data() 114 115 # Concatenate dList set (contains one or more data)before fitting 115 116 data = listdata 116 self.curr_thread = curr_thread117 self.curr_thread = curr_thread 117 118 result = fitresult(model=model, paramList=self.paramList) 118 119 if handler is not None: … … 120 121 #try: 121 122 functor = SansAssembly(self.paramList, model, data, handler=handler, 122 fitresult=result,curr_thread= self.curr_thread)123 fitresult=result, curr_thread= self.curr_thread) 123 124 124 125 … … 146 147 return result 147 148 else: 148 raise ValueError, "SVD did not converge" +str(success)149 raise ValueError, "SVD did not converge" + str(success) 149 150 150 151 -
park_integration/temp_code_exchange.py
raa36f96 r89f3b66 8 8 # This code belongs in AbstractFitEngine 9 9 class FitData1D: 10 def setFitRange(self, qmin=None,qmax=None):10 def setFitRange(self, qmin=None, qmax=None): 11 11 """ 12 12 Change the fit range. … … 18 18 # Skip Q=0 point, (especially for y(q=0)=None at x[0]). 19 19 #ToDo: Fix this. 20 if qmin ==0.0 and not numpy.isfinite(self.data.y[qmin]):20 if qmin == 0.0 and not numpy.isfinite(self.data.y[qmin]): 21 21 self.qmin = min(self.data.x[self.data.x!=0]) 22 elif qmin !=None:22 elif qmin != None: 23 23 self.qmin = qmin 24 24 25 if qmax != None:25 if qmax != None: 26 26 self.qmax = qmax 27 27 … … 40 40 # Take 3 sigmas as the offset between smeared and unsmeared space. 41 41 try: 42 offset = 3.0 *max(self.smearer.width)42 offset = 3.0 * max(self.smearer.width) 43 43 self._qmin_unsmeared = max([min(self.data.x), self.qmin-offset]) 44 44 self._qmax_unsmeared = min([max(self.data.x), self.qmax+offset]) … … 64 64 65 65 """ 66 x, y = [numpy.asarray(v) for v in (self.x,self.y)]67 if self.dy == None or self.dy==[]:68 dy = numpy.zeros(len(y))66 x, y = [numpy.asarray(v) for v in (self.x, self.y)] 67 if self.dy == None or self.dy == []: 68 dy = numpy.zeros(len(y)) 69 69 else: 70 dy= numpy.asarray(dy) 71 72 dy[dy==0]=1 73 idx_unsmeared = (x>=self._qmin_unsmeared) & (x <= self._qmax_unsmeared) 74 70 dy = numpy.asarray(dy) 71 dy[dy == 0] = 1 72 idx_unsmeared = (x >= self._qmin_unsmeared) \ 73 & (x <= self._qmax_unsmeared) 75 74 # Compute theory data f(x) 76 idx=[] 77 tempy=[] 78 tempfx=[] 79 tempdy=[] 80 75 idx = [] 76 tempy = [] 77 tempfx = [] 78 tempdy = [] 81 79 _first_bin = None 82 80 for i_x in range(len(x)): 83 81 try: 84 if idx_unsmeared[i_x] ==True:82 if idx_unsmeared[i_x] == True: 85 83 if _first_bin is None: 86 84 _first_bin = i_x 87 85 88 value= fn(x[i_x]) 89 idx.append(x[i_x]>=self.qmin and x[i_x]<=self.qmax) 86 value = fn(x[i_x]) 87 idx.append(x[i_x] >= self.qmin and \ 88 x[i_x] <= self.qmax) 90 89 tempfx.append( value) 91 90 tempy.append(y[i_x]) … … 101 100 102 101 newy = numpy.asarray(tempy) 103 newfx = numpy.asarray(tempfx)104 newdy = numpy.asarray(tempdy)102 newfx = numpy.asarray(tempfx) 103 newdy = numpy.asarray(tempdy) 105 104 106 105 ## Sanity check 107 if numpy.size(newdy) != numpy.size(newfx):108 raise RuntimeError, "FitData1D: invalid error array %d <> %d" % (numpy.size(newdy), numpy.size(newfx))109 110 return (newy[idx]-newfx[idx])/newdy[idx]111 106 if numpy.size(newdy) != numpy.size(newfx): 107 msg = "FitData1D: invalid error " 108 msg += "array %d <> %d" % (numpy.size(newdy), numpy.size(newfx)) 109 raise RuntimeError, msg 110 return (newy[idx] - newfx[idx]) / newdy[idx] 112 111 113 112 def residuals_alt(self, fn): … … 137 136 # Make sure the arrays are numpy arrays, which are 138 137 # expected by the fitter. 139 x, y = [numpy.asarray(v) for v in (self.x,self.y)]140 if self.dy == None or self.dy==[]:141 dy = numpy.zeros(len(y))138 x, y = [numpy.asarray(v) for v in (self.x, self.y)] 139 if self.dy == None or self.dy == []: 140 dy = numpy.zeros(len(y)) 142 141 else: 143 dy= numpy.asarray(dy) 144 145 dy[dy==0]=1 146 idx = (x>=self.qmin) & (x <= self.qmax) 147 idx_unsmeared = (x>=self._qmin_unsmeared) & (x <= self._qmax_unsmeared) 148 142 dy = numpy.asarray(dy) 143 dy[dy ==0 ] = 1 144 idx = (x >= self.qmin) & (x <= self.qmax) 145 idx_unsmeared = (x >= self._qmin_unsmeared) \ 146 & (x <= self._qmax_unsmeared) 149 147 # Compute theory data f(x) 150 fx= numpy.zeros(len(x)) 151 148 fx = numpy.zeros(len(x)) 152 149 # First and last bins of the array, corresponding to 153 150 # the Q range to be smeared … … 156 153 for i_x in range(len(x)): 157 154 try: 158 if idx_unsmeared[i_x] ==True:155 if idx_unsmeared[i_x] == True: 159 156 if _first_bin is None: 160 157 _first_bin = i_x 161 158 else: 162 159 _last_bin = i_x 163 164 160 value = fn(x[i_x]) 165 161 fx[i_x] = value … … 168 164 ## Should properly log the error 169 165 pass 170 171 166 # Smear theory data 172 167 if self.smearer is not None: 173 168 fx = self.smearer(fx, _first_bin, _last_bin) 174 175 169 # Sanity check 176 if numpy.size(dy)!= numpy.size(fx): 177 raise RuntimeError, "FitData1D: invalid error array %d <> %d" % (numpy.size(dy), numpy.size(fx)) 178 170 if numpy.size(dy) != numpy.size(fx): 171 msg = "FitData1D: invalid error array" 172 msg += " %d <> %d" % (numpy.size(dy), numpy.size(fx)) 173 174 raise RuntimeError, msg 179 175 # Return the residuals for the smeared (observed) Q range 180 return (y[idx] -fx[idx])/dy[idx]176 return (y[idx] - fx[idx]) / dy[idx] 181 177 182 178 # The following code belongs in DataLoader.qsmearing … … 202 198 """ 203 199 # Sanity check 204 if len(iq)+first_bin > self.nbins: 205 raise RuntimeError, "Invalid I(q) vector: inconsistent array length %s > %s" % (str(len(iq)+first_bin), str(self.nbins)) 200 if len(iq) + first_bin > self.nbins: 201 msg = "Invalid I(q) vector: inconsistent array length " 202 msg += " %s > %s" % (str(len(iq) + first_bin), str(self.nbins)) 203 raise RuntimeError, msg 206 204 207 205 if self._weights == None: … … 210 208 iq_smeared = numpy.zeros(len(iq)) 211 209 # Loop over q-values 212 idwb =[]210 idwb = [] 213 211 214 212 for q_i in range(len(iq)): … … 216 214 counts = 0.0 217 215 for i in range(len(iq)): 218 if iq[i]==0 or self._weights[q_i+first_bin][i+first_bin]==0: 216 if iq[i] == 0 or \ 217 self._weights[q_i+first_bin][i+first_bin] == 0: 219 218 continue 220 219 else: 221 220 sum += iq[i] * self._weights[q_i+first_bin][i+first_bin] 222 221 counts += self._weights[q_i+first_bin][i+first_bin] 223 224 222 if counts == 0: 225 223 iq_smeared[q_i] = 0 226 224 else: 227 225 iq_smeared[q_i] = sum/counts 228 return iq_smeared 226 return iq_smeared 227 228
Note: See TracChangeset
for help on using the changeset viewer.