source: trunk/src/SDLineFinder.cc@ 368

Last change on this file since 368 was 368, checked in by vor010, 20 years ago

SDLineFinder: work around to detect weak and broad lines
as well as to avoid creating sidelobes near strong lines due to imperfections in edge detection

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