source: trunk/src/STFitter.cpp @ 3106

Last change on this file since 3106 was 3106, checked in by Takeshi Nakazato, 8 years ago

New Development: No

JIRA Issue: No

Ready for Test: Yes/No?

Interface Changes: Yes/No?

What Interface Changed: Please list interface changes

Test Programs: List test programs

Put in Release Notes: Yes/No?

Module(s): Module Names change impacts.

Description: Describe your changes here...


Check-in asap modifications from Jim regarding casacore namespace conversion.

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