source: trunk/src/STLineFinder.cpp@ 909

Last change on this file since 909 was 907, checked in by vor010, 19 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
Line 
1//#---------------------------------------------------------------------------
2//# STLineFinder.cc: A class for automated spectral line search
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: STLineFinder.cpp 907 2006-03-20 04:17:06Z vor010 $
30//#---------------------------------------------------------------------------
31
32
33// ASAP
34#include "STLineFinder.h"
35#include "STFitter.h"
36
37// STL
38#include <functional>
39#include <algorithm>
40#include <iostream>
41#include <fstream>
42
43using namespace asap;
44using namespace casa;
45using namespace std;
46using namespace boost::python;
47
48namespace asap {
49
50///////////////////////////////////////////////////////////////////////////////
51//
52// RunningBox - a running box calculator. This class implements
53// interations over the specified spectrum and calculates
54// running box filter statistics.
55//
56
57class RunningBox {
58 // The input data to work with. Use reference symantics to avoid
59 // an unnecessary copying
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
64
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)
71
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)
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);
92
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();
98
99 // actual number of channels in the box (max_box_nchan, if no channels
100 // are masked)
101 int getNumberOfBoxPoints() const throw();
102
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);
111
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//
135class LFAboveThreshold : protected LFLineListOperations {
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
144 casa::Float threshold; // detection threshold - the
145 // minimal signal to noise ratio
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
149 casa::Vector<Int> signs; // An array to store the signs of
150 // the value - current mean
151 // (used to search wings)
152 casa::Int last_sign; // a sign (+1, -1 or 0) of the
153 // last point of the detected line
154 //
155public:
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();
162
163 // replace the detection criterion
164 void setCriterion(int in_min_nchan, casa::Float in_threshold) throw();
165
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
172 // find spectral lines and add them into list
173 // if statholder is not NULL, the accumulate function of it will be
174 // called for each channel to save statistics
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,
180 int max_box_nchan) throw(casa::AipsError);
181
182protected:
183
184 // process a channel: update curline and is_detected before and
185 // add a new line to the list, if necessary using processCurLine()
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);
189
190 // process the interval of channels stored in curline
191 // if it satisfies the criterion, add this interval as a new line
192 void processCurLine(const casa::Vector<casa::Bool> &mask)
193 throw(casa::AipsError);
194
195 // get the sign of runningBox->aboveMean(). The RunningBox pointer
196 // should be defined
197 casa::Int getAboveMeanSign() const throw();
198};
199
200//
201///////////////////////////////////////////////////////////////////////////////
202
203} // namespace asap
204
205///////////////////////////////////////////////////////////////////////////////
206//
207// RunningBox - a running box calculator. This class implements
208// interations over the specified spectrum and calculates
209// running box filter statistics.
210//
211
212// set up the object with the references to actual data
213// and the number of channels in the running box
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) :
218 spectrum(in_spectrum), mask(in_mask), edge(in_edge),
219 max_box_nchan(in_max_box_nchan)
220{
221 rewind();
222}
223
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);
236
237 if (initial_box_ch==edge.second)
238 throw AipsError("RunningBox::rewind - too much channels are masked");
239
240 cur_channel=edge.first;
241 start_advance=initial_box_ch-max_box_nchan/2;
242}
243
244// access to the statistics
245const casa::Float& RunningBox::getLinMean() const throw(AipsError)
246{
247 DebugAssert(cur_channel<edge.second, AipsError);
248 if (need2recalculate) updateDerivativeStatistics();
249 return linmean;
250}
251
252const casa::Float& RunningBox::getLinVariance() const throw(AipsError)
253{
254 DebugAssert(cur_channel<edge.second, AipsError);
255 if (need2recalculate) updateDerivativeStatistics();
256 return linvariance;
257}
258
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
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
283void RunningBox::advanceRunningBox(int ch) throw(AipsError)
284{
285 if (ch>=edge.first && ch<edge.second)
286 if (mask[ch]) { // ch is a valid channel
287 ++box_chan_cntr;
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;
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;
299 sumf-=spectrum[ch2remove];
300 sumf2-=square(spectrum[ch2remove]);
301 sumch-=Float(ch2remove);
302 sumch2-=square(Float(ch2remove));
303 sumfch-=spectrum[ch2remove]*Float(ch2remove);
304 need2recalculate=True;
305 }
306}
307
308// next channel
309void RunningBox::next() throw(AipsError)
310{
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
315}
316
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);
328
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
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}
388
389
390// process a channel: update cur_line and is_detected before and
391// add a new line to the list, if necessary
392void LFAboveThreshold::processChannel(Bool detect,
393 const casa::Vector<casa::Bool> &mask) throw(casa::AipsError)
394{
395 try {
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);
413 }
414 catch (const AipsError &ae) {
415 throw;
416 }
417 catch (const exception &ex) {
418 throw AipsError(String("LFAboveThreshold::processChannel - STL error: ")+ex.what());
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
424void LFAboveThreshold::processCurLine(const casa::Vector<casa::Bool> &mask)
425 throw(casa::AipsError)
426{
427 try {
428 if (is_detected_before) {
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;
432 if (lines.size()) {
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 }
439 } else add_new_line=True;
440 if (add_new_line)
441 lines.push_back(cur_line);
442 else lines.back().second=cur_line.second;
443 }
444 is_detected_before=False;
445 }
446 }
447 catch (const AipsError &ae) {
448 throw;
449 }
450 catch (const exception &ex) {
451 throw AipsError(String("LFAboveThreshold::processCurLine - STL error: ")+ex.what());
452 }
453}
454
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
464// find spectral lines and add them into list
465void LFAboveThreshold::findLines(const casa::Vector<casa::Float> &spectrum,
466 const casa::Vector<casa::Bool> &mask,
467 const std::pair<int,int> &edge,
468 int max_box_nchan)
469 throw(casa::AipsError)
470{
471 const int minboxnchan=4;
472 try {
473
474 if (running_box!=NULL) delete running_box;
475 running_box=new RunningBox(spectrum,mask,edge,max_box_nchan);
476
477
478 // determine the off-line variance first
479 // an assumption made: lines occupy a small part of the spectrum
480
481 std::vector<float> variances(edge.second-edge.first);
482 DebugAssert(variances.size(),AipsError);
483
484 for (;running_box->haveMore();running_box->next())
485 variances[running_box->getChannel()-edge.first]=
486 running_box->getLinVariance();
487
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());
493
494 Float offline_variance=0;
495 uInt offline_cnt=uInt(0.8*variances.size());
496 if (!offline_cnt) offline_cnt=variances.size(); // no much else left,
497 // although it is very inaccurate
498 for (uInt n=0;n<offline_cnt;++n)
499 offline_variance+=variances[n];
500 offline_variance/=Float(offline_cnt);
501
502 // actual search algorithm
503 is_detected_before=False;
504
505 // initiate the signs array
506 signs.resize(spectrum.nelements());
507 signs=Vector<Int>(spectrum.nelements(),0);
508
509 //ofstream os("dbg.dat");
510 for (running_box->rewind();running_box->haveMore();
511 running_box->next()) {
512 const int ch=running_box->getChannel();
513 if (running_box->getNumberOfBoxPoints()>=minboxnchan)
514 processChannel(mask[ch] && (fabs(running_box->aboveMean()) >=
515 threshold*offline_variance), mask);
516 else processCurLine(mask); // just finish what was accumulated before
517
518 signs[ch]=getAboveMeanSign();
519 // os<<ch<<" "<<spectrum[ch]<<" "<<fabs(running_box->aboveMean())<<" "<<
520 // threshold*offline_variance<<endl;
521
522 const Float buf=running_box->aboveMean();
523 if (buf>0) signs[ch]=1;
524 else if (buf<0) signs[ch]=-1;
525 else if (buf==0) signs[ch]=0;
526 // os<<ch<<" "<<spectrum[ch]<<" "<<running_box->getLinMean()<<" "<<
527 // threshold*offline_variance<<endl;
528 }
529 if (lines.size())
530 searchForWings(lines,signs,mask,edge);
531 }
532 catch (const AipsError &ae) {
533 throw;
534 }
535 catch (const exception &ex) {
536 throw AipsError(String("LFAboveThreshold::findLines - STL error: ")+ex.what());
537 }
538}
539
540//
541///////////////////////////////////////////////////////////////////////////////
542
543///////////////////////////////////////////////////////////////////////////////
544//
545// LFLineListOperations::IntersectsWith - An auxiliary object function
546// to test whether two lines have a non-void intersection
547//
548
549
550// line1 - range of the first line: start channel and stop+1
551LFLineListOperations::IntersectsWith::IntersectsWith(const std::pair<int,int> &in_line1) :
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
558bool LFLineListOperations::IntersectsWith::operator()(const std::pair<int,int> &line2)
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//
571// LFLineListOperations::BuildUnion - An auxiliary object function to build a union
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)
576LFLineListOperations::BuildUnion::BuildUnion(const std::pair<int,int> &line1) :
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
581void LFLineListOperations::BuildUnion::operator()(const std::pair<int,int> &new_line)
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)
589const std::pair<int,int>& LFLineListOperations::BuildUnion::result() const throw()
590{
591 return temp_line;
592}
593
594//
595///////////////////////////////////////////////////////////////////////////////
596
597///////////////////////////////////////////////////////////////////////////////
598//
599// LFLineListOperations::LaterThan - An auxiliary object function to test whether a
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
605LFLineListOperations::LaterThan::LaterThan(const std::pair<int,int> &in_line1) :
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)
610bool LFLineListOperations::LaterThan::operator()(const std::pair<int,int> &line2)
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
615
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//
627// STLineFinder - a class for automated spectral line search
628//
629//
630
631STLineFinder::STLineFinder() throw() : edge(0,0)
632{
633 setOptions();
634}
635
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
646// Default is 8, but for a bad baseline shape this
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.
650// Setting a very large value doesn't usually provide
651// valid detections.
652// in_box_size the box size for running mean calculation. Default is
653// 1./5. of the whole spectrum size
654void STLineFinder::setOptions(const casa::Float &in_threshold,
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
665STLineFinder::~STLineFinder() throw(AipsError) {}
666
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
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
681// can be achieved using a spectrum mask only
682int STLineFinder::findLines(const std::vector<bool> &in_mask,
683 const std::vector<int> &in_edge,
684 const casa::uInt &whichRow) throw(casa::AipsError)
685{
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.");
696
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()) {
702 // all spectra, no rejection
703 edge.first=0;
704 edge.second=scan->nchan(whichRow);
705 } else {
706 edge.first=in_edge[0];
707 if (edge.first<0)
708 throw AipsError("STLineFinder::findLines - the in_edge parameter has a negative"
709 "number of channels to drop");
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];
714 if (edge.second<0)
715 throw AipsError("STLineFinder::findLines - the in_edge parameter has a negative"
716 "number of channels to drop");
717 edge.second=scan->nchan(whichRow)-edge.second;
718 } else edge.second=scan->nchan(whichRow)-edge.first;
719 if (edge.second<0 || (edge.first>=edge.second))
720 throw AipsError("STLineFinder::findLines - all channels are rejected by the in_edge parameter");
721 }
722
723 //
724 int max_box_nchan=int(scan->nchan(whichRow)*box_size); // number of channels in running
725 // box
726 if (max_box_nchan<2)
727 throw AipsError("STLineFinder::findLines - box_size is too small");
728
729 spectrum.resize();
730 spectrum = Vector<Float>(scan->getSpectrum(whichRow));
731
732 lines.resize(0); // search from the scratch
733 last_row_used=whichRow;
734 Vector<Bool> temp_mask(mask);
735
736 Bool first_pass=True;
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
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
746 while (true) {
747 // a buffer for new lines found at this iteration
748 std::list<pair<int,int> > new_lines;
749
750 try {
751 // line find algorithm
752 LFAboveThreshold lfalg(new_lines,avg_factor*min_nchan, threshold);
753 lfalg.findLines(spectrum,temp_mask,edge,max_box_nchan);
754 signs.resize(lfalg.getSigns().nelements());
755 signs=lfalg.getSigns();
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
760 }
761 catch(const AipsError &ae) {
762 if (first_pass) throw;
763 // nothing new - proceed to the next step of averaging, if any
764 // (to search for broad lines)
765 if (avg_factor>avg_limit) break; // averaging up to avg_limit
766 // adjacent channels,
767 // stop after that
768 avg_factor*=2; // twice as more averaging
769 subtractBaseline(temp_mask,9);
770 averageAdjacentChannels(temp_mask,avg_factor);
771 continue;
772 }
773 keepStrongestOnly(temp_mask,new_lines,max_box_nchan);
774 // update the list (lines) merging intervals, if necessary
775 addNewSearchResult(new_lines,lines);
776 // get a new mask
777 temp_mask=getMask();
778 }
779
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
783
784 if (lines.size())
785 LFLineListOperations::searchForWings(lines,signs,mask,edge);
786
787 return int(lines.size());
788}
789
790// auxiliary function to fit and subtract a polynomial from the current
791// spectrum. It uses the Fitter class. This action is required before
792// reducing the spectral resolution if the baseline shape is bad
793void STLineFinder::subtractBaseline(const casa::Vector<casa::Bool> &temp_mask,
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
798 Fitter sdf;
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
809 spectrum=casa::Vector<casa::Float>(sdf.getResidual());
810}
811
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
818void STLineFinder::averageAdjacentChannels(casa::Vector<casa::Bool> &mask2update,
819 const casa::Int &boxsize)
820 throw(casa::AipsError)
821{
822 DebugAssert(mask2update.nelements()==spectrum.nelements(), AipsError);
823 DebugAssert(boxsize!=0,AipsError);
824
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;
833 }
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}
844
845
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
851std::vector<bool> STLineFinder::getMask(bool invert)
852 const throw(casa::AipsError)
853{
854 try {
855 if (scan.null())
856 throw AipsError("STLineFinder::getMask - a scan should be set first,"
857 " use set_scan followed by find_lines");
858 DebugAssert(mask.nelements()==scan->nchan(last_row_used), AipsError);
859 /*
860 if (!lines.size())
861 throw AipsError("STLineFinder::getMask - one have to search for "
862 "lines first, use find_lines");
863 */
864 std::vector<bool> res_mask(mask.nelements());
865 // iterator through lines
866 std::list<std::pair<int,int> >::const_iterator cli=lines.begin();
867 for (int ch=0;ch<res_mask.size();++ch)
868 if (ch<edge.first || ch>=edge.second) res_mask[ch]=false;
869 else if (!mask[ch]) res_mask[ch]=false;
870 else {
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 }
878
879 return res_mask;
880 }
881 catch (const AipsError &ae) {
882 throw;
883 }
884 catch (const exception &ex) {
885 throw AipsError(String("STLineFinder::getMask - STL error: ")+ex.what());
886 }
887}
888
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).
891std::vector<double> STLineFinder::getLineRanges()
892 const throw(casa::AipsError)
893{
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())
903 throw AipsError("STLineFinder::getLineRanges - getAbcissa provided less channels than reqired");
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
910std::vector<int> STLineFinder::getLineRangesInChannels()
911 const throw(casa::AipsError)
912{
913 try {
914 if (scan.null())
915 throw AipsError("STLineFinder::getLineRangesInChannels - a scan should be set first,"
916 " use set_scan followed by find_lines");
917 DebugAssert(mask.nelements()==scan->nchan(last_row_used), AipsError);
918
919 if (!lines.size())
920 throw AipsError("STLineFinder::getLineRangesInChannels - one have to search for "
921 "lines first, use find_lines");
922
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();
927 for (;cli!=lines.end() && ri!=res.end();++cli,++ri) {
928 *ri=cli->first;
929 if (++ri!=res.end())
930 *ri=cli->second-1;
931 }
932 return res;
933 }
934 catch (const AipsError &ae) {
935 throw;
936 }
937 catch (const exception &ex) {
938 throw AipsError(String("STLineFinder::getLineRanges - STL error: ")+ex.what());
939 }
940}
941
942
943
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,
946// they will be find again at the next iteration. This approach
947// increases the number of iterations required, but is able to remove
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
951// use the simplest solution
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
957void STLineFinder::keepStrongestOnly(const casa::Vector<casa::Bool> &temp_mask,
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
978 const int ch=running_box.getChannel();
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 }
990 }
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;
998 }
999 catch (const exception &ex) {
1000 throw AipsError(String("STLineFinder::keepStrongestOnly - STL error: ")+ex.what());
1001 }
1002
1003}
1004
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
1015// concatenate two lists preserving the order. If two lines appear to
1016// be adjacent, they are joined into the new one
1017void LFLineListOperations::addNewSearchResult(const std::list<pair<int, int> > &newlines,
1018 std::list<std::pair<int, int> > &lines_list)
1019 throw(AipsError)
1020{
1021 try {
1022 for (std::list<pair<int,int> >::const_iterator cli=newlines.begin();
1023 cli!=newlines.end();++cli) {
1024
1025 // the first item, which has a non-void intersection or touches
1026 // the new line
1027 std::list<pair<int,int> >::iterator pos_beg=find_if(lines_list.begin(),
1028 lines_list.end(), IntersectsWith(*cli));
1029 // the last such item
1030 std::list<pair<int,int> >::iterator pos_end=find_if(pos_beg,
1031 lines_list.end(), not1(IntersectsWith(*cli)));
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;
1038 lines_buffer.splice(lines_buffer.end(),lines_list, pos_beg, pos_end);
1039
1040 // build a union of all intersecting lines
1041 pair<int,int> union_line=for_each(lines_buffer.begin(),
1042 lines_buffer.end(),BuildUnion(*cli)).result();
1043
1044 // search for a right place for the new line (union_line) and add
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);
1048 }
1049 }
1050 catch (const AipsError &ae) {
1051 throw;
1052 }
1053 catch (const exception &ex) {
1054 throw AipsError(String("LFLineListOperations::addNewSearchResult - STL error: ")+ex.what());
1055 }
1056}
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
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)
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;
1076 else break;
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;
1083 else break;
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;
1094 }
1095 catch (const exception &ex) {
1096 throw AipsError(String("LFLineListOperations::extendLines - STL error: ")+ex.what());
1097 }
1098}
1099
1100//
1101///////////////////////////////////////////////////////////////////////////////
Note: See TracBrowser for help on using the repository browser.