File: imageweights.cpp

package info (click to toggle)
wsclean 3.6-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 16,296 kB
  • sloc: cpp: 129,246; python: 22,066; sh: 360; ansic: 230; makefile: 185
file content (390 lines) | stat: -rw-r--r-- 12,653 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#include "imageweights.h"

#include <aocommon/io/serialostream.h>
#include <aocommon/io/serialistream.h>
#include <aocommon/multibanddata.h>

#include "../msproviders/msprovider.h"
#include "../msproviders/msreaders/msreader.h"

#include <aocommon/fits/fitswriter.h>
#include <aocommon/banddata.h>
#include <aocommon/logger.h>
#include <aocommon/staticfor.h>
#include <aocommon/system.h>
#include <aocommon/units/angle.h>

#include <cmath>
#include <iostream>
#include <cassert>
#include <cstring>

namespace wsclean {

ImageWeights::ImageWeights()
    : _weightMode(WeightClass::Uniform),
      _imageWidth(0),
      _imageHeight(0),
      _pixelScaleX(0),
      _pixelScaleY(0),
      _totalSum(0.0),
      _isGriddingFinished(false),
      _weightsAsTaper(false) {}

ImageWeights::ImageWeights(const WeightMode& weightMode, size_t imageWidth,
                           size_t imageHeight, double pixelScaleX,
                           double pixelScaleY, bool weightsAsTaper,
                           double superWeight)
    : _weightMode(weightMode),
      _imageWidth(round(double(imageWidth) / superWeight)),
      _imageHeight(round(double(imageHeight) / superWeight)),
      _pixelScaleX(pixelScaleX),
      _pixelScaleY(pixelScaleY),
      _totalSum(0.0),
      _isGriddingFinished(false),
      _weightsAsTaper(weightsAsTaper) {
  if (_imageWidth % 2 != 0) ++_imageWidth;
  if (_imageHeight % 2 != 0) ++_imageHeight;
  _grid.assign(_imageWidth * _imageHeight / 2, 0.0);
}

void ImageWeights::Serialize(aocommon::SerialOStream& stream) const {
  _weightMode.Serialize(stream);
  stream.UInt64(_imageWidth)
      .UInt64(_imageHeight)
      .Double(_pixelScaleX)
      .Double(_pixelScaleY)
      .Vector(_grid)
      .Double(_totalSum)
      .Bool(_isGriddingFinished)
      .Bool(_weightsAsTaper);
}

void ImageWeights::Unserialize(aocommon::SerialIStream& stream) {
  _weightMode.Unserialize(stream);
  stream.UInt64(_imageWidth)
      .UInt64(_imageHeight)
      .Double(_pixelScaleX)
      .Double(_pixelScaleY)
      .Vector(_grid)
      .Double(_totalSum)
      .Bool(_isGriddingFinished)
      .Bool(_weightsAsTaper);
}

void ImageWeights::Grid(MSProvider& msProvider,
                        const aocommon::BandData& selectedBand) {
  assert(!_isGriddingFinished);
  const size_t polarizationCount = msProvider.NPolarizations();
  if (_weightMode.RequiresGridding()) {
    assert(selectedBand.ChannelCount() == msProvider.NChannels());
    aocommon::UVector<float> weightBuffer(selectedBand.ChannelCount() *
                                          polarizationCount);

    std::unique_ptr<MSReader> msReader = msProvider.MakeReader();
    while (msReader->CurrentRowAvailable()) {
      double uInM, vInM, wInM;
      msReader->ReadMeta(uInM, vInM, wInM);
      msReader->ReadWeights(weightBuffer.data());
      if (_weightsAsTaper) {
        for (float& w : weightBuffer) {
          if (w != 0.0) w = 1.0;
        }
      }
      if (vInM < 0.0) {
        uInM = -uInM;
        vInM = -vInM;
      }

      const float* weightIter = weightBuffer.data();
      for (size_t ch = 0; ch != selectedBand.ChannelCount(); ++ch) {
        const double u = uInM / selectedBand.ChannelWavelength(ch);
        const double v = vInM / selectedBand.ChannelWavelength(ch);
        for (size_t p = 0; p != polarizationCount; ++p) {
          Grid(u, v, *weightIter);
          ++weightIter;
        }
      }

      msReader->NextInputRow();
    }
  }
}

void ImageWeights::FinishGridding() {
  if (_isGriddingFinished)
    throw std::runtime_error("FinishGridding() called twice");
  _isGriddingFinished = true;

  switch (_weightMode.Class()) {
    case WeightClass::Briggs: {
      double avgW = 0.0;
      for (double val : _grid) avgW += val * val;
      avgW /= _totalSum;
      double numeratorSqrt =
          5.0 * std::exp((-M_LN10) * _weightMode.BriggsRobustness());
      double sSq = numeratorSqrt * numeratorSqrt / avgW;
      for (double& val : _grid) {
        // Values without coverage are left to zero, because they would
        // otherwise affect the weight rank filter.
        if (val != 0.0) val = 1.0 / (1.0 + val * sSq);
      }
    } break;
    case WeightClass::Uniform: {
      for (double& val : _grid) {
        if (val != 0.0)
          val = 1.0 / val;
        else
          val = 0.0;
      }
    } break;
    case WeightClass::Natural: {
      for (double& val : _grid) {
        if (val != 0.0) val = 1.0;
      }
    } break;
  }
}

void ImageWeights::SetMinUVRange(double minUVInLambda) {
  const double minSq = minUVInLambda * minUVInLambda;
  int halfWidth = _imageWidth / 2;
  aocommon::StaticFor<size_t> loop;
  loop.Run(0, _imageHeight / 2, [&](size_t yStart, size_t yEnd) {
    auto iter = _grid.begin() + yStart * _imageWidth;
    for (size_t y = yStart; y != yEnd; ++y) {
      for (size_t x = 0; x != _imageWidth; ++x) {
        int xi = int(x) - halfWidth;
        double u = double(xi) / (_imageWidth * _pixelScaleX);
        double v = double(y) / (_imageHeight * _pixelScaleY);
        if (u * u + v * v < minSq) *iter = 0.0;
        ++iter;
      }
    }
  });
}

void ImageWeights::SetMaxUVRange(double maxUVInLambda) {
  const double maxSq = maxUVInLambda * maxUVInLambda;
  int halfWidth = _imageWidth / 2;
  aocommon::StaticFor<size_t> loop;
  loop.Run(0, _imageHeight / 2, [&](size_t yStart, size_t yEnd) {
    auto iter = _grid.begin() + yStart * _imageWidth;
    for (size_t y = yStart; y != yEnd; ++y) {
      for (size_t x = 0; x != _imageWidth; ++x) {
        int xi = int(x) - halfWidth;
        double u = double(xi) / (_imageWidth * _pixelScaleX);
        double v = double(y) / (_imageHeight * _pixelScaleY);
        if (u * u + v * v > maxSq) *iter = 0.0;
        ++iter;
      }
    }
  });
}

void ImageWeights::SetTukeyTaper(double transitionSizeInLambda,
                                 double maxUVInLambda) {
  const double maxUVSq = maxUVInLambda * maxUVInLambda;
  const double transitionDistSq = (maxUVInLambda - transitionSizeInLambda) *
                                  (maxUVInLambda - transitionSizeInLambda);
  aocommon::StaticFor<size_t> loop;
  loop.Run(0, _imageHeight / 2, [&](size_t yStart, size_t yEnd) {
    auto iter = _grid.begin() + yStart * _imageWidth;
    for (size_t y = yStart; y != yEnd; ++y) {
      for (size_t x = 0; x != _imageWidth; ++x) {
        double u, v;
        xyToUV(x, y, u, v);
        double distSq = u * u + v * v;
        if (distSq > maxUVSq)
          *iter = 0.0;
        else if (distSq > transitionDistSq) {
          *iter *= tukeyFrom0ToN(maxUVInLambda - sqrt(distSq),
                                 transitionSizeInLambda);
        }
        ++iter;
      }
    }
  });
}

void ImageWeights::SetTukeyInnerTaper(double transitionSizeInLambda,
                                      double minUVInLambda) {
  const double minUVSq = minUVInLambda * minUVInLambda;
  const double totalSizeSq = (minUVInLambda + transitionSizeInLambda) *
                             (minUVInLambda + transitionSizeInLambda);
  aocommon::StaticFor<size_t> loop;
  loop.Run(0, _imageHeight / 2, [&](size_t yStart, size_t yEnd) {
    auto iter = _grid.begin() + yStart * _imageWidth;
    for (size_t y = yStart; y != yEnd; ++y) {
      for (size_t x = 0; x != _imageWidth; ++x) {
        double u, v;
        xyToUV(x, y, u, v);
        double distSq = u * u + v * v;
        if (distSq < minUVSq)
          *iter = 0.0;
        else if (distSq < totalSizeSq) {
          *iter *= tukeyFrom0ToN(sqrt(distSq) - minUVInLambda,
                                 transitionSizeInLambda);
        }
        ++iter;
      }
    }
  });
}

void ImageWeights::SetEdgeTaper(double sizeInLambda) {
  double maxU, maxV;
  xyToUV(_imageWidth, _imageHeight / 2, maxU, maxV);
  aocommon::StaticFor<size_t> loop;
  loop.Run(0, _imageHeight / 2, [&](size_t yStart, size_t yEnd) {
    auto iter = _grid.begin() + yStart * _imageWidth;
    for (size_t y = yStart; y != yEnd; ++y) {
      for (size_t x = 0; x != _imageWidth; ++x) {
        double u, v;
        xyToUV(x, y, u, v);
        if (maxU - std::fabs(u) < sizeInLambda ||
            maxV - std::fabs(v) < sizeInLambda)
          *iter = 0.0;
        ++iter;
      }
    }
  });
}

void ImageWeights::SetEdgeTukeyTaper(double transitionSizeInLambda,
                                     double edgeSizeInLambda) {
  double maxU, maxV;
  xyToUV(_imageWidth, _imageHeight / 2, maxU, maxV);
  double totalSize = transitionSizeInLambda + edgeSizeInLambda;
  aocommon::StaticFor<size_t> loop;
  loop.Run(0, _imageHeight / 2, [&](size_t yStart, size_t yEnd) {
    auto iter = _grid.begin() + yStart * _imageWidth;
    for (size_t y = yStart; y != yEnd; ++y) {
      for (size_t x = 0; x != _imageWidth; ++x) {
        double u, v;
        xyToUV(x, y, u, v);
        double uDist = maxU - std::fabs(u);
        double vDist = maxV - std::fabs(v);
        if (uDist < edgeSizeInLambda || vDist < edgeSizeInLambda)
          *iter = 0.0;
        else if (uDist < totalSize || vDist < totalSize) {
          double ru = uDist - edgeSizeInLambda;
          double rv = vDist - edgeSizeInLambda;
          if (ru > transitionSizeInLambda) ru = transitionSizeInLambda;
          if (rv > transitionSizeInLambda) rv = transitionSizeInLambda;
          *iter *= tukeyFrom0ToN(ru, transitionSizeInLambda) *
                   tukeyFrom0ToN(rv, transitionSizeInLambda);
        }
        ++iter;
      }
    }
  });
}

void ImageWeights::GetGrid(double* image) const {
  aocommon::StaticFor<size_t> loop;
  loop.Run(0, _imageHeight / 2, [&](size_t yStart, size_t yEnd) {
    const double* srcPtr = _grid.data() + (yStart * _imageWidth);
    for (size_t y = yStart; y != yEnd; ++y) {
      size_t yUpper = _imageHeight / 2 - 1 - y;
      size_t yLower = _imageHeight / 2 + y;
      double* upperRow = &image[yUpper * _imageWidth];
      double* lowerRow = &image[yLower * _imageWidth];
      for (size_t x = 0; x != _imageWidth; ++x) {
        upperRow[_imageWidth - x - 1] = *srcPtr;
        lowerRow[x] = *srcPtr;
        ++srcPtr;
      }
    }
  });
}

void ImageWeights::Save(const string& filename) const {
  aocommon::UVector<double> image(_imageWidth * _imageHeight);
  GetGrid(&image[0]);
  aocommon::FitsWriter writer;
  writer.SetImageDimensions(_imageWidth, _imageHeight);
  writer.Write(filename, image.data());
}

void ImageWeights::RankFilter(double rankLimit, size_t windowSize) {
  std::vector<double> newGrid(_grid);
  aocommon::StaticFor<size_t> loop;
  loop.Run(0, _imageHeight / 2, [&](size_t yStart, size_t yEnd) {
    for (size_t y = yStart; y != yEnd; ++y) {
      for (size_t x = 0; x != _imageWidth; ++x) {
        double w = _grid[y * _imageWidth + x];
        if (w != 0.0) {
          double mean = windowMean(x, y, windowSize);
          if (w > mean * rankLimit)
            newGrid[y * _imageWidth + x] = mean * rankLimit;
        }
      }
    }
  });
  _grid = newGrid;
}

void ImageWeights::SetGaussianTaper(double beamSize) {
  aocommon::Logger::Debug << "Applying "
                          << aocommon::units::Angle::ToNiceString(beamSize)
                          << " Gaussian taper...\n";
  double halfPowerUV = 1.0 / (beamSize * 2.0 * M_PI);
  const long double sigmaToHP = 2.0L * sqrtl(2.0L * logl(2.0L));
  double minusTwoSigmaSq = halfPowerUV * sigmaToHP;
  aocommon::Logger::Debug << "UV taper: " << minusTwoSigmaSq << '\n';
  minusTwoSigmaSq *= -2.0 * minusTwoSigmaSq;
  aocommon::StaticFor<size_t> loop;
  loop.Run(0, _imageHeight / 2, [&](size_t yStart, size_t yEnd) {
    for (size_t y = yStart; y != yEnd; ++y) {
      for (size_t x = 0; x != _imageWidth; ++x) {
        double val = _grid[y * _imageWidth + x];
        if (val != 0.0) {
          double u, v;
          xyToUV(x, y, u, v);
          double gaus = exp((u * u + v * v) / minusTwoSigmaSq);
          _grid[y * _imageWidth + x] = val * gaus;
        }
      }
    }
  });
}

double ImageWeights::windowMean(size_t x, size_t y, size_t windowSize) {
  size_t d = windowSize / 2;
  size_t x1, y1, x2, y2;
  if (x <= d)
    x1 = 0;
  else
    x1 = x - d;

  if (y <= d)
    y1 = 0;
  else
    y1 = y - d;

  if (x + d >= _imageWidth)
    x2 = _imageWidth;
  else
    x2 = x + d;

  if (y + d >= _imageHeight / 2)
    y2 = _imageHeight / 2;
  else
    y2 = y + d;

  size_t windowCount = 0;
  double windowSum = 0.0;
  for (size_t yi = y1; yi < y2; ++yi) {
    for (size_t xi = x1; xi < x2; ++xi) {
      double w = _grid[yi * _imageWidth + xi];
      if (w != 0.0) {
        ++windowCount;
        windowSum += w;
      }
    }
  }
  return windowSum / double(windowCount);
}

}  // namespace wsclean