source: trunk/src/STLineFinder.cpp@ 3128

Last change on this file since 3128 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
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 3106 2016-10-04 07:20:50Z TakeshiNakazato $
[297]30//#---------------------------------------------------------------------------
31
32// ASAP
[894]33#include "STLineFinder.h"
34#include "STFitter.h"
[1642]35#include "IndexedCompare.h"
[297]36
37// STL
[343]38#include <functional>
39#include <algorithm>
[297]40#include <iostream>
[351]41#include <fstream>
[297]42
43using namespace asap;
[3106]44using namespace casacore;
[297]45using namespace std;
46
[344]47namespace asap {
48
[343]49///////////////////////////////////////////////////////////////////////////////
50//
[881]51// RunningBox - a running box calculator. This class implements
[1315]52// iterations over the specified spectrum and calculates
[351]53// running box filter statistics.
[343]54//
55
[351]56class RunningBox {
[331]57 // The input data to work with. Use reference symantics to avoid
[881]58 // an unnecessary copying
[3106]59 const casacore::Vector<casacore::Float> &spectrum; // a buffer for the spectrum
60 const casacore::Vector<casacore::Bool> &mask; // associated mask
[331]61 const std::pair<int,int> &edge; // start and stop+1 channels
62 // to work with
[881]63
[351]64 // statistics for running box filtering
[3106]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)
[881]70
[331]71 int box_chan_cntr; // actual number of channels in the box
72 int max_box_nchan; // maximum allowed number of channels in the box
73 // (calculated from boxsize and actual spectrum size)
[351]74 // cache for derivative statistics
[3106]75 mutable casacore::Bool need2recalculate; // if true, values of the statistics
[351]76 // below are invalid
[3106]77 mutable casacore::Float linmean; // a value of the linear fit to the
[351]78 // points in the running box
[3106]79 mutable casacore::Float linvariance; // the same for variance
[351]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
[996]83 // masking)
[351]84public:
85 // set up the object with the references to actual data
86 // as well as the number of channels in the running box
[3106]87 RunningBox(const casacore::Vector<casacore::Float> &in_spectrum,
88 const casacore::Vector<casacore::Bool> &in_mask,
[996]89 const std::pair<int,int> &in_edge,
[3029]90 int in_max_box_nchan);
[881]91
[351]92 // access to the statistics
[3106]93 const casacore::Float& getLinMean() const;
94 const casacore::Float& getLinVariance() const;
95 casacore::Float aboveMean() const;
[3029]96 int getChannel() const;
[881]97
[351]98 // actual number of channels in the box (max_box_nchan, if no channels
99 // are masked)
[3029]100 int getNumberOfBoxPoints() const;
[297]101
[351]102 // next channel
[3029]103 void next();
[351]104
105 // checking whether there are still elements
[3106]106 casacore::Bool haveMore() const;
[351]107
108 // go to start
[3029]109 void rewind();
[881]110
[351]111protected:
[1644]112 // supplementary function to control running mean/median calculations.
113 // It adds a specified channel to the running box and
[351]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
[3029]117 void advanceRunningBox(int ch);
[351]118
119 // calculate derivative statistics. This function is const, because
120 // it updates the cache only
[3029]121 void updateDerivativeStatistics() const;
[351]122};
123
124//
125///////////////////////////////////////////////////////////////////////////////
126
127///////////////////////////////////////////////////////////////////////////////
128//
129// LFAboveThreshold An algorithm for line detection using running box
130// statistics. Line is detected if it is above the
131// specified threshold at the specified number of
132// consequtive channels. Prefix LF stands for Line Finder
133//
[352]134class LFAboveThreshold : protected LFLineListOperations {
[331]135 // temporary line edge channels and flag, which is True if the line
136 // was detected in the previous channels.
137 std::pair<int,int> cur_line;
[3106]138 casacore::Bool is_detected_before;
[331]139 int min_nchan; // A minimum number of consequtive
140 // channels, which should satisfy
[996]141 // the detection criterion, to be
142 // a detection
[3106]143 casacore::Float threshold; // detection threshold - the
[331]144 // minimal signal to noise ratio
[351]145 std::list<pair<int,int> > &lines; // list where detections are saved
146 // (pair: start and stop+1 channel)
147 RunningBox *running_box; // running box filter
[3106]148 casacore::Vector<Int> signs; // An array to store the signs of
[551]149 // the value - current mean
[996]150 // (used to search wings)
[3106]151 casacore::Int last_sign; // a sign (+1, -1 or 0) of the
[907]152 // last point of the detected line
153 //
[1644]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)
[331]160public:
[351]161
162 // set up the detection criterion
163 LFAboveThreshold(std::list<pair<int,int> > &in_lines,
164 int in_min_nchan = 3,
[3106]165 casacore::Float in_threshold = 5,
[1644]166 bool use_median = false,
[3029]167 int noise_sample_size = -1);
168 virtual ~LFAboveThreshold();
[881]169
[331]170 // replace the detection criterion
[3106]171 void setCriterion(int in_min_nchan, casacore::Float in_threshold);
[297]172
[551]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
[3106]177 const casacore::Vector<Int>& getSigns() const;
[551]178
[331]179 // find spectral lines and add them into list
[344]180 // if statholder is not NULL, the accumulate function of it will be
181 // called for each channel to save statistics
[351]182 // spectrum, mask and edge - reference to the data
183 // max_box_nchan - number of channels in the running box
[3106]184 void findLines(const casacore::Vector<casacore::Float> &spectrum,
185 const casacore::Vector<casacore::Bool> &mask,
[996]186 const std::pair<int,int> &edge,
[3029]187 int max_box_nchan);
[351]188
[331]189protected:
[297]190
[331]191 // process a channel: update curline and is_detected before and
192 // add a new line to the list, if necessary using processCurLine()
[351]193 // detect=true indicates that the current channel satisfies the criterion
[3106]194 void processChannel(Bool detect, const casacore::Vector<casacore::Bool> &mask);
[297]195
[331]196 // process the interval of channels stored in curline
197 // if it satisfies the criterion, add this interval as a new line
[3106]198 void processCurLine(const casacore::Vector<casacore::Bool> &mask);
[924]199
[907]200 // get the sign of runningBox->aboveMean(). The RunningBox pointer
201 // should be defined
[3106]202 casacore::Int getAboveMeanSign() const;
[331]203};
[344]204
205//
206///////////////////////////////////////////////////////////////////////////////
[351]207
[1642]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
[1644]235 // return true if the buffer is full (i.e. statistics are representative)
236 inline bool filledToCapacity() const { return itsBufferFull;}
237
[1642]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
[331]275} // namespace asap
[297]276
[344]277///////////////////////////////////////////////////////////////////////////////
[343]278//
[1642]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{
[1670]303 if (isnan(in)) {
304 // normally it shouldn't happen
305 return;
306 }
[1642]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;
[1643]331 AlwaysAssert( (nSamples > 0) && (nSamples <= itsVariances.size()), AipsError);
[1642]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();
[1643]437 AlwaysAssert(nSamples <= itsSortedIndices.size(), AipsError);
[1642]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//
[881]452// RunningBox - a running box calculator. This class implements
[351]453// interations over the specified spectrum and calculates
454// running box filter statistics.
[331]455//
[297]456
[331]457// set up the object with the references to actual data
458// and the number of channels in the running box
[3106]459RunningBox::RunningBox(const casacore::Vector<casacore::Float> &in_spectrum,
460 const casacore::Vector<casacore::Bool> &in_mask,
[996]461 const std::pair<int,int> &in_edge,
[3029]462 int in_max_box_nchan) :
[331]463 spectrum(in_spectrum), mask(in_mask), edge(in_edge),
[996]464 max_box_nchan(in_max_box_nchan)
[351]465{
466 rewind();
467}
[331]468
[3029]469void RunningBox::rewind() {
[351]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);
[881]481
482 if (initial_box_ch==edge.second)
[351]483 throw AipsError("RunningBox::rewind - too much channels are masked");
484
485 cur_channel=edge.first;
[881]486 start_advance=initial_box_ch-max_box_nchan/2;
[351]487}
488
489// access to the statistics
[3106]490const casacore::Float& RunningBox::getLinMean() const
[331]491{
[351]492 DebugAssert(cur_channel<edge.second, AipsError);
493 if (need2recalculate) updateDerivativeStatistics();
494 return linmean;
[297]495}
496
[3106]497const casacore::Float& RunningBox::getLinVariance() const
[351]498{
499 DebugAssert(cur_channel<edge.second, AipsError);
500 if (need2recalculate) updateDerivativeStatistics();
501 return linvariance;
502}
[331]503
[3106]504casacore::Float RunningBox::aboveMean() const
[351]505{
506 DebugAssert(cur_channel<edge.second, AipsError);
507 if (need2recalculate) updateDerivativeStatistics();
508 return spectrum[cur_channel]-linmean;
509}
510
[3029]511int RunningBox::getChannel() const
[351]512{
513 return cur_channel;
514}
515
516// actual number of channels in the box (max_box_nchan, if no channels
517// are masked)
[3029]518int RunningBox::getNumberOfBoxPoints() const
[351]519{
520 return box_chan_cntr;
521}
522
[1644]523// supplementary function to control running mean/median calculations.
524// It adds a specified channel to the running box and
[297]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
[3029]528void RunningBox::advanceRunningBox(int ch)
[297]529{
530 if (ch>=edge.first && ch<edge.second)
531 if (mask[ch]) { // ch is a valid channel
532 ++box_chan_cntr;
[351]533 sumf+=spectrum[ch];
534 sumf2+=square(spectrum[ch]);
[996]535 sumch+=Float(ch);
536 sumch2+=square(Float(ch));
537 sumfch+=spectrum[ch]*Float(ch);
538 need2recalculate=True;
[297]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;
[351]544 sumf-=spectrum[ch2remove];
[881]545 sumf2-=square(spectrum[ch2remove]);
[996]546 sumch-=Float(ch2remove);
547 sumch2-=square(Float(ch2remove));
548 sumfch-=spectrum[ch2remove]*Float(ch2remove);
549 need2recalculate=True;
[297]550 }
551}
552
[351]553// next channel
[3029]554void RunningBox::next()
[297]555{
[351]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
[297]560}
561
[351]562// checking whether there are still elements
[3106]563casacore::Bool RunningBox::haveMore() const
[351]564{
565 return cur_channel<edge.second;
566}
567
568// calculate derivative statistics. This function is const, because
569// it updates the cache only
[3029]570void RunningBox::updateDerivativeStatistics() const
[351]571{
572 AlwaysAssert(box_chan_cntr, AipsError);
[881]573
[351]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;
[1670]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 }
[351]595 }
596 need2recalculate=False;
597}
598
599
600//
601///////////////////////////////////////////////////////////////////////////////
602
603///////////////////////////////////////////////////////////////////////////////
604//
[1644]605// LFAboveThreshold - a running mean/median algorithm for line detection
[351]606//
607//
608
609
610// set up the detection criterion
611LFAboveThreshold::LFAboveThreshold(std::list<pair<int,int> > &in_lines,
612 int in_min_nchan,
[3106]613 casacore::Float in_threshold,
[1644]614 bool use_median,
[3029]615 int noise_sample_size) :
[351]616 min_nchan(in_min_nchan), threshold(in_threshold),
[1644]617 lines(in_lines), running_box(NULL), itsUseMedian(use_median),
618 itsNoiseSampleSize(noise_sample_size) {}
[351]619
[3029]620LFAboveThreshold::~LFAboveThreshold()
[351]621{
622 if (running_box!=NULL) delete running_box;
623}
624
625// replace the detection criterion
[3106]626void LFAboveThreshold::setCriterion(int in_min_nchan, casacore::Float in_threshold)
[351]627{
628 min_nchan=in_min_nchan;
629 threshold=in_threshold;
630}
631
[907]632// get the sign of runningBox->aboveMean(). The RunningBox pointer
633// should be defined
[3106]634casacore::Int LFAboveThreshold::getAboveMeanSign() const
[907]635{
636 const Float buf=running_box->aboveMean();
637 if (buf>0) return 1;
638 if (buf<0) return -1;
639 return 0;
640}
[351]641
[907]642
[297]643// process a channel: update cur_line and is_detected before and
644// add a new line to the list, if necessary
[351]645void LFAboveThreshold::processChannel(Bool detect,
[3106]646 const casacore::Vector<casacore::Bool> &mask)
[297]647{
648 try {
[907]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;
[1315]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);
[297]666 }
667 catch (const AipsError &ae) {
668 throw;
[881]669 }
[297]670 catch (const exception &ex) {
[351]671 throw AipsError(String("LFAboveThreshold::processChannel - STL error: ")+ex.what());
[297]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
[3106]677void LFAboveThreshold::processCurLine(const casacore::Vector<casacore::Bool> &mask)
[297]678{
679 try {
[881]680 if (is_detected_before) {
[1315]681 if (cur_line.second-cur_line.first>=min_nchan) {
[996]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);
[881]694 else lines.back().second=cur_line.second;
[996]695 }
696 is_detected_before=False;
[881]697 }
[297]698 }
699 catch (const AipsError &ae) {
700 throw;
[881]701 }
[297]702 catch (const exception &ex) {
[351]703 throw AipsError(String("LFAboveThreshold::processCurLine - STL error: ")+ex.what());
[297]704 }
705}
706
[551]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
[3106]711const casacore::Vector<Int>& LFAboveThreshold::getSigns() const
[551]712{
713 return signs;
714}
715
[331]716// find spectral lines and add them into list
[3106]717void LFAboveThreshold::findLines(const casacore::Vector<casacore::Float> &spectrum,
718 const casacore::Vector<casacore::Bool> &mask,
[996]719 const std::pair<int,int> &edge,
720 int max_box_nchan)
[331]721{
722 const int minboxnchan=4;
[351]723 try {
[331]724
[351]725 if (running_box!=NULL) delete running_box;
726 running_box=new RunningBox(spectrum,mask,edge,max_box_nchan);
[368]727
728 // determine the off-line variance first
729 // an assumption made: lines occupy a small part of the spectrum
[881]730
[1644]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);
[881]736
[1643]737 for (;running_box->haveMore();running_box->next()) {
[1644]738 ne.add(running_box->getLinVariance());
739 if (ne.filledToCapacity()) {
740 break;
741 }
[1643]742 }
[881]743
[1644]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 }
[881]749
[351]750 // actual search algorithm
751 is_detected_before=False;
[368]752
[551]753 // initiate the signs array
754 signs.resize(spectrum.nelements());
755 signs=Vector<Int>(spectrum.nelements(),0);
756
[369]757 //ofstream os("dbg.dat");
[368]758 for (running_box->rewind();running_box->haveMore();
759 running_box->next()) {
[351]760 const int ch=running_box->getChannel();
[1644]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);
[996]770 processChannel(mask[ch] && (fabs(running_box->aboveMean()) >=
771 threshold*offline_variance), mask);
[1644]772 } else processCurLine(mask); // just finish what was accumulated before
[907]773
[996]774 signs[ch]=getAboveMeanSign();
[1641]775 //os<<ch<<" "<<spectrum[ch]<<" "<<fabs(running_box->aboveMean())<<" "<<
776 //threshold*offline_variance<<endl;
[351]777 }
[352]778 if (lines.size())
779 searchForWings(lines,signs,mask,edge);
[344]780 }
[351]781 catch (const AipsError &ae) {
782 throw;
[881]783 }
[351]784 catch (const exception &ex) {
785 throw AipsError(String("LFAboveThreshold::findLines - STL error: ")+ex.what());
786 }
[331]787}
788
789//
790///////////////////////////////////////////////////////////////////////////////
791
[343]792///////////////////////////////////////////////////////////////////////////////
793//
[352]794// LFLineListOperations::IntersectsWith - An auxiliary object function
795// to test whether two lines have a non-void intersection
[343]796//
[331]797
[343]798
799// line1 - range of the first line: start channel and stop+1
[352]800LFLineListOperations::IntersectsWith::IntersectsWith(const std::pair<int,int> &in_line1) :
[343]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
[3029]807bool LFLineListOperations::IntersectsWith::operator()(const std::pair<int,int> &line2) const
[343]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//
[352]819// LFLineListOperations::BuildUnion - An auxiliary object function to build a union
[343]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)
[352]824LFLineListOperations::BuildUnion::BuildUnion(const std::pair<int,int> &line1) :
[343]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
[352]829void LFLineListOperations::BuildUnion::operator()(const std::pair<int,int> &new_line)
[343]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)
[3029]836const std::pair<int,int>& LFLineListOperations::BuildUnion::result() const
[343]837{
838 return temp_line;
839}
840
841//
842///////////////////////////////////////////////////////////////////////////////
843
844///////////////////////////////////////////////////////////////////////////////
845//
[352]846// LFLineListOperations::LaterThan - An auxiliary object function to test whether a
[343]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
[352]852LFLineListOperations::LaterThan::LaterThan(const std::pair<int,int> &in_line1) :
[343]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)
[352]857bool LFLineListOperations::LaterThan::operator()(const std::pair<int,int> &line2)
[3029]858 const
[343]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
[881]862
[343]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//
[881]874// STLineFinder - a class for automated spectral line search
[343]875//
876//
[331]877
[3029]878STLineFinder::STLineFinder() : edge(0,0), err("spurious")
[331]879{
[2425]880 useScantable = true;
[369]881 setOptions();
[331]882}
883
[369]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
[881]894// Default is 8, but for a bad baseline shape this
[369]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.
[881]898// Setting a very large value doesn't usually provide
899// valid detections.
[1644]900// in_box_size the box size for running mean/median calculation. Default is
[369]901// 1./5. of the whole spectrum size
[1644]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)
[3106]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)
[369]913{
914 threshold=in_threshold;
915 min_nchan=in_min_nchan;
916 avg_limit=in_avg_limit;
917 box_size=in_box_size;
[1644]918 itsNoiseBox = in_noise_box;
919 itsUseMedian = in_median;
[369]920}
921
[3029]922STLineFinder::~STLineFinder() {}
[331]923
[907]924// set scan to work with (in_scan parameter)
[3029]925void STLineFinder::setScan(const ScantableWrapper &in_scan)
[907]926{
927 scan=in_scan.getCP();
928 AlwaysAssert(!scan.null(),AipsError);
[2425]929 useScantable = true;
[2012]930}
[924]931
[2012]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{
[2410]937 //spectrum = Vector<Float>(in_spectrum);
938 spectrum.assign( Vector<Float>(in_spectrum) );
[2012]939 useScantable = false;
[907]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
[331]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
[881]948// can be achieved using a spectrum mask only
[907]949int STLineFinder::findLines(const std::vector<bool> &in_mask,
[2345]950 const std::vector<int> &in_edge,
[3106]951 const casacore::uInt &whichRow)
[331]952{
[2012]953 if (useScantable && scan.null())
[907]954 throw AipsError("STLineFinder::findLines - a scan should be set first,"
955 " use set_scan");
[924]956
[2012]957 uInt nchan = useScantable ? scan->nchan(scan->getIF(whichRow)) : spectrum.nelements();
[907]958 // set up mask and edge rejection
[924]959 // no mask given...
960 if (in_mask.size() == 0) {
[2410]961 //mask = Vector<Bool>(nchan,True);
962 mask.assign( Vector<Bool>(nchan,True) );
[924]963 } else {
964 // use provided mask
[2410]965 //mask=Vector<Bool>(in_mask);
966 mask.assign( Vector<Bool>(in_mask) );
[924]967 }
968 if (mask.nelements()!=nchan)
[2012]969 throw AipsError("STLineFinder::findLines - in_scan and in_mask, or in_spectrum "
970 "and in_mask have different number of spectral channels.");
[1641]971
972 // taking flagged channels into account
[2012]973 if (useScantable) {
[2961]974 if (scan->getFlagRow(whichRow))
975 throw AipsError("STLineFinder::findLines - flagged scantable row.");
[2012]976 vector<bool> flaggedChannels = scan->getMask(whichRow);
977 if (flaggedChannels.size()) {
[1641]978 // there is a mask set for this row
979 if (flaggedChannels.size() != mask.nelements()) {
[2012]980 throw AipsError("STLineFinder::findLines - internal inconsistency: number of "
981 "mask elements do not match the number of channels");
[1641]982 }
983 for (size_t ch = 0; ch<mask.nelements(); ++ch) {
984 mask[ch] &= flaggedChannels[ch];
985 }
[2012]986 }
[1641]987 }
988
[907]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"
[996]992 "should not exceed 2");
[907]993 if (!in_edge.size()) {
[881]994 // all spectra, no rejection
[331]995 edge.first=0;
[996]996 edge.second=nchan;
[907]997 } else {
998 edge.first=in_edge[0];
[996]999 if (edge.first<0)
1000 throw AipsError("STLineFinder::findLines - the in_edge parameter has a negative"
1001 "number of channels to drop");
[2774]1002 if (edge.first>=int(nchan)) {
[996]1003 throw AipsError("STLineFinder::findLines - all channels are rejected by the in_edge parameter");
[2774]1004 }
[907]1005 if (in_edge.size()==2) {
[996]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");
[924]1010 edge.second=nchan-edge.second;
[996]1011 } else edge.second=nchan-edge.first;
[2774]1012 if (edge.second<0 || (edge.first>=edge.second)) {
[996]1013 throw AipsError("STLineFinder::findLines - all channels are rejected by the in_edge parameter");
[2774]1014 }
[881]1015 }
[924]1016
[907]1017 //
[924]1018 int max_box_nchan=int(nchan*box_size); // number of channels in running
[331]1019 // box
1020 if (max_box_nchan<2)
[881]1021 throw AipsError("STLineFinder::findLines - box_size is too small");
[331]1022
[1644]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
[2012]1029 if (useScantable) {
1030 spectrum.resize();
1031 spectrum = Vector<Float>(scan->getSpectrum(whichRow));
1032 }
[331]1033
1034 lines.resize(0); // search from the scratch
[370]1035 last_row_used=whichRow;
[331]1036 Vector<Bool> temp_mask(mask);
[351]1037
1038 Bool first_pass=True;
[368]1039 Int avg_factor=1; // this number of adjacent channels is averaged together
1040 // the total number of the channels is not altered
[996]1041 // instead, min_nchan is also scaled
1042 // it helps to search for broad lines
[551]1043 Vector<Int> signs; // a buffer for signs of the value - mean quantity
1044 // see LFAboveThreshold for details
[996]1045 // We need only signs resulted from last iteration
1046 // because all previous values may be corrupted by the
1047 // presence of spectral lines
[2580]1048
[344]1049 while (true) {
[351]1050 // a buffer for new lines found at this iteration
[881]1051 std::list<pair<int,int> > new_lines;
[351]1052
1053 try {
[369]1054 // line find algorithm
[1644]1055 LFAboveThreshold lfalg(new_lines,avg_factor*min_nchan, threshold, itsUseMedian,noise_box);
[352]1056 lfalg.findLines(spectrum,temp_mask,edge,max_box_nchan);
[996]1057 signs.resize(lfalg.getSigns().nelements());
1058 signs=lfalg.getSigns();
[368]1059 first_pass=False;
1060 if (!new_lines.size())
[2580]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
[351]1065 }
1066 catch(const AipsError &ae) {
1067 if (first_pass) throw;
[368]1068 // nothing new - proceed to the next step of averaging, if any
[996]1069 // (to search for broad lines)
[1315]1070 if (avg_factor>=avg_limit) break; // averaging up to avg_limit
[996]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;
[1315]1077 }
[368]1078 keepStrongestOnly(temp_mask,new_lines,max_box_nchan);
[343]1079 // update the list (lines) merging intervals, if necessary
[344]1080 addNewSearchResult(new_lines,lines);
1081 // get a new mask
[881]1082 temp_mask=getMask();
[343]1083 }
[881]1084
[551]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
[881]1088
[551]1089 if (lines.size())
1090 LFLineListOperations::searchForWings(lines,signs,mask,edge);
[881]1091
[331]1092 return int(lines.size());
1093}
1094
[369]1095// auxiliary function to fit and subtract a polynomial from the current
[890]1096// spectrum. It uses the Fitter class. This action is required before
[369]1097// reducing the spectral resolution if the baseline shape is bad
[3106]1098void STLineFinder::subtractBaseline(const casacore::Vector<casacore::Bool> &temp_mask,
1099 const casacore::Int &order)
[369]1100{
1101 AlwaysAssert(spectrum.nelements(),AipsError);
1102 // use the fact that temp_mask excludes channels rejected at the edge
[890]1103 Fitter sdf;
[369]1104 std::vector<float> absc(spectrum.nelements());
[996]1105 for (unsigned int i=0;i<absc.size();++i)
[369]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);
[2196]1113 if (!sdf.lfit()) return; // fit failed, use old spectrum
[3106]1114 spectrum=casacore::Vector<casacore::Float>(sdf.getResidual());
[369]1115}
1116
[368]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
[3106]1123void STLineFinder::averageAdjacentChannels(casacore::Vector<casacore::Bool> &mask2update,
1124 const casacore::Int &boxsize)
[368]1125{
1126 DebugAssert(mask2update.nelements()==spectrum.nelements(), AipsError);
1127 DebugAssert(boxsize!=0,AipsError);
[881]1128
[368]1129 for (int n=edge.first;n<edge.second;n+=boxsize) {
[3086]1130 DebugAssert((uInt)n<spectrum.nelements(),AipsError);
[368]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
[996]1135 mean+=spectrum[k];
1136 ++nboxch;
[881]1137 }
[368]1138 if (nboxch<boxsize) // mask these channels
1139 for (int k=n;k<n+boxsize && k<edge.second;++k)
[996]1140 mask2update[k]=False;
[368]1141 else {
1142 mean/=Float(boxsize);
[996]1143 for (int k=n;k<n+boxsize && k<edge.second;++k)
1144 spectrum[k]=mean;
[368]1145 }
1146 }
1147}
[331]1148
[368]1149
[297]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
[881]1155std::vector<bool> STLineFinder::getMask(bool invert)
[3029]1156 const
[297]1157{
1158 try {
[2012]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");
[3086]1163 DebugAssert(mask.nelements()==(uInt)scan->getChannels(last_row_used), AipsError);
[2012]1164 }
1165 /*
1166 if (!lines.size())
1167 throw AipsError("STLineFinder::getMask - one have to search for "
[996]1168 "lines first, use find_lines");
[2012]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;
[297]1187 }
1188 catch (const AipsError &ae) {
[2012]1189 throw;
[881]1190 }
[297]1191 catch (const exception &ex) {
[2012]1192 throw AipsError(String("STLineFinder::getMask - STL error: ")+ex.what());
[297]1193 }
1194}
1195
[370]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).
[3029]1198std::vector<double> STLineFinder::getLineRanges() const
[297]1199{
[2012]1200 std::vector<double> vel;
1201 if (useScantable) {
1202 // convert to required abscissa units
1203 vel = scan->getAbcissa(last_row_used);
1204 } else {
[2081]1205 for (uInt i = 0; i < spectrum.nelements(); ++i)
[2012]1206 vel.push_back((double)i);
1207 }
[370]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())
[881]1215 throw AipsError("STLineFinder::getLineRanges - getAbcissa provided less channels than reqired");
[370]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
[3029]1222std::vector<int> STLineFinder::getLineRangesInChannels() const
[370]1223{
[297]1224 try {
[2012]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");
[3086]1229 DebugAssert(mask.nelements()==(uInt)scan->getChannels(last_row_used), AipsError);
[2012]1230 }
[881]1231
[2012]1232 if (!lines.size())
1233 throw AipsError("STLineFinder::getLineRangesInChannels - one have to search for "
1234 "lines first, use find_lines");
[881]1235
[2012]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());
[297]1250 }
1251}
[331]1252
[370]1253
1254
[368]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,
[881]1257// they will be find again at the next iteration. This approach
1258// increases the number of iterations required, but is able to remove
[1315]1259// spurious detections likely to occur near strong lines.
[368]1260// Later a better criterion may be implemented, e.g.
1261// taking into consideration the brightness of different lines. Now
[881]1262// use the simplest solution
[368]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
[3106]1268void STLineFinder::keepStrongestOnly(const casacore::Vector<casacore::Bool> &temp_mask,
[996]1269 std::list<std::pair<int, int> > &lines2update,
1270 int max_box_nchan)
[368]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
[996]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 }
[881]1300 }
[368]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;
[881]1308 }
[368]1309 catch (const exception &ex) {
[881]1310 throw AipsError(String("STLineFinder::keepStrongestOnly - STL error: ")+ex.what());
[368]1311 }
1312
1313}
1314
[352]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
[331]1325// concatenate two lists preserving the order. If two lines appear to
1326// be adjacent, they are joined into the new one
[352]1327void LFLineListOperations::addNewSearchResult(const std::list<pair<int, int> > &newlines,
[881]1328 std::list<std::pair<int, int> > &lines_list)
[331]1329{
1330 try {
1331 for (std::list<pair<int,int> >::const_iterator cli=newlines.begin();
1332 cli!=newlines.end();++cli) {
[881]1333
[996]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)));
[343]1341
1342 // extract all lines which intersect or touch a new one into
[996]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);
[343]1348
[996]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();
[881]1352
[996]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);
[331]1357 }
1358 }
1359 catch (const AipsError &ae) {
1360 throw;
[881]1361 }
[331]1362 catch (const exception &ex) {
[352]1363 throw AipsError(String("LFLineListOperations::addNewSearchResult - STL error: ")+ex.what());
[331]1364 }
1365}
[344]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
[352]1372void LFLineListOperations::searchForWings(std::list<std::pair<int, int> > &newlines,
[3106]1373 const casacore::Vector<casacore::Int> &signs,
1374 const casacore::Vector<casacore::Bool> &mask,
[3029]1375 const std::pair<int,int> &edge)
[344]1376{
1377 try {
1378 for (std::list<pair<int,int> >::iterator li=newlines.begin();
1379 li!=newlines.end();++li) {
[996]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 }
[344]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;
[881]1403 }
[344]1404 catch (const exception &ex) {
[352]1405 throw AipsError(String("LFLineListOperations::extendLines - STL error: ")+ex.what());
[344]1406 }
1407}
[352]1408
1409//
1410///////////////////////////////////////////////////////////////////////////////
Note: See TracBrowser for help on using the repository browser.