LCOV - code coverage report
Current view: top level - synthesis/TransformMachines2 - BriggsCubeWeightor.cc (source / functions) Hit Total Coverage
Test: casacpp_coverage.info Lines: 0 591 0.0 %
Date: 2024-10-12 00:35:29 Functions: 0 14 0.0 %

          Line data    Source code
       1             : //# BriggsCubeWeight.cc: Implementation for Briggs weighting for cubes
       2             : //# Copyright (C) 2018-2021
       3             : //# Associated Universities, Inc. Washington DC, USA.
       4             : //#
       5             : //# This library is free software; you can redistribute it and/or modify it
       6             : //# under the terms of the GNU General Public License as published by
       7             : //# the Free Software Foundation; either version 3 of the License, or (at your
       8             : //# option) any later version.
       9             : //#
      10             : //# This library is distributed in the hope that it will be useful, but WITHOUT
      11             : //# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
      12             : //# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
      13             : //# License for more details.
      14             : //#
      15             : //# https://www.gnu.org/licenses/
      16             : //#
      17             : //# You should have received a copy of the GNU  General Public License
      18             : //# along with this library; if not, write to the Free Software Foundation,
      19             : //# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
      20             : //#
      21             : //# Queries concerning CASA should be submitted at
      22             : //#        https://help.nrao.edu
      23             : //#
      24             : //#        Postal address: CASA Project Manager
      25             : //#                        National Radio Astronomy Observatory
      26             : //#                        520 Edgemont Road
      27             : //#                        Charlottesville, VA 22903-2475 USA
      28             : //#
      29             : //#
      30             : #include <casacore/casa/Arrays/ArrayMath.h>
      31             : #include <casacore/casa/Arrays/Matrix.h>
      32             : #include <casacore/casa/Arrays/Slice.h>
      33             : #include <casacore/casa/Arrays/Vector.h>
      34             : #include <casacore/casa/Containers/Record.h>
      35             : #include <casacore/tables/DataMan/IncrementalStMan.h>
      36             : #include <casacore/tables/DataMan/StManAipsIO.h>
      37             : #include <casacore/tables/DataMan/StandardStMan.h>
      38             : #include <casacore/tables/DataMan/TiledShapeStMan.h>
      39             : #include <casacore/tables/Tables/ArrColDesc.h>
      40             : #include <casacore/tables/Tables/ArrayColumn.h>
      41             : #include <casacore/tables/Tables/ScaColDesc.h>
      42             : #include <casacore/tables/Tables/ScalarColumn.h>
      43             : #include <casacore/tables/Tables/TableUtil.h>
      44             : #include <msvis/MSVis/MSUtil.h>
      45             : #include <msvis/MSVis/VisBuffer2.h>
      46             : #include <msvis/MSVis/VisImagingWeight.h>
      47             : #include <msvis/MSVis/VisibilityIterator2.h>
      48             : #include <synthesis/TransformMachines2/BriggsCubeWeightor.h>
      49             : #include <synthesis/TransformMachines2/FTMachine.h>
      50             : 
      51             : namespace casa {  //# CASA namespace
      52             : namespace refim { //# namespace refactor imaging
      53             : 
      54             : using namespace casacore;
      55             : using namespace casa;
      56             : using namespace casacore;
      57             : using namespace casa::refim;
      58             : using namespace casacore;
      59             : using namespace casa::vi;
      60             : 
      61           0 : BriggsCubeWeightor::BriggsCubeWeightor()
      62           0 :     : grids_p(0), ft_p(0), f2_p(0), d2_p(0), uscale_p(0), vscale_p(0),
      63           0 :       uorigin_p(0), vorigin_p(0), nx_p(0), ny_p(0), rmode_p(""), noise_p(0.0),
      64           0 :       robust_p(2), superUniformBox_p(0), multiField_p(False),
      65           0 :       initialized_p(False), refFreq_p(-1.0),
      66           0 :       freqInterpMethod_p(InterpolateArray1D<Double, Complex>::nearestNeighbour),
      67           0 :       fracBW_p(0.0), wgtTab_p(nullptr), imWgtColName_p("") {
      68             : 
      69           0 :   multiFieldMap_p.clear();
      70           0 : }
      71             : 
      72           0 : BriggsCubeWeightor::BriggsCubeWeightor(
      73             :     const String &rmode, const Quantity &noise, const Double robust,
      74           0 :     const Double &fracBW, const Int superUniformBox, const Bool multiField)
      75           0 :     : grids_p(0), ft_p(0), f2_p(0), d2_p(0), uscale_p(0), vscale_p(0),
      76           0 :       uorigin_p(0), vorigin_p(0), nx_p(0), ny_p(0), initialized_p(False),
      77           0 :       refFreq_p(-1.0),
      78           0 :       freqInterpMethod_p(InterpolateArray1D<Double, Complex>::nearestNeighbour),
      79           0 :       wgtTab_p(nullptr), imWgtColName_p("") {
      80             : 
      81           0 :   rmode_p = rmode;
      82           0 :   noise_p = noise;
      83           0 :   robust_p = robust;
      84           0 :   superUniformBox_p = superUniformBox;
      85           0 :   multiField_p = multiField;
      86           0 :   multiFieldMap_p.clear();
      87           0 :   fracBW_p = fracBW;
      88           0 : }
      89             : 
      90           0 : BriggsCubeWeightor::BriggsCubeWeightor(
      91             :     vi::VisibilityIterator2 &vi, const String &rmode, const Quantity &noise,
      92             :     const Double robust, const ImageInterface<Complex> &templateimage,
      93             :     const RecordInterface &inrec, const Double &fracBW,
      94           0 :     const Int superUniformBox, const Bool multiField)
      95           0 :     : wgtTab_p(nullptr) {
      96           0 :   rmode_p = rmode;
      97           0 :   noise_p = noise;
      98           0 :   robust_p = robust;
      99           0 :   superUniformBox_p = superUniformBox;
     100           0 :   multiField_p = multiField;
     101           0 :   initialized_p = False;
     102           0 :   refFreq_p = -1.0;
     103           0 :   fracBW_p = fracBW;
     104             : 
     105           0 :   init(vi, templateimage, inrec);
     106           0 : }
     107             : 
     108           0 : String BriggsCubeWeightor::initImgWeightCol(
     109             :     vi::VisibilityIterator2 &vi, const ImageInterface<Complex> &templateimage,
     110             :     const RecordInterface &inRec) {
     111             : 
     112             :   // cout << "BriggsCubeWeightor::initImgWeightCol " << endl;
     113             : 
     114           0 :   CoordinateSystem cs = templateimage.coordinates();
     115             : 
     116           0 :   if (initialized_p && nx_p == templateimage.shape()(0) &&
     117           0 :       ny_p == templateimage.shape()(1)) {
     118             : 
     119           0 :     Double freq = cs.toWorld(IPosition(4, 0, 0, 0, 0))[3];
     120           0 :     if (freq == refFreq_p)
     121           0 :       return imWgtColName_p;
     122             :   }
     123             : 
     124           0 :   refFreq_p = cs.toWorld(IPosition(4, 0, 0, 0, 0))[3];
     125           0 :   visWgt_p = vi.getImagingWeightGenerator();
     126           0 :   VisImagingWeight vWghtNat("natural");
     127           0 :   vi.useImagingWeight(vWghtNat);
     128           0 :   vi::VisBuffer2 *vb = vi.getVisBuffer();
     129           0 :   std::vector<pair<Int, Int>> fieldsToUse;
     130           0 :   std::set<Int> msInUse;
     131           0 :   rownr_t nrows = 0;
     132           0 :   String ephemtab("");
     133           0 :   if (inRec.isDefined("ephemeristable")) {
     134           0 :     inRec.get("ephemeristable", ephemtab);
     135             :   }
     136           0 :   Double freqbeg = cs.toWorld(IPosition(4, 0, 0, 0, 0))[3];
     137             :   Double freqend =
     138           0 :       cs.toWorld(IPosition(4, 0, 0, 0, templateimage.shape()[3] - 1))[3];
     139             : 
     140           0 :   for (vi.originChunks(); vi.moreChunks(); vi.nextChunk()) {
     141           0 :     for (vi.origin(); vi.more(); vi.next()) {
     142           0 :       nrows += vb->nRows();
     143           0 :       msInUse.insert(vb->msId());
     144           0 :       if (multiField_p) {
     145             : 
     146           0 :         pair<Int, Int> ms_field = make_pair(vb->msId(), vb->fieldId()[0]);
     147           0 :         if (std::find(fieldsToUse.begin(), fieldsToUse.end(), ms_field) ==
     148           0 :             fieldsToUse.end()) {
     149           0 :           fieldsToUse.push_back(ms_field);
     150             :         }
     151             :       }
     152             :     }
     153             :   }
     154           0 :   wgtTab_p = nullptr;
     155             :   Int tmpInt;
     156           0 :   inRec.get("freqinterpmethod", tmpInt);
     157           0 :   freqInterpMethod_p =
     158           0 :       static_cast<InterpolateArray1D<Double, Complex>::InterpolationMethod>(
     159             :           tmpInt);
     160           0 :   ostringstream oss;
     161           0 :   oss << std::setprecision(12) << nrows << "_" << freqbeg << "_" << freqend
     162           0 :       << "_" << rmode_p << "_" << robust_p << "_interp_" << tmpInt;
     163             : 
     164             :   // cerr << "STRING " << oss.str() << endl;;
     165           0 :   imWgtColName_p = makeScratchImagingWeightTable(wgtTab_p, oss.str());
     166           0 :   if (wgtTab_p->nrow() == nrows) {
     167             :     // cerr << "REUSING "<< wgtTab_p << endl;
     168           0 :     return imWgtColName_p;
     169             :   } else {
     170           0 :     wgtTab_p->lock(True, 100);
     171           0 :     wgtTab_p->removeRow(wgtTab_p->rowNumbers());
     172             :   }
     173             :   // cerr << "CREATING "<< wgtTab_p << endl;
     174           0 :   vbrowms2wgtrow_p.clear();
     175           0 :   if (fieldsToUse.size() == 0)
     176           0 :     fieldsToUse.push_back(make_pair(Int(-1), Int(-1)));
     177             :   // cerr << "FIELDs to use " << Vector<pair<Int,Int> >(fieldsToUse) << endl;
     178             : 
     179           0 :   Bool inOneGo = True;
     180           0 :   uInt allSwingPad = 4;
     181             :   // if multifield each field weight density are independent so no other field
     182             :   // or ms  fields would contribute
     183           0 :   if (!multiField_p) {
     184           0 :     allSwingPad =
     185           0 :         estimateSwingChanPad(vi, -1, cs, templateimage.shape()[3], ephemtab);
     186             :   }
     187           0 :   if (msInUse.size() > 1) {
     188             :     SpectralCoordinate spCoord =
     189           0 :         cs.spectralCoordinate(cs.findCoordinate(Coordinate::SPECTRAL));
     190           0 :     MFrequency::Types freqframe = spCoord.frequencySystem(True);
     191           0 :     if (((allSwingPad > 4) &&
     192           0 :         (allSwingPad > uInt(templateimage.shape()[3] / 10))) 
     193           0 :          || ephemtab.size() > 0 || freqframe==MFrequency::REST){
     194             :   
     195           0 :       inOneGo = False;
     196             :          }
     197           0 :   }
     198             :   ///////////////
     199             :   // cerr << "###fieldsInUSE " << Vector<pair<Int, Int> >(fieldsToUse) << endl;;
     200             :   // inOneGo=True;
     201             : 
     202             :   /////////////////////////////
     203           0 :   if (inOneGo) {
     204           0 :     fillImgWeightCol(vi, inRec, -1, fieldsToUse, allSwingPad,
     205           0 :                      templateimage.shape(), cs);
     206             :   } else {
     207             :     /// Lets process the ms independently as swingpad can become very large for
     208             :     /// MSs seperated by large epochs
     209           0 :     uInt maxswingpad=0;
     210           0 :     for (auto msiter = msInUse.begin(); msiter != msInUse.end(); ++msiter) {
     211           0 :       uInt swingpad = estimateSwingChanPad(vi, *msiter, cs,
     212           0 :                                            templateimage.shape()[3], ephemtab);
     213           0 :       if(maxswingpad < swingpad)
     214           0 :         maxswingpad=swingpad;
     215             :     }
     216           0 :     for (auto msiter = msInUse.begin(); msiter != msInUse.end(); ++msiter) {
     217           0 :       fillImgWeightCol(vi, inRec, *msiter, fieldsToUse, maxswingpad,
     218           0 :                        templateimage.shape(), cs);
     219             :     }
     220             :   }
     221           0 :   initialized_p = True;
     222           0 :   wgtTab_p->unlock();
     223           0 :   return imWgtColName_p;
     224           0 : }
     225             : 
     226           0 : void BriggsCubeWeightor::fillImgWeightCol(
     227             :     vi::VisibilityIterator2 &vi, const Record &inRec, const Int msid,
     228             :     std::vector<pair<Int, Int>> &fieldsToUse, const uInt swingpad,
     229             :     const IPosition &origShp, CoordinateSystem csOrig) {
     230           0 :   vi::VisBuffer2 *vb = vi.getVisBuffer();
     231           0 :   for (uInt k = 0; k < fieldsToUse.size(); ++k) {
     232           0 :     vi.originChunks();
     233           0 :     vi.origin();
     234             :     // cerr << "####nchannels " << vb->nChannels() << " swingpad " << swingpad
     235             :     // << endl;
     236           0 :     IPosition shp = origShp;
     237           0 :     nx_p = shp[0];
     238           0 :     ny_p = shp[1];
     239           0 :     CoordinateSystem cs = csOrig;
     240             :     // CoordinateSystem cs=templateimage.coordinates();
     241             : 
     242           0 :     Vector<String> units = cs.worldAxisUnits();
     243           0 :     units[0] = "rad";
     244           0 :     units[1] = "rad";
     245           0 :     cs.setWorldAxisUnits(units);
     246           0 :     Vector<Double> incr = cs.increment();
     247           0 :     uscale_p = (nx_p * incr[0]);
     248           0 :     vscale_p = (ny_p * incr[1]);
     249           0 :     uorigin_p = nx_p / 2;
     250           0 :     vorigin_p = ny_p / 2;
     251             :     // IPosition shp=templateimage.shape();
     252           0 :     shp[3] = shp[3] + swingpad; // add extra channels at begining and end;
     253           0 :     Vector<Double> refpix = cs.referencePixel();
     254           0 :     refpix[3] += swingpad / 2;
     255           0 :     cs.setReferencePixel(refpix);
     256             :     // cerr << "REFPIX " << refpix << " new SHAPE " << shp  << " swigpad " <<
     257             :     // swingpad  << " msid "<< msid << " fieldToUse.msid "
     258             :     // <<fieldsToUse[k].first << " fieldid " <<  fieldsToUse[k].second << endl;
     259           0 :     TempImage<Complex> newTemplate(shp, cs);
     260           0 :     Matrix<Double> sumWgts;
     261             : 
     262           0 :     initializeFTMachine(0, newTemplate, inRec);
     263           0 :     Matrix<Float> dummy;
     264             :     // cerr << "new template shape " << newTemplate.shape() << endl;
     265           0 :     ft_p[0]->initializeToSky(newTemplate, dummy, *vb);
     266           0 :     Vector<Double> convFunc(2 + superUniformBox_p, 1.0);
     267             :     // cerr << "superuniform box " << superUniformBox_p << endl;
     268           0 :     ft_p[0]->modifyConvFunc(convFunc, superUniformBox_p, 1);
     269           0 :     for (vi.originChunks(); vi.moreChunks(); vi.nextChunk()) {
     270           0 :       for (vi.origin(); vi.more(); vi.next()) {
     271             :         // cerr << "key and index "<< key << "   " << index << "   " <<
     272             :         // multiFieldMap_p[key] << endl;
     273           0 :         if ((vb->fieldId()[0] == fieldsToUse[k].second &&
     274           0 :              vb->msId() == fieldsToUse[k].first) ||
     275           0 :             fieldsToUse[k].first == -1) {
     276           0 :           ft_p[0]->put(*vb, -1, true, FTMachine::PSF);
     277             :         }
     278             :       }
     279             :     }
     280           0 :     Array<Float> griddedWeight;
     281           0 :     ft_p[0]->getGrid(griddedWeight);
     282             :     // cerr  << " griddedWeight Shape " << griddedWeight.shape() << endl;
     283             :     // grids_p[index]->put(griddedWeight.reform(newTemplate.shape()));
     284           0 :     sumWgts = ft_p[0]->getSumWeights();
     285             :     // cerr << "sumweight " << sumWgts[index] << endl;
     286             :     // clear the ftmachine
     287           0 :     ft_p[0]->finalizeToSky();
     288             : 
     289           0 :     Int nchan = newTemplate.shape()(3);
     290             :     // cerr << "rmode " << rmode_p << endl;
     291             : 
     292           0 :     for (uInt chan = 0; chan < uInt(nchan); ++chan) {
     293           0 :       IPosition start(4, 0, 0, 0, chan);
     294           0 :       IPosition end(4, nx_p - 1, ny_p - 1, 0, chan);
     295             :       Matrix<Float> gwt(
     296           0 :           griddedWeight(start, end).reform(IPosition(2, nx_p, ny_p)));
     297           0 :       if ((rmode_p == "norm" || rmode_p == "bwtaper") &&
     298           0 :           (sumWgts(0, chan) >
     299             :            0.0)) { // See CAS-13021 for bwtaper algorithm details
     300             :         // os << "Normal robustness, robust = " << robust << LogIO::POST;
     301           0 :         Double sumlocwt = 0.;
     302           0 :         for (Int vgrid = 0; vgrid < ny_p; vgrid++) {
     303           0 :           for (Int ugrid = 0; ugrid < nx_p; ugrid++) {
     304           0 :             if (gwt(ugrid, vgrid) > 0.0)
     305           0 :               sumlocwt += square(gwt(ugrid, vgrid));
     306             :           }
     307             :         }
     308           0 :         f2_p[0][chan] = square(5.0 * pow(10.0, Double(-robust_p))) /
     309           0 :                         (sumlocwt / (2 * sumWgts(0, chan)));
     310           0 :         d2_p[0][chan] = 1.0;
     311             : 
     312           0 :       } else if (rmode_p == "abs") {
     313             :         // os << "Absolute robustness, robust = " << robust << ", noise = "
     314             :         //    << noise.get("Jy").getValue() << "Jy" << LogIO::POST;
     315           0 :         f2_p[0][chan] = square(robust_p);
     316           0 :         d2_p[0][chan] = 2.0 * square(noise_p.get("Jy").getValue());
     317             : 
     318             :       } else {
     319           0 :         f2_p[0][chan] = 1.0;
     320           0 :         d2_p[0][chan] = 0.0;
     321             :       }
     322             : 
     323           0 :     } // chan
     324             : 
     325             :     // std::ofstream myfile;
     326             :     // myfile.open (wgtTab_p->tableName()+".txt");
     327           0 :     vi.originChunks();
     328           0 :     vi.origin();
     329           0 :     for (vi.originChunks(); vi.moreChunks(); vi.nextChunk()) {
     330           0 :       for (vi.origin(); vi.more(); vi.next()) {
     331           0 :         if ((msid < 0) || ((vb->msId()) == (msid))) {
     332           0 :           if ((vb->fieldId()[0] == fieldsToUse[k].second &&
     333           0 :                vb->msId() == fieldsToUse[k].first) ||
     334           0 :               fieldsToUse[k].first == -1) {
     335           0 :             Matrix<Float> imweight;
     336             :             /*///////////
     337             :               std::vector<Int> cmap=(ft_p[0]->channelMap(*vb)).tovector();
     338             :               int n=0;
     339             :               std::for_each(cmap.begin(), cmap.end(), [&n, &myfile](int
     340             :               &val){if(val > -1)myfile << " " << n; n++; }); myfile << "----msid
     341             :               " << vb->msId() << endl;
     342             :                   /////////////////////////////*/
     343           0 :             getWeightUniform(griddedWeight, imweight, *vb);
     344           0 :             rownr_t nRows = vb->nRows();
     345             :             // Int nChans=vb->nChannels();
     346           0 :             Vector<uInt> msId(nRows, uInt(vb->msId()));
     347           0 :             RowNumbers rowidsnr = vb->rowIds();
     348           0 :             Vector<uInt> rowids(rowidsnr.nelements());
     349           0 :             convertArray(rowids, rowidsnr);
     350           0 :             wgtTab_p->addRow(nRows, False);
     351           0 :             rownr_t endrow = wgtTab_p->nrow() - 1;
     352           0 :             rownr_t beginrow = endrow - nRows + 1;
     353             :             // Slicer sl(IPosition(2,beginrow,0), IPosition(2,endrow,nChans-1),
     354             :             // Slicer::endIsLast);
     355           0 :             ArrayColumn<Float> col(*wgtTab_p, "IMAGING_WEIGHT");
     356             :             // cerr << "sl length " << sl.length() << " array shape " <<
     357             :             // fakeweight.shape() << " col length " << col.nrow() << endl;
     358             :             // col.putColumnRange(sl, fakeweight);
     359             :             // cerr << "nrows " << nRows << " imweight.shape " <<
     360             :             // imweight.shape() << endl;
     361           0 :             for (rownr_t row = 0; row < nRows; ++row)
     362           0 :               col.put(beginrow + row, imweight.column(row));
     363             : 
     364           0 :             Slicer sl2(IPosition(1, endrow - nRows + 1), IPosition(1, endrow),
     365           0 :                        Slicer::endIsLast);
     366           0 :             ScalarColumn<uInt> col2(*wgtTab_p, "MSID");
     367           0 :             col2.putColumnRange(sl2, msId);
     368           0 :             ScalarColumn<uInt> col3(*wgtTab_p, "ROWID");
     369             : 
     370           0 :             col3.putColumnRange(sl2, rowids);
     371           0 :           }
     372             :         }
     373             :       }
     374             :     }
     375             :     // myfile.close();
     376           0 :   }
     377             : 
     378             :   ////Lets reset vi before returning
     379           0 :   vi.originChunks();
     380           0 :   vi.origin();
     381           0 : }
     382             : 
     383           0 : Int BriggsCubeWeightor::estimateSwingChanPad(vi::VisibilityIterator2 &vi,
     384             :                                              const Int msid,
     385             :                                              const CoordinateSystem &cs,
     386             :                                              const Int imNChan,
     387             :                                              const String &ephemtab) {
     388             : 
     389           0 :   vi.originChunks();
     390           0 :   vi.origin();
     391           0 :   vi::VisBuffer2 *vb = vi.getVisBuffer();
     392           0 :   Double freqbeg = cs.toWorld(IPosition(4, 0, 0, 0, 0))[3];
     393           0 :   Double freqend = cs.toWorld(IPosition(4, 0, 0, 0, imNChan - 1))[3];
     394           0 :   Double freqincr = fabs(cs.increment()[3]);
     395             : 
     396             :   SpectralCoordinate spCoord =
     397           0 :       cs.spectralCoordinate(cs.findCoordinate(Coordinate::SPECTRAL));
     398           0 :   MFrequency::Types freqframe = spCoord.frequencySystem(True);
     399             :   ////If using Undefined there is no Doppler correction to do
     400             :   // so no need of padding frequency
     401           0 :   if(freqframe == MFrequency::Undefined )
     402           0 :     return 0;
     403           0 :   Bool sameframe = True;
     404             : 
     405           0 :   uInt swingpad = 16;
     406           0 :   Double swingFreq = 0.0;
     407           0 :   Double minFreq = 1e99;
     408           0 :   Double maxFreq = 0.0;
     409           0 :   std::vector<Double> localminfreq, localmaxfreq, firstchanfreq;
     410           0 :   Int msID = -1;
     411           0 :   Int fieldID = -1;
     412           0 :   Int spwID = -1;
     413             :   ////TESTOO
     414             :   // int my_cpu_id;
     415             :   // MPI_Comm_rank(MPI_COMM_WORLD, &my_cpu_id);
     416             :   ///////////////////
     417             :   ///////
     418           0 :   for (vi.originChunks(); vi.moreChunks(); vi.nextChunk()) {
     419           0 :     for (vi.origin(); vi.more(); vi.next()) {
     420             :       // process for required msid
     421           0 :       if ((msid < 0) || (msid == vb->msId())) {   //note there is msid and msID
     422           0 :         if ((msID != vb->msId()) || (fieldID != vb->fieldId()(0)) ) 
     423             :         {
     424           0 :           if((spwID != vb->spectralWindows()(0)) || (!sameframe) )  // if already not sameframe no need to test further
     425           0 :             sameframe = sameframe && compareframe(freqframe, *vb);
     426           0 :           msID = vb->msId();
     427           0 :           fieldID = vb->fieldId()(0);
     428           0 :           spwID = vb->spectralWindows()(0);
     429             :           Double localBeg, localEnd;
     430           0 :           Double localNchan = imNChan > 1 ? Double(imNChan - 1) : 1.0;
     431           0 :           Double localStep = abs(freqend - freqbeg) / localNchan;
     432           0 :           if (freqbeg < freqend) {
     433           0 :             localBeg = freqbeg;
     434           0 :             localEnd = freqend;
     435             :           } else {
     436           0 :             localBeg = freqend;
     437           0 :             localEnd = freqbeg;
     438             :           }
     439           0 :           Vector<Int> spw, start, nchan;
     440           0 :           if (ephemtab.size() != 0) {
     441           0 :             MSUtil::getSpwInSourceFreqRange(spw, start, nchan, vb->ms(),
     442             :                                             localBeg, localEnd, localStep,
     443             :                                             ephemtab, fieldID);
     444             :           } else {
     445           0 :             MSUtil::getSpwInFreqRange(spw, start, nchan, vb->ms(), localBeg,
     446             :                                       localEnd, localStep, freqframe, fieldID);
     447             :             //cerr <<"SPWID " << spwID << " localBeg " << localBeg << " localEnd " << localEnd
     448             :             //     << " spw " << spw << " start " << start << " nchan " << nchan
     449             :             //     << endl;
     450             :           }
     451           0 :           for (uInt spwk = 0; spwk < spw.nelements(); ++spwk) {
     452           0 :             if (spw[spwk] == spwID) {
     453           0 :               Vector<Double> mschanfreq = (vb->subtableColumns())
     454           0 :                                               .spectralWindow()
     455           0 :                                               .chanFreq()(spw[spwk]);
     456           0 :               if (mschanfreq[start[spwk] + nchan[spwk] - 1] >
     457           0 :                   mschanfreq[start[spwk]]) {
     458           0 :                 localminfreq.push_back(mschanfreq[start[spwk]]);
     459           0 :                 localmaxfreq.push_back(
     460           0 :                     mschanfreq[start[spwk] + nchan[spwk] - 1]);
     461             :               } else {
     462           0 :                 localminfreq.push_back(
     463           0 :                     mschanfreq[start[spwk] + nchan[spwk] - 1]);
     464           0 :                 localmaxfreq.push_back(mschanfreq[start[spwk]]);
     465             :               }
     466           0 :               firstchanfreq.push_back(min(mschanfreq));
     467             :               // if(mschanfreq[start[spwk]+nchan[spwk]-1] <
     468             :               // localminfreq[localminfreq.size()-1])
     469             :               // localminfreq[localminfreq.size()-1]=mschanfreq[start[spwk]+nchan[spwk]-1];
     470           0 :               if (minFreq > localminfreq[localminfreq.size() - 1])
     471           0 :                 minFreq = localminfreq[localminfreq.size() - 1];
     472           0 :               if (maxFreq < localmaxfreq[localmaxfreq.size() - 1])
     473           0 :                 maxFreq = localmaxfreq[localmaxfreq.size() - 1];
     474           0 :             }
     475             :           }
     476           0 :         }
     477             : 
     478             :       } // input msid
     479             :     }
     480             :   }
     481           0 :   vi.originChunks();
     482           0 :   vi.origin();
     483           0 :   if(sameframe)    //no channel swing will happen
     484           0 :     return 0;
     485             :   // no matching spw for field and  in this data selection
     486           0 :   if(firstchanfreq.size()==0)
     487           0 :     return 0;
     488           0 :   auto itf = firstchanfreq.begin();
     489           0 :   auto itmax = localmaxfreq.begin();
     490           0 :   Double firstchanshift = 0.0;
     491           0 :   Double minfirstchan = min(Vector<Double>(firstchanfreq));
     492           0 :   for (auto itmin = localminfreq.begin(); itmin != localminfreq.end();
     493           0 :        ++itmin) {
     494           0 :     if (swingFreq < abs(*itmin - minFreq))
     495           0 :       swingFreq = abs(*itmin - minFreq);
     496           0 :     if (swingFreq < abs(*itmax - maxFreq))
     497           0 :       swingFreq = abs(*itmax - maxFreq);
     498           0 :     if (firstchanshift < abs(*itf - minfirstchan))
     499           0 :       firstchanshift = abs(*itf - minfirstchan);
     500           0 :     itf++;
     501           0 :     itmax++;
     502             :   }
     503           0 :   Int extrapad = max(min(4, Int(imNChan / 10)), 1);
     504           0 :   swingpad =
     505           0 :       2 * (Int(std::ceil((swingFreq + firstchanshift) / freqincr)) + extrapad);
     506             :   // cerr <<" swingfreq " << (swingFreq/freqincr) << " firstchanshift " <<
     507             :   // (firstchanshift/freqincr) << " SWINGPAD " << swingpad << endl;
     508             :   ////////////////
     509           0 :   return swingpad;
     510           0 : }
     511           0 : Bool BriggsCubeWeightor::compareframe(const MFrequency::Types freqFrame, const vi::VisBuffer2& vb){
     512           0 :   Int spwId = vb.spectralWindows()(0);
     513             :   MFrequency::Types dataFrame =
     514           0 :       (MFrequency::Types)vb.subtableColumns().spectralWindow().measFreqRef()(spwId);
     515           0 :   return (freqFrame == dataFrame);
     516             : }
     517           0 : String BriggsCubeWeightor::makeScratchImagingWeightTable(
     518             :     CountedPtr<Table> &weightTable, const String &filetag) {
     519             : 
     520             :   // String wgtname=File::newUniqueName(".", "IMAGING_WEIGHT").absoluteName();
     521           0 :   String wgtname = Path("IMAGING_WEIGHT_" + filetag).absoluteName();
     522           0 :   if (Table::isReadable(wgtname)) {
     523           0 :     weightTable = new Table(wgtname, Table::Update);
     524           0 :     if (weightTable->nrow() > 0)
     525           0 :       return wgtname;
     526           0 :     weightTable = nullptr;
     527           0 :     TableUtil::deleteTable(wgtname, False);
     528             :   }
     529             : 
     530           0 :   TableDesc td;
     531           0 :   uInt cache_val = 32768;
     532           0 :   td.comment() = "Imaging_weight";
     533           0 :   td.addColumn(ScalarColumnDesc<uInt>("MSID"));
     534           0 :   td.addColumn(ScalarColumnDesc<uInt>("ROWID"));
     535           0 :   td.addColumn(ArrayColumnDesc<Float>("IMAGING_WEIGHT", 1));
     536             : 
     537           0 :   td.defineHypercolumn("TiledImagingWeight", 2,
     538           0 :                        stringToVector("IMAGING_WEIGHT"));
     539           0 :   SetupNewTable newtab(wgtname, td, Table::New);
     540           0 :   IncrementalStMan incrStMan("MS_ID", cache_val);
     541           0 :   newtab.bindColumn("MSID", incrStMan);
     542           0 :   StandardStMan aipsStMan("ROWID", cache_val / 4);
     543           0 :   newtab.bindColumn("ROWID", aipsStMan);
     544           0 :   TiledShapeStMan tiledStMan("TiledImagingWeight", IPosition(2, 50, 500));
     545           0 :   newtab.bindColumn("IMAGING_WEIGHT", tiledStMan);
     546           0 :   weightTable = new Table(newtab);
     547             :   // weightTable->markForDelete();
     548           0 :   return wgtname;
     549           0 : }
     550             : 
     551           0 : void BriggsCubeWeightor::init(vi::VisibilityIterator2 &vi,
     552             :                               const ImageInterface<Complex> &templateimage,
     553             :                               const RecordInterface &inRec) {
     554             :   // cout << "BriggsCubeWeightor::init " << endl;
     555           0 :   LogIO os(LogOrigin("BriggsCubeWeightor", "constructor", WHERE));
     556             : 
     557             :   // freqInterpMethod_p=interpMethod;
     558             :   // freqFrameValid_p=freqFrameValid;
     559             :   // chanchunk may call the same object
     560           0 :   if (initialized_p && nx_p == templateimage.shape()(0) &&
     561           0 :       ny_p == templateimage.shape()(1)) {
     562           0 :     CoordinateSystem cs = templateimage.coordinates();
     563           0 :     Double freq = cs.toWorld(IPosition(4, 0, 0, 0, 0))[3];
     564           0 :     if (freq == refFreq_p)
     565           0 :       return;
     566           0 :   }
     567             :   // cerr << "in bgwt init " << endl;
     568             :   // Need to save previous wieght scheme of vi
     569           0 :   visWgt_p = vi.getImagingWeightGenerator();
     570           0 :   VisImagingWeight vWghtNat("natural");
     571           0 :   vi.useImagingWeight(vWghtNat);
     572           0 :   vi::VisBuffer2 *vb = vi.getVisBuffer();
     573           0 :   Int nIndices = 0;
     574           0 :   for (vi.originChunks(); vi.moreChunks(); vi.nextChunk()) {
     575           0 :     for (vi.origin(); vi.more(); vi.next()) {
     576           0 :       String key = String::toString(vb->msId()) + "_" +
     577           0 :                    String::toString(vb->fieldId()(0));
     578           0 :       Int index = 0;
     579           0 :       if (multiField_p) {
     580             :         // find how many indices will be needed
     581           0 :         index = multiFieldMap_p.size();
     582           0 :         if (multiFieldMap_p.count(key) < 1)
     583           0 :           multiFieldMap_p[key] = index;
     584           0 :         nIndices = multiFieldMap_p.size();
     585             :       } else {
     586           0 :         multiFieldMap_p[key] = 0;
     587           0 :         nIndices = 1;
     588             :       }
     589           0 :     }
     590             :   }
     591             :   // cerr << "nindices " << nIndices << endl;
     592           0 :   vi.originChunks();
     593           0 :   vi.origin();
     594             :   String key =
     595           0 :       String::toString(vb->msId()) + "_" + String::toString(vb->fieldId()(0));
     596           0 :   IPosition shp = templateimage.shape();
     597           0 :   nx_p = shp[0];
     598           0 :   ny_p = shp[1];
     599           0 :   CoordinateSystem cs = templateimage.coordinates();
     600           0 :   refFreq_p = cs.toWorld(IPosition(4, 0, 0, 0, 0))[3];
     601           0 :   Vector<String> units = cs.worldAxisUnits();
     602           0 :   units[0] = "rad";
     603           0 :   units[1] = "rad";
     604           0 :   cs.setWorldAxisUnits(units);
     605           0 :   Vector<Double> incr = cs.increment();
     606           0 :   uscale_p = (nx_p * incr[0]);
     607           0 :   vscale_p = (ny_p * incr[1]);
     608           0 :   uorigin_p = nx_p / 2;
     609           0 :   vorigin_p = ny_p / 2;
     610             :   ////TESTOO
     611             :   // IPosition shp=templateimage.shape();
     612           0 :   shp[3] = shp[3] + 4; // add two channel at begining and end;
     613           0 :   Vector<Double> refpix = cs.referencePixel();
     614           0 :   refpix[3] += 2;
     615           0 :   cs.setReferencePixel(refpix);
     616           0 :   TempImage<Complex> newTemplate(shp, cs);
     617             :   ///////////////////////
     618             :   // ImageInterface<Complex>& newTemplate=const_cast<ImageInterface<Complex>&
     619             :   // >(templateimage);
     620           0 :   Vector<Matrix<Double>> sumWgts(nIndices);
     621             : 
     622           0 :   for (int index = 0; index < nIndices; ++index) {
     623           0 :     initializeFTMachine(index, newTemplate, inRec);
     624           0 :     Matrix<Float> dummy;
     625             : 
     626           0 :     ft_p[index]->initializeToSky(newTemplate, dummy, *vb);
     627           0 :     Vector<Double> convFunc(2 + superUniformBox_p, 1.0);
     628             :     // cerr << "superuniform box " << superUniformBox_p << endl;
     629           0 :     ft_p[index]->modifyConvFunc(convFunc, superUniformBox_p, 1);
     630           0 :     for (vi.originChunks(); vi.moreChunks(); vi.nextChunk()) {
     631           0 :       for (vi.origin(); vi.more(); vi.next()) {
     632             : 
     633           0 :         key = String::toString(vb->msId()) + "_" +
     634           0 :               String::toString(vb->fieldId()(0));
     635             : 
     636             :         // cerr << "key and index "<< key << "   " << index << "   " <<
     637             :         // multiFieldMap_p[key] << endl;
     638           0 :         if (multiFieldMap_p[key] == index) {
     639           0 :           ft_p[index]->put(*vb, -1, true, FTMachine::PSF);
     640             :         }
     641             :       }
     642             :     }
     643           0 :     Array<Float> griddedWeight;
     644           0 :     ft_p[index]->getGrid(griddedWeight);
     645             :     // cerr << index << " griddedWeight Shape " << griddedWeight.shape() <<
     646             :     // endl;
     647           0 :     grids_p[index]->put(griddedWeight.reform(newTemplate.shape()));
     648           0 :     sumWgts[index] = ft_p[index]->getSumWeights();
     649             :     // cerr << "sumweight " << sumWgts[index] << endl;
     650             :     // clear the ftmachine
     651           0 :     ft_p[index]->finalizeToSky();
     652           0 :   }
     653             :   ////Lets reset vi before returning
     654           0 :   vi.originChunks();
     655           0 :   vi.origin();
     656             : 
     657           0 :   Int nchan = newTemplate.shape()(3);
     658           0 :   for (uInt index = 0; index < f2_p.nelements(); ++index) {
     659             :     // cerr << "rmode " << rmode_p << endl;
     660             : 
     661           0 :     for (uInt chan = 0; chan < uInt(nchan); ++chan) {
     662           0 :       IPosition start(4, 0, 0, 0, chan);
     663           0 :       IPosition shape(4, nx_p, ny_p, 1, 1);
     664           0 :       Array<Float> arr;
     665           0 :       grids_p[index]->getSlice(arr, start, shape, True);
     666           0 :       Matrix<Float> gwt(arr);
     667           0 :       if ((rmode_p == "norm" || rmode_p == "bwtaper") &&
     668           0 :           (sumWgts[index](0, chan) >
     669             :            0.0)) { // See CAS-13021 for bwtaper algorithm details
     670             :         // os << "Normal robustness, robust = " << robust << LogIO::POST;
     671           0 :         Double sumlocwt = 0.;
     672           0 :         for (Int vgrid = 0; vgrid < ny_p; vgrid++) {
     673           0 :           for (Int ugrid = 0; ugrid < nx_p; ugrid++) {
     674           0 :             if (gwt(ugrid, vgrid) > 0.0)
     675           0 :               sumlocwt += square(gwt(ugrid, vgrid));
     676             :           }
     677             :         }
     678           0 :         f2_p[index][chan] = square(5.0 * pow(10.0, Double(-robust_p))) /
     679           0 :                             (sumlocwt / (2 * sumWgts[index](0, chan)));
     680           0 :         d2_p[index][chan] = 1.0;
     681             : 
     682           0 :       } else if (rmode_p == "abs") {
     683             :         // os << "Absolute robustness, robust = " << robust << ", noise = "
     684             :         //    << noise.get("Jy").getValue() << "Jy" << LogIO::POST;
     685           0 :         f2_p[index][chan] = square(robust_p);
     686           0 :         d2_p[index][chan] = 2.0 * square(noise_p.get("Jy").getValue());
     687             : 
     688             :       } else {
     689           0 :         f2_p[index][chan] = 1.0;
     690           0 :         d2_p[index][chan] = 0.0;
     691             :       }
     692             : 
     693           0 :     } // chan
     694             :   }
     695           0 :   initialized_p = True;
     696           0 : }
     697             : 
     698           0 : void BriggsCubeWeightor::weightUniform(Matrix<Float> &imweight,
     699             :                                        const vi::VisBuffer2 &vb) {
     700             : 
     701             :   // cout << "BriggsCubeWeightor::weightUniform" << endl;
     702             : 
     703           0 :   if (!wgtTab_p.null())
     704           0 :     return readWeightColumn(imweight, vb);
     705             : 
     706           0 :   if (multiFieldMap_p.size() == 0)
     707           0 :     throw(AipsError("BriggsCubeWeightor has not been initialized"));
     708             :   String key =
     709           0 :       String::toString(vb.msId()) + "_" + String::toString(vb.fieldId()(0));
     710           0 :   Int index = multiFieldMap_p[key];
     711           0 :   Vector<Int> chanMap = ft_p[0]->channelMap(vb);
     712             :   // cerr << "weightuniform chanmap " << chanMap << endl;
     713             :   /// No matching channels
     714           0 :   if (max(chanMap) == -1)
     715           0 :     return;
     716           0 :   Int nvischan = vb.nChannels();
     717           0 :   rownr_t nRow = vb.nRows();
     718           0 :   Matrix<Double> uvw = vb.uvw();
     719           0 :   imweight.resize(nvischan, nRow);
     720           0 :   imweight.set(0.0);
     721             : 
     722           0 :   Matrix<Float> weight;
     723           0 :   VisImagingWeight::unPolChanWeight(weight, vb.weightSpectrum());
     724           0 :   Matrix<Bool> flag;
     725           0 :   cube2Matrix(vb.flagCube(), flag);
     726             : 
     727           0 :   Int nChanWt = weight.shape()(0);
     728           0 :   Double sumwt = 0.0;
     729             :   Float u, v;
     730             :   Double fracBW, nCellsBW, uvDistanceFactor;
     731           0 :   IPosition pos(4, 0);
     732             : 
     733           0 :   fracBW = fracBW_p;
     734           0 :   if (rmode_p == "bwtaper") // See CAS-13021 for bwtaper algorithm details
     735             :   {
     736           0 :     if (fracBW == 0.0) {
     737           0 :       throw(AipsError(
     738           0 :           "BriggsCubeWeightor fractional bandwith is not a valid value, 0.0."));
     739             :     }
     740             :     // cout << "BriggsCubeWeightor::weightUniform fracBW " << fracBW << endl;
     741             :   }
     742             : 
     743           0 :   for (rownr_t row = 0; row < nRow; row++) {
     744           0 :     for (Int chn = 0; chn < nvischan; chn++) {
     745           0 :       if ((!flag(chn, row)) && (chanMap(chn) > -1)) {
     746           0 :         pos(3) = chanMap(chn);
     747           0 :         Float f = vb.getFrequency(0, chn) / C::c;
     748           0 :         u = -uvw(0, row) * f;
     749           0 :         v = -uvw(1, row) * f;
     750           0 :         Int ucell = Int(std::round(uscale_p * u + uorigin_p));
     751           0 :         Int vcell = Int(std::round(vscale_p * v + vorigin_p));
     752           0 :         pos(0) = ucell;
     753           0 :         pos(1) = vcell;
     754             : 
     755           0 :         imweight(chn, row) = 0.0;
     756           0 :         if ((ucell > 0) && (ucell < nx_p) && (vcell > 0) && (vcell < ny_p)) {
     757           0 :           Float gwt = grids_p[index]->getAt(pos);
     758           0 :           if (gwt > 0) {
     759           0 :             imweight(chn, row) = weight(chn % nChanWt, row);
     760             : 
     761           0 :             if (rmode_p ==
     762             :                 "bwtaper") { // See CAS-13021 for bwtaper algorithm details
     763           0 :               nCellsBW = fracBW *
     764           0 :                          sqrt(pow(uscale_p * u, 2.0) + pow(vscale_p * v, 2.0));
     765           0 :               uvDistanceFactor = nCellsBW + 0.5;
     766           0 :               if (uvDistanceFactor < 1.5)
     767           0 :                 uvDistanceFactor = (4.0 - nCellsBW) / (4.0 - 2.0 * nCellsBW);
     768           0 :               imweight(chn, row) /=
     769           0 :                   gwt * f2_p[index][pos[3]] / uvDistanceFactor +
     770           0 :                   d2_p[index][pos[3]];
     771             :             } else {
     772           0 :               imweight(chn, row) /=
     773           0 :                   gwt * f2_p[index][pos[3]] + d2_p[index][pos[3]];
     774             :             }
     775             : 
     776           0 :             sumwt += imweight(chn, row);
     777             :           }
     778             :         }
     779             :       } else {
     780           0 :         imweight(chn, row) = 0.0;
     781             :       }
     782             :     }
     783             :   }
     784             : 
     785           0 :   if (visWgt_p.doFilter()) {
     786           0 :     visWgt_p.filter(imweight, flag, uvw, vb.getFrequencies(0), imweight);
     787             :   }
     788           0 : }
     789           0 : void BriggsCubeWeightor::readWeightColumn(
     790             :     casacore::Matrix<casacore::Float> &imweight, const vi::VisBuffer2 &vb) {
     791             : 
     792           0 :   if (vbrowms2wgtrow_p.size() == 0) {
     793           0 :     Vector<uInt> msids = ScalarColumn<uInt>(*wgtTab_p, "MSID").getColumn();
     794           0 :     Vector<rownr_t> msrowid(ScalarColumn<uInt>(*wgtTab_p, "ROWID").nrow());
     795           0 :     convertArray(msrowid, ScalarColumn<uInt>(*wgtTab_p, "ROWID").getColumn());
     796           0 :     for (uInt k = 0; k < msids.nelements(); ++k) {
     797           0 :       vbrowms2wgtrow_p[make_pair(msids[k], msrowid[k])] = k;
     798             :     }
     799             :     // cerr << "Map size " << vbrowms2wgtrow_p.size() << " max size " <<
     800             :     // vbrowms2wgtrow_p.max_size() << endl;
     801           0 :   }
     802           0 :   imweight.resize(vb.nChannels(), vb.nRows());
     803           0 :   uInt msidnow = vb.msId();
     804           0 :   RowNumbers rowIds = vb.rowIds();
     805           0 :   ArrayColumn<Float> imwgtcol(*wgtTab_p, "IMAGING_WEIGHT");
     806           0 :   for (rownr_t k = 0; k < (vb.nRows()); ++k) {
     807           0 :     rownr_t tabrow = vbrowms2wgtrow_p[make_pair(msidnow, rowIds[k])];
     808             :     // cerr << imwgtcol.get(tabrow).shape() << "   " <<
     809             :     // imweight.column(k).shape() << endl;
     810           0 :     imweight.column(k) = imwgtcol.get(tabrow);
     811             :   }
     812           0 : }
     813           0 : void BriggsCubeWeightor::getWeightUniform(const Array<Float> &wgtDensity,
     814             :                                           Matrix<Float> &imweight,
     815             :                                           const vi::VisBuffer2 &vb) {
     816             :   // cout << "BriggsCubeWeightor::getWeightUniform" << endl;
     817           0 :   Vector<Int> chanMap = ft_p[0]->channelMap(vb);
     818             :   // cerr << "weightuniform chanmap " << chanMap << endl;
     819             :   ////
     820             :   // std::vector<Int> cmap=chanMap.tovector();
     821             :   // int n=0;
     822             :   // std::for_each(cmap.begin(), cmap.end(), [&n](int &val){if(val > -1)cerr <<
     823             :   // " " << n; n++; }); cerr << "----msid " << vb.msId() << endl;
     824           0 :   Int nvischan = vb.nChannels();
     825           0 :   rownr_t nRow = vb.nRows();
     826           0 :   Matrix<Double> uvw = vb.uvw();
     827           0 :   imweight.resize(nvischan, nRow);
     828           0 :   imweight.set(0.0);
     829             :   /// No matching channels
     830           0 :   if (max(chanMap) == -1)
     831           0 :     return;
     832           0 :   Matrix<Float> weight;
     833           0 :   VisImagingWeight::unPolChanWeight(weight, vb.weightSpectrum());
     834           0 :   Matrix<Bool> flag;
     835           0 :   cube2Matrix(vb.flagCube(), flag);
     836             : 
     837           0 :   Int nChanWt = weight.shape()(0);
     838           0 :   Double sumwt = 0.0;
     839             :   Float u, v;
     840             :   Double fracBW, nCellsBW, uvDistanceFactor;
     841           0 :   IPosition pos(4, 0);
     842             : 
     843           0 :   fracBW = fracBW_p;
     844           0 :   if (rmode_p == "bwtaper") // See CAS-13021 for bwtaper algorithm details
     845             :   {
     846             :     // cout << "BriggsCubeWeightor::getWeightUniform bwtaper" << f2_p[0] <<
     847             :     // endl;
     848           0 :     if (fracBW == 0.0) {
     849           0 :       throw(AipsError(
     850           0 :           "BriggsCubeWeightor fractional bandwith is not a valid value, 0.0."));
     851             :     }
     852             :     // cout << "BriggsCubeWeightor::weightUniform fracBW " << fracBW << endl;
     853             :   }
     854             : 
     855           0 :   for (rownr_t row = 0; row < nRow; row++) {
     856           0 :     for (Int chn = 0; chn < nvischan; chn++) {
     857           0 :       if ((!flag(chn, row)) && (chanMap(chn) > -1)) {
     858           0 :         pos(3) = chanMap(chn);
     859           0 :         Float f = vb.getFrequency(0, chn) / C::c;
     860           0 :         u = -uvw(0, row) * f;
     861           0 :         v = -uvw(1, row) * f;
     862           0 :         Int ucell = Int(std::round(uscale_p * u + uorigin_p));
     863           0 :         Int vcell = Int(std::round(vscale_p * v + vorigin_p));
     864           0 :         pos(0) = ucell;
     865           0 :         pos(1) = vcell;
     866             :         ////TESTOO
     867             :         // if(row==0){
     868             : 
     869             :         //  ofstream myfile;
     870             :         //  myfile.open ("briggsLoc.txt", ios::out | ios::app | ios::ate );
     871             :         //  myfile << vb.rowIds()(0) << " uv " << uvw.column(0) << " loc " <<
     872             :         //  pos[0] << ", " << pos[1] << "\n"<< endl; myfile.close();
     873             : 
     874             :         //}
     875             :         //////
     876           0 :         imweight(chn, row) = 0.0;
     877           0 :         if ((ucell > 0) && (ucell < nx_p) && (vcell > 0) && (vcell < ny_p)) {
     878           0 :           Float gwt = wgtDensity(pos);
     879           0 :           if (gwt > 0) {
     880           0 :             imweight(chn, row) = weight(chn % nChanWt, row);
     881             : 
     882           0 :             if (rmode_p ==
     883             :                 "bwtaper") { // See CAS-13021 for bwtaper algorithm details
     884           0 :               nCellsBW = fracBW *
     885           0 :                          sqrt(pow(uscale_p * u, 2.0) + pow(vscale_p * v, 2.0));
     886           0 :               uvDistanceFactor = nCellsBW + 0.5;
     887           0 :               if (uvDistanceFactor < 1.5)
     888           0 :                 uvDistanceFactor = (4.0 - nCellsBW) / (4.0 - 2.0 * nCellsBW);
     889           0 :               imweight(chn, row) /=
     890           0 :                   gwt * f2_p[0][pos[3]] / uvDistanceFactor + d2_p[0][pos[3]];
     891             :             } else {
     892           0 :               imweight(chn, row) /= gwt * f2_p[0][pos[3]] + d2_p[0][pos[3]];
     893             :             }
     894             : 
     895           0 :             sumwt += imweight(chn, row);
     896             :           }
     897             :         }
     898             :         // else {
     899             :         //  imweight(chn,row)=0.0;
     900             :         // ndrop++;
     901             :         //}
     902             :       } else {
     903           0 :         imweight(chn, row) = 0.0;
     904             :       }
     905             :     }
     906             :   }
     907             : 
     908           0 :   if (visWgt_p.doFilter()) {
     909           0 :     visWgt_p.filter(imweight, flag, uvw, vb.getFrequencies(0), imweight);
     910             :   }
     911           0 : }
     912             : 
     913           0 : void BriggsCubeWeightor::initializeFTMachine(
     914             :     const uInt index, const ImageInterface<Complex> &templateimage,
     915             :     const RecordInterface &inRec) {
     916           0 :   Int nchan = templateimage.shape()(3);
     917           0 :   if (ft_p.nelements() <= index) {
     918           0 :     ft_p.resize(index + 1);
     919           0 :     grids_p.resize(index + 1);
     920           0 :     f2_p.resize(index + 1);
     921           0 :     d2_p.resize(index + 1);
     922           0 :     f2_p[index] = Vector<Float>(nchan, 0.0);
     923           0 :     d2_p[index] = Vector<Float>(nchan, 0.0);
     924             :   }
     925           0 :   ft_p[index] =
     926           0 :       new refim::GridFT(Long(1000000), Int(200), "BOX", 1.0, true, false);
     927             :   Int tmpInt;
     928           0 :   inRec.get("freqinterpmethod", tmpInt);
     929           0 :   freqInterpMethod_p =
     930           0 :       static_cast<InterpolateArray1D<Double, Complex>::InterpolationMethod>(
     931             :           tmpInt);
     932           0 :   ft_p[index]->setFreqInterpolation(freqInterpMethod_p);
     933           0 :   inRec.get("freqframevalid", freqFrameValid_p);
     934           0 :   ft_p[index]->setFrameValidity(freqFrameValid_p);
     935           0 :   String error;
     936           0 :   if (!(ft_p[index]->recoverMovingSourceState(error, inRec)))
     937           0 :     throw(AipsError(
     938           0 :         "BriggsCubeWeightor could not get the state of the ftmachine:" +
     939           0 :         error));
     940           0 :   Record rec = inRec.asRecord("movingdir_rec");
     941           0 :   MeasureHolder mh;
     942           0 :   if(!mh.fromRecord(error, rec))
     943           0 :     throw(AipsError(
     944           0 :         "BriggsCubeWeightor could not get movingdir_rec from the state of the ftmachine:" +
     945           0 :         error));
     946           0 :   MDirection movingdir=mh.asMDirection();
     947           0 :   if (inRec.isDefined("ephemeristable") && movingdir.getRefString().contains("COMET")) {
     948           0 :      String ephemtabname;
     949           0 :      inRec.get("ephemeristable", ephemtabname);
     950           0 :      ft_p[index]->setMovingSource(ephemtabname);
     951           0 :   }
     952           0 :   else if(movingdir.getRefString().contains("APP")){
     953           0 :     ft_p[index]->setMovingSource("TRACKFIELD");
     954             :   }
     955             :   // remember to make the stokes I
     956           0 :   grids_p[index] = new TempImage<Float>(templateimage.shape(),
     957           0 :                                         templateimage.coordinates(), 0.0);
     958           0 : }
     959           0 : void BriggsCubeWeightor::cube2Matrix(const Cube<Bool> &fcube,
     960             :                                      Matrix<Bool> &fMat) {
     961           0 :   fMat.resize(fcube.shape()[1], fcube.shape()[2]);
     962             :   Bool deleteIt1;
     963             :   Bool deleteIt2;
     964           0 :   const Bool *pcube = fcube.getStorage(deleteIt1);
     965           0 :   Bool *pflags = fMat.getStorage(deleteIt2);
     966           0 :   for (uInt row = 0; row < fcube.shape()[2]; row++) {
     967           0 :     for (Int chn = 0; chn < fcube.shape()[1]; chn++) {
     968           0 :       *pflags = *pcube++;
     969           0 :       for (Int pol = 1; pol < fcube.shape()[0]; pol++, pcube++) {
     970           0 :         *pflags = *pcube ? *pcube : *pflags;
     971             :       }
     972           0 :       pflags++;
     973             :     }
     974             :   }
     975           0 :   fcube.freeStorage(pcube, deleteIt1);
     976           0 :   fMat.putStorage(pflags, deleteIt2);
     977           0 : }
     978             : 
     979             : } // namespace refim
     980             : } // namespace casa

Generated by: LCOV version 1.16