source: tags/Release2.1.0b/src/STFitter.cpp @ 1227

Last change on this file since 1227 was 1221, checked in by mar637, 18 years ago

Fix for ticket #65, fixed parameter issues. This was a problem with mask=!fixed in the fitter. Also, each fit reset the fixed parameters

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 8.9 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 1221 2006-08-31 01:10:17Z mar637 $
[91]30//#---------------------------------------------------------------------------
[125]31#include <casa/aips.h>
[91]32#include <casa/Arrays/ArrayMath.h>
33#include <casa/Arrays/ArrayLogical.h>
34#include <scimath/Fitting.h>
35#include <scimath/Fitting/LinearFit.h>
36#include <scimath/Functionals/CompiledFunction.h>
37#include <scimath/Functionals/CompoundFunction.h>
38#include <scimath/Functionals/Gaussian1D.h>
39#include <scimath/Functionals/Polynomial.h>
40#include <scimath/Mathematics/AutoDiff.h>
41#include <scimath/Mathematics/AutoDiffMath.h>
42#include <scimath/Fitting/NonLinearFitLM.h>
43#include <components/SpectralComponents/SpectralEstimate.h>
44
[894]45#include "STFitter.h"
46
[91]47using namespace asap;
[125]48using namespace casa;
[91]49
[890]50Fitter::Fitter()
[91]51{
52}
53
[890]54Fitter::~Fitter()
[91]55{
[517]56  reset();
[91]57}
58
[890]59void Fitter::clear()
[91]60{
[517]61  for (uInt i=0;i< funcs_.nelements();++i) {
62    delete funcs_[i]; funcs_[i] = 0;
63  }
[612]64  funcs_.resize(0,True);
[517]65  parameters_.resize();
66  error_.resize();
67  thefit_.resize();
68  estimate_.resize();
69  chisquared_ = 0.0;
[91]70}
[517]71
[890]72void Fitter::reset()
[91]73{
[517]74  clear();
75  x_.resize();
76  y_.resize();
77  m_.resize();
[91]78}
79
80
[890]81bool Fitter::computeEstimate() {
[517]82  if (x_.nelements() == 0 || y_.nelements() == 0)
83    throw (AipsError("No x/y data specified."));
[91]84
[517]85  if (dynamic_cast<Gaussian1D<Float>* >(funcs_[0]) == 0)
86    return false;
87  uInt n = funcs_.nelements();
88  SpectralEstimate estimator(n);
89  estimator.setQ(5);
90  Int mn,mx;
91  mn = 0;
92  mx = m_.nelements()-1;
93  for (uInt i=0; i<m_.nelements();++i) {
94    if (m_[i]) {
95      mn = i;
96      break;
[108]97    }
[517]98  }
99  for (uInt j=m_.nelements()-1; j>=0;--j) {
100    if (m_[j]) {
101      mx = j;
102      break;
[108]103    }
[517]104  }
[1067]105  //mn = 0+x_.nelements()/10;
106  //mx = x_.nelements()-x_.nelements()/10;
[517]107  estimator.setRegion(mn,mx);
108  //estimator.setWindowing(True);
109  SpectralList listGauss = estimator.estimate(x_, y_);
110  parameters_.resize(n*3);
111  Gaussian1D<Float>* g = 0;
112  for (uInt i=0; i<n;i++) {
113    g = dynamic_cast<Gaussian1D<Float>* >(funcs_[i]);
114    if (g) {
115      (*g)[0] = listGauss[i].getAmpl();
116      (*g)[1] = listGauss[i].getCenter();
117      (*g)[2] = listGauss[i].getFWHM();
[91]118    }
[517]119  }
120  estimate_.resize();
121  listGauss.evaluate(estimate_,x_);
122  return true;
[91]123}
124
[890]125std::vector<float> Fitter::getEstimate() const
[91]126{
[517]127  if (estimate_.nelements() == 0)
128    throw (AipsError("No estimate set."));
129  std::vector<float> stlout;
130  estimate_.tovector(stlout);
131  return stlout;
[91]132}
133
134
[890]135bool Fitter::setExpression(const std::string& expr, int ncomp)
[91]136{
[517]137  clear();
138  if (expr == "gauss") {
139    if (ncomp < 1) throw (AipsError("Need at least one gaussian to fit."));
140    funcs_.resize(ncomp);
141    for (Int k=0; k<ncomp; ++k) {
142      funcs_[k] = new Gaussian1D<Float>();
143    }
144  } else if (expr == "poly") {
145    funcs_.resize(1);
146    funcs_[0] = new Polynomial<Float>(ncomp);
147  } else {
148    cerr << " compiled functions not yet implemented" << endl;
149    //funcs_.resize(1);
150    //funcs_[0] = new CompiledFunction<Float>();
151    //funcs_[0]->setFunction(String(expr));
152    return false;
153  }
154  return true;
[91]155}
156
[890]157bool Fitter::setData(std::vector<float> absc, std::vector<float> spec,
[91]158                       std::vector<bool> mask)
159{
160    x_.resize();
161    y_.resize();
162    m_.resize();
163    // convert std::vector to casa Vector
164    Vector<Float> tmpx(absc);
165    Vector<Float> tmpy(spec);
166    Vector<Bool> tmpm(mask);
167    AlwaysAssert(tmpx.nelements() == tmpy.nelements(), AipsError);
168    x_ = tmpx;
169    y_ = tmpy;
170    m_ = tmpm;
171    return true;
172}
173
[890]174std::vector<float> Fitter::getResidual() const
[91]175{
176    if (residual_.nelements() == 0)
177        throw (AipsError("Function not yet fitted."));
178    std::vector<float> stlout;
179    residual_.tovector(stlout);
180    return stlout;
181}
182
[890]183std::vector<float> Fitter::getFit() const
[91]184{
185    Vector<Float> out = thefit_;
186    std::vector<float> stlout;
187    out.tovector(stlout);
188    return stlout;
189
190}
191
[890]192std::vector<float> Fitter::getErrors() const
[91]193{
194    Vector<Float> out = error_;
195    std::vector<float> stlout;
196    out.tovector(stlout);
197    return stlout;
198}
199
[890]200bool Fitter::setParameters(std::vector<float> params)
[91]201{
202    Vector<Float> tmppar(params);
203    if (funcs_.nelements() == 0)
204        throw (AipsError("Function not yet set."));
205    if (parameters_.nelements() > 0 && tmppar.nelements() != parameters_.nelements())
206        throw (AipsError("Number of parameters inconsistent with function."));
[1221]207    if (parameters_.nelements() == 0) {
[91]208        parameters_.resize(tmppar.nelements());
[1221]209        if (tmppar.nelements() != fixedpar_.nelements()) {
210          fixedpar_.resize(tmppar.nelements());
211          fixedpar_ = False;
212        }
213    }
[91]214    if (dynamic_cast<Gaussian1D<Float>* >(funcs_[0]) != 0) {
215        uInt count = 0;
216        for (uInt j=0; j < funcs_.nelements(); ++j) {
217            for (uInt i=0; i < funcs_[j]->nparameters(); ++i) {
218                (funcs_[j]->parameters())[i] = tmppar[count];
219                parameters_[count] = tmppar[count];
220                ++count;
221            }
222        }
223    } else if (dynamic_cast<Polynomial<Float>* >(funcs_[0]) != 0) {
224        for (uInt i=0; i < funcs_[0]->nparameters(); ++i) {
225            parameters_[i] = tmppar[i];
226            (funcs_[0]->parameters())[i] =  tmppar[i];
227        }
228    }
229    return true;
230}
231
[890]232bool Fitter::setFixedParameters(std::vector<bool> fixed)
[91]233{
234    if (funcs_.nelements() == 0)
235        throw (AipsError("Function not yet set."));
[1221]236    if (fixedpar_.nelements() > 0 && fixed.size() != fixedpar_.nelements())
[91]237        throw (AipsError("Number of mask elements inconsistent with function."));
238    if (dynamic_cast<Gaussian1D<Float>* >(funcs_[0]) != 0) {
239        uInt count = 0;
240        for (uInt j=0; j < funcs_.nelements(); ++j) {
241            for (uInt i=0; i < funcs_[j]->nparameters(); ++i) {
[1221]242                funcs_[j]->mask(i) = !fixed[count];
243                fixedpar_[count] = fixed[count];
[91]244                ++count;
245            }
246        }
247    } else if (dynamic_cast<Polynomial<Float>* >(funcs_[0]) != 0) {
248        for (uInt i=0; i < funcs_[0]->nparameters(); ++i) {
[1221]249            fixedpar_[i] = fixed[i];
250            funcs_[0]->mask(i) =  !fixed[i];
[91]251        }
252    }
253    return true;
254}
255
[890]256std::vector<float> Fitter::getParameters() const {
[91]257    Vector<Float> out = parameters_;
258    std::vector<float> stlout;
259    out.tovector(stlout);
260    return stlout;
261}
262
[890]263std::vector<bool> Fitter::getFixedParameters() const {
[108]264  Vector<Bool> out(parameters_.nelements());
265  if (fixedpar_.nelements() == 0) {
266    out = False;
267    //throw (AipsError("No parameter mask set."));
268  } else {
269    out = fixedpar_;
270  }
271  std::vector<bool> stlout;
272  out.tovector(stlout);
273  return stlout;
[91]274}
275
[890]276float Fitter::getChisquared() const {
[91]277    return chisquared_;
278}
279
[890]280bool Fitter::fit() {
[517]281  NonLinearFitLM<Float> fitter;
282  CompoundFunction<Float> func;
[612]283
284  uInt n = funcs_.nelements();
[517]285  for (uInt i=0; i<n; ++i) {
286    func.addFunction(*funcs_[i]);
287  }
[612]288
[517]289  fitter.setFunction(func);
290  fitter.setMaxIter(50+n*10);
291  // Convergence criterium
292  fitter.setCriteria(0.001);
[612]293
[517]294  // Fit
295  Vector<Float> sigma(x_.nelements());
296  sigma = 1.0;
[890]297
[517]298  parameters_.resize();
299  parameters_ = fitter.fit(x_, y_, sigma, &m_);
[1067]300  if ( !fitter.converged() ) {
301     return false;
302  }
[517]303  std::vector<float> ps;
304  parameters_.tovector(ps);
305  setParameters(ps);
[612]306
[517]307  error_.resize();
308  error_ = fitter.errors();
[612]309
[517]310  chisquared_ = fitter.getChi2();
[890]311
[517]312  residual_.resize();
313  residual_ =  y_;
314  fitter.residual(residual_,x_);
315  // use fitter.residual(model=True) to get the model
316  thefit_.resize(x_.nelements());
317  fitter.residual(thefit_,x_,True);
318  return true;
319}
[483]320
321
[890]322std::vector<float> Fitter::evaluate(int whichComp) const
323{
[517]324  std::vector<float> stlout;
[890]325  uInt idx = uInt(whichComp);
[517]326  Float y;
327  if ( idx < funcs_.nelements() ) {
328    for (uInt i=0; i<x_.nelements(); ++i) {
329      y = (*funcs_[idx])(x_[i]);
330      stlout.push_back(float(y));
331    }
332  }
333  return stlout;
334}
[483]335
Note: See TracBrowser for help on using the repository browser.