source: branches/parallel/src/STFitter.cpp@ 2187

Last change on this file since 2187 was 2047, checked in by WataruKawasaki, 14 years ago

New Development: Yes

JIRA Issue: Yes CAS-2847

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs:

Put in Release Notes: Yes

Module(s): scantable

Description: added {auto_}sinusoid_baseline() for sinusoidal baseline fitting. also minor bug fixes for asapfitter.


  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 12.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 2047 2011-03-15 07:31:04Z WataruKawasaki $
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/Sinusoid1D.h>
42#include <scimath/Functionals/Polynomial.h>
43#include <scimath/Mathematics/AutoDiff.h>
44#include <scimath/Mathematics/AutoDiffMath.h>
45#include <scimath/Fitting/NonLinearFitLM.h>
46#include <components/SpectralComponents/SpectralEstimate.h>
47
48#include "STFitter.h"
49
50using namespace asap;
51using namespace casa;
52
53Fitter::Fitter()
54{
55}
56
57Fitter::~Fitter()
58{
59 reset();
60}
61
62void Fitter::clear()
63{
64 for (uInt i=0;i< funcs_.nelements();++i) {
65 delete funcs_[i]; funcs_[i] = 0;
66 }
67 funcs_.resize(0,True);
68 parameters_.resize();
69 fixedpar_.resize();
70 error_.resize();
71 thefit_.resize();
72 estimate_.resize();
73 chisquared_ = 0.0;
74}
75
76void Fitter::reset()
77{
78 clear();
79 x_.resize();
80 y_.resize();
81 m_.resize();
82}
83
84
85bool Fitter::computeEstimate() {
86 if (x_.nelements() == 0 || y_.nelements() == 0)
87 throw (AipsError("No x/y data specified."));
88
89 if (dynamic_cast<Gaussian1D<Float>* >(funcs_[0]) == 0)
90 return false;
91 uInt n = funcs_.nelements();
92 SpectralEstimate estimator(n);
93 estimator.setQ(5);
94 Int mn,mx;
95 mn = 0;
96 mx = m_.nelements()-1;
97 for (uInt i=0; i<m_.nelements();++i) {
98 if (m_[i]) {
99 mn = i;
100 break;
101 }
102 }
103 for (uInt j=m_.nelements()-1; j>=0;--j) {
104 if (m_[j]) {
105 mx = j;
106 break;
107 }
108 }
109 //mn = 0+x_.nelements()/10;
110 //mx = x_.nelements()-x_.nelements()/10;
111 estimator.setRegion(mn,mx);
112 //estimator.setWindowing(True);
113 SpectralList listGauss = estimator.estimate(x_, y_);
114 parameters_.resize(n*3);
115 Gaussian1D<Float>* g = 0;
116 for (uInt i=0; i<n;i++) {
117 g = dynamic_cast<Gaussian1D<Float>* >(funcs_[i]);
118 if (g) {
119 (*g)[0] = listGauss[i].getAmpl();
120 (*g)[1] = listGauss[i].getCenter();
121 (*g)[2] = listGauss[i].getFWHM();
122 }
123 }
124 estimate_.resize();
125 listGauss.evaluate(estimate_,x_);
126 return true;
127}
128
129std::vector<float> Fitter::getEstimate() const
130{
131 if (estimate_.nelements() == 0)
132 throw (AipsError("No estimate set."));
133 std::vector<float> stlout;
134 estimate_.tovector(stlout);
135 return stlout;
136}
137
138
139bool Fitter::setExpression(const std::string& expr, int ncomp)
140{
141 clear();
142 if (expr == "gauss") {
143 if (ncomp < 1) throw (AipsError("Need at least one gaussian to fit."));
144 funcs_.resize(ncomp);
145 funcnames_.clear();
146 funccomponents_.clear();
147 for (Int k=0; k<ncomp; ++k) {
148 funcs_[k] = new Gaussian1D<Float>();
149 funcnames_.push_back(expr);
150 funccomponents_.push_back(3);
151 }
152 } else if (expr == "lorentz") {
153 if (ncomp < 1) throw (AipsError("Need at least one lorentzian to fit."));
154 funcs_.resize(ncomp);
155 funcnames_.clear();
156 funccomponents_.clear();
157 for (Int k=0; k<ncomp; ++k) {
158 funcs_[k] = new Lorentzian1D<Float>();
159 funcnames_.push_back(expr);
160 funccomponents_.push_back(3);
161 }
162 } else if (expr == "sinusoid") {
163 if (ncomp < 1) throw (AipsError("Need at least one sinusoid to fit."));
164 funcs_.resize(ncomp);
165 funcnames_.clear();
166 funccomponents_.clear();
167 for (Int k=0; k<ncomp; ++k) {
168 funcs_[k] = new Sinusoid1D<Float>();
169 funcnames_.push_back(expr);
170 funccomponents_.push_back(3);
171 }
172 } else if (expr == "poly") {
173 funcs_.resize(1);
174 funcnames_.clear();
175 funccomponents_.clear();
176 funcs_[0] = new Polynomial<Float>(ncomp);
177 funcnames_.push_back(expr);
178 funccomponents_.push_back(ncomp);
179 } else {
180 LogIO os( LogOrigin( "Fitter", "setExpression()", WHERE ) ) ;
181 os << LogIO::WARN << " compiled functions not yet implemented" << LogIO::POST;
182 //funcs_.resize(1);
183 //funcs_[0] = new CompiledFunction<Float>();
184 //funcs_[0]->setFunction(String(expr));
185 return false;
186 }
187 return true;
188}
189
190bool Fitter::setData(std::vector<float> absc, std::vector<float> spec,
191 std::vector<bool> mask)
192{
193 x_.resize();
194 y_.resize();
195 m_.resize();
196 // convert std::vector to casa Vector
197 Vector<Float> tmpx(absc);
198 Vector<Float> tmpy(spec);
199 Vector<Bool> tmpm(mask);
200 AlwaysAssert(tmpx.nelements() == tmpy.nelements(), AipsError);
201 x_ = tmpx;
202 y_ = tmpy;
203 m_ = tmpm;
204 return true;
205}
206
207std::vector<float> Fitter::getResidual() const
208{
209 if (residual_.nelements() == 0)
210 throw (AipsError("Function not yet fitted."));
211 std::vector<float> stlout;
212 residual_.tovector(stlout);
213 return stlout;
214}
215
216std::vector<float> Fitter::getFit() const
217{
218 Vector<Float> out = thefit_;
219 std::vector<float> stlout;
220 out.tovector(stlout);
221 return stlout;
222
223}
224
225std::vector<float> Fitter::getErrors() const
226{
227 Vector<Float> out = error_;
228 std::vector<float> stlout;
229 out.tovector(stlout);
230 return stlout;
231}
232
233bool Fitter::setParameters(std::vector<float> params)
234{
235 Vector<Float> tmppar(params);
236 if (funcs_.nelements() == 0)
237 throw (AipsError("Function not yet set."));
238 if (parameters_.nelements() > 0 && tmppar.nelements() != parameters_.nelements())
239 throw (AipsError("Number of parameters inconsistent with function."));
240 if (parameters_.nelements() == 0) {
241 parameters_.resize(tmppar.nelements());
242 if (tmppar.nelements() != fixedpar_.nelements()) {
243 fixedpar_.resize(tmppar.nelements());
244 fixedpar_ = False;
245 }
246 }
247 if (dynamic_cast<Gaussian1D<Float>* >(funcs_[0]) != 0) {
248 uInt count = 0;
249 for (uInt j=0; j < funcs_.nelements(); ++j) {
250 for (uInt i=0; i < funcs_[j]->nparameters(); ++i) {
251 (funcs_[j]->parameters())[i] = tmppar[count];
252 parameters_[count] = tmppar[count];
253 ++count;
254 }
255 }
256 } else if (dynamic_cast<Lorentzian1D<Float>* >(funcs_[0]) != 0) {
257 uInt count = 0;
258 for (uInt j=0; j < funcs_.nelements(); ++j) {
259 for (uInt i=0; i < funcs_[j]->nparameters(); ++i) {
260 (funcs_[j]->parameters())[i] = tmppar[count];
261 parameters_[count] = tmppar[count];
262 ++count;
263 }
264 }
265 } else if (dynamic_cast<Sinusoid1D<Float>* >(funcs_[0]) != 0) {
266 uInt count = 0;
267 for (uInt j=0; j < funcs_.nelements(); ++j) {
268 for (uInt i=0; i < funcs_[j]->nparameters(); ++i) {
269 (funcs_[j]->parameters())[i] = tmppar[count];
270 parameters_[count] = tmppar[count];
271 ++count;
272 }
273 }
274 } else if (dynamic_cast<Polynomial<Float>* >(funcs_[0]) != 0) {
275 for (uInt i=0; i < funcs_[0]->nparameters(); ++i) {
276 parameters_[i] = tmppar[i];
277 (funcs_[0]->parameters())[i] = tmppar[i];
278 }
279 }
280 // reset
281 if (params.size() == 0) {
282 parameters_.resize();
283 fixedpar_.resize();
284 }
285 return true;
286}
287
288bool Fitter::setFixedParameters(std::vector<bool> fixed)
289{
290 if (funcs_.nelements() == 0)
291 throw (AipsError("Function not yet set."));
292 if (fixedpar_.nelements() > 0 && fixed.size() != fixedpar_.nelements())
293 throw (AipsError("Number of mask elements inconsistent with function."));
294 if (fixedpar_.nelements() == 0) {
295 fixedpar_.resize(parameters_.nelements());
296 fixedpar_ = False;
297 }
298 if (dynamic_cast<Gaussian1D<Float>* >(funcs_[0]) != 0) {
299 uInt count = 0;
300 for (uInt j=0; j < funcs_.nelements(); ++j) {
301 for (uInt i=0; i < funcs_[j]->nparameters(); ++i) {
302 funcs_[j]->mask(i) = !fixed[count];
303 fixedpar_[count] = fixed[count];
304 ++count;
305 }
306 }
307 } else if (dynamic_cast<Lorentzian1D<Float>* >(funcs_[0]) != 0) {
308 uInt count = 0;
309 for (uInt j=0; j < funcs_.nelements(); ++j) {
310 for (uInt i=0; i < funcs_[j]->nparameters(); ++i) {
311 funcs_[j]->mask(i) = !fixed[count];
312 fixedpar_[count] = fixed[count];
313 ++count;
314 }
315 }
316 } else if (dynamic_cast<Sinusoid1D<Float>* >(funcs_[0]) != 0) {
317 uInt count = 0;
318 for (uInt j=0; j < funcs_.nelements(); ++j) {
319 for (uInt i=0; i < funcs_[j]->nparameters(); ++i) {
320 funcs_[j]->mask(i) = !fixed[count];
321 fixedpar_[count] = fixed[count];
322 ++count;
323 }
324 }
325 } else if (dynamic_cast<Polynomial<Float>* >(funcs_[0]) != 0) {
326 for (uInt i=0; i < funcs_[0]->nparameters(); ++i) {
327 fixedpar_[i] = fixed[i];
328 funcs_[0]->mask(i) = !fixed[i];
329 }
330 }
331 return true;
332}
333
334std::vector<float> Fitter::getParameters() const {
335 Vector<Float> out = parameters_;
336 std::vector<float> stlout;
337 out.tovector(stlout);
338 return stlout;
339}
340
341std::vector<bool> Fitter::getFixedParameters() const {
342 Vector<Bool> out(parameters_.nelements());
343 if (fixedpar_.nelements() == 0) {
344 return std::vector<bool>();
345 //throw (AipsError("No parameter mask set."));
346 } else {
347 out = fixedpar_;
348 }
349 std::vector<bool> stlout;
350 out.tovector(stlout);
351 return stlout;
352}
353
354float Fitter::getChisquared() const {
355 return chisquared_;
356}
357
358bool Fitter::fit() {
359 NonLinearFitLM<Float> fitter;
360 CompoundFunction<Float> func;
361
362 uInt n = funcs_.nelements();
363 for (uInt i=0; i<n; ++i) {
364 func.addFunction(*funcs_[i]);
365 }
366
367 fitter.setFunction(func);
368 fitter.setMaxIter(50+n*10);
369 // Convergence criterium
370 fitter.setCriteria(0.001);
371
372 // Fit
373 Vector<Float> sigma(x_.nelements());
374 sigma = 1.0;
375
376 parameters_.resize();
377 parameters_ = fitter.fit(x_, y_, sigma, &m_);
378 if ( !fitter.converged() ) {
379 return false;
380 }
381 std::vector<float> ps;
382 parameters_.tovector(ps);
383 setParameters(ps);
384
385 error_.resize();
386 error_ = fitter.errors();
387
388 chisquared_ = fitter.getChi2();
389
390 residual_.resize();
391 residual_ = y_;
392 fitter.residual(residual_,x_);
393 // use fitter.residual(model=True) to get the model
394 thefit_.resize(x_.nelements());
395 fitter.residual(thefit_,x_,True);
396 return true;
397}
398
399bool Fitter::lfit() {
400 LinearFit<Float> fitter;
401 CompoundFunction<Float> func;
402
403 uInt n = funcs_.nelements();
404 for (uInt i=0; i<n; ++i) {
405 func.addFunction(*funcs_[i]);
406 }
407
408 fitter.setFunction(func);
409 //fitter.setMaxIter(50+n*10);
410 // Convergence criterium
411 //fitter.setCriteria(0.001);
412
413 // Fit
414 Vector<Float> sigma(x_.nelements());
415 sigma = 1.0;
416
417 parameters_.resize();
418 parameters_ = fitter.fit(x_, y_, sigma, &m_);
419 std::vector<float> ps;
420 parameters_.tovector(ps);
421 setParameters(ps);
422
423 error_.resize();
424 error_ = fitter.errors();
425
426 chisquared_ = fitter.getChi2();
427
428 residual_.resize();
429 residual_ = y_;
430 fitter.residual(residual_,x_);
431 // use fitter.residual(model=True) to get the model
432 thefit_.resize(x_.nelements());
433 fitter.residual(thefit_,x_,True);
434 return true;
435}
436
437std::vector<float> Fitter::evaluate(int whichComp) const
438{
439 std::vector<float> stlout;
440 uInt idx = uInt(whichComp);
441 Float y;
442 if ( idx < funcs_.nelements() ) {
443 for (uInt i=0; i<x_.nelements(); ++i) {
444 y = (*funcs_[idx])(x_[i]);
445 stlout.push_back(float(y));
446 }
447 }
448 return stlout;
449}
450
451STFitEntry Fitter::getFitEntry() const
452{
453 STFitEntry fit;
454 fit.setParameters(getParameters());
455 fit.setErrors(getErrors());
456 fit.setComponents(funccomponents_);
457 fit.setFunctions(funcnames_);
458 fit.setParmasks(getFixedParameters());
459 return fit;
460}
Note: See TracBrowser for help on using the repository browser.