<commit_before>//
//  TextureBuilder.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 08/03/2016.
//  Copyright © 2016 Thomas Harte. All rights reserved.
//

#include "TextureBuilder.hpp"
#include "CRTOpenGL.hpp"
#include "OpenGL.hpp"
#include <string.h>

using namespace Outputs::CRT;

static const GLint internalFormatForDepth(size_t depth)
{
	switch(depth)
	{
		default: return GL_FALSE;
		case 1: return GL_R8UI;
		case 2: return GL_RG8UI;
		case 3: return GL_RGB8UI;
		case 4: return GL_RGBA8UI;
	}
}

static const GLenum formatForDepth(size_t depth)
{
	switch(depth)
	{
		default: return GL_FALSE;
		case 1: return GL_RED_INTEGER;
		case 2: return GL_RG_INTEGER;
		case 3: return GL_RGB_INTEGER;
		case 4: return GL_RGBA_INTEGER;
	}
}

TextureBuilder::TextureBuilder(size_t bytes_per_pixel, GLenum texture_unit) :
	bytes_per_pixel_(bytes_per_pixel),
	write_areas_start_x_(0),
	write_areas_start_y_(0),
	is_full_(false),
	did_submit_(false)
{
	image_.resize(bytes_per_pixel * InputBufferBuilderWidth * InputBufferBuilderHeight);
	glGenTextures(1, &texture_name_);

	glActiveTexture(texture_unit);
	glBindTexture(GL_TEXTURE_2D, texture_name_);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexImage2D(GL_TEXTURE_2D, 0, internalFormatForDepth(bytes_per_pixel), InputBufferBuilderWidth, InputBufferBuilderHeight, 0, formatForDepth(bytes_per_pixel), GL_UNSIGNED_BYTE, nullptr);
}

TextureBuilder::~TextureBuilder()
{
	glDeleteTextures(1, &texture_name_);
}

inline uint8_t *TextureBuilder::pointer_to_location(uint16_t x, uint16_t y)
{
	return &image_[((y * InputBufferBuilderWidth) + x) * bytes_per_pixel_];
}

uint8_t *TextureBuilder::allocate_write_area(size_t required_length)
{
	if(is_full_) return nullptr;

	uint16_t starting_x, starting_y;

	if(!number_of_write_areas_)
	{
		starting_x = write_areas_start_x_;
		starting_y = write_areas_start_y_;
	}
	else
	{
		starting_x = write_areas_[number_of_write_areas_ - 1].x + write_areas_[number_of_write_areas_ - 1].length + 1;
		starting_y = write_areas_[number_of_write_areas_ - 1].y;
	}

	WriteArea next_write_area;
	if(starting_x + required_length + 2 > InputBufferBuilderWidth)
	{
		starting_x = 0;
		starting_y++;

		if(starting_y == InputBufferBuilderHeight)
		{
			is_full_ = true;
			return nullptr;
		}
	}

	next_write_area.x = starting_x + 1;
	next_write_area.y = starting_y;
	next_write_area.length = (uint16_t)required_length;
	if(number_of_write_areas_ < write_areas_.size())
		write_areas_[number_of_write_areas_] = next_write_area;
	else
		write_areas_.push_back(next_write_area);
	number_of_write_areas_++;

	return pointer_to_location(next_write_area.x, next_write_area.y);
}

bool TextureBuilder::is_full()
{
	return is_full_;
}

void TextureBuilder::reduce_previous_allocation_to(size_t actual_length)
{
	if(is_full_) return;

	WriteArea &write_area = write_areas_[number_of_write_areas_-1];
	write_area.length = (uint16_t)actual_length;

	// book end the allocation with duplicates of the first and last pixel, to protect
	// against rounding errors when this run is drawn
	uint8_t *start_pointer = pointer_to_location(write_area.x, write_area.y);
	memcpy(	&start_pointer[-bytes_per_pixel_],
			start_pointer,
			bytes_per_pixel_);

	memcpy(	&start_pointer[actual_length * bytes_per_pixel_],
			&start_pointer[(actual_length - 1) * bytes_per_pixel_],
			bytes_per_pixel_);
}

void TextureBuilder::submit()
{
	uint16_t height = write_areas_start_y_ + (write_areas_start_x_ ? 1 : 0);
	did_submit_ = true;

	glTexSubImage2D(	GL_TEXTURE_2D, 0,
						0, 0,
						InputBufferBuilderWidth, height,
						formatForDepth(bytes_per_pixel_), GL_UNSIGNED_BYTE,
						image_.data());
}

void TextureBuilder::flush(const std::function<void(const std::vector<WriteArea> &write_areas, size_t count)> &function)
{
	bool was_full = is_full_;
	if(did_submit_)
	{
		write_areas_start_y_ = write_areas_start_x_ = 0;
		is_full_ = false;
	}

	if(number_of_write_areas_ && !was_full)
	{
		if(write_areas_[0].x != write_areas_start_x_ || write_areas_[0].y != write_areas_start_y_)
		{
			for(auto write_area : write_areas_)
			{
				if(write_areas_start_x_ + write_area.length + 2 > InputBufferBuilderWidth)
				{
					write_areas_start_x_ = 0;
					write_areas_start_y_ ++;

					if(write_areas_start_y_ == InputBufferBuilderHeight)
					{
						is_full_ = true;
						break;
					}
				}

				memmove(
					pointer_to_location(write_areas_start_x_, write_areas_start_y_),
					pointer_to_location(write_area.x - 1, write_area.y),
					(write_area.length + 2) * bytes_per_pixel_);
				write_area.x = write_areas_start_x_ + 1;
				write_area.y = write_areas_start_y_;
			}
		}

		if(!is_full_)
			function(write_areas_, number_of_write_areas_);
	}

	did_submit_ = false;
	number_of_write_areas_ = 0;
}
<commit_msg>Missed an initialisation. Fixed!<commit_after>//
//  TextureBuilder.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 08/03/2016.
//  Copyright © 2016 Thomas Harte. All rights reserved.
//

#include "TextureBuilder.hpp"
#include "CRTOpenGL.hpp"
#include "OpenGL.hpp"
#include <string.h>

using namespace Outputs::CRT;

static const GLint internalFormatForDepth(size_t depth)
{
	switch(depth)
	{
		default: return GL_FALSE;
		case 1: return GL_R8UI;
		case 2: return GL_RG8UI;
		case 3: return GL_RGB8UI;
		case 4: return GL_RGBA8UI;
	}
}

static const GLenum formatForDepth(size_t depth)
{
	switch(depth)
	{
		default: return GL_FALSE;
		case 1: return GL_RED_INTEGER;
		case 2: return GL_RG_INTEGER;
		case 3: return GL_RGB_INTEGER;
		case 4: return GL_RGBA_INTEGER;
	}
}

TextureBuilder::TextureBuilder(size_t bytes_per_pixel, GLenum texture_unit) :
	bytes_per_pixel_(bytes_per_pixel),
	write_areas_start_x_(0),
	write_areas_start_y_(0),
	is_full_(false),
	did_submit_(false),
	number_of_write_areas_(0)
{
	image_.resize(bytes_per_pixel * InputBufferBuilderWidth * InputBufferBuilderHeight);
	glGenTextures(1, &texture_name_);

	glActiveTexture(texture_unit);
	glBindTexture(GL_TEXTURE_2D, texture_name_);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexImage2D(GL_TEXTURE_2D, 0, internalFormatForDepth(bytes_per_pixel), InputBufferBuilderWidth, InputBufferBuilderHeight, 0, formatForDepth(bytes_per_pixel), GL_UNSIGNED_BYTE, nullptr);
}

TextureBuilder::~TextureBuilder()
{
	glDeleteTextures(1, &texture_name_);
}

inline uint8_t *TextureBuilder::pointer_to_location(uint16_t x, uint16_t y)
{
	return &image_[((y * InputBufferBuilderWidth) + x) * bytes_per_pixel_];
}

uint8_t *TextureBuilder::allocate_write_area(size_t required_length)
{
	if(is_full_) return nullptr;

	uint16_t starting_x, starting_y;

	if(!number_of_write_areas_)
	{
		starting_x = write_areas_start_x_;
		starting_y = write_areas_start_y_;
	}
	else
	{
		starting_x = write_areas_[number_of_write_areas_ - 1].x + write_areas_[number_of_write_areas_ - 1].length + 1;
		starting_y = write_areas_[number_of_write_areas_ - 1].y;
	}

	WriteArea next_write_area;
	if(starting_x + required_length + 2 > InputBufferBuilderWidth)
	{
		starting_x = 0;
		starting_y++;

		if(starting_y == InputBufferBuilderHeight)
		{
			is_full_ = true;
			return nullptr;
		}
	}

	next_write_area.x = starting_x + 1;
	next_write_area.y = starting_y;
	next_write_area.length = (uint16_t)required_length;
	if(number_of_write_areas_ < write_areas_.size())
		write_areas_[number_of_write_areas_] = next_write_area;
	else
		write_areas_.push_back(next_write_area);
	number_of_write_areas_++;

	return pointer_to_location(next_write_area.x, next_write_area.y);
}

bool TextureBuilder::is_full()
{
	return is_full_;
}

void TextureBuilder::reduce_previous_allocation_to(size_t actual_length)
{
	if(is_full_) return;

	WriteArea &write_area = write_areas_[number_of_write_areas_-1];
	write_area.length = (uint16_t)actual_length;

	// book end the allocation with duplicates of the first and last pixel, to protect
	// against rounding errors when this run is drawn
	uint8_t *start_pointer = pointer_to_location(write_area.x, write_area.y);
	memcpy(	&start_pointer[-bytes_per_pixel_],
			start_pointer,
			bytes_per_pixel_);

	memcpy(	&start_pointer[actual_length * bytes_per_pixel_],
			&start_pointer[(actual_length - 1) * bytes_per_pixel_],
			bytes_per_pixel_);
}

void TextureBuilder::submit()
{
	uint16_t height = write_areas_start_y_ + (write_areas_start_x_ ? 1 : 0);
	did_submit_ = true;

	glTexSubImage2D(	GL_TEXTURE_2D, 0,
						0, 0,
						InputBufferBuilderWidth, height,
						formatForDepth(bytes_per_pixel_), GL_UNSIGNED_BYTE,
						image_.data());
}

void TextureBuilder::flush(const std::function<void(const std::vector<WriteArea> &write_areas, size_t count)> &function)
{
	bool was_full = is_full_;
	if(did_submit_)
	{
		write_areas_start_y_ = write_areas_start_x_ = 0;
		is_full_ = false;
	}

	if(number_of_write_areas_ && !was_full)
	{
		if(write_areas_[0].x != write_areas_start_x_ || write_areas_[0].y != write_areas_start_y_)
		{
			for(auto write_area : write_areas_)
			{
				if(write_areas_start_x_ + write_area.length + 2 > InputBufferBuilderWidth)
				{
					write_areas_start_x_ = 0;
					write_areas_start_y_ ++;

					if(write_areas_start_y_ == InputBufferBuilderHeight)
					{
						is_full_ = true;
						break;
					}
				}

				memmove(
					pointer_to_location(write_areas_start_x_, write_areas_start_y_),
					pointer_to_location(write_area.x - 1, write_area.y),
					(write_area.length + 2) * bytes_per_pixel_);
				write_area.x = write_areas_start_x_ + 1;
				write_area.y = write_areas_start_y_;
			}
		}

		if(!is_full_)
			function(write_areas_, number_of_write_areas_);
	}

	did_submit_ = false;
	number_of_write_areas_ = 0;
}
<|endoftext|>


