source: branches/polybatch/src/STFitter.cpp @ 1924

Last change on this file since 1924 was 1924, checked in by Malte Marquarding, 14 years ago

Ticket #206: use STFitEntry as return objetc instead of pointer wrnagling.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 11.7 KB
RevLine 
[91]1//#---------------------------------------------------------------------------
[890]2//# Fitter.cc: A Fitter class for spectra
[91]3//#--------------------------------------------------------------------------
4//# Copyright (C) 2004
[125]5//# ATNF
[91]6//#
7//# This program is free software; you can redistribute it and/or modify it
8//# under the terms of the GNU General Public License as published by the Free
9//# Software Foundation; either version 2 of the License, or (at your option)
10//# any later version.
11//#
12//# This program is distributed in the hope that it will be useful, but
13//# WITHOUT ANY WARRANTY; without even the implied warranty of
14//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
15//# Public License for more details.
16//#
17//# You should have received a copy of the GNU General Public License along
18//# with this program; if not, write to the Free Software Foundation, Inc.,
19//# 675 Massachusetts Ave, Cambridge, MA 02139, USA.
20//#
21//# Correspondence concerning this software should be addressed as follows:
22//#        Internet email: Malte.Marquarding@csiro.au
23//#        Postal address: Malte Marquarding,
24//#                        Australia Telescope National Facility,
25//#                        P.O. Box 76,
26//#                        Epping, NSW, 2121,
27//#                        AUSTRALIA
28//#
[891]29//# $Id: STFitter.cpp 1924 2010-09-14 02:17:16Z MalteMarquarding $
[91]30//#---------------------------------------------------------------------------
[125]31#include <casa/aips.h>
[91]32#include <casa/Arrays/ArrayMath.h>
33#include <casa/Arrays/ArrayLogical.h>
[1819]34#include <casa/Logging/LogIO.h>
[91]35#include <scimath/Fitting.h>
36#include <scimath/Fitting/LinearFit.h>
37#include <scimath/Functionals/CompiledFunction.h>
38#include <scimath/Functionals/CompoundFunction.h>
39#include <scimath/Functionals/Gaussian1D.h>
[1819]40#include "Lorentzian1D.h"
[91]41#include <scimath/Functionals/Polynomial.h>
42#include <scimath/Mathematics/AutoDiff.h>
43#include <scimath/Mathematics/AutoDiffMath.h>
44#include <scimath/Fitting/NonLinearFitLM.h>
45#include <components/SpectralComponents/SpectralEstimate.h>
46
[894]47#include "STFitter.h"
48
[91]49using namespace asap;
[125]50using namespace casa;
[91]51
[890]52Fitter::Fitter()
[91]53{
54}
55
[890]56Fitter::~Fitter()
[91]57{
[517]58  reset();
[91]59}
60
[890]61void Fitter::clear()
[91]62{
[517]63  for (uInt i=0;i< funcs_.nelements();++i) {
64    delete funcs_[i]; funcs_[i] = 0;
65  }
[612]66  funcs_.resize(0,True);
[517]67  parameters_.resize();
[1232]68  fixedpar_.resize();
[517]69  error_.resize();
70  thefit_.resize();
71  estimate_.resize();
72  chisquared_ = 0.0;
[91]73}
[517]74
[890]75void Fitter::reset()
[91]76{
[517]77  clear();
78  x_.resize();
79  y_.resize();
80  m_.resize();
[91]81}
82
83
[890]84bool Fitter::computeEstimate() {
[517]85  if (x_.nelements() == 0 || y_.nelements() == 0)
86    throw (AipsError("No x/y data specified."));
[91]87
[517]88  if (dynamic_cast<Gaussian1D<Float>* >(funcs_[0]) == 0)
89    return false;
90  uInt n = funcs_.nelements();
91  SpectralEstimate estimator(n);
92  estimator.setQ(5);
93  Int mn,mx;
94  mn = 0;
95  mx = m_.nelements()-1;
96  for (uInt i=0; i<m_.nelements();++i) {
97    if (m_[i]) {
98      mn = i;
99      break;
[108]100    }
[517]101  }
102  for (uInt j=m_.nelements()-1; j>=0;--j) {
103    if (m_[j]) {
104      mx = j;
105      break;
[108]106    }
[517]107  }
[1067]108  //mn = 0+x_.nelements()/10;
109  //mx = x_.nelements()-x_.nelements()/10;
[517]110  estimator.setRegion(mn,mx);
111  //estimator.setWindowing(True);
112  SpectralList listGauss = estimator.estimate(x_, y_);
113  parameters_.resize(n*3);
114  Gaussian1D<Float>* g = 0;
115  for (uInt i=0; i<n;i++) {
116    g = dynamic_cast<Gaussian1D<Float>* >(funcs_[i]);
117    if (g) {
118      (*g)[0] = listGauss[i].getAmpl();
119      (*g)[1] = listGauss[i].getCenter();
120      (*g)[2] = listGauss[i].getFWHM();
[91]121    }
[517]122  }
123  estimate_.resize();
124  listGauss.evaluate(estimate_,x_);
125  return true;
[91]126}
127
[890]128std::vector<float> Fitter::getEstimate() const
[91]129{
[517]130  if (estimate_.nelements() == 0)
131    throw (AipsError("No estimate set."));
132  std::vector<float> stlout;
133  estimate_.tovector(stlout);
134  return stlout;
[91]135}
136
137
[890]138bool Fitter::setExpression(const std::string& expr, int ncomp)
[91]139{
[517]140  clear();
141  if (expr == "gauss") {
142    if (ncomp < 1) throw (AipsError("Need at least one gaussian to fit."));
143    funcs_.resize(ncomp);
[1924]144    funcnames_.clear();
145    funccomponents_.clear();
[517]146    for (Int k=0; k<ncomp; ++k) {
147      funcs_[k] = new Gaussian1D<Float>();
[1924]148      funcnames_.push_back(expr);
149      funccomponents_.push_back(3);
[517]150    }
151  } else if (expr == "poly") {
152    funcs_.resize(1);
[1924]153    funcnames_.clear();
154    funccomponents_.clear();
[517]155    funcs_[0] = new Polynomial<Float>(ncomp);
[1924]156      funcnames_.push_back(expr);
157      funccomponents_.push_back(ncomp);
[1819]158  } else if (expr == "lorentz") {
159    if (ncomp < 1) throw (AipsError("Need at least one lorentzian to fit."));
160    funcs_.resize(ncomp);
[1924]161    funcnames_.clear();
162    funccomponents_.clear();
[1819]163    for (Int k=0; k<ncomp; ++k) {
164      funcs_[k] = new Lorentzian1D<Float>();
[1924]165      funcnames_.push_back(expr);
166      funccomponents_.push_back(3);
[1819]167    }
[517]168  } else {
[1819]169    //cerr << " compiled functions not yet implemented" << endl;
170    LogIO os( LogOrigin( "Fitter", "setExpression()", WHERE ) ) ;
171    os << LogIO::WARN << " compiled functions not yet implemented" << LogIO::POST;
[517]172    //funcs_.resize(1);
173    //funcs_[0] = new CompiledFunction<Float>();
174    //funcs_[0]->setFunction(String(expr));
175    return false;
176  }
177  return true;
[91]178}
179
[890]180bool Fitter::setData(std::vector<float> absc, std::vector<float> spec,
[91]181                       std::vector<bool> mask)
182{
183    x_.resize();
184    y_.resize();
185    m_.resize();
186    // convert std::vector to casa Vector
187    Vector<Float> tmpx(absc);
188    Vector<Float> tmpy(spec);
189    Vector<Bool> tmpm(mask);
190    AlwaysAssert(tmpx.nelements() == tmpy.nelements(), AipsError);
191    x_ = tmpx;
192    y_ = tmpy;
193    m_ = tmpm;
194    return true;
195}
196
[890]197std::vector<float> Fitter::getResidual() const
[91]198{
199    if (residual_.nelements() == 0)
200        throw (AipsError("Function not yet fitted."));
201    std::vector<float> stlout;
202    residual_.tovector(stlout);
203    return stlout;
204}
205
[890]206std::vector<float> Fitter::getFit() const
[91]207{
208    Vector<Float> out = thefit_;
209    std::vector<float> stlout;
210    out.tovector(stlout);
211    return stlout;
212
213}
214
[890]215std::vector<float> Fitter::getErrors() const
[91]216{
217    Vector<Float> out = error_;
218    std::vector<float> stlout;
219    out.tovector(stlout);
220    return stlout;
221}
222
[890]223bool Fitter::setParameters(std::vector<float> params)
[91]224{
225    Vector<Float> tmppar(params);
226    if (funcs_.nelements() == 0)
227        throw (AipsError("Function not yet set."));
228    if (parameters_.nelements() > 0 && tmppar.nelements() != parameters_.nelements())
229        throw (AipsError("Number of parameters inconsistent with function."));
[1232]230    if (parameters_.nelements() == 0) {
[91]231        parameters_.resize(tmppar.nelements());
[1232]232        if (tmppar.nelements() != fixedpar_.nelements()) {
233            fixedpar_.resize(tmppar.nelements());
234            fixedpar_ = False;
235        }
236    }
[91]237    if (dynamic_cast<Gaussian1D<Float>* >(funcs_[0]) != 0) {
238        uInt count = 0;
239        for (uInt j=0; j < funcs_.nelements(); ++j) {
240            for (uInt i=0; i < funcs_[j]->nparameters(); ++i) {
241                (funcs_[j]->parameters())[i] = tmppar[count];
242                parameters_[count] = tmppar[count];
243                ++count;
244            }
245        }
246    } else if (dynamic_cast<Polynomial<Float>* >(funcs_[0]) != 0) {
247        for (uInt i=0; i < funcs_[0]->nparameters(); ++i) {
248            parameters_[i] = tmppar[i];
249            (funcs_[0]->parameters())[i] =  tmppar[i];
250        }
[1819]251    } else if (dynamic_cast<Lorentzian1D<Float>* >(funcs_[0]) != 0) {
252        uInt count = 0;
253        for (uInt j=0; j < funcs_.nelements(); ++j) {
254            for (uInt i=0; i < funcs_[j]->nparameters(); ++i) {
255                (funcs_[j]->parameters())[i] = tmppar[count];
256                parameters_[count] = tmppar[count];
257                ++count;
258            }
259        }
[91]260    }
[1232]261    // reset
262    if (params.size() == 0) {
263        parameters_.resize();
264        fixedpar_.resize();
265    }
[91]266    return true;
267}
268
[890]269bool Fitter::setFixedParameters(std::vector<bool> fixed)
[91]270{
271    if (funcs_.nelements() == 0)
272        throw (AipsError("Function not yet set."));
[1232]273    if (fixedpar_.nelements() > 0 && fixed.size() != fixedpar_.nelements())
[91]274        throw (AipsError("Number of mask elements inconsistent with function."));
[1232]275    if (fixedpar_.nelements() == 0) {
276        fixedpar_.resize(parameters_.nelements());
277        fixedpar_ = False;
278    }
[91]279    if (dynamic_cast<Gaussian1D<Float>* >(funcs_[0]) != 0) {
280        uInt count = 0;
281        for (uInt j=0; j < funcs_.nelements(); ++j) {
282            for (uInt i=0; i < funcs_[j]->nparameters(); ++i) {
[1232]283                funcs_[j]->mask(i) = !fixed[count];
284                fixedpar_[count] = fixed[count];
[91]285                ++count;
286            }
287        }
288    } else if (dynamic_cast<Polynomial<Float>* >(funcs_[0]) != 0) {
289        for (uInt i=0; i < funcs_[0]->nparameters(); ++i) {
[1232]290            fixedpar_[i] = fixed[i];
291            funcs_[0]->mask(i) =  !fixed[i];
[91]292        }
[1819]293    } else if (dynamic_cast<Lorentzian1D<Float>* >(funcs_[0]) != 0) {
294      uInt count = 0;
295        for (uInt j=0; j < funcs_.nelements(); ++j) {
296            for (uInt i=0; i < funcs_[j]->nparameters(); ++i) {
297                funcs_[j]->mask(i) = !fixed[count];
298                fixedpar_[count] = fixed[count];
299                ++count;
300            }
301        }
[91]302    }
303    return true;
304}
305
[890]306std::vector<float> Fitter::getParameters() const {
[91]307    Vector<Float> out = parameters_;
308    std::vector<float> stlout;
309    out.tovector(stlout);
310    return stlout;
311}
312
[890]313std::vector<bool> Fitter::getFixedParameters() const {
[108]314  Vector<Bool> out(parameters_.nelements());
315  if (fixedpar_.nelements() == 0) {
[1232]316    return std::vector<bool>();
[108]317    //throw (AipsError("No parameter mask set."));
318  } else {
319    out = fixedpar_;
320  }
321  std::vector<bool> stlout;
322  out.tovector(stlout);
323  return stlout;
[91]324}
325
[890]326float Fitter::getChisquared() const {
[91]327    return chisquared_;
328}
329
[890]330bool Fitter::fit() {
[517]331  NonLinearFitLM<Float> fitter;
332  CompoundFunction<Float> func;
[612]333
334  uInt n = funcs_.nelements();
[517]335  for (uInt i=0; i<n; ++i) {
336    func.addFunction(*funcs_[i]);
337  }
[612]338
[517]339  fitter.setFunction(func);
340  fitter.setMaxIter(50+n*10);
341  // Convergence criterium
342  fitter.setCriteria(0.001);
[612]343
[517]344  // Fit
345  Vector<Float> sigma(x_.nelements());
346  sigma = 1.0;
[890]347
[517]348  parameters_.resize();
349  parameters_ = fitter.fit(x_, y_, sigma, &m_);
[1067]350  if ( !fitter.converged() ) {
351     return false;
352  }
[517]353  std::vector<float> ps;
354  parameters_.tovector(ps);
355  setParameters(ps);
[612]356
[517]357  error_.resize();
358  error_ = fitter.errors();
[612]359
[517]360  chisquared_ = fitter.getChi2();
[890]361
[517]362  residual_.resize();
363  residual_ =  y_;
364  fitter.residual(residual_,x_);
365  // use fitter.residual(model=True) to get the model
366  thefit_.resize(x_.nelements());
367  fitter.residual(thefit_,x_,True);
368  return true;
369}
[483]370
[1391]371bool Fitter::lfit() {
372  LinearFit<Float> fitter;
373  CompoundFunction<Float> func;
[483]374
[1391]375  uInt n = funcs_.nelements();
376  for (uInt i=0; i<n; ++i) {
377    func.addFunction(*funcs_[i]);
378  }
379
380  fitter.setFunction(func);
381  //fitter.setMaxIter(50+n*10);
382  // Convergence criterium
383  //fitter.setCriteria(0.001);
384
385  // Fit
386  Vector<Float> sigma(x_.nelements());
387  sigma = 1.0;
388
389  parameters_.resize();
390  parameters_ = fitter.fit(x_, y_, sigma, &m_);
391  std::vector<float> ps;
392  parameters_.tovector(ps);
393  setParameters(ps);
394
395  error_.resize();
396  error_ = fitter.errors();
397
398  chisquared_ = fitter.getChi2();
399
400  residual_.resize();
401  residual_ =  y_;
402  fitter.residual(residual_,x_);
403  // use fitter.residual(model=True) to get the model
404  thefit_.resize(x_.nelements());
405  fitter.residual(thefit_,x_,True);
406  return true;
407}
408
[890]409std::vector<float> Fitter::evaluate(int whichComp) const
410{
[517]411  std::vector<float> stlout;
[890]412  uInt idx = uInt(whichComp);
[517]413  Float y;
414  if ( idx < funcs_.nelements() ) {
415    for (uInt i=0; i<x_.nelements(); ++i) {
416      y = (*funcs_[idx])(x_[i]);
417      stlout.push_back(float(y));
418    }
419  }
420  return stlout;
421}
[483]422
[1924]423STFitEntry Fitter::getFitEntry() const
424{
425  STFitEntry fit;
426  fit.setParameters(getParameters());
427  fit.setErrors(getErrors());
428  fit.setComponents(funccomponents_);
429  fit.setFunctions(funcnames_);
430  fit.setParmasks(getFixedParameters());
431  return fit;
432}
Note: See TracBrowser for help on using the repository browser.