File: indirectbaselinereader.cpp

package info (click to toggle)
aoflagger 2.13.0-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 4,232 kB
  • sloc: cpp: 61,805; python: 60; sh: 23; makefile: 8
file content (559 lines) | stat: -rw-r--r-- 20,045 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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
#include "indirectbaselinereader.h"

#include <casacore/ms/MeasurementSets/MeasurementSet.h>

#include <fstream>
#include <set>
#include <stdexcept>
#include <vector>

#include <fcntl.h>

#include <boost/filesystem.hpp>

#include "../structures/arraycolumniterator.h"
#include "../structures/scalarcolumniterator.h"
#include "../structures/timefrequencydata.h"
#include "../structures/system.h"

#include "../util/logger.h"
#include "../util/stopwatch.h"

#include "reorderedfilebuffer.h"

IndirectBaselineReader::IndirectBaselineReader(const std::string &msFile) : BaselineReader(msFile), _directReader(msFile),
_seqIndexTable(0),
_msIsReordered(false), _removeReorderedFiles(false), _reorderedDataFilesHaveChanged(false), _reorderedFlagFilesHaveChanged(false), _readUVW(false)
{
}

IndirectBaselineReader::~IndirectBaselineReader()
{
	if(_reorderedDataFilesHaveChanged)
		updateOriginalMSData();
	if(_reorderedFlagFilesHaveChanged)
		updateOriginalMSFlags();
	removeTemporaryFiles();
	
	delete _seqIndexTable;
	_filePositions.clear();
}

void IndirectBaselineReader::PerformReadRequests()
{
	initializeMeta();

	if(!_msIsReordered) reorderedMS();

	_results.clear();
	Logger::Debug << "Performing " << _readRequests.size() << " read requests...\n";
	for(size_t i=0;i<_readRequests.size();++i)
	{
		const ReadRequest request = _readRequests[i];
		_results.push_back(Result());
		const size_t width = ObservationTimes(request.sequenceId).size();
		for(size_t p=0;p<Polarizations().size();++p)
		{
			if(ReadData()) {
				_results[i]._realImages.push_back(Image2D::CreateZeroImagePtr(width, Set().FrequencyCount(request.spectralWindow)));
				_results[i]._imaginaryImages.push_back(Image2D::CreateZeroImagePtr(width, Set().FrequencyCount(request.spectralWindow)));
			}
			if(ReadFlags()) {
				// The flags should be initialized to true, as a baseline might
				// miss some time scans that other baselines do have, and these
				// should be flagged.
				_results[i]._flags.push_back(Mask2D::CreateSetMaskPtr<true>(width, Set().FrequencyCount(request.spectralWindow)));
			}
		}
		if(_readUVW)
			_results[i]._uvw = _directReader.ReadUVW(request.antenna1, request.antenna2, request.spectralWindow, request.sequenceId);
		else {
			_results[i]._uvw.clear();
			for(unsigned j=0;j<width;++j)
			_results[i]._uvw.push_back(UVW(0.0, 0.0, 0.0));
		}

		std::ifstream dataFile(DataFilename(), std::ifstream::binary);
		std::ifstream flagFile(FlagFilename(), std::ifstream::binary);
		size_t index = _seqIndexTable->Value(request.antenna1, request.antenna2, request.spectralWindow, request.sequenceId);
		size_t filePos = _filePositions[index];
		dataFile.seekg(filePos * (sizeof(float)*2), std::ios_base::beg);
		flagFile.seekg(filePos * sizeof(bool), std::ios_base::beg);

		const size_t bufferSize = Set().FrequencyCount(request.spectralWindow) * Polarizations().size();
		for(size_t x=0;x<width;++x)
		{
			std::vector<float> dataBuffer(bufferSize*2);
			std::vector<char> flagBuffer(bufferSize);
			dataFile.read((char *) &dataBuffer[0], bufferSize * sizeof(float) * 2);
			size_t dataBufferPtr = 0;
			flagFile.read((char *) &flagBuffer[0], bufferSize * sizeof(bool));
			size_t flagBufferPtr = 0;
			for(size_t f=0;f<Set().FrequencyCount(request.spectralWindow);++f) {
				for(size_t p=0;p<Polarizations().size();++p)
				{
					_results[i]._realImages[p]->SetValue(x, f, dataBuffer[dataBufferPtr]);
					++dataBufferPtr;
					_results[i]._imaginaryImages[p]->SetValue(x, f, dataBuffer[dataBufferPtr]);
					++dataBufferPtr;
					_results[i]._flags[p]->SetValue(x, f, flagBuffer[flagBufferPtr]);
					++flagBufferPtr;
				}
			}
		}
	}
	Logger::Debug << "Done reading.\n";

	_readRequests.clear();
}

