Пример #1
0
EKF::EKF(const char *configurationFileName, const char *outputPath) : _ekfSteps(0), _strOutputPath(outputPath)
{
    ConfigurationManager &configManager = ConfigurationManager::getInstance();
    configManager.loadConfigurationFromFile(configurationFileName);

    if (!_strOutputPath.empty())
    {
        std::string outputFileName(_strOutputPath + "output.yml");

        _outputFileStorage.open(outputFileName, cv::FileStorage::WRITE);

        std::string logFileName(_strOutputPath + "log.txt");
        _logFile.open(logFileName.c_str(), std::ios_base::out);

#ifndef ANDROID
        // Se genera el video en el cual se va a guardar la secuencia de predicciones
        cv::Size size(configManager.cameraCalibration->pixelsX, configManager.cameraCalibration->pixelsY);
        _outputVideoWriter.open(_strOutputPath + "videoOutput.mpg", CV_FOURCC('P','I','M','1'), 20, size, true);
#endif
    }
}
Пример #2
0
bool
QPrinter::prepare(PMPrintSettings *s)
{
  if (!psession && PMCreateSession(&psession) != noErr)
    return FALSE;
  if (*s == kPMNoPrintSettings) {
    if (PMCreatePrintSettings(s) != noErr)
      return FALSE;
    if (PMSessionDefaultPrintSettings(psession, *s) != noErr)
      return FALSE;
  } else {
    if (PMSessionValidatePrintSettings(psession, *s, kPMDontWantBoolean) != noErr)
      return FALSE;
  }
  if (minPage() != 0 || maxPage() != 0)
    PMSetPageRange(*s, minPage(), maxPage());
  if (d->printRange != AllPages) {
    PMSetFirstPage(*s, fromPage(), TRUE);
    PMSetLastPage(*s, toPage(), TRUE);
  }
  PMSetColorMode(*s, colorMode() == GrayScale ? kPMGray : kPMColor);
  PMSetCopies(*s, numCopies(), TRUE);
  if (outputToFile()) {
    CFStringRef cfstring = qstring2cfstring(outputFileName());
    CFURLRef outFile = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, cfstring,
                                                     kCFURLPOSIXPathStyle, false);
    PMSessionSetDestination(psession, *s, kPMDestinationFile, kPMDocumentFormatPDF, outFile);
    CFRelease(outFile);
    CFRelease(cfstring);
  }

  QString printName = printerName();
  if (!printName.isEmpty()) {
    CFStringRef pname = qstring2cfstring(printName);
    PMSessionSetCurrentPrinter(psession, pname);
    CFRelease(pname);
  }
  return TRUE;
}
Пример #3
0
int main(int argc, char *argv[])
{

    if(argc != 3) {
        qWarning("Error: pass two arguments: fuzzyFileName outputFileName");
        return 1;
    }

    QString fuzzyFileName(argv[1]);
    QString outputFileName(argv[2]);

    Fuzzyficacion fuzzyficacion;
    fuzzy b;

    Fuzzyficacion::importFuzzy(b, fuzzyFileName);
    fuzzyficacion.setFuzzy(b);

    QFile file(outputFileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
             return 1;

    QTextStream out(&file);

    for(float distancia=0.0; distancia < 1.05; distancia += 0.05) {
        for(float vel=-1.0; vel < 1.05; vel += 0.05) {
            float result;
            result = fuzzyficacion.fuzzyfica(distancia, vel);
            out << distancia << "\t";
            out << vel << "\t";
            out << result << "\n";
        }
    }

    file.close();

    return 0;
}
Пример #4
0
QString WebUpdater::downloadUpdate_p (const ProductVersion &version, const QString &dir)
{
	outputFile_.setFileName (outputFileName (dir, version.productUrl ()));

	if (outputFile_.exists()
			&& isFileCorrect (outputFile_.fileName(), version.productMd5sum())) {
		qDebug () << "File alredy downloaded";
		emit downloadFinished ();
		return outputFile_.fileName();
	}

	if (!outputFile_.open (QIODevice::WriteOnly | QIODevice::Truncate)) {
		qDebug () << "Error open file " << outputFile_.fileName ();
		return outputFile_.fileName();
	}

	qDebug () << version.productUrl () << outputFile_.fileName();

	const QUrl url (version.productUrl ());

	const QNetworkRequest request (url);

	QNetworkReply *reply_ = manager_->get (request);
	replyList.push_back (reply_);

	connect (reply_, SIGNAL (downloadProgress (qint64, qint64)),
			 this, SIGNAL (downloadProgress (qint64, qint64)));
	connect (reply_, SIGNAL (readyRead()),
			 this, SLOT (readyRead()));
	connect (reply_, SIGNAL (finished()),
			 this, SLOT (updateDownloaded()));
	connect (reply_, SIGNAL (finished()),
			 this, SLOT (replyFinished()));

	return outputFile_.fileName();
}
Пример #5
0
void FillSimulation(vector <Mat> fillRegions, vector<Scalar> colorValue, vector<StrokeCluster> &fisrtDrawCluster){
	float size = 0;
	int gap = 15;
	int lineWidth = 10;
	
	//Filling regions
	for (int i = 0; i < fillRegions.size(); i++) {
		// Boundary initialization
		int ys = 1;
		int ye = fillRegions[i].rows - 1;
		int xs = 1;
		int xe = fillRegions[i].cols - 1;
		Mat fillRgionBlack;
		cvtColor(fillRegions[i], fillRgionBlack, CV_RGB2GRAY);
		fillRgionBlack = fillRgionBlack > 245;
		ofstream outputFile;
		string fileName = outputFileName("drawPoints/fill", i, ".txt");
		outputFile.open(fileName);
		Point previousPoint;
		Vec3b fillColor = Vec3b(colorValue[i][0], colorValue[i][1], colorValue[i][2]);
		Vec4f cmyk;
		rgb2cmyk(fillColor, cmyk);
		// Write indexing of color
		outputFile << (int)fillColor[0] << " " << (int)fillColor[1] << " " << (int)fillColor[2] << endl;
		outputFile << (float)cmyk[0] << " " << (float)cmyk[1] << " " << (float)cmyk[2] <<" " << (float)cmyk[3] << endl;

		// Find draw points
		for (int j = ys; j <= ye; j = j + gap)
			FindDrawPoints(j, xs, ys, xe, fillRgionBlack, outputFile, size, fillColor, cmyk, lineWidth, fisrtDrawCluster[i]);
		// Last Row
		for (int k = xs; k <= xe; k = k + gap)
			FindDrawPoints(ye, k, ys, xe, fillRgionBlack, outputFile, size, fillColor, cmyk, lineWidth, fisrtDrawCluster[i]);
		outputFile.close();
	}
	cout << "\nTotal Number of fill lines: " << fillLines << endl << endl;
}
//_________________________________________________________//
AliAnalysisTaskBF *AddTaskBalanceFunctionInppMultiplicityTrain(Int_t nMultMin = 0,
							       Int_t nMultMax = 100,
							       Double_t vertexZ=10.,
							       Double_t DCAxy=-1,
							       Double_t DCAz=-1,
							       Double_t ptMin=0.3,
							       Double_t ptMax=1.5,
							       Double_t etaMin=-0.8,
							       Double_t etaMax=0.8,
							       TString fileNameBase="AnalysisResults") {
  // Creates a balance function analysis task and adds it to the analysis manager.
  // Get the pointer to the existing analysis manager via the static access method.
  TString outputFileName(fileNameBase);
  outputFileName.Append(".root");

  
  //===========================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskBF", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //===========================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskBF", "This task requires an input event handler");
    return NULL;
  }
  TString analysisType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
  gROOT->LoadMacro("$ALICE_PHYSICS/PWGCF/EBYE/macros/configBalanceFunctionAnalysis.C");
  AliBalance *bf  = 0;  // Balance Function object
  AliBalance *bfs = 0;  // shuffled Balance function object

  if (analysisType=="ESD"){
    bf  = GetBalanceFunctionObject("ESD",0,nMultMin,nMultMax);
    bfs = GetBalanceFunctionObject("ESD",0,nMultMin,nMultMax,kTRUE);
  }
  else if (analysisType=="AOD"){
    bf  = GetBalanceFunctionObject("AOD",0,nMultMin,nMultMax);
    bfs = GetBalanceFunctionObject("AOD",0,nMultMin,nMultMax,kTRUE);
  }
  else{
    bf  = GetBalanceFunctionObject("MC",0,nMultMin,nMultMax);
    bfs = GetBalanceFunctionObject("MC",0,nMultMin,nMultMax,kTRUE);
  }

  // Create the task, add it to manager and configure it.
  //===========================================================================
  AliAnalysisTaskBF *taskBF = new AliAnalysisTaskBF("TaskBF");
  taskBF->SetAnalysisObject(bf);
  taskBF->SetShufflingObject(bfs);
  if(analysisType == "ESD") {
    AliESDtrackCuts *trackCuts = GetTrackCutsObject();
    taskBF->SetAnalysisCutObject(trackCuts);
    
    // offline trigger selection (AliVEvent.h)
    // taskBF->UseOfflineTrigger(); // NOT used (selection is done with the AliAnalysisTaskSE::SelectCollisionCandidates()) 
    // with this only selected events are analyzed (first 2 bins in event QA histogram are the same))
    taskBF->SelectCollisionCandidates(AliVEvent::kMB);
  }
  else if(analysisType == "AOD") {
    // pt and eta cut (pt_min, pt_max, eta_min, eta_max)
    taskBF->SetAODtrackCutBit(128);
    taskBF->SetKinematicsCutsAOD(ptMin,ptMax,etaMin,etaMax);
    //taskBF->SetExtraDCACutsAOD(DCAxy,DCAz);
    taskBF->SetMultiplicityRange(nMultMin,nMultMax);
  }
  
  // vertex cut (x,y,z)
  taskBF->SetVertexDiamond(.3,.3,vertexZ);
  
  //bf->PrintAnalysisSettings();
  mgr->AddTask(taskBF);

  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //======================================================================
  TString listQAName = "listQA"; listQAName += (Int_t) (nMultMin);
  listQAName += "-"; listQAName += (Int_t) (nMultMax);
  AliAnalysisDataContainer *coutQA = mgr->CreateContainer(listQAName.Data(), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
 
  TString listBFName = "listBF"; listBFName += (Int_t) (nMultMin);
  listBFName += "-"; listBFName += (Int_t) (nMultMax);
  AliAnalysisDataContainer *coutBF = mgr->CreateContainer(listBFName.Data(), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  
  TString listBFshuffledName = "listBFshuffled"; listBFshuffledName += (Int_t) (nMultMin);
  listBFshuffledName += "-"; listBFshuffledName += (Int_t) (nMultMax);
  AliAnalysisDataContainer *coutBFS= mgr->CreateContainer(listBFshuffledName.Data(), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  mgr->ConnectInput(taskBF, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(taskBF, 1, coutQA);
  mgr->ConnectOutput(taskBF, 2, coutBF);
  mgr->ConnectOutput(taskBF, 3, coutBFS);

  return taskBF;
}
Пример #7
0
void VcImporter::AddConfiguration(ProjectSettingsPtr settings, wxXmlNode* config)
{
    // configuration name
    wxString name = XmlUtils::ReadString(config, wxT("Name"));
    name = name.BeforeFirst(wxT('|'));
    name.Replace(wxT(" "), wxT("_"));

    BuildConfigPtr le_conf(new BuildConfig(NULL));
    le_conf->SetName(name);
    le_conf->SetIntermediateDirectory(XmlUtils::ReadString(config, wxT("IntermediateDirectory")));
    // get the compiler settings
    wxXmlNode* cmpNode = XmlUtils::FindNodeByName(config, wxT("Tool"), wxT("VCCLCompilerTool"));
    // get the include directories
    le_conf->SetIncludePath(SplitString(XmlUtils::ReadString(cmpNode, wxT("AdditionalIncludeDirectories"))));
    le_conf->SetPreprocessor(XmlUtils::ReadString(cmpNode, wxT("PreprocessorDefinitions")));

    // Select the best compiler for the import process (we select g++ by default)
    le_conf->SetCompilerType(m_compiler);

    // Get the configuration type
    long type = XmlUtils::ReadLong(config, wxT("ConfigurationType"), 1);
    wxString projectType;
    wxString errMsg;
    switch(type) {
    case 2: // dll
        projectType = Project::DYNAMIC_LIBRARY;
        break;
    case 4: // static library
        projectType = Project::STATIC_LIBRARY;
        break;
    case 1: // exe
    default:
        projectType = Project::EXECUTABLE;
        break;
    }

    le_conf->SetProjectType(projectType);

    // if project type is DLL or Executable, copy linker settings as well
    if(settings->GetProjectType(le_conf->GetName()) == Project::EXECUTABLE ||
       settings->GetProjectType(le_conf->GetName()) == Project::DYNAMIC_LIBRARY) {
        wxXmlNode* linkNode = XmlUtils::FindNodeByName(config, wxT("Tool"), wxT("VCLinkerTool"));
        if(linkNode) {
            wxString outputFileName(XmlUtils::ReadString(linkNode, wxT("OutputFile")));
#ifndef __WXMSW__
            outputFileName.Replace(wxT(".dll"), wxT(".so"));
            outputFileName.Replace(wxT(".exe"), wxT(""));
#endif

            le_conf->SetOutputFileName(outputFileName);

            // read in the additional libraries & libpath
            wxString libs = XmlUtils::ReadString(linkNode, wxT("AdditionalDependencies"));

            // libs is a space delimited string
            wxStringTokenizer tk(libs, wxT(" "));
            libs.Empty();
            while(tk.HasMoreTokens()) {
                libs << tk.NextToken() << wxT(";");
            }
            le_conf->SetLibraries(libs);
            le_conf->SetLibPath(XmlUtils::ReadString(linkNode, wxT("AdditionalLibraryDirectories")));
        }
    } else {
        // static library
        wxXmlNode* libNode = XmlUtils::FindNodeByName(config, wxT("Tool"), wxT("VCLibrarianTool"));
        if(libNode) {

            wxString outputFileName(XmlUtils::ReadString(libNode, wxT("OutputFile")));
            outputFileName.Replace(wxT("\\"), wxT("/"));

            wxString outputFileNameOnly = outputFileName.AfterLast(wxT('/'));
            wxString outputFilePath = outputFileName.BeforeLast(wxT('/'));

            if(m_compilerLowercase.Contains(wxT("gnu"))) {
                if(outputFileNameOnly.StartsWith(wxT("lib")) == false) {
                    outputFileNameOnly.Prepend(wxT("lib"));
                }
                outputFileName.Clear();
                outputFileName << outputFilePath << wxT("/") << outputFileNameOnly;
                outputFileName.Replace(wxT(".lib"), wxT(".a"));
            }
            le_conf->SetOutputFileName(outputFileName);
        }
    }

    // add the configuration
    settings->SetBuildConfiguration(le_conf);
}
Пример #8
0
int main(int argc, char* argv[])
{
    if (2 != argc) {
        printf("arg[1] = inputFileName\n");
        return -1;
    }

    char* inputFileName = argv[1];
    FILE* infp;
    FILE* outfp;

    // 入力ファイル
    infp = fopen(inputFileName, "r");
    if (!infp) {
        printf("file not open.\n");
        return -1;
    }

    // 入力
    // X, Y
    int maxX = 0;
    int maxY = 0;
    fscanf(infp, "%d,%d", &maxX, &maxY);
    printf("(X, Y) = (%d, %d)\n", maxX, maxY);

    // 領域確保
    int** data = new int*[maxX+1];
    for (int i = 0; i <= maxX; ++i) {
        data[i] = new int[maxY+1];
    }

    // 初期化
    for (int i = 0; i <= maxX; ++i) {
        for (int j = 0; j <= maxY; ++j) {
            data[i][j] = 1;
        }
    }

    // Num of Blocked
    int numOfBlocked = 0;
    fscanf(infp, "%d", &numOfBlocked);
    printf("numOfBlocked = %d\n", numOfBlocked);

    // Blocked point
    for (int i = 0; i < numOfBlocked; ++i) {
        int tmpX = 0;
        int tmpY = 0;
        fscanf(infp, "%d,%d", &tmpX, &tmpY);
        data[tmpX][tmpY] = 0;
    }
    fclose(infp); // 入力ファイル

    for (int i = 0; i <= maxX; ++i) {
        for (int j = 0; j <= maxY; ++j) {
            printf("%d ", data[i][j]);
        }
        printf("\n");
    }

    RouteSearch* routeSearch = new RouteSearch(data, maxX, maxY);

    timeval startTime;     // 開始時刻
    timeval endTime;       // 終了時刻

    // 時間計測開始
    gettimeofday(&startTime, NULL);

    int result =  routeSearch->calc();
//printf("result = %d\n", result);

    // 時間計測終了
    gettimeofday(&endTime, NULL);
    double timeDiff = static_cast<double>(endTime.tv_sec  - startTime.tv_sec);
    double usecDiff = static_cast<double>(endTime.tv_usec - startTime.tv_usec);
    timeDiff += (usecDiff/1000000.0);

    delete routeSearch;

    // 出力ファイル
    std::string inputPath(inputFileName);
    int l = inputPath.length();
    std::string outputFileName(inputPath.substr(l-6));
    std::string indexStr(inputPath.substr(l-2));

    outfp = fopen(outputFileName.c_str(), "w");
    if (!outfp) {
        printf("file not open.");
        return -1;
    }

    fprintf(outfp, "Case #%s: %4d  %.3f[msec]\n", indexStr.c_str(), result, timeDiff*1000.0);
    printf("Case #%s: %4d  %.3f[msec]\n", indexStr.c_str(), result, timeDiff*1000.0);

    // 解放
    for (int i = 0; i <= maxX; ++i) {
        delete[] data[i];
    }
    delete[] data;


    return 0;
}
Пример #9
0
      }
      nSample_ = 0;
   }

   /* 
   * Increment structure factors for all wavevectors and modes.
   */
   void StructureFactor::sample(long iStep) 
   {
      if (isAtInterval(iStep))  {

<<<<<<< HEAD
         fileMaster().openOutputFile(outputFileName("_max.dat"), outputFile_, !isFirstStep_);
         //fileMaster().openOutputFile(outputFileName(".dat"), logFile_, !isFirstStep_);
=======
         fileMaster().openOutputFile(outputFileName("_max.dat"), 
                                     outputFile_, !isFirstStep_);
>>>>>>> 7454788cb955ae6920d2fc65f1ee1fa595a406d8
         isFirstStep_ = false;

         Vector position;
         std::complex<double> expFactor;
         double product;
         System::ConstMoleculeIterator molIter;
         Molecule::ConstAtomIterator atomIter;
         int nSpecies, iSpecies, typeId, i, j;

         makeWaveVectors();

         // Set all Fourier modes to zero
         for (i = 0; i < nWave_; ++i) {
//_________________________________________________________//
AliAnalysisTaskBFPsi *AddTaskBalancePsiCentralityTrain(Double_t centrMin=0.,
						       Double_t centrMax=100.,
						       Bool_t gRunShuffling=kFALSE,
						       Bool_t gRunMixing=kTRUE,
						       Bool_t gRunMixingWithEventPlane=kFALSE,
						       TString centralityEstimator="V0M",
						       Double_t vertexZ=10.,
						       Double_t DCAxy=-1,
						       Double_t DCAz=-1,
						       Double_t ptMin=0.3,
						       Double_t ptMax=1.5,
						       Double_t etaMin=-0.8,
						       Double_t etaMax=0.8,
						       Double_t maxTPCchi2 = -1, 
						       Int_t minNClustersTPC = -1,
						       Bool_t kUsePID = kTRUE,
						       Bool_t bResonancesCut = kTRUE,
						       Bool_t bHBTcut = kTRUE,
						       Double_t HBTCutValue = 0.02,
						       Bool_t bConversionCut = kTRUE,
						       Double_t invMassForConversionCut = 0.04,
						       Bool_t bMomentumDifferenceCut = kTRUE,
						       Double_t fQCutMin = 0.0,
						       Int_t AODfilterBit = 128,
						       AliAnalysisTaskBFPsi::etriggerSel triggerSel = AliAnalysisTaskBFPsi::kINT7,
						       TString fileNameBase="AnalysisResults",
						       TString dirNameExtra="",
						       TString fArgEventClass="Centrality",
						       TString analysisTypeUser="******",
						       Bool_t bVertexBinning=kTRUE,
						       Double_t sigmaElectronRejection=3,
						       Bool_t electronExclusiveRejection=kFALSE,
						       TString correctionFileName = "",
						       Int_t nCentralityArrayBinsForCorrection = -1,
						       Double_t *gCentralityArrayForCorrections = 0x0,
						       Bool_t gRunEbyE = kFALSE,
						       Bool_t bMomentumOrdering = kTRUE,
						       AliAnalysisTaskBFPsi::eCorrProcedure corrProc = AliAnalysisTaskBFPsi::kNoCorr) {
  // Creates a balance function analysis task and adds it to the analysis manager.
  // Get the pointer to the existing analysis manager via the static access method.
  TString outputFileName(fileNameBase);
  outputFileName.Append(".root");

  //===========================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskBF", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //===========================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskBF", "This task requires an input event handler");
    return NULL;
  }
  TString analysisType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
  if(dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler())) analysisType = "MC";
  
  // to set the analysis type manually
  if(analysisTypeUser != ""){
    analysisType = analysisTypeUser;
    ::Info("AddTaskBF",Form("Analysis Type manually set to %s",analysisType.Data()));
  }

  // for local changed BF configuration
  //gROOT->LoadMacro("./configBalanceFunctionPsiAnalysis.C");
  gROOT->LoadMacro("$ALICE_PHYSICS/PWGCF/EBYE/macros/configBalanceFunctionPsiAnalysis.C");
  AliBalancePsi *bf  = 0;  // Balance Function object
  AliBalancePsi *bfs = 0;  // shuffled Balance function object
  AliBalancePsi *bfm = 0;  // mixing Balance function object
  AliBalanceEbyE *bfebye = 0;  // EbyE Balance function object

  //maximum Delta eta range
  Double_t deltaEtaMax=TMath::Abs(etaMax-etaMin);

  if (analysisType=="ESD"){
    bf  = GetBalanceFunctionObject("ESD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
    if(gRunShuffling) bfs = GetBalanceFunctionObject("ESD",centralityEstimator,centrMin,centrMax,kTRUE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
    if(gRunMixing)    bfm = GetBalanceFunctionObject("ESD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
  }
  else if (analysisType=="AOD"){
    bf  = GetBalanceFunctionObject("AOD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
    if(gRunShuffling) bfs = GetBalanceFunctionObject("AOD",centralityEstimator,centrMin,centrMax,kTRUE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
    if(gRunMixing)    bfm = GetBalanceFunctionObject("AOD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
    if(gRunEbyE)      bfebye = GetBalanceFunctionEbyEObject(bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,deltaEtaMax,bMomentumOrdering);
  }
  else if (analysisType=="MC"){
    bf  = GetBalanceFunctionObject("MC",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
    if(gRunShuffling) bfs = GetBalanceFunctionObject("MC",centralityEstimator,centrMin,centrMax,kTRUE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
    if(gRunMixing)    bfm = GetBalanceFunctionObject("MC",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
  }
  else if (analysisType=="MCAOD"){
    bf  = GetBalanceFunctionObject("MCAOD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
    if(gRunShuffling) bfs = GetBalanceFunctionObject("MCAOD",centralityEstimator,centrMin,centrMax,kTRUE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
    if(gRunMixing)    bfm = GetBalanceFunctionObject("MCAOD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
  }
  else if (analysisType=="MCAODrec"){
    bf  = GetBalanceFunctionObject("MCAODrec",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
    if(gRunShuffling) bfs = GetBalanceFunctionObject("MCAODrec",centralityEstimator,centrMin,centrMax,kTRUE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
    if(gRunMixing)    bfm = GetBalanceFunctionObject("MCAODrec",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
  }
  else if (analysisType=="AODnano"){
    bf  = GetBalanceFunctionObject("AODnano",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
    if(gRunShuffling) bfs = GetBalanceFunctionObject("AODnano",centralityEstimator,centrMin,centrMax,kTRUE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
    if(gRunMixing)    bfm = GetBalanceFunctionObject("AODnano",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,HBTCutValue,bConversionCut,invMassForConversionCut,bMomentumDifferenceCut,fQCutMin,fArgEventClass,deltaEtaMax,bVertexBinning,bMomentumOrdering);
  }
  else{
    ::Error("AddTaskBF", "analysis type NOT known.");
    return NULL;
  }

  // Create the task, add it to manager and configure it.
  //===========================================================================
  AliAnalysisTaskBFPsi *taskBF = new AliAnalysisTaskBFPsi(Form("TaskBFPsi_%.0f-%.0f_Bit%d_%s%s",centrMin,centrMax,AODfilterBit,centralityEstimator.Data(),dirNameExtra.Data()));
  
  //Event characteristics scheme
  taskBF->SetEventClass(fArgEventClass);
  //taskBF->SetCustomBinning("centralityVertex:0,80");
  //taskBF->SetCustomBinning("multiplicity:0,260");
  
  if(fArgEventClass == "Multiplicity") {
    taskBF->SetPercentileRange(centrMin,centrMax);
    //taskBF->SetMultiplicityRange(centrMin,centrMax);
    taskBF->SetMultiplicityEstimator(centralityEstimator);
    cout<<"Multiplicity estimator "<<centralityEstimator.Data()<<endl;
  }
  else if(fArgEventClass == "Centrality") {
    if(analysisType == "MC")
      taskBF->SetImpactParameterRange(centrMin,centrMax);
    else {
      taskBF->SetPercentileRange(centrMin,centrMax);
      //taskBF->SetCentralityPercentileRange(centrMin,centrMax);
      // centrality estimator (default = V0M)
      taskBF->SetCentralityEstimator(centralityEstimator);
      cout<<"Centrality estimator "<<centralityEstimator.Data()<<endl;
    }
  }

  
  //+++++++++++++++++++++

  taskBF->SetAnalysisObject(bf);
  if(gRunShuffling) taskBF->SetShufflingObject(bfs);
  if(gRunMixing){
    taskBF->SetMixingObject(bfm);
    taskBF->SetMixingTracks(50000);
    if(gRunMixingWithEventPlane){
      taskBF->SetMixingWithEventPlane(gRunMixingWithEventPlane);
    }
  }
  if(gRunEbyE) taskBF->SetEbyEObject(bfebye);

  if(analysisType == "ESD") {
    AliESDtrackCuts *trackCuts = GetTrackCutsObject(ptMin,ptMax,etaMin,etaMax,maxTPCchi2,DCAxy,DCAz,minNClustersTPC);
    taskBF->SetAnalysisCutObject(trackCuts);
    if(kUsePID) {
      if(kUseBayesianPID)
	taskBF->SetUseBayesianPID(gMinAcceptedProbability);
      else if(kUseNSigmaPID)
	taskBF->SetUseNSigmaPID(nSigmaMax);
      taskBF->SetParticleOfInterest(AliAnalysisTaskBFPsi::kPion);
      taskBF->SetDetectorUsedForPID(AliAnalysisTaskBFPsi::kTOFpid);
    }
  }
  else if(analysisType == "AOD" || analysisType == "AODnano") {
    // pt and eta cut (pt_min, pt_max, eta_min, eta_max)
    taskBF->SetAODtrackCutBit(AODfilterBit);
    taskBF->SetKinematicsCutsAOD(ptMin,ptMax,etaMin,etaMax);

    // set extra DCA cuts (-1 no extra cut)
    taskBF->SetExtraDCACutsAOD(DCAxy,DCAz);

    // set extra TPC chi2 / nr of clusters cut
    taskBF->SetExtraTPCCutsAOD(maxTPCchi2, minNClustersTPC);

    // electron rejection (so far only for AOD), <0 --> no rejection
    if(sigmaElectronRejection > 0){
      if(electronExclusiveRejection) taskBF->SetElectronOnlyRejection(sigmaElectronRejection); // no other particle in nsigma 
      else                           taskBF->SetElectronRejection(sigmaElectronRejection); // check only if electrons in nsigma
    }

    //++++++++++++++++//
    if(kUsePID) {
      if(kUseBayesianPID)
	taskBF->SetUseBayesianPID(gMinAcceptedProbability);
      else if(kUseNSigmaPID)
	taskBF->SetUseNSigmaPID(nSigmaMax);
      taskBF->SetParticleOfInterest(AliAnalysisTaskBFPsi::kKaon);
      taskBF->SetDetectorUsedForPID(AliAnalysisTaskBFPsi::kTPCTOF); //TOFpid,TPCpid
    }
    //++++++++++++++++//

  }
  else if(analysisType == "MC") {
    taskBF->SetKinematicsCutsAOD(ptMin,ptMax,etaMin,etaMax);
  }
  else if(analysisType == "MCAOD") {
    // pt and eta cut (pt_min, pt_max, eta_min, eta_max)
    taskBF->SetAODtrackCutBit(AODfilterBit);
    taskBF->SetKinematicsCutsAOD(ptMin,ptMax,etaMin,etaMax);    
  }
  else if(analysisType == "MCAODrec") {     //++++++++++++++++
    // pt and eta cut (pt_min, pt_max, eta_min, eta_max)
    taskBF->SetAODtrackCutBit(AODfilterBit);
    taskBF->SetKinematicsCutsAOD(ptMin,ptMax,etaMin,etaMax); 

    // set extra DCA cuts (-1 no extra cut)
    taskBF->SetExtraDCACutsAOD(DCAxy,DCAz);

    // set extra TPC chi2 / nr of clusters cut
    taskBF->SetExtraTPCCutsAOD(maxTPCchi2, minNClustersTPC);

    // electron rejection (so far only for AOD), <0 --> no rejection
    if(sigmaElectronRejection > 0){
      if(electronExclusiveRejection) taskBF->SetElectronOnlyRejection(sigmaElectronRejection); // no other particle in nsigma 
      else                           taskBF->SetElectronRejection(sigmaElectronRejection); // check only if electrons in nsigma
    }
  }//++++++++++++++++

  // offline trigger selection (AliVEvent.h)
  // taskBF->UseOfflineTrigger(); // NOT used (selection is done with the AliAnalysisTaskSE::SelectCollisionCandidates()) 
  // with this only selected events are analyzed (first 2 bins in event QA histogram are the same))
  // documentation in https://twiki.cern.ch/twiki/bin/viewauth/ALICE/PWG1EvSelDocumentation

  
  if(triggerSel == AliAnalysisTaskBFPsi::kCentral) taskBF->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral);
  else if(triggerSel == AliAnalysisTaskBFPsi::kMB) taskBF->SelectCollisionCandidates(AliVEvent::kMB);
  else if(triggerSel == AliAnalysisTaskBFPsi::kINT7) taskBF->SelectCollisionCandidates(AliVEvent::kINT7);

  // centrality estimator (default = V0M)
  taskBF->SetCentralityEstimator(centralityEstimator);
  
  // vertex cut (x,y,z)
  taskBF->SetVertexDiamond(3.,3.,vertexZ);

  taskBF->SetCorrectionProcedure(corrProc);


  //++++++++++++++++++++++
  // Efficiency + Contamination corrections
  // If correctionFileName = "", do not use corrections
  // if(corrProc == AliAnalysisTaskBFPsi::kMCCorr)
  // taskBF->SetInputCorrection(Form("$ALICE_PHYSICS/PWGCF/EBYE/BalanceFunctions/Corrections/%s",correctionFileName.Data()),nCentralityArrayBinsForCorrection,gCentralityArrayForCorrections);
  
  /*else if (corrProc == AliAnalysisTaskBFPsi::kDataDrivCorr){

    TFile* fNUAFile = TFile::Open(nuaCorrFileName.Data(),"READ");
    TFile* fNUEFile = TFile::Open(nueCorrFileName.Data(),"READ");
    
    if(!fNUAFile) {
      printf(" *** ERROR: NUA file not found! **EXIT** ");
    } 
    TList* fListNUA = dynamic_cast<TList*>(fNUAFile->Get("fListNUA"));
    if(fListNUA)
      taskBF->SetInputListForNUACorr(fListNUA);
    else
      printf(" *** ERROR: NUA List not found! **EXIT**");
    
    
    if(!fNUEFile) {
      printf(" *** ERROR: NUE file not found! **EXIT** ");
    } 
    TList* fListNUE = dynamic_cast<TList*>(fNUEFile->Get("fListNUE"));
    if(fListNUE)
      taskBF->SetInputListForNUECorr(fListNUE);
    else
      printf(" *** ERROR: NUE List not found! **EXIT**");    
  }
  */
  
  //bf->PrintAnalysisSettings();
  mgr->AddTask(taskBF);
  
  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  TString outputFileName = AliAnalysisManager::GetCommonFileName();
  outputFileName += ":PWGCFEbyE.outputBalanceFunctionPsiAnalysis";
  AliAnalysisDataContainer *coutQA = mgr->CreateContainer(Form("listQAPsi_%.0f-%.0f_Bit%d_%s%s",centrMin,centrMax,AODfilterBit,centralityEstimator.Data(),dirNameExtra.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  AliAnalysisDataContainer *coutBF = mgr->CreateContainer(Form("listBFPsi_%.0f-%.0f_Bit%d_%s%s",centrMin,centrMax,AODfilterBit,centralityEstimator.Data(),dirNameExtra.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  if(gRunShuffling) AliAnalysisDataContainer *coutBFS = mgr->CreateContainer(Form("listBFPsiShuffled_%.0f-%.0f_Bit%d_%s%s",centrMin,centrMax,AODfilterBit,centralityEstimator.Data(),dirNameExtra.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  if(gRunMixing) AliAnalysisDataContainer *coutBFM = mgr->CreateContainer(Form("listBFPsiMixed_%.0f-%.0f_Bit%d_%s%s",centrMin,centrMax,AODfilterBit,centralityEstimator.Data(),dirNameExtra.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  if(kUsePID || sigmaElectronRejection > 0) AliAnalysisDataContainer *coutQAPID = mgr->CreateContainer(Form("listQAPIDPsi_%.0f-%.0f_Bit%d_%s%s",centrMin,centrMax,AODfilterBit,centralityEstimator.Data(),dirNameExtra.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());

  mgr->ConnectInput(taskBF, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(taskBF, 1, coutQA);
  mgr->ConnectOutput(taskBF, 2, coutBF);
  if(gRunShuffling) mgr->ConnectOutput(taskBF, 3, coutBFS);
  if(gRunMixing) mgr->ConnectOutput(taskBF, 4, coutBFM);
  if(kUsePID||sigmaElectronRejection > 0) mgr->ConnectOutput(taskBF, 5, coutQAPID);
  //if((kUsePID && analysisType == "AOD")||sigmaElectronRejection > 0) mgr->ConnectOutput(taskBF, 5, coutQAPID);
  //if((kUsePID && analysisType == "ESD")||sigmaElectronRejection > 0) mgr->ConnectOutput(taskBF, 5, coutQAPID);

  return taskBF;
}
Пример #11
0
AliAnalysisTaskEffContBF *AddTaskBalanceEffCont( TString  centralityEstimator="V0M",
						 Double_t centrMin=0.,
						 Double_t centrMax=80.,
						 Double_t vertexZ=10.,
						 Int_t AODfilterBit = 128,
						 Bool_t bUseElectronRejection = kFALSE,
						 TString fileNameBase="AnalysisResults",
						 AliAnalysisTaskBFPsi::etriggerSel triggerSel = AliAnalysisTaskBFPsi::kINT7,
						 Bool_t usePID=kFALSE,
						 AliPID::EParticleType particleType = AliPID::kPion
						 ) {

  // Creates a balance function analysis task and adds it to the analysis manager.
  // Get the pointer to the existing analysis manager via the static access method.
  TString centralityName("");

  centralityName+=Form("%.0f-%.0f_%.0f",centrMin,centrMax,vertexZ);
  TString outputFileName(fileNameBase);
  outputFileName.Append(".root");
  
  //===========================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskTriggeredBF", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //===========================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskTriggeredBF", "This task requires an input event handler");
    return NULL;
  }
  TString analysisType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
  if(dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler())) analysisType = "MC";

 
  // Create the task, add it to manager and configure it.
  //===========================================================================


  AliAnalysisTaskEffContBF *taskEffContBF = new AliAnalysisTaskEffContBF("TaskEffContBF");

  // centrality
  if(centralityEstimator) {
    taskEffContBF->UseCentrality();
    taskEffContBF->SetCentralityEstimator(centralityEstimator);
    taskEffContBF->SetCentralityPercentileRange(centrMin,centrMax);
  }
  
  if (triggerSel == AliAnalysisTaskBFPsi::kCentral) taskEffContBF->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral);
  else if(triggerSel == AliAnalysisTaskBFPsi::kMB) taskEffContBF->SelectCollisionCandidates(AliVEvent::kMB);
  else if(triggerSel == AliAnalysisTaskBFPsi::kINT7) taskEffContBF->SelectCollisionCandidates(AliVEvent::kINT7);
  
  // vertex
  taskEffContBF->SetVertexDiamond(.3,.3,vertexZ);

  //analysis kinematic cuts
  taskEffContBF->SetMinPt(0.0);
  taskEffContBF->SetMaxPt(20.0); //5.0
  //taskEffContBF->SetEtaRange(-0.8,0.8,100,0.0,1.6, 64); //acceptance cuts
  //taskEffContBF->SetPtRange(0.1, 20.0, 100);  //acceptance cuts //5.0,49
  taskEffContBF->SetEtaRange(-0.8,0.8,100,0.0,1.6, 64); //acceptance cuts
  taskEffContBF->SetPtRange(0.0, 20.0, 100);  //acceptance cuts //5.0,49

  // electron rejection
    if(bUseElectronRejection){
      taskEffContBF->SetElectronOnlyRejection(3.); // no other particle in nsigma (this is what we use standard in BF code)
    }

    TString pidsuffix ="ch";
    if (usePID) {
      pidsuffix = AliPID::ParticleShortName(particleType);
      taskEffContBF->SetUsePID(usePID, particleType);
    }
    
  //AODs  
  taskEffContBF->SetAODtrackCutBit(AODfilterBit);
  mgr->AddTask(taskEffContBF);

  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  TString outputFileName = AliAnalysisManager::GetCommonFileName();
  outputFileName += ":PWGCFEbyE.outputBalanceFunctionEffContAnalysis";
  AliAnalysisDataContainer *coutQA = mgr->CreateContainer(Form("listQA_%s_%s",centralityName.Data(), pidsuffix.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  AliAnalysisDataContainer *coutEffContBF = mgr->CreateContainer(Form("listEffContBF_%s_%s",centralityName.Data(), pidsuffix.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());

  mgr->ConnectInput(taskEffContBF, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(taskEffContBF, 1, coutQA);
  mgr->ConnectOutput(taskEffContBF, 2, coutEffContBF);
  
  return taskEffContBF;
}
Пример #12
0
int main (int argc, char *argv[]) {
    if(argc <= 1) {
        cerr << "usage: " << endl << argv[0] << " <file.osm/.osm.bz2/.osm.pbf>" << endl;
        exit(-1);
    }

    cout << "[extractor] extracting data from input file " << argv[1] << endl;
    bool isPBF = false;
    string outputFileName(argv[1]);
    string restrictionsFileName(argv[1]);
    string::size_type pos = outputFileName.find(".osm.bz2");
    if(pos==string::npos) {
        pos = outputFileName.find(".osm.pbf");
        if(pos!=string::npos) {
            isPBF = true;
        }
    }
    if(pos!=string::npos) {
        outputFileName.replace(pos, 8, ".osrm");
        restrictionsFileName.replace(pos, 8, ".osrm.restrictions");
    } else {
        pos=outputFileName.find(".osm");
        if(pos!=string::npos) {
            outputFileName.replace(pos, 5, ".osrm");
            restrictionsFileName.replace(pos, 5, ".osrm.restrictions");
        } else {
            outputFileName.append(".osrm");
            restrictionsFileName.append(".osrm.restrictions");
        }
    }
    string adressFileName(outputFileName);

    unsigned amountOfRAM = 1;
    unsigned installedRAM = GetPhysicalmemory(); 
    if(installedRAM < 2048264) {
        cout << "[Warning] Machine has less than 2GB RAM." << endl;
    }
    if(testDataFile("extractor.ini")) {
        ExtractorConfiguration extractorConfig("extractor.ini");
        unsigned memoryAmountFromFile = atoi(extractorConfig.GetParameter("Memory").c_str());
        if( memoryAmountFromFile != 0 && memoryAmountFromFile <= installedRAM/(1024*1024*1024))
            amountOfRAM = memoryAmountFromFile;
        cout << "[extractor] using " << amountOfRAM << " GB of RAM for buffers" << endl;
    }

    STXXLContainers externalMemory;

    unsigned usedNodeCounter = 0;
    unsigned usedEdgeCounter = 0;

    StringMap * stringMap = new StringMap();
    Settings settings;
    settings.speedProfile.names.insert(settings.speedProfile.names.begin(), names, names+14);
    settings.speedProfile.speed.insert(settings.speedProfile.speed.begin(), speeds, speeds+14);

    double time = get_timestamp();

    stringMap->set_empty_key(GetRandomString());
    stringMap->insert(make_pair("", 0));
    extractCallBacks = new ExtractorCallbacks(&externalMemory, settings, stringMap);

    BaseParser<_Node, _RawRestrictionContainer, _Way> * parser;
    if(isPBF) {
        parser = new PBFParser(argv[1]);
    } else {
        parser = new XMLParser(argv[1]);
    }
    parser->RegisterCallbacks(&nodeFunction, &restrictionFunction, &wayFunction, &adressFunction);
    if(parser->Init()) {
        parser->Parse();
    } else {
        cerr << "[error] parser not initialized!" << endl;
        exit(-1);
    }
    delete parser;

    try {
//        INFO("raw no. of names:        " << externalMemory.nameVector.size());
//        INFO("raw no. of nodes:        " << externalMemory.allNodes.size());
//        INFO("no. of used nodes:       " << externalMemory.usedNodeIDs.size());
//        INFO("raw no. of edges:        " << externalMemory.allEdges.size());
//        INFO("raw no. of ways:         " << externalMemory.wayStartEndVector.size());
//        INFO("raw no. of addresses:    " << externalMemory.adressVector.size());
//        INFO("raw no. of restrictions: " << externalMemory.restrictionsVector.size());

        cout << "[extractor] parsing finished after " << get_timestamp() - time << "seconds" << endl;
        time = get_timestamp();
        uint64_t memory_to_use = static_cast<uint64_t>(amountOfRAM) * 1024 * 1024 * 1024;

        cout << "[extractor] Sorting used nodes        ... " << flush;
        stxxl::sort(externalMemory.usedNodeIDs.begin(), externalMemory.usedNodeIDs.end(), Cmp(), memory_to_use);
        cout << "ok, after " << get_timestamp() - time << "s" << endl;

        time = get_timestamp();
        cout << "[extractor] Erasing duplicate nodes   ... " << flush;
        stxxl::vector<NodeID>::iterator NewEnd = unique ( externalMemory.usedNodeIDs.begin(),externalMemory.usedNodeIDs.end() ) ;
        externalMemory.usedNodeIDs.resize ( NewEnd - externalMemory.usedNodeIDs.begin() );
        cout << "ok, after " << get_timestamp() - time << "s" << endl;
        time = get_timestamp();

        cout << "[extractor] Sorting all nodes         ... " << flush;
        stxxl::sort(externalMemory.allNodes.begin(), externalMemory.allNodes.end(), CmpNodeByID(), memory_to_use);
        cout << "ok, after " << get_timestamp() - time << "s" << endl;
        time = get_timestamp();

        cout << "[extractor] Sorting used ways         ... " << flush;
        stxxl::sort(externalMemory.wayStartEndVector.begin(), externalMemory.wayStartEndVector.end(), CmpWayStartAndEnd(), memory_to_use);
        cout << "ok, after " << get_timestamp() - time << "s" << endl;

        cout << "[extractor] Sorting restrctns. by from... " << flush;
        stxxl::sort(externalMemory.restrictionsVector.begin(), externalMemory.restrictionsVector.end(), CmpRestrictionByFrom(), memory_to_use);
        cout << "ok, after " << get_timestamp() - time << "s" << endl;

        cout << "[extractor] Fixing restriction starts ... " << flush;
        STXXLRestrictionsVector::iterator restrictionsIT = externalMemory.restrictionsVector.begin();
        STXXLWayIDStartEndVector::iterator wayStartAndEndEdgeIT = externalMemory.wayStartEndVector.begin();

        while(wayStartAndEndEdgeIT != externalMemory.wayStartEndVector.end() && restrictionsIT != externalMemory.restrictionsVector.end()) {
            if(wayStartAndEndEdgeIT->wayID < restrictionsIT->fromWay){
                wayStartAndEndEdgeIT++;
                continue;
            }
            if(wayStartAndEndEdgeIT->wayID > restrictionsIT->fromWay) {
                restrictionsIT++;
                continue;
            }
            assert(wayStartAndEndEdgeIT->wayID == restrictionsIT->fromWay);
            NodeID viaNode = restrictionsIT->restriction.viaNode;

            if(wayStartAndEndEdgeIT->firstStart == viaNode) {
                restrictionsIT->restriction.fromNode = wayStartAndEndEdgeIT->firstTarget;
            } else if(wayStartAndEndEdgeIT->firstTarget == viaNode) {
                restrictionsIT->restriction.fromNode = wayStartAndEndEdgeIT->firstStart;
            } else if(wayStartAndEndEdgeIT->lastStart == viaNode) {
                restrictionsIT->restriction.fromNode = wayStartAndEndEdgeIT->lastTarget;
            } else if(wayStartAndEndEdgeIT->lastTarget == viaNode) {
                restrictionsIT->restriction.fromNode = wayStartAndEndEdgeIT->lastStart;
            }
            restrictionsIT++;
        }

        cout << "ok, after " << get_timestamp() - time << "s" << endl;
        time = get_timestamp();

        cout << "[extractor] Sorting restrctns. by to  ... " << flush;
        stxxl::sort(externalMemory.restrictionsVector.begin(), externalMemory.restrictionsVector.end(), CmpRestrictionByTo(), memory_to_use);
        cout << "ok, after " << get_timestamp() - time << "s" << endl;

        time = get_timestamp();
        unsigned usableRestrictionsCounter(0);
        cout << "[extractor] Fixing restriction ends   ... " << flush;
        restrictionsIT = externalMemory.restrictionsVector.begin();
        wayStartAndEndEdgeIT = externalMemory.wayStartEndVector.begin();
        while(wayStartAndEndEdgeIT != externalMemory.wayStartEndVector.end() &&
                restrictionsIT != externalMemory.restrictionsVector.end()) {
            if(wayStartAndEndEdgeIT->wayID < restrictionsIT->toWay){
                wayStartAndEndEdgeIT++;
                continue;
            }
            if(wayStartAndEndEdgeIT->wayID > restrictionsIT->toWay) {
                restrictionsIT++;
                continue;
            }
            NodeID viaNode = restrictionsIT->restriction.viaNode;
            if(wayStartAndEndEdgeIT->lastStart == viaNode) {
                restrictionsIT->restriction.toNode = wayStartAndEndEdgeIT->lastTarget;
            } else if(wayStartAndEndEdgeIT->lastTarget == viaNode) {
                restrictionsIT->restriction.toNode = wayStartAndEndEdgeIT->lastStart;
            } else if(wayStartAndEndEdgeIT->firstStart == viaNode) {
                restrictionsIT->restriction.toNode = wayStartAndEndEdgeIT->firstTarget;
            } else if(wayStartAndEndEdgeIT->firstTarget == viaNode) {
                restrictionsIT->restriction.toNode = wayStartAndEndEdgeIT->firstStart;
            }

            if(UINT_MAX != restrictionsIT->restriction.fromNode && UINT_MAX != restrictionsIT->restriction.toNode) {
                usableRestrictionsCounter++;
            }
            restrictionsIT++;
        }

        cout << "ok, after " << get_timestamp() - time << "s" << endl;
        //serialize restrictions
        ofstream restrictionsOutstream;
        restrictionsOutstream.open(restrictionsFileName.c_str(), ios::binary);
        restrictionsOutstream.write((char*)&usableRestrictionsCounter, sizeof(unsigned));
        for(restrictionsIT = externalMemory.restrictionsVector.begin(); restrictionsIT != externalMemory.restrictionsVector.end(); restrictionsIT++) {
            if(UINT_MAX != restrictionsIT->restriction.fromNode && UINT_MAX != restrictionsIT->restriction.toNode) {
                restrictionsOutstream.write((char *)&(restrictionsIT->restriction), sizeof(_Restriction));
            }
        }
        restrictionsOutstream.close();

        ofstream fout;
        fout.open(outputFileName.c_str(), ios::binary);
        fout.write((char*)&usedNodeCounter, sizeof(unsigned));
        time = get_timestamp();
        cout << "[extractor] Confirming used nodes     ... " << flush;
        STXXLNodeVector::iterator nodesIT = externalMemory.allNodes.begin();
        STXXLNodeIDVector::iterator usedNodeIDsIT = externalMemory.usedNodeIDs.begin();
        while(usedNodeIDsIT != externalMemory.usedNodeIDs.end() && nodesIT != externalMemory.allNodes.end()) {
            if(*usedNodeIDsIT < nodesIT->id){
                usedNodeIDsIT++;
                continue;
            }
            if(*usedNodeIDsIT > nodesIT->id) {
                nodesIT++;
                continue;
            }
            if(*usedNodeIDsIT == nodesIT->id) {
                fout.write((char*)&(nodesIT->id), sizeof(unsigned));
                fout.write((char*)&(nodesIT->lon), sizeof(int));
                fout.write((char*)&(nodesIT->lat), sizeof(int));
                usedNodeCounter++;
                usedNodeIDsIT++;
                nodesIT++;
            }
        }

        cout << "ok, after " << get_timestamp() - time << "s" << endl;
        time = get_timestamp();

        cout << "[extractor] setting number of nodes   ... " << flush;
        ios::pos_type positionInFile = fout.tellp();
        fout.seekp(ios::beg);
        fout.write((char*)&usedNodeCounter, sizeof(unsigned));
        fout.seekp(positionInFile);

        cout << "ok" << endl;
        time = get_timestamp();

        // Sort edges by start.
        cout << "[extractor] Sorting edges by start    ... " << flush;
        stxxl::sort(externalMemory.allEdges.begin(), externalMemory.allEdges.end(), CmpEdgeByStartID(), memory_to_use);
        cout << "ok, after " << get_timestamp() - time << "s" << endl;
        time = get_timestamp();

        cout << "[extractor] Setting start coords      ... " << flush;
        fout.write((char*)&usedEdgeCounter, sizeof(unsigned));
        // Traverse list of edges and nodes in parallel and set start coord
        nodesIT = externalMemory.allNodes.begin();
        STXXLEdgeVector::iterator edgeIT = externalMemory.allEdges.begin();
        while(edgeIT != externalMemory.allEdges.end() && nodesIT != externalMemory.allNodes.end()) {
            if(edgeIT->start < nodesIT->id){
                edgeIT++;
                continue;
            }
            if(edgeIT->start > nodesIT->id) {
                nodesIT++;
                continue;
            }
            if(edgeIT->start == nodesIT->id) {
                edgeIT->startCoord.lat = nodesIT->lat;
                edgeIT->startCoord.lon = nodesIT->lon;
                edgeIT++;
            }
        }
        cout << "ok, after " << get_timestamp() - time << "s" << endl;
        time = get_timestamp();

        // Sort Edges by target
        cout << "[extractor] Sorting edges by target   ... " << flush;
        stxxl::sort(externalMemory.allEdges.begin(), externalMemory.allEdges.end(), CmpEdgeByTargetID(), memory_to_use);
        cout << "ok, after " << get_timestamp() - time << "s" << endl;
        time = get_timestamp();

        cout << "[extractor] Setting target coords     ... " << flush;
        // Traverse list of edges and nodes in parallel and set target coord
        nodesIT = externalMemory.allNodes.begin();
        edgeIT = externalMemory.allEdges.begin();
        while(edgeIT != externalMemory.allEdges.end() && nodesIT != externalMemory.allNodes.end()) {
            if(edgeIT->target < nodesIT->id){
                edgeIT++;
                continue;
            }
            if(edgeIT->target > nodesIT->id) {
                nodesIT++;
                continue;
            }
            if(edgeIT->target == nodesIT->id) {
                if(edgeIT->startCoord.lat != INT_MIN && edgeIT->startCoord.lon != INT_MIN) {
                    edgeIT->targetCoord.lat = nodesIT->lat;
                    edgeIT->targetCoord.lon = nodesIT->lon;

                    double distance = ApproximateDistance(edgeIT->startCoord.lat, edgeIT->startCoord.lon, nodesIT->lat, nodesIT->lon);
                    if(edgeIT->speed == -1)
                        edgeIT->speed = settings.speedProfile.speed[edgeIT->type];
                    double weight = ( distance * 10. ) / (edgeIT->speed / 3.6);
                    int intWeight = max(1, (int) weight);
                    int intDist = max(1, (int)distance);
                    int ferryIndex = settings.indexInAccessListOf("ferry");
                    assert(ferryIndex != -1);
                    short zero = 0;
                    short one = 1;

                    fout.write((char*)&edgeIT->start, sizeof(unsigned));
                    fout.write((char*)&edgeIT->target, sizeof(unsigned));
                    fout.write((char*)&intDist, sizeof(int));
                    switch(edgeIT->direction) {
                    case _Way::notSure:
                        fout.write((char*)&zero, sizeof(short));
                        break;
                    case _Way::oneway:
                        fout.write((char*)&one, sizeof(short));
                        break;
                    case _Way::bidirectional:
                        fout.write((char*)&zero, sizeof(short));

                        break;
                    case _Way::opposite:
                        fout.write((char*)&one, sizeof(short));
                        break;
                    default:
                        cerr << "[error] edge with no direction: " << edgeIT->direction << endl;
                        assert(false);
                        break;
                    }
                    fout.write((char*)&intWeight, sizeof(int));
                    short edgeType = edgeIT->type;
                    fout.write((char*)&edgeType, sizeof(short));
                    fout.write((char*)&edgeIT->nameID, sizeof(unsigned));
                }
                usedEdgeCounter++;
                edgeIT++;
            }
        }
        cout << "ok, after " << get_timestamp() - time << "s" << endl;
        time = get_timestamp();

        cout << "[extractor] setting number of edges   ... " << flush;
        fout.seekp(positionInFile);
        fout.write((char*)&usedEdgeCounter, sizeof(unsigned));
        fout.close();
        cout << "ok" << endl;
        time = get_timestamp();


        cout << "[extractor] writing street name index ... " << flush;
        vector<unsigned> * nameIndex = new vector<unsigned>(externalMemory.nameVector.size()+1, 0);
        outputFileName.append(".names");
        ofstream nameOutFile(outputFileName.c_str(), ios::binary);
        unsigned sizeOfNameIndex = nameIndex->size();
        nameOutFile.write((char *)&(sizeOfNameIndex), sizeof(unsigned));

        for(STXXLStringVector::iterator it = externalMemory.nameVector.begin(); it != externalMemory.nameVector.end(); it++) {
            unsigned lengthOfRawString = strlen(it->c_str());
            nameOutFile.write((char *)&(lengthOfRawString), sizeof(unsigned));
            nameOutFile.write(it->c_str(), lengthOfRawString);
        }

        nameOutFile.close();
        delete nameIndex;
        cout << "ok, after " << get_timestamp() - time << "s" << endl;

        //        time = get_timestamp();
        //        cout << "[extractor] writing address list      ... " << flush;
        //
        //        adressFileName.append(".address");
        //        ofstream addressOutFile(adressFileName.c_str());
        //        for(STXXLAddressVector::iterator it = adressVector.begin(); it != adressVector.end(); it++) {
        //            addressOutFile << it->node.id << "|" << it->node.lat << "|" << it->node.lon << "|" << it->city << "|" << it->street << "|" << it->housenumber << "|" << it->state << "|" << it->country << "\n";
        //        }
        //        addressOutFile.close();
        //        cout << "ok, after " << get_timestamp() - time << "s" << endl;

    } catch ( const exception& e ) {
        cerr <<  "Caught Execption:" << e.what() << endl;
        return false;
    }

    delete extractCallBacks;
    cout << "[extractor] finished." << endl;
    return 0;
}
Пример #13
0
int main (int argc, char *argv[]) {
    if(argc < 2) {
        ERR("usage: \n" << argv[0] << " <file.osm/.osm.bz2/.osm.pbf> [<profile.lua>]");
    }

    /*** Setup Scripting Environment ***/
    ScriptingEnvironment scriptingEnvironment((argc > 2 ? argv[2] : "profile.lua"), argv[1]);

    unsigned numberOfThreads = omp_get_num_procs();
    if(testDataFile("extractor.ini")) {
        ExtractorConfiguration extractorConfig("extractor.ini");
        unsigned rawNumber = stringToInt(extractorConfig.GetParameter("Threads"));
        if( rawNumber != 0 && rawNumber <= numberOfThreads)
            numberOfThreads = rawNumber;
    }
    omp_set_num_threads(numberOfThreads);


    INFO("extracting data from input file " << argv[1]);
    bool isPBF(false);
    std::string outputFileName(argv[1]);
    std::string restrictionsFileName(argv[1]);
    std::string::size_type pos = outputFileName.find(".osm.bz2");
    if(pos==std::string::npos) {
        pos = outputFileName.find(".osm.pbf");
        if(pos!=std::string::npos) {
            isPBF = true;
        }
    }
    if(pos!=string::npos) {
        outputFileName.replace(pos, 8, ".osrm");
        restrictionsFileName.replace(pos, 8, ".osrm.restrictions");
    } else {
        pos=outputFileName.find(".osm");
        if(pos!=string::npos) {
            outputFileName.replace(pos, 5, ".osrm");
            restrictionsFileName.replace(pos, 5, ".osrm.restrictions");
        } else {
            outputFileName.append(".osrm");
            restrictionsFileName.append(".osrm.restrictions");
        }
    }

    unsigned amountOfRAM = 1;
    unsigned installedRAM = GetPhysicalmemory(); 
    if(installedRAM < 2048264) {
        WARN("Machine has less than 2GB RAM.");
    }
	
    StringMap stringMap;
    ExtractionContainers externalMemory;


    stringMap[""] = 0;
    extractCallBacks = new ExtractorCallbacks(&externalMemory, &stringMap);
    BaseParser<ExtractorCallbacks, _Node, _RawRestrictionContainer, _Way> * parser;
    if(isPBF) {
        parser = new PBFParser(argv[1]);
    } else {
        parser = new XMLParser(argv[1]);
    }
    parser->RegisterCallbacks(extractCallBacks);
    parser->RegisterScriptingEnvironment(scriptingEnvironment);

    if(!parser->Init())
        ERR("Parser not initialized!");
    double time = get_timestamp();
    parser->Parse();
    INFO("parsing finished after " << get_timestamp() - time << " seconds");

    externalMemory.PrepareData(outputFileName, restrictionsFileName, amountOfRAM, scriptingEnvironment.luaStateVector[0]);

    stringMap.clear();
    delete parser;
    delete extractCallBacks;
    INFO("finished");
    std::cout << "\nRun:\n"
                   "./osrm-prepare " << outputFileName << " " << restrictionsFileName << std::endl;
    return 0;
}
Пример #14
0
void MainWindow::code()
{
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
            QMessageBox::information(this,"Error","Can't open the file!");
            return;
    }

    QTextStream in(&file);
    QStringList text;

    int i=0;
    while(!in.atEnd())
    {
        if(i==1)
            text.append(in.readLine());
        else
            in.readLine();
        i++;
        if(i==4)
            i=0;
    }

    //qDebug()<<text;
    file.close();

    HashTable *hashTable = new HashTable;
    unsigned int FirPrefix[1048576];
    unsigned int count=0;

    for(i=0;i<text.length();i++)
    {
        for(int j=0;j<65;j++)
        {
            hashTable->addTable(text[i].mid(j,24));
        }
    }


    /*for(i=0;i<1048576;i++)
    {
        hashTable->locate(i);
        if(hashTable->getFreInRead()!=0)
        {
            FirPrefix[count]=i;
            count++;
        }
    }

    unsigned int countFreInRead[9];
    for(i=0;i<9;i++)
        countFreInRead[i]=0;
    for(unsigned int i=0;i<count;i++)
    {
        hashTable->locate(FirPrefix[i]);
        unsigned short freInRead=hashTable->getFreInRead();
        //qDebug()<<freInRead<<endl;
        for(int j=10;j<=90;j+=10)
        {
            if(freInRead<=j&&(freInRead>j-10))
            {
                countFreInRead[j/10-1]++;
                //qDebug()<<"countFreInRead["<<j/10-1<<"]="<<countFreInRead[j/10-1];
            }

        }

    }

    for(i=0;i<9;i++)
    {
        qDebug()<<i*10<<"~"<<(i+1)*10<<"  "<<countFreInRead[i]<<endl;
    } //研究发现,fre 值在 1~30 之间分布较集中*/


    /*qDebug()<<"--------------------------"<<endl;
    hashTable->locate(955561);
    hashTable->getFirPrefix();*/

    for(i=0;i<1048576;i++)
    {
        hashTable->locate(i);
        if(hashTable->getFreInRead()<=30&&hashTable->getFreInRead()>20)
        {
            FirPrefix[count]=i;
            //qDebug()<<FirPrefix[count]<<endl;
            count++;

        }
    }




    qDebug()<<"--------------------------------";


    QTime t;
    t.start();


    QStringList contigList;
    for(unsigned int i=0;i<count;i++)
    {

        //qDebug()<<"for"<<endl;
        hashTable->locate(FirPrefix[i]);
        //qDebug()<<FirPrefix[i]<<endl;
        if(hashTable->getFreInContig()==1)
            continue;

        QString contig;
        contig+=hashTable->getFirPrefix();
        contig+=hashTable->getSecPrefix();
        while(hashTable->getFreInRead()!=0&&hashTable->getFreInContig()!=1)
        {

            //qDebug()<<"while"<<endl;
            hashTable->setFreInContig();


            contig+=hashTable->getPostfix();


            //qDebug()<<contig<<endl;


            unsigned int next = hashTable->hash(contig.mid(contig.length()-20,10));

            //qDebug()<<next<<endl;
            hashTable->locate(next);

        }
        contigList.append(contig);

    }
    int time = t.elapsed();




    QString outputFileName(fileName);
    outputFileName+=".assembly";
    QFile outputFile(outputFileName);


    if (!outputFile.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QMessageBox::information(this,"Error","Can't create the assembly file!");
        return;
    }
    QTextStream out(&outputFile);



    unsigned int totalLength=0;
    unsigned int maximalLength=0;
    unsigned int length[contigList.length()];
    unsigned int medianLength;

    unsigned int N50Length;
    for(unsigned int i=0;i<contigList.length();i++)
    {
        out<<contigList[i]<<endl;
        totalLength+=contigList[i].length();
        length[i]=contigList[i].length();
        if(contigList[i].length()>maximalLength)
            maximalLength=contigList[i].length();

    }
    unsigned int meanLength = totalLength/contigList.length();
    std::sort(length,length+contigList.length());
    for(unsigned int i=0;i<contigList.length();i++)
        //qDebug()<<length[i]<<endl;

    if(contigList.length()%2==0)
        medianLength = (length[contigList.length()/2]+length[contigList.length()/2-1])/2;
    else
        medianLength = length[contigList.length()/2];

    unsigned int sum=0;
    //qDebug()<<length[contigList.length()-1];
    for(unsigned int i=contigList.length()-1;i>=0;i--)
    {
        //qDebug()<<"for";
        sum=length[i]+sum;
        //qDebug()<<i;
        if(sum>=totalLength/2)
        {
            N50Length = length[i];
            break;
        }
    }



    rowCount++;

    table->setRowCount(rowCount);
    table->setItem(table->rowCount()-1,0,new QTableWidgetItem(QString::number(rowCount)));
    table->setItem(table->rowCount()-1,1,new QTableWidgetItem(QString::number(contigList.length())));
    table->setItem(table->rowCount()-1,2,new QTableWidgetItem(QString::number(totalLength)));
    table->setItem(table->rowCount()-1,3,new QTableWidgetItem(QString::number(maximalLength)));
    table->setItem(table->rowCount()-1,4,new QTableWidgetItem(QString::number(N50Length)));
    table->setItem(table->rowCount()-1,5,new QTableWidgetItem(QString::number(meanLength)));
    table->setItem(table->rowCount()-1,6,new QTableWidgetItem(QString::number(medianLength)));
    table->setItem(table->rowCount()-1,7,new QTableWidgetItem(QString::number(time)));



     QString dir("ID ");
     dir+=QString::number(rowCount);
     dir+="  finished assembling  ";
     dir+="<a href = ";
     dir += outputFileName;
     dir += ">";
     dir += outputFileName;
     dir +="</a>";
     QLabel *fileDir = new QLabel(dir);
     connect(fileDir,SIGNAL(linkActivated(QString)),this,SLOT(openCodeFile(QString)));

     mainLayout->addWidget(fileDir);

     QMessageBox::information(this,"Success","Assemble success!");





}
Пример #15
0
//
// MAIN ANALYZER LOOP
//
void DileptonAnalyzer::Loop()
{
  // Check you have a file/chain
  if (fChain == 0) return;

  // Get number of entries in chain
  Long64_t nentries = fChain->GetEntries();

  double nEventCount=0;
  double nEventGot=0;

  // Loop over events
  for (Long64_t jentry=0; jentry<nentries;jentry++) {
    nEventCount++;
    // Checks recommended from TTree:MakeClass
    Long64_t ientry = LoadTree(jentry);
    if (ientry < 0) break;
    nEventGot++;
    fChain->GetEntry(jentry);

    getEventWeight();

    // Study gen level info if this is signal MC
    // In particular, get total number of exotics decaying to something this analysis is sensitive to?
    if ( isSignalMC_ ) {
      // Filter out events where there is no interesting exotics
      // This can happen when e.g. the generated event is H->XX and both X->jj
      if ( !interestingExoticInEvent() ) continue;
      nSensitiveExoticDecayInEvent_=getNumberOfExotics();

      // Check which triggers fired
      studyTriggers();

      if ( !signalTriggerFired() ) continue;
    }

    // Loop over candidates in event
    for( unsigned int iTreeCand=0; iTreeCand != candidates->candidates_.size(); ++iTreeCand ) {

      TreeDipseudoLeptonCandidate cand = candidates->candidates_.at(iTreeCand);

      // Check what type of leptons make up this candidate
      if ( !correctLeptonsInCandidate(cand) ) continue;

      // Get leptons
      TreeLepton leptonL = getLepton( cand.leptonIndexL );
      TreeLepton leptonH = getLepton( cand.leptonIndexH );

      // Choose appropiate mass to plot
      double mass = cand.mass;
      if (anaType_==_2eTrack) mass=cand.caloCorrMass;

      // Sign of Lxy/sigma
      int sign = 1;
      if( cand.dPhiCorr > TMath::PiOver2() ) sign = -1;

      // Apply analysis cuts.
      // And fill histograms_
      DileptonAnalysisCuts::PassedWhichCuts finalCuts = dileptonCuts_final_.whichCuts( cand, leptonL, leptonH, anaType_, lxyScale_, d0Scale_ );
      DileptonAnalysisCuts::PassedWhichCuts removedLifetimeCuts = dileptonCuts_removedLifetime_.whichCuts( cand, leptonL, leptonH, anaType_, lxyScale_, d0Scale_ );

      // Final Selection
      // n-1 plots

      // Lxy significance
      DileptonAnalysisCuts::PassedWhichCuts finalCutsTemp = finalCuts;
      finalCutsTemp.passMinLxySig = true;
      finalCutsTemp.passMaxLxySig = true;

      if ( dileptonCuts_final_.passAllCuts( finalCutsTemp ) ) {
        histograms_.h_nMinus1_LxySig_finalCuts->Fill( sign*cand.decayLengthSignificance*lxyScale_, eventWeight_ );
      }

      // Also remove deltaPhi cut to see -ve Lxy/sigma distibution
      finalCutsTemp.passDeltaPhi = true;
      if ( dileptonCuts_final_.passAllCuts( finalCutsTemp ) ) {
        histograms_.h_nMinus1_LxySig_removeDeltaPhi_finalCuts->Fill( sign*cand.decayLengthSignificance*lxyScale_, eventWeight_ );
      }

      // Chi^2
      finalCutsTemp = finalCuts;
      finalCutsTemp.passVertexChi2 = true;

      if ( dileptonCuts_final_.passAllCuts( finalCutsTemp ) ) {
        histograms_.h_nMinus1_vertexChi2_finalCuts->Fill( cand.vertexChi2, eventWeight_);
      }

      // dPhi
      finalCutsTemp = finalCuts;
      finalCutsTemp.passDeltaPhi = true;

      if ( dileptonCuts_final_.passAllCuts( finalCutsTemp ) ) {
        histograms_.h_nMinus1_deltaPhi_finalCuts->Fill( cand.dPhiCorr, eventWeight_);
      }

      // smallest d0/sigma of the two leptons
      finalCutsTemp = finalCuts;
      finalCutsTemp.passLeptonAbsD0 = true;

      if ( dileptonCuts_final_.passAllCuts( finalCutsTemp ) ) {
        histograms_.h_nMinus1_leptonAbsD0Sig_finalCuts->Fill( std::min(leptonL.d0Significance,leptonH.d0Significance), eventWeight_ );
      }

      // Calo match delta R (largest of two leptons)
      finalCutsTemp = finalCuts;
      finalCutsTemp.passCaloMatch = true; // Shouldn't do anything at the moment.  Cut at deltaR < 0.2, which is very loose and applied in Tree Producer anyway.
      if ( dileptonCuts_final_.passAllCuts( finalCutsTemp ) ) {
        histograms_.h_nMinus1_leptonCaloMatchDeltaR_finalCuts->Fill( std::max(leptonL.cmDeltaR,leptonH.cmDeltaR), eventWeight_ );
        histograms_.h_nMinus1_leptonCaloMatchDeltaEta_finalCuts->Fill( std::max(leptonL.cmDeltaEta,leptonH.cmDeltaEta), eventWeight_ );
        histograms_.h_nMinus1_leptonCaloMatchDeltaPhi_finalCuts->Fill( std::max(leptonL.cmDeltaPhi,leptonH.cmDeltaPhi), eventWeight_ );
      }

      // Track pt cut
      finalCutsTemp = finalCuts;
      finalCutsTemp.passTrackPt = true;
      if ( dileptonCuts_final_.passAllCuts( finalCutsTemp ) ) {
        histograms_.h_nMinus1_leptonTrackPt_finalCuts->Fill(std::min(leptonL.pt,leptonH.pt),eventWeight_);
      }

      // Isolation
      // Gen matched signal only
      if ( isSignalMC_ && correctlyReconstructed( cand ) ) {
        finalCutsTemp = finalCuts;
        finalCutsTemp.passIso = true;

        if ( dileptonCuts_final_.passAllCuts( finalCutsTemp ) ) {
          histograms_.h_nMinus1_isolationLeptonL_finalCuts_genMatched->Fill( cand.leptonIsoL, eventWeight_ );
          histograms_.h_nMinus1_isolationLeptonH_finalCuts_genMatched->Fill( cand.leptonIsoH, eventWeight_ );
          histograms_.h_nMinus1_relIsolationLeptonL_finalCuts_genMatched->Fill( cand.leptonIsoL/cand.leptonPtL, eventWeight_ );
          histograms_.h_nMinus1_relIsolationLeptonH_finalCuts_genMatched->Fill( cand.leptonIsoH/cand.leptonPtH, eventWeight_ );

          histograms_.h_nMinus1_isolationLeptonL_vsPU_finalCuts_genMatched->Fill( cand.leptonIsoL, candidates->numPV, eventWeight_ );
          histograms_.h_nMinus1_isolationLeptonH_vsPU_finalCuts_genMatched->Fill( cand.leptonIsoH, candidates->numPV, eventWeight_ );
          histograms_.h_nMinus1_relIsolationLeptonL_vsPU_finalCuts_genMatched->Fill( cand.leptonIsoL/cand.leptonPtL, candidates->numPV, eventWeight_ );
          histograms_.h_nMinus1_relIsolationLeptonH_vsPU_finalCuts_genMatched->Fill( cand.leptonIsoH/cand.leptonPtH, candidates->numPV, eventWeight_ );
        }
      }

      // Final selection
      // All cuts

      // Monitor cut flow for final selection cuts
      monitorCutFlow( finalCuts, eventWeight_ );

      if ( dileptonCuts_final_.passAllCuts( finalCuts ) ) {
        //
        // These candidates have passed all final selection criteria
        //
        histograms_.h_mass_finalCuts->Fill( mass, eventWeight_ );
//        histograms_.h_mt_finalCuts->Fill( cand.transverseMass, eventWeight_ );
        histograms_.h_Lxy_finalCuts->Fill( cand.decayLength, eventWeight_ );
        histograms_.h_nRecoPV_finalCuts->Fill(candidates->numPV, eventWeight_ );

        // Study efficiencies etc.

        // Study gen level info
        // Count number of correctly reconstructed candidates
        if ( isSignalMC_ ) storeNumberOfExoticsRECO( cand );

      }

      // Removed lifetime cuts
      // All cuts
      if ( dileptonCuts_removedLifetime_.passAllCuts( removedLifetimeCuts ) ) {
        histograms_.h_mass_removedLifetimeCuts->Fill( mass, eventWeight_ );
        histograms_.h_nRecoPV_removedLifetimeCuts->Fill( candidates->numPV, eventWeight_ );

        // Calculate different event weight with different pu weight
        double puP5weight = puweights_p5_.weight( candidates->nvtx_true );
        double puM5weight = puweights_m5_.weight( candidates->nvtx_true );
        histograms_.h_nRecoPV_p5_removedLifetimeCuts->Fill(candidates->numPV, puP5weight * weight_ );
        histograms_.h_nRecoPV_m5_removedLifetimeCuts->Fill(candidates->numPV, puM5weight * weight_ );

        histograms_.h_leptonLPt_removedLifetimeCuts->Fill( leptonL.pt, eventWeight_ );
        histograms_.h_leptonHPt_removedLifetimeCuts->Fill( leptonH.pt, eventWeight_ );
        histograms_.h_leptonLEta_removedLifetimeCuts->Fill( leptonL.eta, eventWeight_ );
        histograms_.h_leptonHEta_removedLifetimeCuts->Fill( leptonH.eta, eventWeight_ );
        histograms_.h_leptonLCaloMatchDeltaR_removedLifetimeCuts->Fill( leptonL.cmDeltaR, eventWeight_ );
        histograms_.h_leptonHCaloMatchDeltaR_removedLifetimeCuts->Fill( leptonH.cmDeltaR, eventWeight_ );
        histograms_.h_LxySig_removedLifetimeCuts->Fill( sign*cand.decayLengthSignificance*lxyScale_, eventWeight_ );
        histograms_.h_leptonAbsD0Sig_removedLifetimeCuts->Fill( std::min(leptonL.d0Significance,leptonH.d0Significance)*d0Scale_, eventWeight_ );
      }

      // n-1 (for isolation)
      DileptonAnalysisCuts::PassedWhichCuts removedLifetimeCutsTemp = removedLifetimeCuts;
      removedLifetimeCutsTemp.passIso = true;

      if ( dileptonCuts_removedLifetime_.passAllCuts( removedLifetimeCutsTemp ) ) {
        histograms_.h_nMinus1_isolationLeptonL_removedLifetimeCuts->Fill( cand.leptonIsoL, eventWeight_ );
        histograms_.h_nMinus1_isolationLeptonH_removedLifetimeCuts->Fill( cand.leptonIsoH, eventWeight_ );
        histograms_.h_nMinus1_relIsolationLeptonL_removedLifetimeCuts->Fill( cand.leptonIsoL/cand.leptonPtL, eventWeight_ );
        histograms_.h_nMinus1_relIsolationLeptonH_removedLifetimeCuts->Fill( cand.leptonIsoH/cand.leptonPtH, eventWeight_ );
      }

    } // cand loop
  } // event loop

  // Draw overflow of histograms_ in final bin
  histograms_.drawOverflows();

  // Save histograms_
  TString type("dummy");
  if ( anaType_==_2eTrack) type = "2eTrack";
  else if ( anaType_==_2muTrack ) type = "2muTrack";
  else if ( anaType_==_2globalMu ) type = "2globalMu";
  else if ( anaType_==_2trackerMu ) type = "2trackerMu";
  else if ( anaType_==_2saMu ) type = "2saMu";

  TString outputFileName("WeightedFiles/"+dirName_+"_weighted_"+type+".root");

  TFile outputFile(outputFileName, "RECREATE");
  outputFile.cd();


  histograms_.writeHistograms(outputFile);

  // Report cut flow
  reportCutFlow(outputFile);

  if ( isSignalMC_ ) {

    // Store signal efficiencies
    storeSignalEfficiencies(outputFile);

    // Report trigger info
    for ( unsigned int iTrig=0; iTrig < signalTriggers_.size(); iTrig++ ) {
      std::cout << "Trigger : " << signalTriggers_[iTrig].c_str() << " Number times fired : " << triggerFired_[iTrig] << std::endl;
    }
  }

  std::cout << "Writing and closing files" << std::endl;
  // Close file
  outputFile.Write();
  outputFile.Close();

  std::cout << "Deleting histograms" << std::endl;
  // Delete histograms
  histograms_.deleteHistograms();

}
Пример #16
0
int main (int argc, char *argv[]) {
    if(argc < 2) {
        ERR("usage: \n" << argv[0] << " <file.osm/.osm.bz2/.osm.pbf> [<profile.lua>]");
    }

    INFO("extracting data from input file " << argv[1]);
    bool isPBF(false);
    std::string outputFileName(argv[1]);
    std::string restrictionsFileName(argv[1]);
    std::string::size_type pos = outputFileName.find(".osm.bz2");
    if(pos==std::string::npos) {
        pos = outputFileName.find(".osm.pbf");
        if(pos!=std::string::npos) {
            isPBF = true;
        }
    }
    if(pos!=string::npos) {
        outputFileName.replace(pos, 8, ".osrm");
        restrictionsFileName.replace(pos, 8, ".osrm.restrictions");
    } else {
        pos=outputFileName.find(".osm");
        if(pos!=string::npos) {
            outputFileName.replace(pos, 5, ".osrm");
            restrictionsFileName.replace(pos, 5, ".osrm.restrictions");
        } else {
            outputFileName.append(".osrm");
            restrictionsFileName.append(".osrm.restrictions");
        }
    }

    /*** Setup Scripting Environment ***/

    // Create a new lua state
    lua_State *myLuaState = luaL_newstate();

    // Connect LuaBind to this lua state
    luabind::open(myLuaState);

    // Add our function to the state's global scope
    luabind::module(myLuaState) [
      luabind::def("print", LUA_print<std::string>),
      luabind::def("parseMaxspeed", parseMaxspeed),
      luabind::def("durationIsValid", durationIsValid),
      luabind::def("parseDuration", parseDuration)
    ];

    if(0 != luaL_dostring(
      myLuaState,
      "print('Initializing LUA engine')\n"
    )) {
        ERR(lua_tostring(myLuaState,-1)<< " occured in scripting block");
    }

    luabind::module(myLuaState) [
      luabind::class_<HashTable<std::string, std::string> >("keyVals")
      .def("Add", &HashTable<std::string, std::string>::Add)
      .def("Find", &HashTable<std::string, std::string>::Find)
    ];

    luabind::module(myLuaState) [
      luabind::class_<ImportNode>("Node")
          .def(luabind::constructor<>())
          .def_readwrite("lat", &ImportNode::lat)
          .def_readwrite("lon", &ImportNode::lon)
          .def_readwrite("id", &ImportNode::id)
          .def_readwrite("bollard", &ImportNode::bollard)
          .def_readwrite("traffic_light", &ImportNode::trafficLight)
          .def_readwrite("tags", &ImportNode::keyVals)
    ];

    luabind::module(myLuaState) [
      luabind::class_<_Way>("Way")
          .def(luabind::constructor<>())
          .def_readwrite("name", &_Way::name)
          .def_readwrite("speed", &_Way::speed)
          .def_readwrite("type", &_Way::type)
          .def_readwrite("access", &_Way::access)
          .def_readwrite("roundabout", &_Way::roundabout)
          .def_readwrite("is_duration_set", &_Way::isDurationSet)
          .def_readwrite("is_access_restricted", &_Way::isAccessRestricted)
          .def_readwrite("ignore_in_grid", &_Way::ignoreInGrid)
          .def_readwrite("tags", &_Way::keyVals)
          .def_readwrite("direction", &_Way::direction)
          .enum_("constants")
          [
           luabind::value("notSure", 0),
           luabind::value("oneway", 1),
           luabind::value("bidirectional", 2),
           luabind::value("opposite", 3)
          ]
    ];
    // Now call our function in a lua script
	INFO("Parsing speedprofile from " << (argc > 2 ? argv[2] : "profile.lua") );
    if(0 != luaL_dofile(myLuaState, (argc > 2 ? argv[2] : "profile.lua") )) {
        ERR(lua_tostring(myLuaState,-1)<< " occured in scripting block");
    }

    //open utility libraries string library;
    luaL_openlibs(myLuaState);

    /*** End of Scripting Environment Setup; ***/

    unsigned amountOfRAM = 1;
    unsigned installedRAM = GetPhysicalmemory(); 
    if(installedRAM < 2048264) {
        WARN("Machine has less than 2GB RAM.");
    }
/*    if(testDataFile("extractor.ini")) {
        ExtractorConfiguration extractorConfig("extractor.ini");
        unsigned memoryAmountFromFile = atoi(extractorConfig.GetParameter("Memory").c_str());
        if( memoryAmountFromFile != 0 && memoryAmountFromFile <= installedRAM/(1024*1024))
            amountOfRAM = memoryAmountFromFile;
        INFO("Using " << amountOfRAM << " GB of RAM for buffers");
    }
	*/
	
    StringMap stringMap;
    ExtractionContainers externalMemory;

    stringMap[""] = 0;
    extractCallBacks = new ExtractorCallbacks(&externalMemory, &stringMap);
    BaseParser<_Node, _RawRestrictionContainer, _Way> * parser;
    if(isPBF) {
        parser = new PBFParser(argv[1]);
    } else {
        parser = new XMLParser(argv[1]);
    }
    parser->RegisterCallbacks(&nodeFunction, &restrictionFunction, &wayFunction);
    parser->RegisterLUAState(myLuaState);

    if(!parser->Init())
        INFO("Parser not initialized!");
    parser->Parse();

    externalMemory.PrepareData(outputFileName, restrictionsFileName, amountOfRAM);

    stringMap.clear();
    delete parser;
    delete extractCallBacks;
    INFO("[extractor] finished.");
    std::cout << "\nRun:\n"
                   "./osrm-prepare " << outputFileName << " " << restrictionsFileName << std::endl;
    return 0;
}