<commit_before>/**
 * @file   AddTaskFMDELoss.C
 * @author Christian Holm Christensen <cholm@dalsgaard.hehi.nbi.dk>
 * @date   Wed Mar 23 12:14:03 2011
 *
 * @brief
 *
 *
 * @ingroup pwg2_forward_scripts_tasks
 */
/**
 * @defgroup pwg2_forward_eloss Energy Loss Fits
 * @ingroup pwg2_forward_topical
 */

/**
 * This is the macro to include the FMD energy fitter in a train.
 *
 * @ingroup pwg2_forward_eloss
 */
AliAnalysisTask*
AddTaskFMDELoss(Bool_t mc, Bool_t useCent)
{
  gSystem->Load("libPWG2forward2");

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

  // --- Make the task and add it to the manager ---------------------
  AliFMDEnergyFitterTask* task = new AliFMDEnergyFitterTask("fmdEnergyFitter");
  // task->SetBLow(blow);
  // task->SetBLow(bhigh);
  mgr->AddTask(task);

  // --- Set parameters on the algorithms ----------------------------
  // Set the number of SPD tracklets for which we consider the event a
  // low flux event
  task->GetEventInspector().SetLowFluxCut(1000);
  // Set the maximum error on v_z [cm]
  task->GetEventInspector().SetMaxVzErr(0.2);
  // Set the eta axis to use - note, this overrides whatever is used
  // by the rest of the algorithms - but only for the energy fitter
  // algorithm.
  task->GetEnergyFitter().SetEtaAxis(200, -4, 6);
  // Set maximum energy loss to consider
  task->GetEnergyFitter().SetMaxE(15);
  // Set number of energy loss bins
  task->GetEnergyFitter().SetNEbins(100);
  // Set whether to use increasing bin sizes
  task->GetEnergyFitter().SetUseIncreasingBins(true);
  // Set whether to do fit the energy distributions
  task->GetEnergyFitter().SetDoFits(kTRUE);
  // Set whether to make the correction object
  task->GetEnergyFitter().SetDoMakeObject(kTRUE);
  // Set the low cut used for energy
  task->GetEnergyFitter().SetLowCut(0.4);
  // Set the number of bins to subtract from maximum of distributions
  // to get the lower bound of the fit range
  task->GetEnergyFitter().SetFitRangeBinWidth(4);
  // Set the maximum number of landaus to try to fit (max 5)
  task->GetEnergyFitter().SetNParticles(5);
  // Set the minimum number of entries in the distribution before
  // trying to fit to the data
  task->GetEnergyFitter().SetMinEntries(1000);
  // --- Set limits on fits the energy -------------------------------
  // Maximum relative error on parameters
  AliFMDCorrELossFit::ELossFit::fgMaxRelError = .12;
  // Least weight to use
  AliFMDCorrELossFit::ELossFit::fgLeastWeight = 1e-5;
  // Maximum value of reduced chi^2
  AliFMDCorrELossFit::ELossFit::fgMaxChi2nu   = 10;

  // --- Make the output container and connect it --------------------
  TString outputfile = AliAnalysisManager::GetCommonFileName();
  // outputfile += ":PWG2forwardDnDeta";
  // Form(":%s",pars->GetDndetaAnalysisName());
  AliAnalysisDataContainer* histOut =
    mgr->CreateContainer("Forward", TList::Class(),
			 AliAnalysisManager::kOutputContainer,outputfile);
  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, histOut);

  return task;
}
<commit_msg>Bug fix<commit_after>/**
 * @file   AddTaskFMDELoss.C
 * @author Christian Holm Christensen <cholm@dalsgaard.hehi.nbi.dk>
 * @date   Wed Mar 23 12:14:03 2011
 *
 * @brief
 *
 *
 * @ingroup pwg2_forward_scripts_tasks
 */
/**
 * @defgroup pwg2_forward_eloss Energy Loss Fits
 * @ingroup pwg2_forward_topical
 */

/**
 * This is the macro to include the FMD energy fitter in a train.
 *
 * @ingroup pwg2_forward_eloss
 */
AliAnalysisTask*
AddTaskFMDELoss(Bool_t mc, Bool_t useCent)
{
  gSystem->Load("libPWG2forward2");

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

  // --- Make the task and add it to the manager ---------------------
  AliFMDEnergyFitterTask* task = new AliFMDEnergyFitterTask("fmdEnergyFitter");
  // task->SetBLow(blow);
  // task->SetBLow(bhigh);
  mgr->AddTask(task);

  // --- Set parameters on the algorithms ----------------------------
  // Set the number of SPD tracklets for which we consider the event a
  // low flux event
  task->GetEventInspector().SetLowFluxCut(1000);
  // Set the maximum error on v_z [cm]
  task->GetEventInspector().SetMaxVzErr(0.2);
  // Set the eta axis to use - note, this overrides whatever is used
  // by the rest of the algorithms - but only for the energy fitter
  // algorithm.
  task->GetEnergyFitter().SetEtaAxis(200, -4, 6);
  // Set maximum energy loss to consider
  task->GetEnergyFitter().SetMaxE(15);
  // Set number of energy loss bins
  task->GetEnergyFitter().SetNEbins(100);
  // Set whether to use increasing bin sizes
  task->GetEnergyFitter().SetUseIncreasingBins(true);
  // Set whether to do fit the energy distributions
  task->GetEnergyFitter().SetDoFits(kTRUE);
  // Set whether to make the correction object
  task->GetEnergyFitter().SetDoMakeObject(kTRUE);
  // Set the low cut used for energy
  task->GetEnergyFitter().SetLowCut(0.4);
  // Set the number of bins to subtract from maximum of distributions
  // to get the lower bound of the fit range
  task->GetEnergyFitter().SetFitRangeBinWidth(4);
  // Set the maximum number of landaus to try to fit (max 5)
  task->GetEnergyFitter().SetNParticles(5);
  // Set the minimum number of entries in the distribution before
  // trying to fit to the data
  task->GetEnergyFitter().SetMinEntries(1000);
  // --- Set limits on fits the energy -------------------------------
  // Maximum relative error on parameters
  AliFMDCorrELossFit::ELossFit::fgMaxRelError = .12;
  // Least weight to use
  AliFMDCorrELossFit::ELossFit::fgLeastWeight = 1e-5;
  // Maximum value of reduced chi^2
  AliFMDCorrELossFit::ELossFit::fgMaxChi2nu   = 10;

  // --- Make the output container and connect it --------------------
  TString outputfile = ;
  // outputfile += ":PWG2forwardDnDeta";
  // Form(":%s",pars->GetDndetaAnalysisName());
  AliAnalysisDataContainer* histOut =
    mgr->CreateContainer("Forward", TList::Class(),
			 AliAnalysisManager::kOutputContainer,
			 AliAnalysisManager::GetCommonFileName());
  AliAnalysisDataContainer *output =
    mgr->CreateContainer("ForwardResults", TList::Class(),
			 AliAnalysisManager::kParamContainer,
			 AliAnalysisManager::GetCommonFileName());
  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, histOut);
  mgr->ConnectOutput(task, 2, output);

  return task;
}
<|endoftext|>


<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)
#include "TString.h"
#include "TObjArray.h"

#include "AliLog.h"

#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"

#include "AliAnalysisTaskNonlinearFlow.h"
#endif