void IndirectBaselineReader::PerformFlagWriteRequests()
{
	for(size_t i=0;i!=_writeRequests.size();++i)
	{
		const FlagWriteRequest request = _writeRequests[i];
		performFlagWriteTask(request.flags, request.antenna1, request.antenna2, request.spectralWindow, request.sequenceId);
	}
	_writeRequests.clear();
}

void IndirectBaselineReader::reorderedMS()
{
	boost::filesystem::path path(MetaFilename());
	bool reorderRequired = true;
	
	if(boost::filesystem::exists(path))
	{
		std::ifstream str(path.string().c_str());
		std::string name;
		std::getline(str, name);
		if(boost::filesystem::equivalent(boost::filesystem::path(name), Set().Path()))
		{
			Logger::Debug << "Measurement set has already been reordered; using old temporary files.\n";
			reorderRequired = false;
			_msIsReordered = true;
			_removeReorderedFiles = false;
			_reorderedDataFilesHaveChanged = false;
			_reorderedFlagFilesHaveChanged = false;
		}
	}
	if(reorderRequired)
	{
		reorderFull();
		std::ofstream str(path.string().c_str());
		str << Set().Path() << '\n';
	} else {
		size_t fileSize;
		makeLookupTables(fileSize);
	}
}

void IndirectBaselineReader::makeLookupTables(size_t &fileSize)
{
	std::vector<MeasurementSet::Sequence> sequences = Set().GetSequences();
	const size_t
		antennaCount = Set().AntennaCount(),
		polarizationCount = Polarizations().size(),
		bandCount = Set().BandCount(),
		sequencesPerBaselineCount = Set().SequenceCount();

	_seqIndexTable = new SeqIndexLookupTable(antennaCount, bandCount, sequencesPerBaselineCount);
	fileSize = 0;
	for(size_t i=0;i<sequences.size();++i)
	{
		// Initialize look-up table to get index into Sequence-array quickly
		const MeasurementSet::Sequence &s = sequences[i];
		_seqIndexTable->Value(s.antenna1, s.antenna2, s.spw, s.sequenceId) = i;
		
		// Initialize look-up table to go from sequence array to file position. Is in samples, so
		// multiple times sizeof(bool) or ..(float)) for exact position.
		_filePositions.push_back(fileSize);
		fileSize += ObservationTimes(s.sequenceId).size() * Set().FrequencyCount(s.spw) * polarizationCount;
	}
}

void IndirectBaselineReader::preAllocate(const char *filename, size_t fileSize)
{
	Logger::Debug << "Pre-allocating " << (fileSize/(1024*1024)) << " MB...\n";
	int fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, S_IWUSR | S_IRUSR);
	if(fd < 0)
	{
		std::ostringstream s;
		s << "Error while opening file '" << filename << "', check access rights and free space";
		throw std::runtime_error(s.str());
	}
#if defined(HAVE_POSIX_FALLOCATE)
	int allocResult = posix_fallocate(fd, 0, fileSize);
	close(fd);
	if(allocResult != 0)
	{
		Logger::Warn <<
			"Could not allocate temporary file '" << filename << "': posix_fallocate returned " << allocResult << ".\n"
			"Tried to allocate " << (fileSize/(1024*1024)) << " MB.\n"
			"Disk could be full or filesystem could not support fallocate.\n";
	}
#else
	close(fd);
	Logger::Warn << "Compiled without posix_fallocate() support: skipping pre-allocation.\n";
