File: imageweights.cpp

package info (click to toggle)
wsclean 2.8-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 2,196 kB
  • sloc: cpp: 34,504; ansic: 234; python: 174; makefile: 10
file content (474 lines) | stat: -rw-r--r-- 12,629 bytes parent folder | download
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
#include "imageweights.h"
#include "banddata.h"
#include "multibanddata.h"

#include "msproviders/msprovider.h"
#include "fitswriter.h"
#include "units/angle.h"
#include "wsclean/logger.h"

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

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::Grid(casacore::MeasurementSet& ms, const MSSelection& selection)
{
	if(_isGriddingFinished)
		throw std::runtime_error("Grid() called after a call to FinishGridding()");
	const MultiBandData bandData(ms.spectralWindow(), ms.dataDescription());
	casacore::ROScalarColumn<int> antenna1Column(ms, casacore::MS::columnName(casacore::MSMainEnums::ANTENNA1));
	casacore::ROScalarColumn<int> antenna2Column(ms, casacore::MS::columnName(casacore::MSMainEnums::ANTENNA2));
	casacore::ROScalarColumn<int> fieldIdColumn(ms, casacore::MS::columnName(casacore::MSMainEnums::FIELD_ID));
	casacore::ROScalarColumn<double> timeColumn(ms, casacore::MS::columnName(casacore::MSMainEnums::TIME));
	casacore::ROArrayColumn<double> uvwColumn(ms, casacore::MS::columnName(casacore::MSMainEnums::UVW));
	casacore::ROArrayColumn<float> weightColumn(ms, casacore::MS::columnName(casacore::MSMainEnums::WEIGHT_SPECTRUM));
	casacore::ROArrayColumn<bool> flagColumn(ms, casacore::MS::columnName(casacore::MSMainEnums::FLAG));
	casacore::ROScalarColumn<int> dataDescIdColumn(ms, ms.columnName(casacore::MSMainEnums::DATA_DESC_ID));
	
	const casacore::IPosition shape(flagColumn.shape(0));
	
	bool hasWeights = false;
	if(weightColumn.isDefined(0) && !_weightsAsTaper)
	{
		casacore::IPosition weightShape = weightColumn.shape(0);
		hasWeights = (weightShape == shape);
	}
	
	const size_t polarizationCount = shape[0];
	
	casacore::Array<casacore::Complex> dataArr(shape);
	casacore::Array<bool> flagArr(shape);
	casacore::Array<float> weightArr(shape);
	size_t timestep = 0;
	double time = timeColumn(0);
	
	if(!hasWeights)
		weightArr.set(1.0);
	
	for(size_t row=0; row!=ms.nrow(); ++row)
	{
		const int a1 = antenna1Column(row), a2 = antenna2Column(row), fieldId = fieldIdColumn(row);
		if(time != timeColumn(row))
		{
			++timestep;
			time = timeColumn(row);
		}
		const casacore::Vector<double> uvw = uvwColumn(row);
		if(selection.IsSelected(fieldId, timestep, a1, a2, uvw))
		{
			flagColumn.get(row, flagArr);
			if(hasWeights)
				weightColumn.get(row, weightArr);
			const BandData& curBand = bandData[dataDescIdColumn(row)];
			
			bool* flagIter = flagArr.cbegin();
			float* weightIter = weightArr.cbegin();
			
			double uInM = uvw(0), vInM = uvw(1);
			if(vInM < 0.0)
			{
				uInM = -uInM;
				vInM = -vInM;
			}
			
			size_t startChannel, endChannel;
			if(selection.HasChannelRange())
			{
				startChannel = selection.ChannelRangeStart();
				endChannel = selection.ChannelRangeEnd();
			}
			else {
				startChannel = 0;
				endChannel = curBand.ChannelCount();
			}
	
			for(size_t ch=startChannel; ch!=endChannel; ++ch)
			{
				double
					u = uInM / curBand.ChannelWavelength(ch),
					v = vInM / curBand.ChannelWavelength(ch);
				int x, y;
				uvToXY(u, v, x, y);
				if(isWithinLimits(x, y))
				{
					for(size_t p=0; p!=polarizationCount; ++p)
					{
						if(!*flagIter)
						{
							size_t index = (size_t) x + (size_t) y*_imageWidth;
							_grid[index] += *weightIter;
							_totalSum += *weightIter;
						}
						++flagIter;
						++weightIter;
					}
				}
				else {
					for(size_t p=0; p!=polarizationCount; ++p)
					{
						++flagIter;
						++weightIter;
					}
				}
			}
		}
	}
}

