source: tags/asap-4.4.0/src/STLineFinder.cpp@ 3120

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

New Development: No

JIRA Issue: No

Ready for Test: Yes/No

Interface Changes: Yes/No

What Interface Changed: Please list interface changes

Test Programs: List test programs

Put in Release Notes: Yes/No

Module(s): Module Names change impacts.

Description: Describe your changes here...


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

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