Citlali
Loading...
Searching...
No Matches
lali.h
Go to the documentation of this file.
1#pragma once
2
3#include <mutex>
4
6
10
11// selects the type of TCData
12using timestream::TCDataKind;
13
14class Lali: public Engine {
15public:
16 // initial setup for each obs
17 void setup();
18
19 // main grppi pipeline
20 template <class KidsProc, class RawObs>
21 void pipeline(KidsProc &, RawObs &);
22
23 // run the reduction for the obs
24 auto run();
25
26 // output files
27 template <mapmaking::MapType map_type>
28 void output();
29};
30
32 // run obsnum setup
34}
35
36template <class KidsProc, class RawObs>
37void Lali::pipeline(KidsProc &kidsproc, RawObs &rawobs) {
39
40 // initialize number of completed scans
41 n_scans_done = 0;
42
43 // declare random number generator
44 boost::random::mt19937 eng;
45
46 // boost random number generator (0,1)
47 boost::random::uniform_int_distribution<> rands{0,1};
48
49 // progress bar
50 tula::logging::progressbar pb(
51 [&](const auto &msg) { logger->info("{}", msg); }, 100, "citlali progress ");
52
53 // grppi generator function. gets time chunk data from files sequentially and passes them to grppi::farm
54 grppi::pipeline(tula::grppi_utils::dyn_ex(parallel_policy),
55 [&]() -> std::optional<tuple_t> {
56 // variable to hold current scan
57 static int scan = 0;
58 // loop through scans
59 while (scan < telescope.scan_indices.cols()) {
60 // update progress bar
61 pb.count(telescope.scan_indices.cols(), 1);
62
63 // create rtcdata
64 TCData<TCDataKind::RTC, Eigen::MatrixXd> rtcdata;
65 // get scan indices
66 rtcdata.scan_indices.data = telescope.scan_indices.col(scan);
67 // current scan
68 rtcdata.index.data = scan;
69
70 // populate noise matrix (do outside of parallelized region for thread safety)
71 if (run_noise) {
72 if (omb.randomize_dets) {
73 // n_noise x n_dets
74 rtcdata.noise.data = Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic>::Zero(omb.n_noise, calib.n_dets)
75 .unaryExpr([&](int dummy){ return 2 * rands(eng) - 1; });
76 } else {
77 // n_noise
78 rtcdata.noise.data = Eigen::Matrix<int, Eigen::Dynamic, 1>::Zero(omb.n_noise)
79 .unaryExpr([&](int dummy){ return 2 * rands(eng) - 1; });
80 }
81 }
82 // vector to store kids data
83 std::vector<kids::KidsData<kids::KidsDataKind::RawTimeStream>> scan_rawobs;
84 // get kids data
85 scan_rawobs = kidsproc.load_rawobs(rawobs, scan, telescope.scan_indices, start_indices, end_indices);
86
87 // current length of outer scans
88 Eigen::Index sl = rtcdata.scan_indices.data(3) - rtcdata.scan_indices.data(2) + 1;
89
90 // get raw tod from files
91 rtcdata.scans.data = kidsproc.populate_rtc(scan_rawobs, sl, calib.n_dets, tod_type);
92 // try and clear input vector
93 std::vector<kids::KidsData<kids::KidsDataKind::RawTimeStream>>().swap(scan_rawobs);
94
95 // increment scan
96 scan++;
97 // return rtcdata
98 return rtcdata;
99 }
100 // reset scan to zero for each obs
101 scan = 0;
102 return {};
103 },
104
105 // run the farm
106 run());
107
108 if (run_mapmaking) {
109 // normalize maps
110 logger->info("normalizing maps");
111 if (map_method != "maximum_likelihood") {
112 if (rtcproc.run_polarization) {
113 omb.normalize_polarized_maps();
114 }
115 else {
116 omb.normalize_maps();
117 }
118 }
119 // calculate map psds
120 logger->info("calculating map psd");
121 omb.calc_map_psd();
122 // calculate map histograms
123 logger->info("calculating map histogram");
124 omb.calc_map_hist();
125 // calculate mean error
126 omb.calc_median_err();
127 // calculate mean rms
128 omb.calc_median_rms();
129
130 // write map summary
131 if (verbose_mode) {
132 write_map_summary(omb);
133 }
134 }
135}
136
137auto Lali::run() {
139
140 auto farm = grppi::farm(n_threads,[&](input_t &rtcdata) {
141 // starting index for scan
142 Eigen::Index si = rtcdata.scan_indices.data(2);
143 // current length of outer scans
144 Eigen::Index sl = rtcdata.scan_indices.data(3) - rtcdata.scan_indices.data(2) + 1;
145
146 // copy scan's telescope vectors
147 for (const auto& x: telescope.tel_data) {
148 rtcdata.tel_data.data[x.first] = telescope.tel_data[x.first].segment(si,sl);
149 }
150
151 // copy pointing offsets
152 for (const auto& [axis,offset]: pointing_offsets_arcsec) {
153 rtcdata.pointing_offsets_arcsec.data[axis] = offset.segment(si,sl);
154 }
155
156 // get hwpr
158 if (calib.run_hwpr) {
159 rtcdata.hwpr_angle.data = calib.hwpr_angle.segment(si + hwpr_start_indices, sl);
160 }
161 }
162
163 // create PTCData
165
166 logger->info("starting scan {}. {}/{} scans completed", rtcdata.index.data + 1, n_scans_done,
167 telescope.scan_indices.cols());
168
169 // run rtcproc
170 logger->info("raw time chunk processing for scan {}", rtcdata.index.data + 1);
171 auto map_indices = rtcproc.run(rtcdata, ptcdata, calib, telescope, omb.pixel_size_rad, map_grouping);
172
173 // remove flagged detectors
175
176 // remove outliers before cleaning
177 auto calib_scan = rtcproc.remove_bad_dets(ptcdata, calib, map_grouping);
178
179 // remove duplicate tones
180 if (!telescope.sim_obs) {
181 calib_scan = rtcproc.remove_nearby_tones(ptcdata, calib, map_grouping);
182 }
183
184 // write rtc timestreams
185 if (run_tod_output && !tod_filename.empty()) {
186 if (tod_output_type == "rtc" || tod_output_type == "both") {
187 logger->info("writing raw time chunk");
189 ptcdata.pointing_offsets_arcsec.data, calib);
190 }
191 }
192
193 // if running fruit loops and a map has been read in
194 if (ptcproc.run_fruit_loops && !ptcproc.tod_mb.signal.empty()) {
195 logger->info("subtracting map from tod");
196 // subtract map
198 map_indices, telescope.pixel_axes,
200 }
201
202 // run cleaning
203 logger->info("processed time chunk processing for scan {}", ptcdata.index.data + 1);
204 ptcproc.run(ptcdata, ptcdata, calib, telescope.pixel_axes, map_grouping);
205
206 // if running fruit loops and a map has been read in
207 if (ptcproc.run_fruit_loops && !ptcproc.tod_mb.signal.empty()) {
208 if (run_mapmaking && run_noise) {
209 // calculate weights
210 logger->info("calculating weights");
212
213 // reset weights to median
214 auto calib_scans = ptcproc.reset_weights(ptcdata, calib, map_grouping);
215
216 // populate noise maps only
217 bool run_omb = false;
218 logger->info("populating noise maps");
219 if (map_method=="naive") {
220 naive_mm.populate_maps_naive(ptcdata, omb, cmb, map_indices, telescope.pixel_axes,
221 calib.apt, telescope.d_fsmp, run_omb, run_noise);
222 }
223 else if (map_method=="jinc") {
224 jinc_mm.populate_maps_jinc(ptcdata, omb, cmb, map_indices, telescope.pixel_axes,
225 calib.apt, telescope.d_fsmp, run_omb, run_noise);
226 }
227 }
228 logger->info("adding map to tod");
229 // add map back
231 map_indices, telescope.pixel_axes,
233 }
234
235 // remove outliers after cleaning
236 calib_scan = ptcproc.remove_bad_dets(ptcdata, calib, map_grouping);
237
238 // calculate weights
239 logger->info("calculating weights");
241
242 // reset weights to median
243 calib_scan = ptcproc.reset_weights(ptcdata, calib, map_grouping);
244
245 // write ptc timestreams
246 if (run_tod_output && !tod_filename.empty()) {
247 if (tod_output_type == "ptc" || tod_output_type == "both") {
248 logger->info("writing processed time chunk");
250 ptcdata.pointing_offsets_arcsec.data, calib);
251 }
252 }
253
254 // write out chunk summary
255 if (verbose_mode) {
256 write_chunk_summary(ptcdata);
257 }
258
259 // write stats
260 logger->debug("calculating stats");
261 diagnostics.calc_stats(ptcdata);
262
263 // populate maps
264 if (run_mapmaking) {
265 // make signal, weight, kernel, and coverage maps
266 bool run_omb = true;
267 bool run_noise_fruit = run_noise;
268
269 // if running fruit loops, noise maps are made on source
270 // subtracted timestreams so don't make them here
271 if (ptcproc.run_fruit_loops && !ptcproc.tod_mb.signal.empty()) {
272 run_noise_fruit = false;
273 }
274
275 // populate maps with current time chunk
276 logger->info("populating maps");
277 if (map_method=="naive") {
278 naive_mm.populate_maps_naive(ptcdata, omb, cmb, map_indices, telescope.pixel_axes,
279 calib.apt, telescope.d_fsmp, run_omb, run_noise_fruit);
280 }
281 else if (map_method=="jinc") {
282 jinc_mm.populate_maps_jinc(ptcdata, omb, cmb, map_indices, telescope.pixel_axes,
283 calib.apt, telescope.d_fsmp, run_omb, run_noise_fruit);
284 }
285 else if (map_method=="maximum_likelihood") {
286 ml_mm.populate_maps_ml(ptcdata, omb, cmb, map_indices, telescope.pixel_axes,
287 calib, telescope.d_fsmp, run_omb, run_noise_fruit);
288 }
289 }
290
291 // increment number of completed scans
292 n_scans_done++;
293 logger->info("done with scan {}. {}/{} scans completed", ptcdata.index.data + 1, n_scans_done, telescope.scan_indices.cols());
294 });
295
296 return farm;
297}
298
299template <mapmaking::MapType map_type>
301 // pointer to map buffer
302 mapmaking::MapBuffer* mb = nullptr;
303 // pointer to data file fits vector
304 std::vector<fitsIO<file_type_enum::write_fits, CCfits::ExtHDU*>>* f_io = nullptr;
305 // pointer to noise file fits vector
306 std::vector<fitsIO<file_type_enum::write_fits, CCfits::ExtHDU*>>* n_io = nullptr;
307
308 // directory name
309 std::string dir_name;
310
311 // set common variables depending on map_type
312 if constexpr (map_type == mapmaking::RawObs || map_type == mapmaking::FilteredObs) {
313 mb = &omb;
314 dir_name = obsnum_dir_name + (map_type == mapmaking::RawObs ? "raw/" : "filtered/");
315 f_io = (map_type == mapmaking::RawObs) ? &fits_io_vec : &filtered_fits_io_vec;
317
318 if constexpr (map_type == mapmaking::RawObs) {
319 // write stats file
320 write_stats();
321 if (run_tod_output && !tod_filename.empty()) {
322 // add tod header information
324 }
325 }
326 }
327 else if constexpr (map_type == mapmaking::RawCoadd || map_type == mapmaking::FilteredCoadd) {
328 mb = &cmb;
329 dir_name = coadd_dir_name + (map_type == mapmaking::RawCoadd ? "raw/" : "filtered/");
332 }
333
334 if (run_mapmaking) {
335 // wiener filtered maps write before this and are deleted from the vector.
336 if (!f_io->empty()) {
337 {
338 // progress bar
339 tula::logging::progressbar pb(
340 [&](const auto &msg) { logger->info("{}", msg); }, 100, "output progress ");
341
342 for (Eigen::Index i=0; i<f_io->size(); ++i) {
343 // get the array for the given map
344 // add primary hdu
345 logger->debug("adding primary header to file {}",i);
346 add_phdu(f_io, mb, i);
347
348 // add primary hdu to noise maps
349 if (!mb->noise.empty()) {
350 logger->debug("adding primary header to noise file {}",i);
351 add_phdu(n_io, mb, i);
352 }
353 }
354
355 logger->debug("done adding primary headers");
356
357 // write the maps
358 for (Eigen::Index i=0; i<n_maps; ++i) {
359 // update progress bar
360 pb.count(n_maps, 1);
361 write_maps(f_io,n_io,mb,i);
362 }
363 }
364
365 logger->info("maps have been written to:");
366 for (Eigen::Index i=0; i<f_io->size(); ++i) {
367 logger->info("{}.fits",f_io->at(i).filepath);
368 }
369 }
370
371 // clear fits file vectors to ensure its closed.
372 std::vector<fitsIO<file_type_enum::write_fits, CCfits::ExtHDU*>>().swap(*f_io);
373 std::vector<fitsIO<file_type_enum::write_fits, CCfits::ExtHDU*>>().swap(*n_io);
374
375 // write psd and histogram files
376 logger->debug("writing psds");
377 write_psd<map_type>(mb, dir_name);
378 logger->debug("writing histograms");
379 write_hist<map_type>(mb, dir_name);
380
381 // write source table
382 if (run_source_finder) {
383 logger->debug("writing source table");
384 write_sources<map_type>(mb, dir_name);
385 }
386 }
387}
Definition engine.h:153
Eigen::Index hwpr_start_indices
Definition engine.h:201
void obsnum_setup()
Definition engine.h:346
std::string obsnum_dir_name
Definition engine.h:177
void write_stats()
Definition engine.h:2239
std::string parallel_policy
Definition engine.h:189
std::map< std::string, Eigen::VectorXd > pointing_offsets_arcsec
Definition engine.h:234
std::vector< fitsIO< file_type_enum::write_fits, CCfits::ExtHDU * > > filtered_coadd_fits_io_vec
Definition engine.h:244
std::vector< Eigen::Index > start_indices
Definition engine.h:198
std::vector< fitsIO< file_type_enum::write_fits, CCfits::ExtHDU * > > noise_fits_io_vec
Definition engine.h:239
std::vector< fitsIO< file_type_enum::write_fits, CCfits::ExtHDU * > > coadd_noise_fits_io_vec
Definition engine.h:243
std::string tod_output_type
Definition engine.h:216
std::string coadd_dir_name
Definition engine.h:177
std::vector< fitsIO< file_type_enum::write_fits, CCfits::ExtHDU * > > filtered_noise_fits_io_vec
Definition engine.h:240
bool verbose_mode
Definition engine.h:165
int n_maps
Definition engine.h:222
std::vector< fitsIO< file_type_enum::write_fits, CCfits::ExtHDU * > > filtered_fits_io_vec
Definition engine.h:240
int n_scans_done
Definition engine.h:192
void add_tod_header()
Definition engine.h:1044
std::vector< Eigen::Index > end_indices
Definition engine.h:198
std::vector< fitsIO< file_type_enum::write_fits, CCfits::ExtHDU * > > filtered_coadd_noise_fits_io_vec
Definition engine.h:244
void add_phdu(fits_io_type &, map_buffer_t &, Eigen::Index)
Definition engine.h:1727
std::string map_grouping
Definition engine.h:219
std::shared_ptr< spdlog::logger > logger
Definition engine.h:159
std::map< std::string, std::string > tod_filename
Definition engine.h:180
std::string tod_type
Definition engine.h:204
std::vector< fitsIO< file_type_enum::write_fits, CCfits::ExtHDU * > > coadd_fits_io_vec
Definition engine.h:243
void write_chunk_summary(TCData< tc_t, Eigen::MatrixXd > &)
Definition engine.h:1519
std::vector< fitsIO< file_type_enum::write_fits, CCfits::ExtHDU * > > fits_io_vec
Definition engine.h:239
int n_threads
Definition engine.h:186
std::string map_method
Definition engine.h:219
void write_maps(fits_io_type &, fits_io_type &, map_buffer_t &, Eigen::Index)
Definition engine.h:2018
Definition lali.h:14
void setup()
Definition lali.h:31
void output()
Definition lali.h:300
auto run()
Definition lali.h:137
void pipeline(KidsProc &, RawObs &)
Definition lali.h:37
bool run_hwpr
Definition calib.h:41
std::map< std::string, Eigen::VectorXd > apt
Definition calib.h:22
Eigen::VectorXd hwpr_angle
Definition calib.h:24
Eigen::Index n_dets
Definition calib.h:47
void calc_stats(timestream::TCData< tcdata_kind, Eigen::MatrixXd > &)
Definition diagnostics.h:61
bool sim_obs
Definition telescope.h:20
std::map< std::string, Eigen::VectorXd > tel_data
Definition telescope.h:54
double d_fsmp
Definition telescope.h:42
Eigen::MatrixXI scan_indices
Definition telescope.h:51
std::string pixel_axes
Definition telescope.h:59
void populate_maps_jinc(TCData< TCDataKind::PTC, Eigen::MatrixXd > &, map_buffer_t &, map_buffer_t &, Eigen::DenseBase< Derived > &, std::string &, apt_t &, double, bool, bool)
Definition jinc_mm.h:211
void populate_maps_ml(TCData< TCDataKind::PTC, Eigen::MatrixXd > &, map_buffer_t &, map_buffer_t &, Eigen::DenseBase< Derived > &, std::string &, calib_t &, double, bool, bool)
Definition ml_mm.h:37
Definition map.h:45
std::vector< Eigen::MatrixXd > signal
Definition map.h:78
std::vector< Eigen::Tensor< double, 3 > > noise
Definition map.h:81
double pixel_size_rad
Definition map.h:69
void populate_maps_naive(TCData< TCDataKind::PTC, Eigen::MatrixXd > &, map_buffer_t &, map_buffer_t &, Eigen::DenseBase< Derived > &, std::string &, apt_t &, double, bool, bool)
Definition naive_mm.h:95
Definition ptcproc.h:19
void append_to_netcdf(TCData< TCDataKind::PTC, Eigen::MatrixXd > &, std::string, std::string, std::string &, pointing_offset_t &, calib_t &)
Definition ptcproc.h:499
void calc_weights(TCData< TCDataKind::PTC, Eigen::MatrixXd > &, apt_type &, tel_type &)
Definition ptcproc.h:301
void run(TCData< TCDataKind::PTC, Eigen::MatrixXd > &, TCData< TCDataKind::PTC, Eigen::MatrixXd > &, calib_type &, std::string, std::string)
Definition ptcproc.h:173
auto reset_weights(TCData< TCDataKind::PTC, Eigen::MatrixXd > &, calib_t &, std::string)
Definition ptcproc.h:384
Definition rtcproc.h:18
void remove_flagged_dets(TCData< TCDataKind::PTC, Eigen::MatrixXd > &, apt_t &)
Definition rtcproc.h:497
bool run_polarization
Definition rtcproc.h:23
auto remove_nearby_tones(TCData< TCDataKind::PTC, Eigen::MatrixXd > &, calib_t &, std::string)
Definition rtcproc.h:520
void append_to_netcdf(TCData< TCDataKind::PTC, Eigen::MatrixXd > &, std::string, std::string, std::string &, pointing_offset_t &, calib_t &)
Definition rtcproc.h:557
auto run(TCData< TCDataKind::RTC, Eigen::MatrixXd > &, TCData< TCDataKind::PTC, Eigen::MatrixXd > &, calib_t &, telescope_t &, double, std::string)
Definition rtcproc.h:261
void map_to_tod(mb_t &, TCData< tcdata_t, Eigen::MatrixXd > &, calib_t &, Eigen::DenseBase< Derived > &, std::string, std::string)
Definition timestream.h:624
auto remove_bad_dets(TCData< tcdata_t, Eigen::MatrixXd > &, calib_t &, std::string)
Definition timestream.h:703
@ NegativeMap
Definition timestream.h:272
@ Map
Definition timestream.h:271
bool run_fruit_loops
Definition timestream.h:279
mapmaking::MapBuffer tod_mb
Definition timestream.h:296
@ FilteredObs
Definition map.h:19
@ FilteredCoadd
Definition map.h:21
@ RawObs
Definition map.h:18
@ RawCoadd
Definition map.h:20
int run(const rc_t &rc)
Definition main.cpp:104
The raw obs struct This represents a single observation that contains a set of data items and calibra...
Definition io.h:50
mapmaking::NaiveMapmaker naive_mm
Definition engine.h:107
engine::Telescope telescope
Definition engine.h:94
mapmaking::MLMapmaker ml_mm
Definition engine.h:109
engine::Diagnostics diagnostics
Definition engine.h:96
timestream::PTCProc ptcproc
Definition engine.h:103
mapmaking::JincMapmaker jinc_mm
Definition engine.h:108
mapmaking::MapBuffer omb
Definition engine.h:106
mapmaking::MapBuffer cmb
Definition engine.h:106
timestream::RTCProc rtcproc
Definition engine.h:100
engine::Calib calib
Definition engine.h:93
bool run_noise
Definition engine.h:84
bool run_source_finder
Definition engine.h:88
bool run_tod_output
Definition engine.h:79
bool run_mapmaking
Definition engine.h:82
TC data class.
Definition timestream.h:55