void ImageWeights::Grid(MSProvider& msProvider, const MSSelection& selection)
{
	if(_isGriddingFinished)
		throw std::runtime_error("Grid() called after a call to FinishGridding()");
	size_t polarizationCount = (msProvider.Polarization() == Polarization::Instrumental) ? 4 : 1;
	if(_weightMode.RequiresGridding())
	{
		SynchronizedMS ms(msProvider.MS());
		const MultiBandData bandData(ms->spectralWindow(), ms->dataDescription());
		MultiBandData selectedBand;
		if(selection.HasChannelRange())
			selectedBand = MultiBandData(bandData, selection.ChannelRangeStart(), selection.ChannelRangeEnd());
		else
			selectedBand = bandData;
		ao::uvector<float> weightBuffer(selectedBand.MaxChannels()*polarizationCount);
		
		msProvider.Reset();
		while(msProvider.CurrentRowAvailable())
		{
			double uInM, vInM, wInM;
			size_t dataDescId;
			msProvider.ReadMeta(uInM, vInM, wInM, dataDescId);
			msProvider.ReadWeights(weightBuffer.data());
			if(_weightsAsTaper)
			{
				for(float& w : weightBuffer)
				{
					if(w != 0.0)
						w = 1.0;
				}
			}
			const BandData& curBand = selectedBand[dataDescId];
			if(vInM < 0.0)
			{
				uInM = -uInM;
				vInM = -vInM;
			}
			
			const float* weightIter = weightBuffer.data();
			for(size_t ch=0; ch!=curBand.ChannelCount(); ++ch)
			{
				double
					u = uInM / curBand.ChannelWavelength(ch),
					v = vInM / curBand.ChannelWavelength(ch);
				for(size_t p=0; p!=polarizationCount; ++p)
				{
					Grid(u, v, *weightIter);
					++weightIter;
				}
			}
			
			msProvider.NextRow();
		}
	}
}

void ImageWeights::FinishGridding()
{
	if(_isGriddingFinished)
		throw std::runtime_error("FinishGridding() called twice");
	_isGriddingFinished = true;
	
	switch(_weightMode.Mode())
	{
		case WeightMode::BriggsWeighted:
		{
			double avgW = 0.0;
			for(ao::uvector<double>::const_iterator i=_grid.begin(); i!=_grid.end(); ++i)
				avgW += *i * *i;
			avgW /= _totalSum;
			double numeratorSqrt = 5.0 * exp10(-_weightMode.BriggsRobustness());
			double sSq = numeratorSqrt*numeratorSqrt / avgW;
			for(ao::uvector<double>::iterator i=_grid.begin(); i!=_grid.end(); ++i)
			{
				*i = 1.0 / (1.0 + *i * sSq);
			}
		}
		break;
		case WeightMode::UniformWeighted:
		{
			for(ao::uvector<double>::iterator i=_grid.begin(); i!=_grid.end(); ++i)
			{
				if(*i != 0.0)
					*i = 1.0 / *i;
				else
					*i = 0.0;
			}
		}
		break;
		case WeightMode::NaturalWeighted:
		{
			for(ao::uvector<double>::iterator i=_grid.begin(); i!=_grid.end(); ++i)
			{
				if(*i != 0.0)
					*i = 1.0;
			}
		}
		break;
	}
}