AliAnalysisTaskNonlinearFlow* AddTaskNonlinearFlow(
		Int_t		fFilterbit 		= 96,
		Double_t	fMinPt			= 0.2,
		Double_t	fMaxPt			= 3.0,
                Int_t           trigger                 = 0,
                Int_t           fSystFlag               = 0,
                TString         fPeriod                 = "LHC15o",
                TString         fNtrksName              = "Mult",
	        Bool_t		fNUA			= true,
	        Bool_t		fNUE 			= true,
		TString		uniqueID        	= ""
		)
{
        // The common parameters
	Double_t	fEtaCut 			= 0.8;
	Double_t	fVtxCut				= 10.0;
	Int_t		TPCclusters		        = 70;
	Double_t        chi2PerTPCcluster               = 10000;
	Int_t		fMinITSClus		        = 5;
	Double_t	fMaxChi2			= 2.5;
	Bool_t		fUseDCAzCut		        = false;
	Double_t	fDCAz				= 1.0;
	Bool_t		fUseDCAxyCut	                = false;
	Double_t	fDCAxy				= 0.2;
	Int_t		IsSample			= 10;
	Short_t		nCentFl				= 0;
	Bool_t		fLS				= false;

	// Creates a pid task and adds it to the analysis manager
	// Get the pointer to the existing analysis manager via the static
	//access method
	//=========================================================================
	AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
	if (!mgr) {
		Error("AddTaskNonlinearFlow.C", "No analysis manager to connect to.");
		return NULL;
	}

	// Check the analysis type using the event handlers connected to the
	// analysis manager The availability of MC handler can also be
	// checked here.
	// =========================================================================
	if (!mgr->GetInputEventHandler()) {
		Error("AddTaskNonLinearFlow.C", "This task requires an input event handler");
		return NULL;
	}

	// Create the task and configure it
	//========================================================================
	TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

	AliAnalysisTaskNonlinearFlow* taskFlowEp = new AliAnalysisTaskNonlinearFlow("taskFlowEp", fNUA, fNUE);
	taskFlowEp->SetDebugLevel(3);
	taskFlowEp->SetFilterbit(fFilterbit); // For systematics
	taskFlowEp->SetFilterbitDefault(fFilterbit);
	taskFlowEp->SetEtaCut(fEtaCut);
	taskFlowEp->SetVtxCut(fVtxCut); // For systematics
	taskFlowEp->SetVtxCutDefault(fVtxCut);
	taskFlowEp->SetMinPt(fMinPt);
	taskFlowEp->SetMaxPt(fMaxPt);
	taskFlowEp->SetTPCclusters(TPCclusters); // For systematics
	taskFlowEp->SetTPCclustersDefault(TPCclusters);
	taskFlowEp->SetChi2PerTPCcluster(chi2PerTPCcluster); // max. chi2 per TPC cluster
	taskFlowEp->SetMinITSClusters(fMinITSClus);
	taskFlowEp->SetMaxChi2(fMaxChi2);
	taskFlowEp->SetUseDCAzCut(fUseDCAzCut);
	taskFlowEp->SetDCAzCut(fDCAz); // For systematics
	taskFlowEp->SetDCAzCutDefault(fDCAz);
	taskFlowEp->SetUseDCAxyCut(fUseDCAxyCut);
	taskFlowEp->SetDCAxyCut(fDCAxy); // For systematics
	taskFlowEp->SetDCAxyCutDefault(fDCAxy);
	taskFlowEp->SetIsSample(IsSample);
	taskFlowEp->SetCentFlag(nCentFl);
	taskFlowEp->SetTrigger(trigger);
	taskFlowEp->SetLSFlag(fLS);
	taskFlowEp->SetNUEFlag(fNUE);
	taskFlowEp->SetNUA(fNUA);
	taskFlowEp->SetNtrksName(fNtrksName);
        taskFlowEp->SetSystFlag(fSystFlag);

        taskFlowEp->SetUseWeigthsRunByRun(false);
        taskFlowEp->SetUsePeriodWeigths(false);
        taskFlowEp->SetUseWeights3D(false);

	//....
	taskFlowEp->SetPeriod(fPeriod);
	mgr->AddTask(taskFlowEp);

	// 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 fileName = AliAnalysisManager::GetCommonFileName();
	//fileName+=suffixName;
	AliAnalysisDataContainer* cinput = mgr->GetCommonInputContainer();
	AliAnalysisDataContainer *cout_hist = mgr->CreateContainer(Form("QA_%s", uniqueID.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("AnalysisResults.root:%s", uniqueID.Data()));
	mgr->ConnectInput (taskFlowEp, 0, cinput);
	mgr->ConnectOutput(taskFlowEp, 1, cout_hist);
	AliAnalysisDataContainer *physics_hist = mgr->CreateContainer(Form("output_%s", uniqueID.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("AnalysisResults.root:%s", uniqueID.Data()));
	mgr->ConnectOutput(taskFlowEp, 2, physics_hist);
        int outSlotCounter=2;
        for (int i = 0; i < 30; i++) {
            outSlotCounter++;
	    AliAnalysisDataContainer *physics_hist_i = mgr->CreateContainer(Form("output_%s_%d", uniqueID.Data(), i), TList::Class(), AliAnalysisManager::kOutputContainer, Form("AnalysisResults.root:%s", uniqueID.Data()));
	    mgr->ConnectOutput(taskFlowEp, outSlotCounter, physics_hist_i);
        }

	Int_t inSlotCounter=1;
	TGrid::Connect("alien:");

        TObjArray *AllContainers = mgr->GetContainers();
	if(fNUA) {

                if(!AllContainers->FindObject("NUA")) {

		AliAnalysisDataContainer *cin_NUA = mgr->CreateContainer(Form("NUA"), TList::Class(), AliAnalysisManager::kInputContainer);
                TFile *inNUA;

                if (fPeriod.EqualTo("LHC15o")) {
			inNUA = TFile::Open("alien:///alice/cern.ch/user/m/mzhao/Weights/NUA/WeightsPbPb15o.root");
			taskFlowEp->SetUseWeigthsRunByRun(true);
                } else if (fPeriod.EqualTo("LHC15oKatarina")) {
			inNUA = TFile::Open("alien:///alice/cern.ch/user/m/mzhao/Weights/NUA/PhiWeight_Katarina.root");
			taskFlowEp->SetUseWeigthsRunByRun(true);
                } else if (fPeriod.EqualTo("LHC17")) {
	            taskFlowEp->SetUsePeriodWeigths(true);
                    if (trigger == 0) {
                        inNUA = TFile::Open("alien:///alice/cern.ch/user/z/zumoravc/weights/pp_LHC17/weights_LHC17_MB_periods.root");
                    } else {
			inNUA = TFile::Open("alien:///alice/cern.ch/user/m/mzhao/Weights/NUA/Weights_pp17.root");
			taskFlowEp->SetUseWeigthsRunByRun(true);
                    }
                } else if (fPeriod.EqualTo("LHC15i")) {
	            taskFlowEp->SetUsePeriodWeigths(true);
		    if (trigger == 0) {
                        inNUA = TFile::Open("alien:///alice/cern.ch/user/z/zumoravc/weights/pp_LHC15/weights_LHC15i_MB.root");
                    } else {
                        inNUA = TFile::Open("alien:///alice/cern.ch/user/z/zumoravc/weights/pp_LHC15/weights_LHC15i_HM.root");
                    }
                } else if (fPeriod.EqualTo("LHC15l")) {
	            taskFlowEp->SetUsePeriodWeigths(true);
		    if (trigger == 0) {
                        inNUA = TFile::Open("alien:///alice/cern.ch/user/z/zumoravc/weights/pp_LHC15/weights_LHC15l_MB.root");
                    } else {
                        inNUA = TFile::Open("alien:///alice/cern.ch/user/z/zumoravc/weights/pp_LHC15/weights_LHC15l_HM.root");
                    }
                } else if (fPeriod.EqualTo("LHC16")) {
	            taskFlowEp->SetUsePeriodWeigths(true);
		    if (trigger == 0) {
                        inNUA = TFile::Open("alien:///alice/cern.ch/user/z/zumoravc/weights/pp_LHC16/weights_LHC16_MB_periods.root");
                    } else {
			inNUA = TFile::Open("alien:///alice/cern.ch/user/m/mzhao/Weights/NUA/Weights_pp16.root");
			taskFlowEp->SetUseWeigthsRunByRun(true);
                    }
                } else if (fPeriod.EqualTo("LHC18")) {
	            taskFlowEp->SetUsePeriodWeigths(true);
		    if (trigger == 0) {
                        inNUA = TFile::Open("alien:///alice/cern.ch/user/z/zumoravc/weights/pp_LHC18/weights_LHC18_MB_periods.root");
                    } else {
			inNUA = TFile::Open("alien:///alice/cern.ch/user/m/mzhao/Weights/NUA/Weights_pp18.root");
			taskFlowEp->SetUseWeigthsRunByRun(true);
                    }
                }

                TList* weight_list = NULL;
		if (fPeriod.EqualTo("LHC15oKatarina")) {
		    weight_list = dynamic_cast<TList*>(inNUA->Get("weightList"));
                    cin_NUA->SetData(weight_list);
                } else {
		    weight_list = dynamic_cast<TList*>(inNUA->Get("WeightList"));
		    cin_NUA->SetData(weight_list);
                }
		mgr->ConnectInput(taskFlowEp,inSlotCounter,cin_NUA);
		inSlotCounter++;
		} else {
		    mgr->ConnectInput(taskFlowEp,inSlotCounter,(AliAnalysisDataContainer*)AllContainers->FindObject("NUA"));
		    inSlotCounter++;
		    printf("NUA already loaded\n");
		}
	}

	if(fNUE) {

                if(!AllContainers->FindObject("NUE")) {
                TFile *inNUE = NULL;

		AliAnalysisDataContainer *cin_NUE = mgr->CreateContainer(Form("NUE"), TList::Class(), AliAnalysisManager::kInputContainer);
                if (fPeriod.EqualTo("LHC15o")) {
			inNUE = TFile::Open("alien:///alice/cern.ch/user/m/mzhao/Weights/NUE/LHC18e1_MBEff_FD_wSyst_v2.root");
			taskFlowEp->SetUseWeigthsRunByRun(true);
                } else if (fPeriod.EqualTo("LHC15oKatarina")) {
			inNUE = TFile::Open("alien:///alice/cern.ch/user/m/mzhao/Weights/NUE/TrackingEfficiency_Katarina.root");
			taskFlowEp->SetUseWeigthsRunByRun(true);
                } else {
			inNUE = TFile::Open("alien:///alice/cern.ch/user/m/mzhao/Weights/NUE/LHC17d20a1_WithModEff_Syst.root");
			taskFlowEp->SetUseWeigthsRunByRun(true);
		}

		if(!inNUE) {
			printf("Could not open efficiency file!\n");
			return 0;
		}
                TList* weight_list = NULL;
                if (fPeriod.EqualTo("LHC15oKatarina")) {
		    weight_list = dynamic_cast<TList*>(inNUE->Get("weightList"));
		    cin_NUE->SetData(weight_list);
                } else {
		    weight_list = dynamic_cast<TList*>(inNUE->Get("EffAndFD"));
		    cin_NUE->SetData(weight_list);
                }
		mgr->ConnectInput(taskFlowEp,inSlotCounter,cin_NUE);
		inSlotCounter++;
           	} else {
		    mgr->ConnectInput(taskFlowEp,inSlotCounter,(AliAnalysisDataContainer*)AllContainers->FindObject("NUA"));
		    inSlotCounter++;
		    printf("NUA already loaded\n");
		}

	}

	// Return task pointer at the end
	return taskFlowEp;
}
//
// EOF
//
<commit_msg>fix a bug<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)
#include "TString.h"
#include "TObjArray.h"

#include "AliLog.h"

#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"

#include "AliAnalysisTaskNonlinearFlow.h"
#endif

AliAnalysisTaskNonlinearFlow* AddTaskNonlinearFlow(
		Int_t		fFilterbit 		= 96,
		Double_t	fMinPt			= 0.2,
		Double_t	fMaxPt			= 3.0,
                Int_t           trigger                 = 0,
                Int_t           fSystFlag               = 0,
                TString         fPeriod                 = "LHC15o",
                TString         fNtrksName              = "Mult",
	        Bool_t		fNUA			= true,
	        Bool_t		fNUE 			= true,
		TString		uniqueID        	= ""
		)
{
        // The common parameters
	Double_t	fEtaCut 			= 0.8;
	Double_t	fVtxCut				= 10.0;
	Int_t		TPCclusters		        = 70;
	Double_t        chi2PerTPCcluster               = 10000;
	Int_t		fMinITSClus		        = 5;
	Double_t	fMaxChi2			= 2.5;
	Bool_t		fUseDCAzCut		        = false;
	Double_t	fDCAz				= 1.0;
	Bool_t		fUseDCAxyCut	                = false;
	Double_t	fDCAxy				= 0.2;
	Int_t		IsSample			= 10;
	Short_t		nCentFl				= 0;
	Bool_t		fLS				= false;

	// Creates a pid task and adds it to the analysis manager
	// Get the pointer to the existing analysis manager via the static
	//access method
	//=========================================================================
	AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
	if (!mgr) {
		Error("AddTaskNonlinearFlow.C", "No analysis manager to connect to.");
		return NULL;
	}

	// Check the analysis type using the event handlers connected to the
	// analysis manager The availability of MC handler can also be
	// checked here.
	// =========================================================================
	if (!mgr->GetInputEventHandler()) {
		Error("AddTaskNonLinearFlow.C", "This task requires an input event handler");
		return NULL;
	}

	// Create the task and configure it
	//========================================================================
	TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

	AliAnalysisTaskNonlinearFlow* taskFlowEp = new AliAnalysisTaskNonlinearFlow("taskFlowEp", fNUA, fNUE);
	taskFlowEp->SetDebugLevel(3);
	taskFlowEp->SetFilterbit(fFilterbit); // For systematics
	taskFlowEp->SetFilterbitDefault(fFilterbit);
	taskFlowEp->SetEtaCut(fEtaCut);
	taskFlowEp->SetVtxCut(fVtxCut); // For systematics
	taskFlowEp->SetVtxCutDefault(fVtxCut);
	taskFlowEp->SetMinPt(fMinPt);
	taskFlowEp->SetMaxPt(fMaxPt);
	taskFlowEp->SetTPCclusters(TPCclusters); // For systematics
	taskFlowEp->SetTPCclustersDefault(TPCclusters);
	taskFlowEp->SetChi2PerTPCcluster(chi2PerTPCcluster); // max. chi2 per TPC cluster
	taskFlowEp->SetMinITSClusters(fMinITSClus);
	taskFlowEp->SetMaxChi2(fMaxChi2);
	taskFlowEp->SetUseDCAzCut(fUseDCAzCut);
	taskFlowEp->SetDCAzCut(fDCAz); // For systematics
	taskFlowEp->SetDCAzCutDefault(fDCAz);
	taskFlowEp->SetUseDCAxyCut(fUseDCAxyCut);
	taskFlowEp->SetDCAxyCut(fDCAxy); // For systematics
	taskFlowEp->SetDCAxyCutDefault(fDCAxy);
	taskFlowEp->SetIsSample(IsSample);
	taskFlowEp->SetCentFlag(nCentFl);
	taskFlowEp->SetTrigger(trigger);
	taskFlowEp->SetLSFlag(fLS);
	taskFlowEp->SetNUEFlag(fNUE);
	taskFlowEp->SetNUA(fNUA);
	taskFlowEp->SetNtrksName(fNtrksName);
        taskFlowEp->SetSystFlag(fSystFlag);

        taskFlowEp->SetUseWeigthsRunByRun(false);
        taskFlowEp->SetUsePeriodWeigths(false);
        taskFlowEp->SetUseWeights3D(false);

	//....
	taskFlowEp->SetPeriod(fPeriod);
	mgr->AddTask(taskFlowEp);

	// 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 fileName = AliAnalysisManager::GetCommonFileName();
	//fileName+=suffixName;
	AliAnalysisDataContainer* cinput = mgr->GetCommonInputContainer();
	AliAnalysisDataContainer *cout_hist = mgr->CreateContainer(Form("QA_%s", uniqueID.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("AnalysisResults.root:%s", uniqueID.Data()));
	mgr->ConnectInput (taskFlowEp, 0, cinput);
	mgr->ConnectOutput(taskFlowEp, 1, cout_hist);
	AliAnalysisDataContainer *physics_hist = mgr->CreateContainer(Form("output_%s", uniqueID.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("AnalysisResults.root:%s", uniqueID.Data()));
	mgr->ConnectOutput(taskFlowEp, 2, physics_hist);
        int outSlotCounter=2;
        for (int i = 0; i < 30; i++) {
            outSlotCounter++;
	    AliAnalysisDataContainer *physics_hist_i = mgr->CreateContainer(Form("output_%s_%d", uniqueID.Data(), i), TList::Class(), AliAnalysisManager::kOutputContainer, Form("AnalysisResults.root:%s", uniqueID.Data()));
	    mgr->ConnectOutput(taskFlowEp, outSlotCounter, physics_hist_i);
        }

	Int_t inSlotCounter=1;
	TGrid::Connect("alien:");

        TObjArray *AllContainers = mgr->GetContainers();
	if(fNUA) {

                if(!AllContainers->FindObject("NUA")) {

		AliAnalysisDataContainer *cin_NUA = mgr->CreateContainer(Form("NUA"), TList::Class(), AliAnalysisManager::kInputContainer);
                TFile *inNUA;

                if (fPeriod.EqualTo("LHC15o")) {
			inNUA = TFile::Open("alien:///alice/cern.ch/user/m/mzhao/Weights/NUA/WeightsPbPb15o.root");
			taskFlowEp->SetUseWeigthsRunByRun(true);
                } else if (fPeriod.EqualTo("LHC15oKatarina")) {
			inNUA = TFile::Open("alien:///alice/cern.ch/user/m/mzhao/Weights/NUA/PhiWeight_Katarina.root");
			taskFlowEp->SetUseWeigthsRunByRun(true);
                } else if (fPeriod.EqualTo("LHC17")) {
	            taskFlowEp->SetUsePeriodWeigths(true);
                    if (trigger == 0) {
                        inNUA = TFile::Open("alien:///alice/cern.ch/user/z/zumoravc/weights/pp_LHC17/weights_LHC17_MB_periods.root");
                    } else {
			inNUA = TFile::Open("alien:///alice/cern.ch/user/m/mzhao/Weights/NUA/Weights_pp17.root");
			taskFlowEp->SetUseWeigthsRunByRun(true);
                    }
                } else if (fPeriod.EqualTo("LHC15i")) {
	            taskFlowEp->SetUsePeriodWeigths(true);
		    if (trigger == 0) {
                        inNUA = TFile::Open("alien:///alice/cern.ch/user/z/zumoravc/weights/pp_LHC15/weights_LHC15i_MB.root");
                    } else {
                        inNUA = TFile::Open("alien:///alice/cern.ch/user/z/zumoravc/weights/pp_LHC15/weights_LHC15i_HM.root");
                    }
                } else if (fPeriod.EqualTo("LHC15l")) {
	            taskFlowEp->SetUsePeriodWeigths(true);
		    if (trigger == 0) {
                        inNUA = TFile::Open("alien:///alice/cern.ch/user/z/zumoravc/weights/pp_LHC15/weights_LHC15l_MB.root");
                    } else {
                        inNUA = TFile::Open("alien:///alice/cern.ch/user/z/zumoravc/weights/pp_LHC15/weights_LHC15l_HM.root");
                    }
                } else if (fPeriod.EqualTo("LHC16")) {
	            taskFlowEp->SetUsePeriodWeigths(true);
		    if (trigger == 0) {
                        inNUA = TFile::Open("alien:///alice/cern.ch/user/z/zumoravc/weights/pp_LHC16/weights_LHC16_MB_periods.root");
                    } else {
			inNUA = TFile::Open("alien:///alice/cern.ch/user/m/mzhao/Weights/NUA/Weights_pp16.root");
			taskFlowEp->SetUseWeigthsRunByRun(true);
                    }
                } else if (fPeriod.EqualTo("LHC18")) {
	            taskFlowEp->SetUsePeriodWeigths(true);
		    if (trigger == 0) {
                        inNUA = TFile::Open("alien:///alice/cern.ch/user/z/zumoravc/weights/pp_LHC18/weights_LHC18_MB_periods.root");
                    } else {
			inNUA = TFile::Open("alien:///alice/cern.ch/user/m/mzhao/Weights/NUA/Weights_pp18.root");
			taskFlowEp->SetUseWeigthsRunByRun(true);
                    }
                }

                TList* weight_list = NULL;
		if (fPeriod.EqualTo("LHC15oKatarina")) {
		    weight_list = dynamic_cast<TList*>(inNUA->Get("weightList"));
                    cin_NUA->SetData(weight_list);
                } else {
		    weight_list = dynamic_cast<TList*>(inNUA->Get("WeightList"));
		    cin_NUA->SetData(weight_list);
                }
		mgr->ConnectInput(taskFlowEp,inSlotCounter,cin_NUA);
		inSlotCounter++;
		} else {
		    mgr->ConnectInput(taskFlowEp,inSlotCounter,(AliAnalysisDataContainer*)AllContainers->FindObject("NUA"));
		    inSlotCounter++;
		    printf("NUA already loaded\n");
		}
	}

	if(fNUE) {

                if(!AllContainers->FindObject("NUE")) {
                TFile *inNUE = NULL;

		AliAnalysisDataContainer *cin_NUE = mgr->CreateContainer(Form("NUE"), TList::Class(), AliAnalysisManager::kInputContainer);
                if (fPeriod.EqualTo("LHC15o")) {
			inNUE = TFile::Open("alien:///alice/cern.ch/user/m/mzhao/Weights/NUE/LHC18e1_MBEff_FD_wSyst_v2.root");
			taskFlowEp->SetUseWeigthsRunByRun(true);
                } else if (fPeriod.EqualTo("LHC15oKatarina")) {
			inNUE = TFile::Open("alien:///alice/cern.ch/user/m/mzhao/Weights/NUE/TrackingEfficiency_Katarina.root");
			taskFlowEp->SetUseWeigthsRunByRun(true);
                } else {
			inNUE = TFile::Open("alien:///alice/cern.ch/user/m/mzhao/Weights/NUE/LHC17d20a1_WithModEff_Syst.root");
			taskFlowEp->SetUseWeigthsRunByRun(true);
		}

		if(!inNUE) {
			printf("Could not open efficiency file!\n");
			return 0;
		}
                TList* weight_list = NULL;
                if (fPeriod.EqualTo("LHC15oKatarina")) {
		    weight_list = dynamic_cast<TList*>(inNUE->Get("weightList"));
		    cin_NUE->SetData(weight_list);
                } else {
		    weight_list = dynamic_cast<TList*>(inNUE->Get("EffAndFD"));
		    cin_NUE->SetData(weight_list);
                }
		mgr->ConnectInput(taskFlowEp,inSlotCounter,cin_NUE);
		inSlotCounter++;
           	} else {
		    mgr->ConnectInput(taskFlowEp,inSlotCounter,(AliAnalysisDataContainer*)AllContainers->FindObject("NUE"));
		    inSlotCounter++;
		    printf("NUE already loaded\n");
		}

	}

	// Return task pointer at the end
	return taskFlowEp;
}
//
// EOF
//
<|endoftext|>


<commit_before>#include "graph.hpp"
#include <stack>
#include <queue>

using namespace std;

shared_ptr<Vertex> Graph::getVertex(std::string name) {
  auto it = this->vertices.begin();
  for (; it != this->vertices.end(); it++) {
    if ((*it)->getName() == name) break;
  }
  return (it != this->vertices.end()) ? *it : nullptr;

}

Graph::Graph(vector<tuple<string, int>> vertices,
	     vector<tuple<string, string, int>> edges,
	     bool directed=false) {

  this->directed = directed; 	// Is the graph directed?

  // Build the vertices
  for (auto it = vertices.begin(); it != vertices.end(); it++)
    this->vertices.push_back(make_shared<Vertex>(get<1>(*it), get<0>(*it)));

  vector<shared_ptr<Edge>> gedges;
  for (auto it = edges.begin(); it != edges.end(); it++)
    this->edges.push_back(make_shared<Edge>(get<2>(*it),
				       Graph::getVertex(get<0>(*it)),
				       Graph::getVertex(get<1>(*it))));
  // Now make the alist for the vertices
  for (auto it = this->vertices.begin(); it != this->vertices.end(); it++) {
    vector<shared_ptr<Edge>> ie;
    for (auto eit = this->edges.begin(); eit != this->edges.end(); eit++) {
      if ((*it)->getName() == (*eit)->second()->getName()
	  || (*it)->getName() == (*eit)->first()->getName())
	ie.push_back(*eit);
	// (*it)->getIEdges().push_back(*eit);
    }
    (*it)->setIEdges(ie);
    // cout << "name: " << (*it)->getName() << " " << (*it)->getIEdges().size() << endl;
  }
}

shared_ptr<Vertex> Edge::opposite(string v) {
  if (v == this->first()->getName())
    return this->second();
  else return this->first();
}

vector<shared_ptr<Vertex>> Vertex::neighbors() {
  vector<shared_ptr<Vertex>> ret;
  for (auto it = this->incidentEdges.begin(); it != this->incidentEdges.end(); it++) {
    ret.push_back((*it)->opposite(this->getName()));
  }
  return ret;
}

void print(shared_ptr<Vertex> v) {
  cout << " name: " << v->getName() << endl;
}

// DFS for the graph with a function.
template <void (*fun)(shared_ptr<Vertex>)>
static void doDFS(Graph g, shared_ptr<Vertex> start) {
  stack<shared_ptr<Vertex>> s;
  s.push(start);

  do
    {
      // First get all the neighbors
      shared_ptr<Vertex> n = s.top();
      // Print the name of the node
      fun(n);
      s.pop(); 			// Very bad stack interface of C++!
      n->setVisited(true);
      vector<shared_ptr<Vertex>> vns = n->neighbors();
      for (auto it = vns.begin(); it != vns.end(); it++) {
	if (!(*it)->getVisited()) {
	  s.push(*it);
	  (*it)->setVisited(true);
	}
      }
    } while (!s.empty());

  g.resetVisited();
}

// Topological sort in a directed graph
template<void (*fun)(shared_ptr<Vertex>)>
static void topological_sort(Graph g) {
  // First make the degree for the vertex.
  queue<shared_ptr<Vertex>> start_vertices;
  vector<shared_ptr<Vertex>> mvertices = g.getVertices();
  for (auto it = mvertices.begin(); it != mvertices.end(); ++it) {
    vector<shared_ptr<Edge>> ves = (*it)->getIEdges();
    for (auto eit = ves.begin(); eit != ves.end(); ++eit) {
      // Increment your degree if you are the second in the incidentedge
      if ((*eit)->second()->getName() == (*it)->getName())
	(*it)->degree += 1;
    }
    if ((*it)->degree == 0) start_vertices.push(g.getVertex((*it)->getName()));
  }
  do
    {
      // Process vertices
      shared_ptr<Vertex> el = start_vertices.front();
      start_vertices.pop(); 	// C++'s horrible API!
      fun(el);
      // We can call the function on the damn element.

      // Get all its neighbors and if their degree is 0, then push
      // them onto the queue.
      vector<shared_ptr<Vertex>> eln = el->neighbors();
      for (auto it = eln.begin(); it != eln.end(); ++it) {
	(*it)->degree -= 1;
	if ((*it)->degree == 0) start_vertices.push(*it);
      }
    } while (!start_vertices.empty());

  // Now we can start going through and doing the actual topological sort.
}

// TODO: shortest path and MST together

int main(void)
{
  // Test program.
  vector<tuple<string, int>> vertices = {make_tuple("a", 1), make_tuple("b", 2),
					 make_tuple("c", 3), make_tuple("d", 4)};
  vector<tuple<string, string, int>> edges = {make_tuple("a", "b", 5), make_tuple("a", "c", 1),
					      make_tuple("a", "d", 4), make_tuple("c", "d", 2),
					      make_tuple("d", "b", 3)};

  // This is the graph.
  Graph g(vertices, edges, false);
  vector<shared_ptr<Vertex>> mv = g.getVertices();

  // // Just checking the ref-count.
  // for (auto it = mv.begin(); it != mv.end(); ++it) {
  //   cout << (*it).use_count() << endl;
  // }
  // Print the graph using dfs and a lambda
  cout  << "DFS" << endl;
  doDFS<print>(g, g.getVertex("a"));

  // Do topological sort, if it works.
  cout  << "Topological sort" << endl;
  topological_sort<print>(g);

  // // Just checking the ref-count.
  for (auto it = mv.begin(); it != mv.end(); ++it) {
    cout << (*it).use_count() << endl;
  }

  return 0;
}

<commit_msg>Using lambdas.<commit_after>#include "graph.hpp"
#include <stack>
#include <queue>

using namespace std;

shared_ptr<Vertex> Graph::getVertex(std::string name) {
  auto it = this->vertices.begin();
  for (; it != this->vertices.end(); it++) {
    if ((*it)->getName() == name) break;
  }
  return (it != this->vertices.end()) ? *it : nullptr;

}

Graph::Graph(vector<tuple<string, int>> vertices,
	     vector<tuple<string, string, int>> edges,
	     bool directed=false) {

  this->directed = directed; 	// Is the graph directed?

  // Build the vertices
  for (auto it = vertices.begin(); it != vertices.end(); it++)
    this->vertices.push_back(make_shared<Vertex>(get<1>(*it), get<0>(*it)));

  vector<shared_ptr<Edge>> gedges;
  for (auto it = edges.begin(); it != edges.end(); it++)
    this->edges.push_back(make_shared<Edge>(get<2>(*it),
				       Graph::getVertex(get<0>(*it)),
				       Graph::getVertex(get<1>(*it))));
  // Now make the alist for the vertices
  for (auto it = this->vertices.begin(); it != this->vertices.end(); it++) {
    vector<shared_ptr<Edge>> ie;
    for (auto eit = this->edges.begin(); eit != this->edges.end(); eit++) {
      if ((*it)->getName() == (*eit)->second()->getName()
	  || (*it)->getName() == (*eit)->first()->getName())
	ie.push_back(*eit);
	// (*it)->getIEdges().push_back(*eit);
    }
    (*it)->setIEdges(ie);
    // cout << "name: " << (*it)->getName() << " " << (*it)->getIEdges().size() << endl;
  }
}

shared_ptr<Vertex> Edge::opposite(string v) {
  if (v == this->first()->getName())
    return this->second();
  else return this->first();
}

vector<shared_ptr<Vertex>> Vertex::neighbors() {
  vector<shared_ptr<Vertex>> ret;
  for (auto it = this->incidentEdges.begin(); it != this->incidentEdges.end(); it++) {
    ret.push_back((*it)->opposite(this->getName()));
  }
  return ret;
}

void print(shared_ptr<Vertex> v) {
  cout << " name: " << v->getName() << endl;
}

// DFS for the graph with a function.
template<typename F>
static void doDFS(Graph g, shared_ptr<Vertex> start, F fun) {
  stack<shared_ptr<Vertex>> s;
  s.push(start);

  do
    {
      // First get all the neighbors
      shared_ptr<Vertex> n = s.top();
      // Print the name of the node
      fun(n);
      s.pop(); 			// Very bad stack interface of C++!
      n->setVisited(true);
      vector<shared_ptr<Vertex>> vns = n->neighbors();
      for (auto it = vns.begin(); it != vns.end(); it++) {
	if (!(*it)->getVisited()) {
	  s.push(*it);
	  (*it)->setVisited(true);
	}
      }
    } while (!s.empty());

  g.resetVisited();
}

// Topological sort in a directed graph
template<void (*fun)(shared_ptr<Vertex>)>
static void topological_sort(Graph g) {
  // First make the degree for the vertex.
  queue<shared_ptr<Vertex>> start_vertices;
  vector<shared_ptr<Vertex>> mvertices = g.getVertices();
  for (auto it = mvertices.begin(); it != mvertices.end(); ++it) {
    vector<shared_ptr<Edge>> ves = (*it)->getIEdges();
    for (auto eit = ves.begin(); eit != ves.end(); ++eit) {
      // Increment your degree if you are the second in the incidentedge
      if ((*eit)->second()->getName() == (*it)->getName())
	(*it)->degree += 1;
    }
    if ((*it)->degree == 0) start_vertices.push(g.getVertex((*it)->getName()));
  }
  do
    {
      // Process vertices
      shared_ptr<Vertex> el = start_vertices.front();
      start_vertices.pop(); 	// C++'s horrible API!
      fun(el);
      // We can call the function on the damn element.

      // Get all its neighbors and if their degree is 0, then push
      // them onto the queue.
      vector<shared_ptr<Vertex>> eln = el->neighbors();
      for (auto it = eln.begin(); it != eln.end(); ++it) {
	(*it)->degree -= 1;
	if ((*it)->degree == 0) start_vertices.push(*it);
      }
    } while (!start_vertices.empty());

  // Now we can start going through and doing the actual topological sort.
}

// TODO: shortest path and MST together

int main(void)
{
  // Test program.
  vector<tuple<string, int>> vertices = {make_tuple("a", 1), make_tuple("b", 2),
					 make_tuple("c", 3), make_tuple("d", 4)};
  vector<tuple<string, string, int>> edges = {make_tuple("a", "b", 5), make_tuple("a", "c", 1),
					      make_tuple("a", "d", 4), make_tuple("c", "d", 2),
					      make_tuple("d", "b", 3)};

  // This is the graph.
  Graph g(vertices, edges, false);
  vector<shared_ptr<Vertex>> mv = g.getVertices();

  // // Just checking the ref-count.
  // for (auto it = mv.begin(); it != mv.end(); ++it) {
  //   cout << (*it).use_count() << endl;
  // }
  // Print the graph using dfs and a lambda
  cout  << "DFS" << endl;
  // Here lambda is most likely not inlined.
  doDFS(g, g.getVertex("a"), [](shared_ptr<Vertex> x) -> void {cout << x->getName() << endl;});

  // Do topological sort, if it works.
  cout  << "Topological sort" << endl;
  // Here print should be inlined
  topological_sort<print>(g);

  // // Just checking the ref-count.
  // for (auto it = mv.begin(); it != mv.end(); ++it) {
  //   cout << (*it).use_count() << endl;
  // }

  return 0;
}

<|endoftext|>


<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)
#include "TString.h"
#include "TObjArray.h"

#include "AliLog.h"

#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"

#include "AliAnalysisTaskNonlinearFlow.h"
#endif

AliAnalysisTaskNonlinearFlow* AddTaskNonlinearFlow(
		Int_t			fFilterbit 		= 96,
		Double_t	fMinPt				= 0.2,
		Double_t	fMaxPt				= 3.0,
		TString		uniqueID 			= ""
		)
{
        // The common parameters
	Double_t	fEtaCut 			= 0.8;
	Double_t	fVtxCut				= 10.0;
	Int_t		TPCclusters		        = 70;
	Int_t		fMinITSClus		        = 5;
	Double_t	fMaxChi2			= 2.5;
	Bool_t		fUseDCAzCut		        = false;
	Double_t	fDCAz				= 1.0;
	Bool_t		fUseDCAxyCut	                = false;
	Double_t	fDCAxy				= 0.2;
	Int_t		IsSample			= 10;
	Short_t		nCentFl				= 0;
	Int_t		trigger				= 1;
	Bool_t		fLS				= false;
	Bool_t		fNUE 				= true;
	Bool_t		fNUA				= true;
	TString		fPeriod 			= "";

	// Creates a pid task and adds it to the analysis manager
	// Get the pointer to the existing analysis manager via the static
	//access method
	//=========================================================================
	AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
	if (!mgr) {
		Error("AddTaskNonlinearFlow.C", "No analysis manager to connect to.");
		return NULL;
	}

	// Check the analysis type using the event handlers connected to the
	// analysis manager The availability of MC handler can also be
	// checked here.
	// =========================================================================
	if (!mgr->GetInputEventHandler()) {
		Error("AddTaskNonLinearFlow.C", "This task requires an input event handler");
		return NULL;
	}

	// Create the task and configure it
	//========================================================================
	TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

	AliAnalysisTaskNonlinearFlow* taskFlowEp = new AliAnalysisTaskNonlinearFlow("taskFlowEp");
	taskFlowEp->SetDebugLevel(3);
	taskFlowEp->SetFilterbit(fFilterbit);
	taskFlowEp->SetEtaCut(fEtaCut);
	taskFlowEp->SetVtxCut(fVtxCut);
	taskFlowEp->SetMinPt(fMinPt);
	taskFlowEp->SetMaxPt(fMaxPt);
	taskFlowEp->SetTPCclusters(TPCclusters);
	taskFlowEp->SetMinITSClusters(fMinITSClus);
	taskFlowEp->SetMaxChi2(fMaxChi2);
	taskFlowEp->SetUseDCAzCut(fUseDCAzCut);
	taskFlowEp->SetDCAzCut(fDCAz);
	taskFlowEp->SetUseDCAxyCut(fUseDCAxyCut);
	taskFlowEp->SetDCAxyCut(fDCAxy);
	taskFlowEp->SetIsSample(IsSample);
	taskFlowEp->SetCentFlag(nCentFl);
	taskFlowEp->SetTrigger(trigger);
	taskFlowEp->SetLSFlag(fLS);
	taskFlowEp->SetNUEFlag(fNUE);
	taskFlowEp->SetNUA(fNUA);

	//....
	taskFlowEp->SetPeriod(fPeriod);
	mgr->AddTask(taskFlowEp);

	// 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 fileName = AliAnalysisManager::GetCommonFileName();
	//fileName+=suffixName;
	AliAnalysisDataContainer* cinput = mgr->GetCommonInputContainer();
	AliAnalysisDataContainer *cout_hist = mgr->CreateContainer(Form("output_%s", uniqueID.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("v4New.root:%s", uniqueID.Data()));
	mgr->ConnectInput (taskFlowEp, 0, cinput);
	mgr->ConnectOutput(taskFlowEp, 1, cout_hist);

	// Return task pointer at the end
	return taskFlowEp;
}
//
// EOF
//
<commit_msg>change the output file name<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)
#include "TString.h"
#include "TObjArray.h"

#include "AliLog.h"

#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"

#include "AliAnalysisTaskNonlinearFlow.h"
#endif

AliAnalysisTaskNonlinearFlow* AddTaskNonlinearFlow(
		Int_t			fFilterbit 		= 96,
		Double_t	fMinPt				= 0.2,
		Double_t	fMaxPt				= 3.0,
		TString		uniqueID 			= ""
		)
{
        // The common parameters
	Double_t	fEtaCut 			= 0.8;
	Double_t	fVtxCut				= 10.0;
	Int_t		TPCclusters		        = 70;
	Int_t		fMinITSClus		        = 5;
	Double_t	fMaxChi2			= 2.5;
	Bool_t		fUseDCAzCut		        = false;
	Double_t	fDCAz				= 1.0;
	Bool_t		fUseDCAxyCut	                = false;
	Double_t	fDCAxy				= 0.2;
	Int_t		IsSample			= 10;
	Short_t		nCentFl				= 0;
	Int_t		trigger				= 1;
	Bool_t		fLS				= false;
	Bool_t		fNUE 				= true;
	Bool_t		fNUA				= true;
	TString		fPeriod 			= "";

	// Creates a pid task and adds it to the analysis manager
	// Get the pointer to the existing analysis manager via the static
	//access method
	//=========================================================================
	AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
	if (!mgr) {
		Error("AddTaskNonlinearFlow.C", "No analysis manager to connect to.");
		return NULL;
	}

	// Check the analysis type using the event handlers connected to the
	// analysis manager The availability of MC handler can also be
	// checked here.
	// =========================================================================
	if (!mgr->GetInputEventHandler()) {
		Error("AddTaskNonLinearFlow.C", "This task requires an input event handler");
		return NULL;
	}

	// Create the task and configure it
	//========================================================================
	TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

	AliAnalysisTaskNonlinearFlow* taskFlowEp = new AliAnalysisTaskNonlinearFlow("taskFlowEp");
	taskFlowEp->SetDebugLevel(3);
	taskFlowEp->SetFilterbit(fFilterbit);
	taskFlowEp->SetEtaCut(fEtaCut);
	taskFlowEp->SetVtxCut(fVtxCut);
	taskFlowEp->SetMinPt(fMinPt);
	taskFlowEp->SetMaxPt(fMaxPt);
	taskFlowEp->SetTPCclusters(TPCclusters);
	taskFlowEp->SetMinITSClusters(fMinITSClus);
	taskFlowEp->SetMaxChi2(fMaxChi2);
	taskFlowEp->SetUseDCAzCut(fUseDCAzCut);
	taskFlowEp->SetDCAzCut(fDCAz);
	taskFlowEp->SetUseDCAxyCut(fUseDCAxyCut);
	taskFlowEp->SetDCAxyCut(fDCAxy);
	taskFlowEp->SetIsSample(IsSample);
	taskFlowEp->SetCentFlag(nCentFl);
	taskFlowEp->SetTrigger(trigger);
	taskFlowEp->SetLSFlag(fLS);
	taskFlowEp->SetNUEFlag(fNUE);
	taskFlowEp->SetNUA(fNUA);

	//....
	taskFlowEp->SetPeriod(fPeriod);
	mgr->AddTask(taskFlowEp);

	// 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 fileName = AliAnalysisManager::GetCommonFileName();
	//fileName+=suffixName;
	AliAnalysisDataContainer* cinput = mgr->GetCommonInputContainer();
	AliAnalysisDataContainer *cout_hist = mgr->CreateContainer(Form("output_%s", uniqueID.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("AnalysisResults.root:%s", uniqueID.Data()));
	mgr->ConnectInput (taskFlowEp, 0, cinput);
	mgr->ConnectOutput(taskFlowEp, 1, cout_hist);

	// Return task pointer at the end
	return taskFlowEp;
}
//
// EOF
//
<|endoftext|>


<commit_before>#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace std;
using namespace boost::filesystem;
using namespace boost::posix_time;

#define STATS 0
#define LIST 1
#define ALL 2

#define STATS_ARG "--stats"
#define LIST_ARG "--list"
#define ALL_ARG "--all"

int checkTSForErrors(int fileLinesAmount, vector<string> linesVector, vector<int> *invalidTimestampsLines);
void showStats(int fileLinesAmount, vector<int> invalidTimestampsLines, int totalInvalidTimestamps);
void showList(int fileLinesAmount, vector<string> linesVector, vector<int> invalidTimestampsLines, int totalInvalidTimestamps);

int main(int argc, char* argv[])
{
	// If no input file argument provided - show error message
	if (argc < 2)
	{
		cout << "Input file missing!\n";
		cout << "Try again: " << argv[0] << " <filename> --optionalArgument\n";
		cout << "\n";
		// Arguments info:
		cout << "--stats\nOutputs statistical information about time stamp anomalies.\n";
		cout << "--list\nOutputs lines with erroneous time stamps along with line numbers.\n";
		cout << "--all\nOutputs lines with erroneous time stamps along with line numbers and statistical information about time stamp anomalies.\n";

		return -1;
	}

	vector<string> linesVector;
	long fileLines;

	try
	{
		path p(argv[1]);
		if (exists(p))
		{
			if (!is_regular_file(p))
			{
				cout << "Not regular file provided!\n";

				return -1;
			}

			// Open file after checking that it exists and is regular
			std::ifstream file(p.c_str());
			fileLines = count(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), '\n') + 1;

			// Go back to beginning of file
			file.clear();
			file.seekg(0, ios::beg);

			// Reading every line into vector
			string str;
			while (getline(file, str)) linesVector.push_back(str);
		}
		else
		{
			cout << "File does not exist!\n";

			return -1;
		}
	}
	catch (const filesystem_error& ex)
	{
		cout << "File reading error!\n" << ex.what() << '\n';

		return -1;
	}

	// Checking additional action argument:
	int action = STATS;
	if (argc > 2 && strcmp(argv[2], STATS_ARG) != 0)
	{
		if (strcmp(argv[2], LIST_ARG) != 0 && strcmp(argv[2], ALL_ARG) != 0)
		{
			cout << "Wrong action. Default action '--stats' selected instead.";
		}
		else
		{
			action = ALL;
			if (strcmp(argv[2], LIST_ARG) == 0) action = LIST;
		}
	}

	vector<int> invalidTimestampsLines;
	int totalInvalidTimestamps = checkTSForErrors(fileLines, linesVector, &invalidTimestampsLines);

	if (action == STATS || action == ALL) showStats(fileLines, invalidTimestampsLines, totalInvalidTimestamps);
	if (action == LIST || action == ALL) showList(fileLines, linesVector, invalidTimestampsLines, totalInvalidTimestamps);

	return 0;
}

int checkTSForErrors(int fileLinesAmount, vector<string> lines, vector<int> *invalidTimestampsLines)
{
	const locale loc = locale(locale::classic(), new time_input_facet("%Y-%m-%d %H:%M:%s"));
	ptime* lastNormalTimestamp = NULL;
	ptime currentTimestamp;
	int i, totalInvalidTimestamps = 0;
	for (i = 0; i < fileLinesAmount; ++i)
	{
		// PARSING PART
		string lineDate = lines[i].substr(0, 23);
		istringstream is(lineDate);
		is.imbue(loc);
		is >> currentTimestamp;

		// ERROR CHECKING PART
		if (lastNormalTimestamp != NULL
			&& (lastNormalTimestamp->time_of_day() > currentTimestamp.time_of_day()
				|| lastNormalTimestamp->date() > currentTimestamp.date()))
		{
			invalidTimestampsLines->push_back(i);
			totalInvalidTimestamps++;
		}
		else
		{
			free(lastNormalTimestamp);
			lastNormalTimestamp = new ptime(currentTimestamp);
		}
	}

	return totalInvalidTimestamps;
}

void showStats(int fileLinesAmount, vector<int> invalidTimestampsLines, int totalInvalidTimestamps)
{
	cout << "Number of lines:\n" << fileLinesAmount << "\n";
	cout << "Invalid time stamps at line(s):\n";

	bool isRange = false;
	string output;
	int i;
	for (i = 0; i < totalInvalidTimestamps; ++i)
	{
		// Starting point ("x")
		if (!isRange) output = to_string(invalidTimestampsLines[i] + 1);

		// Check if next line number is next to this to form a range ("x-")
		if (i + 1 != totalInvalidTimestamps && !isRange
			&& invalidTimestampsLines[i + 1] + 1 == invalidTimestampsLines[i] + 2)
		{
			isRange = true;
			output += "-";
		}

		if (isRange)
		{
			// Check if there is no more line numbers in this range to close it ("x-y")
			if (i + 1 == totalInvalidTimestamps || invalidTimestampsLines[i + 1] + 1 != invalidTimestampsLines[i] + 2)
			{
				output += to_string(invalidTimestampsLines[i] + 1);
				isRange = false;
			}
			else { continue; }
		}

		cout << output << "\n";
	}

	cout << "\n";
}

void showList(int fileLinesAmount, vector<string> lines, vector<int> invalidTimestampsLines, int totalInvalidTimestamps)
{
	int i, currentInvalidTimestampLine;
	for (i = 0; i < totalInvalidTimestamps; ++i)
	{
		currentInvalidTimestampLine = invalidTimestampsLines[i];

		// Normal entry before the invalid timestamp
		if (currentInvalidTimestampLine > 0
			&& (i == 0 || invalidTimestampsLines[i - 1] != currentInvalidTimestampLine - 1))
		{
			cout << "[" << currentInvalidTimestampLine << "] " + lines[currentInvalidTimestampLine - 1] << "\n";
		}

		// Invalid timestamp entry
		cout << "[" << currentInvalidTimestampLine + 1 << "] " + lines[currentInvalidTimestampLine] << "\n";

		// Normal entry after invalid timestamp
		if (currentInvalidTimestampLine + 1 < fileLinesAmount
			&& (i + 1 == totalInvalidTimestamps || invalidTimestampsLines[i + 1] != currentInvalidTimestampLine + 1))
		{
			cout << "[" << currentInvalidTimestampLine + 2 << "] " + lines[currentInvalidTimestampLine + 1] << "\n";
			cout << "---" << "\n";
		}
	}
}<commit_msg>Minor Fix<commit_after>#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace std;
using namespace boost::filesystem;
using namespace boost::posix_time;

#define STATS 0
#define LIST 1
#define ALL 2

#define STATS_ARG "--stats"
#define LIST_ARG "--list"
#define ALL_ARG "--all"

int checkTSForErrors(int fileLinesAmount, vector<string> linesVector, vector<int> *invalidTimestampsLines);
void showStats(int fileLinesAmount, vector<int> invalidTimestampsLines, int totalInvalidTimestamps);
void showList(int fileLinesAmount, vector<string> linesVector, vector<int> invalidTimestampsLines, int totalInvalidTimestamps);

int main(int argc, char* argv[])
{
	// If no input file argument provided - show error message
	if (argc < 2)
	{
		cout << "Input file missing!\n";
		cout << "Try again: " << argv[0] << " <filename> --optionalArgument\n";
		cout << "\n";
		// Arguments info:
		cout << "--stats\nOutputs statistical information about time stamp anomalies.\n";
		cout << "--list\nOutputs lines with erroneous time stamps along with line numbers.\n";
		cout << "--all\nOutputs lines with erroneous time stamps along with line numbers and statistical information about time stamp anomalies.\n";

		return -1;
	}

	vector<string> linesVector;
	long fileLines;

	try
	{
		path p(argv[1]);
		if (exists(p))
		{
			if (!is_regular_file(p))
			{
				cout << "Not regular file provided!\n";

				return -1;
			}

			// Open file after checking that it exists and is regular
			std::ifstream file(p.c_str());
			fileLines = count(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), '\n') + 1;

			// Go back to beginning of file
			file.clear();
			file.seekg(0, ios::beg);

			// Reading every line into vector
			string str;
			while (getline(file, str)) linesVector.push_back(str);
		}
		else
		{
			cout << "File does not exist!\n";

			return -1;
		}
	}
	catch (const filesystem_error& ex)
	{
		cout << "File reading error!\n" << ex.what() << '\n';

		return -1;
	}

	// Checking additional action argument:
	int action = STATS;
	if (argc > 2 && strcmp(argv[2], STATS_ARG) != 0)
	{
		if (strcmp(argv[2], LIST_ARG) != 0 && strcmp(argv[2], ALL_ARG) != 0)
		{
			cout << "Wrong action. Default action '--stats' selected instead.";
		}
		else
		{
			action = ALL;
			if (strcmp(argv[2], LIST_ARG) == 0) action = LIST;
		}
	}

	vector<int> invalidTimestampsLines;
	int totalInvalidTimestamps = checkTSForErrors(fileLines, linesVector, &invalidTimestampsLines);

	if (action == STATS || action == ALL) showStats(fileLines, invalidTimestampsLines, totalInvalidTimestamps);
	if (action == LIST || action == ALL) showList(fileLines, linesVector, invalidTimestampsLines, totalInvalidTimestamps);

	return 0;
}

int checkTSForErrors(int fileLinesAmount, vector<string> linesVector, vector<int> *invalidTimestampsLines)
{
	const locale loc = locale(locale::classic(), new time_input_facet("%Y-%m-%d %H:%M:%s"));
	ptime* lastNormalTimestamp = NULL;
	ptime currentTimestamp;
	int i, totalInvalidTimestamps = 0;
	for (i = 0; i < fileLinesAmount; ++i)
	{
		// PARSING PART
		string lineDate = linesVector[i].substr(0, 23);
		istringstream is(lineDate);
		is.imbue(loc);
		is >> currentTimestamp;

		// ERROR CHECKING PART
		if (lastNormalTimestamp != NULL
			&& (lastNormalTimestamp->time_of_day() > currentTimestamp.time_of_day()
				|| lastNormalTimestamp->date() > currentTimestamp.date()))
		{
			invalidTimestampsLines->push_back(i);
			totalInvalidTimestamps++;
		}
		else
		{
			free(lastNormalTimestamp);
			lastNormalTimestamp = new ptime(currentTimestamp);
		}
	}

	return totalInvalidTimestamps;
}

void showStats(int fileLinesAmount, vector<int> invalidTimestampsLines, int totalInvalidTimestamps)
{
	cout << "Number of lines:\n" << fileLinesAmount << "\n";
	cout << "Invalid time stamps at line(s):\n";

	bool isRange = false;
	string output;
	int i;
	for (i = 0; i < totalInvalidTimestamps; ++i)
	{
		// Starting point ("x")
		if (!isRange) output = to_string(invalidTimestampsLines[i] + 1);

		// Check if next line number is next to this to form a range ("x-")
		if (i + 1 != totalInvalidTimestamps && !isRange
			&& invalidTimestampsLines[i + 1] + 1 == invalidTimestampsLines[i] + 2)
		{
			isRange = true;
			output += "-";
		}

		if (isRange)
		{
			// Check if there is no more line numbers in this range to close it ("x-y")
			if (i + 1 == totalInvalidTimestamps || invalidTimestampsLines[i + 1] + 1 != invalidTimestampsLines[i] + 2)
			{
				output += to_string(invalidTimestampsLines[i] + 1);
				isRange = false;
			}
			else { continue; }
		}

		cout << output << "\n";
	}

	cout << "\n";
}

void showList(int fileLinesAmount, vector<string> linesVector, vector<int> invalidTimestampsLines, int totalInvalidTimestamps)
{
	int i, currentInvalidTimestampLine;
	for (i = 0; i < totalInvalidTimestamps; ++i)
	{
		currentInvalidTimestampLine = invalidTimestampsLines[i];

		// Normal entry before the invalid timestamp
		if (currentInvalidTimestampLine > 0
			&& (i == 0 || invalidTimestampsLines[i - 1] != currentInvalidTimestampLine - 1))
		{
			cout << "[" << currentInvalidTimestampLine << "] " + linesVector[currentInvalidTimestampLine - 1] << "\n";
		}

		// Invalid timestamp entry
		cout << "[" << currentInvalidTimestampLine + 1 << "] " + linesVector[currentInvalidTimestampLine] << "\n";

		// Normal entry after invalid timestamp
		if (currentInvalidTimestampLine + 1 < fileLinesAmount
			&& (i + 1 == totalInvalidTimestamps || invalidTimestampsLines[i + 1] != currentInvalidTimestampLine + 1))
		{
			cout << "[" << currentInvalidTimestampLine + 2 << "] " + linesVector[currentInvalidTimestampLine + 1] << "\n";
			cout << "---" << "\n";
		}
	}
}<|endoftext|>


<commit_before><commit_msg>fix cut<commit_after><|endoftext|>


<commit_before>/*
  Template of calibration/filtering macro using ESD:
  - requires AliESDs.root and AliESDfriend.root
  - requires OCDB access (default set to "raw://")
  - requires run number as argument to init OCDB
  - calls LoadLibraries.C, ConfigCalibTrain.C and AddTaskTPCCalib.C macros
  - output AliESDfriends_v1.root with TPC and TRD calibration objects are created

  Example:
  .L $ALICE_ROOT/ANALYSIS/macros/runCalibTrain.C
  runCalibTrain("104892");
*/

void runCalibTrain(Int_t runNumber, const char *inFileName = "AliESDs.root", const char *ocdb="raw://")
{
  //
  // macro to run TPC calibration train
  //
  AliSysInfo::SetVerbose(kTRUE);
  AliLog::SetGlobalLogLevel(AliLog::kError);
  gROOT->Macro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/LoadLibraries.C");
  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/ConfigCalibTrain.C");
  gSystem->SetIncludePath("-I$ALICE_ROOT/include -I$ALICE_ROOT/ANALYSIS");
  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/commonMacros/CleanGeom.C++");

  // detector tasks
  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/AddTaskTPCCalib.C");
  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/AddTaskTRDCalib.C");
  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/AddTOFAnalysisTaskCalibPass0.C");
  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/AddTaskT0Calib.C");
  //  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/AddTaskMeanVertexCalib.C");
  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/AddTaskSDDCalib.C");

  // switch off debug
  AliLog::SetClassDebugLevel("AliESDEvent",0);

  // steering input chain
  TChain *chain = new TChain("esdTree");
  chain->Add(inFileName);

  // config calibration train
  // setting geometry and B-field from GRP
  printf("runNumber from runCalibTrain = %d\n",runNumber);
  printf("ocdb from runCalibTrain = %s\n",ocdb);
  AliSysInfo::AddStamp("BeforeConfiguringCalibTrain");
  ConfigCalibTrain(runNumber, ocdb);
  AliSysInfo::AddStamp("AfterConfiguringCalibTrain");

  if (gROOT->LoadMacro("localOCDBaccessConfig.C")==0) {
    localOCDBaccessConfig();
  }

  //
  // check the presence of the detectors
  AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/GRP/Data");
  AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry->GetObject());
  if (!grpData) {printf("Failed to get GRP data for run",runNumber); return;}
  Int_t activeDetectors = grpData->GetDetectorMask();
  TString detStr = AliDAQ::ListOfTriggeredDetectors(activeDetectors);
  printf("Detectors in the data:\n%s\n",detStr.Data());

  // setup analysis
  //
  AliAnalysisManager *mgr  = new AliAnalysisManager("ESD to ESD", "Analysis Manager");
  // mgr->SetDebugLevel(3);
  mgr->SetNSysInfo(50);
  mgr->SetCacheSize(0);

  // Input
  AliESDInputHandler* inpHandler = new AliESDInputHandler();
  inpHandler->SetReadFriends(1);
  mgr->SetInputEventHandler(inpHandler);

  // Output
  const char *outFile = "AliESDfriends_v1.root";
  AliESDHandler* esdHandler   = new AliESDHandler();
  mgr->SetOutputEventHandler(esdHandler);
  esdHandler->SetOutputFileName(outFile);
  mgr->SetCommonFileName(outFile);
  //
  // Detector Tasks
  //
  AliSysInfo::AddStamp("BeforeTPC");
  if ( detStr.Contains("TPC"))  AddTaskTPCCalib(runNumber);

  AliSysInfo::AddStamp("BeforeTRD");
  if ( detStr.Contains("TRD") && detStr.Contains("TPC"))  AddTaskTRDCalib(runNumber);

  AliSysInfo::AddStamp("BeforeTOF");
  if ( detStr.Contains("TOF") && detStr.Contains("TPC"))  AddTOFAnalysisTaskCalibPass0();

  AliSysInfo::AddStamp("BeforeT0");
  if ( detStr.Contains("T0"))   AddTaskT0Calib(runNumber);
  //if ( detStr.Contains("ITSSPD")) tMeanVtx = AddTaskMeanVertexCalib();
  //
  Bool_t okTPC = detStr.Contains("TPC");
  Bool_t useTPCcrv=kFALSE;
  Bool_t writeITSTP = kFALSE;
  if (!okTPC) useTPCcrv = kFALSE;
  AliSysInfo::AddStamp("BeforeSDD");
  AliAnalysisTaskITSAlignQA *itsAlign = AddTaskSDDCalib(0,writeITSTP,useTPCcrv);
  if (!okTPC) itsAlign->SetUseITSstandaloneTracks(kTRUE);
  if (grpData->GetL3Current()[0] < 300) itsAlign->SetMinPt(0.001);
  //
  // dummy task to clean geometry in Terminate >>>>
  CleanGeom* clgmTask = new CleanGeom("cleanGeom");
  mgr->AddTask(clgmTask);
  AliAnalysisDataContainer *dummyInp = mgr->GetCommonInputContainer();
  if (dummyInp) mgr->ConnectInput(clgmTask,0,dummyInp);

  // Run the analysis
  AliSysInfo::AddStamp("BeforeInitAnalysis");
  if (!mgr->InitAnalysis()) {
    printf("Analysis cannot be started, returning\n");
    return;
  }

  mgr->PrintStatus();
  AliSysInfo::AddStamp("BeforeStartAnalysis");
  mgr->StartAnalysis("local", chain);

  return;
}
<commit_msg>Adding new TOF and T0 tasks to CPass1 (output in separate files)<commit_after>/*
  Template of calibration/filtering macro using ESD:
  - requires AliESDs.root and AliESDfriend.root
  - requires OCDB access (default set to "raw://")
  - requires run number as argument to init OCDB
  - calls LoadLibraries.C, ConfigCalibTrain.C and AddTaskTPCCalib.C macros
  - output AliESDfriends_v1.root with TPC and TRD calibration objects are created

  Example:
  .L $ALICE_ROOT/ANALYSIS/macros/runCalibTrain.C
  runCalibTrain("104892");
*/