#endif
}

void IndirectBaselineReader::reorderFull()
{
	Stopwatch watch(true);
	
	casacore::Table &table = *Table();

	casacore::ROScalarColumn<double> timeColumn(*Table(), "TIME");
	casacore::ROArrayColumn<bool> flagColumn(table, "FLAG");
	casacore::ROScalarColumn<int> fieldIdColumn(table, "FIELD_ID"); 
	casacore::ROScalarColumn<int> dataDescIdColumn(table, "DATA_DESC_ID"); 
	casacore::ROScalarColumn<int> antenna1Column(table, "ANTENNA1"); 
	casacore::ROScalarColumn<int> antenna2Column(table, "ANTENNA2");

	size_t rowCount = table.nrow();
	if(rowCount == 0)
		throw std::runtime_error("Measurement set is empty (zero rows)");

	std::unique_ptr<casacore::ROArrayColumn<casacore::Complex>> dataColumn( new casacore::ROArrayColumn<casacore::Complex>(table, DataColumnName()) );

	std::vector<size_t> dataIdToSpw;
	Set().GetDataDescToBandVector(dataIdToSpw);
	
	size_t fileSize;
	makeLookupTables(fileSize);
	
	Logger::Debug << "Opening temporary files.\n";
	ReorderInfo reorderInfo;
	preAllocate(DataFilename(), fileSize*sizeof(float)*2);
	reorderInfo.dataFile.reset(new std::ofstream(DataFilename(), std::ofstream::binary | std::ios_base::in | std::ios_base::out));
	if(reorderInfo.dataFile->fail())
		throw std::runtime_error("Error: failed to open temporary data files for writing! Check access rights and free disk space.");
	
	preAllocate(FlagFilename(), fileSize*sizeof(bool));
	reorderInfo.flagFile.reset(new std::ofstream(FlagFilename(), std::ofstream::binary | std::ios_base::in | std::ios_base::out));
	if(reorderInfo.flagFile->fail())
		throw std::runtime_error("Error: failed to open temporary data files for writing! Check access rights and free disk space.");

	Logger::Debug << "Reordering data set...\n";
	
	size_t bufferMem = std::min<size_t>(System::TotalMemory()/10, 1024l*1024l*1024l);
	ReorderedFileBuffer dataFile(reorderInfo.dataFile.get(), bufferMem);
	ReorderedFileBuffer flagFile(reorderInfo.flagFile.get(), bufferMem/8);
	
	size_t prevFieldId = size_t(-1), sequenceId = size_t(-1);
	std::vector<std::size_t> writeFilePositions = _filePositions;
	std::vector<std::size_t> timePositions(_filePositions.size(), size_t(-1));
	double prevTime = -1.0;
	size_t timeIndex = size_t(-1);
	unsigned progress = 0;
	for(size_t rowIndex = 0; rowIndex!=rowCount; ++rowIndex)
	{
		if(rowIndex*1000/rowCount != progress)
		{
			progress = rowIndex*1000/rowCount;
			if(progress%10 == 0)
				Logger::Debug << "\nReorder progress: ";
			Logger::Debug << progress/10.0 << "% ";
			Logger::Debug.Flush();
		}
		size_t fieldId = fieldIdColumn(rowIndex);
		if(fieldId != prevFieldId)
		{
			prevFieldId = fieldId;
			sequenceId++;
			prevTime = -1.0;
		}
		double time = timeColumn(rowIndex);
		if(time != prevTime)
		{
			timeIndex = ObservationTimes(sequenceId).find(time)->second;
			prevTime = time;
		}
		
		size_t polarizationCount = Polarizations().size();
		size_t antenna1 = antenna1Column(rowIndex);
		size_t antenna2 = antenna2Column(rowIndex);
		size_t spw = dataIdToSpw[dataDescIdColumn(rowIndex)];
		size_t channelCount = Set().FrequencyCount(spw);
		size_t arrayIndex = _seqIndexTable->Value(antenna1, antenna2, spw, sequenceId);
		size_t &filePos = writeFilePositions[arrayIndex];
		size_t &timePos = timePositions[arrayIndex];
		size_t sampleCount = channelCount * polarizationCount;
		
		casacore::Array<casacore::Complex> data = (*dataColumn)(rowIndex);
		casacore::Array<bool> flag = flagColumn(rowIndex);
		
		dataFile.seekp(filePos * (sizeof(float)*2));
		flagFile.seekp(filePos * sizeof(bool));
		
		// If this baseline missed some time steps, pad the files
		// (we can't just skip over, because the flags should be set to true)
		++timePos;
		while(timePos < timeIndex)
		{
			const std::vector<float> nullData(sampleCount*2, 0.0);
			const std::vector<char> nullFlags(sampleCount, (char) true);
			dataFile.write(reinterpret_cast<const char*>(&*nullData.begin()), sampleCount * 2 * sizeof(float));
			flagFile.write(reinterpret_cast<const char*>(&*nullFlags.begin()), sampleCount * sizeof(bool));
			++timePos;
			filePos += sampleCount;
		}
		
		dataFile.write(reinterpret_cast<const char*>(&*data.cbegin()), sampleCount * 2 * sizeof(float));
		
		flagFile.write(reinterpret_cast<const char*>(&*flag.cbegin()), sampleCount * sizeof(bool));
		
		filePos += sampleCount;
	}
	
	uint64_t dataSetSize = (uint64_t) fileSize * (uint64_t) (sizeof(float)*2 + sizeof(bool));
	Logger::Debug << "Done reordering data set of " << dataSetSize/(1024*1024) << " MB in " << watch.Seconds() << " s (" << (long double) dataSetSize/(1024.0L*1024.0L*watch.Seconds()) << " MB/s)\n";
	_msIsReordered = true;
	_removeReorderedFiles = true;
	_reorderedDataFilesHaveChanged = false;
	_reorderedFlagFilesHaveChanged = false;
}