void ImageWeights::SetMinUVRange(double minUVInLambda)
{
	ao::uvector<double>::iterator i = _grid.begin();
	const double minSq = minUVInLambda*minUVInLambda;
	int halfWidth = _imageWidth/2;
	for(size_t y=0; y!=_imageHeight/2; ++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)
				*i = 0.0;
			++i;
		}
	}
}

void ImageWeights::SetMaxUVRange(double maxUVInLambda)
{
	ao::uvector<double>::iterator i = _grid.begin();
	const double maxSq = maxUVInLambda*maxUVInLambda;
	int halfWidth = _imageWidth/2;
	for(size_t y=0; y!=_imageHeight/2; ++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)
				*i = 0.0;
			++i;
		}
	}
}

void ImageWeights::SetTukeyTaper(double transitionSizeInLambda, double maxUVInLambda)
{
	ao::uvector<double>::iterator i = _grid.begin();
	const double maxUVSq = maxUVInLambda * maxUVInLambda;
	const double transitionDistSq = (maxUVInLambda-transitionSizeInLambda) * (maxUVInLambda-transitionSizeInLambda);
	for(size_t y=0; y!=_imageHeight/2; ++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)
				*i = 0.0;
			else if(distSq > transitionDistSq)
			{
				*i *= tukeyFrom0ToN(maxUVInLambda - sqrt(distSq), transitionSizeInLambda);
			}
			++i;
		}
	}
}

void ImageWeights::SetTukeyInnerTaper(double transitionSizeInLambda, double minUVInLambda)
{
	ao::uvector<double>::iterator i = _grid.begin();
	const double minUVSq = minUVInLambda * minUVInLambda;
	const double totalSizeSq = (minUVInLambda+transitionSizeInLambda) * (minUVInLambda+transitionSizeInLambda);
	for(size_t y=0; y!=_imageHeight/2; ++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)
				*i = 0.0;
			else if(distSq < totalSizeSq)
			{
				*i *= tukeyFrom0ToN(sqrt(distSq) - minUVInLambda, transitionSizeInLambda);
			}
			++i;
		}
	}
}

void ImageWeights::SetEdgeTaper(double sizeInLambda)
{
	ao::uvector<double>::iterator i = _grid.begin();
	double maxU, maxV;
	xyToUV(_imageWidth, _imageHeight/2, maxU, maxV);
	for(size_t y=0; y!=_imageHeight/2; ++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)
				*i = 0.0;
			++i;
		}
	}
}

void ImageWeights::SetEdgeTukeyTaper(double transitionSizeInLambda, double edgeSizeInLambda)
{
	ao::uvector<double>::iterator i = _grid.begin();
	double maxU, maxV;
	xyToUV(_imageWidth, _imageHeight/2, maxU, maxV);
	double totalSize = transitionSizeInLambda + edgeSizeInLambda;
	for(size_t y=0; y!=_imageHeight/2; ++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)
				*i = 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;
				*i *= tukeyFrom0ToN(ru, transitionSizeInLambda) * tukeyFrom0ToN(rv, transitionSizeInLambda);
			}
			++i;
		}
	}
}

void ImageWeights::GetGrid(double* image) const
{
	const double* srcPtr = _grid.data();
	for(size_t y=0; y!=_imageHeight/2; ++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
{
	ao::uvector<double> image(_imageWidth*_imageHeight);
	GetGrid(&image[0]);
	FitsWriter writer;
	writer.SetImageDimensions(_imageWidth, _imageHeight);
	writer.Write(filename, image.data());
}

void ImageWeights::RankFilter(double rankLimit, size_t windowSize)
{
	ao::uvector<double> newGrid(_grid);
	for(size_t y=0; y!=_imageHeight/2; ++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)
{
	Logger::Debug << "Applying " << 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;
	Logger::Debug << "UV taper: " << minusTwoSigmaSq << '\n';
	minusTwoSigmaSq *= -2.0 * minusTwoSigmaSq;
	for(size_t y=0; y!=_imageHeight/2; ++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);
}