void runCalibTrain(Int_t runNumber, const char *inFileName = "AliESDs.root", const char *ocdb="raw://")
{
  //
  // macro to run TPC calibration train
  //
  AliSysInfo::SetVerbose(kTRUE);
  AliLog::SetGlobalLogLevel(AliLog::kError);
  gROOT->Macro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/LoadLibraries.C");
  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/ConfigCalibTrain.C");
  gSystem->SetIncludePath("-I$ALICE_ROOT/include -I$ALICE_ROOT/ANALYSIS");
  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/commonMacros/CleanGeom.C++");

  // detector tasks
  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/AddTaskTPCCalib.C");
  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/AddTaskTRDCalib.C");
  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/AddTOFAnalysisTaskCalibPass0.C");
  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/AddTOFAnalysisTaskCalibTree.C");
  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/AddTaskT0Calib.C");
  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/AddTaskT0Analysis.C");
  //  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/AddTaskMeanVertexCalib.C");
  gROOT->LoadMacro("$ALICE_ROOT/PWGPP/CalibMacros/CPass1/AddTaskSDDCalib.C");

  // switch off debug
  AliLog::SetClassDebugLevel("AliESDEvent",0);

  // steering input chain
  TChain *chain = new TChain("esdTree");
  chain->Add(inFileName);

  // config calibration train
  // setting geometry and B-field from GRP
  printf("runNumber from runCalibTrain = %d\n",runNumber);
  printf("ocdb from runCalibTrain = %s\n",ocdb);
  AliSysInfo::AddStamp("BeforeConfiguringCalibTrain");
  ConfigCalibTrain(runNumber, ocdb);
  AliSysInfo::AddStamp("AfterConfiguringCalibTrain");

  if (gROOT->LoadMacro("localOCDBaccessConfig.C")==0) {
    localOCDBaccessConfig();
  }

  //
  // check the presence of the detectors
  AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/GRP/Data");
  AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry->GetObject());
  if (!grpData) {printf("Failed to get GRP data for run",runNumber); return;}
  Int_t activeDetectors = grpData->GetDetectorMask();
  TString detStr = AliDAQ::ListOfTriggeredDetectors(activeDetectors);
  printf("Detectors in the data:\n%s\n",detStr.Data());

  // setup analysis
  //
  AliAnalysisManager *mgr  = new AliAnalysisManager("ESD to ESD", "Analysis Manager");
  // mgr->SetDebugLevel(3);
  mgr->SetNSysInfo(50);
  mgr->SetCacheSize(0);

  // Input
  AliESDInputHandler* inpHandler = new AliESDInputHandler();
  inpHandler->SetReadFriends(1);
  mgr->SetInputEventHandler(inpHandler);

  // Output
  const char *outFile = "AliESDfriends_v1.root";
  AliESDHandler* esdHandler   = new AliESDHandler();
  mgr->SetOutputEventHandler(esdHandler);
  esdHandler->SetOutputFileName(outFile);
  mgr->SetCommonFileName(outFile);
  //
  // Detector Tasks
  //
  AliSysInfo::AddStamp("BeforeTPC");
  if ( detStr.Contains("TPC"))  AddTaskTPCCalib(runNumber);

  AliSysInfo::AddStamp("BeforeTRD");
  if ( detStr.Contains("TRD") && detStr.Contains("TPC"))  AddTaskTRDCalib(runNumber);

  AliSysInfo::AddStamp("BeforeTOF");
  if ( detStr.Contains("TOF") && detStr.Contains("TPC"))  {
    AddTOFAnalysisTaskCalibPass0();
    AddTOFAnalysisTaskCalibTree();
  }

  AliSysInfo::AddStamp("BeforeT0");
  if ( detStr.Contains("T0"))   {
    AddTaskT0Calib(runNumber);
    AddTaskT0Analysis();
  }

  //if ( detStr.Contains("ITSSPD")) tMeanVtx = AddTaskMeanVertexCalib();
  //
  Bool_t okTPC = detStr.Contains("TPC");
  Bool_t useTPCcrv=kFALSE;
  Bool_t writeITSTP = kFALSE;
  if (!okTPC) useTPCcrv = kFALSE;
  AliSysInfo::AddStamp("BeforeSDD");
  AliAnalysisTaskITSAlignQA *itsAlign = AddTaskSDDCalib(0,writeITSTP,useTPCcrv);
  if (!okTPC) itsAlign->SetUseITSstandaloneTracks(kTRUE);
  if (grpData->GetL3Current()[0] < 300) itsAlign->SetMinPt(0.001);
  //
  // dummy task to clean geometry in Terminate >>>>
  CleanGeom* clgmTask = new CleanGeom("cleanGeom");
  mgr->AddTask(clgmTask);
  AliAnalysisDataContainer *dummyInp = mgr->GetCommonInputContainer();
  if (dummyInp) mgr->ConnectInput(clgmTask,0,dummyInp);

  // Run the analysis
  AliSysInfo::AddStamp("BeforeInitAnalysis");
  if (!mgr->InitAnalysis()) {
    printf("Analysis cannot be started, returning\n");
    return;
  }

  mgr->PrintStatus();
  AliSysInfo::AddStamp("BeforeStartAnalysis");
  mgr->StartAnalysis("local", chain);

  return;
}
<|endoftext|>


