CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
SiStripDetVOffBuilder.cc
Go to the documentation of this file.
2 #include "boost/foreach.hpp"
3 #include <sys/stat.h>
4 
5 // constructor
7  onlineDbConnectionString(pset.getParameter<std::string>("onlineDB")),
8  authenticationPath(pset.getParameter<std::string>("authPath")),
9  whichTable(pset.getParameter<std::string>("queryType")),
10  lastValueFileName(pset.getParameter<std::string>("lastValueFile")),
11  fromFile(pset.getParameter<bool>("lastValueFromFile")),
12  psuDetIdMapFile_(pset.getParameter<std::string>("PsuDetIdMapFile")),
13  debug_(pset.getParameter<bool>("debugModeOn")),
14  tDefault(7,0),
15  tmax_par(pset.getParameter< std::vector<int> >("Tmax")),
16  tmin_par(pset.getParameter< std::vector<int> >("Tmin")),
17  tset_par(pset.getParameter< std::vector<int> >("TSetMin")),
18  detIdListFile_(pset.getParameter< std::string >("DetIdListFile")),
19  excludedDetIdListFile_(pset.getParameter< std::string >("ExcludedDetIdListFile")),
20  highVoltageOnThreshold_(pset.getParameter<double>("HighVoltageOnThreshold"))
21 {
22  lastStoredCondObj.first = NULL;
23  lastStoredCondObj.second = 0;
24 
25  edm::LogError("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::SiStripDetVOffBuilder] constructor" << endl;
26 
27  // set up vectors based on pset parameters (tDefault purely for initialization)
28 
29  whichQuery=(whichTable == "STATUSCHANGE" || (whichTable == "LASTVALUE" && !fromFile));
30 
31  //Define the query interval [Tmin, Tmax]
32  //where Tmax comes from the cfg
33  // Tmin comes from the cfg for the first o2o, after that it is extracted from Offline DB
34 
35  tmax = coral::TimeStamp(tmax_par[0],tmax_par[1],tmax_par[2],tmax_par[3],tmax_par[4],tmax_par[5],tmax_par[6]);
36 
37  if (whichQuery) {
38  // Is there a better way to do this? TODO - investigate
39  tmin=coral::TimeStamp(tmin_par[0],tmin_par[1],tmin_par[2],tmin_par[3],tmin_par[4],tmin_par[5],tmin_par[6]);
40  }
41 
42  if (whichTable == "LASTVALUE") {
43  tsetmin = coral::TimeStamp(tset_par[0],tset_par[1],tset_par[2],tset_par[3],tset_par[4],tset_par[5],tset_par[6]);
44  }
45 
46  if (onlineDbConnectionString == "") {
47  edm::LogError("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::SiStripDetVOffBuilder] DB name has not been set properly ... Returning ...";
48  return;
49  }
50 
51  if (fromFile && whichTable == "LASTVALUE" && lastValueFileName == "") {
52  edm::LogError("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::SiStripDetVOffBuilder] File expected for lastValue table, but filename not specified ... Returning ...";
53  return;
54  }
55 
56  // write out the parameters
57  std::stringstream ss;
58  ss << "[SiStripDetVOffBuilder::SiStripDetVOffBuilder]\n"
59  << " Parameters:\n"
60  << " DB connection string: " << onlineDbConnectionString << "\n"
61  << " Authentication path: " << authenticationPath << "\n"
62  << " Table to be queried: " << whichTable << "\n"
63  << " MapFile: " << psuDetIdMapFile_ << "\n";
64 
65  if (whichQuery){
66  ss << " Tmin: "; printPar(ss,tmin_par); ss << std::endl;
67  }
68  ss << " Tmax: " ; printPar(ss,tmax_par); ss << std::endl;
69 
70  if (whichTable == "LASTVALUE"){
71  ss << " TSetMin: "; printPar(ss,tset_par); ss << std::endl;
72  }
73  edm::LogError("SiStripDetVOffBuilder") << ss.str();
74 
75 }
76 
77 // destructor
79  edm::LogError("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::" << __func__ << "]: destructing ...";
80 }
81 
82 void SiStripDetVOffBuilder::printPar(std::stringstream& ss, const std::vector<int>& par){
83  BOOST_FOREACH(int val, par){
84  ss << val << " ";
85  }
86 }
87 
89 {
90  // vectors for storing output from DB or text file
91  TimesAndValues timesAndValues;
92 
93  // Open the PVSS DB connection
95  edm::LogError("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::BuildDetVOff]: Query type is " << whichTable << endl;
96 
97  if (whichTable == "LASTVALUE") {edm::LogError("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::BuildDetVOff]: Use file? " << ((fromFile) ? "TRUE" : "FALSE");}
98 
99  if (lastStoredCondObj.second > 0) {edm::LogError("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::BuildDetVOff]: retrieved last time stamp from DB: "
100  << lastStoredCondObj.second << endl;}
101  // access the information!
102  //We've been using the STATUSCHANGE query only in last year or so... LASTVALUE may have untested issues...
103  //In either case the idea is that the results of the query are saved into the timesAndValues struct
104  //ready to be anaylized (i.e. translated into detIDs, HV/LV statuses)
105 
106  if (whichQuery) {
107  if( whichTable == "STATUSCHANGE" ) {
108  statusChange( lastStoredCondObj.second, timesAndValues );
109  }
110  if( whichTable == "LASTVALUE" ) {
111  if( fromFile ) {
112  lastValueFromFile(timesAndValues);
113  }
114  else {
115  lastValue(timesAndValues);
116  }
117  }
118  }
119 
120  //Initialize the stuct that will be used to keep the detID-translated information
121  DetIdListTimeAndStatus dStruct;
122 
123  // build PSU - det ID map
124  //The following method actually "builds" 4 maps: LVMap, HVMap, HVUnmapped_Map, HVCrosstalking_Map.
125  //It also takes the timesAndValues from the query above and using the maps, it processes the information
126  //populating the DetIDListTimeAndStatus struct that will hold the information by detid.
127  buildPSUdetIdMap(timesAndValues, dStruct);
128 
129 
130  // initialize variables
131  modulesOff.clear();
132  cond::Time_t saveIovTime = 0;
133 
134 
135  // - If there is already an object stored in the database
136  // -- store it in the modulesOff vector
137  // -- set the saveIovTime as that
138  // -- set the payload stats to empty
139  // Successivamente:
140  // - loop su tutti gli elementi del detidV, che è stato letto dal pvss (questi elementi sono pair<vettore di detid, time>)
141  // -- setta il tempo dell'IOV:
142  // --- LASTVALUE -> iovtime settato a latestTime
143  // --- altrimenti iovtime = tempo associato al detId vector del loop
144 
145 
146  // check if there is already an object stored in the DB
147  // This happens only if you are using STATUSCHANGE
148  if (lastStoredCondObj.first != NULL && lastStoredCondObj.second > 0) {
149  modulesOff.push_back( lastStoredCondObj );
150  saveIovTime = lastStoredCondObj.second;
151  setPayloadStats(0, 0, 0);
152  }
153 
154 
155  //Master loop over all the results of the query stored in the dStruct (that contains vectors with vectors of detids, statuses, isHV flags, etc and in particular a vector of timestamps for which the info is valid... basically it is a loop over the timestamps (i.e. IOVs).
156  for (unsigned int i = 0; i < dStruct.detidV.size(); i++) {
157 
158  // std::vector<uint32_t> detids = dStruct.detidV[i].first;
159  // removeDuplicates(detids);
160  std::vector<uint32_t> * detids = &(dStruct.detidV[i].first);
161 
162  // set the condition time for the transfer
163  cond::Time_t iovtime = 0;
164 
165  if (whichTable == "LASTVALUE") {iovtime = timesAndValues.latestTime;}
166 
167  else {iovtime = getCondTime((dStruct.detidV[i]).second);}
168 
169  // decide how to initialize modV
170  SiStripDetVOff *modV = 0;
171 
172  // When using STATUSCHANGE they are equal only for the first
173  // When using LASTVALUE they are equal only if the tmin was set to tsetmin
174 
175  if (iovtime != saveIovTime) { // time is different, so create new object
176 
177  // This can be only when using LASTVALUE or with a new tag
178  if (modulesOff.empty()) {
179  // create completely new object and set the initial state to Tracker all off
180  modV = new SiStripDetVOff();
181 
182  // Use the file
185  const std::map<uint32_t, SiStripDetInfoFileReader::DetInfo > detInfos = reader.getAllData();
186 
187  //FIXME:
188  //Following code is actually broken (well not until the cfg has "" for excludedDetIDListFile parameter!
189  //Fix it if felt necessary (remember that it assumes that whatever detids are excluded should NOT be in the regular map
190  //breaking our current situation with a fully mapped (LV-wise) tracker...
191  // Careful: if a module is in the exclusion list it must be ignored and the initial status is set to ON.
192  // These modules are expected to not be in the PSU-DetId map, so they will never get any status change from the query.
193  SiStripPsuDetIdMap map;
194  std::vector< std::pair<uint32_t, std::string> > excludedDetIdMap;
195  if( excludedDetIdListFile_ != "" ) {
196  map.BuildMap(excludedDetIdListFile_, excludedDetIdMap);
197  }
198  for(std::map<uint32_t, SiStripDetInfoFileReader::DetInfo >::const_iterator it = detInfos.begin(); it != detInfos.end(); ++it) {
199  std::vector< std::pair<uint32_t, std::string> >::const_iterator exclIt = excludedDetIdMap.begin();
200  bool excluded = false;
201  for( ; exclIt != excludedDetIdMap.end(); ++exclIt ) {
202  if( it->first == exclIt->first ) {
203  excluded = true;
204  break;
205  }
206  }
207  if( !excluded ) {
208  modV->put( it->first, 1, 1 );
209  }
210  }
211 
212  }
213  else {modV = new SiStripDetVOff( *(modulesOff.back().first) );} // start from copy of previous object
214  }
215  else {
216  modV = (modulesOff.back()).first; // modify previous object (TEST THIS if possible! it's fundamental in handling changes at the edges of O2O executions and also in case of PVSS DB buffering!
217  }
218 
219 
220 
221  // extract the detID vector before modifying for stats calculation
222  std::vector<uint32_t> beforeV;
223  modV->getDetIds(beforeV);
224 
225  //CHECKTHIS
226  //The following method call is potentially problematic:
227  //passing modV as argument while extracting information about dStruct,
228  //modV is not currently used in the method!
229  std::pair<int, int> hvlv = extractDetIdVector(i, modV, dStruct);//Returns a pair like this HV OFF->1,-1 HV ON->0,-1 LV OFF->-1,1 LV ON->-1,0
230  //Basically a LV OFF of -1 means that the information (IOV) in question is from an HV channel turning on or off and viceversa for an HVOFF of -1.
231  //This could be confusing when reading the debug output!
232 
233  for (unsigned int j = 0; j < detids->size(); j++) {
234  if( debug_ ) cout << "at time = " << iovtime << " detid["<<j<<"] = " << (*detids)[j] << " has hv = " << hvlv.first << " and lv = " << hvlv.second << endl;
235  modV->put((*detids)[j],hvlv.first,hvlv.second);
236  }
237 
238  // calculate the stats for storage
239  unsigned int numAdded = 0, numRemoved = 0;
240  if (iovtime == saveIovTime) {
241  std::vector<uint32_t> oldStats = payloadStats.back();
242  numAdded = oldStats[1];
243  numRemoved = oldStats[2];
244  }
245  std::vector<uint32_t> afterV;
246  modV->getDetIds(afterV);
247 
248  if ((afterV.size() - beforeV.size()) > 0) {
249  numAdded += afterV.size() - beforeV.size();
250  } else if ((beforeV.size() - afterV.size()) > 0) {
251  numRemoved += beforeV.size() - afterV.size();
252  }
253 
254 
255  // store the object if it's a new object
256  if (iovtime != saveIovTime) {
257  SiStripDetVOff * testV = 0;
258  if (!modulesOff.empty()) {testV = modulesOff.back().first;}
259  if (modulesOff.empty() || !(*modV == *testV) ) {
260  modulesOff.push_back( std::make_pair(modV,iovtime) );
261  // save the time of the object
262  saveIovTime = iovtime;
263  // save stats
264  setPayloadStats(afterV.size(), numAdded, numRemoved);
265  }
266  } else {
267  (payloadStats.back())[0] = afterV.size();
268  (payloadStats.back())[1] = numAdded;
269  (payloadStats.back())[2] = numRemoved;
270  }
271  }
272 
273 
274  // compare the first element and the last from previous transfer
275  if (lastStoredCondObj.first != NULL && lastStoredCondObj.second > 0) {
276  if ( lastStoredCondObj.second == modulesOff[0].second &&
277  *(lastStoredCondObj.first) == *(modulesOff[0].first) ) {
278  std::vector< std::pair<SiStripDetVOff*,cond::Time_t> >::iterator moIt = modulesOff.begin();
279  modulesOff.erase(moIt);
280  std::vector< std::vector<uint32_t> >::iterator plIt = payloadStats.begin();
281  payloadStats.erase(plIt);
282  }
283  }
284 
285  if (debug_) {
286  std::cout << std::endl;
287  std::cout << "Size of modulesOff = " << modulesOff.size() << std::endl;
288  for (unsigned int i = 0; i < modulesOff.size(); i++) {
289  std::vector<uint32_t> finalids;
290  (modulesOff[i].first)->getDetIds(finalids);
291  std::cout << "Index = " << i << " Size of DetIds vector = " << finalids.size() << std::endl;
292  std::cout << "Time = " << modulesOff[i].second << std::endl;
293  for (unsigned int j = 0; j < finalids.size(); j++) {
294  std::cout << "detid = " << finalids[j] << " LV off = " << (modulesOff[i].first)->IsModuleLVOff(finalids[j]) << " HV off = "
295  << (modulesOff[i].first)->IsModuleHVOff(finalids[j]) << std::endl;
296  }
297  }
298  }
299 }
300 
301 int SiStripDetVOffBuilder::findSetting(uint32_t id, const coral::TimeStamp& changeDate, const std::vector<uint32_t>& settingID, const std::vector<coral::TimeStamp>& settingDate) {
302  int setting = -1;
303  // find out how many channel entries there are
304  std::vector<int> locations;
305  for (unsigned int i = 0; i < settingID.size(); i++) { if (settingID[i] == id) {locations.push_back((int)i);} }
306 
307  // simple cases
308  if (locations.size() == 0) {setting = -1;}
309  else if (locations.size() == 1) {setting = locations[0];}
310  // more than one entry for this channel
311  // NB. entries ordered by date!
312  else {
313  for (unsigned int j = 0; j < locations.size(); j++) {
314 #ifdef USING_NEW_CORAL
315  const boost::posix_time::ptime& testSec = changeDate.time();
316  const boost::posix_time::ptime& limitSec = settingDate[(unsigned int)locations[j]].time();
317 #else
318  long testSec = changeDate.time().ns();
319  long limitSec = settingDate[(unsigned int)locations[j]].time().ns();
320 #endif
321  if (testSec >= limitSec) {setting = locations[j];}
322  }
323  }
324  return setting;
325 }
326 
327 int SiStripDetVOffBuilder::findSetting(std::string dpname, const coral::TimeStamp& changeDate, const std::vector<std::string>& settingDpname, const std::vector<coral::TimeStamp>& settingDate) {
328  int setting = -1;
329  // find out how many channel entries there are
330  std::vector<int> locations;
331  for (unsigned int i = 0; i < settingDpname.size(); i++) { if (settingDpname[i] == dpname) {locations.push_back((int)i);} }
332 
333  // simple cases
334  if (locations.size() == 0) {setting = -1;}
335  else if (locations.size() == 1) {setting = locations[0];}
336  // more than one entry for this channel
337  // NB. entries ordered by date!
338  else {
339  for (unsigned int j = 0; j < locations.size(); j++) {
340 #ifdef USING_NEW_CORAL
341  const boost::posix_time::ptime& testSec = changeDate.time();
342  const boost::posix_time::ptime& limitSec = settingDate[(unsigned int)locations[j]].time();
343 #else
344  long testSec = changeDate.time().ns();
345  long limitSec = settingDate[(unsigned int)locations[j]].time().ns();
346 #endif
347  if (testSec >= limitSec) {setting = locations[j];}
348  }
349  }
350  return setting;
351 }
352 
353 void SiStripDetVOffBuilder::readLastValueFromFile(std::vector<uint32_t> &dpIDs, std::vector<float> &vmonValues, std::vector<coral::TimeStamp> &dateChange) {
354  std::ifstream lastValueFile(lastValueFileName.c_str());
355  if (lastValueFile.bad()) {
356  edm::LogError("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::" << __func__ << "]: last Value file does not exist!";
357  return;
358  }
359 
360  dpIDs.clear();
361  vmonValues.clear();
362  dateChange.clear();
363  std::vector<std::string> changeDates;
364 
366  // remove the first line as it is the title line
367  // std::getline(lastValueFile,line);
368  // line.clear();
369  // now extract data
370  while( std::getline(lastValueFile,line) ) {
371  std::istringstream ss(line);
372  uint32_t dpid;
373  float vmon;
374  std::string changeDate;
375  ss >> std::skipws >> dpid >> vmon >> changeDate;
376  dpIDs.push_back(dpid);
377  vmonValues.push_back(vmon);
378  changeDates.push_back(changeDate);
379  }
380  lastValueFile.close();
381 
382  // Now convert dates to coral::TimeStamp
383  for (unsigned int i = 0; i < changeDates.size(); i++) {
384  std::string part = changeDates[i].substr(0,4);
385  int year = atoi(part.c_str());
386  part.clear();
387 
388  part = changeDates[i].substr(5,2);
389  int month = atoi(part.c_str());
390  part.clear();
391 
392  part = changeDates[i].substr(8,2);
393  int day = atoi(part.c_str());
394  part.clear();
395 
396  part = changeDates[i].substr(11,2);
397  int hour = atoi(part.c_str());
398  part.clear();
399 
400  part = changeDates[i].substr(14,2);
401  int minute = atoi(part.c_str());
402  part.clear();
403 
404  part = changeDates[i].substr(17,2);
405  int second = atoi(part.c_str());
406  part.clear();
407 
408  coral::TimeStamp date(year,month,day,hour,minute,second,0);
409  dateChange.push_back(date);
410  }
411 
412  if (changeDates.size() != dateChange.size()) {edm::LogError("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::" << __func__ << "]: date conversion failed!!";}
413 }
414 
415 cond::Time_t SiStripDetVOffBuilder::getCondTime(const coral::TimeStamp& coralTime) {
416 
417  // const boost::posix_time::ptime& t = coralTime.time();
418  cond::Time_t condTime = cond::time::from_boost(coralTime.time());
419 
420  // cout << "[SiStripDetVOffBuilder::getCondTime] Converting CoralTime into CondTime: "
421  // << " coralTime = (coralTimeInNs) " << coralTime.total_nanoseconds() << " condTime " << (condTime>> 32) << " - " << (condTime & 0xFFFFFFFF) << endl;
422 
423  return condTime;
424 }
425 
427 {
428  // This method is defined in the TimeConversions header and it does the following:
429  // - takes the seconds part of the iovTime (bit-shifting of 32)
430  // - adds the nanoseconds part (first 32 bits mask)
431  // - adds the time0 that is the time from begin of times (boost::posix_time::from_time_t(0);)
432  coral::TimeStamp coralTime(cond::time::to_boost(iovTime));
433 
434  if( debug_ ) {
435  unsigned long long iovSec = iovTime >> 32;
436  uint32_t iovNanoSec = uint32_t(iovTime);
437  cond::Time_t testTime=getCondTime(coralTime);
438  cout << "[SiStripDetVOffBuilder::getCoralTime] Converting CondTime into CoralTime: "
439  << " condTime = " << iovSec << " - " << iovNanoSec
440  << " getCondTime(coralTime) = " << (testTime>>32) << " - " << (testTime&0xFFFFFFFF) << endl;
441  }
442 
443  return coralTime;
444 }
445 
446 void SiStripDetVOffBuilder::removeDuplicates( std::vector<uint32_t> & vec ) {
447  std::sort(vec.begin(),vec.end());
448  std::vector<uint32_t>::iterator it = std::unique(vec.begin(),vec.end());
449  vec.resize( it - vec.begin() );
450 }
451 
453  lastStoredCondObj.first = lastPayload;
454  lastStoredCondObj.second = lastTimeStamp;
455 }
456 
457 cond::Time_t SiStripDetVOffBuilder::findMostRecentTimeStamp( const std::vector<coral::TimeStamp>& coralDate ) {
458  cond::Time_t latestDate = getCondTime(coralDate[0]);
459 
460  if( debug_ ) {
461  std::cout << "latestDate: condTime = "
462  << (latestDate>>32)
463  << " - "
464  << (latestDate&0xFFFFFFFF)
465  //<< " coralTime= " << coralDate[0]
466  << std::endl;
467  }
468 
469  for (unsigned int i = 1; i < coralDate.size(); i++) {
470  cond::Time_t testDate = getCondTime(coralDate[i]);
471  if (testDate > latestDate) {
472  latestDate = testDate;
473  }
474  }
475  return latestDate;
476 }
477 
478 void SiStripDetVOffBuilder::reduce( std::vector< std::pair<SiStripDetVOff*,cond::Time_t> >::iterator & it,
479  std::vector< std::pair<SiStripDetVOff*,cond::Time_t> >::iterator & initialIt,
480  std::vector< std::pair<SiStripDetVOff*,cond::Time_t> > & resultVec,
481  const bool last )
482 {
483  //const bool last is set to false by default in the header file...
484  int first = 0;
485  // Check if it is the first
486  if( distance(resultVec.begin(), initialIt) == 0 ) {
487  first = 1;
488  }
489 
490  if( debug_ && ( it->first->getLVoffCounts() - initialIt->first->getLVoffCounts() == 0 ) && ( it->first->getHVoffCounts() - initialIt->first->getHVoffCounts() == 0 ) ) {
491  cout << "Same number of LV and HV at start and end of sequence: LV off = " << it->first->getLVoffCounts() << " HV off = " << it->first->getHVoffCounts() << endl;
492  }
493 
494  // if it was going off
495  if( ( it->first->getLVoffCounts() - initialIt->first->getLVoffCounts() > 0 ) || ( it->first->getHVoffCounts() - initialIt->first->getHVoffCounts() > 0 ) ) {
496  // Set the time of the current (last) iov as the time of the initial iov of the sequence
497  // replace the first iov with the last one
498  //Naughty use of const bool last... by default it is false (=0), and for the case of the last timestamp in the query results it is set to true(=1) in the call
499  (it+last)->second = (initialIt)->second;
500  discardIOVs(it, initialIt, resultVec, last, 0);
501  if( debug_ ) cout << "Reducing IOV sequence (going off)" << endl;
502  }
503  // if it was going on
504  else if( ( it->first->getLVoffCounts() - initialIt->first->getLVoffCounts() <= 0 ) || ( it->first->getHVoffCounts() - initialIt->first->getHVoffCounts() <= 0 ) ) {
505  // replace the last minus one iov with the first one
506  discardIOVs(it, initialIt, resultVec, last, first);
507  if( debug_ ) cout << "Reducing IOV sequence (going on)" << endl;
508  }
509 }
510 
511 void SiStripDetVOffBuilder::discardIOVs( std::vector< std::pair<SiStripDetVOff*,cond::Time_t> >::iterator & it,
512  std::vector< std::pair<SiStripDetVOff*,cond::Time_t> >::iterator & initialIt,
513  std::vector< std::pair<SiStripDetVOff*,cond::Time_t> > & resultVec,
514  const bool last, const unsigned int first )
515 {
516  if( debug_ ) {
517  cout << "first (1->means the sequence started at the first timestamp in the query results, 0-> that it did not)= " << first << endl;
518  cout << "initial->first (initial SiStripDetVOff object of the IOV sequence)= " << initialIt->first << ", second (initial timestamp of the IOV sequence) = " << initialIt->second << endl;
519  cout << "last (0->means that the sequence is not ending with the last item in the query results, 1-> that it DOES!)= " << last << endl;
520  }
521  if( last == true ) {
522  resultVec.erase(initialIt+first, it+1);
523  // Minus 2 because it will be incremented at the end of the loop becoming end()-1.
524  it = resultVec.end()-2;
525  }
526  else {
527  it = resultVec.erase(initialIt+first, it);
528  }
529 }
530 
531 //This is the method that (called by GetModulesOff, declared in the header file) executes the reduction by massaging modulesOff
532 void SiStripDetVOffBuilder::reduction(const uint32_t deltaTmin, const uint32_t maxIOVlength)
533 {
534 
535  int count = 0;
536  std::vector< std::pair<SiStripDetVOff*,cond::Time_t> >::iterator initialIt;
537 
538  int resultVecSize = modulesOff.size();
539  int resultsIndex = 0;
540 
541  if( resultVecSize > 1 ) {
542  std::vector< std::pair<SiStripDetVOff*,cond::Time_t> >::iterator it = modulesOff.begin();
543  for( ; it != modulesOff.end()-1; ++it, ++resultsIndex ) {
544  unsigned long long deltaT = ((it+1)->second - it->second) >> 32;
545  unsigned long long deltaTsequence = 0;
546  if( count > 1 ) {
547  deltaTsequence = ((it+1)->second - initialIt->second) >> 32;
548  }
549  // Save the initial pair
550  if( (deltaT < deltaTmin) && ( (count == 0) || ( deltaTsequence < maxIOVlength ) ) ) {
551  // If we are not in a the sequence
552  if( count == 0 ) {
553  initialIt = it;
554  }
555  // Increase the counter in any case.
556  ++count;
557  }
558  // We do it only if the sequence is bigger than two cases
559  else if( count > 1 ) {
560  reduce(it, initialIt, modulesOff);
561  // reset all
562  count = 0;
563  }
564  else {
565  // reset all
566  count = 0;
567  }
568  // Border case
569  if( resultsIndex == resultVecSize-2 && count != 0 ) {
570  reduce(it, initialIt, modulesOff, true);
571  }
572  }
573  }
574 }
575 
577 {
578  // Setting tmin to the last value IOV of the database tag
579  if( lastTime > 0 ) {
580  tmin = getCoralTime(lastTime);
581  }
582 
583  coralInterface->doQuery(whichTable, tmin ,tmax, tStruct.changeDate, tStruct.actualValue, tStruct.dpname);
584  //UNIT TEST DEBUG to bypass the query wait time!!!
585  //coral::TimeStamp testtime=getCoralTime(lastTime);
586  //tStruct.changeDate.push_back(testtime);
587  //tStruct.actualValue.push_back(1.);
588  //tStruct.dpname.push_back("cms_trk_dcs_03:CAEN/CMS_TRACKER_SY1527_3/branchController00/easyCrate3/easyBoard17/channel002");
589 
590  // preset the size of the status vector
591  tStruct.actualStatus.resize(tStruct.actualValue.size());
592  tStruct.actualStatus.clear();
593 
594  BOOST_FOREACH(float val, tStruct.actualValue) {
595  tStruct.actualStatus.push_back(static_cast<int>(val));
596  }
597 }
598 
600 {
601  coralInterface->doQuery(whichTable, tmin ,tmax, tStruct.changeDate, tStruct.actualValue, tStruct.dpname);
602 
603  tStruct.latestTime = findMostRecentTimeStamp( tStruct.changeDate );
604 
605  // preset the size of the status vector
606  tStruct.actualStatus.resize(tStruct.actualValue.size());
607 
608  // retrieve the channel settings from the PVSS DB
609  std::vector<coral::TimeStamp> settingDate;
610  std::vector<float> settingValue;
611  std::vector<std::string> settingDpname;
612  std::vector<uint32_t> settingDpid;
613  coralInterface->doSettingsQuery(tsetmin,tmax,settingDate,settingValue,settingDpname,settingDpid);
614  LogDebug("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::BuildDetVOff]: Channel settings retrieved";
615  LogDebug("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::BuildDetVOff]: Number of PSU channels: " << settingDpname.size();
616 
617  unsigned int missing = 0;
618  std::stringstream ss;
619  for (unsigned int j = 0; j < tStruct.dpname.size(); j++) {
620  int setting = findSetting(tStruct.dpname[j],tStruct.changeDate[j],settingDpname,settingDate);
621  if (setting >= 0) {
622  if (tStruct.actualValue[j] > (highVoltageOnThreshold_*(settingValue[setting]))) {tStruct.actualStatus[j] = 1;}
623  else {tStruct.actualStatus[j] = 0;}
624  } else {
625  tStruct.actualStatus[j] = -1;
626  missing++;
627  ss << "Channel = " << tStruct.dpname[j] << std::endl;
628  }
629  }
630  LogDebug("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::BuildDetVOff]: Number of channels with no setting information " << missing;
631  LogDebug("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::BuildDetVOff]: Number of entries in dpname vector " << tStruct.dpname.size();
632 }
633 
635 {
636  readLastValueFromFile(tStruct.dpid,tStruct.actualValue,tStruct.changeDate);
637  tStruct.latestTime = findMostRecentTimeStamp( tStruct.changeDate );
638  LogDebug("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::BuildDetVOff]: File access complete \n\t Number of values read from file: " << tStruct.dpid.size();
639 
640  // retrieve the channel settings from the PVSS DB
641  std::vector<coral::TimeStamp> settingDate;
642  std::vector<float> settingValue;
643  std::vector<std::string> settingDpname;
644  std::vector<uint32_t> settingDpid;
645 
646  coralInterface->doSettingsQuery(tsetmin,tmax,settingDate,settingValue,settingDpname,settingDpid);
647  LogDebug("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::BuildDetVOff]: Channel settings retrieved";
648  LogDebug("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::BuildDetVOff]: Number of PSU channels: " << settingDpname.size();
649 
650  unsigned int missing = 0;
651  std::stringstream ss;
652  // need to get the PSU channel names from settings
653  tStruct.dpname.clear();
654  tStruct.dpname.resize(tStruct. dpid.size());
655  for (unsigned int j = 0; j < tStruct.dpid.size(); j++) {
656  int setting = findSetting(tStruct.dpid[j],tStruct.changeDate[j],settingDpid,settingDate);
657  if (setting >= 0) {
658  if (tStruct.actualValue[j] > (highVoltageOnThreshold_*settingValue[setting])) {tStruct.actualStatus[j] = 1;}
659  else {
660  tStruct.actualStatus[j] = 0;
661  }
662  tStruct.dpname[j] = settingDpname[setting];
663  } else {
664  tStruct.actualStatus[j] = -1;
665  tStruct.dpname[j] = "UNKNOWN";
666  missing++;
667  ss << "DP ID = " << tStruct.dpid[j] << std::endl;
668  }
669  }
670  LogDebug("SiStripDetVOffBuilder") << "Number of missing psu channels = " << missing << std::endl;
671  LogDebug("SiStripDetVOffBuilder") << "IDs are: = " << ss.str();
672 }
673 
674 string SiStripDetVOffBuilder::timeToStream(const cond::Time_t & condTime, const string & comment)
675 {
676  stringstream ss;
677  ss << comment << (condTime>> 32) << " - " << (condTime & 0xFFFFFFFF) << std::endl;
678  return ss.str();
679 }
680 
681 string SiStripDetVOffBuilder::timeToStream(const coral::TimeStamp & coralTime, const string & comment)
682 {
683  stringstream ss;
684  ss << "Starting from IOV time in the database : year = " << coralTime.year()
685  << ", month = " << coralTime.month()
686  << ", day = " << coralTime.day()
687  << ", hour = " << coralTime.hour()
688  << ", minute = " << coralTime.minute()
689  << ", second = " << coralTime.second()
690  << ", nanosecond = " << coralTime.nanosecond() << std::endl;
691  return ss.str();
692 }
694  //Helper method to check if local files exist (needed to handle HVUnmapped, HVCrosstalking modules)
695  struct stat FileInfo;
696  bool Existence;
697  int Stat;
698  //Try to get file attributes
699  Stat=stat(FileName.c_str(),&FileInfo);
700  if (Stat==0) {
701  Existence=true;
702  }
703  else {
704  Existence=false;
705  }
706  return Existence;
707 }
708 
710 //This function builds a PSU to DetID map one way or the other. Then it processes the psuStruct that contains
711 //the results of the CAEN status query to the Online DB, filling the detIdStruct with the detIDs corresponding
712 //to the PSU (channel in some cases, PSU only in others) reported in the CAEN status query to the Online DB.
713 //It may make sense to split this method eventually.
714 {
716  if( psuDetIdMapFile_ == "" ) {
717  std::cout<<"PLEASE provide the name of a valid PSUDetIDMapFile in the cfg: currently still necessary to have a file, soon will access the info straight from the DB!"<<endl;
718  //map_.BuildMap();//This method is not currently used (it would try to build a map based on a query to SiStripConfigDB, and the info there is STALE!)
719  }
720  else {
721  map_.BuildMap(psuDetIdMapFile_,debug_); //This is the method used to build the map.
722  }
723  LogTrace("SiStripDetVOffBuilder") <<"[SiStripDetVOffBuilder::BuildDetVOff] PSU(Channel)-detID map(s) built";
724  //Following method to be replaced by printMaps... to print all 4 maps built!
725  map_.printMap(); //This method prints to the info.log file, notice that it is overwritten by each individual O2O job running in the same dir.
726 
727  // use map info to build input for list of objects
728  // no need to check for duplicates, as put method for SiStripDetVOff checks for you!
729 
730  //Debug variables
731  unsigned int ch0bad = 0, ch1bad = 0, ch2bad = 0, ch3bad = 0;
732  std::vector<unsigned int> numLvBad, numHvBad;
733 
734  //Create 2 extra maps that we'll use to keep track of unmapped and crosstalking detids when turning ON and OFF HV:
735  //-unmapped need to be both turned OFF when any HV goes OFF and to be turned ON when both are ON
736  //-crosstaling need to be both turned ON when any HV goes ON and to be turned OFF ONLY when BOTH are OFF.
737  std::map<std::string,bool> UnmappedState, CrosstalkingState;
738  //Get the HVUnmapped map from the map, so that we can set know which PSU are unmapped:
739  std::map<std::string,std::vector<uint32_t> > UnmappedPSUs=map_.getHVUnmappedMap();
740  //Check here if there is a file already, otherwise initialize to OFF all channels in these PSU!
741  if (FileExists("HVUnmappedChannelState.dat")) {
742  std::cout<<"File HVUnmappedChannelState.dat exists!"<<std::endl;
743  std::ifstream ifs("HVUnmappedChannelState.dat");
744  string line;
745  while( getline( ifs, line ) ) {
746  if( line != "" ) {
747  // split the line and insert in the map
748  stringstream ss(line);
749  string PSUChannel;
750  bool HVStatus;
751  ss >> PSUChannel;
752  ss >> HVStatus;
753  //Extract the PSU from the PSUChannel (since the HVUnmapped_Map uses PSU as key
754  std::string PSU=PSUChannel.substr(0,PSUChannel.size()-10);
755  //Look for the PSU in the unmapped map!
756  std::map<std::string,std::vector<uint32_t> >::iterator iter=UnmappedPSUs.find(PSU);
757  if (iter!=UnmappedPSUs.end()) {
758  UnmappedState[PSUChannel]=HVStatus;
759  }
760  else {
761  std::cout<<"WARNING!!! There are channels in the local file with the channel status for HVUnmapped channels, that ARE NOT CONSIDERED AS UNMAPPED in the current map!"<<std::endl;
762  }
763  }
764  }//End of the while loop reading and initializing UnmappedState map from file
765  //Extra check:
766  //Should check if there any HVUnmapped channels in the map that are not listed in the local file!
767  bool MissingChannels=false;
768  for (std::map<std::string, vector<uint32_t> >::iterator it=UnmappedPSUs.begin(); it!=UnmappedPSUs.end(); it++) {
769  std::string chan002=it->first+"channel002";
770  std::string chan003=it->first+"channel003";
771  std::map<std::string,bool>::iterator iter=UnmappedState.find(chan002);
772  if (iter==UnmappedState.end()) {
773  std::cout<<"ERROR! The local file with the channel status for HVUnmapped channels IS MISSING one of the following unmapped channel voltage status information:"<<std::endl;
774  std::cout<<chan002<<std::endl;
775  MissingChannels=true;
776  }
777  iter=UnmappedState.find(chan003);
778  if (iter==UnmappedState.end()) {
779  std::cout<<"ERROR! The local file with the channel status for HVUnmapped channels IS MISSING one of the following unmapped channel voltage status information:"<<std::endl;
780  std::cout<<chan003<<std::endl;
781  MissingChannels=true;
782  }
783  }
784  //Now if any channel WAS missing, exit!
785  if (MissingChannels) {
786  std::cout<<"!!!!\n"<<"Exiting now... please check the local HVUnmappedChannelState.dat and the mapfile you provided ("<<psuDetIdMapFile_<<")"<<std::endl;
787  exit(1);
788  }
789  }
790  else { //If the file HVUnmappedChannelState.dat does not exist, initialize the map to all OFF.
791  //(see below for creating the file at the end of the execution with the latest state of unmapped channels.
792  for (std::map<std::string, vector<uint32_t> >::iterator it=UnmappedPSUs.begin(); it!=UnmappedPSUs.end(); it++) {
793  std::string chan002=it->first+"channel002";
794  std::string chan003=it->first+"channel003";
795  UnmappedState[chan002]=false;
796  UnmappedState[chan003]=false;
797  }
798  }
799  //Get the HVCrosstalking map from the map, so that we can set know which PSU are crosstalking:
800  std::map<std::string,std::vector<uint32_t> > CrosstalkingPSUs=map_.getHVCrosstalkingMap();
801  //Check here if there is a file already, otherwise initialize to OFF all channels in these PSU!
802  if (FileExists("HVCrosstalkingChannelState.dat")) {
803  std::cout<<"File HVCrosstalkingChannelState.dat exists!"<<std::endl;
804  std::ifstream ifs("HVCrosstalkingChannelState.dat");
805  string line;
806  while( getline( ifs, line ) ) {
807  if( line != "" ) {
808  // split the line and insert in the map
809  stringstream ss(line);
810  string PSUChannel;
811  bool HVStatus;
812  ss >> PSUChannel;
813  ss >> HVStatus;
814  //Extract the PSU from the PSUChannel (since the HVCrosstalking_Map uses PSU as key
815  std::string PSU=PSUChannel.substr(0,PSUChannel.size()-10);
816  //Look for the PSU in the unmapped map!
817  std::map<std::string,std::vector<uint32_t> >::iterator iter=CrosstalkingPSUs.find(PSU);
818  if (iter!=CrosstalkingPSUs.end()) {
819  CrosstalkingState[PSUChannel]=HVStatus;
820  }
821  else {
822  std::cout<<"WARNING!!! There are channels in the local file with the channel status for HVUnmapped channels, that ARE NOT CONSIDERED AS UNMAPPED in the current map!"<<std::endl;
823  }
824  }
825  }//End of the while loop reading and initializing CrosstalkingState map from file
826  //Extra check:
827  //Should check if there any HVCrosstalking channels in the map that are not listed in the local file!
828  bool MissingChannels=false;
829  for (std::map<std::string, vector<uint32_t> >::iterator it=CrosstalkingPSUs.begin(); it!=CrosstalkingPSUs.end(); it++) {
830  std::string chan002=it->first+"channel002";
831  std::string chan003=it->first+"channel003";
832  std::map<std::string,bool>::iterator iter=CrosstalkingState.find(chan002);
833  if (iter==CrosstalkingState.end()) {
834  std::cout<<"ERROR! The local file with the channel status for HVCrosstalking channels IS MISSING one of the following unmapped channel voltage status information:"<<std::endl;
835  std::cout<<chan002<<std::endl;
836  MissingChannels=true;
837  }
838  iter=CrosstalkingState.find(chan003);
839  if (iter==CrosstalkingState.end()) {
840  std::cout<<"ERROR! The local file with the channel status for HVCrosstalking channels IS MISSING one of the following unmapped channel voltage status information:"<<std::endl;
841  std::cout<<chan003<<std::endl;
842  MissingChannels=true;
843  }
844  }
845  //Now if any channel WAS missing, exit!
846  if (MissingChannels) {
847  std::cout<<"!!!!\n"<<"Exiting now... please check the local HVCrosstalkingChannelState.dat and the mapfile you provided ("<<psuDetIdMapFile_<<")"<<std::endl;
848  exit(1);
849  }
850  }
851  else { //If the file HVCrosstalkingChannelState.dat does not exist, initialize the map to all OFF.
852  //(see below for creating the file at the end of the execution with the latest state of unmapped channels.
853  for (std::map<std::string, vector<uint32_t> >::iterator it=CrosstalkingPSUs.begin(); it!=CrosstalkingPSUs.end(); it++) {
854  std::string chan002=it->first+"channel002";
855  std::string chan003=it->first+"channel003";
856  CrosstalkingState[chan002]=false;
857  CrosstalkingState[chan003]=false;
858  }
859  }
860 
861  if (debug_) {
862  //print out the UnmappedState map:
863  std::cout<<"Printing the UnmappedChannelState initial map:"<<std::endl;
864  std::cout<<"PSUChannel\t\tHVON?(true or false)"<<std::endl;
865  for (std::map<std::string,bool>::iterator it=UnmappedState.begin(); it!=UnmappedState.end(); it++) {
866  std::cout<<it->first<<"\t\t"<<it->second<<std::endl;
867  }
868  //print out the CrosstalkingState map:
869  std::cout<<"Printing the CrosstalkingChannelState initial map:"<<std::endl;
870  std::cout<<"PSUChannel\t\tHVON?(true or false)"<<std::endl;
871  for (std::map<std::string,bool>::iterator it=CrosstalkingState.begin(); it!=CrosstalkingState.end(); it++) {
872  std::cout<<it->first<<"\t\t"<<it->second<<std::endl;
873  }
874  }
875 
876  //Loop over the psuStruct (DB query results), lopping over the PSUChannels
877  //This will probably change int he future when we will change the query itself
878  //to report directly the detIDs associated with a channel
879  //Probably we will report in the query results the detID, the changeDate
880  //and whether the channel is HV mapped, HV unmapped, HV crosstalking using a flag...
881  for (unsigned int dp = 0; dp < psuStruct.dpname.size(); dp++) {
882  //FIX ME:
883  //Check if the following if condition can EVER be true!
884  std::string PSUChannel=psuStruct.dpname[dp];
885  if (PSUChannel != "UNKNOWN") {
886 
887  // figure out the channel and the PSU individually
888  std::string Channel = PSUChannel.substr(PSUChannel.size()-10); //Channel is the channel, i.e. channel000, channel001 etc
889  std::string PSU = PSUChannel.substr(0,PSUChannel.size()-10);
890 
891  // Get the detIDs corresponding to the given PSU channel using the getDetID function of SiStripPsuDetIdMap.cc
892  //NOTA BENE
893  //Need to make sure the information is treated consistently here:
894  //The map by convention has
895  //detID-> channel002 or channel003 IF the channel is HV mapped,
896  //detID->channel000 if it is not HV mapped
897  //We want to differentiate the behavior depending on the status reported for the channel for channels that are unmapped!
898  //1-if the channel is turning OFF (!=1) then we want to report all detIDs for that channel and all detIDs that are listed as channel000 for that PSU.
899  //2-if the channel is turning ON (==1) then we want to turn on all detIDs for that channel but turn on all detIDs listed as channel000 for that PSU ONLY IF BOTH channel002 and channel003 are BOTH ON!
900  //Need to handle the case of coupled Power supplies (that only turn off when both are turned off).
901 
902  //Fixed SiStripPSUdetidMap.cc to make sure now getDetID gets the correct list of detIDs:
903  //-for channels 000/001 all the detIDs connected to the PSU
904  //-for channels 002/003 HV1/HV2 modules only (exclusively)
905  //UPDATE for HV channels:
906  //actually fixed it to report also detIDs listed as
907  //channel000 on the same supply of channel002 or channel003
908  //and the crosstalking ones (channel999) too..
909 
910  //Get the detIDs associated with the DPNAME (i.e. PSUChannel) reported by the query
911  //Declare the vector to be passed as reference parameters to the getDetID method
912  //std::vector<uint32_t> ids,unmapped_ids,crosstalking_ids;
913  std::vector<uint32_t> ids;
914  //map_.getDetID(PSUChannel, debug_, ids, unmapped_ids, crosstalking_ids);
915  //Actually the method above is a bit of an overkill, we could already use the individual methods:
916  //getLvDetID
917  //getHvDetID
918 
919  //Declaring the two vector needed for the HV case in this scope.
920  std::vector<uint32_t> unmapped_ids,crosstalking_ids;
921  bool LVCase;
922  //LV CASE
923  if (Channel=="channel000" || Channel=="channel001") {
924  LVCase=true;
925  ids=map_.getLvDetID(PSU); //Since in the LV case only 1 list of detids is returned (unmapped and crosstalking are irrelevant for LV) return the vector directly
926  }
927  //HV CASE
928  else { //if (Channel=="channel002" || Channel=="channel003") {
929  LVCase=false;
930  map_.getHvDetID(PSUChannel,ids,unmapped_ids,crosstalking_ids); //In the HV case since 3 vectors are filled, use reference parameters
931  }
932 
933  if ( debug_ ) {
934  cout <<"dpname["<<dp<<"] = "<<PSUChannel<<", for time = "<<timeToStream(psuStruct.changeDate[dp])<<endl;
935  if (!ids.empty()) {
936  if (Channel=="channel000" || Channel=="channel001") {
937  cout << "Corresponding to LV (PSU-)matching detids: "<<endl;
938  for (unsigned int i_detid=0;i_detid<ids.size();i_detid++) {
939  cout<< ids[i_detid] << std::endl;
940  }
941  }
942  else {
943  cout << "Corresponding to straight HV matching detids: "<<endl;
944  for (unsigned int i_detid=0;i_detid<ids.size();i_detid++) {
945  cout<< ids[i_detid] << std::endl;
946  }
947  }
948  }
949  //The unmapped_ids and crosstalking_ids are only filled for HV channels!
950  if (!unmapped_ids.empty()) {
951  cout << "Corresponding to HV unmapped (PSU-)matching detids: "<<endl;
952  for (unsigned int i_detid=0;i_detid<unmapped_ids.size();i_detid++) {
953  cout<< unmapped_ids[i_detid] << std::endl;
954  }
955  }
956  if (!crosstalking_ids.empty()) {
957  cout << "Corresponding to HV crosstalking (PSU-)matching detids: "<<endl;
958  for (unsigned int i_detid=0;i_detid<crosstalking_ids.size();i_detid++) {
959  cout<< crosstalking_ids[i_detid] << std::endl;
960  }
961  }
962  }
963 
964  //NOW implement the new logic using the detids, unmapped_detids, crosstalking_detids!
965 
966  //First check whether the channel we're looking at is turning OFF or turning ON!
967 
968  //TURN OFF case:
969  if (psuStruct.actualStatus[dp] != 1) {
970  //Behavior is different for LV vs HV channels:
971  //LV case:
972  if (LVCase) {
973  //Turn OFF all:
974  //-positively matching
975  //-unmapped matching
976  //-crosstalking
977  //for the LV case all the detids are automatically reported in the ids vector
978  //unmapped and crosstalking are only differentiated (relevant) for HV.
979  if (!ids.empty()) {
980  //debug variables increment
981  ch0bad++;
982  ch1bad++;
983 
984  //Create a pair with the relevant detIDs (vector) and its timestamp
985  //And put it in the detidV vector of the detIdStruct that will contain all the
986  //results
987  detIdStruct.detidV.push_back( std::make_pair(ids,psuStruct.changeDate[dp]) );
988 
989  //Set the status to OFF
990  detIdStruct.StatusGood.push_back(false);
991 
992  //debug variable population
993  numLvBad.insert(numLvBad.end(),ids.begin(),ids.end());
994 
995  //Set the flag for LV/HV:
996  detIdStruct.isHV.push_back(0); //LV
997 
998  //Set the PSUChannel (I guess for debug purposes?)
999  detIdStruct.psuName.push_back( PSUChannel );
1000  }
1001  }
1002  //HV case:
1003  else { //if (!LVCase) {
1004  //Debug variables increment:
1005  if (!ids.empty() || !unmapped_ids.empty() || !crosstalking_ids.empty()) {
1006  if (Channel=="channel002") {
1007  ch2bad++;
1008  }
1009  else if (Channel=="channel003") {
1010  ch3bad++;
1011  }
1012  }
1013  //First sum the ids (positively matching detids) and the unmapped_ids (since both should be TURNED OFF):
1014  std::vector<uint32_t> OFFids;
1015  OFFids.insert(OFFids.end(),ids.begin(),ids.end()); //Add the ids (if any!)
1016  OFFids.insert(OFFids.end(),unmapped_ids.begin(),unmapped_ids.end()); //Add the unmapped_ids (if any!)
1017  //Now for the cross-talking ids this is a bit more complicated!
1018  if (!crosstalking_ids.empty()) {//This already means that the PSUChannel is one of the crosstalking ones (even if only a few modules in that PSU are showing crosstalking behavior both its channels have to be considered crosstalking of course!
1019  //Set the channel OFF in the CrosstalkingState map!
1020  CrosstalkingState[PSUChannel]=false; //Turn OFF the channel in the state map!
1021 
1022  //Need to check if both channels (HV1==channel002 or HV2==channel003) are OFF!
1023  if (!CrosstalkingState[PSUChannel.substr(0,PSUChannel.size()-1)+"2"] && !CrosstalkingState[PSUChannel.substr(0,PSUChannel.size()-1)+"3"]) { //if HV1 & HV2 both OFF (false)
1024  OFFids.insert(OFFids.end(),crosstalking_ids.begin(),crosstalking_ids.end()); //Add the crosstalking_ids (if any!) since both HV1 and HV2 are OFF!
1025  if (debug_) {
1026  std::cout<<"Adding the unmapped detids corresponding to (HV1/2 cross-talking) PSU "<<PSUChannel.substr(0,PSUChannel.size()-10)<<" to the list of detids turning OFF"<<std::endl;
1027  }
1028  }
1029  }
1030  //Handle the crosstalking channel by setting it to OFF in the CrosstalkingState map!
1031  if (!unmapped_ids.empty()) {//This already means that the PSUChannel is one of the unmapped ones (even if only a few modules in that PSU are unmapped both its channels have to be considered crosstalking of course!
1032  UnmappedState[PSUChannel]=false; //Turn OFF the channel in the state map!
1033  }
1034  if (!OFFids.empty()) {
1035  //Create a pair with the relevant detIDs (vector) and its timestamp
1036  //And put it in the detidV vector of the detIdStruct that will contain all the
1037  //results
1038 
1039  //Going OFF HV:
1040  //report not only ids, but also unmapped_ids.
1041  //have to handle crosstalking_ids here... (only OFF if they corresponding PSU HV1/HV2 is off already...
1042  //then add all three vectors to the pair below...
1043  detIdStruct.detidV.push_back( std::make_pair(OFFids,psuStruct.changeDate[dp]) );
1044 
1045  //Set the status to OFF
1046  detIdStruct.StatusGood.push_back(false);
1047 
1048  //debug variable population
1049  numHvBad.insert(numHvBad.end(),ids.begin(),ids.end());
1050 
1051  //Set the flag for LV/HV:
1052  detIdStruct.isHV.push_back(1); //HV
1053 
1054  //Set the PSUChannel (I guess for debug purposes?)
1055  detIdStruct.psuName.push_back( PSUChannel );
1056  }
1057  }
1058  }
1059  //TURNING ON CASE
1060  else {
1061  //Implement the rest of the logic!
1062  //Behavior is different for LV vs HV channels:
1063  //LV case:
1064  if (LVCase) {
1065  //Turn ON all (PSU)matching detids:
1066  //for the LV case all the detids are automatically reported in the ids vector
1067  //unmapped and crosstalking are only differentiated (relevant) for HV.
1068  if (!ids.empty()) {
1069  //Create a pair with the relevant detIDs (vector) and its timestamp
1070  //And put it in the detidV vector of the detIdStruct that will contain all the
1071  //results
1072  detIdStruct.detidV.push_back( std::make_pair(ids,psuStruct.changeDate[dp]) );
1073 
1074  //Set the status to ON
1075  detIdStruct.StatusGood.push_back(true);
1076 
1077  //Set the flag for LV/HV:
1078  detIdStruct.isHV.push_back(0); //LV
1079 
1080  //Set the PSUChannel (I guess for debug purposes?)
1081  detIdStruct.psuName.push_back( PSUChannel );
1082  }
1083  }
1084  //HV case:
1085  else { //if (!LVCase) {
1086  //First sum the ids (positively matching detids) and the crosstalking_ids (since all ids on a crosstalking PSU should be TURNED ON when at least one HV channel is ON):
1087  std::vector<uint32_t> ONids;
1088  ONids.insert(ONids.end(),ids.begin(),ids.end()); //Add the ids (if any!)
1089  ONids.insert(ONids.end(),crosstalking_ids.begin(),crosstalking_ids.end()); //Add the crosstalking_ids (if any!)
1090  //Now for the unmapped ids this is a bit more complicated!
1091  if (!unmapped_ids.empty()) {//This already means that the PSUChannel is one of the unmapped ones (even if only a few modules in that PSU are unmapped both its channels have to be considered unmapped of course!
1092  //Set the HV1 channel on in the UnmappedState map!
1093  UnmappedState[PSUChannel]=true; //Turn ON the channel in the state map!
1094 
1095  //Need to check if BOTH channels (HV1==channel002 or HV2==channel003) are ON!
1096  if (UnmappedState[PSUChannel.substr(0,PSUChannel.size()-1)+"2"] && UnmappedState[PSUChannel.substr(0,PSUChannel.size()-1)+"3"]) { //if HV1 & HV2 are both ON (true)
1097  ONids.insert(ONids.end(),unmapped_ids.begin(),unmapped_ids.end()); //Add the unmapped_ids (if any!) since both HV1 and HV2 are ON!
1098  if (debug_) {
1099  std::cout<<"Adding the detids corresponding to HV-unmapped PSU "<<PSUChannel.substr(0,PSUChannel.size()-10)<<" to the list of detids turning ON"<<std::endl;
1100  }
1101  }
1102  }
1103  //Handle the crosstalking channel by setting it to OFF in the CrosstalkingState map!
1104  if (!crosstalking_ids.empty()) {//This already means that the PSUChannel is one of the crosstalking ones (even if only a few modules in that PSU are showing crosstalking behavior both its channels have to be considered crosstalking of course!
1105  CrosstalkingState[PSUChannel]=true; //Turn ON the channel in the state map!
1106  }
1107  if (!ONids.empty()) {
1108  //Create a pair with the relevant detIDs (vector) and its timestamp
1109  //And put it in the detidV vector of the detIdStruct that will contain all the
1110  //results
1111 
1112  //Going OFF HV:
1113  //report not only ids, but also unmapped_ids.
1114  //have to handle crosstalking_ids here... (only OFF if they corresponding PSU HV1/HV2 is off already...
1115  //then add all three vectors to the pair below...
1116  detIdStruct.detidV.push_back( std::make_pair(ONids,psuStruct.changeDate[dp]) );
1117 
1118  //Set the status to ON
1119  detIdStruct.StatusGood.push_back(true);
1120 
1121  //Set the flag for LV/HV:
1122  detIdStruct.isHV.push_back(1); //HV
1123 
1124  //Set the PSUChannel (I guess for debug purposes?)
1125  detIdStruct.psuName.push_back( PSUChannel );
1126  }
1127  }
1128  }
1129  }//End of if dpname not "UNKNOWN"
1130  else {
1131  //if (debug) {
1132  //std::cout<<"PSU Channel name WAS NOT RECOGNIZED"<<std::endl;
1133  //}
1134  detIdStruct.notMatched++;
1135  }
1136  }//End of the loop over all PSUChannels reported by the DB query.
1137  //At this point we need to (over)write the 2 files that will keep the HVUnmapped and HVCrosstalking channels status:
1138  std::ofstream ofsUnmapped("HVUnmappedChannelState.dat");
1139  for (std::map<std::string,bool>::iterator it=UnmappedState.begin(); it!=UnmappedState.end(); it++) {
1140  ofsUnmapped<<it->first<<"\t"<<it->second<<std::endl;
1141  }
1142  std::ofstream ofsCrosstalking("HVCrosstalkingChannelState.dat");
1143  for (std::map<std::string,bool>::iterator it=CrosstalkingState.begin(); it!=CrosstalkingState.end(); it++) {
1144  ofsCrosstalking<<it->first<<"\t"<<it->second<<std::endl;
1145  }
1146 
1147  removeDuplicates(numLvBad);
1148  removeDuplicates(numHvBad);
1149 
1150 
1151  // useful debugging stuff!
1152  if( debug_ ) {
1153  std::cout << "Number of channels that turned OFF in this O2O interval"<<std::endl;
1154  std::cout << "Channel000 = " << ch0bad << " Channel001 = " << ch1bad << std::endl;
1155  std::cout << "Channel002 = " << ch2bad << " Channel003 = " << ch3bad << std::endl;
1156  std::cout << "Number of LV detIDs that turned OFF in this O2O interval = " << numLvBad.size() << std::endl;
1157  std::cout << "Number of HV detIDs that turned OFF in this O2O interval = " << numHvBad.size() << std::endl;
1158  }
1159 
1160  LogTrace("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::" << __func__ << "]: Number of PSUs retrieved from DB with map information " << detIdStruct.detidV.size();
1161  LogTrace("SiStripDetVOffBuilder") << "[SiStripDetVOffBuilder::" << __func__ << "]: Number of PSUs retrieved from DB with no map information " << detIdStruct.notMatched;
1162 
1163  unsigned int dupCount = 0;
1164  for (unsigned int t = 0; t < numLvBad.size(); t++) {
1165  std::vector<unsigned int>::iterator iter = std::find(numHvBad.begin(),numHvBad.end(),numLvBad[t]);
1166  if (iter != numHvBad.end()) {dupCount++;}
1167  }
1168  if( debug_ ) std::cout << "Number of channels for which LV & HV turned OFF in this O2O interval = " << dupCount << std::endl;
1169 
1170 }
1171 
1172 void SiStripDetVOffBuilder::setPayloadStats(const uint32_t afterV, const uint32_t numAdded, const uint32_t numRemoved)
1173 {
1174  std::vector<uint32_t> pStats(3,0);
1175  pStats.push_back(afterV);
1176  pStats.push_back(numAdded);
1177  pStats.push_back(numRemoved);
1178  payloadStats.push_back(pStats);
1179 }
1180 
1181 pair<int, int> SiStripDetVOffBuilder::extractDetIdVector( const unsigned int i, SiStripDetVOff * modV, DetIdListTimeAndStatus & detIdStruct )
1182 {
1183  // set the LV and HV off flags ready for storing
1184  int lv_off = -1, hv_off = -1;
1185  if (detIdStruct.isHV[i] == 0) {lv_off = !(detIdStruct.StatusGood[i]);}
1186  if (detIdStruct.isHV[i] == 1) {
1187  hv_off = !(detIdStruct.StatusGood[i]);
1188 
1189  // TESTING WITHOUT THE FIX
1190  // -----------------------
1191 
1192  if( psuDetIdMapFile_ == "" ) {
1193  // temporary fix to handle the fact that we don't know which HV channel the detIDs are associated to
1194  if (i > 0) {
1195  std::string iChannel = detIdStruct.psuName[i].substr( (detIdStruct.psuName[i].size()-3) );
1196  std::string iPsu = detIdStruct.psuName[i].substr(0, (detIdStruct.psuName[i].size()-3) );
1197  if (iChannel == "002" || iChannel == "003") {
1198  bool lastStatusOfOtherChannel = true;
1199  for (unsigned int j = 0; j < i; j++) {
1200  std::string jPsu = detIdStruct.psuName[j].substr(0, (detIdStruct.psuName[j].size()-3) );
1201  std::string jChannel = detIdStruct.psuName[j].substr( (detIdStruct.psuName[j].size()-3) );
1202  if (iPsu == jPsu && iChannel != jChannel && (jChannel == "002" || jChannel == "003")) {
1203  if( debug_ ) cout << "psu["<<i<<"] = " << detIdStruct.psuName[i] << " with status = " << detIdStruct.StatusGood[i] << " and psu["<<j<<"] = " << detIdStruct.psuName[j] << " with status " << detIdStruct.StatusGood[j] << endl;
1204  lastStatusOfOtherChannel = detIdStruct.StatusGood[j];
1205  }
1206  }
1207  if (detIdStruct.StatusGood[i] != lastStatusOfOtherChannel) {
1208  if( debug_ ) cout << "turning off hv" << endl;
1209  hv_off = 1;
1210  }
1211  }
1212  }
1213  }
1214 
1215  // -----------------------
1216 
1217  }
1218 
1219  return make_pair(hv_off, lv_off);
1220 }
#define LogDebug(id)
dictionary missing
Definition: combine.py:4
Map map_
SiStripDetVOffBuilder(const edm::ParameterSet &, const edm::ActivityRegistry &)
int i
Definition: DBlmapReader.cc:9
void discardIOVs(std::vector< std::pair< SiStripDetVOff *, cond::Time_t > >::iterator &it, std::vector< std::pair< SiStripDetVOff *, cond::Time_t > >::iterator &initialIt, std::vector< std::pair< SiStripDetVOff *, cond::Time_t > > &resultVec, const bool last, const unsigned int first)
Removes IOVs as dictated by reduction.
std::pair< int, int > extractDetIdVector(const unsigned int i, SiStripDetVOff *modV, DetIdListTimeAndStatus &detIdStruct)
std::map< std::string, std::vector< uint32_t > > getHVCrosstalkingMap()
void printPar(std::stringstream &ss, const std::vector< int > &par)
void buildPSUdetIdMap(TimesAndValues &tStruct, DetIdListTimeAndStatus &dStruct)
#define NULL
Definition: scimark2.h:8
Extension to SiStripConfigDb to map PSU channels to DetIDs using DCU-PSU map and DCU-DetID map...
bool put(const uint32_t DetId, const int HVoff, const int LVoff)
Insert information for a single detId.
std::map< std::string, std::vector< uint32_t > > getHVUnmappedMap()
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:7
std::auto_ptr< SiStripCoralIface > coralInterface
int findSetting(uint32_t id, const coral::TimeStamp &changeDate, const std::vector< uint32_t > &settingID, const std::vector< coral::TimeStamp > &settingDate)
void removeDuplicates(std::vector< uint32_t > &vec)
U second(std::pair< T, U > const &p)
bool FileExists(std::string filename)
unsigned long long Time_t
Definition: Time.h:16
cond::Time_t getCondTime(const coral::TimeStamp &coralTime)
std::vector< coral::TimeStamp > changeDate
void getDetIds(std::vector< uint32_t > &DetIds_) const
int j
Definition: DBlmapReader.cc:9
std::vector< uint32_t > getLvDetID(std::string psu)
void reduction(const uint32_t deltaTmin, const uint32_t maxIOVlength)
An interface class to the PVSS cond DB.
void lastValue(TimesAndValues &tStruct)
void getHvDetID(std::string psuchannel, std::vector< uint32_t > &ids, std::vector< uint32_t > &unmapped_ids, std::vector< uint32_t > &crosstalking_ids)
Time_t from_boost(boost::posix_time::ptime bt)
void readLastValueFromFile(std::vector< uint32_t > &dpIDs, std::vector< float > &vmonValues, std::vector< coral::TimeStamp > &dateChange)
#define LogTrace(id)
cond::Time_t findMostRecentTimeStamp(const std::vector< coral::TimeStamp > &coralDate)
void lastValueFromFile(TimesAndValues &tStruct)
std::vector< int > tmax_par
coral::TimeStamp getCoralTime(cond::Time_t iovTime)
auto dp
Definition: deltaR.h:22
part
Definition: HCALResponse.h:20
void setLastSiStripDetVOff(SiStripDetVOff *lastPayload, cond::Time_t lastTimeStamp)
void BuildMap(const std::string &mapFile, const bool debug)
std::vector< int > tmin_par
std::vector< std::vector< uint32_t > > payloadStats
void setPayloadStats(const uint32_t afterV, const uint32_t numAdded, const uint32_t numRemoved)
void reduce(std::vector< std::pair< SiStripDetVOff *, cond::Time_t > >::iterator &it, std::vector< std::pair< SiStripDetVOff *, cond::Time_t > >::iterator &initialIt, std::vector< std::pair< SiStripDetVOff *, cond::Time_t > > &resultVec, const bool last=false)
Operates the reduction of the fast sequences of ramping up and down of the voltages.
tuple cout
Definition: gather_cfg.py:145
DQMChannel Channel
std::string fullPath() const
Definition: FileInPath.cc:184
std::vector< std::pair< SiStripDetVOff *, cond::Time_t > > modulesOff
void statusChange(cond::Time_t &lastTime, TimesAndValues &tStruct)
std::pair< SiStripDetVOff *, cond::Time_t > lastStoredCondObj
std::string timeToStream(const coral::TimeStamp &coralTime, const string &comment="")
std::vector< int > tset_par
boost::posix_time::ptime to_boost(Time_t iValue)
#define comment(par)
Definition: vmac.h:161
dictionary FileName