CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_4_4_5_patch3/src/CalibFormats/SiPixelObjects/src/PixelCalibConfiguration.cc

Go to the documentation of this file.
00001 //
00002 // This class is a first attempt at writing a configuration
00003 // object that will perform a calibration loop.
00004 //
00005 //
00006 //
00007 
00008 #include "CalibFormats/SiPixelObjects/interface/PixelCalibConfiguration.h"
00009 #include "CalibFormats/SiPixelObjects/interface/PixelTimeFormatter.h"
00010 #include "CalibFormats/SiPixelObjects/interface/PixelDACNames.h"
00011 //#include "PixelUtilities/PixelTestStandUtilities/include/PixelTimer.h"
00012 #include <fstream>
00013 #include <iostream>
00014 #include <ios>
00015 #include <cassert>
00016 #include <cstdlib>
00017 #include <algorithm>
00018 
00019 using namespace pos;
00020 using namespace std;
00021 
00022 #define BPIX
00023 
00024 PixelCalibConfiguration::PixelCalibConfiguration(std::vector< std::vector<std::string> > & tableMat):
00025                                                  PixelCalibBase(), PixelConfigBase("","","") 
00026 {
00027   std::string mthn = "[PixelCalibConfiguration::PixelCalibConfiguration()]\t    " ;
00028   std::map<std::string , int > colM;
00029   std::vector<std::string > colNames;
00044   colNames.push_back("CONFIG_KEY"         );
00045   colNames.push_back("KEY_TYPE"           );
00046   colNames.push_back("KEY_ALIAS"          );
00047   colNames.push_back("VERSION"            );
00048   colNames.push_back("KIND_OF_COND"       );
00049   colNames.push_back("CALIB_TYPE"         );
00050   colNames.push_back("CALIB_OBJ_DATA_FILE");
00051   colNames.push_back("CALIB_OBJ_DATA_CLOB");
00052 
00053   for(unsigned int c = 0 ; c < tableMat[0].size() ; c++)
00054     {
00055       for(unsigned int n=0; n<colNames.size(); n++)
00056         {
00057           if(tableMat[0][c] == colNames[n])
00058             {
00059               colM[colNames[n]] = c;
00060               break;
00061             }
00062         }
00063     }//end for
00064   for(unsigned int n=0; n<colNames.size(); n++)
00065     {
00066       if(colM.find(colNames[n]) == colM.end())
00067         {
00068           std::cerr << mthn << "Couldn't find in the database the column with name " << colNames[n] << std::endl;
00069           assert(0);
00070         }
00071     }
00072 
00073   _bufferData=true; 
00074   
00075   std::istringstream in ;
00076   in.str(tableMat[1][colM["CALIB_OBJ_DATA_CLOB"]]) ;
00077   
00078   std::string tmp;
00079 
00080   in >> tmp;
00081   
00082   if (tmp=="Mode:"){
00083     in >> mode_;
00084     std::cout << __LINE__ << "]\t" << mthn << "mode=" << mode_ << std::endl;
00085     in >>tmp;
00086   } else {
00087     mode_="FEDChannelOffsetPixel";
00088     std::cout << __LINE__ << "]\t" << mthn << "mode not set, is this an old file? "
00089               << std::endl;
00090     assert(0);
00091   }
00092   
00093   singleROC_=false;
00094   
00095   if (tmp=="SingleROC") {
00096     singleROC_=true;
00097     in >> tmp;
00098   }
00099   
00100   // Read in parameters, if any.
00101   if (tmp=="Parameters:") {
00102     in >> tmp;
00103     while (tmp!="Rows:")
00104       {
00105         assert( !in.eof() );
00106         std::string paramName = tmp;
00107         in >> tmp; // tmp contains the parameter value
00108         parameters_[paramName] = tmp;
00109         in >> tmp; // tmp contains the next parameter's name, or "Rows:"
00110       }
00111   }
00112   
00113   assert(tmp=="Rows:");
00114   
00115   in >> tmp;
00116   
00117   std::vector <unsigned int> rows;
00118   while (tmp!="Cols:"){
00119     if (tmp=="|") {
00120       rows_.push_back(rows);
00121       rows.clear();
00122     }
00123     else{
00124       if (tmp!="*"){
00125         rows.push_back(atoi(tmp.c_str()));
00126       }
00127     }
00128     in >> tmp;
00129   }
00130   rows_.push_back(rows);
00131   rows.clear();
00132   
00133   in >> tmp;
00134   
00135   std::vector <unsigned int> cols;
00136   while ((tmp!="VcalLow:")&&(tmp!="VcalHigh:")&&
00137          (tmp!="Vcal:")&&(tmp!="VcalHigh")&&(tmp!="VcalLow")){
00138     if (tmp=="|") {
00139       cols_.push_back(cols);
00140       cols.clear();
00141     }
00142     else{
00143       if (tmp!="*"){
00144         cols.push_back(atoi(tmp.c_str()));
00145       }
00146     }
00147     in >> tmp;
00148   }
00149   cols_.push_back(cols);
00150   cols.clear();
00151   
00152   highVCalRange_=true;
00153   
00154   if (tmp=="VcalLow") {
00155     highVCalRange_=false;
00156     in >> tmp;
00157   }
00158   
00159   if (tmp=="VcalHigh") {
00160     highVCalRange_=true;
00161     in >> tmp;
00162   }
00163   
00164   if (tmp=="VcalLow:") {
00165     highVCalRange_=false;
00166   }
00167   
00168   if ((tmp=="VcalLow:")||(tmp=="VcalHigh:")||(tmp=="Vcal:")){
00169     unsigned int  first,last,step;
00170     in >> first >> last >> step;
00171     unsigned int index=1;
00172     if (dacs_.size()>0) {
00173       index=dacs_.back().index()*dacs_.back().getNPoints();
00174     }
00175     in >> tmp;
00176     bool mix = false;
00177     if ( tmp=="mix" )
00178       {
00179         mix = true;
00180         in >> tmp;
00181       }
00182     PixelDACScanRange dacrange(pos::k_DACName_Vcal,first,last,step,index,mix);
00183     dacs_.push_back(dacrange);
00184   }
00185   else{
00186     
00187     //in >> tmp;
00188     while(tmp=="Scan:"||tmp=="ScanValues:"){
00189       if (tmp=="ScanValues:"){
00190         std::string dacname;
00191         in >> dacname;
00192         vector<unsigned int> values;
00193         int val;  
00194         in >> val;
00195         while (val!=-1) {
00196           values.push_back(val);
00197           in >> val;
00198         }
00199         unsigned int index=1;
00200         if (dacs_.size()>0) {
00201           index=dacs_.back().index()*dacs_.back().getNPoints();
00202         }
00203         PixelDACScanRange dacrange(dacname,values,index,false);
00204         dacs_.push_back(dacrange);
00205         in >> tmp;
00206       }
00207       else {
00208         std::string dacname;
00209         in >> dacname;
00210         unsigned int  first,last,step;
00211         in >> first >> last >> step;
00212         unsigned int index=1;
00213         if (dacs_.size()>0) {
00214           index=dacs_.back().index()*dacs_.back().getNPoints();
00215         }
00216         in >> tmp;
00217         bool mix = false;
00218         if ( tmp=="mix" )
00219           {
00220             mix = true;
00221             in >> tmp;
00222           }
00223         PixelDACScanRange dacrange(dacname,first,last,step,index,mix);
00224         dacs_.push_back(dacrange);
00225       }
00226     }
00227     
00228     while ((tmp=="Set:")||(tmp=="SetRelative:")){
00229       string name;
00230       in >> name;
00231       int val;
00232       in >> val;
00233       unsigned int index=1;
00234       if (dacs_.size()>0) index=dacs_.back().index()*dacs_.back().getNPoints();
00235       PixelDACScanRange dacrange(name,val,val,1,index,false);
00236       if (tmp=="SetRelative:") {
00237         dacrange.setRelative();
00238       }
00239       dacs_.push_back(dacrange);
00240       in >> tmp;
00241     }
00242   }
00243   
00244   assert(tmp=="Repeat:");
00245 
00246   in >> ntrigger_;
00247   
00248   in >> tmp;
00249   
00250   usesROCList_=false;
00251   bool buildROCListNow = false;
00252   if ( tmp=="Rocs:" ) {
00253     buildROCListNow = true;
00254     usesROCList_=true;
00255   }
00256   else { assert(tmp=="ToCalibrate:"); buildROCListNow = false; }
00257   
00258   while (!in.eof())
00259     {
00260       tmp = "";
00261       in >> tmp;
00262       
00263       // added by F.Blekman to be able to deal with POS245 style calib.dat files in CMSSW
00264       // these files use the syntax: 
00265       // Rocs:
00266       // all
00267       
00268       if( tmp=="all" || tmp=="+" || tmp=="-" ){
00269         buildROCListNow=false;
00270       }
00271       // end of addition by F.B.
00272       
00273       if ( tmp=="" ) continue;
00274       rocListInstructions_.push_back(tmp);
00275     }
00276   
00277   rocAndModuleListsBuilt_ = false;
00278   if ( buildROCListNow )
00279     {
00280       std::set<PixelROCName> rocSet;
00281       for(std::vector<std::string>::iterator rocListInstructions_itr = rocListInstructions_.begin(); rocListInstructions_itr != rocListInstructions_.end(); rocListInstructions_itr++)
00282         {
00283           PixelROCName rocname(*rocListInstructions_itr);
00284           rocSet.insert(rocname);
00285         }
00286       buildROCAndModuleListsFromROCSet(rocSet);
00287     }
00288   
00289   objectsDependingOnTheNameTranslationBuilt_ = false;
00290   
00291   // Added by Dario as a temporary patch for Debbie (this will disappear in the future)
00292   calibFileContent_ = in.str() ;
00293   // End of temporary patch
00294   
00295   return;
00296   
00297 }
00298 
00299 
00300 PixelCalibConfiguration::PixelCalibConfiguration(std::string filename):
00301   PixelCalibBase(), PixelConfigBase("","","") {
00302 
00303   std::string mthn = "[PixelCalibConfiguration::PixelCalibConfiguration()]\t    " ;
00304 
00305   _bufferData=true; 
00306   
00307     std::ifstream in(filename.c_str());
00308 
00309     if (!in.good()){
00310         std::cout << __LINE__ << "]\t" << mthn << "Could not open:"<<filename<<std::endl;
00311         assert(0);
00312     }
00313     else {
00314         std::cout << __LINE__ << "]\t" << mthn << "Opened:"<<filename<<std::endl;
00315     }
00316 
00317     std::string tmp;
00318 
00319     in >> tmp;
00320 
00321     if (tmp=="Mode:"){
00322       in >> mode_;
00323       std::cout << __LINE__ << "]\t" << mthn << "PixelCalibConfiguration mode="<<mode_<< std::endl;
00324       in >>tmp;
00325     } else {
00326       mode_="FEDChannelOffsetPixel";
00327       std::cout << __LINE__ << "]\t" << mthn << "PixelCalibConfiguration mode not set, is this an old file? "
00328                 << __LINE__ << "]\t" << std::endl;
00329       assert(0);
00330     }
00331 
00332     singleROC_=false;
00333       
00334     if (tmp=="SingleROC") {
00335       singleROC_=true;
00336       in >> tmp;
00337     }
00338 
00339         // Read in parameters, if any.
00340         if (tmp=="Parameters:") {
00341                 in >> tmp;
00342                 while (tmp!="Rows:")
00343                 {
00344                         assert( !in.eof() );
00345                         std::string paramName = tmp;
00346                         in >> tmp; // tmp contains the parameter value
00347                         parameters_[paramName] = tmp;
00348                         in >> tmp; // tmp contains the next parameter's name, or "Rows:"
00349                 }
00350         }
00351 
00352     assert(tmp=="Rows:");
00353 
00354     in >> tmp;
00355 
00356     std::vector <unsigned int> rows;
00357     while (tmp!="Cols:"){
00358         if (tmp=="|") {
00359             rows_.push_back(rows);
00360             rows.clear();
00361         }
00362         else{
00363           if (tmp!="*"){
00364             rows.push_back(atoi(tmp.c_str()));
00365           }
00366         }
00367         in >> tmp;
00368     }
00369     rows_.push_back(rows);
00370     rows.clear();
00371     
00372     in >> tmp;
00373 
00374     std::vector <unsigned int> cols;
00375     while ((tmp!="VcalLow:")&&(tmp!="VcalHigh:")&&
00376            (tmp!="Vcal:")&&(tmp!="VcalHigh")&&(tmp!="VcalLow")){
00377         if (tmp=="|") {
00378             cols_.push_back(cols);
00379             cols.clear();
00380         }
00381         else{
00382           if (tmp!="*"){
00383             cols.push_back(atoi(tmp.c_str()));
00384           }
00385         }
00386         in >> tmp;
00387     }
00388     cols_.push_back(cols);
00389     cols.clear();
00390 
00391     highVCalRange_=true;
00392 
00393     if (tmp=="VcalLow") {
00394       highVCalRange_=false;
00395       in >> tmp;
00396     }
00397 
00398     if (tmp=="VcalHigh") {
00399       highVCalRange_=true;
00400       in >> tmp;
00401     }
00402 
00403     if (tmp=="VcalLow:") {
00404         highVCalRange_=false;
00405     }
00406 
00407     if ((tmp=="VcalLow:")||(tmp=="VcalHigh:")||(tmp=="Vcal:")){
00408       unsigned int  first,last,step;
00409       in >> first >> last >> step;
00410       unsigned int index=1;
00411       if (dacs_.size()>0) {
00412         index=dacs_.back().index()*dacs_.back().getNPoints();
00413       }
00414       in >> tmp;
00415       bool mix = false;
00416       if ( tmp=="mix" )
00417       {
00418         mix = true;
00419         in >> tmp;
00420       }
00421       PixelDACScanRange dacrange(pos::k_DACName_Vcal,first,last,step,index,mix);
00422       dacs_.push_back(dacrange);
00423     }
00424     else{
00425 
00426       //in >> tmp;
00427       while(tmp=="Scan:"||tmp=="ScanValues:"){
00428         if (tmp=="ScanValues:"){
00429           std::string dacname;
00430           in >> dacname;
00431           vector<unsigned int> values;
00432           int val;  
00433           in >> val;
00434           while (val!=-1) {
00435             values.push_back(val);
00436             in >> val;
00437           }
00438           unsigned int index=1;
00439           if (dacs_.size()>0) {
00440             index=dacs_.back().index()*dacs_.back().getNPoints();
00441           }
00442           PixelDACScanRange dacrange(dacname,values,index,false);
00443           dacs_.push_back(dacrange);
00444           in >> tmp;
00445         }
00446         else {
00447           std::string dacname;
00448           in >> dacname;
00449           unsigned int  first,last,step;
00450           in >> first >> last >> step;
00451           unsigned int index=1;
00452           if (dacs_.size()>0) {
00453             index=dacs_.back().index()*dacs_.back().getNPoints();
00454           }
00455           in >> tmp;
00456           bool mix = false;
00457           if ( tmp=="mix" )
00458             {
00459               mix = true;
00460               in >> tmp;
00461             }
00462           PixelDACScanRange dacrange(dacname,first,last,step,index,mix);
00463           dacs_.push_back(dacrange);
00464         }
00465       }
00466       
00467       while ((tmp=="Set:")||(tmp=="SetRelative:")){
00468         string name;
00469         in >> name;
00470         int val;
00471         in >> val;
00472         unsigned int absval=std::abs(val);
00473         unsigned int index=1;
00474         if (dacs_.size()>0) index=dacs_.back().index()*dacs_.back().getNPoints();
00475         PixelDACScanRange dacrange(name,absval,absval,1,index,false);
00476         if (tmp=="SetRelative:") {
00477           dacrange.setRelative();
00478           if (val<0) {
00479             dacrange.setNegative();
00480           }
00481         }
00482         dacs_.push_back(dacrange);
00483         in >> tmp;
00484       }
00485     }
00486 
00487     assert(tmp=="Repeat:");
00488 
00489     in >> ntrigger_;
00490 
00491     in >> tmp;
00492 
00493     usesROCList_=false;
00494     bool buildROCListNow = false;
00495     if ( tmp=="Rocs:" ) {
00496       buildROCListNow = true;
00497       usesROCList_=true;
00498     }
00499     else { assert(tmp=="ToCalibrate:"); buildROCListNow = false; }
00500 
00501     while (!in.eof())
00502     {
00503        tmp = "";
00504        in >> tmp;
00505 
00506        // added by F.Blekman to be able to deal with POS245 style calib.dat files in CMSSW
00507        // these files use the syntax: 
00508        // Rocs:
00509        // all
00510 
00511        if( tmp=="all" || tmp=="+" || tmp=="-" ){
00512          buildROCListNow=false;
00513        }
00514        // end of addition by F.B.
00515          
00516        if ( tmp=="" ) continue;
00517        rocListInstructions_.push_back(tmp);
00518     }
00519 
00520     in.close();
00521     
00522     rocAndModuleListsBuilt_ = false;
00523     if ( buildROCListNow )
00524     {
00525        std::set<PixelROCName> rocSet;
00526        for(std::vector<std::string>::iterator rocListInstructions_itr = rocListInstructions_.begin(); rocListInstructions_itr != rocListInstructions_.end(); rocListInstructions_itr++)
00527        {
00528           PixelROCName rocname(*rocListInstructions_itr);
00529           rocSet.insert(rocname);
00530        }
00531        buildROCAndModuleListsFromROCSet(rocSet);
00532     }
00533     
00534     objectsDependingOnTheNameTranslationBuilt_ = false;
00535     
00536     // Added by Dario as a temporary patch for Debbie (this will disappear in the future)
00537     std::ifstream inTmp(filename.c_str());
00538     calibFileContent_ = "" ;
00539     while(!inTmp.eof())
00540     {
00541      std::string tmpString ;
00542      getline (inTmp, tmpString);
00543      calibFileContent_ += tmpString + "\n";
00544      //cout << __LINE__ << "]\t" << "[PixelCalibConfiguration::~PixelCalibConfiguration()]\t\t" << calibFileContent_ << endl ;
00545     }
00546     inTmp.close() ;
00547     // End of temporary patch
00548     
00549     return;
00550 
00551 }
00552 
00553 PixelCalibConfiguration::~PixelCalibConfiguration(){}
00554 
00555 void PixelCalibConfiguration::buildROCAndModuleLists(const PixelNameTranslation* translation, const PixelDetectorConfig* detconfig)
00556 {
00557   assert( translation != 0 );
00558   assert( detconfig != 0 );
00559 
00560   if ( rocAndModuleListsBuilt_ )
00561     {
00562       buildObjectsDependingOnTheNameTranslation(translation);
00563       return;
00564     }
00565   
00566   // Build the ROC set from the instructions.
00567   std::set<PixelROCName> rocSet;
00568   bool addNext = true;
00569   const map<PixelROCName, PixelROCStatus>& iroclist=detconfig->getROCsList();
00570   for(std::vector<std::string>::iterator rocListInstructions_itr = rocListInstructions_.begin(); rocListInstructions_itr != rocListInstructions_.end(); rocListInstructions_itr++)
00571         {
00572           std::string instruction = *rocListInstructions_itr;
00573           
00574           if ( instruction == "+" )
00575             {
00576               addNext = true;
00577               continue;
00578                 }
00579           if ( instruction == "-" )
00580             {
00581               addNext = false;
00582               continue;
00583             }
00584                 
00585           if ( instruction == "all" )
00586             {
00587               if ( addNext ) // add all ROCs in the configuration
00588                 {
00589                   const std::vector <PixelModuleName>& moduleList = detconfig->getModuleList();
00590                   for ( std::vector <PixelModuleName>::const_iterator moduleList_itr = moduleList.begin(); moduleList_itr != moduleList.end(); moduleList_itr++ )
00591                     {
00592                       std::vector<PixelROCName> ROCsOnThisModule = translation->getROCsFromModule( *moduleList_itr );
00593                       for ( std::vector<PixelROCName>::const_iterator ROCsOnThisModule_itr = ROCsOnThisModule.begin(); ROCsOnThisModule_itr != ROCsOnThisModule.end(); ROCsOnThisModule_itr++ ) {
00594                         map<PixelROCName, PixelROCStatus>::const_iterator it=
00595                           iroclist.find(*ROCsOnThisModule_itr);
00596                         assert(it!=iroclist.end());
00597                         PixelROCStatus istatus =  it->second;
00598                         if ( !istatus.get(PixelROCStatus::noAnalogSignal) )
00599                           rocSet.insert(*ROCsOnThisModule_itr);
00600                       }
00601                     }
00602                 }
00603               else // remove all ROCs
00604                 {
00605                   rocSet.clear();
00606                 }
00607               addNext = true;
00608               continue;
00609             }
00610                 
00611           // Assume it's a ROC or module name.
00612           PixelModuleName modulename(instruction);
00613           
00614           // Skip if this module (or the module this ROC is on) isn't in the detector config.
00615           if ( !(detconfig->containsModule(modulename)) )
00616             {
00617               addNext = true;
00618               continue;
00619             }
00620           
00621           if ( modulename.modulename() == instruction ) // it's a module
00622             {
00623               std::vector<PixelROCName> ROCsOnThisModule = translation->getROCsFromModule( modulename );
00624               for ( std::vector<PixelROCName>::iterator ROCsOnThisModule_itr = ROCsOnThisModule.begin(); ROCsOnThisModule_itr != ROCsOnThisModule.end(); ROCsOnThisModule_itr++ )
00625                 {
00626                   if ( addNext ) {
00627                     map<PixelROCName, PixelROCStatus>::const_iterator it= iroclist.find(*ROCsOnThisModule_itr);
00628                     assert(it!=iroclist.end());
00629                     PixelROCStatus istatus =  it->second;
00630                     if ( !istatus.get(PixelROCStatus::noAnalogSignal) )  rocSet.insert(*ROCsOnThisModule_itr);
00631                   }
00632                   else           rocSet.erase( *ROCsOnThisModule_itr);
00633                 }
00634               addNext = true;
00635               continue;
00636             }
00637           else // it's a ROC
00638             {
00639               PixelROCName rocname(instruction);
00640               if ( addNext )
00641                 {
00642                   // Only add this ROC if it's in the configuration.
00643                   bool foundIt = false;
00644                   std::list<const PixelROCName*> allROCs = translation->getROCs();
00645                   for ( std::list<const PixelROCName*>::iterator allROCs_itr = allROCs.begin(); allROCs_itr != allROCs.end(); allROCs_itr++ )
00646                     {
00647                       if ( (*(*allROCs_itr)) == rocname )
00648                         {
00649                           foundIt = true;
00650                           break;
00651                         }
00652                     }
00653                   if (foundIt) {
00654                     map<PixelROCName, PixelROCStatus>::const_iterator it= iroclist.find(rocname);
00655                     assert(it!=iroclist.end());
00656                     PixelROCStatus istatus =  it->second;
00657                     if ( !istatus.get(PixelROCStatus::noAnalogSignal) ) rocSet.insert(rocname);
00658                   }
00659                 }
00660               else
00661                 {
00662                   rocSet.erase(rocname);
00663                 }
00664               addNext = true;
00665               continue;
00666             }
00667           
00668           // should never get here
00669           assert(0);
00670         }
00671   // done building ROC set
00672 
00673   buildROCAndModuleListsFromROCSet(rocSet);
00674 
00675   buildObjectsDependingOnTheNameTranslation(translation);
00676        
00677 }
00678 
00679 void PixelCalibConfiguration::buildROCAndModuleListsFromROCSet(const std::set<PixelROCName>& rocSet)
00680 {
00681   assert( !rocAndModuleListsBuilt_ );
00682 
00683   std::string mthn = "[PixelCalibConfiguration::buildROCAndModuleListsFromROCSet()]    " ;
00684   // Build the ROC list from the ROC set.
00685   for (std::set<PixelROCName>::iterator rocSet_itr = rocSet.begin(); 
00686        rocSet_itr != rocSet.end(); 
00687        rocSet_itr++ ) {
00688     rocs_.push_back(*rocSet_itr);
00689   }
00690 
00691   //t.stop();
00692   //cout << "buildROCAndModuleListsFromROCSet 1 time="<<t.tottime()<<endl;
00693   //t.start();
00694 
00695   // Build the module set from the ROC set.
00696   std::map <PixelModuleName,unsigned int> countROC;
00697   for (std::set<PixelROCName>::iterator rocSet_itr = rocSet.begin(); rocSet_itr != rocSet.end(); rocSet_itr++ ){
00698     //t1.start();
00699     PixelModuleName modulename(*rocSet_itr);
00700     //t1.stop();
00701     //t2.start();
00702     modules_.insert( modulename );
00703     countROC[modulename]++;
00704     //t2.stop();
00705   }
00706 
00707   //t.stop();
00708   //cout << "buildROCAndModuleListsFromROCSet 2 time="<<t.tottime()<<endl;
00709   //cout << "buildROCAndModuleListsFromROCSet t1="<<t1.tottime()<<endl;
00710   //cout << "buildROCAndModuleListsFromROCSet t2="<<t2.tottime()<<endl;
00711   //t.start();
00712   
00713   // Test printout.
00714   /*cout << "\nROC list:\n";
00715     for ( std::vector<PixelROCName>::iterator rocs_itr = rocs_.begin(); 
00716     rocs_itr != rocs_.end(); 
00717     rocs_itr++ ){
00718     cout << rocs_itr->rocname() << "\n";
00719     }    cout << "\nModule list:\n";
00720     for ( std::set<PixelModuleName>::iterator modules_itr = modules_.begin(); modules_itr != modules_.end(); modules_itr++ )
00721         {
00722         cout << modules_itr->modulename() << "\n";
00723         }
00724         cout << "\n";*/
00725   
00726   // Determine max ROCs on a module for singleROC mode.
00727   nROC_=1;
00728   if (singleROC_) {
00729     unsigned maxROCs=0;
00730     for (std::map<PixelModuleName,unsigned int>::iterator imodule=countROC.begin();imodule!=countROC.end();++imodule) {
00731       if (imodule->second>maxROCs) maxROCs=imodule->second;
00732     }
00733     nROC_=maxROCs;
00734                 
00735     std::cout << __LINE__ << "]\t" << mthn << "Max ROCs on a module="<<nROC_<<std::endl;
00736   }
00737         
00738   for(unsigned int irocs=0;irocs<rocs_.size();irocs++){
00739     old_irows.push_back(-1);
00740     old_icols.push_back(-1);
00741   }
00742   
00743   rocAndModuleListsBuilt_ = true;
00744 
00745 }
00746 
00747 void PixelCalibConfiguration::buildObjectsDependingOnTheNameTranslation(const PixelNameTranslation* aNameTranslation)
00748 {
00749   assert( !objectsDependingOnTheNameTranslationBuilt_ );
00750   assert( rocAndModuleListsBuilt_ );
00751   assert( aNameTranslation != 0 );
00752   
00753   // Build the channel list.
00754   assert ( channels_.empty() );
00755   for (std::vector<PixelROCName>::const_iterator rocs_itr = rocs_.begin(); rocs_itr != rocs_.end(); ++rocs_itr)
00756     {
00757       channels_.insert( aNameTranslation->getChannelForROC(*rocs_itr) );
00758     }
00759   
00760   // Build the maps from ROC to ROC number.
00761 
00762   assert ( ROCNumberOnChannelAmongThoseCalibrated_.empty() && numROCsCalibratedOnChannel_.empty() );
00763   
00764   std::set<PixelROCName> tempROCs;
00765   
00766   for(std::vector<PixelROCName>::const_iterator it=rocs_.begin();it!=rocs_.end();it++){
00767     tempROCs.insert(*it);
00768   }
00769 
00770 
00771   for ( std::set<PixelChannel>::const_iterator channels_itr = channels_.begin(); 
00772         channels_itr != channels_.end(); 
00773         channels_itr++ ) {
00774 
00775     std::vector<PixelROCName> rocsOnChannel = 
00776       aNameTranslation->getROCsFromChannel(*channels_itr);
00777 
00778     std::set<PixelROCName> foundROCs;
00779 
00780     for ( std::vector<PixelROCName>::const_iterator rocsOnChannel_itr = rocsOnChannel.begin(); 
00781           rocsOnChannel_itr != rocsOnChannel.end(); 
00782           rocsOnChannel_itr++ ) {
00783 
00784       if ( tempROCs.find(*rocsOnChannel_itr) != tempROCs.end() ){
00785         ROCNumberOnChannelAmongThoseCalibrated_[*rocsOnChannel_itr] = foundROCs.size();
00786         foundROCs.insert(*rocsOnChannel_itr);
00787       }
00788     }
00789 
00790     for ( std::set<PixelROCName>::const_iterator foundROCs_itr = foundROCs.begin(); 
00791           foundROCs_itr != foundROCs.end(); 
00792           foundROCs_itr++ ) {
00793       numROCsCalibratedOnChannel_[*foundROCs_itr] = foundROCs.size();
00794     }
00795 
00796   }
00797 
00798   objectsDependingOnTheNameTranslationBuilt_ = true;
00799 }
00800 
00801 unsigned int PixelCalibConfiguration::iScan(std::string dac) const{
00802 
00803   for (unsigned int i=0;i<dacs_.size();i++){
00804     if (dac==dacs_[i].name()) return i;
00805   }
00806 
00807   std::cout << __LINE__ << "]\t[PixelCalibConfiguration::iScan()]\t\t    could not find dac="
00808             << dac <<std::endl; 
00809 
00810   assert(0);
00811 
00812   return 0;
00813 
00814 }
00815 
00816 
00817 
00818 unsigned int PixelCalibConfiguration::scanROC(unsigned int state) const{
00819 
00820   assert(state<nConfigurations());
00821 
00822   unsigned int i_ROC=state/(cols_.size()*rows_.size()*nScanPoints());
00823   
00824   return i_ROC;
00825 }
00826 
00827 
00828 unsigned int PixelCalibConfiguration::scanValue(unsigned int iscan,
00829                                                 unsigned int state,
00830                                                 unsigned int ROCNumber,
00831                                                 unsigned int ROCsOnChannel) const{
00832 
00833     unsigned int i_threshold = scanCounter(iscan, state);
00834 
00835     // Spread the DAC values on the different ROCs uniformly across the scan range.
00836     if ( dacs_[iscan].mixValuesAcrossROCs() ) i_threshold = (i_threshold + (nScanPoints(iscan)*ROCNumber)/ROCsOnChannel)%nScanPoints(iscan);
00837 
00838     unsigned int threshold=dacs_[iscan].value(i_threshold);
00839     
00840     //assert(threshold==dacs_[iscan].first()+i_threshold*dacs_[iscan].step());
00841 
00842     return threshold;
00843 
00844 }
00845 
00846 bool PixelCalibConfiguration::scanningROCForState(PixelROCName roc, unsigned int state) const
00847 {
00848         if (!singleROC_) return true;
00849         return scanROC(state) == ROCNumberOnChannelAmongThoseCalibrated(roc);
00850 }
00851 
00852 unsigned int PixelCalibConfiguration::scanValue(unsigned int iscan,
00853                                                 unsigned int state,
00854                                                 PixelROCName roc) const {
00855 
00856         unsigned int ROCNumber = ROCNumberOnChannelAmongThoseCalibrated(roc);
00857         unsigned int ROCsOnChannel = numROCsCalibratedOnChannel(roc);
00858         
00859         return scanValue( iscan, state, ROCNumber, ROCsOnChannel );
00860 }
00861 
00862 unsigned int PixelCalibConfiguration::ROCNumberOnChannelAmongThoseCalibrated(PixelROCName roc) const
00863 {
00864         assert( objectsDependingOnTheNameTranslationBuilt_ );
00865         std::map <PixelROCName, unsigned int>::const_iterator foundROC = ROCNumberOnChannelAmongThoseCalibrated_.find(roc);
00866         assert( foundROC != ROCNumberOnChannelAmongThoseCalibrated_.end() );
00867         return foundROC->second;
00868 }
00869 
00870 unsigned int PixelCalibConfiguration::numROCsCalibratedOnChannel(PixelROCName roc) const
00871 {
00872         assert( objectsDependingOnTheNameTranslationBuilt_ );
00873         std::map <PixelROCName, unsigned int>::const_iterator foundROC = numROCsCalibratedOnChannel_.find(roc);
00874         assert( foundROC != numROCsCalibratedOnChannel_.end() );
00875         return foundROC->second;
00876 }
00877 
00878 unsigned int PixelCalibConfiguration::scanCounter(unsigned int iscan,
00879                                                  unsigned int state) const{
00880 
00881 
00882     assert(state<nConfigurations());
00883 
00884     unsigned int i_scan=state%nScanPoints();
00885 
00886     for(unsigned int i=0;i<iscan;i++){
00887       i_scan/=nScanPoints(i);
00888     }
00889 
00890     unsigned int i_threshold=i_scan%nScanPoints(iscan);
00891 
00892     return i_threshold;
00893 
00894 }
00895 
00896 unsigned int PixelCalibConfiguration::rowCounter(unsigned int state) const
00897 {
00898         unsigned int i_row=( state - scanROC(state)*cols_.size()*rows_.size()*nScanPoints() )/( cols_.size()*nScanPoints() );
00899         assert(i_row<rows_.size());
00900         return i_row;
00901 }
00902 
00903 unsigned int PixelCalibConfiguration::colCounter(unsigned int state) const
00904 {
00905         unsigned int i_col=( state - scanROC(state)*cols_.size()*rows_.size()*nScanPoints() - rowCounter(state)*cols_.size()*nScanPoints() )/(nScanPoints());
00906         assert(i_col<cols_.size());
00907         return i_col;
00908 }
00909 
00910 void PixelCalibConfiguration::nextFECState(std::map<unsigned int, PixelFECConfigInterface*>& pixelFECs,
00911                                            PixelDetectorConfig* detconfig,
00912                                            PixelNameTranslation* trans,
00913                                            std::map<pos::PixelModuleName,pos::PixelMaskBase*>* masks,
00914                                            std::map<pos::PixelModuleName,pos::PixelTrimBase*>* trims,
00915                                            std::map<pos::PixelModuleName,pos::PixelDACSettings*>* dacs,
00916 
00917                                            unsigned int state) const {
00918 
00919   std::string mthn = "[PixelCalibConfiguration::nextFECState()]\t\t    " ;
00920   std::string modeName=parameterValue("ScanMode");
00921 
00922   int mode=-1;
00923 
00924   if (modeName=="maskAllPixel")  mode=0;
00925   if (modeName=="useAllPixel"||modeName=="")  mode=1;
00926   if (modeName=="default")  mode=2;
00927 
00928   static bool first=true;
00929 
00930   if (first) {
00931     cout << __LINE__ << "]\t" << mthn << "mode="<<mode<<endl;
00932     first=false;
00933   }
00934   
00935   if (mode==-1) {
00936     cout << __LINE__ << "]\t" << mthn << "ScanMode=" << modeName
00937          << " not understood."<< endl;
00938     ::abort();
00939   }
00940 
00941   if (rocInfo_.size()==0){
00942     //here we will do some initialization...
00943     for(unsigned int i=0;i<rocs_.size();i++){
00944       const PixelHdwAddress* hdwadd=trans->getHdwAddress(rocs_[i]);
00945       PixelROCInfo rocInfo;
00946       rocInfo.use_=true;
00947       //FIXME This is very inefficient
00948       PixelModuleName module(rocs_[i].rocname());
00949 
00950       std::map<pos::PixelModuleName,pos::PixelMaskBase*>::const_iterator foundMask = masks->find(module);
00951       if (foundMask==masks->end()){
00952         rocInfo.use_=false;
00953         rocInfo_.push_back(rocInfo);
00954         continue;
00955       }
00956       
00957 
00958 
00959       rocInfo.hdwadd_=hdwadd;
00960       rocInfo.trims_=(*trims)[module]->getTrimBits(rocs_[i]);
00961       rocInfo.masks_=(*masks)[module]->getMaskBits(rocs_[i]);
00962 
00963 #ifdef BPIX      
00964       const PixelChannel channel = trans->getChannelForROC(rocs_[i]);
00965       string tbmChannel = channel.TBMChannelString();
00966       //cout<<" tbm channel "<<tbmChannel<<endl; 
00967       rocInfo.tbmChannel_ = tbmChannel;
00968 #endif
00969 
00970       std::map<std::string, unsigned int> defaultDACValues;
00971       (*dacs)[PixelModuleName(rocs_[i].rocname())]->getDACSettings(rocs_[i])->getDACs(defaultDACValues);
00972 
00973       for ( std::vector<PixelDACScanRange>::const_iterator dacs_itr = dacs_.begin(); dacs_itr != dacs_.end(); dacs_itr++ )
00974       {
00975         std::map<std::string, unsigned int>::const_iterator foundThisDAC = defaultDACValues.find(dacs_itr->name());
00976         assert( foundThisDAC != defaultDACValues.end() );
00977 
00978         pair<unsigned int, unsigned int> 
00979           dacchannelAndValue(dacs_itr->dacchannel(),
00980                              foundThisDAC->second);
00981 
00982         rocInfo.defaultDACs_.push_back(dacchannelAndValue);
00983       }
00984       rocInfo_.push_back(rocInfo);
00985     }
00986   }
00987 
00988   assert(rocs_.size()==rocInfo_.size());
00989 
00990   bool changedWBC=false;
00991 
00992   std::map<unsigned int, PixelFECConfigInterface*>::iterator iPixelFEC=pixelFECs.begin();
00993   //for(;iPixelFEC!=pixelFECs.end();++iPixelFEC){
00994   //iPixelFEC->second->fecDebug(1);
00995   //}
00996 
00997   //unsigned long version=0;
00998   //pixelFEC->getversion(&version);
00999   //std::cout<<"mfec firmware version:"<<version<<std::endl;
01000 
01001   assert(rocAndModuleListsBuilt_);
01002     
01003   assert(state<nConfigurations());
01004 
01005   // Which set of rows we're on.
01006   unsigned int i_row=rowCounter(state);
01007 
01008   // Which set of columns we're on.
01009   unsigned int i_col=colCounter(state);
01010 
01011   // Whether we're beginning a new scan over the DACs after changing which ROC or which pixel pattern.
01012   unsigned int first_scan=true;
01013   for (unsigned int i=0;i<dacs_.size();i++){
01014     if (scanCounter(i,state)!=0) first_scan=false;
01015   }
01016 
01017   // Disable all pixels at the beginning.
01018   if (state==0&&(mode==0||mode==1)) {
01019 
01020     for(unsigned int i=0;i<rocs_.size();i++){
01021 
01022       if (!rocInfo_[i].use_) continue;
01023 
01024       PixelHdwAddress theROC=*rocInfo_[i].hdwadd_;
01025       PixelROCTrimBits* rocTrims=rocInfo_[i].trims_;
01026 
01027       //Turn off all pixels
01028       disablePixels(pixelFECs[theROC.fecnumber()], rocTrims, theROC);
01029 
01030     }
01031 
01032     // reset
01033     //cout<<"finish init"<<endl;
01034     //sleep(1);
01035     //pixelFEC->injectrstroc(7,1);
01036     // or do    pixelFEC->rocreset(theROC.mfec(),
01037     //                 theROC.mfecchannel(),
01038     //                 14,                    //FIXME hardcode for Channel A
01039     //                 theROC.hubaddress());
01040 
01041    
01042   }
01043 
01044   // When a scan is complete for a given ROC or pixel pattern, reset the DACs to default values and disable the previously-enabled pixels.
01045   if (first_scan && state!=0 && mode!=2){
01046 
01047     unsigned int previousState=state-1;
01048 
01049     unsigned int i_row_previous=rowCounter(previousState);
01050 
01051     unsigned int i_col_previous=colCounter(previousState);
01052 
01053     for(unsigned int i=0;i<rocs_.size();i++){
01054 
01055       if (!rocInfo_[i].use_) continue;
01056 
01057       PixelHdwAddress theROC=*rocInfo_[i].hdwadd_;
01058 
01059       if ( !scanningROCForState(rocs_[i], previousState) ) continue;
01060 
01061       // Set the DACs back to their default values when we're done with a scan.
01062       for ( unsigned int j=0; j< dacs_.size(); j++ ) {
01063 
01064 
01065         //Try to not reprogram DACs as often..
01066         if (state!=0){
01067           if (scanCounter(dacs_[j].name(),state)==scanCounter(dacs_[j].name(),state-1)){
01068             continue;
01069           }
01070         }
01071 
01072         pixelFECs[theROC.fecnumber()]->progdac(theROC.mfec(),
01073                                                theROC.mfecchannel(),
01074                                                theROC.hubaddress(),
01075                                                theROC.portaddress(),
01076                                                theROC.rocid(),
01077                                                rocInfo_[i].defaultDACs_[j].first,
01078                                                rocInfo_[i].defaultDACs_[j].second,
01079                                                _bufferData);    
01080 
01081         if (dacs_[j].dacchannel()==k_DACAddress_WBC) {
01082           changedWBC=true;
01083           //cout << "Changed WBC 1"<<endl;
01084         }
01085 
01086       }
01087       
01088       PixelROCTrimBits* rocTrims=rocInfo_[i].trims_;
01089 
01090       disablePixels(pixelFECs[theROC.fecnumber()], 
01091                     i_row_previous, 
01092                     i_col_previous, 
01093                     rocTrims, 
01094                     theROC);
01095 
01096     }
01097   }
01098   
01099   // Set each ROC with the new settings for this state.
01100   for(unsigned int i=0;i<rocs_.size();i++){
01101 
01102     if (!rocInfo_[i].use_) continue;
01103 
01104 
01105     PixelHdwAddress theROC=*rocInfo_[i].hdwadd_;
01106 
01107     
01108     // Skip this ROC if we're in SingleROC mode and we're not on this ROC number.
01109     if ( !scanningROCForState(rocs_[i], state) ) continue;
01110 
01111     //  std::cout << "Will call progdac for vcal:"<< vcal << std::endl;
01112     
01113     // Program all the DAC values.
01114     for (unsigned int ii=0;ii<dacs_.size();ii++){
01115 
01116       //Try to not reprogram DACs as often..
01117       if (state!=0){
01118         if (scanCounter(dacs_[ii].name(),state)==scanCounter(dacs_[ii].name(),state-1)){
01119           continue;
01120         }
01121       }
01122 
01123       int dacvalue = scanValue(ii, state, rocs_[i]);
01124 
01125       //cout << "dacname ii:"<<dacs_[ii].name()<<" "<<ii<<endl;
01126       
01127       if (dacs_[ii].relative()){
01128 
01129         //We have to find the default DAC setting so that we can
01130         //add the offset as we are in relative mode.
01131 
01132         if (dacs_[ii].negative()) dacvalue=-dacvalue;
01133         
01134         dacvalue+=rocInfo_[i].defaultDACs_[ii].second;
01135         //cout << "[PixelCalibConfiguration::nextFECState] ROC="<<rocs_[i]
01136         //     << " dac="<<dacs_[ii].name()<<" new value="<<dacvalue<<endl;
01137       }
01138 
01139       pixelFECs[theROC.fecnumber()]->progdac(theROC.mfec(),
01140                                              theROC.mfecchannel(),
01141                                              theROC.hubaddress(),
01142                                              theROC.portaddress(),
01143                                              theROC.rocid(),
01144                                              rocInfo_[i].defaultDACs_[ii].first,
01145                                              dacvalue,_bufferData);
01146 
01147       if (dacs_[ii].dacchannel()==k_DACAddress_WBC) {
01148         changedWBC=true;
01149         //cout << "Changed WBC 2"<<endl;
01150       }
01151 
01152     }
01153 
01154     // At the beginning of a scan, set the pixel pattern.
01155     if (first_scan){
01156 
01157       // Set masks and trims.
01158       if (mode!=2){
01159 
01160 
01161         PixelROCMaskBits* rocMasks=rocInfo_[i].masks_;
01162         PixelROCTrimBits* rocTrims=rocInfo_[i].trims_;
01163 
01164         if (mode==1) rocMasks=0;
01165 
01166         //std::cout << "Will enable pixels!" <<std::endl;
01167         enablePixels(pixelFECs[theROC.fecnumber()], 
01168                      i_row, 
01169                      i_col, 
01170                      rocMasks, 
01171                      rocTrims, 
01172                      theROC);
01173 
01174       }
01175 
01176       // Set high or low Vcal range.
01177 
01178       if (state==0) {
01179 
01180         PixelModuleName module(rocs_[i].rocname());
01181 
01182         unsigned int roccontrolword=(*dacs)[module]->getDACSettings(rocs_[i])->getControlRegister();
01183    
01184         //range is controlled here by one bit, but rest must match config
01185         //bit 0 on/off= 20/40 MHz speed; bit 1 on/off=disabled/enable; bit 3=Vcal range
01186 
01187         if (highVCalRange_) roccontrolword|=0x4;  //turn range bit on
01188         else roccontrolword&=0xfb;                //turn range bit off
01189       
01190         pixelFECs[theROC.fecnumber()]->progdac(theROC.mfec(),
01191                                                theROC.mfecchannel(),
01192                                                theROC.hubaddress(),
01193                                                theROC.portaddress(),
01194                                                theROC.rocid(),
01195                                                0xfd,
01196                                                roccontrolword,_bufferData);
01197         
01198 
01199       }      
01200 
01201       // Clear all pixels before setting the pixel pattern.
01202       pixelFECs[theROC.fecnumber()]->clrcal(theROC.mfec(),
01203                                             theROC.mfecchannel(),
01204                                             theROC.hubaddress(),
01205                                             theROC.portaddress(),
01206                                             theROC.rocid(),_bufferData);
01207 
01208       // Program the pixel pattern.
01209       unsigned int nrow=rows_[i_row].size();
01210       unsigned int ncol=cols_[i_col].size();
01211       unsigned int nmax=std::max(nrow,ncol);
01212       if (nrow==0||ncol==0) nmax=0;
01213       for (unsigned int n=0;n<nmax;n++){
01214         unsigned int irow=n;
01215         unsigned int icol=n;
01216         if (irow>=nrow) irow=nrow-1;
01217         if (icol>=ncol) icol=ncol-1;
01218         unsigned int row=rows_[i_row][irow];
01219         unsigned int col=cols_[i_col][icol];
01220 
01221         pixelFECs[theROC.fecnumber()]->calpix(theROC.mfec(),
01222                                               theROC.mfecchannel(),
01223                                               theROC.hubaddress(),
01224                                               theROC.portaddress(),
01225                                               theROC.rocid(),
01226                                               col,
01227                                               row,
01228                                               1,_bufferData);
01229       }
01230       
01231     } // end of instructions for the beginning of a scan
01232   } // end of loop over ROCs
01233 
01234   if (_bufferData) {
01235     std::map<unsigned int, PixelFECConfigInterface*>::iterator iPixelFEC=pixelFECs.begin();
01236     for(;iPixelFEC!=pixelFECs.end();++iPixelFEC){
01237       iPixelFEC->second->qbufsend();
01238     }
01239   }
01240   
01241   if (changedWBC){
01242     for(unsigned int i=0;i<rocs_.size();i++){
01243 
01244       if (!rocInfo_[i].use_) continue;
01245       
01246       PixelHdwAddress theROC=*rocInfo_[i].hdwadd_;
01247       
01248       int tbmRegister = 14;  // define for TBM-A
01249 #ifdef BPIX
01250       string tbmChannel = rocInfo_[i].tbmChannel_; // get TBM channel
01251       if( tbmChannel=="B") tbmRegister = 15;  // for TBM=B
01252 #endif     
01253 
01254       pixelFECs[theROC.fecnumber()]->rocreset(theROC.mfec(),
01255                          theROC.mfecchannel(),
01256                          tbmRegister, 
01257                          theROC.hubaddress());
01258     } // for rocs
01259   }
01260 
01261   return;
01262 } 
01263 
01264 // FIXME This code breaks if it is called more than once with different crate numbers!
01265 std::vector<std::pair<unsigned int, std::vector<unsigned int> > >& PixelCalibConfiguration::fedCardsAndChannels(unsigned int crate,
01266                                                                                                                 PixelNameTranslation* translation,
01267                                                                                                                 PixelFEDConfig* fedconfig,
01268                                                                                                                 PixelDetectorConfig* detconfig) const{
01269 
01270     assert(rocAndModuleListsBuilt_);
01271     
01272     assert(rocs_.size()!=0);
01273 
01274     for(unsigned int i=0;i<rocs_.size();i++){
01275       PixelModuleName module(rocs_[i].rocname());
01276       if (!detconfig->containsModule(module)) continue;
01277       const PixelHdwAddress* hdw=translation->getHdwAddress(rocs_[i]);
01278         assert(hdw!=0);
01279         //std::cout << "ROC, fednumber:"<<rocs_[i]<<" "<<hdw->fednumber()
01280         //        << std::endl;
01281         //first check if fed associated with the roc is in the right crate
01282         if (fedconfig->crateFromFEDNumber(hdw->fednumber())!=crate) continue;
01283         //next look if we have already found fed number
01284         unsigned int index=fedCardsAndChannels_.size();
01285         for(unsigned int j=0;j<fedCardsAndChannels_.size();j++){
01286             if (fedCardsAndChannels_[j].first==hdw->fednumber()){
01287                 index=j;
01288                 break;
01289             }
01290         }
01291         //If we didn't find the fedcard we will create it
01292         if (index==fedCardsAndChannels_.size()){
01293             std::vector<unsigned int> tmp;
01294             tmp.push_back(hdw->fedchannel());
01295             std::pair<unsigned int, std::vector<unsigned int> > tmp2(hdw->fednumber(),tmp);
01296             fedCardsAndChannels_.push_back(tmp2);
01297             continue;
01298         }
01299         //Now look and see if the channel has been added
01300         std::vector<unsigned int>& channels=fedCardsAndChannels_[index].second;
01301         bool found=false;
01302         for(unsigned int k=0;k<channels.size();k++){
01303             if (channels[k]==hdw->fedchannel()) {
01304                 found=true;
01305                 break;
01306             }
01307         }
01308         if (found) continue;
01309         channels.push_back(hdw->fedchannel());
01310 
01311     }
01312 
01313 
01314     return fedCardsAndChannels_;
01315 
01316 }
01317 
01318 std::map <unsigned int, std::set<unsigned int> > PixelCalibConfiguration::getFEDsAndChannels (PixelNameTranslation *translation) {
01319 
01320   assert(rocAndModuleListsBuilt_);
01321   
01322   std::map <unsigned int, std::set<unsigned int> > fedsChannels;
01323   assert(rocs_.size()!=0);
01324   std::vector<PixelROCName>::iterator iroc=rocs_.begin();
01325 
01326   for (;iroc!=rocs_.end();++iroc){
01327     const PixelHdwAddress *roc_hdwaddress=translation->getHdwAddress(*iroc);
01328     unsigned int fednumber=roc_hdwaddress->fednumber();
01329     unsigned int fedchannel=roc_hdwaddress->fedchannel();
01330     fedsChannels[fednumber].insert(fedchannel);
01331   }
01332 
01333   return fedsChannels;
01334 }
01335 
01336 std::set <unsigned int> PixelCalibConfiguration::getFEDCrates(const PixelNameTranslation* translation, const PixelFEDConfig* fedconfig) const{
01337 
01338         assert(rocAndModuleListsBuilt_);
01339         
01340         std::set<unsigned int> fedcrates;
01341         assert(modules_.size()!=0);
01342         std::set<PixelModuleName>::iterator imodule=modules_.begin();
01343 
01344         for (;imodule!=modules_.end();++imodule)
01345         {
01346                 std::set<PixelChannel> channelsOnThisModule = translation->getChannelsOnModule(*imodule);
01347                 for ( std::set<PixelChannel>::const_iterator channelsOnThisModule_itr = channelsOnThisModule.begin(); channelsOnThisModule_itr != channelsOnThisModule.end(); channelsOnThisModule_itr++ )
01348                 {
01349                         const PixelHdwAddress& channel_hdwaddress = translation->getHdwAddress(*channelsOnThisModule_itr);
01350                         unsigned int fednumber=channel_hdwaddress.fednumber();
01351                         fedcrates.insert(fedconfig->crateFromFEDNumber(fednumber));
01352                 }
01353         }
01354 
01355         return fedcrates;
01356 }
01357 
01358 std::set <unsigned int> PixelCalibConfiguration::getFECCrates(const PixelNameTranslation* translation, const PixelFECConfig* fecconfig) const{
01359 
01360         assert(rocAndModuleListsBuilt_);
01361         
01362         std::set<unsigned int> feccrates;
01363         assert(modules_.size()!=0);
01364         std::set<PixelModuleName>::iterator imodule=modules_.begin();
01365 
01366         for (;imodule!=modules_.end();++imodule)
01367         {
01368                 std::set<PixelChannel> channelsOnThisModule = translation->getChannelsOnModule(*imodule);
01369                 for ( std::set<PixelChannel>::const_iterator channelsOnThisModule_itr = channelsOnThisModule.begin(); channelsOnThisModule_itr != channelsOnThisModule.end(); channelsOnThisModule_itr++ )
01370                 {
01371                         const PixelHdwAddress& channel_hdwaddress = translation->getHdwAddress(*channelsOnThisModule_itr);
01372                         unsigned int fecnumber=channel_hdwaddress.fecnumber();
01373                         feccrates.insert(fecconfig->crateFromFECNumber(fecnumber));
01374                 }
01375         }
01376 
01377         return feccrates;
01378 }
01379 
01380 std::set <unsigned int> PixelCalibConfiguration::getTKFECCrates(const PixelPortcardMap *portcardmap, const std::map<std::string,PixelPortCardConfig*>& mapNamePortCard, const PixelTKFECConfig* tkfecconfig) const{
01381 
01382         assert(rocAndModuleListsBuilt_);
01383         
01384         std::set<unsigned int> tkfeccrates;
01385         assert(modules_.size()!=0);
01386         std::set<PixelModuleName>::iterator imodule=modules_.begin();
01387 
01388         for (;imodule!=modules_.end();++imodule)
01389         {
01390                 // implement this by module --(PixelPortcardMap)-> port card(s) --(PixelPortCardConfig)-> FEC # --(PixelFECConfig theTKFECConfiguration_)-> crate
01391                 const std::set< std::string > portCards = portcardmap->portcards(*imodule);
01392                 for ( std::set< std::string >::const_iterator portCards_itr = portCards.begin(); portCards_itr != portCards.end(); ++portCards_itr)
01393                 {
01394                         const std::string portcardname=*portCards_itr;
01395                         std::map<std::string,PixelPortCardConfig*>::const_iterator portcardconfig_itr = mapNamePortCard.find(portcardname);
01396                         assert(portcardconfig_itr != mapNamePortCard.end());
01397                         PixelPortCardConfig* portcardconfig = portcardconfig_itr->second;
01398                         std::string TKFECID = portcardconfig->getTKFECID();
01399                         tkfeccrates.insert(tkfecconfig->crateFromTKFECID(TKFECID));
01400                 }
01401         }
01402 
01403         return tkfeccrates;
01404 }
01405 
01406 std::ostream& pos::operator<<(std::ostream& s, const PixelCalibConfiguration& calib){
01407      if (!calib.parameters_.empty())
01408     {
01409        s<< "Parameters:"<<std::endl;
01410        for ( std::map<std::string, std::string>::const_iterator paramItr = calib.parameters_.begin(); paramItr != calib.parameters_.end(); ++paramItr )
01411        {
01412           s<< paramItr->first << " " << paramItr->second << std::endl;
01413        }
01414     }
01415     
01416     s<< "Rows:"<<std::endl;
01417     for (unsigned int i=0;i<calib.rows_.size();i++){
01418         for (unsigned int j=0;j<calib.rows_[i].size();j++){
01419             s<<calib.rows_[i][j]<<" "<<std::endl;
01420         }
01421         s<< "|"<<std::endl;
01422     }
01423 
01424     s<< "Cols:"<<std::endl;
01425     for (unsigned int i=0;i<calib.cols_.size();i++){
01426         for (unsigned int j=0;j<calib.cols_[i].size();j++){
01427           s<<calib.cols_[i][j]<<" "<<std::endl;
01428         }
01429         s<< "|"<<std::endl;
01430     }
01431 
01432     s << "Vcal:"<<std::endl;
01433 
01434     //s << calib.vcal_<<std::endl;
01435 
01436     s << "Vcthr:"<<std::endl;
01437 
01438     s << calib.dacs_[0].first() << " " << calib.dacs_[0].last() 
01439       << " "<< calib.dacs_[0].step()<<std::endl;
01440 
01441     s << "CalDel:"<<std::endl;
01442 
01443     s << calib.dacs_[1].first() << " " << calib.dacs_[0].last() 
01444       << " "<< calib.dacs_[1].step()<<std::endl;
01445 
01446     s << "Repeat:"<<std::endl;
01447     
01448     s << calib.ntrigger_<<std::endl;
01449 
01450     return s;
01451 
01452 }
01453 
01454 
01455 void PixelCalibConfiguration::enablePixels(PixelFECConfigInterface* pixelFEC,
01456                                            unsigned int irows, 
01457                                            unsigned int icols,
01458                                            pos::PixelROCMaskBits* masks,
01459                                            pos::PixelROCTrimBits* trims, 
01460                                            PixelHdwAddress theROC) const{
01461 
01462   for (unsigned int irow=0;irow<rows_[irows].size();irow++){
01463     for (unsigned int icol=0;icol<cols_[icols].size();icol++){
01464       /*            std::cout << "Will turn on pixel col="
01465                     <<cols_[icols][icol]
01466                     <<" row="<<rows_[irows][irow]<<std::endl;
01467       */
01468       unsigned int bits=trims->trim(cols_[icols][icol],rows_[irows][irow]);
01469 
01470       //if masks==0 always enable pixel
01471       if (masks==0||
01472           masks->mask(cols_[icols][icol],rows_[irows][irow])) bits|=0x80;
01473 
01474       pixelFEC->progpix(theROC.mfec(),
01475                         theROC.mfecchannel(),
01476                         theROC.hubaddress(),
01477                         theROC.portaddress(),
01478                         theROC.rocid(),
01479                         cols_[icols][icol],
01480                         rows_[irows][irow],
01481                         bits,_bufferData);
01482     }
01483   }  
01484 }
01485 
01486 void PixelCalibConfiguration::disablePixels(PixelFECConfigInterface* pixelFEC,
01487                               unsigned int irows, unsigned int icols,
01488                               pos::PixelROCTrimBits* trims, 
01489                               PixelHdwAddress theROC) const{
01490 
01491         for (unsigned int irow=0;irow<rows_[irows].size();irow++){
01492             for (unsigned int icol=0;icol<cols_[icols].size();icol++){
01493               /*                std::cout << "Will turn off pixel col="
01494                           <<cols_[old_icols][icol]
01495                           <<" row="<<rows_[old_irows][irow]<<std::endl;
01496               */
01497               unsigned int bits=trims->trim(cols_[icols][icol],rows_[irows][irow]);
01498               pixelFEC->progpix(theROC.mfec(),
01499                                 theROC.mfecchannel(),
01500                                 theROC.hubaddress(),
01501                                 theROC.portaddress(),
01502                                 theROC.rocid(),
01503                                 cols_[icols][icol],
01504                                 rows_[irows][irow],
01505                                 bits,_bufferData);
01506             }
01507         }
01508 }
01509 
01510 
01511 void PixelCalibConfiguration::disablePixels(PixelFECConfigInterface* pixelFEC,
01512                                             pos::PixelROCTrimBits* trims, 
01513                                             PixelHdwAddress theROC) const{
01514 
01515   //cout<<" disable ROC "<<theROC.hubaddress()<<" "<<theROC.rocid()<<endl;
01516   //FIXME This should be done with more efficient commands!
01517   for (unsigned int row=0;row<80;row++){
01518     for (unsigned int col=0;col<52;col++){
01519       unsigned int bits=trims->trim(col,row);
01520       pixelFEC->progpix(theROC.mfec(),
01521                         theROC.mfecchannel(),
01522                         theROC.hubaddress(),
01523                         theROC.portaddress(),
01524                         theROC.rocid(),
01525                         col,
01526                         row,
01527                         bits,_bufferData);
01528     }
01529   }
01530 }
01531 
01532 std::string PixelCalibConfiguration::parameterValue(std::string parameterName) const
01533 {
01534         std::map<std::string, std::string>::const_iterator itr = parameters_.find(parameterName);
01535         if (itr == parameters_.end()) // parameterName is not in the list
01536         {
01537                 return "";
01538         }
01539         else
01540         {
01541                 return itr->second;
01542         }
01543 }
01544 
01545 void PixelCalibConfiguration::writeASCII(std::string dir) const {
01546 
01547 
01548   //FIXME this is not tested for all the use cases...
01549 
01550   if (dir!="") dir+="/";
01551   std::string filename=dir+"calib.dat";
01552   std::ofstream out(filename.c_str());
01553 
01554   out << "Mode: "<<mode_<<endl;
01555   if (singleROC_) out << "SingleROC"<<endl;
01556   if (!parameters_.empty()){
01557     out << "Parameters:"<<endl;
01558     std::map<std::string, std::string>::const_iterator it=parameters_.begin();
01559     for (;it!=parameters_.end();++it){
01560       out << it->first << "        " << it->second <<endl;
01561     }
01562   }
01563   out << "Rows:" <<endl;
01564   for (unsigned int i=0;i<rows_.size();i++){
01565     for (unsigned int j=0;j<rows_[i].size();j++){
01566       out << rows_[i][j] <<" ";
01567     }
01568     if (i!=rows_.size()-1) out <<"|";
01569     out <<endl;
01570   }
01571   out << "Cols:" <<endl;
01572   for (unsigned int i=0;i<cols_.size();i++){
01573     for (unsigned int j=0;j<cols_[i].size();j++){
01574       out << cols_[i][j] <<" ";
01575     }
01576     if (i!=cols_.size()-1) out <<"|";
01577     out <<endl;
01578   }
01579 
01580   if (highVCalRange_) {
01581     out << "VcalHigh" << endl;
01582   }
01583   else {
01584     out << "VcalLow" << endl;
01585   }
01586 
01587 
01588   for (unsigned int i=0;i<dacs_.size();i++){
01589     if (dacs_[i].uniformSteps()) {
01590       if (dacs_[i].first()!=dacs_[i].last()) {
01591         out << "Scan: "<<dacs_[i].name()<<" ";
01592         out <<dacs_[i].first()<<" ";
01593         out <<dacs_[i].last()<<" ";
01594         out <<dacs_[i].step()<<endl;
01595       }
01596       else {
01597         out << "Set: "<<dacs_[i].name()<<" ";
01598         out <<dacs_[i].first()<<endl;
01599       }
01600     }
01601     else {
01602       out << "ScanValues: "<<dacs_[i].name()<<" ";
01603       for(unsigned int ival=0;ival<dacs_[i].getNPoints();ival++){
01604         out << dacs_[i].value(ival)<<" ";
01605       }
01606       out<<" -1"<<endl;
01607     }
01608   }
01609 
01610   out << "Repeat:" <<endl;
01611   out << ntrigger_ << endl;
01612 
01613   if (usesROCList_){
01614     out << "Rocs:"<< endl;
01615   }
01616   else{
01617     out << "ToCalibrate:"<< endl;
01618   }
01619   for (unsigned int i=0;i<rocListInstructions_.size();i++){
01620     out << rocListInstructions_[i] <<endl;
01621     if (rocListInstructions_[i]=="+"||rocListInstructions_[i]=="-"){
01622       out << " ";
01623     }
01624     else {
01625       out << endl;
01626     }
01627   }  
01628 
01629   out.close();
01630 
01631 }
01632 
01633 unsigned int PixelCalibConfiguration::maxNumHitsPerROC() const
01634 {
01635         unsigned int returnValue = 0;
01636         for ( std::vector<std::vector<unsigned int> >::const_iterator rows_itr = rows_.begin(); rows_itr != rows_.end(); rows_itr++ )
01637         {
01638                 for ( std::vector<std::vector<unsigned int> >::const_iterator cols_itr = cols_.begin(); cols_itr != cols_.end(); cols_itr++ )
01639                 {
01640                       unsigned int theSize = rows_itr->size()*cols_itr->size(); 
01641                       returnValue = max( returnValue, theSize );
01642                 }
01643         }
01644         return returnValue;
01645 }
01646 
01647 std::set< std::pair<unsigned int, unsigned int> > PixelCalibConfiguration::pixelsWithHits(unsigned int state) const
01648 {
01649         std::set< std::pair<unsigned int, unsigned int> > pixels;
01650         //                  column #      row #
01651         
01652         for ( std::vector<unsigned int>::const_iterator col_itr = cols_[colCounter(state)].begin(); col_itr != cols_[colCounter(state)].end(); col_itr++ )
01653         {
01654                 for ( std::vector<unsigned int>::const_iterator row_itr = rows_[rowCounter(state)].begin(); row_itr != rows_[rowCounter(state)].end(); row_itr++ )
01655                 {
01656                         pixels.insert( std::pair<unsigned int, unsigned int>( *col_itr, *row_itr ) );
01657                 }
01658         }
01659         
01660         return pixels;
01661 }
01662 
01663 bool PixelCalibConfiguration::containsScan(std::string name) const
01664 {
01665         for ( unsigned int i = 0; i < numberOfScanVariables(); i++ )
01666         {
01667                 if ( scanName(i) == name )
01668                 {
01669                         return true;
01670                 }
01671         }
01672         return false;
01673 }
01674 
01675 //=============================================================================================
01676 void PixelCalibConfiguration::writeXMLHeader(pos::PixelConfigKey key, 
01677                                              int version, 
01678                                              std::string path, 
01679                                              std::ofstream *outstream,
01680                                              std::ofstream *out1stream,
01681                                              std::ofstream *out2stream) const
01682 {
01683   std::string mthn = "[PixelCalibConfiguration::writeXMLHeader()]\t\t    " ;
01684   std::stringstream maskFullPath ;
01685 
01686   writeASCII(path) ;
01687 
01688   maskFullPath << path << "/PixelCalib_Test_" << PixelTimeFormatter::getmSecTime() << ".xml";
01689   std::cout << __LINE__ << "]\t" << mthn << "Writing to: " << maskFullPath.str() << std::endl ;
01690 
01691   outstream->open(maskFullPath.str().c_str()) ;
01692   
01693   *outstream << "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>"                                 << std::endl ;
01694   *outstream << "<ROOT xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>"                            << std::endl ;
01695   *outstream << ""                                                                                        << std::endl ; 
01696   *outstream << " <!-- " << mthn << "-->"                                                                 << std::endl ; 
01697   *outstream << ""                                                                                        << std::endl ; 
01698   *outstream << " <HEADER>"                                                                               << std::endl ; 
01699   *outstream << "  <TYPE>"                                                                                << std::endl ; 
01700   *outstream << "   <EXTENSION_TABLE_NAME>PIXEL_CALIB_CLOB</EXTENSION_TABLE_NAME>"                        << std::endl ; 
01701   *outstream << "   <NAME>Calibration Object Clob</NAME>"                                                 << std::endl ; 
01702   *outstream << "  </TYPE>"                                                                               << std::endl ; 
01703   *outstream << "  <RUN>"                                                                                 << std::endl ; 
01704   *outstream << "   <RUN_TYPE>Gain Calibration</RUN_TYPE>"                                                << std::endl ; 
01705   *outstream << "   <RUN_NUMBER>1</RUN_NUMBER>"                                                           << std::endl ; 
01706   *outstream << "   <RUN_BEGIN_TIMESTAMP>" << PixelTimeFormatter::getTime() << "</RUN_BEGIN_TIMESTAMP>"   << std::endl ; 
01707   *outstream << "   <LOCATION>CERN P5</LOCATION>"                                                         << std::endl ; 
01708   *outstream << "  </RUN>"                                                                                << std::endl ; 
01709   *outstream << " </HEADER>"                                                                              << std::endl ; 
01710   *outstream << ""                                                                                        << std::endl ; 
01711   *outstream << " <DATA_SET>"                                                                             << std::endl ;
01712   *outstream << ""                                                                                        << std::endl ;
01713   *outstream << "  <VERSION>" << version << "</VERSION>"                                                  << std::endl ;
01714   *outstream << "  <COMMENT_DESCRIPTION>" << getComment() << "</COMMENT_DESCRIPTION>"                     << std::endl ;
01715   *outstream << "  <CREATED_BY_USER>"     << getAuthor()  << "</CREATED_BY_USER>"                         << std::endl ; 
01716   *outstream << ""                                                                                        << std::endl ;
01717   *outstream << "  <PART>"                                                                                << std::endl ;
01718   *outstream << "   <NAME_LABEL>CMS-PIXEL-ROOT</NAME_LABEL>"                                              << std::endl ;      
01719   *outstream << "   <KIND_OF_PART>Detector ROOT</KIND_OF_PART>"                                           << std::endl ;         
01720   *outstream << "  </PART>"                                                                               << std::endl ;
01721 
01722 }
01723 
01724 //=============================================================================================
01725 void PixelCalibConfiguration::writeXML( std::ofstream *outstream,
01726                                         std::ofstream *out1stream,
01727                                         std::ofstream *out2stream) const 
01728 {
01729   std::string mthn = "[PixelCalibConfiguration::writeXML()]\t\t    " ;
01730   
01731 
01732   *outstream << " "                                                                                       << std::endl ;
01733   *outstream << "  <DATA>"                                                                                << std::endl ;
01734   *outstream << "   <CALIB_OBJ_DATA_FILE>./calib.dat</CALIB_OBJ_DATA_FILE>"                               << std::endl ;
01735   *outstream << "   <CALIB_TYPE>calib</CALIB_TYPE>"                                                       << std::endl ;
01736   *outstream << "  </DATA>"                                                                               << std::endl ;
01737   *outstream << " "                                                                                       << std::endl ;
01738 }
01739 
01740 //=============================================================================================
01741 void PixelCalibConfiguration::writeXMLTrailer(std::ofstream *outstream,
01742                                               std::ofstream *out1stream,
01743                                               std::ofstream *out2stream ) const 
01744 {
01745   std::string mthn = "[PixelCalibConfiguration::writeXMLTrailer()]\t\t    " ;
01746   
01747   *outstream << " </DATA_SET>"                                                                            << std::endl ;
01748   *outstream << "</ROOT>"                                                                                 << std::endl ;
01749   
01750   outstream->close() ;
01751   std::cout << __LINE__ << "]\t" << mthn << "Data written "                                               << std::endl ;
01752 
01753 }
01754