<commit_before>#include "Thread.h"

#include <SDL/SDL_thread.h>
#include <SDL/SDL_timer.h>

// Just serves to start the Runnable run method after a thread fork.
int runRunnable(void* data) {
    Runnable* r = (Runnable*) data;
    r->run();
    return 0;
}

Thread::Thread() {
    runnable = this;
}

Thread::Thread(Runnable *runnable) {
    this->runnable = runnable;
    this->threadhandle = NULL;
}

void Thread::start() {
    threadhandle = (void*) SDL_CreateThread(runRunnable, runnable);
}

void Thread::stop() {
    SDL_KillThread((SDL_Thread*) threadhandle);
}

void Thread::sleep(unsigned int ms) {
    SDL_Delay(ms);
}

int Thread::hashCode() {
    return (int)((unsigned long long)this & 0xFFFFFFFF);
}

<commit_msg>Thread: Cleaning initialization issues.<commit_after>#include "Thread.h"

#include <SDL/SDL_thread.h>
#include <SDL/SDL_timer.h>

// Just serves to start the Runnable run method after a thread fork.
int runRunnable(void* data) {
    Runnable* r = (Runnable*) data;
    r->run();
    return 0;
}

Thread::Thread() {
    this->runnable = this;
    this->threadhandle = NULL;
}

Thread::Thread(Runnable *runnable) {
    this->runnable = runnable;
    this->threadhandle = NULL;
}

void Thread::start() {
    threadhandle = (void*) SDL_CreateThread(runRunnable, runnable);
}

void Thread::stop() {
    SDL_KillThread((SDL_Thread*) threadhandle);
}

void Thread::sleep(unsigned int ms) {
    SDL_Delay(ms);
}

int Thread::hashCode() {
    return (int)((unsigned long long)this & 0xFFFFFFFF);
}

<|endoftext|>