File: runner.cpp

package info (click to toggle)
aoflagger 3.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 4,476 kB
  • sloc: cpp: 51,868; python: 152; sh: 25; makefile: 17
file content (254 lines) | stat: -rw-r--r-- 8,631 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
#include "runner.h"
#include "baselineiterator.h"

#include "../lua/luathreadgroup.h"
#include "../lua/scriptdata.h"
#include "../lua/optionsfunction.h"
#include "../lua/telescopefile.h"

#include "../quality/statisticscollection.h"

#include "../structures/msmetadata.h"

#include "../imagesets/joinedspwset.h"
#include "../imagesets/msimageset.h"
#include "../imagesets/msoptions.h"

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

#include <boost/date_time/posix_time/posix_time.hpp>

#include <fstream>

using namespace rfiStrategy;

// The order of initialization:
// 1. If Lua strategy given, load Lua strategy
// 2. Determine options
// 3. For each run and each file:
//   a) If no Lua strategy was given, open file and load corresponding Lua strategy
//   b) Run strategy

void Runner::Run()
{
	std::map<std::string, Options> optionsForAllRuns;
	{
		LuaThreadGroup lua(1);
		loadStrategy(lua, _cmdLineOptions, std::unique_ptr<rfiStrategy::ImageSet>());
		Logger::Debug << "Loading options from strategy...\n";
		optionsForAllRuns = OptionsFunction::GetOptions(lua.GetThread(0).State(), _cmdLineOptions);
	} // Let threadgroup go out of scope
	if(optionsForAllRuns.empty())
		optionsForAllRuns.emplace("main", _cmdLineOptions);
	for(const std::pair<std::string, Options>& singleRunOptions : optionsForAllRuns)
	{
		Logger::Debug << "Starting run '" + singleRunOptions.first + "'...\n";
		run(singleRunOptions.second);
	}
}

void Runner::loadStrategy(LuaThreadGroup& lua, const Options& options, const std::unique_ptr<rfiStrategy::ImageSet>& imageSet)
{
	if(!options.preamble.empty())
	{
		Logger::Debug << "Running preample...\n";
		lua.RunPreamble(options.preamble);
	}
	
	std::string executeFilename;
	// Execute filename override strategy filename, so that the options() function
	// can be in a different file than the execute functions.
	if(!options.executeFilename.empty())
		executeFilename = options.executeFilename;
	if(!options.strategyFilename.empty())
		executeFilename = options.strategyFilename;
	if(executeFilename.empty() && imageSet) {
		std::string telescopeName = imageSet->TelescopeName();
		TelescopeFile::TelescopeId telescopeId = TelescopeFile::TelescopeIdFromName(telescopeName);
		if(telescopeId == TelescopeFile::GENERIC_TELESCOPE)
		{
			Logger::Warn << 
				"**\n"
				"** Measurement set specified the following telescope name: '" << telescopeName << "'\n"
				"** No good strategy is known for this telescope!\n"
				"** A generic strategy will be used which might not be optimal.\n"
				"**\n";
		}
		else {
			Logger::Info
				<< "\nUsing a stock strategy that was optimized for the following telescope:\n"
				<< "- " << TelescopeFile::TelescopeDescription(telescopeId) << "\n"
				<< "Stock strategies might not perform well. It is recommended to make your own strategy\n"
				<< "using the rfigui and specify it with the '-strategy ...' parameter.\n\n";
		}
		executeFilename = TelescopeFile::FindStrategy("", telescopeId);
	}
	if(!executeFilename.empty())
	{
		try {
			Logger::Debug << "Opening strategy file '" << executeFilename << "'\n";
			lua.LoadFile(executeFilename.c_str());
			Logger::Debug << "Strategy parsed succesfully.\n";
		} catch(std::exception &e)
		{
			throw std::runtime_error(
				"ERROR: Reading strategy file \"" + executeFilename + "\" failed!\n"
				"\nThe thrown exception was:\n" + e.what() + "\n");
		}
	}
}

void Runner::run(const Options& options)
{
	Logger::SetVerbosity(options.logVerbosity.value_or(Logger::NormalVerbosity));
	
	size_t threadCount = options.CalculateThreadCount();
	Logger::Debug << "Number of threads: " << options.threadCount << "\n";

	for(const std::string& filename : _cmdLineOptions.filenames)
	{
		processFile(options, filename, threadCount);
	}
}