void IndirectBaselineReader::removeTemporaryFiles()
{
	if(_msIsReordered && _removeReorderedFiles)
	{
		boost::filesystem::remove(MetaFilename());
		boost::filesystem::remove(DataFilename());
		boost::filesystem::remove(FlagFilename());
		Logger::Debug << "Temporary files removed.\n";
	}
	_msIsReordered = false;
	_removeReorderedFiles = false;
	_reorderedDataFilesHaveChanged = false;
	_reorderedFlagFilesHaveChanged = false;
}

void IndirectBaselineReader::PerformDataWriteTask(std::vector<Image2DCPtr> _realImages, std::vector<Image2DCPtr> _imaginaryImages, int antenna1, int antenna2, int spectralWindow, unsigned sequenceId)
{
	initializeMeta();

	Logger::Debug << "Performing data write task with indirect baseline reader...\n";

	const size_t polarizationCount = Polarizations().size();
	
	if(_realImages.size() != polarizationCount || _imaginaryImages.size() != polarizationCount)
		throw std::runtime_error("PerformDataWriteTask: input format did not match number of polarizations in measurement set");
	
	for(size_t i=1;i<_realImages.size();++i)
	{
		if(_realImages[0]->Width() != _realImages[i]->Width() || _realImages[0]->Height() != _realImages[i]->Height() || _realImages[0]->Width() != _imaginaryImages[i]->Width() || _realImages[0]->Height() != _imaginaryImages[i]->Height())
		throw std::runtime_error("PerformDataWriteTask: width and/or height of input images did not match");
	}
	
	if(!_msIsReordered) reorderedMS();
	
	const size_t width = _realImages[0]->Width();
	const size_t bufferSize = Set().FrequencyCount(spectralWindow) * Polarizations().size();
	
	std::ofstream dataFile(DataFilename(), std::ofstream::binary | std::ios_base::in | std::ios_base::out);
	size_t index = _seqIndexTable->Value(antenna1, antenna2, spectralWindow, sequenceId);
	size_t filePos = _filePositions[index];
	dataFile.seekp(filePos*(sizeof(float)*2), std::ios_base::beg);
	
	std::vector<float> dataBuffer(bufferSize*2);
	for(size_t x=0;x<width;++x)
	{
		size_t dataBufferPtr = 0;
		for(size_t f=0;f<Set().FrequencyCount(spectralWindow);++f) {
			for(size_t p=0; p<Polarizations().size(); ++p)
			{
				dataBuffer[dataBufferPtr] = _realImages[p]->Value(x, f);
				++dataBufferPtr;
				dataBuffer[dataBufferPtr] = _imaginaryImages[p]->Value(x, f);
				++dataBufferPtr;
			}
		}

		dataFile.write(reinterpret_cast<char*>(&dataBuffer[0]), bufferSize * sizeof(float) * 2);
		if(dataFile.bad())
			throw std::runtime_error("Error: failed to update temporary data files! Check access rights and free disk space.");
	}
	
	_reorderedDataFilesHaveChanged = true;
	
	Logger::Debug << "Done writing.\n";
}

