source: trunk/src/STLineFinder.cpp@ 1642

Last change on this file since 1642 was 1642, checked in by Max Voronkov, 16 years ago

added a new helper class to the line finder (compilable, but not yet used). It will allow to improve line finder by adding more options of noise estimation

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 50.1 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 1642 2009-10-02 14:13:24Z MaximVoronkov $
[297]30//#---------------------------------------------------------------------------
31
32
33// ASAP
[894]34#include "STLineFinder.h"
35#include "STFitter.h"
[1642]36#include "IndexedCompare.h"
[297]37
38// STL
[343]39#include <functional>
40#include <algorithm>
[297]41#include <iostream>
[351]42#include <fstream>
[297]43
44using namespace asap;
45using namespace casa;
46using namespace std;
47
[344]48namespace asap {
49
[343]50///////////////////////////////////////////////////////////////////////////////
51//
[881]52// RunningBox - a running box calculator. This class implements
[1315]53// iterations over the specified spectrum and calculates
[351]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
[996]84 // masking)
[351]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,
[996]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
[996]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
[996]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,
[996]160 casa::Float in_threshold = 5) throw();
[351]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,
[996]178 const casa::Vector<casa::Bool> &mask,
179 const std::pair<int,int> &edge,
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);
[924]194
[907]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
[1642]203///////////////////////////////////////////////////////////////////////////////
204//
205// LFNoiseEstimator a helper class designed to estimate off-line variance
206// using statistics depending on the distribution of
207// values (e.g. like a median)
208//
209// Two statistics are supported: median and an average of
210// 80% of smallest values.
211//
212
213struct LFNoiseEstimator {
214 // construct an object
215 // size - maximum sample size. After a size number of elements is processed
216 // any new samples would cause the algorithm to drop the oldest samples in the
217 // buffer.
218 explicit LFNoiseEstimator(size_t size);
219
220 // add a new sample
221 // in - the new value
222 void add(float in);
223
224 // median of the distribution
225 float median() const;
226
227 // mean of lowest 80% of the samples
228 float meanLowest80Percent() const;
229
230protected:
231 // update cache of sorted indices
232 // (it is assumed that itsSampleNumber points to the newly
233 // replaced element)
234 void updateSortedCache() const;
235
236 // build sorted cache from the scratch
237 void buildSortedCache() const;
238
239 // number of samples accumulated so far
240 // (can be less than the buffer size)
241 size_t numberOfSamples() const;
242
243 // this helper method builds the cache if
244 // necessary using one of the methods
245 void fillCacheIfNecessary() const;
246
247private:
248 // buffer with samples (unsorted)
249 std::vector<float> itsVariances;
250 // current sample number (<=itsVariances.size())
251 size_t itsSampleNumber;
252 // true, if the buffer all values in the sample buffer are used
253 bool itsBufferFull;
254 // cached indices into vector of samples
255 mutable std::vector<size_t> itsSortedIndices;
256 // true if any of the statistics have been obtained at least
257 // once. This flag allows to implement a more efficient way of
258 // calculating statistics, if they are needed at once and not
259 // after each addition of a new element
260 mutable bool itsStatisticsAccessed;
261};
262
263//
264///////////////////////////////////////////////////////////////////////////////
265
266
[331]267} // namespace asap
[297]268
[344]269///////////////////////////////////////////////////////////////////////////////
[343]270//
[1642]271// LFNoiseEstimator a helper class designed to estimate off-line variance
272// using statistics depending on the distribution of
273// values (e.g. like a median)
274//
275// Two statistics are supported: median and an average of
276// 80% of smallest values.
277//
278
279// construct an object
280// size - maximum sample size. After a size number of elements is processed
281// any new samples would cause the algorithm to drop the oldest samples in the
282// buffer.
283LFNoiseEstimator::LFNoiseEstimator(size_t size) : itsVariances(size),
284 itsSampleNumber(0), itsBufferFull(false), itsSortedIndices(size),
285 itsStatisticsAccessed(false)
286{
287 AlwaysAssert(size>0,AipsError);
288}
289
290
291// add a new sample
292// in - the new value
293void LFNoiseEstimator::add(float in)
294{
295 itsVariances[itsSampleNumber] = in;
296
297 if (itsStatisticsAccessed) {
298 // only do element by element addition if on-the-fly
299 // statistics are needed
300 updateSortedCache();
301 }
302
303 // advance itsSampleNumber now
304 ++itsSampleNumber;
305 if (itsSampleNumber == itsVariances.size()) {
306 itsSampleNumber = 0;
307 itsBufferFull = true;
308 }
309 AlwaysAssert(itsSampleNumber<itsVariances.size(),AipsError);
310}
311
312// number of samples accumulated so far
313// (can be less than the buffer size)
314size_t LFNoiseEstimator::numberOfSamples() const
315{
316 // the number of samples accumulated so far may be less than the
317 // buffer size
318 const size_t nSamples = itsBufferFull ? itsVariances.size(): itsSampleNumber;
319 AlwaysAssert( (nSamples > 0) && (nSamples < itsVariances.size()), AipsError);
320 return nSamples;
321}
322
323// this helper method builds the cache if
324// necessary using one of the methods
325void LFNoiseEstimator::fillCacheIfNecessary() const
326{
327 if (!itsStatisticsAccessed) {
328 if ((itsSampleNumber!=0) || itsBufferFull) {
329 // build the whole cache efficiently
330 buildSortedCache();
331 } else {
332 updateSortedCache();
333 }
334 itsStatisticsAccessed = true;
335 } // otherwise, it is updated in 'add' using on-the-fly method
336}
337
338// median of the distribution
339float LFNoiseEstimator::median() const
340{
341 fillCacheIfNecessary();
342 // the number of samples accumulated so far may be less than the
343 // buffer size
344 const size_t nSamples = numberOfSamples();
345 const size_t medSample = nSamples / 2;
346 AlwaysAssert(medSample < itsSortedIndices.size(), AipsError);
347 return itsVariances[itsSortedIndices[medSample]];
348}
349
350// mean of lowest 80% of the samples
351float LFNoiseEstimator::meanLowest80Percent() const
352{
353 fillCacheIfNecessary();
354 // the number of samples accumulated so far may be less than the
355 // buffer size
356 const size_t nSamples = numberOfSamples();
357 float result = 0;
358 size_t numpt=size_t(0.8*nSamples);
359 if (!numpt) {
360 numpt=nSamples; // no much else left,
361 // although it is very inaccurate
362 }
363 AlwaysAssert( (numpt > 0) && (numpt<itsSortedIndices.size()), AipsError);
364 for (size_t ch=0; ch<numpt; ++ch) {
365 result += itsVariances[itsSortedIndices[ch]];
366 }
367 result /= float(numpt);
368 return result;
369}
370
371// update cache of sorted indices
372// (it is assumed that itsSampleNumber points to the newly
373// replaced element)
374void LFNoiseEstimator::updateSortedCache() const
375{
376 // the number of samples accumulated so far may be less than the
377 // buffer size
378 const size_t nSamples = numberOfSamples();
379
380 if (itsBufferFull) {
381 // first find the index of the element which is being replaced
382 size_t index = nSamples;
383 for (size_t i=0; i<nSamples; ++i) {
384 AlwaysAssert(i < itsSortedIndices.size(), AipsError);
385 if (itsSortedIndices[i] == itsSampleNumber) {
386 index = i;
387 break;
388 }
389 }
390 AlwaysAssert( index < nSamples, AipsError);
391
392 const vector<size_t>::iterator indStart = itsSortedIndices.begin();
393 // merge this element with preceeding block first
394 if (index != 0) {
395 // merge indices on the basis of variances
396 inplace_merge(indStart,indStart+index,indStart+index+1,
397 indexedCompare<size_t>(itsVariances.begin()));
398 }
399 // merge with the following block
400 if (index + 1 != nSamples) {
401 // merge indices on the basis of variances
402 inplace_merge(indStart,indStart+index+1,indStart+nSamples,
403 indexedCompare<size_t>(itsVariances.begin()));
404 }
405 } else {
406 // itsSampleNumber is the index of the new element
407 AlwaysAssert(itsSampleNumber < itsSortedIndices.size(), AipsError);
408 itsSortedIndices[itsSampleNumber] = itsSampleNumber;
409 if (itsSampleNumber >= 1) {
410 // we have to place this new sample in
411 const vector<size_t>::iterator indStart = itsSortedIndices.begin();
412 // merge indices on the basis of variances
413 inplace_merge(indStart,indStart+itsSampleNumber,indStart+itsSampleNumber+1,
414 indexedCompare<size_t>(itsVariances.begin()));
415 }
416 }
417}
418
419// build sorted cache from the scratch
420void LFNoiseEstimator::buildSortedCache() const
421{
422 // the number of samples accumulated so far may be less than the
423 // buffer size
424 const size_t nSamples = numberOfSamples();
425 AlwaysAssert(nSamples < itsSortedIndices.size(), AipsError);
426 for (size_t i=0; i<nSamples; ++i) {
427 itsSortedIndices[i]=i;
428 }
429
430 // sort indices, but check the array of variances
431 const vector<size_t>::iterator indStart = itsSortedIndices.begin();
432 stable_sort(indStart,indStart+nSamples, indexedCompare<size_t>(itsVariances.begin()));
433}
434
435//
436///////////////////////////////////////////////////////////////////////////////
437
438///////////////////////////////////////////////////////////////////////////////
439//
[881]440// RunningBox - a running box calculator. This class implements
[351]441// interations over the specified spectrum and calculates
442// running box filter statistics.
[331]443//
[297]444
[331]445// set up the object with the references to actual data
446// and the number of channels in the running box
[351]447RunningBox::RunningBox(const casa::Vector<casa::Float> &in_spectrum,
448 const casa::Vector<casa::Bool> &in_mask,
[996]449 const std::pair<int,int> &in_edge,
450 int in_max_box_nchan) throw(AipsError) :
[331]451 spectrum(in_spectrum), mask(in_mask), edge(in_edge),
[996]452 max_box_nchan(in_max_box_nchan)
[351]453{
454 rewind();
455}
[331]456
[351]457void RunningBox::rewind() throw(AipsError) {
458 // fill statistics for initial box
459 box_chan_cntr=0; // no channels are currently in the box
460 sumf=0.; // initialize statistics
461 sumf2=0.;
462 sumch=0.;
463 sumch2=0.;
464 sumfch=0.;
465 int initial_box_ch=edge.first;
466 for (;initial_box_ch<edge.second && box_chan_cntr<max_box_nchan;
467 ++initial_box_ch)
468 advanceRunningBox(initial_box_ch);
[881]469
470 if (initial_box_ch==edge.second)
[351]471 throw AipsError("RunningBox::rewind - too much channels are masked");
472
473 cur_channel=edge.first;
[881]474 start_advance=initial_box_ch-max_box_nchan/2;
[351]475}
476
477// access to the statistics
478const casa::Float& RunningBox::getLinMean() const throw(AipsError)
[331]479{
[351]480 DebugAssert(cur_channel<edge.second, AipsError);
481 if (need2recalculate) updateDerivativeStatistics();
482 return linmean;
[297]483}
484
[351]485const casa::Float& RunningBox::getLinVariance() const throw(AipsError)
486{
487 DebugAssert(cur_channel<edge.second, AipsError);
488 if (need2recalculate) updateDerivativeStatistics();
489 return linvariance;
490}
[331]491
[351]492const casa::Float RunningBox::aboveMean() const throw(AipsError)
493{
494 DebugAssert(cur_channel<edge.second, AipsError);
495 if (need2recalculate) updateDerivativeStatistics();
496 return spectrum[cur_channel]-linmean;
497}
498
499int RunningBox::getChannel() const throw()
500{
501 return cur_channel;
502}
503
504// actual number of channels in the box (max_box_nchan, if no channels
505// are masked)
506int RunningBox::getNumberOfBoxPoints() const throw()
507{
508 return box_chan_cntr;
509}
510
[297]511// supplementary function to control running mean calculations.
512// It adds a specified channel to the running mean box and
513// removes (ch-max_box_nchan+1)'th channel from there
514// Channels, for which the mask is false or index is beyond the
515// allowed range, are ignored
[351]516void RunningBox::advanceRunningBox(int ch) throw(AipsError)
[297]517{
518 if (ch>=edge.first && ch<edge.second)
519 if (mask[ch]) { // ch is a valid channel
520 ++box_chan_cntr;
[351]521 sumf+=spectrum[ch];
522 sumf2+=square(spectrum[ch]);
[996]523 sumch+=Float(ch);
524 sumch2+=square(Float(ch));
525 sumfch+=spectrum[ch]*Float(ch);
526 need2recalculate=True;
[297]527 }
528 int ch2remove=ch-max_box_nchan;
529 if (ch2remove>=edge.first && ch2remove<edge.second)
530 if (mask[ch2remove]) { // ch2remove is a valid channel
531 --box_chan_cntr;
[351]532 sumf-=spectrum[ch2remove];
[881]533 sumf2-=square(spectrum[ch2remove]);
[996]534 sumch-=Float(ch2remove);
535 sumch2-=square(Float(ch2remove));
536 sumfch-=spectrum[ch2remove]*Float(ch2remove);
537 need2recalculate=True;
[297]538 }
539}
540
[351]541// next channel
542void RunningBox::next() throw(AipsError)
[297]543{
[351]544 AlwaysAssert(cur_channel<edge.second,AipsError);
545 ++cur_channel;
546 if (cur_channel+max_box_nchan/2<edge.second && cur_channel>=start_advance)
547 advanceRunningBox(cur_channel+max_box_nchan/2); // update statistics
[297]548}
549
[351]550// checking whether there are still elements
551casa::Bool RunningBox::haveMore() const throw()
552{
553 return cur_channel<edge.second;
554}
555
556// calculate derivative statistics. This function is const, because
557// it updates the cache only
558void RunningBox::updateDerivativeStatistics() const throw(AipsError)
559{
560 AlwaysAssert(box_chan_cntr, AipsError);
[881]561
[351]562 Float mean=sumf/Float(box_chan_cntr);
563
564 // linear LSF formulae
565 Float meanch=sumch/Float(box_chan_cntr);
566 Float meanch2=sumch2/Float(box_chan_cntr);
567 if (meanch==meanch2 || box_chan_cntr<3) {
568 // vertical line in the spectrum, can't calculate linmean and linvariance
569 linmean=0.;
570 linvariance=0.;
571 } else {
572 Float coeff=(sumfch/Float(box_chan_cntr)-meanch*mean)/
573 (meanch2-square(meanch));
574 linmean=coeff*(Float(cur_channel)-meanch)+mean;
575 linvariance=sqrt(sumf2/Float(box_chan_cntr)-square(mean)-
576 square(coeff)*(meanch2-square(meanch)));
577 }
578 need2recalculate=False;
579}
580
581
582//
583///////////////////////////////////////////////////////////////////////////////
584
585///////////////////////////////////////////////////////////////////////////////
586//
587// LFAboveThreshold - a running mean algorithm for line detection
588//
589//
590
591
592// set up the detection criterion
593LFAboveThreshold::LFAboveThreshold(std::list<pair<int,int> > &in_lines,
594 int in_min_nchan,
595 casa::Float in_threshold) throw() :
596 min_nchan(in_min_nchan), threshold(in_threshold),
[996]597 lines(in_lines), running_box(NULL) {}
[351]598
599LFAboveThreshold::~LFAboveThreshold() throw()
600{
601 if (running_box!=NULL) delete running_box;
602}
603
604// replace the detection criterion
605void LFAboveThreshold::setCriterion(int in_min_nchan, casa::Float in_threshold)
606 throw()
607{
608 min_nchan=in_min_nchan;
609 threshold=in_threshold;
610}
611
[907]612// get the sign of runningBox->aboveMean(). The RunningBox pointer
613// should be defined
614casa::Int LFAboveThreshold::getAboveMeanSign() const throw()
615{
616 const Float buf=running_box->aboveMean();
617 if (buf>0) return 1;
618 if (buf<0) return -1;
619 return 0;
620}
[351]621
[907]622
[297]623// process a channel: update cur_line and is_detected before and
624// add a new line to the list, if necessary
[351]625void LFAboveThreshold::processChannel(Bool detect,
626 const casa::Vector<casa::Bool> &mask) throw(casa::AipsError)
[297]627{
628 try {
[907]629 if (is_detected_before) {
630 // we have to check that the current detection has the
631 // same sign of running_box->aboveMean
632 // otherwise it could be a spurious detection
633 if (last_sign && last_sign!=getAboveMeanSign())
634 detect=False;
[1315]635 }
636 if (detect) {
637 last_sign=getAboveMeanSign();
638 if (is_detected_before)
639 cur_line.second=running_box->getChannel()+1;
640 else {
641 is_detected_before=True;
642 cur_line.first=running_box->getChannel();
643 cur_line.second=running_box->getChannel()+1;
644 }
645 } else processCurLine(mask);
[297]646 }
647 catch (const AipsError &ae) {
648 throw;
[881]649 }
[297]650 catch (const exception &ex) {
[351]651 throw AipsError(String("LFAboveThreshold::processChannel - STL error: ")+ex.what());
[297]652 }
653}
654
655// process the interval of channels stored in cur_line
656// if it satisfies the criterion, add this interval as a new line
[351]657void LFAboveThreshold::processCurLine(const casa::Vector<casa::Bool> &mask)
[331]658 throw(casa::AipsError)
[297]659{
660 try {
[881]661 if (is_detected_before) {
[1315]662 if (cur_line.second-cur_line.first>=min_nchan) {
[996]663 // it was a detection. We need to change the list
664 Bool add_new_line=False;
665 if (lines.size()) {
666 for (int i=lines.back().second;i<cur_line.first;++i)
667 if (mask[i]) { // one valid channel in between
668 // means that we deal with a separate line
669 add_new_line=True;
670 break;
671 }
672 } else add_new_line=True;
673 if (add_new_line)
674 lines.push_back(cur_line);
[881]675 else lines.back().second=cur_line.second;
[996]676 }
677 is_detected_before=False;
[881]678 }
[297]679 }
680 catch (const AipsError &ae) {
681 throw;
[881]682 }
[297]683 catch (const exception &ex) {
[351]684 throw AipsError(String("LFAboveThreshold::processCurLine - STL error: ")+ex.what());
[297]685 }
686}
687
[551]688// return the array with signs of the value-current mean
689// An element is +1 if value>mean, -1 if less, 0 if equal.
690// This array is updated each time the findLines method is called and
691// is used to search the line wings
692const casa::Vector<Int>& LFAboveThreshold::getSigns() const throw()
693{
694 return signs;
695}
696
[331]697// find spectral lines and add them into list
[351]698void LFAboveThreshold::findLines(const casa::Vector<casa::Float> &spectrum,
[996]699 const casa::Vector<casa::Bool> &mask,
700 const std::pair<int,int> &edge,
701 int max_box_nchan)
[331]702 throw(casa::AipsError)
703{
704 const int minboxnchan=4;
[351]705 try {
[331]706
[351]707 if (running_box!=NULL) delete running_box;
708 running_box=new RunningBox(spectrum,mask,edge,max_box_nchan);
[368]709
710 // determine the off-line variance first
711 // an assumption made: lines occupy a small part of the spectrum
[881]712
[368]713 std::vector<float> variances(edge.second-edge.first);
714 DebugAssert(variances.size(),AipsError);
[881]715
716 for (;running_box->haveMore();running_box->next())
[368]717 variances[running_box->getChannel()-edge.first]=
[996]718 running_box->getLinVariance();
[881]719
[368]720 // in the future we probably should do a proper Chi^2 estimation
721 // now a simple 80% of smaller values will be used.
722 // it may degrade the performance of the algorithm for weak lines
723 // due to a bias of the Chi^2 distribution.
724 stable_sort(variances.begin(),variances.end());
[881]725
[368]726 Float offline_variance=0;
[881]727 uInt offline_cnt=uInt(0.8*variances.size());
[368]728 if (!offline_cnt) offline_cnt=variances.size(); // no much else left,
729 // although it is very inaccurate
[881]730 for (uInt n=0;n<offline_cnt;++n)
731 offline_variance+=variances[n];
732 offline_variance/=Float(offline_cnt);
733
[351]734 // actual search algorithm
735 is_detected_before=False;
[368]736
[551]737 // initiate the signs array
738 signs.resize(spectrum.nelements());
739 signs=Vector<Int>(spectrum.nelements(),0);
740
[369]741 //ofstream os("dbg.dat");
[368]742 for (running_box->rewind();running_box->haveMore();
743 running_box->next()) {
[351]744 const int ch=running_box->getChannel();
745 if (running_box->getNumberOfBoxPoints()>=minboxnchan)
[996]746 processChannel(mask[ch] && (fabs(running_box->aboveMean()) >=
747 threshold*offline_variance), mask);
748 else processCurLine(mask); // just finish what was accumulated before
[907]749
[996]750 signs[ch]=getAboveMeanSign();
[1641]751 //os<<ch<<" "<<spectrum[ch]<<" "<<fabs(running_box->aboveMean())<<" "<<
752 //threshold*offline_variance<<endl;
[351]753 }
[352]754 if (lines.size())
755 searchForWings(lines,signs,mask,edge);
[344]756 }
[351]757 catch (const AipsError &ae) {
758 throw;
[881]759 }
[351]760 catch (const exception &ex) {
761 throw AipsError(String("LFAboveThreshold::findLines - STL error: ")+ex.what());
762 }
[331]763}
764
765//
766///////////////////////////////////////////////////////////////////////////////
767
[343]768///////////////////////////////////////////////////////////////////////////////
769//
[352]770// LFLineListOperations::IntersectsWith - An auxiliary object function
771// to test whether two lines have a non-void intersection
[343]772//
[331]773
[343]774
775// line1 - range of the first line: start channel and stop+1
[352]776LFLineListOperations::IntersectsWith::IntersectsWith(const std::pair<int,int> &in_line1) :
[343]777 line1(in_line1) {}
778
779
780// return true if line2 intersects with line1 with at least one
781// common channel, and false otherwise
782// line2 - range of the second line: start channel and stop+1
[352]783bool LFLineListOperations::IntersectsWith::operator()(const std::pair<int,int> &line2)
[343]784 const throw()
785{
786 if (line2.second<line1.first) return false; // line2 is at lower channels
787 if (line2.first>line1.second) return false; // line2 is at upper channels
788 return true; // line2 has an intersection or is adjacent to line1
789}
790
791//
792///////////////////////////////////////////////////////////////////////////////
793
794///////////////////////////////////////////////////////////////////////////////
795//
[352]796// LFLineListOperations::BuildUnion - An auxiliary object function to build a union
[343]797// of several lines to account for a possibility of merging the nearby lines
798//
799
800// set an initial line (can be a first line in the sequence)
[352]801LFLineListOperations::BuildUnion::BuildUnion(const std::pair<int,int> &line1) :
[343]802 temp_line(line1) {}
803
804// update temp_line with a union of temp_line and new_line
805// provided there is no gap between the lines
[352]806void LFLineListOperations::BuildUnion::operator()(const std::pair<int,int> &new_line)
[343]807 throw()
808{
809 if (new_line.first<temp_line.first) temp_line.first=new_line.first;
810 if (new_line.second>temp_line.second) temp_line.second=new_line.second;
811}
812
813// return the result (temp_line)
[352]814const std::pair<int,int>& LFLineListOperations::BuildUnion::result() const throw()
[343]815{
816 return temp_line;
817}
818
819//
820///////////////////////////////////////////////////////////////////////////////
821
822///////////////////////////////////////////////////////////////////////////////
823//
[352]824// LFLineListOperations::LaterThan - An auxiliary object function to test whether a
[343]825// specified line is at lower spectral channels (to preserve the order in
826// the line list)
827//
828
829// setup the line to compare with
[352]830LFLineListOperations::LaterThan::LaterThan(const std::pair<int,int> &in_line1) :
[343]831 line1(in_line1) {}
832
833// return true if line2 should be placed later than line1
834// in the ordered list (so, it is at greater channel numbers)
[352]835bool LFLineListOperations::LaterThan::operator()(const std::pair<int,int> &line2)
[343]836 const throw()
837{
838 if (line2.second<line1.first) return false; // line2 is at lower channels
839 if (line2.first>line1.second) return true; // line2 is at upper channels
[881]840
[343]841 // line2 intersects with line1. We should have no such situation in
842 // practice
843 return line2.first>line1.first;
844}
845
846//
847///////////////////////////////////////////////////////////////////////////////
848
849
850///////////////////////////////////////////////////////////////////////////////
851//
[881]852// STLineFinder - a class for automated spectral line search
[343]853//
854//
[331]855
[881]856STLineFinder::STLineFinder() throw() : edge(0,0)
[331]857{
[369]858 setOptions();
[331]859}
860
[369]861// set the parameters controlling algorithm
862// in_threshold a single channel threshold default is sqrt(3), which
863// means together with 3 minimum channels at least 3 sigma
864// detection criterion
865// For bad baseline shape, in_threshold may need to be
866// increased
867// in_min_nchan minimum number of channels above the threshold to report
868// a detection, default is 3
869// in_avg_limit perform the averaging of no more than in_avg_limit
870// adjacent channels to search for broad lines
[881]871// Default is 8, but for a bad baseline shape this
[369]872// parameter should be decreased (may be even down to a
873// minimum of 1 to disable this option) to avoid
874// confusing of baseline undulations with a real line.
[881]875// Setting a very large value doesn't usually provide
876// valid detections.
[369]877// in_box_size the box size for running mean calculation. Default is
878// 1./5. of the whole spectrum size
[881]879void STLineFinder::setOptions(const casa::Float &in_threshold,
[369]880 const casa::Int &in_min_nchan,
[996]881 const casa::Int &in_avg_limit,
[369]882 const casa::Float &in_box_size) throw()
883{
884 threshold=in_threshold;
885 min_nchan=in_min_nchan;
886 avg_limit=in_avg_limit;
887 box_size=in_box_size;
888}
889
[881]890STLineFinder::~STLineFinder() throw(AipsError) {}
[331]891
[907]892// set scan to work with (in_scan parameter)
893void STLineFinder::setScan(const ScantableWrapper &in_scan) throw(AipsError)
894{
895 scan=in_scan.getCP();
896 AlwaysAssert(!scan.null(),AipsError);
[924]897
[907]898}
899
900// search for spectral lines. Number of lines found is returned
901// in_edge and in_mask control channel rejection for a given row
[331]902// if in_edge has zero length, all channels chosen by mask will be used
903// if in_edge has one element only, it represents the number of
904// channels to drop from both sides of the spectrum
905// in_edge is introduced for convinience, although all functionality
[881]906// can be achieved using a spectrum mask only
[907]907int STLineFinder::findLines(const std::vector<bool> &in_mask,
[996]908 const std::vector<int> &in_edge,
909 const casa::uInt &whichRow) throw(casa::AipsError)
[331]910{
[996]911 //const int minboxnchan=4;
[907]912 if (scan.null())
913 throw AipsError("STLineFinder::findLines - a scan should be set first,"
914 " use set_scan");
[924]915
916 uInt nchan = scan->nchan(scan->getIF(whichRow));
[907]917 // set up mask and edge rejection
[924]918 // no mask given...
919 if (in_mask.size() == 0) {
920 mask = Vector<Bool>(nchan,True);
921 } else {
922 // use provided mask
923 mask=Vector<Bool>(in_mask);
924 }
925 if (mask.nelements()!=nchan)
[907]926 throw AipsError("STLineFinder::findLines - in_scan and in_mask have different"
927 "number of spectral channels.");
[1641]928
929 // taking flagged channels into account
930 vector<bool> flaggedChannels = scan->getMask(whichRow);
931 if (flaggedChannels.size()) {
932 // there is a mask set for this row
933 if (flaggedChannels.size() != mask.nelements()) {
934 throw AipsError("STLineFinder::findLines - internal inconsistency: number of mask elements do not match the number of channels");
935 }
936 for (size_t ch = 0; ch<mask.nelements(); ++ch) {
937 mask[ch] &= flaggedChannels[ch];
938 }
939 }
940
[907]941 // number of elements in in_edge
942 if (in_edge.size()>2)
943 throw AipsError("STLineFinder::findLines - the length of the in_edge parameter"
[996]944 "should not exceed 2");
[907]945 if (!in_edge.size()) {
[881]946 // all spectra, no rejection
[331]947 edge.first=0;
[996]948 edge.second=nchan;
[907]949 } else {
950 edge.first=in_edge[0];
[996]951 if (edge.first<0)
952 throw AipsError("STLineFinder::findLines - the in_edge parameter has a negative"
953 "number of channels to drop");
954 if (edge.first>=int(nchan))
955 throw AipsError("STLineFinder::findLines - all channels are rejected by the in_edge parameter");
[907]956 if (in_edge.size()==2) {
[996]957 edge.second=in_edge[1];
958 if (edge.second<0)
959 throw AipsError("STLineFinder::findLines - the in_edge parameter has a negative"
960 "number of channels to drop");
[924]961 edge.second=nchan-edge.second;
[996]962 } else edge.second=nchan-edge.first;
[369]963 if (edge.second<0 || (edge.first>=edge.second))
[996]964 throw AipsError("STLineFinder::findLines - all channels are rejected by the in_edge parameter");
[881]965 }
[924]966
[907]967 //
[924]968 int max_box_nchan=int(nchan*box_size); // number of channels in running
[331]969 // box
970 if (max_box_nchan<2)
[881]971 throw AipsError("STLineFinder::findLines - box_size is too small");
[331]972
[881]973 spectrum.resize();
974 spectrum = Vector<Float>(scan->getSpectrum(whichRow));
[331]975
976 lines.resize(0); // search from the scratch
[370]977 last_row_used=whichRow;
[331]978 Vector<Bool> temp_mask(mask);
[351]979
980 Bool first_pass=True;
[368]981 Int avg_factor=1; // this number of adjacent channels is averaged together
982 // the total number of the channels is not altered
[996]983 // instead, min_nchan is also scaled
984 // it helps to search for broad lines
[551]985 Vector<Int> signs; // a buffer for signs of the value - mean quantity
986 // see LFAboveThreshold for details
[996]987 // We need only signs resulted from last iteration
988 // because all previous values may be corrupted by the
989 // presence of spectral lines
[344]990 while (true) {
[351]991 // a buffer for new lines found at this iteration
[881]992 std::list<pair<int,int> > new_lines;
[351]993
994 try {
[369]995 // line find algorithm
996 LFAboveThreshold lfalg(new_lines,avg_factor*min_nchan, threshold);
[352]997 lfalg.findLines(spectrum,temp_mask,edge,max_box_nchan);
[996]998 signs.resize(lfalg.getSigns().nelements());
999 signs=lfalg.getSigns();
[368]1000 first_pass=False;
1001 if (!new_lines.size())
[996]1002 throw AipsError("spurious"); // nothing new - use the same
1003 // code as for a real exception
[351]1004 }
1005 catch(const AipsError &ae) {
1006 if (first_pass) throw;
[368]1007 // nothing new - proceed to the next step of averaging, if any
[996]1008 // (to search for broad lines)
[1315]1009 if (avg_factor>=avg_limit) break; // averaging up to avg_limit
[996]1010 // adjacent channels,
1011 // stop after that
1012 avg_factor*=2; // twice as more averaging
1013 subtractBaseline(temp_mask,9);
1014 averageAdjacentChannels(temp_mask,avg_factor);
1015 continue;
[1315]1016 }
[368]1017 keepStrongestOnly(temp_mask,new_lines,max_box_nchan);
[343]1018 // update the list (lines) merging intervals, if necessary
[344]1019 addNewSearchResult(new_lines,lines);
1020 // get a new mask
[881]1021 temp_mask=getMask();
[343]1022 }
[881]1023
[551]1024 // an additional search for wings because in the presence of very strong
1025 // lines temporary mean used at each iteration will be higher than
1026 // the true mean
[881]1027
[551]1028 if (lines.size())
1029 LFLineListOperations::searchForWings(lines,signs,mask,edge);
[881]1030
[331]1031 return int(lines.size());
1032}
1033
[369]1034// auxiliary function to fit and subtract a polynomial from the current
[890]1035// spectrum. It uses the Fitter class. This action is required before
[369]1036// reducing the spectral resolution if the baseline shape is bad
[881]1037void STLineFinder::subtractBaseline(const casa::Vector<casa::Bool> &temp_mask,
[369]1038 const casa::Int &order) throw(casa::AipsError)
1039{
1040 AlwaysAssert(spectrum.nelements(),AipsError);
1041 // use the fact that temp_mask excludes channels rejected at the edge
[890]1042 Fitter sdf;
[369]1043 std::vector<float> absc(spectrum.nelements());
[996]1044 for (unsigned int i=0;i<absc.size();++i)
[369]1045 absc[i]=float(i)/float(spectrum.nelements());
1046 std::vector<float> spec;
1047 spectrum.tovector(spec);
1048 std::vector<bool> std_mask;
1049 temp_mask.tovector(std_mask);
1050 sdf.setData(absc,spec,std_mask);
1051 sdf.setExpression("poly",order);
1052 if (!sdf.fit()) return; // fit failed, use old spectrum
[881]1053 spectrum=casa::Vector<casa::Float>(sdf.getResidual());
[369]1054}
1055
[368]1056// auxiliary function to average adjacent channels and update the mask
1057// if at least one channel involved in summation is masked, all
1058// output channels will be masked. This function works with the
1059// spectrum and edge fields of this class, but updates the mask
1060// array specified, rather than the field of this class
1061// boxsize - a number of adjacent channels to average
[881]1062void STLineFinder::averageAdjacentChannels(casa::Vector<casa::Bool> &mask2update,
[368]1063 const casa::Int &boxsize)
1064 throw(casa::AipsError)
1065{
1066 DebugAssert(mask2update.nelements()==spectrum.nelements(), AipsError);
1067 DebugAssert(boxsize!=0,AipsError);
[881]1068
[368]1069 for (int n=edge.first;n<edge.second;n+=boxsize) {
1070 DebugAssert(n<spectrum.nelements(),AipsError);
1071 int nboxch=0; // number of channels currently in the box
1072 Float mean=0; // buffer for mean calculations
1073 for (int k=n;k<n+boxsize && k<edge.second;++k)
1074 if (mask2update[k]) { // k is a valid channel
[996]1075 mean+=spectrum[k];
1076 ++nboxch;
[881]1077 }
[368]1078 if (nboxch<boxsize) // mask these channels
1079 for (int k=n;k<n+boxsize && k<edge.second;++k)
[996]1080 mask2update[k]=False;
[368]1081 else {
1082 mean/=Float(boxsize);
[996]1083 for (int k=n;k<n+boxsize && k<edge.second;++k)
1084 spectrum[k]=mean;
[368]1085 }
1086 }
1087}
[331]1088
[368]1089
[297]1090// get the mask to mask out all lines that have been found (default)
1091// if invert=true, only channels belong to lines will be unmasked
1092// Note: all channels originally masked by the input mask (in_mask
1093// in setScan) or dropped out by the edge parameter (in_edge
1094// in setScan) are still excluded regardless on the invert option
[881]1095std::vector<bool> STLineFinder::getMask(bool invert)
[297]1096 const throw(casa::AipsError)
1097{
1098 try {
1099 if (scan.null())
[881]1100 throw AipsError("STLineFinder::getMask - a scan should be set first,"
[297]1101 " use set_scan followed by find_lines");
[924]1102 DebugAssert(mask.nelements()==scan->getChannels(last_row_used), AipsError);
[297]1103 /*
1104 if (!lines.size())
[881]1105 throw AipsError("STLineFinder::getMask - one have to search for "
[996]1106 "lines first, use find_lines");
[881]1107 */
[297]1108 std::vector<bool> res_mask(mask.nelements());
1109 // iterator through lines
1110 std::list<std::pair<int,int> >::const_iterator cli=lines.begin();
[1497]1111 for (int ch=0;ch<int(res_mask.size());++ch) {
[297]1112 if (ch<edge.first || ch>=edge.second) res_mask[ch]=false;
[996]1113 else if (!mask[ch]) res_mask[ch]=false;
1114 else {
1115 res_mask[ch]=!invert; // no line by default
[1497]1116 if (cli!=lines.end())
1117 if (ch>=cli->first && ch<cli->second)
1118 res_mask[ch]=invert; // this is a line
1119 }
1120 if (cli!=lines.end())
1121 if (ch>=cli->second) {
1122 ++cli; // next line in the list
1123 }
1124 }
[297]1125 return res_mask;
1126 }
1127 catch (const AipsError &ae) {
1128 throw;
[881]1129 }
[297]1130 catch (const exception &ex) {
[881]1131 throw AipsError(String("STLineFinder::getMask - STL error: ")+ex.what());
[297]1132 }
1133}
1134
[370]1135// get range for all lines found. The same units as used in the scan
1136// will be returned (e.g. velocity instead of channels).
[881]1137std::vector<double> STLineFinder::getLineRanges()
[297]1138 const throw(casa::AipsError)
1139{
[370]1140 // convert to required abscissa units
1141 std::vector<double> vel=scan->getAbcissa(last_row_used);
1142 std::vector<int> ranges=getLineRangesInChannels();
1143 std::vector<double> res(ranges.size());
1144
1145 std::vector<int>::const_iterator cri=ranges.begin();
1146 std::vector<double>::iterator outi=res.begin();
1147 for (;cri!=ranges.end() && outi!=res.end();++cri,++outi)
1148 if (uInt(*cri)>=vel.size())
[881]1149 throw AipsError("STLineFinder::getLineRanges - getAbcissa provided less channels than reqired");
[370]1150 else *outi=vel[*cri];
1151 return res;
1152}
1153
1154// The same as getLineRanges, but channels are always used to specify
1155// the range
[881]1156std::vector<int> STLineFinder::getLineRangesInChannels()
[370]1157 const throw(casa::AipsError)
1158{
[297]1159 try {
1160 if (scan.null())
[881]1161 throw AipsError("STLineFinder::getLineRangesInChannels - a scan should be set first,"
[297]1162 " use set_scan followed by find_lines");
[924]1163 DebugAssert(mask.nelements()==scan->getChannels(last_row_used), AipsError);
[881]1164
[297]1165 if (!lines.size())
[881]1166 throw AipsError("STLineFinder::getLineRangesInChannels - one have to search for "
[996]1167 "lines first, use find_lines");
[881]1168
[297]1169 std::vector<int> res(2*lines.size());
1170 // iterator through lines & result
1171 std::list<std::pair<int,int> >::const_iterator cli=lines.begin();
1172 std::vector<int>::iterator ri=res.begin();
[881]1173 for (;cli!=lines.end() && ri!=res.end();++cli,++ri) {
[996]1174 *ri=cli->first;
1175 if (++ri!=res.end())
1176 *ri=cli->second-1;
[881]1177 }
[297]1178 return res;
1179 }
1180 catch (const AipsError &ae) {
1181 throw;
[881]1182 }
[297]1183 catch (const exception &ex) {
[881]1184 throw AipsError(String("STLineFinder::getLineRanges - STL error: ")+ex.what());
[297]1185 }
1186}
[331]1187
[370]1188
1189
[368]1190// an auxiliary function to remove all lines from the list, except the
1191// strongest one (by absolute value). If the lines removed are real,
[881]1192// they will be find again at the next iteration. This approach
1193// increases the number of iterations required, but is able to remove
[1315]1194// spurious detections likely to occur near strong lines.
[368]1195// Later a better criterion may be implemented, e.g.
1196// taking into consideration the brightness of different lines. Now
[881]1197// use the simplest solution
[368]1198// temp_mask - mask to work with (may be different from original mask as
1199// the lines previously found may be masked)
1200// lines2update - a list of lines to work with
1201// nothing will be done if it is empty
1202// max_box_nchan - channels in the running box for baseline filtering
[881]1203void STLineFinder::keepStrongestOnly(const casa::Vector<casa::Bool> &temp_mask,
[996]1204 std::list<std::pair<int, int> > &lines2update,
1205 int max_box_nchan)
[368]1206 throw (casa::AipsError)
1207{
1208 try {
1209 if (!lines2update.size()) return; // ignore an empty list
1210
1211 // current line
1212 std::list<std::pair<int,int> >::iterator li=lines2update.begin();
1213 // strongest line
1214 std::list<std::pair<int,int> >::iterator strongli=lines2update.begin();
1215 // the flux (absolute value) of the strongest line
1216 Float peak_flux=-1; // negative value - a flag showing uninitialized
1217 // value
1218 // the algorithm below relies on the list being ordered
1219 Float tmp_flux=-1; // a temporary peak
1220 for (RunningBox running_box(spectrum,temp_mask,edge,max_box_nchan);
1221 running_box.haveMore(); running_box.next()) {
1222
1223 if (li==lines2update.end()) break; // no more lines
[996]1224 const int ch=running_box.getChannel();
1225 if (ch>=li->first && ch<li->second)
1226 if (temp_mask[ch] && tmp_flux<fabs(running_box.aboveMean()))
1227 tmp_flux=fabs(running_box.aboveMean());
1228 if (ch==li->second-1) {
1229 if (peak_flux<tmp_flux) { // if peak_flux=-1, this condition
1230 peak_flux=tmp_flux; // will be satisfied
1231 strongli=li;
1232 }
1233 ++li;
1234 tmp_flux=-1;
1235 }
[881]1236 }
[368]1237 std::list<std::pair<int,int> > res;
1238 res.splice(res.end(),lines2update,strongli);
1239 lines2update.clear();
1240 lines2update.splice(lines2update.end(),res);
1241 }
1242 catch (const AipsError &ae) {
1243 throw;
[881]1244 }
[368]1245 catch (const exception &ex) {
[881]1246 throw AipsError(String("STLineFinder::keepStrongestOnly - STL error: ")+ex.what());
[368]1247 }
1248
1249}
1250
[352]1251//
1252///////////////////////////////////////////////////////////////////////////////
1253
1254
1255///////////////////////////////////////////////////////////////////////////////
1256//
1257// LFLineListOperations - a class incapsulating operations with line lists
1258// The LF prefix stands for Line Finder
1259//
1260
[331]1261// concatenate two lists preserving the order. If two lines appear to
1262// be adjacent, they are joined into the new one
[352]1263void LFLineListOperations::addNewSearchResult(const std::list<pair<int, int> > &newlines,
[881]1264 std::list<std::pair<int, int> > &lines_list)
[331]1265 throw(AipsError)
1266{
1267 try {
1268 for (std::list<pair<int,int> >::const_iterator cli=newlines.begin();
1269 cli!=newlines.end();++cli) {
[881]1270
[996]1271 // the first item, which has a non-void intersection or touches
1272 // the new line
1273 std::list<pair<int,int> >::iterator pos_beg=find_if(lines_list.begin(),
1274 lines_list.end(), IntersectsWith(*cli));
1275 // the last such item
1276 std::list<pair<int,int> >::iterator pos_end=find_if(pos_beg,
1277 lines_list.end(), not1(IntersectsWith(*cli)));
[343]1278
1279 // extract all lines which intersect or touch a new one into
[996]1280 // a temporary buffer. This may invalidate the iterators
1281 // line_buffer may be empty, if no lines intersects with a new
1282 // one.
1283 std::list<pair<int,int> > lines_buffer;
1284 lines_buffer.splice(lines_buffer.end(),lines_list, pos_beg, pos_end);
[343]1285
[996]1286 // build a union of all intersecting lines
1287 pair<int,int> union_line=for_each(lines_buffer.begin(),
1288 lines_buffer.end(),BuildUnion(*cli)).result();
[881]1289
[996]1290 // search for a right place for the new line (union_line) and add
1291 std::list<pair<int,int> >::iterator pos2insert=find_if(lines_list.begin(),
1292 lines_list.end(), LaterThan(union_line));
1293 lines_list.insert(pos2insert,union_line);
[331]1294 }
1295 }
1296 catch (const AipsError &ae) {
1297 throw;
[881]1298 }
[331]1299 catch (const exception &ex) {
[352]1300 throw AipsError(String("LFLineListOperations::addNewSearchResult - STL error: ")+ex.what());
[331]1301 }
1302}
[344]1303
1304// extend all line ranges to the point where a value stored in the
1305// specified vector changes (e.g. value-mean change its sign)
1306// This operation is necessary to include line wings, which are below
1307// the detection threshold. If lines becomes adjacent, they are
1308// merged together. Any masked channel stops the extension
[352]1309void LFLineListOperations::searchForWings(std::list<std::pair<int, int> > &newlines,
1310 const casa::Vector<casa::Int> &signs,
[996]1311 const casa::Vector<casa::Bool> &mask,
1312 const std::pair<int,int> &edge) throw(casa::AipsError)
[344]1313{
1314 try {
1315 for (std::list<pair<int,int> >::iterator li=newlines.begin();
1316 li!=newlines.end();++li) {
[996]1317 // update the left hand side
1318 for (int n=li->first-1;n>=edge.first;--n) {
1319 if (!mask[n]) break;
1320 if (signs[n]==signs[li->first] && signs[li->first])
1321 li->first=n;
1322 else break;
1323 }
1324 // update the right hand side
1325 for (int n=li->second;n<edge.second;++n) {
1326 if (!mask[n]) break;
1327 if (signs[n]==signs[li->second-1] && signs[li->second-1])
1328 li->second=n;
1329 else break;
1330 }
[344]1331 }
1332 // need to search for possible mergers.
1333 std::list<std::pair<int, int> > result_buffer;
1334 addNewSearchResult(newlines,result_buffer);
1335 newlines.clear();
1336 newlines.splice(newlines.end(),result_buffer);
1337 }
1338 catch (const AipsError &ae) {
1339 throw;
[881]1340 }
[344]1341 catch (const exception &ex) {
[352]1342 throw AipsError(String("LFLineListOperations::extendLines - STL error: ")+ex.what());
[344]1343 }
1344}
[352]1345
1346//
1347///////////////////////////////////////////////////////////////////////////////
Note: See TracBrowser for help on using the repository browser.