std::unique_ptr<ImageSet> Runner::initializeImageSet(const Options& options, FileOptions& fileOptions)
{
	MSOptions msOptions;
	msOptions.ioMode = options.readMode.value_or(BaselineIOMode::AutoReadMode);
	msOptions.baselineIntegration = options.baselineIntegration;

	std::unique_ptr<ImageSet> imageSet(ImageSet::Create(std::vector<std::string>{fileOptions.filename}, msOptions));
	bool isMS = dynamic_cast<MSImageSet*>(imageSet.get()) != nullptr;
	if(isMS)
	{ 
		MSImageSet* msImageSet = static_cast<MSImageSet*>(imageSet.get());
		if(options.dataColumn.empty())
			msImageSet->SetDataColumnName("DATA");
		else
			msImageSet->SetDataColumnName(options.dataColumn);
		msImageSet->SetReadUVW(options.readUVW.get_value_or(false));
		// during the first iteration, the nr of intervals hasn't been calculated yet. Do that now.
		if(fileOptions.intervalIndex == 0)
		{
			if(options.chunkSize != 0)
			{
				msImageSet->SetInterval(fileOptions.intervalStart, fileOptions.intervalEnd);
				const size_t obsTimesSize = msImageSet->MetaData().GetObservationTimesSet().size();
				fileOptions.nIntervals = (obsTimesSize + options.chunkSize - 1) / options.chunkSize;
				Logger::Info << "Maximum interval size of " << options.chunkSize << " timesteps for total of " << obsTimesSize << " timesteps results in " << fileOptions.nIntervals << " intervals.\n";
				if(options.startTimestep)
					fileOptions.resolvedIntStart = *options.startTimestep;
				else
					fileOptions.resolvedIntStart = 0;
				if(options.endTimestep)
					fileOptions.resolvedIntEnd = *options.endTimestep;
				else
					fileOptions.resolvedIntEnd = obsTimesSize + fileOptions.resolvedIntStart;
			}
			else {
				fileOptions.nIntervals = 1;
			}
		}
		if(fileOptions.nIntervals == 1)
			msImageSet->SetInterval(fileOptions.intervalStart, fileOptions.intervalEnd);
		else {
			size_t nTimes = fileOptions.resolvedIntEnd - fileOptions.resolvedIntStart;
			size_t start = fileOptions.resolvedIntStart + fileOptions.intervalIndex*nTimes/fileOptions.nIntervals;
			size_t end = fileOptions.resolvedIntStart + (fileOptions.intervalIndex+1)*nTimes/fileOptions.nIntervals;
			Logger::Info << "Starting flagging of interval " << fileOptions.intervalIndex << ", timesteps " << start << " - " << end << '\n';
			msImageSet->SetInterval(start, end);
		}
		if(options.combineSPWs)
		{
			msImageSet->Initialize();
			imageSet.release();
			std::unique_ptr<MSImageSet> msImageSetPtr(msImageSet);
			imageSet.reset(new JoinedSPWSet(std::move(msImageSetPtr)));
		}
	}
	imageSet->Initialize();
	return imageSet;
}

void Runner::processFile(const Options& options, const std::string& filename, size_t threadCount)
{
	Logger::Info << "Starting strategy on " << to_simple_string(boost::posix_time::microsec_clock::local_time()) << '\n';
	
	bool skip = false;
	if(options.skipFlagged)
	{
		MSMetaData set(filename);
		if(set.HasAOFlaggerHistory())
		{
			skip = true;
			Logger::Info << "Skipping " << filename << ",\n"
				"because the set contains AOFlagger history and -skip-flagged was given.\n";
		}
	}
	
	if(!skip)
	{
		ScriptData scriptData;
		FileOptions fileOptions;
		fileOptions.intervalStart = options.startTimestep;
		fileOptions.intervalEnd = options.endTimestep;
		fileOptions.filename = filename;
		bool isMS = false;
		while(fileOptions.intervalIndex < fileOptions.nIntervals)
		{
			std::unique_ptr<ImageSet> imageSet = initializeImageSet(options, fileOptions);
			isMS = dynamic_cast<MSImageSet*>(imageSet.get()) != nullptr;
			
			LuaThreadGroup lua(threadCount);

			loadStrategy(lua, options, imageSet);

			std::mutex ioMutex;
			BaselineIterator blIterator(&ioMutex, options);
			blIterator.Run(*imageSet, lua, scriptData);
			
			++fileOptions.intervalIndex;
		}

		if(isMS)
			writeHistory(options, filename);
		
		finishStatistics(filename, scriptData, isMS);
	}
}

void Runner::writeHistory(const Options& options, const std::string &filename)
{
	MSMetaData ms(filename);
	Logger::Debug << "Adding strategy to history table of MS...\n";
	try {
		std::string strategyFilename;
		if(options.strategyFilename.empty())
			/// TODO
			;
		else
			strategyFilename = options.strategyFilename;
		//std::ifstream strategyFile(strategyFilename);
		//std::string content((std::istreambuf_iterator<char>(strategyFile)), (std::istreambuf_iterator<char>()) );
		ms.AddAOFlaggerHistory(strategyFilename, options.commandLine);
	} catch(std::exception &e)
	{
		Logger::Warn << "Failed to write history to MS: " << e.what() << '\n';
	}
}

void Runner::finishStatistics(const std::string& filename, ScriptData& scriptData, bool isMS)
{
	std::unique_ptr<StatisticsCollection>& statistics = scriptData.GetStatistics();
	if(statistics)
	{
		if(isMS) {
			Logger::Debug << "Writing quality statistics to MS.\n";
			QualityTablesFormatter qFormatter(filename);
			statistics->Save(qFormatter);
		}
		else {
			// TODO write separate .qs file?
		}
	}
}