Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/python/asapfitter.py

    r1938 r1826  
    11import _asap
    22from asap.parameters import rcParams
    3 from asap.logging import asaplog, asaplog_post_dec
     3from asap.logging import asaplog, print_log, print_log_dec
    44from asap.utils import _n_bools, mask_and
    55
     
    99    The fitting class for ASAP.
    1010    """
     11
    1112    def __init__(self):
    1213        """
     
    4849        return
    4950
    50     @asaplog_post_dec
    5151    def set_scan(self, thescan=None, mask=None):
    5252        """
     
    5858        if not thescan:
    5959            msg = "Please give a correct scan"
    60             raise TypeError(msg)
     60            if rcParams['verbose']:
     61                #print msg
     62                asaplog.push(msg)
     63                print_log('ERROR')
     64                return
     65            else:
     66                raise TypeError(msg)
    6167        self.fitted = False
    6268        self.data = thescan
     
    6874        return
    6975
    70     @asaplog_post_dec
    7176    def set_function(self, **kwargs):
    7277        """
     
    8792        if kwargs.has_key('poly'):
    8893            self.fitfunc = 'poly'
    89             self.fitfuncs = ['poly']
    9094            n = kwargs.get('poly')
    91             self.components = [n+1]
     95            self.components = [n]
    9296            self.uselinear = False
    9397        elif kwargs.has_key('lpoly'):
    9498            self.fitfunc = 'poly'
    95             self.fitfuncs = ['lpoly']
    9699            n = kwargs.get('lpoly')
    97             self.components = [n+1]
     100            self.components = [n]
    98101            self.uselinear = True
    99102        elif kwargs.has_key('gauss'):
     
    111114        else:
    112115            msg = "Invalid function type."
    113             raise TypeError(msg)
     116            if rcParams['verbose']:
     117                #print msg
     118                asaplog.push(msg)
     119                print_log('ERROR')
     120                return
     121            else:
     122                raise TypeError(msg)
    114123
    115124        self.fitter.setexpression(self.fitfunc,n)
     
    117126        return
    118127
    119     @asaplog_post_dec
     128    @print_log_dec
    120129    def fit(self, row=0, estimate=False):
    121130        """
     
    137146               or self.fitfunc is None:
    138147            msg = "Fitter not yet initialised. Please set data & fit function"
    139             raise RuntimeError(msg)
     148            if rcParams['verbose']:
     149                #print msg
     150                asaplog.push(msg)
     151                print_log('ERROR')
     152                return
     153            else:
     154                raise RuntimeError(msg)
    140155
    141156        else:
     
    157172            if len(ps) == 0 or estimate:
    158173                self.fitter.estimate()
    159         fxdpar = list(self.fitter.getfixedparameters())
    160         if len(fxdpar) and fxdpar.count(0) == 0:
    161              raise RuntimeError,"No point fitting, if all parameters are fixed."
    162         if self.uselinear:
    163             converged = self.fitter.lfit()
    164         else:
    165             converged = self.fitter.fit()
    166         if not converged:
    167             raise RuntimeError,"Fit didn't converge."
     174        try:
     175            fxdpar = list(self.fitter.getfixedparameters())
     176            if len(fxdpar) and fxdpar.count(0) == 0:
     177                 raise RuntimeError,"No point fitting, if all parameters are fixed."
     178            if self.uselinear:
     179                converged = self.fitter.lfit()
     180            else:
     181                converged = self.fitter.fit()
     182            if not converged:
     183                raise RuntimeError,"Fit didn't converge."
     184        except RuntimeError, msg:
     185            if rcParams['verbose']:
     186                #print msg
     187                print_log()
     188                asaplog.push(str(msg))
     189                print_log('ERROR')
     190            else:
     191                raise
    168192        self._fittedrow = row
    169193        self.fitted = True
     194        print_log()
    170195        return
    171196
     
    196221                self.data._addfit(fit,self._fittedrow)
    197222
    198     @asaplog_post_dec
     223    @print_log_dec
    199224    def set_parameters(self,*args,**kwargs):
    200225        """
     
    204229              fixed:     a vector of which parameters are to be held fixed
    205230                         (default is none)
    206               component: in case of multiple gaussians/lorentzians,
    207                          the index of the component
     231              component: in case of multiple gaussians, the index of the
     232                         component
    208233        """
    209234        component = None
     
    219244        if self.fitfunc is None:
    220245            msg = "Please specify a fitting function first."
    221             raise RuntimeError(msg)
     246            if rcParams['verbose']:
     247                #print msg
     248                asaplog.push(msg)
     249                print_log('ERROR')
     250                return
     251            else:
     252                raise RuntimeError(msg)
    222253        if (self.fitfunc == "gauss" or self.fitfunc == 'lorentz') and component is not None:
    223254            if not self.fitted and sum(self.fitter.getparameters()) == 0:
     
    235266        if fixed is not None:
    236267            self.fitter.setfixedparameters(fixed)
     268        print_log()
    237269        return
    238270
    239     @asaplog_post_dec
    240271    def set_gauss_parameters(self, peak, centre, fwhm,
    241272                             peakfixed=0, centrefixed=0,
     
    257288        if self.fitfunc != "gauss":
    258289            msg = "Function only operates on Gaussian components."
    259             raise ValueError(msg)
     290            if rcParams['verbose']:
     291                #print msg
     292                asaplog.push(msg)
     293                print_log('ERROR')
     294                return
     295            else:
     296                raise ValueError(msg)
    260297        if 0 <= component < len(self.components):
    261298            d = {'params':[peak, centre, fwhm],
     
    264301        else:
    265302            msg = "Please select a valid  component."
    266             raise ValueError(msg)
    267 
    268     @asaplog_post_dec
     303            if rcParams['verbose']:
     304                #print msg
     305                asaplog.push(msg)
     306                print_log('ERROR')
     307                return
     308            else:
     309                raise ValueError(msg)
     310
    269311    def set_lorentz_parameters(self, peak, centre, fwhm,
    270312                             peakfixed=0, centrefixed=0,
     
    274316        Set the Parameters of a 'Lorentzian' component, set with set_function.
    275317        Parameters:
    276             peak, centre, fwhm:  The lorentzian parameters
     318            peak, centre, fwhm:  The gaussian parameters
    277319            peakfixed,
    278320            centrefixed,
     
    286328        if self.fitfunc != "lorentz":
    287329            msg = "Function only operates on Lorentzian components."
    288             raise ValueError(msg)
     330            if rcParams['verbose']:
     331                #print msg
     332                asaplog.push(msg)
     333                print_log('ERROR')
     334                return
     335            else:
     336                raise ValueError(msg)
    289337        if 0 <= component < len(self.components):
    290338            d = {'params':[peak, centre, fwhm],
     
    293341        else:
    294342            msg = "Please select a valid  component."
    295             raise ValueError(msg)
     343            if rcParams['verbose']:
     344                #print msg
     345                asaplog.push(msg)
     346                print_log('ERROR')
     347                return
     348            else:
     349                raise ValueError(msg)
    296350
    297351    def get_area(self, component=None):
     
    324378            return sum(areas)
    325379
    326     @asaplog_post_dec
    327380    def get_errors(self, component=None):
    328381        """
     
    334387        if not self.fitted:
    335388            msg = "Not yet fitted."
    336             raise RuntimeError(msg)
     389            if rcParams['verbose']:
     390                #print msg
     391                asaplog.push(msg)
     392                print_log('ERROR')
     393                return
     394            else:
     395                raise RuntimeError(msg)
    337396        errs = list(self.fitter.geterrors())
    338397        cerrs = errs
     
    344403        return cerrs
    345404
    346 
    347     @asaplog_post_dec
    348405    def get_parameters(self, component=None, errors=False):
    349406        """
     
    355412        if not self.fitted:
    356413            msg = "Not yet fitted."
    357             raise RuntimeError(msg)
     414            if rcParams['verbose']:
     415                #print msg
     416                asaplog.push(msg)
     417                print_log('ERROR')
     418                return
     419            else:
     420                raise RuntimeError(msg)
    358421        pars = list(self.fitter.getparameters())
    359422        fixed = list(self.fitter.getfixedparameters())
     
    381444                  area += [a for i in range(3)]
    382445        fpars = self._format_pars(cpars, cfixed, errors and cerrs, area)
    383         asaplog.push(fpars)
     446        if rcParams['verbose']:
     447            #print fpars
     448            asaplog.push(fpars)
     449            print_log()
    384450        return {'params':cpars, 'fixed':cfixed, 'formatted': fpars,
    385451                'errors':cerrs}
     
    415481        return out
    416482
    417 
    418     @asaplog_post_dec
    419483    def get_estimate(self):
    420484        """
     
    423487        pars = self.fitter.getestimate()
    424488        fixed = self.fitter.getfixedparameters()
    425         asaplog.push(self._format_pars(pars,fixed,None,None))
     489        if rcParams['verbose']:
     490            #print self._format_pars(pars,fixed,None)
     491            asaplog.push(self._format_pars(pars,fixed,None))
     492            print_log()
    426493        return pars
    427494
    428     @asaplog_post_dec
    429495    def get_residual(self):
    430496        """
     
    433499        if not self.fitted:
    434500            msg = "Not yet fitted."
    435             raise RuntimeError(msg)
     501            if rcParams['verbose']:
     502                #print msg
     503                asaplog.push(msg)
     504                print_log('ERROR')
     505                return
     506            else:
     507                raise RuntimeError(msg)
    436508        return self.fitter.getresidual()
    437509
    438     @asaplog_post_dec
    439510    def get_chi2(self):
    440511        """
     
    443514        if not self.fitted:
    444515            msg = "Not yet fitted."
    445             raise RuntimeError(msg)
     516            if rcParams['verbose']:
     517                #print msg
     518                asaplog.push(msg)
     519                print_log('ERROR')
     520                return
     521            else:
     522                raise RuntimeError(msg)
    446523        ch2 = self.fitter.getchi2()
    447         asaplog.push( 'Chi^2 = %3.3f' % (ch2) )
     524        if rcParams['verbose']:
     525            #print 'Chi^2 = %3.3f' % (ch2)
     526            asaplog.push( 'Chi^2 = %3.3f' % (ch2) )
     527            print_log()
    448528        return ch2
    449529
    450     @asaplog_post_dec
    451530    def get_fit(self):
    452531        """
     
    455534        if not self.fitted:
    456535            msg = "Not yet fitted."
    457             raise RuntimeError(msg)
     536            if rcParams['verbose']:
     537                #print msg
     538                asaplog.push(msg)
     539                print_log('ERROR')
     540                return
     541            else:
     542                raise RuntimeError(msg)
    458543        return self.fitter.getfit()
    459544
    460     @asaplog_post_dec
     545    @print_log_dec
    461546    def commit(self):
    462547        """
     
    465550        if not self.fitted:
    466551            msg = "Not yet fitted."
    467             raise RuntimeError(msg)
     552            if rcParams['verbose']:
     553                #print msg
     554                asaplog.push(msg)
     555                print_log('ERROR')
     556                return
     557            else:
     558                raise RuntimeError(msg)
    468559        from asap import scantable
    469560        if not isinstance(self.data, scantable):
    470561            msg = "Not a scantable"
    471             raise TypeError(msg)
     562            if rcParams['verbose']:
     563                #print msg
     564                asaplog.push(msg)
     565                print_log('ERROR')
     566                return
     567            else:
     568                raise TypeError(msg)
    472569        scan = self.data.copy()
    473570        scan._setspectrum(self.fitter.getresidual())
     571        print_log()
    474572        return scan
    475573
    476     @asaplog_post_dec
     574    @print_log_dec
    477575    def plot(self, residual=False, components=None, plotparms=False,
    478576             filename=None):
     
    573671        if (not rcParams['plotter.gui']):
    574672            self._p.save(filename)
    575 
    576     @asaplog_post_dec
     673        print_log()
     674
     675    @print_log_dec
    577676    def auto_fit(self, insitu=None, plot=False):
    578677        """
     
    584683        if not isinstance(self.data, scantable) :
    585684            msg = "Data is not a scantable"
    586             raise TypeError(msg)
     685            if rcParams['verbose']:
     686                #print msg
     687                asaplog.push(msg)
     688                print_log('ERROR')
     689                return
     690            else:
     691                raise TypeError(msg)
    587692        if insitu is None: insitu = rcParams['insitu']
    588693        if not insitu:
     
    620725            self._p.unmap()
    621726            self._p = None
     727        print_log()
    622728        return scan
Note: See TracChangeset for help on using the changeset viewer.