void IndirectBaselineReader::performFlagWriteTask(std::vector<Mask2DCPtr> flags, unsigned antenna1, unsigned antenna2, unsigned spw, unsigned sequenceId)
{
	initializeMeta();

	const unsigned polarizationCount = Polarizations().size();
	
	if(flags.size() != polarizationCount)
		throw std::runtime_error("PerformDataWriteTask: input format did not match number of polarizations in measurement set");
	
	for(size_t i=1;i<flags.size();++i)
	{
		if(flags[0]->Width() != flags[i]->Width() || flags[0]->Height() != flags[i]->Height())
		throw std::runtime_error("PerformDataWriteTask: width and/or height of input images did not match");
	}
	
	if(!_msIsReordered) reorderedMS();
	
	const size_t width = flags[0]->Width();
	const size_t bufferSize = Set().FrequencyCount(spw) * Polarizations().size();
	
	std::ofstream flagFile(FlagFilename(), std::ofstream::binary | std::ios_base::in | std::ios_base::out);
	size_t index = _seqIndexTable->Value(antenna1, antenna2, spw, sequenceId);
	size_t filePos = _filePositions[index];
	flagFile.seekp(filePos*(sizeof(bool)), std::ios_base::beg);
	
	std::unique_ptr<bool[]> flagBuffer( new bool[bufferSize] );
	for(size_t x=0;x<width;++x)
	{
		size_t flagBufferPtr = 0;
		for(size_t f=0;f<Set().FrequencyCount(spw);++f) {
			for(size_t p=0; p<polarizationCount; ++p)
			{
				flagBuffer[flagBufferPtr] = flags[p]->Value(x, f);
				++flagBufferPtr;
			}
		}

		flagFile.write(reinterpret_cast<char*>(flagBuffer.get()), bufferSize * sizeof(bool));
		if(flagFile.bad())
			throw std::runtime_error("Error: failed to update temporary flag files! Check access rights and free disk space.");
	}
	
	_reorderedFlagFilesHaveChanged = true;
}

