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

Last change on this file since 3137 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
Line 
1//#---------------------------------------------------------------------------
2//# Fitter.cc: A Fitter class for spectra
3//#--------------------------------------------------------------------------
4//# Copyright (C) 2004
5//# ATNF
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//#
29//# $Id: STFitter.cpp 1924 2010-09-14 02:17:16Z MalteMarquarding $
30//#---------------------------------------------------------------------------
31#include <casa/aips.h>
32#include <casa/Arrays/ArrayMath.h>
33#include <casa/Arrays/ArrayLogical.h>
34#include <casa/Logging/LogIO.h>
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>
40#include "Lorentzian1D.h"
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
47#include "STFitter.h"
48
49using namespace asap;
50using namespace casa;
51
52Fitter::Fitter()
53{
54}
55
56Fitter::~Fitter()
57{
58 reset();
59}
60
61void Fitter::clear()
62{
63 for (uInt i=0;i< funcs_.nelements();++i) {
64 delete funcs_[i]; funcs_[i] = 0;
65 }
66 funcs_.resize(0,True);
67 parameters_.resize();
68 fixedpar_.resize();
69 error_.resize();
70 thefit_.resize();
71 estimate_.resize();
72 chisquared_ = 0.0;
73}
74
75void Fitter::reset()
76{
77 clear();
78 x_.resize();
79 y_.resize();
80 m_.resize();
81}
82
83
84bool Fitter::computeEstimate() {
85 if (x_.nelements() == 0 || y_.nelements() == 0)
86 throw (AipsError("No x/y data specified."));
87
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;
100 }
101 }
102 for (uInt j=m_.nelements()-1; j>=0;--j) {
103 if (m_[j]) {
104 mx = j;
105 break;
106 }
107 }
108 //mn = 0+x_.nelements()/10;
109 //mx = x_.nelements()-x_.nelements()/10;
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();
121 }
122 }
123 estimate_.resize();
124 listGauss.evaluate(estimate_,x_);
125 return true;
126}
127
128std::vector<float> Fitter::getEstimate() const
129{
130 if (estimate_.nelements() == 0)
131 throw (AipsError("No estimate set."));
132 std::vector<float> stlout;
133 estimate_.tovector(stlout);
134 return stlout;
135}
136
137
138bool Fitter::setExpression(const std::string& expr, int ncomp)
139{
140 clear();
141 if (expr == "gauss") {
142 if (ncomp < 1) throw (AipsError("Need at least one gaussian to fit."));
143 funcs_.resize(ncomp);
144 funcnames_.clear();
145 funccomponents_.clear();
146 for (Int k=0; k<ncomp; ++k) {
147 funcs_[k] = new Gaussian1D<Float>();
148 funcnames_.push_back(expr);
149 funccomponents_.push_back(3);
150 }
151 } else if (expr == "poly") {
152 funcs_.resize(1);
153 funcnames_.clear();
154 funccomponents_.clear();
155 funcs_[0] = new Polynomial<Float>(ncomp);
156 funcnames_.push_back(expr);
157 funccomponents_.push_back(ncomp);
158 } else if (expr == "lorentz") {
159 if (ncomp < 1) throw (AipsError("Need at least one lorentzian to fit."));
160 funcs_.resize(ncomp);
161 funcnames_.clear();
162 funccomponents_.clear();
163 for (Int k=0; k<ncomp; ++k) {
164 funcs_[k] = new Lorentzian1D<Float>();
165 funcnames_.push_back(expr);
166 funccomponents_.push_back(3);
167 }
168 } else {
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;
172 //funcs_.resize(1);
173 //funcs_[0] = new CompiledFunction<Float>();
174 //funcs_[0]->setFunction(String(expr));
175 return false;
176 }
177 return true;
178}
179
180bool Fitter::setData(std::vector<float> absc, std::vector<float> spec,
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
197std::vector<float> Fitter::getResidual() const
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
206std::vector<float> Fitter::getFit() const
207{
208 Vector<Float> out = thefit_;
209 std::vector<float> stlout;
210 out.tovector(stlout);
211 return stlout;
212
213}
214
215std::vector<float> Fitter::getErrors() const
216{
217 Vector<Float> out = error_;
218 std::vector<float> stlout;
219 out.tovector(stlout);
220 return stlout;
221}
222
223bool Fitter::setParameters(std::vector<float> params)
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."));
230 if (parameters_.nelements() == 0) {
231 parameters_.resize(tmppar.nelements());
232 if (tmppar.nelements() != fixedpar_.nelements()) {
233 fixedpar_.resize(tmppar.nelements());
234 fixedpar_ = False;
235 }
236 }
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 }
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 }
260 }
261 // reset
262 if (params.size() == 0) {
263 parameters_.resize();
264 fixedpar_.resize();
265 }
266 return true;
267}
268
269bool Fitter::setFixedParameters(std::vector<bool> fixed)
270{
271 if (funcs_.nelements() == 0)
272 throw (AipsError("Function not yet set."));
273 if (fixedpar_.nelements() > 0 && fixed.size() != fixedpar_.nelements())
274 throw (AipsError("Number of mask elements inconsistent with function."));
275 if (fixedpar_.nelements() == 0) {
276 fixedpar_.resize(parameters_.nelements());
277 fixedpar_ = False;
278 }
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) {
283 funcs_[j]->mask(i) = !fixed[count];
284 fixedpar_[count] = fixed[count];
285 ++count;
286 }
287 }
288 } else if (dynamic_cast<Polynomial<Float>* >(funcs_[0]) != 0) {
289 for (uInt i=0; i < funcs_[0]->nparameters(); ++i) {
290 fixedpar_[i] = fixed[i];
291 funcs_[0]->mask(i) = !fixed[i];
292 }
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 }
302 }
303 return true;
304}
305
306std::vector<float> Fitter::getParameters() const {
307 Vector<Float> out = parameters_;
308 std::vector<float> stlout;
309 out.tovector(stlout);
310 return stlout;
311}
312
313std::vector<bool> Fitter::getFixedParameters() const {
314 Vector<Bool> out(parameters_.nelements());
315 if (fixedpar_.nelements() == 0) {
316 return std::vector<bool>();
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;
324}
325
326float Fitter::getChisquared() const {
327 return chisquared_;
328}
329
330bool Fitter::fit() {
331 NonLinearFitLM<Float> fitter;
332 CompoundFunction<Float> func;
333
334 uInt n = funcs_.nelements();
335 for (uInt i=0; i<n; ++i) {
336 func.addFunction(*funcs_[i]);
337 }
338
339 fitter.setFunction(func);
340 fitter.setMaxIter(50+n*10);
341 // Convergence criterium
342 fitter.setCriteria(0.001);
343
344 // Fit
345 Vector<Float> sigma(x_.nelements());
346 sigma = 1.0;
347
348 parameters_.resize();
349 parameters_ = fitter.fit(x_, y_, sigma, &m_);
350 if ( !fitter.converged() ) {
351 return false;
352 }
353 std::vector<float> ps;
354 parameters_.tovector(ps);
355 setParameters(ps);
356
357 error_.resize();
358 error_ = fitter.errors();
359
360 chisquared_ = fitter.getChi2();
361
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}
370
371bool Fitter::lfit() {
372 LinearFit<Float> fitter;
373 CompoundFunction<Float> func;
374
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
409std::vector<float> Fitter::evaluate(int whichComp) const
410{
411 std::vector<float> stlout;
412 uInt idx = uInt(whichComp);
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}
422
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.