source: trunk/src/SDLineFinder.cc @ 369

Last change on this file since 369 was 369, checked in by vor010, 19 years ago

SDLineFinder: bug corrections, setOption method
has been added + fitting baseline at each iterations to cope with bad
baselines

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