template<bool UpdateData, bool UpdateFlags>
void IndirectBaselineReader::updateOriginalMS()
{
	casacore::Table &table = *Table();

	casacore::ROScalarColumn<double> timeColumn(*Table(), "TIME");
	casacore::ROScalarColumn<int> antenna1Column(table, "ANTENNA1"); 
	casacore::ROScalarColumn<int> antenna2Column(table, "ANTENNA2");
	casacore::ROScalarColumn<int> fieldIdColumn(table, "FIELD_ID");
	casacore::ROScalarColumn<int> dataDescIdColumn(table, "DATA_DESC_ID");
	casacore::ArrayColumn<bool> flagColumn(table, "FLAG");
	std::unique_ptr<casacore::ArrayColumn<casacore::Complex>> dataColumn ( new casacore::ArrayColumn<casacore::Complex>(table, DataColumnName()) );

	int rowCount = table.nrow();

	std::vector<MeasurementSet::Sequence> sequences = Set().GetSequences();
	std::vector<size_t> dataIdToSpw;
	Set().GetDataDescToBandVector(dataIdToSpw);
	
	size_t polarizationCount = Polarizations().size();

	Logger::Debug << "Opening updated files\n";
	UpdateInfo updateInfo;
	
	if(UpdateData)
	{
		updateInfo.dataFile.reset(new std::ifstream(DataFilename(), std::ifstream::binary));
		if(updateInfo.dataFile->fail())
			throw std::runtime_error("Failed to open temporary data file");
	}
	if(UpdateFlags)
	{
		updateInfo.flagFile.reset(new std::ifstream(FlagFilename(), std::ifstream::binary));
		if(updateInfo.flagFile->fail())
			throw std::runtime_error("Failed to open temporary flag file");
	}

	size_t prevFieldId = size_t(-1), sequenceId = size_t(-1);
	std::vector<size_t> updatedFilePos = _filePositions;
	std::vector<size_t> timePositions(updatedFilePos.size(), size_t(-1));
	double prevTime = -1.0;
	size_t timeIndex = size_t(-1);
	for(int rowIndex = 0; rowIndex!=rowCount; ++rowIndex)
	{
		size_t fieldId = fieldIdColumn(rowIndex);
		if(fieldId != prevFieldId)
		{
			prevFieldId = fieldId;
			sequenceId++;
		}
		double time = timeColumn(rowIndex);
		if(time != prevTime)
		{
			timeIndex = ObservationTimes(sequenceId).find(time)->second;
			prevTime = time;
		}
		
		size_t antenna1 = antenna1Column(rowIndex);
		size_t antenna2 = antenna2Column(rowIndex);
		size_t spw = dataIdToSpw[dataDescIdColumn(rowIndex)];
		size_t channelCount = Set().FrequencyCount(spw);
		size_t arrayIndex = _seqIndexTable->Value(antenna1, antenna2, spw, sequenceId);
		size_t sampleCount = channelCount * polarizationCount;
		size_t &filePos = updatedFilePos[arrayIndex];
		size_t &timePos = timePositions[arrayIndex];
		
		casacore::IPosition shape(2, polarizationCount, channelCount);
		
		// Skip over samples in the temporary files that are missing in the measurement set
		++timePos;
		while(timePos < timeIndex)
		{
			filePos += sampleCount;
			++timePos;
		}
		
		if(UpdateData)
		{
			casacore::Array<casacore::Complex> data(shape);
			
			std::ifstream &dataFile = *updateInfo.dataFile;
			dataFile.seekg(filePos*(sizeof(float)*2), std::ios_base::beg);
			dataFile.read(reinterpret_cast<char*>(&*data.cbegin()), sampleCount * 2 * sizeof(float));
			if(dataFile.fail())
				throw std::runtime_error("Error: failed to read temporary data files!");
						
			dataColumn->basePut(rowIndex, data);
		}
		if(UpdateFlags)
		{
			casacore::Array<bool> flagArray(shape);
			
			std::ifstream &flagFile = *updateInfo.flagFile;
			flagFile.seekg(filePos*sizeof(bool), std::ios_base::beg);
			flagFile.read(reinterpret_cast<char*>(&*flagArray.cbegin()), sampleCount * sizeof(bool));
			if(flagFile.fail())
				throw std::runtime_error("Error: failed to read temporary flag files!");
			
			flagColumn.basePut(rowIndex, flagArray);
		}
		
		filePos += sampleCount;
	}
	
	Logger::Debug << "Freeing the data\n";
	
	// Close the files
	updateInfo.dataFile.reset();
	updateInfo.flagFile.reset();

	if(UpdateData)
		Logger::Debug << "Done updating measurement set data\n";
	if(UpdateFlags)
		Logger::Debug << "Done updating measurement set flags\n";
}

void IndirectBaselineReader::updateOriginalMSData()
{
	Logger::Debug << "Data was changed, need to update the original MS...\n";
	updateOriginalMS<true, false>();
	_reorderedDataFilesHaveChanged = false;
}

void IndirectBaselineReader::updateOriginalMSFlags()
{
	Stopwatch watch(true);
	Logger::Debug << "Flags were changed, need to update the original MS...\n";
	updateOriginalMS<false, true>();
	_reorderedFlagFilesHaveChanged = false;
	Logger::Debug << "Storing flags toke: " << watch.ToString() << '\n';
}