source: trunk/src/STLineFinder.cpp@ 920

Last change on this file since 920 was 907, checked in by vor010, 18 years ago

LineFinder & auto_poly_baseline: a support of
new scantable format has been added. Now findLines accept a mask and edge
parameters, which can therefore be different for different rows. Constructor
need now just a scan table. Boost types removed from STLineFinder. auto_poly_baseline can accept a nested tuple of edges, which would be interpreted as
different edge parameters for different IFs

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 40.8 KB
RevLine 
[297]1//#---------------------------------------------------------------------------
[881]2//# STLineFinder.cc: A class for automated spectral line search
[297]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//#
[890]29//# $Id: STLineFinder.cpp 907 2006-03-20 04:17:06Z vor010 $
[297]30//#---------------------------------------------------------------------------
31
32
33// ASAP
[894]34#include "STLineFinder.h"
35#include "STFitter.h"
[297]36
37// STL
[343]38#include <functional>
39#include <algorithm>
[297]40#include <iostream>
[351]41#include <fstream>
[297]42
43using namespace asap;
44using namespace casa;
45using namespace std;
46using namespace boost::python;
47
[344]48namespace asap {
49
[343]50///////////////////////////////////////////////////////////////////////////////
51//
[881]52// RunningBox - a running box calculator. This class implements
[351]53// interations over the specified spectrum and calculates
54// running box filter statistics.
[343]55//
56
[351]57class RunningBox {
[331]58 // The input data to work with. Use reference symantics to avoid
[881]59 // an unnecessary copying
[331]60 const casa::Vector<casa::Float> &spectrum; // a buffer for the spectrum
61 const casa::Vector<casa::Bool> &mask; // associated mask
62 const std::pair<int,int> &edge; // start and stop+1 channels
63 // to work with
[881]64
[351]65 // statistics for running box filtering
66 casa::Float sumf; // sum of fluxes
67 casa::Float sumf2; // sum of squares of fluxes
68 casa::Float sumch; // sum of channel numbers (for linear fit)
69 casa::Float sumch2; // sum of squares of channel numbers (for linear fit)
70 casa::Float sumfch; // sum of flux*(channel number) (for linear fit)
[881]71
[331]72 int box_chan_cntr; // actual number of channels in the box
73 int max_box_nchan; // maximum allowed number of channels in the box
74 // (calculated from boxsize and actual spectrum size)
[351]75 // cache for derivative statistics
76 mutable casa::Bool need2recalculate; // if true, values of the statistics
77 // below are invalid
78 mutable casa::Float linmean; // a value of the linear fit to the
79 // points in the running box
80 mutable casa::Float linvariance; // the same for variance
81 int cur_channel; // the number of the current channel
82 int start_advance; // number of channel from which the box can
83 // be moved (the middle of the box, if there is no
84 // masking)
85public:
86 // set up the object with the references to actual data
87 // as well as the number of channels in the running box
88 RunningBox(const casa::Vector<casa::Float> &in_spectrum,
89 const casa::Vector<casa::Bool> &in_mask,
90 const std::pair<int,int> &in_edge,
91 int in_max_box_nchan) throw(AipsError);
[881]92
[351]93 // access to the statistics
94 const casa::Float& getLinMean() const throw(AipsError);
95 const casa::Float& getLinVariance() const throw(AipsError);
96 const casa::Float aboveMean() const throw(AipsError);
97 int getChannel() const throw();
[881]98
[351]99 // actual number of channels in the box (max_box_nchan, if no channels
100 // are masked)
101 int getNumberOfBoxPoints() const throw();
[297]102
[351]103 // next channel
104 void next() throw(AipsError);
105
106 // checking whether there are still elements
107 casa::Bool haveMore() const throw();
108
109 // go to start
110 void rewind() throw(AipsError);
[881]111
[351]112protected:
113 // supplementary function to control running mean calculations.
114 // It adds a specified channel to the running mean box and
115 // removes (ch-maxboxnchan+1)'th channel from there
116 // Channels, for which the mask is false or index is beyond the
117 // allowed range, are ignored
118 void advanceRunningBox(int ch) throw(casa::AipsError);
119
120 // calculate derivative statistics. This function is const, because
121 // it updates the cache only
122 void updateDerivativeStatistics() const throw(AipsError);
123};
124
125//
126///////////////////////////////////////////////////////////////////////////////
127
128///////////////////////////////////////////////////////////////////////////////
129//
130// LFAboveThreshold An algorithm for line detection using running box
131// statistics. Line is detected if it is above the
132// specified threshold at the specified number of
133// consequtive channels. Prefix LF stands for Line Finder
134//
[352]135class LFAboveThreshold : protected LFLineListOperations {
[331]136 // temporary line edge channels and flag, which is True if the line
137 // was detected in the previous channels.
138 std::pair<int,int> cur_line;
139 casa::Bool is_detected_before;
140 int min_nchan; // A minimum number of consequtive
141 // channels, which should satisfy
142 // the detection criterion, to be
143 // a detection
[881]144 casa::Float threshold; // detection threshold - the
[331]145 // minimal signal to noise ratio
[351]146 std::list<pair<int,int> > &lines; // list where detections are saved
147 // (pair: start and stop+1 channel)
148 RunningBox *running_box; // running box filter
[551]149 casa::Vector<Int> signs; // An array to store the signs of
150 // the value - current mean
151 // (used to search wings)
[907]152 casa::Int last_sign; // a sign (+1, -1 or 0) of the
153 // last point of the detected line
154 //
[331]155public:
[351]156
157 // set up the detection criterion
158 LFAboveThreshold(std::list<pair<int,int> > &in_lines,
159 int in_min_nchan = 3,
160 casa::Float in_threshold = 5) throw();
161 virtual ~LFAboveThreshold() throw();
[881]162
[331]163 // replace the detection criterion
164 void setCriterion(int in_min_nchan, casa::Float in_threshold) throw();
[297]165
[551]166 // return the array with signs of the value-current mean
167 // An element is +1 if value>mean, -1 if less, 0 if equal.
168 // This array is updated each time the findLines method is called and
169 // is used to search the line wings
170 const casa::Vector<Int>& getSigns() const throw();
171
[331]172 // find spectral lines and add them into list
[344]173 // if statholder is not NULL, the accumulate function of it will be
174 // called for each channel to save statistics
[351]175 // spectrum, mask and edge - reference to the data
176 // max_box_nchan - number of channels in the running box
177 void findLines(const casa::Vector<casa::Float> &spectrum,
178 const casa::Vector<casa::Bool> &mask,
179 const std::pair<int,int> &edge,
[352]180 int max_box_nchan) throw(casa::AipsError);
[351]181
[331]182protected:
[297]183
[331]184 // process a channel: update curline and is_detected before and
185 // add a new line to the list, if necessary using processCurLine()
[351]186 // detect=true indicates that the current channel satisfies the criterion
187 void processChannel(Bool detect, const casa::Vector<casa::Bool> &mask)
188 throw(casa::AipsError);
[297]189
[331]190 // process the interval of channels stored in curline
191 // if it satisfies the criterion, add this interval as a new line
[351]192 void processCurLine(const casa::Vector<casa::Bool> &mask)
193 throw(casa::AipsError);
[907]194
195 // get the sign of runningBox->aboveMean(). The RunningBox pointer
196 // should be defined
197 casa::Int getAboveMeanSign() const throw();
[331]198};
[344]199
200//
201///////////////////////////////////////////////////////////////////////////////
[351]202
[331]203} // namespace asap
[297]204
[344]205///////////////////////////////////////////////////////////////////////////////
[343]206//
[881]207// RunningBox - a running box calculator. This class implements
[351]208// interations over the specified spectrum and calculates
209// running box filter statistics.
[331]210//
[297]211
[331]212// set up the object with the references to actual data
213// and the number of channels in the running box
[351]214RunningBox::RunningBox(const casa::Vector<casa::Float> &in_spectrum,
215 const casa::Vector<casa::Bool> &in_mask,
216 const std::pair<int,int> &in_edge,
217 int in_max_box_nchan) throw(AipsError) :
[331]218 spectrum(in_spectrum), mask(in_mask), edge(in_edge),
[351]219 max_box_nchan(in_max_box_nchan)
220{
221 rewind();
222}
[331]223
[351]224void RunningBox::rewind() throw(AipsError) {
225 // fill statistics for initial box
226 box_chan_cntr=0; // no channels are currently in the box
227 sumf=0.; // initialize statistics
228 sumf2=0.;
229 sumch=0.;
230 sumch2=0.;
231 sumfch=0.;
232 int initial_box_ch=edge.first;
233 for (;initial_box_ch<edge.second && box_chan_cntr<max_box_nchan;
234 ++initial_box_ch)
235 advanceRunningBox(initial_box_ch);
[881]236
237 if (initial_box_ch==edge.second)
[351]238 throw AipsError("RunningBox::rewind - too much channels are masked");
239
240 cur_channel=edge.first;
[881]241 start_advance=initial_box_ch-max_box_nchan/2;
[351]242}
243
244// access to the statistics
245const casa::Float& RunningBox::getLinMean() const throw(AipsError)
[331]246{
[351]247 DebugAssert(cur_channel<edge.second, AipsError);
248 if (need2recalculate) updateDerivativeStatistics();
249 return linmean;
[297]250}
251
[351]252const casa::Float& RunningBox::getLinVariance() const throw(AipsError)
253{
254 DebugAssert(cur_channel<edge.second, AipsError);
255 if (need2recalculate) updateDerivativeStatistics();
256 return linvariance;
257}
[331]258
[351]259const casa::Float RunningBox::aboveMean() const throw(AipsError)
260{
261 DebugAssert(cur_channel<edge.second, AipsError);
262 if (need2recalculate) updateDerivativeStatistics();
263 return spectrum[cur_channel]-linmean;
264}
265
266int RunningBox::getChannel() const throw()
267{
268 return cur_channel;
269}
270
271// actual number of channels in the box (max_box_nchan, if no channels
272// are masked)
273int RunningBox::getNumberOfBoxPoints() const throw()
274{
275 return box_chan_cntr;
276}
277
[297]278// supplementary function to control running mean calculations.
279// It adds a specified channel to the running mean box and
280// removes (ch-max_box_nchan+1)'th channel from there
281// Channels, for which the mask is false or index is beyond the
282// allowed range, are ignored
[351]283void RunningBox::advanceRunningBox(int ch) throw(AipsError)
[297]284{
285 if (ch>=edge.first && ch<edge.second)
286 if (mask[ch]) { // ch is a valid channel
287 ++box_chan_cntr;
[351]288 sumf+=spectrum[ch];
289 sumf2+=square(spectrum[ch]);
290 sumch+=Float(ch);
291 sumch2+=square(Float(ch));
292 sumfch+=spectrum[ch]*Float(ch);
293 need2recalculate=True;
[297]294 }
295 int ch2remove=ch-max_box_nchan;
296 if (ch2remove>=edge.first && ch2remove<edge.second)
297 if (mask[ch2remove]) { // ch2remove is a valid channel
298 --box_chan_cntr;
[351]299 sumf-=spectrum[ch2remove];
[881]300 sumf2-=square(spectrum[ch2remove]);
[351]301 sumch-=Float(ch2remove);
302 sumch2-=square(Float(ch2remove));
303 sumfch-=spectrum[ch2remove]*Float(ch2remove);
304 need2recalculate=True;
[297]305 }
306}
307
[351]308// next channel
309void RunningBox::next() throw(AipsError)
[297]310{
[351]311 AlwaysAssert(cur_channel<edge.second,AipsError);
312 ++cur_channel;
313 if (cur_channel+max_box_nchan/2<edge.second && cur_channel>=start_advance)
314 advanceRunningBox(cur_channel+max_box_nchan/2); // update statistics
[297]315}
316
[351]317// checking whether there are still elements
318casa::Bool RunningBox::haveMore() const throw()
319{
320 return cur_channel<edge.second;
321}
322
323// calculate derivative statistics. This function is const, because
324// it updates the cache only
325void RunningBox::updateDerivativeStatistics() const throw(AipsError)
326{
327 AlwaysAssert(box_chan_cntr, AipsError);
[881]328
[351]329 Float mean=sumf/Float(box_chan_cntr);
330
331 // linear LSF formulae
332 Float meanch=sumch/Float(box_chan_cntr);
333 Float meanch2=sumch2/Float(box_chan_cntr);
334 if (meanch==meanch2 || box_chan_cntr<3) {
335 // vertical line in the spectrum, can't calculate linmean and linvariance
336 linmean=0.;
337 linvariance=0.;
338 } else {
339 Float coeff=(sumfch/Float(box_chan_cntr)-meanch*mean)/
340 (meanch2-square(meanch));
341 linmean=coeff*(Float(cur_channel)-meanch)+mean;
342 linvariance=sqrt(sumf2/Float(box_chan_cntr)-square(mean)-
343 square(coeff)*(meanch2-square(meanch)));
344 }
345 need2recalculate=False;
346}
347
348
349//
350///////////////////////////////////////////////////////////////////////////////
351
352///////////////////////////////////////////////////////////////////////////////
353//
354// LFAboveThreshold - a running mean algorithm for line detection
355//
356//
357
358
359// set up the detection criterion
360LFAboveThreshold::LFAboveThreshold(std::list<pair<int,int> > &in_lines,
361 int in_min_nchan,
362 casa::Float in_threshold) throw() :
363 min_nchan(in_min_nchan), threshold(in_threshold),
364 lines(in_lines), running_box(NULL) {}
365
366LFAboveThreshold::~LFAboveThreshold() throw()
367{
368 if (running_box!=NULL) delete running_box;
369}
370
371// replace the detection criterion
372void LFAboveThreshold::setCriterion(int in_min_nchan, casa::Float in_threshold)
373 throw()
374{
375 min_nchan=in_min_nchan;
376 threshold=in_threshold;
377}
378
[907]379// get the sign of runningBox->aboveMean(). The RunningBox pointer
380// should be defined
381casa::Int LFAboveThreshold::getAboveMeanSign() const throw()
382{
383 const Float buf=running_box->aboveMean();
384 if (buf>0) return 1;
385 if (buf<0) return -1;
386 return 0;
387}
[351]388
[907]389
[297]390// process a channel: update cur_line and is_detected before and
391// add a new line to the list, if necessary
[351]392void LFAboveThreshold::processChannel(Bool detect,
393 const casa::Vector<casa::Bool> &mask) throw(casa::AipsError)
[297]394{
395 try {
[907]396 if (is_detected_before) {
397 // we have to check that the current detection has the
398 // same sign of running_box->aboveMean
399 // otherwise it could be a spurious detection
400 if (last_sign && last_sign!=getAboveMeanSign())
401 detect=False;
402 }
403 if (detect) {
404 last_sign=getAboveMeanSign();
405 if (is_detected_before)
406 cur_line.second=running_box->getChannel()+1;
407 else {
408 is_detected_before=True;
409 cur_line.first=running_box->getChannel();
410 cur_line.second=running_box->getChannel()+1;
411 }
412 } else processCurLine(mask);
[297]413 }
414 catch (const AipsError &ae) {
415 throw;
[881]416 }
[297]417 catch (const exception &ex) {
[351]418 throw AipsError(String("LFAboveThreshold::processChannel - STL error: ")+ex.what());
[297]419 }
420}
421
422// process the interval of channels stored in cur_line
423// if it satisfies the criterion, add this interval as a new line
[351]424void LFAboveThreshold::processCurLine(const casa::Vector<casa::Bool> &mask)
[331]425 throw(casa::AipsError)
[297]426{
427 try {
[881]428 if (is_detected_before) {
[297]429 if (cur_line.second-cur_line.first>min_nchan) {
430 // it was a detection. We need to change the list
431 Bool add_new_line=False;
[881]432 if (lines.size()) {
[297]433 for (int i=lines.back().second;i<cur_line.first;++i)
434 if (mask[i]) { // one valid channel in between
435 // means that we deal with a separate line
436 add_new_line=True;
437 break;
438 }
[881]439 } else add_new_line=True;
440 if (add_new_line)
[297]441 lines.push_back(cur_line);
[881]442 else lines.back().second=cur_line.second;
[297]443 }
444 is_detected_before=False;
[881]445 }
[297]446 }
447 catch (const AipsError &ae) {
448 throw;
[881]449 }
[297]450 catch (const exception &ex) {
[351]451 throw AipsError(String("LFAboveThreshold::processCurLine - STL error: ")+ex.what());
[297]452 }
453}
454
[551]455// return the array with signs of the value-current mean
456// An element is +1 if value>mean, -1 if less, 0 if equal.
457// This array is updated each time the findLines method is called and
458// is used to search the line wings
459const casa::Vector<Int>& LFAboveThreshold::getSigns() const throw()
460{
461 return signs;
462}
463
[331]464// find spectral lines and add them into list
[351]465void LFAboveThreshold::findLines(const casa::Vector<casa::Float> &spectrum,
466 const casa::Vector<casa::Bool> &mask,
467 const std::pair<int,int> &edge,
[352]468 int max_box_nchan)
[331]469 throw(casa::AipsError)
470{
471 const int minboxnchan=4;
[351]472 try {
[331]473
[351]474 if (running_box!=NULL) delete running_box;
475 running_box=new RunningBox(spectrum,mask,edge,max_box_nchan);
[368]476
[881]477
[368]478 // determine the off-line variance first
479 // an assumption made: lines occupy a small part of the spectrum
[881]480
[368]481 std::vector<float> variances(edge.second-edge.first);
482 DebugAssert(variances.size(),AipsError);
[881]483
484 for (;running_box->haveMore();running_box->next())
[368]485 variances[running_box->getChannel()-edge.first]=
486 running_box->getLinVariance();
[881]487
[368]488 // in the future we probably should do a proper Chi^2 estimation
489 // now a simple 80% of smaller values will be used.
490 // it may degrade the performance of the algorithm for weak lines
491 // due to a bias of the Chi^2 distribution.
492 stable_sort(variances.begin(),variances.end());
[881]493
[368]494 Float offline_variance=0;
[881]495 uInt offline_cnt=uInt(0.8*variances.size());
[368]496 if (!offline_cnt) offline_cnt=variances.size(); // no much else left,
497 // although it is very inaccurate
[881]498 for (uInt n=0;n<offline_cnt;++n)
499 offline_variance+=variances[n];
500 offline_variance/=Float(offline_cnt);
501
[351]502 // actual search algorithm
503 is_detected_before=False;
[368]504
[551]505 // initiate the signs array
506 signs.resize(spectrum.nelements());
507 signs=Vector<Int>(spectrum.nelements(),0);
508
[369]509 //ofstream os("dbg.dat");
[368]510 for (running_box->rewind();running_box->haveMore();
511 running_box->next()) {
[351]512 const int ch=running_box->getChannel();
513 if (running_box->getNumberOfBoxPoints()>=minboxnchan)
[352]514 processChannel(mask[ch] && (fabs(running_box->aboveMean()) >=
[368]515 threshold*offline_variance), mask);
[351]516 else processCurLine(mask); // just finish what was accumulated before
[907]517
518 signs[ch]=getAboveMeanSign();
519 // os<<ch<<" "<<spectrum[ch]<<" "<<fabs(running_box->aboveMean())<<" "<<
520 // threshold*offline_variance<<endl;
521
[352]522 const Float buf=running_box->aboveMean();
523 if (buf>0) signs[ch]=1;
524 else if (buf<0) signs[ch]=-1;
[368]525 else if (buf==0) signs[ch]=0;
[369]526 // os<<ch<<" "<<spectrum[ch]<<" "<<running_box->getLinMean()<<" "<<
527 // threshold*offline_variance<<endl;
[351]528 }
[352]529 if (lines.size())
530 searchForWings(lines,signs,mask,edge);
[344]531 }
[351]532 catch (const AipsError &ae) {
533 throw;
[881]534 }
[351]535 catch (const exception &ex) {
536 throw AipsError(String("LFAboveThreshold::findLines - STL error: ")+ex.what());
537 }
[331]538}
539
540//
541///////////////////////////////////////////////////////////////////////////////
542
[343]543///////////////////////////////////////////////////////////////////////////////
544//
[352]545// LFLineListOperations::IntersectsWith - An auxiliary object function
546// to test whether two lines have a non-void intersection
[343]547//
[331]548
[343]549
550// line1 - range of the first line: start channel and stop+1
[352]551LFLineListOperations::IntersectsWith::IntersectsWith(const std::pair<int,int> &in_line1) :
[343]552 line1(in_line1) {}
553
554
555// return true if line2 intersects with line1 with at least one
556// common channel, and false otherwise
557// line2 - range of the second line: start channel and stop+1
[352]558bool LFLineListOperations::IntersectsWith::operator()(const std::pair<int,int> &line2)
[343]559 const throw()
560{
561 if (line2.second<line1.first) return false; // line2 is at lower channels
562 if (line2.first>line1.second) return false; // line2 is at upper channels
563 return true; // line2 has an intersection or is adjacent to line1
564}
565
566//
567///////////////////////////////////////////////////////////////////////////////
568
569///////////////////////////////////////////////////////////////////////////////
570//
[352]571// LFLineListOperations::BuildUnion - An auxiliary object function to build a union
[343]572// of several lines to account for a possibility of merging the nearby lines
573//
574
575// set an initial line (can be a first line in the sequence)
[352]576LFLineListOperations::BuildUnion::BuildUnion(const std::pair<int,int> &line1) :
[343]577 temp_line(line1) {}
578
579// update temp_line with a union of temp_line and new_line
580// provided there is no gap between the lines
[352]581void LFLineListOperations::BuildUnion::operator()(const std::pair<int,int> &new_line)
[343]582 throw()
583{
584 if (new_line.first<temp_line.first) temp_line.first=new_line.first;
585 if (new_line.second>temp_line.second) temp_line.second=new_line.second;
586}
587
588// return the result (temp_line)
[352]589const std::pair<int,int>& LFLineListOperations::BuildUnion::result() const throw()
[343]590{
591 return temp_line;
592}
593
594//
595///////////////////////////////////////////////////////////////////////////////
596
597///////////////////////////////////////////////////////////////////////////////
598//
[352]599// LFLineListOperations::LaterThan - An auxiliary object function to test whether a
[343]600// specified line is at lower spectral channels (to preserve the order in
601// the line list)
602//
603
604// setup the line to compare with
[352]605LFLineListOperations::LaterThan::LaterThan(const std::pair<int,int> &in_line1) :
[343]606 line1(in_line1) {}
607
608// return true if line2 should be placed later than line1
609// in the ordered list (so, it is at greater channel numbers)
[352]610bool LFLineListOperations::LaterThan::operator()(const std::pair<int,int> &line2)
[343]611 const throw()
612{
613 if (line2.second<line1.first) return false; // line2 is at lower channels
614 if (line2.first>line1.second) return true; // line2 is at upper channels
[881]615
[343]616 // line2 intersects with line1. We should have no such situation in
617 // practice
618 return line2.first>line1.first;
619}
620
621//
622///////////////////////////////////////////////////////////////////////////////
623
624
625///////////////////////////////////////////////////////////////////////////////
626//
[881]627// STLineFinder - a class for automated spectral line search
[343]628//
629//
[331]630
[881]631STLineFinder::STLineFinder() throw() : edge(0,0)
[331]632{
[369]633 setOptions();
[331]634}
635
[369]636// set the parameters controlling algorithm
637// in_threshold a single channel threshold default is sqrt(3), which
638// means together with 3 minimum channels at least 3 sigma
639// detection criterion
640// For bad baseline shape, in_threshold may need to be
641// increased
642// in_min_nchan minimum number of channels above the threshold to report
643// a detection, default is 3
644// in_avg_limit perform the averaging of no more than in_avg_limit
645// adjacent channels to search for broad lines
[881]646// Default is 8, but for a bad baseline shape this
[369]647// parameter should be decreased (may be even down to a
648// minimum of 1 to disable this option) to avoid
649// confusing of baseline undulations with a real line.
[881]650// Setting a very large value doesn't usually provide
651// valid detections.
[369]652// in_box_size the box size for running mean calculation. Default is
653// 1./5. of the whole spectrum size
[881]654void STLineFinder::setOptions(const casa::Float &in_threshold,
[369]655 const casa::Int &in_min_nchan,
656 const casa::Int &in_avg_limit,
657 const casa::Float &in_box_size) throw()
658{
659 threshold=in_threshold;
660 min_nchan=in_min_nchan;
661 avg_limit=in_avg_limit;
662 box_size=in_box_size;
663}
664
[881]665STLineFinder::~STLineFinder() throw(AipsError) {}
[331]666
[907]667// set scan to work with (in_scan parameter)
668void STLineFinder::setScan(const ScantableWrapper &in_scan) throw(AipsError)
669{
670 scan=in_scan.getCP();
671 AlwaysAssert(!scan.null(),AipsError);
672
673}
674
675// search for spectral lines. Number of lines found is returned
676// in_edge and in_mask control channel rejection for a given row
[331]677// if in_edge has zero length, all channels chosen by mask will be used
678// if in_edge has one element only, it represents the number of
679// channels to drop from both sides of the spectrum
680// in_edge is introduced for convinience, although all functionality
[881]681// can be achieved using a spectrum mask only
[907]682int STLineFinder::findLines(const std::vector<bool> &in_mask,
683 const std::vector<int> &in_edge,
684 const casa::uInt &whichRow) throw(casa::AipsError)
[331]685{
[907]686 const int minboxnchan=4;
687 if (scan.null())
688 throw AipsError("STLineFinder::findLines - a scan should be set first,"
689 " use set_scan");
690
691 // set up mask and edge rejection
692 mask=in_mask;
693 if (mask.nelements()!=scan->nchan(whichRow))
694 throw AipsError("STLineFinder::findLines - in_scan and in_mask have different"
695 "number of spectral channels.");
[516]696
[907]697 // number of elements in in_edge
698 if (in_edge.size()>2)
699 throw AipsError("STLineFinder::findLines - the length of the in_edge parameter"
700 "should not exceed 2");
701 if (!in_edge.size()) {
[881]702 // all spectra, no rejection
[331]703 edge.first=0;
[907]704 edge.second=scan->nchan(whichRow);
705 } else {
706 edge.first=in_edge[0];
[331]707 if (edge.first<0)
[907]708 throw AipsError("STLineFinder::findLines - the in_edge parameter has a negative"
[331]709 "number of channels to drop");
[907]710 if (edge.first>=scan->nchan(whichRow))
711 throw AipsError("STLineFinder::findLines - all channels are rejected by the in_edge parameter");
712 if (in_edge.size()==2) {
713 edge.second=in_edge[1];
[331]714 if (edge.second<0)
[907]715 throw AipsError("STLineFinder::findLines - the in_edge parameter has a negative"
[331]716 "number of channels to drop");
[907]717 edge.second=scan->nchan(whichRow)-edge.second;
718 } else edge.second=scan->nchan(whichRow)-edge.first;
[369]719 if (edge.second<0 || (edge.first>=edge.second))
[907]720 throw AipsError("STLineFinder::findLines - all channels are rejected by the in_edge parameter");
[881]721 }
[907]722
723 //
724 int max_box_nchan=int(scan->nchan(whichRow)*box_size); // number of channels in running
[331]725 // box
726 if (max_box_nchan<2)
[881]727 throw AipsError("STLineFinder::findLines - box_size is too small");
[331]728
[881]729 spectrum.resize();
730 spectrum = Vector<Float>(scan->getSpectrum(whichRow));
[331]731
732 lines.resize(0); // search from the scratch
[370]733 last_row_used=whichRow;
[331]734 Vector<Bool> temp_mask(mask);
[351]735
736 Bool first_pass=True;
[368]737 Int avg_factor=1; // this number of adjacent channels is averaged together
738 // the total number of the channels is not altered
739 // instead, min_nchan is also scaled
740 // it helps to search for broad lines
[551]741 Vector<Int> signs; // a buffer for signs of the value - mean quantity
742 // see LFAboveThreshold for details
743 // We need only signs resulted from last iteration
744 // because all previous values may be corrupted by the
745 // presence of spectral lines
[344]746 while (true) {
[351]747 // a buffer for new lines found at this iteration
[881]748 std::list<pair<int,int> > new_lines;
[351]749
750 try {
[369]751 // line find algorithm
752 LFAboveThreshold lfalg(new_lines,avg_factor*min_nchan, threshold);
[352]753 lfalg.findLines(spectrum,temp_mask,edge,max_box_nchan);
[551]754 signs.resize(lfalg.getSigns().nelements());
755 signs=lfalg.getSigns();
[368]756 first_pass=False;
757 if (!new_lines.size())
758 throw AipsError("spurious"); // nothing new - use the same
759 // code as for a real exception
[351]760 }
761 catch(const AipsError &ae) {
762 if (first_pass) throw;
[368]763 // nothing new - proceed to the next step of averaging, if any
764 // (to search for broad lines)
[369]765 if (avg_factor>avg_limit) break; // averaging up to avg_limit
766 // adjacent channels,
767 // stop after that
[368]768 avg_factor*=2; // twice as more averaging
[369]769 subtractBaseline(temp_mask,9);
[368]770 averageAdjacentChannels(temp_mask,avg_factor);
[881]771 continue;
[351]772 }
[368]773 keepStrongestOnly(temp_mask,new_lines,max_box_nchan);
[343]774 // update the list (lines) merging intervals, if necessary
[344]775 addNewSearchResult(new_lines,lines);
776 // get a new mask
[881]777 temp_mask=getMask();
[343]778 }
[881]779
[551]780 // an additional search for wings because in the presence of very strong
781 // lines temporary mean used at each iteration will be higher than
782 // the true mean
[881]783
[551]784 if (lines.size())
785 LFLineListOperations::searchForWings(lines,signs,mask,edge);
[881]786
[331]787 return int(lines.size());
788}
789
[369]790// auxiliary function to fit and subtract a polynomial from the current
[890]791// spectrum. It uses the Fitter class. This action is required before
[369]792// reducing the spectral resolution if the baseline shape is bad
[881]793void STLineFinder::subtractBaseline(const casa::Vector<casa::Bool> &temp_mask,
[369]794 const casa::Int &order) throw(casa::AipsError)
795{
796 AlwaysAssert(spectrum.nelements(),AipsError);
797 // use the fact that temp_mask excludes channels rejected at the edge
[890]798 Fitter sdf;
[369]799 std::vector<float> absc(spectrum.nelements());
800 for (Int i=0;i<absc.size();++i)
801 absc[i]=float(i)/float(spectrum.nelements());
802 std::vector<float> spec;
803 spectrum.tovector(spec);
804 std::vector<bool> std_mask;
805 temp_mask.tovector(std_mask);
806 sdf.setData(absc,spec,std_mask);
807 sdf.setExpression("poly",order);
808 if (!sdf.fit()) return; // fit failed, use old spectrum
[881]809 spectrum=casa::Vector<casa::Float>(sdf.getResidual());
[369]810}
811
[368]812// auxiliary function to average adjacent channels and update the mask
813// if at least one channel involved in summation is masked, all
814// output channels will be masked. This function works with the
815// spectrum and edge fields of this class, but updates the mask
816// array specified, rather than the field of this class
817// boxsize - a number of adjacent channels to average
[881]818void STLineFinder::averageAdjacentChannels(casa::Vector<casa::Bool> &mask2update,
[368]819 const casa::Int &boxsize)
820 throw(casa::AipsError)
821{
822 DebugAssert(mask2update.nelements()==spectrum.nelements(), AipsError);
823 DebugAssert(boxsize!=0,AipsError);
[881]824
[368]825 for (int n=edge.first;n<edge.second;n+=boxsize) {
826 DebugAssert(n<spectrum.nelements(),AipsError);
827 int nboxch=0; // number of channels currently in the box
828 Float mean=0; // buffer for mean calculations
829 for (int k=n;k<n+boxsize && k<edge.second;++k)
830 if (mask2update[k]) { // k is a valid channel
831 mean+=spectrum[k];
832 ++nboxch;
[881]833 }
[368]834 if (nboxch<boxsize) // mask these channels
835 for (int k=n;k<n+boxsize && k<edge.second;++k)
836 mask2update[k]=False;
837 else {
838 mean/=Float(boxsize);
839 for (int k=n;k<n+boxsize && k<edge.second;++k)
840 spectrum[k]=mean;
841 }
842 }
843}
[331]844
[368]845
[297]846// get the mask to mask out all lines that have been found (default)
847// if invert=true, only channels belong to lines will be unmasked
848// Note: all channels originally masked by the input mask (in_mask
849// in setScan) or dropped out by the edge parameter (in_edge
850// in setScan) are still excluded regardless on the invert option
[881]851std::vector<bool> STLineFinder::getMask(bool invert)
[297]852 const throw(casa::AipsError)
853{
854 try {
855 if (scan.null())
[881]856 throw AipsError("STLineFinder::getMask - a scan should be set first,"
[297]857 " use set_scan followed by find_lines");
[907]858 DebugAssert(mask.nelements()==scan->nchan(last_row_used), AipsError);
[297]859 /*
860 if (!lines.size())
[881]861 throw AipsError("STLineFinder::getMask - one have to search for "
[297]862 "lines first, use find_lines");
[881]863 */
[297]864 std::vector<bool> res_mask(mask.nelements());
865 // iterator through lines
866 std::list<std::pair<int,int> >::const_iterator cli=lines.begin();
[881]867 for (int ch=0;ch<res_mask.size();++ch)
[297]868 if (ch<edge.first || ch>=edge.second) res_mask[ch]=false;
869 else if (!mask[ch]) res_mask[ch]=false;
[881]870 else {
[297]871 res_mask[ch]=!invert; // no line by default
872 if (cli==lines.end()) continue;
873 if (ch>=cli->first && ch<cli->second)
874 res_mask[ch]=invert; // this is a line
875 if (ch>=cli->second)
876 ++cli; // next line in the list
877 }
[881]878
[297]879 return res_mask;
880 }
881 catch (const AipsError &ae) {
882 throw;
[881]883 }
[297]884 catch (const exception &ex) {
[881]885 throw AipsError(String("STLineFinder::getMask - STL error: ")+ex.what());
[297]886 }
887}
888
[370]889// get range for all lines found. The same units as used in the scan
890// will be returned (e.g. velocity instead of channels).
[881]891std::vector<double> STLineFinder::getLineRanges()
[297]892 const throw(casa::AipsError)
893{
[370]894 // convert to required abscissa units
895 std::vector<double> vel=scan->getAbcissa(last_row_used);
896 std::vector<int> ranges=getLineRangesInChannels();
897 std::vector<double> res(ranges.size());
898
899 std::vector<int>::const_iterator cri=ranges.begin();
900 std::vector<double>::iterator outi=res.begin();
901 for (;cri!=ranges.end() && outi!=res.end();++cri,++outi)
902 if (uInt(*cri)>=vel.size())
[881]903 throw AipsError("STLineFinder::getLineRanges - getAbcissa provided less channels than reqired");
[370]904 else *outi=vel[*cri];
905 return res;
906}
907
908// The same as getLineRanges, but channels are always used to specify
909// the range
[881]910std::vector<int> STLineFinder::getLineRangesInChannels()
[370]911 const throw(casa::AipsError)
912{
[297]913 try {
914 if (scan.null())
[881]915 throw AipsError("STLineFinder::getLineRangesInChannels - a scan should be set first,"
[297]916 " use set_scan followed by find_lines");
[907]917 DebugAssert(mask.nelements()==scan->nchan(last_row_used), AipsError);
[881]918
[297]919 if (!lines.size())
[881]920 throw AipsError("STLineFinder::getLineRangesInChannels - one have to search for "
[297]921 "lines first, use find_lines");
[881]922
[297]923 std::vector<int> res(2*lines.size());
924 // iterator through lines & result
925 std::list<std::pair<int,int> >::const_iterator cli=lines.begin();
926 std::vector<int>::iterator ri=res.begin();
[881]927 for (;cli!=lines.end() && ri!=res.end();++cli,++ri) {
[297]928 *ri=cli->first;
[881]929 if (++ri!=res.end())
930 *ri=cli->second-1;
931 }
[297]932 return res;
933 }
934 catch (const AipsError &ae) {
935 throw;
[881]936 }
[297]937 catch (const exception &ex) {
[881]938 throw AipsError(String("STLineFinder::getLineRanges - STL error: ")+ex.what());
[297]939 }
940}
[331]941
[370]942
943
[368]944// an auxiliary function to remove all lines from the list, except the
945// strongest one (by absolute value). If the lines removed are real,
[881]946// they will be find again at the next iteration. This approach
947// increases the number of iterations required, but is able to remove
[368]948// the sidelobes likely to occur near strong lines.
949// Later a better criterion may be implemented, e.g.
950// taking into consideration the brightness of different lines. Now
[881]951// use the simplest solution
[368]952// temp_mask - mask to work with (may be different from original mask as
953// the lines previously found may be masked)
954// lines2update - a list of lines to work with
955// nothing will be done if it is empty
956// max_box_nchan - channels in the running box for baseline filtering
[881]957void STLineFinder::keepStrongestOnly(const casa::Vector<casa::Bool> &temp_mask,
[368]958 std::list<std::pair<int, int> > &lines2update,
959 int max_box_nchan)
960 throw (casa::AipsError)
961{
962 try {
963 if (!lines2update.size()) return; // ignore an empty list
964
965 // current line
966 std::list<std::pair<int,int> >::iterator li=lines2update.begin();
967 // strongest line
968 std::list<std::pair<int,int> >::iterator strongli=lines2update.begin();
969 // the flux (absolute value) of the strongest line
970 Float peak_flux=-1; // negative value - a flag showing uninitialized
971 // value
972 // the algorithm below relies on the list being ordered
973 Float tmp_flux=-1; // a temporary peak
974 for (RunningBox running_box(spectrum,temp_mask,edge,max_box_nchan);
975 running_box.haveMore(); running_box.next()) {
976
977 if (li==lines2update.end()) break; // no more lines
[881]978 const int ch=running_box.getChannel();
[368]979 if (ch>=li->first && ch<li->second)
980 if (temp_mask[ch] && tmp_flux<fabs(running_box.aboveMean()))
981 tmp_flux=fabs(running_box.aboveMean());
982 if (ch==li->second-1) {
983 if (peak_flux<tmp_flux) { // if peak_flux=-1, this condition
984 peak_flux=tmp_flux; // will be satisfied
985 strongli=li;
986 }
987 ++li;
988 tmp_flux=-1;
989 }
[881]990 }
[368]991 std::list<std::pair<int,int> > res;
992 res.splice(res.end(),lines2update,strongli);
993 lines2update.clear();
994 lines2update.splice(lines2update.end(),res);
995 }
996 catch (const AipsError &ae) {
997 throw;
[881]998 }
[368]999 catch (const exception &ex) {
[881]1000 throw AipsError(String("STLineFinder::keepStrongestOnly - STL error: ")+ex.what());
[368]1001 }
1002
1003}
1004
[352]1005//
1006///////////////////////////////////////////////////////////////////////////////
1007
1008
1009///////////////////////////////////////////////////////////////////////////////
1010//
1011// LFLineListOperations - a class incapsulating operations with line lists
1012// The LF prefix stands for Line Finder
1013//
1014
[331]1015// concatenate two lists preserving the order. If two lines appear to
1016// be adjacent, they are joined into the new one
[352]1017void LFLineListOperations::addNewSearchResult(const std::list<pair<int, int> > &newlines,
[881]1018 std::list<std::pair<int, int> > &lines_list)
[331]1019 throw(AipsError)
1020{
1021 try {
1022 for (std::list<pair<int,int> >::const_iterator cli=newlines.begin();
1023 cli!=newlines.end();++cli) {
[881]1024
[343]1025 // the first item, which has a non-void intersection or touches
1026 // the new line
[344]1027 std::list<pair<int,int> >::iterator pos_beg=find_if(lines_list.begin(),
[881]1028 lines_list.end(), IntersectsWith(*cli));
1029 // the last such item
[343]1030 std::list<pair<int,int> >::iterator pos_end=find_if(pos_beg,
[344]1031 lines_list.end(), not1(IntersectsWith(*cli)));
[343]1032
1033 // extract all lines which intersect or touch a new one into
1034 // a temporary buffer. This may invalidate the iterators
1035 // line_buffer may be empty, if no lines intersects with a new
1036 // one.
1037 std::list<pair<int,int> > lines_buffer;
[344]1038 lines_buffer.splice(lines_buffer.end(),lines_list, pos_beg, pos_end);
[343]1039
[881]1040 // build a union of all intersecting lines
[343]1041 pair<int,int> union_line=for_each(lines_buffer.begin(),
1042 lines_buffer.end(),BuildUnion(*cli)).result();
[881]1043
[343]1044 // search for a right place for the new line (union_line) and add
[344]1045 std::list<pair<int,int> >::iterator pos2insert=find_if(lines_list.begin(),
1046 lines_list.end(), LaterThan(union_line));
1047 lines_list.insert(pos2insert,union_line);
[331]1048 }
1049 }
1050 catch (const AipsError &ae) {
1051 throw;
[881]1052 }
[331]1053 catch (const exception &ex) {
[352]1054 throw AipsError(String("LFLineListOperations::addNewSearchResult - STL error: ")+ex.what());
[331]1055 }
1056}
[344]1057
1058// extend all line ranges to the point where a value stored in the
1059// specified vector changes (e.g. value-mean change its sign)
1060// This operation is necessary to include line wings, which are below
1061// the detection threshold. If lines becomes adjacent, they are
1062// merged together. Any masked channel stops the extension
[352]1063void LFLineListOperations::searchForWings(std::list<std::pair<int, int> > &newlines,
1064 const casa::Vector<casa::Int> &signs,
1065 const casa::Vector<casa::Bool> &mask,
1066 const std::pair<int,int> &edge) throw(casa::AipsError)
[344]1067{
1068 try {
1069 for (std::list<pair<int,int> >::iterator li=newlines.begin();
1070 li!=newlines.end();++li) {
1071 // update the left hand side
1072 for (int n=li->first-1;n>=edge.first;--n) {
1073 if (!mask[n]) break;
1074 if (signs[n]==signs[li->first] && signs[li->first])
1075 li->first=n;
[881]1076 else break;
[344]1077 }
1078 // update the right hand side
1079 for (int n=li->second;n<edge.second;++n) {
1080 if (!mask[n]) break;
1081 if (signs[n]==signs[li->second-1] && signs[li->second-1])
1082 li->second=n;
[881]1083 else break;
[344]1084 }
1085 }
1086 // need to search for possible mergers.
1087 std::list<std::pair<int, int> > result_buffer;
1088 addNewSearchResult(newlines,result_buffer);
1089 newlines.clear();
1090 newlines.splice(newlines.end(),result_buffer);
1091 }
1092 catch (const AipsError &ae) {
1093 throw;
[881]1094 }
[344]1095 catch (const exception &ex) {
[352]1096 throw AipsError(String("LFLineListOperations::extendLines - STL error: ")+ex.what());
[344]1097 }
1098}
[352]1099
1100//
1101///////////////////////////////////////////////////////////////////////////////
Note: See TracBrowser for help on using the repository browser.