RdGalacticDatasetMaker.cc
Go to the documentation of this file.
2 
3 // framework
4 #include <fwk/CentralConfig.h>
5 
6 // utilities
7 #include <utl/ErrorLogger.h>
8 #include <utl/TimeStamp.h>
9 #include <utl/TraceAlgorithm.h>
10 #include <utl/UTCDateTime.h>
11 #include <utl/Minou.h>
12 // event
13 #include <evt/Event.h>
14 
15 // revent
16 #include <revt/REvent.h>
17 #include <revt/Header.h>
18 #include <revt/Station.h>
19 
20 // det / rdet
21 #include <rdet/RDetector.h>
22 #include <rdet/Channel.h>
23 
24 // general
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <iomanip>
28 
29 // for folder creation
30 #include <string.h>
31 #include <errno.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 
35 // boost
36 #include <boost/algorithm/string.hpp>
37 
38 using namespace std;
39 using namespace utl;
40 using namespace fwk;
41 using namespace revt;
42 using namespace evt;
43 
44 
46 
47  REvent* RdGalacticDatasetMaker::fgCurrentREvent;
48 
50  fInfoLevel(0),
51  fCurRunId(0),
52  fCurEventId(0),
53  fCurStationId(0),
54  fCurChannelId(0),
55  fADCthreshold(0),
56  fSTDthreshold(0),
57  ffreqBinWidth(0),
58  ftimeBinWidth(0),
59  fdebugData(0),
60  fdayStack(false),
61  ffilteredDebugData(false),
62  fchannels(vector<int>()),
63  fMinFrequency(0),
64  fMaxFrequency(0),
65  fstartBin(0),
66  ftraceCutBinLength(0),
67  fsamplingFrequency4Header(0),
68  fimpedanceFile(false)
69  {}
70 
73  {
74  INFO("RdGalacticDatasetMaker::Init()");
75  string tmpstring;
76  ostringstream info;
77 
79  Branch topBranch =
80  CentralConfig::GetInstance()->GetTopBranch("RdGalacticDatasetMaker");
81  topBranch.GetChild("InfoLevel").GetData(fInfoLevel);
82  topBranch.GetChild("freqBinWidth").GetData(ffreqBinWidth);
83  topBranch.GetChild("timeBinWidth").GetData(ftimeBinWidth);
84  topBranch.GetChild("ADCthreshold").GetData(fADCthreshold);
85  topBranch.GetChild("STDthreshold").GetData(fSTDthreshold);
86  topBranch.GetChild("debugData").GetData(fdebugData);
87  string fdayStackStr = "";
88  topBranch.GetChild("dayStack").GetData(fdayStackStr);
89  fdayStack = (fdayStackStr=="yes");
90  string filteredDebugDataStr = "";
91  topBranch.GetChild("filteredDebugData").GetData(filteredDebugDataStr);
92  ffilteredDebugData = (filteredDebugDataStr=="yes");
93  topBranch.GetChild("channels").GetData(fchannels);
94  topBranch.GetChild("MinFrequency").GetData(fMinFrequency);
95  topBranch.GetChild("MaxFrequency").GetData(fMaxFrequency);
96  topBranch.GetChild("startBin").GetData(fstartBin);
97  topBranch.GetChild("traceCutBinLength").GetData(ftraceCutBinLength);
98  topBranch.GetChild("samplingFrequency").GetData(fsamplingFrequency4Header);
99  string fimpedanceFileStr = "";
100  topBranch.GetChild("impedanceFile").GetData(fimpedanceFileStr);
101  fimpedanceFile = (fimpedanceFileStr=="yes");
102 
103  vector<int> StationIDlist_dummy;
104  Branch stationsB = topBranch.GetChild("stations");
105  for (Branch stationB = stationsB.GetFirstChild(); stationB; stationB = stationB.GetNextSibling()) {
106  StationIDlist_dummy.push_back(stoi(stationB.GetAttributes().find("id")->second));
107  }
108 
109  fStationIds = vector<int>(StationIDlist_dummy.begin(), StationIDlist_dummy.end());
110 
111  for (unsigned int i = 0; i < fStationIds.size(); ++i) {
112  info << "Station: " << fStationIds[i] << endl;
113  }
114  INFODebug(info);
115  info.str("");
116 
117  if (fimpedanceFile == true) {
118  (impedanceTopBranch = topBranch.GetChild("RImpedanceProfile"));
119  } else {
120  WARNING( "No impedance file selected. Impedance will be set to 1 Ohms for all frequencies.");
121  }
122 
123  info << "Settings: Frequency bin width: " << ffreqBinWidth << "MHz" << "; Time bin width: "
124  << ftimeBinWidth << " hours" << "; ADC threshold: " << fADCthreshold << " ADC" << "; STD threshold: "
125  << fSTDthreshold << " ADC" << "; DayStack is " << fdayStack << "; MinFrequency: " << fMinFrequency << " MHz"
126  << " MaxFrequency: " << fMaxFrequency << " MHz" << "; Start bin: " << fstartBin << "; Total bins to take from time trace: "
127  << ftraceCutBinLength << "; Sampling frequency (for the header in the output files: "
128  << fsamplingFrequency4Header << endl;
129  INFOFinal(info.str());
130  info.str("");
131 
132  // create time and frequency bin vector based on bin widths
133  // create time bin vector
134  for (float currentTimeBin = 0; currentTimeBin <= 24; currentTimeBin += ftimeBinWidth){
135  timeBins.push_back(currentTimeBin);
136  }
137  // create freq bin vector
138  for (float currentFreqBin = fMinFrequency; currentFreqBin <= fMaxFrequency; currentFreqBin += ffreqBinWidth){
139  freqBins.push_back(currentFreqBin);
140  }
141 
142  // init dataset vectors
143  vector<vector<vector<vector<float>>>> AllChannelsAndStationsDatasets_dummy(fchannels.size(), vector<vector<vector<float>>>
144  (fStationIds.size(), vector<vector<float>>(timeBins.size()-1, vector<float>(freqBins.size()+1)) ));
145 
146  AllChannelsAndStationsDatasets = AllChannelsAndStationsDatasets_dummy;
147  vector<vector<float> > stationTraceCounter_dummy(fStationIds.size(), vector<float>(2,0));
148  stationTraceCounter = stationTraceCounter_dummy;
149 
150  vector<vector<vector<vector<float>>>> (0, vector<vector<vector<float>>>
151  (0, vector<vector<float>>(0, vector<float>(0)) )).swap(AllChannelsAndStationsDatasets_dummy); // deallocating memory
152 
153  // fill the Time columns
154  for (unsigned int chan = 0; chan < AllChannelsAndStationsDatasets.size(); ++chan) {
155  for (unsigned int st = 0; st < AllChannelsAndStationsDatasets[chan].size(); ++st) {
156  for (unsigned int row = 0; row < AllChannelsAndStationsDatasets[chan][st].size(); ++row) {
157  AllChannelsAndStationsDatasets[chan][st][row][0] = timeBins[row];
158  }
159  } //end station
160  } //end chan
161 
162  info << "Dataset vectors with dimensions " << AllChannelsAndStationsDatasets.size() << "x"
163  << AllChannelsAndStationsDatasets[0].size() << "x" << AllChannelsAndStationsDatasets[0][0].size()
164  << "x" << AllChannelsAndStationsDatasets[0][0][0].size() << " (channels x stations x Time bins x frequency bins) has been created.";
165  INFOFinal(info.str());
166  info.str("");
167 
168  // Create dataset directory
169  if (mkdir("datasets", 0777) == -1){
170  WARNING("Directory for datasets cannot be created, maybe it exists already?");
171  // cerr << "Error, directory for datasets : " << strerror(errno) << endl;
172  } else {
173  info << "Directory for datasets has been created";
174  INFO(info.str());
175  }
176  info.str("");
177 
178  // Create debug directory
179  if (fdebugData >= 1){
180  if (mkdir("debug", 0777) == -1){
181  WARNING("Directory for debug data cannot be created, maybe it exists already?");
182  // cerr << "Error, directory for debug : " << strerror(errno) << endl;
183  } else {
184  info << "Directory for debug has been created";
185  INFO(info.str());
186  }
187  }
188  info.str("");
189 
190  for (unsigned int i=0; i<fStationIds.size(); ++i) {
191  // initialize save to file
192  for (unsigned int j=0; j< fchannels.size(); ++j) {
193  if (fdebugData >= 1){
194 
195  ofstream tracePropertiesDebugFile; // initialize std and peakmax spectrum trace to file
196  tracePropertiesDebugFile.open
197  ("./debug/tracePropertiesDebugFile_"+to_string(fStationIds[i])+"_channel_"+to_string(fchannels[j])+".txt", ios::out | ios::app);
198 
199  tracePropertiesDebugFile << "event" << " " << "station" <<" " << "channel" << " gpsTime"
200  << " UTChour" << " sidTime" << " STD" << " absMaxPeakADC" <<endl;
201  tracePropertiesDebugFile.close();
202 
203  } // end fdebugData >=1
204  if (fdebugData == 2){
205 
206  ofstream ADCtraceFile;
207  ADCtraceFile.open
208  ("./debug/ADCtracesDebugFile_"+to_string(fStationIds[i])+"_channel_"+to_string(fchannels[j])+".txt", ios::out | ios::app);
209 
210  ADCtraceFile << "event" << " " << "station" <<" " << "channel" << " gpsTime" << " UTChour" << " sidTime" ;
211  for (int k=fstartBin; k<ftraceCutBinLength; ++k) {
212  ADCtraceFile << " " << k;
213  }
214  ADCtraceFile << endl;
215  ADCtraceFile.close();
216 
217  // initialize save to file
218  ofstream spectrumTraceFile;
219  spectrumTraceFile.open
220  ("./debug/spectraDebugFile_"+to_string(fStationIds[i])+"_channel_"+to_string(fchannels[j])+".txt", ios::out | ios::app);
221 
222  spectrumTraceFile << "event" << " " << "station" <<" " << "channel" << " gpsTime" << " UTChour" << " sidTime";
223  for (int k=fstartBin; k<(ftraceCutBinLength/2+1); ++k) {
224  spectrumTraceFile << " " << k*fsamplingFrequency4Header/ftraceCutBinLength;
225  }
226  spectrumTraceFile << endl;
227  spectrumTraceFile.close();
228 
229  } // end fdebugData == 2
230  } // end channel file creation loop
231  // end of station file creation loop to file
232  }
233  return eSuccess;
234  } //end init
235 
236 
238  RdGalacticDatasetMaker::Run(evt::Event& event)
239  {
240  if (!event.HasREvent()) {
241  ERROR("Read event without radio part");
242  return eFailure;
243  }
244 
246  // General event properties
247  REvent& rEvent = event.GetREvent();
248  fgCurrentREvent = &event.GetREvent();
249  fCurRunId = rEvent.GetHeader().GetRunNumber();
250  fCurEventId = rEvent.GetHeader().GetId();
254 
255  // Loop over stations
256  for (REvent::StationIterator sIt = rEvent.StationsBegin(); sIt != rEvent.StationsEnd(); ++sIt) {
257  fCurStationId = sIt->GetId();
258  Station& station = *sIt;
259 
260  // init filter flag
261  bool filterPass = true;
262 
263  // init off all temp vectors
264  vector<vector<float>> powerDepositedInFreqBins(fchannels.size(), vector<float>(freqBins.size()-1, 0.0));
265  vector<vector<float>> cachedSpectra(fchannels.size(), vector<float>());
266  vector<vector<float>> cachedADCtraces(fchannels.size(), vector<float>());
267  vector<vector<float>> cachedSTD(fchannels.size(), vector<float>());
268  vector<vector<float>> cachedTraceADCmax(fchannels.size(), vector<float>());
269 
270  // Loop over channels
271  const rdet::Station& detStation = det::Detector::GetInstance().GetRDetector().GetStation(station); // rdStation
272  for (Station::ChannelIterator cIt = station.ChannelsBegin(); cIt != station.ChannelsEnd(); ++cIt) {
273  Channel& channel = *cIt;
274 
275  // Check if channel exists
276  if (!channel.IsActive()) {
277  continue;
278  }
279 
280  ostringstream info;
281 
282  fCurChannelId=channel.GetId();
283  int channelIndex = getChannelIndex(fchannels,fCurChannelId); //find the channel index in the selected channels
284  const rdet::Channel& rdetChannel = detStation.GetChannel(fCurChannelId);
285 
287  // Start
288 
290 
291  // check length before
292 
293  // get time traces
294  revt::ChannelADCTimeSeries ADCtrace = cIt->GetChannelADCTimeSeries();
295  revt::ChannelTimeSeries& trace = cIt->GetChannelTimeSeries();
296 
297  // time length of the trace
298  float T = trace.GetSize()*trace.GetBinning();
299 
300  info << "BEFORE cutting: trace size: " << trace.GetSize() << "; ADC trace size: " << ADCtrace.GetSize()
301  << "; Spectrum should be half+1 of that" << "; The length of the time trace is: "<< T << "ns" <<endl;
302  INFODebug(info);
303  info.str("");
304 
305  // if different length than default, do the cut
306  if (ftraceCutBinLength !=2048) {
307  revt::ChannelTimeSeries tempTimeSeries;
308  revt::ChannelADCTimeSeries tempADCTimeSeries;
309 
310  tempTimeSeries.SetBinning(trace.GetBinning());
311  tempADCTimeSeries.SetBinning(ADCtrace.GetBinning());
312 
313  unsigned int endBin = fstartBin + ftraceCutBinLength;
314  for (unsigned int i = fstartBin; i < endBin; ++i) {
315  tempTimeSeries.PushBack(trace[i]);
316  tempADCTimeSeries.PushBack(ADCtrace[i]);
317  }
318  trace = tempTimeSeries;
319  ADCtrace = tempADCTimeSeries;
320  // request new instance
321  trace = cIt->GetChannelTimeSeries();
322  // the length of the time trace should change accordingly
323  T = trace.GetSize()*trace.GetBinning();
324  }
325 
326  // get spectrum
328  // get sampling frequency
329  const double samplingfreq = rdetChannel.GetSamplingFrequency()*1000;
330 
331  info << "AFTER cutting: trace size: " << trace.GetSize() << "; ADC trace size: " << ADCtrace.GetSize()
332  << "; Spectrum size: " << spectrum.GetSize() << "; The length of the time trace is: "<< T << "ns" <<endl;
333  INFODebug(info);
334  info.str("");
335 
336  info << "Trace size: " << trace.GetSize() << "; Trace bin length (ns): " << trace.GetBinning()
337  << "Spectrum bin size (GHz): " << spectrum.GetBinning() << "; Trace time length (nano sec): " << T << endl;
338  info << "GPS time: " << fCurGPSSecond << "; LST time: " << GPSSecToLSTHourAuger(fCurGPSSecond)
339  << "; HHMMSS: " << fHHMMSS << "; Converted to UTC hour: " << fCurUTChour << "; Spectrum.GetSize(): "
340  << spectrum.GetSize() << "; Sampling rate from XML: " << samplingfreq << "MHz" << endl;
341  INFOIntermediate(info);
342  info.str("");
343 
344  // get statistics
345  int ADCtraceAbsMax;
346  double ADCtraceSTD = TraceAlgorithm::StandardDeviation(ADCtrace, 0, trace.GetSize()-1);
347  double ADCtraceMax = TraceAlgorithm::Max(ADCtrace, 0, trace.GetSize()-1);
348  double ADCtraceMin = TraceAlgorithm::Min(ADCtrace, 0, trace.GetSize()-1);
349 
350  if (ADCtraceMax >= abs(ADCtraceMin)){
351  ADCtraceAbsMax = ADCtraceMax;
352  }
353  if (ADCtraceMax < abs(ADCtraceMin)){
354  ADCtraceAbsMax = abs(ADCtraceMin);
355  }
356 
357  // update filter flag
358  if (filterPass == true){
359  if ( (ADCtraceSTD < fSTDthreshold) & (ADCtraceAbsMax < fADCthreshold) ){
360  filterPass = true;
361  } else {
362  filterPass = false;
363  }
364  }
365 
366  info << "Threshold settings and quantity values in the Channel " << to_string(fCurChannelId)
367  << "; STD threshold: " << fSTDthreshold << "; ADC threshold: " << fADCthreshold << "\n"
368  << "Properties of current trace::: abs Max: " << ADCtraceAbsMax <<"; STD: " << ADCtraceSTD
369  << "; Min: " << ADCtraceMin << "; Max" << ADCtraceMax << "; Filterpass flag: " << filterPass << endl;
370  INFOIntermediate(info);
371  info.str("");
372 
373  //bin integration
374  float Z;
375  for (unsigned j=0; j < freqBins.size()-1; ++j){
376  for (unsigned int i = 0; i < spectrum.GetSize(); ++i){
377  if ((channel.GetFrequencyOfBin(i)*1000 >= freqBins[j]) && (channel.GetFrequencyOfBin(i)*1000 < freqBins[j+1] )){
378  if (fimpedanceFile == false){
379  Z = 1;
380  WARNING("No impedance from file! Setting Z = 1 for all frequencies.");
381  } else {
383  }
384 
385  info << "Interpolated impedance for frequency " << to_string(channel.GetFrequencyOfBin(i)*1000)
386  << "in channel " << to_string(fCurChannelId) << " is " << to_string(Z) << " This was done in bin interval: "
387  << freqBins[j] << " to " << freqBins[j+1] << "[MHz]" << endl;
388  INFODebug(info);
389  info.str("");
390 
391  // power integration, the units in T, spectrum.GetBinning and spectrum*spectrum cancel each other
392  powerDepositedInFreqBins[channelIndex][j] += 2*(1/Z)*(1/T)*abs(spectrum[i]*spectrum[i])*spectrum.GetBinning();
393 
394  }
395  }
396  } // end bin integration
397 
398  // fill debug vectors
399  if (fdebugData >= 1) {
400  cachedSTD[channelIndex].push_back(ADCtraceSTD);
401  cachedTraceADCmax[channelIndex].push_back(ADCtraceAbsMax);
402  } // end of debugData >= 1
403  if (fdebugData == 2) {
404  for (unsigned int j = spectrum.GetStart(); j < spectrum.GetSize(); ++j) {
405  cachedSpectra[channelIndex].push_back(abs(spectrum[j]));
406  }
407  for (unsigned int j = ADCtrace.GetStart(); j < ADCtrace.GetSize(); ++j) {
408  cachedADCtraces[channelIndex].push_back(ADCtrace[j]);
409  }
410  } // end of debugData == 2
411  } // end channel loop
412 
413  // flag for if dump filtered debug data or not
414  bool filterPass4debugData = true;
415  if (ffilteredDebugData == true){
416  if (filterPass == true){
417  filterPass4debugData = true;
418  } else {
419  filterPass4debugData = false;
420  }
421  }
422 
423  // debug data dump
424  if (filterPass4debugData == true) {
425  for (unsigned int channelIndex=0; channelIndex < fchannels.size(); ++channelIndex) {
426  if (fdebugData >= 1){
427  // debuggin tool, save all STD and ADC peak height with event,station and channel number to to file
428  ofstream tracePropertiesDebugFile;
429  tracePropertiesDebugFile.open
430  ("./debug/tracePropertiesDebugFile_"+to_string(fCurStationId)+"_channel_"+to_string(fchannels[channelIndex])+".txt", ios::out | ios::app);
431 
432  tracePropertiesDebugFile << fCurEventId << " " << fCurStationId <<" " << fCurChannelId
433  << " " << fCurGPSSecond << " " << fCurUTChour << " " << GPSSecToLSTHourAuger(fCurGPSSecond)
434  << " " << cachedSTD[channelIndex][0] << " " << cachedTraceADCmax[channelIndex][0] << endl;
435  tracePropertiesDebugFile.close();
436 
437  } //end if debug >= 1
438  if (fdebugData == 2){
439  // debuggin tool, save all spectra with event,station and channel number to to file
440  ofstream spectrumTraceFile;
441  spectrumTraceFile.open
442  ("./debug/spectraDebugFile_"+to_string(fCurStationId)+"_channel_"+to_string(fchannels[channelIndex])+".txt", ios::out | ios::app);
443 
444  spectrumTraceFile << fCurEventId << " " << fCurStationId <<" " << fCurChannelId << " "
446  for (unsigned int j = 0; j < cachedSpectra[channelIndex].size(); ++j) {
447  spectrumTraceFile << " " << cachedSpectra[channelIndex][j];
448  }
449  spectrumTraceFile << "\n";
450  spectrumTraceFile.close();
451  // end of saving to file
452 
453  // debuggin tool, save all ADC time traces with event,station and channel number to to file
454  ofstream ADCtraceFile;
455  ADCtraceFile.open
456  ("./debug/ADCtracesDebugFile_"+to_string(fCurStationId)+"_channel_"+to_string(fchannels[channelIndex])+".txt", ios::out | ios::app);
457 
458  ADCtraceFile << fCurEventId << " " << fCurStationId <<" "<< fCurChannelId << " "
460  for (unsigned int j = 0; j < cachedADCtraces[channelIndex].size(); j++) {
461  ADCtraceFile << " " << cachedADCtraces[channelIndex][j] ;
462  }
463  ADCtraceFile << "\n";
464  ADCtraceFile.close();
465 
466  } //end if debug == 2
467  } // end channel loop
468  } // end if pass
469 
471 
472  // put the vector to the correct sidereal time if the trace passed the threshold filters
473  if (filterPass == true){
474  float currentTime;
475  if (fdayStack == true){
476  currentTime = fCurUTChour; // "normal" hour time
477  } else {
478  currentTime = GPSSecToLSTHourAuger(fCurGPSSecond); // LST hour time
479  }
480 
481  int n;
483  for (unsigned int chan = 0; chan < AllChannelsAndStationsDatasets.size(); ++chan) {
484  for (unsigned int st = 0; st < AllChannelsAndStationsDatasets[0].size(); ++st) {
485  if (fCurStationId == fStationIds[st]){
486  for (unsigned int row = 0; row < timeBins.size()-1; ++row) {
487  if ((currentTime >= timeBins[row]) & (currentTime < timeBins[row+1] )) {
488  AllChannelsAndStationsDatasets[chan][st][row][1] += 1; // this is the weight column
489  n = AllChannelsAndStationsDatasets[chan][st][row][1]; // it easier to pass this to the function "online average"
490 
491  // the row is starting from 2nd columns, since the zeroth is lst time and the first is the weight of the row
492  transform(AllChannelsAndStationsDatasets[chan][st][row].begin()+2, AllChannelsAndStationsDatasets[chan][st][row].end(),
493  powerDepositedInFreqBins[chan].begin(), AllChannelsAndStationsDatasets[chan][st][row].begin()+2, [n](float v1, float v2)
494  {return onlineMean(v1,v2,n);});
495 
496  } // end if is in Time bin
497  } // end row
498  } // end if station
499  } // end station loop
500  } // end channel loop
501  } // end filterPass
503 
504  // just some statistics, to see at the end how many traces in each stations were and how many has passed
505  for (unsigned int st = 0; st < stationTraceCounter.size(); ++st){
506  if (fCurStationId == fStationIds[st]){
507  stationTraceCounter[st][1] += 1;
508  if (filterPass == true){
509  stationTraceCounter[st][0] += 1;
510  }
511  }
512  } //end stats
513 
514  } // end station loop
515 
516  ostringstream info;
517  info << "Output of the cached dataset vector after reading the event: " << endl;
518  info << "*********************" << endl;
519  for (unsigned int chan = 0; chan < AllChannelsAndStationsDatasets.size(); ++chan) {
520  info << " Channel number:" << fchannels[chan] << " " << endl;
521  for (unsigned int st = 0; st < AllChannelsAndStationsDatasets[chan].size(); ++st) {
522  info << " Station number:" << fStationIds[st] << " " << endl;
523  for (unsigned int row = 0; row < AllChannelsAndStationsDatasets[chan][st].size(); ++row) {
524  for (unsigned int col = 0; col < AllChannelsAndStationsDatasets[chan][st][row].size(); ++col) {
525  info << AllChannelsAndStationsDatasets[chan][st][row][col] << " ";
526  } // end col loop
527  info << endl;
528  } // end row loop
529  } //end station
530  } //end channel loop
531  info << "*********************" << endl;
532  INFODebug(info);
533  info.str("");
534 
535  return eSuccess;
536 
537  } // end event
538 
540  RdGalacticDatasetMaker::Finish()
541  {
542 
543  ostringstream info;
544 
545  info << "Output of the whole final dataset vector: \n";
546  info << "*********************" << endl;
547  for (unsigned int chan = 0; chan < AllChannelsAndStationsDatasets.size(); ++chan) {
548  info << "\n";
549  info << " Channel number:" << fchannels[chan] << " " << endl;
550  for (unsigned int st = 0; st < AllChannelsAndStationsDatasets[chan].size(); ++st) {
551  info << " Station number:" << fStationIds[st] << " " << endl;
552  for (unsigned int row = 0; row < AllChannelsAndStationsDatasets[chan][st].size(); ++row){
553  for (unsigned int col = 0; col < AllChannelsAndStationsDatasets[chan][st][row].size(); ++col) {
554  info << AllChannelsAndStationsDatasets[chan][st][row][col] << " ";
555  } // end col loop
556  info << endl;
557  } // end row loop
558  } //end station
559  } //end channel loop
560  info << "*********************" << endl;
561  INFOIntermediate(info);
562  info.str("");
563 
565  // initialize average dataset file header, this is now 3d vector (channel X rows(Time bins) X cols (freq bins)
566  vector<vector<vector<float>>>
567  AllChannelsAndStationsDatasets_average(fchannels.size(), vector<vector<float>>(timeBins.size()-1, vector<float>(freqBins.size()+1)));
568 
569  // fill the Time columns
570  for (unsigned int chan = 0; chan < AllChannelsAndStationsDatasets_average.size(); ++chan) {
571  for (unsigned int row = 0; row < AllChannelsAndStationsDatasets_average[chan].size(); ++row) {
572  AllChannelsAndStationsDatasets_average[chan][row][0] = timeBins[row]; // fill the Time bin times in the zeroth col
573  }
574  }
575 
576  // make average from station vectors
577  vector<float> tempVector;
578  int st;
579  for (unsigned int chan = 0; chan < AllChannelsAndStationsDatasets.size(); ++chan) {
580  st = 0;
581  tempVector.clear();
582  for (unsigned int row=0; row < AllChannelsAndStationsDatasets[chan][st].size(); ++row) {
583  for (unsigned int col=1; col < AllChannelsAndStationsDatasets[chan][st][row].size(); ++col) {
584  for (unsigned int st=0; st < AllChannelsAndStationsDatasets[chan].size(); ++st) {
585  if ((AllChannelsAndStationsDatasets[chan][st][row][col] != 0) & (col!=1)) {
586  tempVector.push_back(AllChannelsAndStationsDatasets[chan][st][row][col]);
587  if (tempVector.size() != 0){
588  float tempAverage = accumulate(tempVector.begin(), tempVector.end(), 0.0) / tempVector.size();
589  AllChannelsAndStationsDatasets_average[chan][row][col] = tempAverage;
590  tempVector.clear();
591  } else {
592  AllChannelsAndStationsDatasets_average[chan][row][col] = 0;
593  }
594  } //end if for freq cols
595  if (col == 1){
596 
597  info << "Weight of the rows in each station and channel: \n";
598  info << "weight test: station:" << fStationIds[st] << "channel: "<< fchannels[chan] << " row:"<<row<< " "
599  << AllChannelsAndStationsDatasets[chan][st][row][col] << endl;
600  INFODebug(info);
601  info.str("");
602 
603  // data
604  AllChannelsAndStationsDatasets_average[chan][row][1] += AllChannelsAndStationsDatasets[chan][st][row][col];
605 
606  } // end if for weight
607  } // end station loop
608  } // end cols loop
609  } //end row loop
610  } // end channel loop
611 
612  // save average from station and channels to file
613  INFO("Saving average of station datasets for each channel.");
614 
615  string timeHeaderString;
616  if (fdayStack == true){
617  timeHeaderString = "UTChour"; // "normal" hour time
618  } else {
619  timeHeaderString = "LSTtime"; // LST hour time
620  }
621  for (unsigned int chan = 0; chan < AllChannelsAndStationsDatasets_average.size(); ++chan) {
622  ofstream AllChannelsAndStationsDatasets_average_FILE;
623  AllChannelsAndStationsDatasets_average_FILE.open("./datasets/dataSetFile_Ch"+to_string(fchannels[chan])+"_average.txt", ios::out | ios::app);
624  AllChannelsAndStationsDatasets_average_FILE << std::setprecision(6) << fixed;
625  AllChannelsAndStationsDatasets_average_FILE << timeHeaderString << setw(16) << "weight";
626  for (unsigned int i=0; i<freqBins.size()-1; ++i){
627  AllChannelsAndStationsDatasets_average_FILE << setw(16) << freqBins[i];
628  }
629  AllChannelsAndStationsDatasets_average_FILE << endl;
630  // end of saving to file
631  cout << "\tStoring dataset. " << endl;
632  AllChannelsAndStationsDatasets_average_FILE << std::setprecision(9) << scientific;
633  for (unsigned int row = 0; row < AllChannelsAndStationsDatasets_average[chan].size(); ++row) {
634  for (unsigned int col = 0; col < AllChannelsAndStationsDatasets_average[chan][row].size(); ++col) {
635  AllChannelsAndStationsDatasets_average_FILE << AllChannelsAndStationsDatasets_average[chan][row][col] << "\t" ;
636  }
637  AllChannelsAndStationsDatasets_average_FILE << endl;
638  }
639  AllChannelsAndStationsDatasets_average_FILE.close();
640  }
641 
643 
644  info << "Output of the final averaged datasets for each channel: \n";
645  info << "*********************" << endl;
646  info <<"**********************" << endl;
647  // test of 3d vector
648  for (unsigned int chan = 0; chan < AllChannelsAndStationsDatasets_average.size(); ++chan) {
649  info <<"***channel: " << fchannels[chan] << " ***" << endl;
650  for (unsigned int row=0; row < AllChannelsAndStationsDatasets_average[chan].size(); ++row) {
651  for (unsigned int col=0; col < AllChannelsAndStationsDatasets_average[chan][row].size(); ++col) {
652  info << AllChannelsAndStationsDatasets_average[chan][row][col] << " ";
653  }
654  info << endl;
655  }
656  }
657  info << "\n" <<"**********************" << "\n";
658  info << "\n" <<"**********************" << "\n";
659  INFOIntermediate(info);
660  info.str("");
661 
662  // save all channel and station datasets separately
663  INFO("Saving station and channel datasets (separately).");
664  // initialize dataset file header
665  for (unsigned chan=0; chan < AllChannelsAndStationsDatasets.size(); ++chan) {
666  for (unsigned st=0; st< AllChannelsAndStationsDatasets[chan].size(); ++st) {
667  ofstream dataSetFileOutput;
668  dataSetFileOutput.open("./datasets/dataSetFile_Station"+to_string(fStationIds[st])+"_Ch"+to_string(fchannels[chan])+".txt", ios::out | ios::app);
669  dataSetFileOutput << std::setprecision(6) << fixed;
670  dataSetFileOutput << timeHeaderString << setw(16) << "weight";
671  for (unsigned int u=0; u<freqBins.size()-1; ++u) {
672  dataSetFileOutput << setw(16) << freqBins[u];
673  }
674  dataSetFileOutput << endl;
675  dataSetFileOutput << std::setprecision(9) << scientific;
676  for (unsigned int row = 0; row < AllChannelsAndStationsDatasets[chan][st].size(); ++row) {
677  for (unsigned int col = 0; col < AllChannelsAndStationsDatasets[chan][st][row].size(); ++col) {
678  dataSetFileOutput << AllChannelsAndStationsDatasets[chan][st][row][col] << " ";
679  } // end col loop
680  dataSetFileOutput << endl;
681  } // end row loop
682  } //end station
683  } //end channel loop
684  //
685 
686  // just some statistics, to see at the end how many traces in each stations were and how many has passed
687  INFO("How many traces in each station passed the filtering conditions from the total number of traces that were in the station:");
688  for (unsigned int st = 0; st < stationTraceCounter.size(); ++st) {
689  cout << "Station: " << fStationIds[st] << " ::: " << stationTraceCounter[st][0] << "/" << stationTraceCounter[st][1] << endl;
690  }
691 
692  return eSuccess;
693 
694  }
695 
696  float
697  RdGalacticDatasetMaker::onlineMean(float oldMean, float nextValue, int n)
698  {
699  return oldMean + (nextValue-oldMean)/n;
700  }
701 
702  int
703  RdGalacticDatasetMaker::getChannelIndex(vector<int> vector, int element)
704  {
705  auto it = find(vector.begin(), vector.end(), element);
706  int index;
707  // If element was found get the index of element in vector
708  if (it != vector.end()) {
709  index = distance(vector.begin(), it);
710  } else {
711  ERROR("Channel number not found! \n"); //If the element is not
712  return eFailure;
713  }
714  return index;
715  }
716 
717  // copied from RdChannelGalacticConstantsGenerator
718  // function to calculate LST
719  double
720  RdGalacticDatasetMaker::GPSSecToLSTHourAuger(const int gps)
721  {
722  const double J2000 = 2451545.0;
723  const float Dtohr = 0.066666666666666;
724  const time_t utc = gps + 315964800 - 18; // GPS UTC offset, leap seconds are added to utc, so they have to be substracted from GPS time
725 
726  const tm* const t = gmtime(&utc);
727  int year = t->tm_year + 1900;
728  int month = t->tm_mon + 1;
729  const int day = t->tm_mday;
730  const int hour = t->tm_hour;
731  const int min = t->tm_min;
732  const int sec = t->tm_sec;
733 
734 //#warning can you use the utl::ModifiedJulianDate here?
735  //Date to Julian Date
736  if (month <= 2) {
737  --year;
738  month += 12;
739  }
740  const int a = int(floor(year / 100.));
741  const int b = 2 - a + a/4;
742  double jd = floor(365.25*(year + 4716)) + floor(30.6001*(month + 1)) + day + b - 1524.5;
743 
744  const double fd = double(60*60*hour + 60*min + sec) / 86400;
745  jd = jd + fd;
746 
747  static double sidereal_coeff[4] = { 280.46061837, 360.98564736629, 0.000387933, 38710000 };
748  const double dt = jd - J2000;
749  const double dt0 = dt / 36525.;
750  const double theta =
751  sidereal_coeff[0] + dt * sidereal_coeff[1] +
752  dt0 * dt0 * (sidereal_coeff[2] - dt0 / sidereal_coeff[3]); // is in degrees
753  // original J. Meeus: longitude is positive westwards *lst = mod(theta-longitude,360.) * kSTC::Dtohr;
754  // with the new convention for longitudes (positive eastwards) :
755  // the PAO longitude -69.25 is taken from GAP-2001-038
756  const double lst = fmod(theta + (360 - 69.25), 360.) * Dtohr;
757  return lst;
758  }
759 
760  float
761  RdGalacticDatasetMaker::HHMMSS2hour(float ffHHMMSS)
762  {
763  float fhour = floor(ffHHMMSS/10000);
764  float fminute = floor((ffHHMMSS - fhour*10000)/100);
765  float fsecond = ffHHMMSS - fhour*10000 - fminute*100;
766  return fhour + fminute/60 + fsecond/3600;
767  }
768 
769  unsigned int
771  {
772  const UTCDateTime t = timest;
773  return t.GetHour()*10000 + t.GetMinute()*100 + t.GetSecond();
774  }
775 
776  double
777  RdGalacticDatasetMaker::GetImpedanceAt(Branch topBranch, int channelID, float frequencyMHz)
778  {
779  TabulatedFunction returnData;
780  Branch mainBranch = topBranch.GetFirstChild();
781  // Branch mainBranch = topBranch;
782  Branch impBranch;
783  vector<float> frequency;
784  vector<float> impedance;
785  for (; mainBranch; mainBranch = mainBranch.GetNextSibling()){
786  if (stoi(mainBranch.GetAttributes().begin()->second) == channelID){
787  impBranch = mainBranch.GetChild("impedance");
788  impBranch.GetChild("x").GetData(frequency);
789  impBranch.GetChild("y").GetData(impedance);
790  for (unsigned int i = 0; i < frequency.size(); ++i)
791  returnData.PushBack(frequency[i], impedance[i]);
792  return returnData.Y(frequencyMHz/1000);
793  }
794  }
795  ERROR("Impedance for the channel not found!"); //If the element is not
796  return eFailure;
797  }
798 }
Branch GetTopBranch() const
Definition: Branch.cc:63
static double GetImpedanceAt(utl::Branch topBranch, int channelID, float frequencyMHz)
double StandardDeviation(const std::vector< double > &v, const double mean)
Definition: Functions.cc:26
bool IsActive() const
int GetId() const
Return Id of the Channel.
Report success to RunController.
Definition: VModule.h:62
Detector description interface for Station-related data.
int GetHour() const
Definition: UTCDateTime.h:54
Interface class to access to the Radio part of an event.
Definition: REvent.h:42
Class to hold collection (x,y) points and provide interpolation between them.
utl::TimeStamp GetTime() const
Definition: REvent/Header.h:17
double GetBinning() const
size of one slot
Definition: Trace.h:138
#define INFO(message)
Macro for logging informational messages.
Definition: ErrorLogger.h:161
StationIterator StationsEnd()
Definition: REvent.h:130
StationIterator StationsBegin()
Definition: REvent.h:128
void Init()
Initialise the registry.
vector< t2list > out
output of the algorithm: a list of clusters
Definition: XbAlgo.cc:32
Detector description interface for Channel-related data.
void PushBack(const double x, const double y)
Branch GetChild(const std::string &childName) const
Get child of this Branch by child name.
Definition: Branch.cc:211
unsigned int TimeStamp2HHMMSS(const utl::TimeStamp &timest)
Convert a TimeStamp into an integer representing the time as HHMMSS.
ChannelIterator ChannelsBegin()
begin Channel iterator for read/write
boost::filter_iterator< StationFilter, AllStationIterator > StationIterator
Iterator over all (non-exculded) stations.
Definition: REvent.h:125
bool HasREvent() const
int GetMinute() const
Definition: UTCDateTime.h:56
ChannelIterator ChannelsEnd()
end Channel iterator for read/write
static unsigned int TimeStamp2HHMMSS(const utl::TimeStamp &timest)
A TimeStamp holds GPS second and nanosecond for some event.
Definition: TimeStamp.h:110
AttributeMap GetAttributes() const
Get a map&lt;string, string&gt; containing all the attributes of this Branch.
Definition: Branch.cc:267
Branch GetNextSibling() const
Get next sibling of this branch.
Definition: Branch.cc:284
int fd
Definition: dump1090.h:233
#define INFOIntermediate(y)
Definition: VModule.h:162
Class representing a document branch.
Definition: Branch.h:107
class to hold data at the radio Station level.
int GetSecond() const
Definition: UTCDateTime.h:58
double abs(const SVector< n, T > &v)
Header & GetHeader()
access to REvent Header
Definition: REvent.h:239
std::vector< std::vector< std::vector< std::vector< float > > > > AllChannelsAndStationsDatasets
SizeType GetSize() const
Definition: Trace.h:156
#define WARNING(message)
Macro for logging warning messages.
Definition: ErrorLogger.h:163
void GetData(bool &b) const
Overloads of the GetData member template function.
Definition: Branch.cc:644
constexpr double hour
Definition: AugerUnits.h:150
#define INFODebug(y)
Definition: VModule.h:163
const Channel & GetChannel(const int id) const
Get specified Channel by id.
void SetBinning(const double binning)
Definition: Trace.h:139
ResultFlag
Flag returned by module methods to the RunController.
Definition: VModule.h:60
int GetRunNumber() const
Event id in the run (Start at zero at the beginning of each run) /provided by the daq...
Definition: REvent/Header.h:22
unsigned long GetGPSSecond() const
GPS second.
Definition: TimeStamp.h:124
SizeType GetStart() const
Get valid data start bin.
Definition: Trace.h:142
ChannelFrequencySpectrum & GetChannelFrequencySpectrum()
retrieve Channel Frequency Spectrum (write access, only use this if you intend to change the data) ...
double GetFrequencyOfBin(const ChannelFrequencySpectrum::SizeType bin) const
Get the frequency corresponding to a bin of the frequency spectrum.
static int getChannelIndex(std::vector< int > vector, int element)
Class that holds the data associated to an individual radio channel.
v push_back(value)
Report failure to RunController, causing RunController to terminate execution.
Definition: VModule.h:64
std::vector< std::vector< float > > stationTraceCounter
Branch GetFirstChild() const
Get first child of this Branch.
Definition: Branch.cc:98
static float onlineMean(float oldMean, float nextValue, int n)
double GetSamplingFrequency() const
Get sampling Frequency of ADC (unit?)
double Y(const double x) const
Get or interpolate the Y value that corresponds to parameter x.
#define INFOFinal(y)
Definition: VModule.h:161
void PushBack(const T &value)
Insert a single value at the end.
Definition: Trace.h:119
#define ERROR(message)
Macro for logging error messages.
Definition: ErrorLogger.h:165
int GetId() const
Definition: REvent/Header.h:21
constexpr double day
Definition: AugerUnits.h:151
const double year
Definition: GalacticUnits.h:22

, generated on Tue Sep 26 2023.