<commit_before>/************************************************************************
*
* Flood Project  (2008-201x)
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/

#include "Engine/API.h"

#include "Engine/Scene/Entity.h"
#include "Engine/Scene/Transform.h"
#include "Engine/Scene/Geometry.h"
#include "Engine/Scene/Group.h"
#include "Engine/Scene/Tags.h"
#include <algorithm>

NAMESPACE_ENGINE_BEGIN

//-----------------------------------//

REFLECT_CHILD_CLASS(Entity, Object)
	FIELD_PRIMITIVE(1, string, name)
	FIELD_PRIMITIVE(2, bool, visible)
	FIELD_VECTOR_PTR(3, Component, ComponentPtr, components, RefPointer)
	FIELD_PRIMITIVE(4, int32, tags)
	//FIELD_PRIMITIVE_CUSTOM(4, int32, tags, Bitfield)
REFLECT_CLASS_END()

//-----------------------------------//

Entity* EntityCreate(Allocator* alloc)
{
	return Allocate(alloc, Entity);
}

//-----------------------------------//

Entity::Entity()
	: visible(true)
	, tags(0)
	, parent(nullptr)
{
}

//-----------------------------------//

Entity::Entity( const String& name )
	: name(name)
	, visible(true)
	, tags(0)
	, parent(nullptr)
{
}

//-----------------------------------//

Entity::~Entity()
{
	// Keep a reference so it is the last component destroyed.
	TransformPtr transform = getTransform();

	components.clear();

	ComponentMap::iterator it = componentsMap.begin();

	for(; it != componentsMap.end(); it++ )
	{
		ComponentPtr& component = it->second;
		component.reset();
	}
}

//-----------------------------------//

static bool IsGroup(Entity* entity)
{
	return entity && ClassInherits(ClassGetType(entity), GroupGetType());
}

//-----------------------------------//

bool Entity::addComponent( const ComponentPtr& component )
{
	if( !component ) return false;

	Class* type = component->getType();

	if( componentsMap.find(type) != componentsMap.end() )
	{
		LogWarn( "Component '%s' already exists in '%s'", type->name, name.c_str() );
		return false;
	}

	componentsMap[type] = component;
	component->setEntity(this);

	onComponentAdded(component);
	sendEvents();

	if( IsGroup(parent) )
	{
		Group* group = (Group*) parent;
		group->onEntityComponentAdded(component);
	}

	components.push_back(component);

	return true;
}

//-----------------------------------//

bool Entity::removeComponent( const ComponentPtr& component )
{
	if( !component ) return false;

	Class* type = component->getType();

	ComponentMap::iterator it = componentsMap.find(type);

	if( it == componentsMap.end() )
		return false;

	componentsMap.erase(it);

	onComponentRemoved(component);
	sendEvents();

	if( IsGroup(parent) )
	{
		Group* group = (Group*) parent;
		group->onEntityComponentRemoved(component);
	}

	if( ClassInherits(type, ReflectionGetType(Geometry)) )
		getTransform()->markBoundingVolumeDirty();

	return true;
}

//-----------------------------------//

ComponentPtr Entity::getComponent(const char* name) const
{
	Type* type = ReflectionFindType(name);

	if( !ReflectionIsComposite(type) )
		return nullptr;

	return getComponent((Class*) type);
}

//-----------------------------------//

ComponentPtr Entity::getComponent(Class* klass) const
{
	ComponentMap::const_iterator it = componentsMap.find(klass);

	if( it == componentsMap.end() )
		return nullptr;

	return it->second;
}

//-----------------------------------//

ComponentPtr Entity::getComponentFromFamily(Class* klass) const
{
	ComponentMap::const_iterator it;

	for( it = componentsMap.begin(); it != componentsMap.end(); it++ )
	{
		const ComponentPtr& component = it->second;
		Class* componentClass = component->getType();

		if( ClassInherits(componentClass, klass) )
			return component;
	}

	return nullptr;
}

//-----------------------------------//

std::vector<GeometryPtr> Entity::getGeometry() const
{
	std::vector<GeometryPtr> geoms;

	ComponentMap::const_iterator it;
	for( it = componentsMap.begin(); it != componentsMap.end(); it++ )
	{
		const ComponentPtr& component = it->second;

		if( !ClassInherits(component->getType(), ReflectionGetType(Geometry)) )
			continue;

		const GeometryPtr& geo = RefCast<Geometry>(component);
		geoms.push_back(geo);
	}

	return geoms;
}

//-----------------------------------//

void Entity::update( float delta )
{
	// Update all geometry bounding boxes first.
	const std::vector<GeometryPtr>& geoms = getGeometry();

	for( size_t i = 0; i < geoms.size(); i++ )
	{
		Geometry* geom = geoms[i].get();
		geom->update( delta );
	}

	// Update the transform component.
	Transform* transform = getTransform().get();
	if( transform ) transform->update( delta );

	// Update the other components.
	ComponentMap::const_iterator it;
	for( it = componentsMap.begin(); it != componentsMap.end(); it++ )
	{
		const ComponentPtr& component = it->second;

		if( component == transform )
			continue;

		component->update( delta );
	}
}

//-----------------------------------//

void Entity::fixUp()
{
	for(size_t i = 0; i < components.size(); i++ )
	{
		Component* component = components[i].get();
		if( !component ) continue;

		component->setEntity(this);

		Class* type = component->getType();
		componentsMap[type] = component;
	}

	if( !getTransform() ) addTransform();
}

//-----------------------------------//

void Entity::sendEvents()
{
	if( !parent ) return;

	Class* type =  parent->getType();

	if( !ClassInherits(type, ReflectionGetType(Group)) )
		return;

	Group* group = (Group*) parent;
	group->onEntityChanged();
}

//-----------------------------------//

bool Entity::addTransform()
{
	Transform* transform = TransformCreate( AllocatorGetThis() );
	return addComponent(transform);
}

//-----------------------------------//

TransformPtr Entity::getTransform() const
{
	return getComponent<Transform>();
}

//-----------------------------------//

Entity* Entity::getParent() const
{
	return parent;
}

//-----------------------------------//

void Entity::setName( const String& name )
{
	this->name = name;
	sendEvents();
}

//-----------------------------------//

bool Entity::isVisible() const
{
	return visible;
}

//-----------------------------------//

bool Entity::getTag(int32 index) const
{
	return GetBitFlag(tags, (uint32)(1 << index));
}

//-----------------------------------//

void Entity::setTag(int32 index, bool state)
{
	SetBitFlag(tags, (uint32)(1 << index), state);
}

//-----------------------------------//

NAMESPACE_ENGINE_END<commit_msg>Added missing Utilities.h include<commit_after>/************************************************************************
*
* Flood Project  (2008-201x)
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/

#include "Engine/API.h"

#include "Engine/Scene/Entity.h"
#include "Engine/Scene/Transform.h"
#include "Engine/Scene/Geometry.h"
#include "Engine/Scene/Group.h"
#include "Engine/Scene/Tags.h"
#include "Core/Utilities.h"
#include <algorithm>

NAMESPACE_ENGINE_BEGIN

//-----------------------------------//

REFLECT_CHILD_CLASS(Entity, Object)
	FIELD_PRIMITIVE(1, string, name)
	FIELD_PRIMITIVE(2, bool, visible)
	FIELD_VECTOR_PTR(3, Component, ComponentPtr, components, RefPointer)
	FIELD_PRIMITIVE(4, int32, tags)
	//FIELD_PRIMITIVE_CUSTOM(4, int32, tags, Bitfield)
REFLECT_CLASS_END()

//-----------------------------------//

Entity* EntityCreate(Allocator* alloc)
{
	return Allocate(alloc, Entity);
}

//-----------------------------------//

Entity::Entity()
	: visible(true)
	, tags(0)
	, parent(nullptr)
{
}

//-----------------------------------//

Entity::Entity( const String& name )
	: name(name)
	, visible(true)
	, tags(0)
	, parent(nullptr)
{
}

//-----------------------------------//

Entity::~Entity()
{
	// Keep a reference so it is the last component destroyed.
	TransformPtr transform = getTransform();

	components.clear();

	ComponentMap::iterator it = componentsMap.begin();

	for(; it != componentsMap.end(); it++ )
	{
		ComponentPtr& component = it->second;
		component.reset();
	}
}

//-----------------------------------//

static bool IsGroup(Entity* entity)
{
	return entity && ClassInherits(ClassGetType(entity), GroupGetType());
}

//-----------------------------------//

bool Entity::addComponent( const ComponentPtr& component )
{
	if( !component ) return false;

	Class* type = component->getType();

	if( componentsMap.find(type) != componentsMap.end() )
	{
		LogWarn( "Component '%s' already exists in '%s'", type->name, name.c_str() );
		return false;
	}

	componentsMap[type] = component;
	component->setEntity(this);

	onComponentAdded(component);
	sendEvents();

	if( IsGroup(parent) )
	{
		Group* group = (Group*) parent;
		group->onEntityComponentAdded(component);
	}

	components.push_back(component);

	return true;
}

//-----------------------------------//

bool Entity::removeComponent( const ComponentPtr& component )
{
	if( !component ) return false;

	Class* type = component->getType();

	ComponentMap::iterator it = componentsMap.find(type);

	if( it == componentsMap.end() )
		return false;

	componentsMap.erase(it);

	onComponentRemoved(component);
	sendEvents();

	if( IsGroup(parent) )
	{
		Group* group = (Group*) parent;
		group->onEntityComponentRemoved(component);
	}

	if( ClassInherits(type, ReflectionGetType(Geometry)) )
		getTransform()->markBoundingVolumeDirty();

	return true;
}

//-----------------------------------//

ComponentPtr Entity::getComponent(const char* name) const
{
	Type* type = ReflectionFindType(name);

	if( !ReflectionIsComposite(type) )
		return nullptr;

	return getComponent((Class*) type);
}

//-----------------------------------//

ComponentPtr Entity::getComponent(Class* klass) const
{
	ComponentMap::const_iterator it = componentsMap.find(klass);

	if( it == componentsMap.end() )
		return nullptr;

	return it->second;
}

//-----------------------------------//

ComponentPtr Entity::getComponentFromFamily(Class* klass) const
{
	ComponentMap::const_iterator it;

	for( it = componentsMap.begin(); it != componentsMap.end(); it++ )
	{
		const ComponentPtr& component = it->second;
		Class* componentClass = component->getType();

		if( ClassInherits(componentClass, klass) )
			return component;
	}

	return nullptr;
}

//-----------------------------------//

std::vector<GeometryPtr> Entity::getGeometry() const
{
	std::vector<GeometryPtr> geoms;

	ComponentMap::const_iterator it;
	for( it = componentsMap.begin(); it != componentsMap.end(); it++ )
	{
		const ComponentPtr& component = it->second;

		if( !ClassInherits(component->getType(), ReflectionGetType(Geometry)) )
			continue;

		const GeometryPtr& geo = RefCast<Geometry>(component);
		geoms.push_back(geo);
	}

	return geoms;
}

//-----------------------------------//

void Entity::update( float delta )
{
	// Update all geometry bounding boxes first.
	const std::vector<GeometryPtr>& geoms = getGeometry();

	for( size_t i = 0; i < geoms.size(); i++ )
	{
		Geometry* geom = geoms[i].get();
		geom->update( delta );
	}

	// Update the transform component.
	Transform* transform = getTransform().get();
	if( transform ) transform->update( delta );

	// Update the other components.
	ComponentMap::const_iterator it;
	for( it = componentsMap.begin(); it != componentsMap.end(); it++ )
	{
		const ComponentPtr& component = it->second;

		if( component == transform )
			continue;

		component->update( delta );
	}
}

//-----------------------------------//

void Entity::fixUp()
{
	for(size_t i = 0; i < components.size(); i++ )
	{
		Component* component = components[i].get();
		if( !component ) continue;

		component->setEntity(this);

		Class* type = component->getType();
		componentsMap[type] = component;
	}

	if( !getTransform() ) addTransform();
}

//-----------------------------------//

void Entity::sendEvents()
{
	if( !parent ) return;

	Class* type =  parent->getType();

	if( !ClassInherits(type, ReflectionGetType(Group)) )
		return;

	Group* group = (Group*) parent;
	group->onEntityChanged();
}

//-----------------------------------//

bool Entity::addTransform()
{
	Transform* transform = TransformCreate( AllocatorGetThis() );
	return addComponent(transform);
}

//-----------------------------------//

TransformPtr Entity::getTransform() const
{
	return getComponent<Transform>();
}

//-----------------------------------//

Entity* Entity::getParent() const
{
	return parent;
}

//-----------------------------------//

void Entity::setName( const String& name )
{
	this->name = name;
	sendEvents();
}

//-----------------------------------//

bool Entity::isVisible() const
{
	return visible;
}

//-----------------------------------//

bool Entity::getTag(int32 index) const
{
	return GetBitFlag(tags, (uint32)(1 << index));
}

//-----------------------------------//

void Entity::setTag(int32 index, bool state)
{
	SetBitFlag(tags, (uint32)(1 << index), state);
}

//-----------------------------------//

NAMESPACE_ENGINE_END<|endoftext|>


<commit_before>
#include <TROOT.h>
#include <TSystem.h>
#include <TInterpreter.h>
#include <TChain.h>
#include <TFile.h>
#include <TList.h>
#include <iostream>
#include "TH1F.h"
#include "TH2F.h"
#include "AliFMDAnalysisTaskBFCorrelation.h"
#include "AliAnalysisManager.h"
#include "AliESDFMD.h"
#include "AliESDEvent.h"
#include "AliAODEvent.h"
#include "AliAODHandler.h"
#include "AliMCEventHandler.h"
#include "AliStack.h"
#include "AliLog.h"
#include "AliESDVertex.h"
#include "TMath.h"
#include "AliFMDAnaParameters.h"
//#include "AliFMDGeometry.h"
#include "AliGenEventHeader.h"
#include "AliGenPythiaEventHeader.h"
#include "AliHeader.h"
//#include "TDatabasePDG.h"
//#include "TParticlePDG.h"
#include "AliESDInputHandler.h"
ClassImp(AliFMDAnalysisTaskBFCorrelation)

AliFMDAnalysisTaskBFCorrelation::AliFMDAnalysisTaskBFCorrelation()
: fDebug(0),
  fOutputList(0),
  fInputList(0),
  fVertexString(0x0),
  fStandalone(kTRUE)
{
  // Default constructor
  DefineInput (0, TList::Class());
  DefineOutput(0, TList::Class());
}
//_____________________________________________________________________
AliFMDAnalysisTaskBFCorrelation::AliFMDAnalysisTaskBFCorrelation(const char* name, Bool_t SE):
  AliAnalysisTask(name,name),
    fDebug(0),
    fOutputList(0),
    fInputList(0),
    fVertexString(0x0),
    fStandalone(kTRUE)
{
  fStandalone = SE;
  if(fStandalone) {
    DefineInput (0, TList::Class());
    DefineInput(1, TObjString::Class());
    DefineOutput(0, TList::Class());

  }
}
//_____________________________________________________________________
void AliFMDAnalysisTaskBFCorrelation::CreateOutputObjects()
{
  AliFMDAnaParameters* pars = AliFMDAnaParameters::Instance();

  if(!fOutputList) {
    fOutputList = new TList();
    fOutputList->SetName("BackgroundCorrected");
  }

  TH1F* test = new TH1F("test","test",10,0,10);
  fOutputList->Add(test);
}
//_____________________________________________________________________
void AliFMDAnalysisTaskBFCorrelation::ConnectInputData(Option_t */*option*/)
{
  if(fStandalone) {
    fInputList   = (TList*)GetInputData(0);
    fVertexString = (TObjString*)GetInputData(1);
  }
}
//_____________________________________________________________________
void AliFMDAnalysisTaskBFCorrelation::Exec(Option_t */*option*/)
{
  AliFMDAnaParameters* pars = AliFMDAnaParameters::Instance();

  fVertexString = (TObjString*)fInputList->At(0);

  Int_t vtxbin   = fVertexString->GetString().Atoi();
  //for(UShort_t det=1;det<=3;det++) {
  //  Int_t nRings = (det==1 ? 1 : 2);
  //  for (UShort_t ir = 0; ir < nRings; ir++) {
  //    Char_t ringChar = (ir == 0 ? 'I' : 'O');
  //TH2F* hMultTotal = (TH2F*)fOutputList->FindObject(Form("dNdeta_FMD%d%c_vtxbin%d",det,ringChar,vtxbin));
  // TH2F* hMultTotalTrVtx = (TH2F*)fOutputList->FindObject(Form("dNdetaTrVtx_FMD%d%c_vtxbin%d",det,ringChar,vtxbin));

  TH1F* test = (TH1F*)fOutputList->FindObject("test");
  test->Fill(vtxbin);
  if(pars->GetProcessPrimary())
    ProcessPrimary();

  if(fStandalone) {
    PostData(0, fOutputList);
  }

}
//_____________________________________________________________________
void AliFMDAnalysisTaskBFCorrelation::Terminate(Option_t */*option*/) {

}
//_____________________________________________________________________
void AliFMDAnalysisTaskBFCorrelation::ProcessPrimary() {
  /*
  AliMCEventHandler* eventHandler = dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler());
  AliMCEvent* mcEvent = eventHandler->MCEvent();
  if(!mcEvent)
    return;

  AliFMDAnaParameters* pars = AliFMDAnaParameters::Instance();

  AliMCParticle* particle = 0;
  AliStack* stack = mcEvent->Stack();

  TH1F* hPrimary = (TH1F*)fOutputList->FindObject("hMultvsEta");
  AliHeader* header            = mcEvent->Header();
  AliGenEventHeader* genHeader = header->GenEventHeader();

  TArrayF vertex;
  genHeader->PrimaryVertex(vertex);
  if(TMath::Abs(vertex.At(2)) > pars->GetVtxCutZ())
    return;
  Double_t delta           = 2*pars->GetVtxCutZ()/pars->GetNvtxBins();
  Double_t vertexBinDouble = (vertex.At(2) + pars->GetVtxCutZ()) / delta;
  Int_t    vertexBin       = (Int_t)vertexBinDouble;

  Bool_t firstTrack = kTRUE;

  // we loop over the primaries only unless we need the hits (diagnostics running slowly)
  Int_t nTracks = stack->GetNprimary();
  if(pars->GetProcessHits())
    nTracks = stack->GetNtrack();

  for(Int_t i = 0 ;i<nTracks;i++) {
    particle = (AliMCParticle*) mcEvent->GetTrack(i);
    if(!particle)
      continue;

    if(stack->IsPhysicalPrimary(i) && particle->Charge() != 0) {
      hPrimary->Fill(particle->Eta());

      TH1F* hPrimVtxBin = (TH1F*)fOutputList->FindObject(Form("primmult_vtxbin%d",vertexBin));
      hPrimVtxBin->Fill(particle->Eta());
      if(firstTrack) {
	fNMCevents.Fill(vertexBin);
	firstTrack = kFALSE;
      }
    }
  }
  */
}
//_____________________________________________________________________
//
//
// EOF
<commit_msg>fixing a warning<commit_after>
#include <TROOT.h>
#include <TSystem.h>
#include <TInterpreter.h>
#include <TChain.h>
#include <TFile.h>
#include <TList.h>
#include <iostream>
#include "TH1F.h"
#include "TH2F.h"
#include "AliFMDAnalysisTaskBFCorrelation.h"
#include "AliAnalysisManager.h"
#include "AliESDFMD.h"
#include "AliESDEvent.h"
#include "AliAODEvent.h"
#include "AliAODHandler.h"
#include "AliMCEventHandler.h"
#include "AliStack.h"
#include "AliLog.h"
#include "AliESDVertex.h"
#include "TMath.h"
#include "AliFMDAnaParameters.h"
//#include "AliFMDGeometry.h"
#include "AliGenEventHeader.h"
#include "AliGenPythiaEventHeader.h"
#include "AliHeader.h"
//#include "TDatabasePDG.h"
//#include "TParticlePDG.h"
#include "AliESDInputHandler.h"
ClassImp(AliFMDAnalysisTaskBFCorrelation)

AliFMDAnalysisTaskBFCorrelation::AliFMDAnalysisTaskBFCorrelation()
: fDebug(0),
  fOutputList(0),
  fInputList(0),
  fVertexString(0x0),
  fStandalone(kTRUE)
{
  // Default constructor
  DefineInput (0, TList::Class());
  DefineOutput(0, TList::Class());
}
//_____________________________________________________________________
AliFMDAnalysisTaskBFCorrelation::AliFMDAnalysisTaskBFCorrelation(const char* name, Bool_t SE):
  AliAnalysisTask(name,name),
    fDebug(0),
    fOutputList(0),
    fInputList(0),
    fVertexString(0x0),
    fStandalone(kTRUE)
{
  fStandalone = SE;
  if(fStandalone) {
    DefineInput (0, TList::Class());
    DefineInput(1, TObjString::Class());
    DefineOutput(0, TList::Class());

  }
}
//_____________________________________________________________________
void AliFMDAnalysisTaskBFCorrelation::CreateOutputObjects()
{
  //AliFMDAnaParameters* pars = AliFMDAnaParameters::Instance();

  if(!fOutputList) {
    fOutputList = new TList();
    fOutputList->SetName("BackgroundCorrected");
  }

  TH1F* test = new TH1F("test","test",10,0,10);
  fOutputList->Add(test);
}
//_____________________________________________________________________
void AliFMDAnalysisTaskBFCorrelation::ConnectInputData(Option_t */*option*/)
{
  if(fStandalone) {
    fInputList   = (TList*)GetInputData(0);
    fVertexString = (TObjString*)GetInputData(1);
  }
}
//_____________________________________________________________________
void AliFMDAnalysisTaskBFCorrelation::Exec(Option_t */*option*/)
{
  AliFMDAnaParameters* pars = AliFMDAnaParameters::Instance();

  fVertexString = (TObjString*)fInputList->At(0);

  Int_t vtxbin   = fVertexString->GetString().Atoi();
  //for(UShort_t det=1;det<=3;det++) {
  //  Int_t nRings = (det==1 ? 1 : 2);
  //  for (UShort_t ir = 0; ir < nRings; ir++) {
  //    Char_t ringChar = (ir == 0 ? 'I' : 'O');
  //TH2F* hMultTotal = (TH2F*)fOutputList->FindObject(Form("dNdeta_FMD%d%c_vtxbin%d",det,ringChar,vtxbin));
  // TH2F* hMultTotalTrVtx = (TH2F*)fOutputList->FindObject(Form("dNdetaTrVtx_FMD%d%c_vtxbin%d",det,ringChar,vtxbin));

  TH1F* test = (TH1F*)fOutputList->FindObject("test");
  test->Fill(vtxbin);
  if(pars->GetProcessPrimary())
    ProcessPrimary();

  if(fStandalone) {
    PostData(0, fOutputList);
  }

}
//_____________________________________________________________________
void AliFMDAnalysisTaskBFCorrelation::Terminate(Option_t */*option*/) {

}
//_____________________________________________________________________
void AliFMDAnalysisTaskBFCorrelation::ProcessPrimary() {
  /*
  AliMCEventHandler* eventHandler = dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler());
  AliMCEvent* mcEvent = eventHandler->MCEvent();
  if(!mcEvent)
    return;

  AliFMDAnaParameters* pars = AliFMDAnaParameters::Instance();

  AliMCParticle* particle = 0;
  AliStack* stack = mcEvent->Stack();

  TH1F* hPrimary = (TH1F*)fOutputList->FindObject("hMultvsEta");
  AliHeader* header            = mcEvent->Header();
  AliGenEventHeader* genHeader = header->GenEventHeader();

  TArrayF vertex;
  genHeader->PrimaryVertex(vertex);
  if(TMath::Abs(vertex.At(2)) > pars->GetVtxCutZ())
    return;
  Double_t delta           = 2*pars->GetVtxCutZ()/pars->GetNvtxBins();
  Double_t vertexBinDouble = (vertex.At(2) + pars->GetVtxCutZ()) / delta;
  Int_t    vertexBin       = (Int_t)vertexBinDouble;

  Bool_t firstTrack = kTRUE;

  // we loop over the primaries only unless we need the hits (diagnostics running slowly)
  Int_t nTracks = stack->GetNprimary();
  if(pars->GetProcessHits())
    nTracks = stack->GetNtrack();

  for(Int_t i = 0 ;i<nTracks;i++) {
    particle = (AliMCParticle*) mcEvent->GetTrack(i);
    if(!particle)
      continue;

    if(stack->IsPhysicalPrimary(i) && particle->Charge() != 0) {
      hPrimary->Fill(particle->Eta());

      TH1F* hPrimVtxBin = (TH1F*)fOutputList->FindObject(Form("primmult_vtxbin%d",vertexBin));
      hPrimVtxBin->Fill(particle->Eta());
      if(firstTrack) {
	fNMCevents.Fill(vertexBin);
	firstTrack = kFALSE;
      }
    }
  }
  */
}
//_____________________________________________________________________
//
//
// EOF
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2015, John Haddon. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include <algorithm>

#include "openvdb/openvdb.h"
#include "openvdb/io/Stream.h"

#include "IECore/Exception.h"
#include "IECore/MurmurHash.h"
#include "IECore/SimpleTypedData.h"

#include "GafferVDB/VDBObject.h"

using namespace IECore;
using namespace GafferVDB;

namespace
{

//! Calculate the worldspace bounds - 0.5 padding required to include the full volume and not the bound of the voxel centres.
template<typename T>
Imath::Box<Imath::Vec3<T> > worldBound( const openvdb::GridBase* grid, float padding = 0.50f )
{
	openvdb::Vec3i min = grid->metaValue<openvdb::Vec3i>( grid->META_FILE_BBOX_MIN );
	openvdb::Vec3i max = grid->metaValue<openvdb::Vec3i>( grid->META_FILE_BBOX_MAX );

	openvdb::Vec3d offset = openvdb::Vec3d( padding );
	openvdb::BBoxd indexBounds = openvdb::BBoxd( min - offset, max + offset );
	openvdb::BBoxd worldBounds = grid->transform().indexToWorld( indexBounds );
	openvdb::Vec3d minBB = worldBounds.min();
	openvdb::Vec3d maxBB = worldBounds.max();

	return Imath::Box<Imath::Vec3<T> >( Imath::Vec3<T>( minBB[0], minBB[1], minBB[2] ), Imath::Vec3<T>( maxBB[0], maxBB[1], maxBB[2] ) );
}

}

IE_CORE_DEFINEOBJECTTYPEDESCRIPTION( VDBObject );

const unsigned int VDBObject::m_ioVersion = 0;

VDBObject::VDBObject()
: m_grids(new openvdb::GridPtrVec)
{
}

VDBObject::VDBObject(const std::string& filename)
{
	openvdb::initialize(); // safe to call multiple times but has a performance hit of a mutex.

	// note it seems fine for this file object to go out of scope
	// and grids are still able to pull in additional grid data
	openvdb::io::File file( filename );
	file.open(); //lazy loading of grid data is default enabling OPENVDB_DISABLE_DELAYED_LOAD will load the grids up front

	m_grids = file.getGrids();
}

VDBObject::~VDBObject()
{
}

openvdb::GridBase::ConstPtr VDBObject::findGrid(const std::string& name) const
{

	for(const auto &grid : *m_grids )
	{
		if (grid->getName() == name)
			return grid;
	}

	return openvdb::GridBase::Ptr();
}

openvdb::GridBase::Ptr VDBObject::findGrid(const std::string& name)
{
	for(const auto &grid : *m_grids )
	{
		if (grid->getName() == name)
			return grid;
	}

	return openvdb::GridBase::Ptr();
}

std::vector<std::string> VDBObject::gridNames() const
{
	std::vector<std::string> outputGridNames;
	for(const auto &grid : *m_grids )
	{
		outputGridNames.push_back( grid->getName() );
	}
	return outputGridNames;
}

void VDBObject::addGrid(openvdb::GridBase::Ptr grid)
{
	m_grids->push_back(grid);
}

void VDBObject::removeGrid(const std::string& name)
{
	for(auto it = m_grids->begin(); it != m_grids->end(); ++it )
	{
		if( ( *it )->getName() == name )
		{
			m_grids->erase( it );
			return;
		}
	}
}

Imath::Box3f VDBObject::bound() const
{
	Imath::Box3f combinedBounds;

	for (const auto& grid : *m_grids)
	{
		Imath::Box3f gridBounds = worldBound<float>( grid.get() );

		combinedBounds.extendBy( gridBounds );
	}

	return combinedBounds;
}

void VDBObject::render( IECore::Renderer *renderer ) const
{
}

IECore::UCharVectorDataPtr VDBObject::memoryBuffer() const
{
	std::ostringstream ss;
	openvdb::io::Stream vdbStream( ss );
	vdbStream.write( *m_grids );
	std::string s = ss.str();

	IECore::UCharVectorDataPtr newByteArray = new IECore::UCharVectorData();
	auto& v = newByteArray->writable();
	v.resize( s.length() );
	std::copy( s.begin(), s.end(), v.begin() );

	return newByteArray;
}

void VDBObject::forceRead(const std::string& name)
{
	openvdb::GridBase::Ptr grid = findGrid( name );
	grid->readNonresidentBuffers();
}

IECore::CompoundObjectPtr VDBObject::metadata(const std::string& name) const
{
	//todo dirty this when the grid has been updated rather
	//than assuming it always has to be done.
	openvdb::GridBase::ConstPtr grid = findGrid( name );

	if (!grid)
	{
		return IECore::CompoundObjectPtr();
	}

	CompoundObjectPtr metadata = new CompoundObject();

	for (auto metaIt = grid->beginMeta(); metaIt != grid->endMeta(); ++metaIt)
	{
		openvdb::Metadata::Ptr ptr = metaIt->second;

		if (metaIt->second->typeName() == "string")
		{
			openvdb::TypedMetadata<openvdb::Name>::ConstPtr typedPtr = openvdb::DynamicPtrCast<openvdb::TypedMetadata<openvdb::Name> >(ptr);

			if (typedPtr)
			{
				StringDataPtr stringData = new StringData();
				stringData->writable() = typedPtr->value();
				metadata->members()[metaIt->first] = stringData;
			}
		}
		else if (metaIt->second->typeName() == "int64")
		{
			openvdb::TypedMetadata<openvdb::Int64>::ConstPtr typedPtr = openvdb::DynamicPtrCast<openvdb::TypedMetadata<openvdb::Int64> >(ptr);
			if (typedPtr)
			{
				Int64DataPtr intData = new Int64Data();
				intData->writable() = typedPtr->value();
				metadata->members()[metaIt->first] = intData;
			}
		}
		else if (metaIt->second->typeName() == "bool")
		{
			openvdb::TypedMetadata<bool>::ConstPtr typedPtr = openvdb::DynamicPtrCast<openvdb::TypedMetadata<bool> > (ptr);
			if (typedPtr)
			{
				BoolDataPtr data = new BoolData();
				data->writable() = typedPtr->value();
				metadata->members()[metaIt->first] = data;
			}

		}
		else if (metaIt->second->typeName() == "vec3i")
		{
			openvdb::TypedMetadata<openvdb::math::Vec3i>::ConstPtr typedPtr = openvdb::DynamicPtrCast<openvdb::TypedMetadata<openvdb::math::Vec3i> >(ptr);
			if (typedPtr)
			{
				V3iDataPtr data = new V3iData();
				data->writable() = Imath::V3i( typedPtr->value().x(), typedPtr->value().y(), typedPtr->value().z() );
				metadata->members()[metaIt->first] = data;
			}
		}
		else
		{
			StringDataPtr stringData = new StringData();
			stringData->writable() = "unsupported type: " + metaIt->second->typeName();
			metadata->members()[metaIt->first] = stringData;
		}
	}
	return metadata;
}

bool VDBObject::isEqualTo( const IECore::Object *other ) const
{
	if (!IECore::VisibleRenderable::isNotEqualTo( other ))
	{
		return false;
	}

	const VDBObject *vdbObject = runTimeCast<const VDBObject>(other);

	// are the grid pointers identical
	return *m_grids == *vdbObject->m_grids;
}

void VDBObject::hash( IECore::MurmurHash &h ) const
{
	IECore::VisibleRenderable::hash( h );

	// hash the pointers of the grids for now. todo discuss with John / Andrew
	for (const auto &grid : *m_grids)
	{
		h.append( (size_t) grid.get() );
	}
}

void VDBObject::copyFrom( const IECore::Object *other, IECore::Object::CopyContext *context  )
{
	IECore::VisibleRenderable::copyFrom( other, context);

	const VDBObject *vdbObject = runTimeCast<const VDBObject>(other);

	for (const auto &grid : *vdbObject->m_grids)
	{
		m_grids->push_back( grid );
	}
}

void VDBObject::save( IECore::Object::SaveContext *context ) const
{
	IECore::VisibleRenderable::save( context );
	throw IECore::NotImplementedException( "VDBObject::save" );
}

void VDBObject::load( IECore::Object::LoadContextPtr context )
{
	IECore::VisibleRenderable::load( context );
	throw IECore::NotImplementedException( "VDBObject::load" );
}

void VDBObject::memoryUsage( IECore::Object::MemoryAccumulator &acc) const
{
	IECore::VisibleRenderable::memoryUsage( acc );

	// todo this is going to over estimate memory usage because the grids might be shared with other VDBObjects
	for ( const auto &grid  : *m_grids )
	{
		acc.accumulate( grid->memUsage() );
	}
}

<commit_msg>VDBObject : remove copies from memoryBuffer<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2015, John Haddon. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include <algorithm>

#include "boost/iostreams/categories.hpp"
#include "boost/iostreams/stream.hpp"

#include "openvdb/openvdb.h"
#include "openvdb/io/Stream.h"

#include "IECore/Exception.h"
#include "IECore/MurmurHash.h"
#include "IECore/SimpleTypedData.h"

#include "GafferVDB/VDBObject.h"

using namespace IECore;
using namespace GafferVDB;

namespace
{

//! Calculate the worldspace bounds - 0.5 padding required to include the full volume and not the bound of the voxel centres.
template<typename T>
Imath::Box<Imath::Vec3<T> > worldBound( const openvdb::GridBase* grid, float padding = 0.50f )
{
	openvdb::Vec3i min = grid->metaValue<openvdb::Vec3i>( grid->META_FILE_BBOX_MIN );
	openvdb::Vec3i max = grid->metaValue<openvdb::Vec3i>( grid->META_FILE_BBOX_MAX );

	openvdb::Vec3d offset = openvdb::Vec3d( padding );
	openvdb::BBoxd indexBounds = openvdb::BBoxd( min - offset, max + offset );
	openvdb::BBoxd worldBounds = grid->transform().indexToWorld( indexBounds );
	openvdb::Vec3d minBB = worldBounds.min();
	openvdb::Vec3d maxBB = worldBounds.max();

	return Imath::Box<Imath::Vec3<T> >( Imath::Vec3<T>( minBB[0], minBB[1], minBB[2] ), Imath::Vec3<T>( maxBB[0], maxBB[1], maxBB[2] ) );
}

///! utility to allow us to stream directly into a UCharVectorData
struct UCharVectorDataSink
{
	typedef char char_type;
	typedef boost::iostreams::sink_tag category;

	UCharVectorDataSink( IECore::UCharVectorData *storage ) : m_storage( storage->writable() )
	{
	}

	std::streamsize write( const char *s, std::streamsize n )
	{
		m_storage.insert( m_storage.end(), s, s + n );
		return n;
	}

	std::vector<unsigned char>& m_storage;
};

}

IE_CORE_DEFINEOBJECTTYPEDESCRIPTION( VDBObject );

const unsigned int VDBObject::m_ioVersion = 0;

VDBObject::VDBObject()
: m_grids(new openvdb::GridPtrVec)
{
}

VDBObject::VDBObject(const std::string& filename)
{
	openvdb::initialize(); // safe to call multiple times but has a performance hit of a mutex.

	// note it seems fine for this file object to go out of scope
	// and grids are still able to pull in additional grid data
	openvdb::io::File file( filename );
	file.open(); //lazy loading of grid data is default enabling OPENVDB_DISABLE_DELAYED_LOAD will load the grids up front

	m_grids = file.getGrids();
}

VDBObject::~VDBObject()
{
}

openvdb::GridBase::ConstPtr VDBObject::findGrid(const std::string& name) const
{

	for(const auto &grid : *m_grids )
	{
		if (grid->getName() == name)
			return grid;
	}

	return openvdb::GridBase::Ptr();
}

openvdb::GridBase::Ptr VDBObject::findGrid(const std::string& name)
{
	for(const auto &grid : *m_grids )
	{
		if (grid->getName() == name)
			return grid;
	}

	return openvdb::GridBase::Ptr();
}

std::vector<std::string> VDBObject::gridNames() const
{
	std::vector<std::string> outputGridNames;
	for(const auto &grid : *m_grids )
	{
		outputGridNames.push_back( grid->getName() );
	}
	return outputGridNames;
}

void VDBObject::addGrid(openvdb::GridBase::Ptr grid)
{
	m_grids->push_back(grid);
}

void VDBObject::removeGrid(const std::string& name)
{
	for(auto it = m_grids->begin(); it != m_grids->end(); ++it )
	{
		if( ( *it )->getName() == name )
		{
			m_grids->erase( it );
			return;
		}
	}
}

Imath::Box3f VDBObject::bound() const
{
	Imath::Box3f combinedBounds;

	for (const auto& grid : *m_grids)
	{
		Imath::Box3f gridBounds = worldBound<float>( grid.get() );

		combinedBounds.extendBy( gridBounds );
	}

	return combinedBounds;
}

void VDBObject::render( IECore::Renderer *renderer ) const
{
}

UCharVectorDataPtr VDBObject::memoryBuffer() const
{
	// estimate the size of the memory required to hand the VDB to arnold.
	// This is required so we can reserve the right amount of space in the output
	// buffer.
	int64_t totalSizeBytes = 0;
	try
	{
		for( const auto &grid : *m_grids )
		{
			totalSizeBytes += grid->metaValue<int64_t>( "file_mem_bytes" );
		}
	}
	catch(const std::exception& e)
	{
		msg( MessageHandler::Warning, "VDBObject::memoryBuffer", "Unable to estimate vdb size." );
	}

	IECore::UCharVectorDataPtr buffer = new IECore::UCharVectorData();
	buffer->writable().reserve( totalSizeBytes );
	UCharVectorDataSink sink( buffer.get() );
	boost::iostreams::stream<UCharVectorDataSink> memoryStream( sink );

	openvdb::io::Stream vdbStream( memoryStream );
	vdbStream.write( *m_grids );

	return buffer;
}

void VDBObject::forceRead(const std::string& name)
{
	openvdb::GridBase::Ptr grid = findGrid( name );
	grid->readNonresidentBuffers();
}

IECore::CompoundObjectPtr VDBObject::metadata(const std::string& name) const
{
	//todo dirty this when the grid has been updated rather
	//than assuming it always has to be done.
	openvdb::GridBase::ConstPtr grid = findGrid( name );

	if (!grid)
	{
		return IECore::CompoundObjectPtr();
	}

	CompoundObjectPtr metadata = new CompoundObject();

	for (auto metaIt = grid->beginMeta(); metaIt != grid->endMeta(); ++metaIt)
	{
		openvdb::Metadata::Ptr ptr = metaIt->second;

		if (metaIt->second->typeName() == "string")
		{
			openvdb::TypedMetadata<openvdb::Name>::ConstPtr typedPtr = openvdb::DynamicPtrCast<openvdb::TypedMetadata<openvdb::Name> >(ptr);

			if (typedPtr)
			{
				StringDataPtr stringData = new StringData();
				stringData->writable() = typedPtr->value();
				metadata->members()[metaIt->first] = stringData;
			}
		}
		else if (metaIt->second->typeName() == "int64")
		{
			openvdb::TypedMetadata<openvdb::Int64>::ConstPtr typedPtr = openvdb::DynamicPtrCast<openvdb::TypedMetadata<openvdb::Int64> >(ptr);
			if (typedPtr)
			{
				Int64DataPtr intData = new Int64Data();
				intData->writable() = typedPtr->value();
				metadata->members()[metaIt->first] = intData;
			}
		}
		else if (metaIt->second->typeName() == "bool")
		{
			openvdb::TypedMetadata<bool>::ConstPtr typedPtr = openvdb::DynamicPtrCast<openvdb::TypedMetadata<bool> > (ptr);
			if (typedPtr)
			{
				BoolDataPtr data = new BoolData();
				data->writable() = typedPtr->value();
				metadata->members()[metaIt->first] = data;
			}

		}
		else if (metaIt->second->typeName() == "vec3i")
		{
			openvdb::TypedMetadata<openvdb::math::Vec3i>::ConstPtr typedPtr = openvdb::DynamicPtrCast<openvdb::TypedMetadata<openvdb::math::Vec3i> >(ptr);
			if (typedPtr)
			{
				V3iDataPtr data = new V3iData();
				data->writable() = Imath::V3i( typedPtr->value().x(), typedPtr->value().y(), typedPtr->value().z() );
				metadata->members()[metaIt->first] = data;
			}
		}
		else
		{
			StringDataPtr stringData = new StringData();
			stringData->writable() = "unsupported type: " + metaIt->second->typeName();
			metadata->members()[metaIt->first] = stringData;
		}
	}
	return metadata;
}

bool VDBObject::isEqualTo( const IECore::Object *other ) const
{
	if (!IECore::VisibleRenderable::isNotEqualTo( other ))
	{
		return false;
	}

	const VDBObject *vdbObject = runTimeCast<const VDBObject>(other);

	// are the grid pointers identical
	return *m_grids == *vdbObject->m_grids;
}

void VDBObject::hash( IECore::MurmurHash &h ) const
{
	IECore::VisibleRenderable::hash( h );

	// hash the pointers of the grids for now. todo discuss with John / Andrew
	for (const auto &grid : *m_grids)
	{
		h.append( (size_t) grid.get() );
	}
}

void VDBObject::copyFrom( const IECore::Object *other, IECore::Object::CopyContext *context  )
{
	IECore::VisibleRenderable::copyFrom( other, context);

	const VDBObject *vdbObject = runTimeCast<const VDBObject>(other);

	for (const auto &grid : *vdbObject->m_grids)
	{
		m_grids->push_back( grid );
	}
}

void VDBObject::save( IECore::Object::SaveContext *context ) const
{
	IECore::VisibleRenderable::save( context );
	throw IECore::NotImplementedException( "VDBObject::save" );
}

void VDBObject::load( IECore::Object::LoadContextPtr context )
{
	IECore::VisibleRenderable::load( context );
	throw IECore::NotImplementedException( "VDBObject::load" );
}

void VDBObject::memoryUsage( IECore::Object::MemoryAccumulator &acc) const
{
	IECore::VisibleRenderable::memoryUsage( acc );

	// todo this is going to over estimate memory usage because the grids might be shared with other VDBObjects
	for ( const auto &grid  : *m_grids )
	{
		acc.accumulate( grid->memUsage() );
	}
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    IsoSurfaceExtraction.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

//  Software Guide : BeginLatex
//
//  Software Guide : EndLatex

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageRegionIterator.h"
#include "itkMesh.h"
#include "itkBinaryMask3DMeshSource.h"

int main(int argc, char * argv[] )
{

  if( argc < 3 )
    {
    std::cerr << "Usage: IsoSurfaceExtraction  inputImageFile   isoValue " << std::endl;
    return EXIT_FAILURE;
    }

// Software Guide : BeginCodeSnippet
  // Define the dimension of the images
  const unsigned int Dimension = 3;

  // Define the pixel type of the input image
  typedef unsigned short  PixelType;

  // Declare the types of the output images
  typedef itk::Image< PixelType, Dimension >   ImageType;

  // Declare the reader type
  typedef itk::ImageFileReader< ImageType >    ReaderType;

  // Instantiate the reader object and attempt to read the image
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );

  try
    {
    reader->Update();
    }
  catch( itk::ExceptionObject & exp )
    {
    std::cerr << "Exception thrown while reading the input file " << std::endl;
    std::cerr << exp << std::endl;
    return EXIT_FAILURE;
    }

  // Declare the type of the Mesh
  typedef itk::Mesh<double>                         MeshType;

  // Declare the Filter for Iso-surface extraction
  typedef itk::BinaryMask3DMeshSource< MeshType >   MeshSourceType;

  MeshSourceType::Pointer meshSource = MeshSourceType::New();

  const PixelType isovalue = atof( argv[2] );

  meshSource->SetBinaryImage( reader->GetOutput() );

  meshSource->SetObjectValue( isovalue );

  try
    {
    meshSource->Update();
    }
  catch( itk::ExceptionObject & exp )
    {
    std::cerr << "Exception thrown during Update() " << std::endl;
    std::cerr << exp << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << meshSource->GetNumberOfNodes() << std::endl;
  std::cout << meshSource->GetNumberOfCells() << std::endl;

  return EXIT_SUCCESS;

// Software Guide : EndCodeSnippet

}

<commit_msg>ERR: warnings.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    IsoSurfaceExtraction.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

//  Software Guide : BeginLatex
//
//  Software Guide : EndLatex

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageRegionIterator.h"
#include "itkMesh.h"
#include "itkBinaryMask3DMeshSource.h"

int main(int argc, char * argv[] )
{

  if( argc < 3 )
    {
    std::cerr << "Usage: IsoSurfaceExtraction  inputImageFile   isoValue " << std::endl;
    return EXIT_FAILURE;
    }

// Software Guide : BeginCodeSnippet
  // Define the dimension of the images
  const unsigned int Dimension = 3;

  // Define the pixel type of the input image
  typedef unsigned short  PixelType;

  // Declare the types of the output images
  typedef itk::Image< PixelType, Dimension >   ImageType;

  // Declare the reader type
  typedef itk::ImageFileReader< ImageType >    ReaderType;

  // Instantiate the reader object and attempt to read the image
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );

  try
    {
    reader->Update();
    }
  catch( itk::ExceptionObject & exp )
    {
    std::cerr << "Exception thrown while reading the input file " << std::endl;
    std::cerr << exp << std::endl;
    return EXIT_FAILURE;
    }

  // Declare the type of the Mesh
  typedef itk::Mesh<double>                         MeshType;

  // Declare the Filter for Iso-surface extraction
  typedef itk::BinaryMask3DMeshSource< MeshType >   MeshSourceType;

  MeshSourceType::Pointer meshSource = MeshSourceType::New();

  const PixelType isovalue = static_cast<PixelType>(atof( argv[2] ));

  meshSource->SetBinaryImage( reader->GetOutput() );

  meshSource->SetObjectValue( isovalue );

  try
    {
    meshSource->Update();
    }
  catch( itk::ExceptionObject & exp )
    {
    std::cerr << "Exception thrown during Update() " << std::endl;
    std::cerr << exp << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << meshSource->GetNumberOfNodes() << std::endl;
  std::cout << meshSource->GetNumberOfCells() << std::endl;

  return EXIT_SUCCESS;

// Software Guide : EndCodeSnippet

}

<|endoftext|>


<commit_before>#if !defined (__CINT__) || defined (__CLING__)
#include "AliAnalysisAlien.h"
#include "AliAnalysisManager.h"
#include "AliAODInputHandler.h"

#include "AliPhysicsSelectionTask.h"
#include "AliMultSelectionTask.h"
#include "AliAnalysisTaskPIDResponse.h"

#include "AliAnalysisTaskSEHFTreeCreator.h"
#endif

//SETTINGS
//************************************

Bool_t runLocal=kTRUE;                                  // flag to run locally on AliAOD.root + AliAOD.VertexingHF.root
TString pathToLocalAODfiles="/data2/InputsAODLc/002";               // path to find AOD files when running locally
Bool_t runGridTest=kFALSE;                                // flag to run a grid test: kTRUE (+runLocal=kFALSE). To run job on GRID: runGridTest=kFALSE, runLocal=kFALSE
TString runMode="full";                                  // sets the run grid mode: "full", "terminate"

TString aliPhysVersion="vAN-20180930-1";

Bool_t isRunOnMC=kFALSE;                                 // set to kTRUE to run on Mone Carlo and uncomment/comment accordingly the following lines about paths on Alien
//paths on Alien
// Monte Carlo
//TString gridDataDir="/alice/sim/2016/LHC16i2a/";
//TString gridDataPattern="/AOD198";
// Data
TString gridDataDir="/alice/data/2015/LHC15o/";
TString gridDataPattern="/pass1/AOD194";

// Alien output directory
TString gridWorkingDir="testNtupleCreator";
TString gridOutputDir="output";

//run numbers
const Int_t nruns = 1;
Int_t runlist[nruns] = {246994};

//Task configuration
TString cutFile="D0DsDplusDstarLcBplusCuts_pp.root";          // file containing the cuts for the different mesons
  														 // to generate the cut file: 1) move to cutfile directory
  														 //                           2) .L makeCutsTreeCreator.C
  														 //                           3) makeCutsTreeCreator();
  														 // to run with ROOT5/6 generate the cut file using AliPhysics built on ROOT5/6

//************************************

void runAnalysis()
{
    // set if you want to run the analysis locally (kTRUE), or on grid (kFALSE)
    Bool_t local = runLocal;
    // if you run on grid, specify test mode (kTRUE) or full grid model (kFALSE)
    Bool_t gridTest = runGridTest;

    // since we will compile a class, tell root where to look for headers
#if !defined (__CINT__) || defined (__CLING__)
    gInterpreter->ProcessLine(".include $ROOTSYS/include");
    gInterpreter->ProcessLine(".include $ALICE_ROOT/include");
#else
    gROOT->ProcessLine(".include $ROOTSYS/include");
    gROOT->ProcessLine(".include $ALICE_ROOT/include");
#endif

    // create the analysis manager
    AliAnalysisManager *mgr = new AliAnalysisManager("AnalysisTaskExample");
    AliAODInputHandler *aodH = new AliAODInputHandler();
    mgr->SetInputEventHandler(aodH);

    // compile the class and load the add task macro
    // here we have to differentiate between using the just-in-time compiler
    // from root6, or the interpreter of root5
#if !defined (__CINT__) || defined (__CLING__)

    AliPhysicsSelectionTask *physseltask = reinterpret_cast<AliPhysicsSelectionTask *>(gInterpreter->ProcessLine(Form(".x %s (%d)", gSystem->ExpandPathName("$ALICE_PHYSICS/OADB/macros/AddTaskPhysicsSelection.C"),isRunOnMC)));

    AliAnalysisTaskPIDResponse *pidResp = reinterpret_cast<AliAnalysisTaskPIDResponse *>(gInterpreter->ProcessLine(Form(".x %s (%d)", gSystem->ExpandPathName("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C"),isRunOnMC)));

    //AliMultSelectionTask *multSel = reinterpret_cast<AliMultSelectionTask *>(gInterpreter->ProcessLine(Form(".x %s", gSystem->ExpandPathName("$ALICE_PHYSICS/OADB/COMMON/MULTIPLICITY/macros/AddTaskMultSelection.C"))));
    //multSel->SetAlternateOADBforEstimators("LHC15o-DefaultMC-HIJING");

    //gInterpreter->LoadMacro("AliHFCutOptTreeHandler.cxx++g");
    //gInterpreter->LoadMacro("AliAnalysisTaskSEHFTreeCreator.cxx++g");
    AliAnalysisTaskSEHFTreeCreator *task = reinterpret_cast<AliAnalysisTaskSEHFTreeCreator*>(gInterpreter->ProcessLine(Form(".x %s (%d,%d,\"%s\",\"%s\")",gSystem->ExpandPathName("$ALICE_PHYSICS/PWGHF/treeHF/macros/AddTaskHFTreeCreator.C"),isRunOnMC, 1, "HFTreeCreator", cutFile.Data())));

    AliAnalysisTaskSECleanupVertexingHF *taskclean =reinterpret_cast<AliAnalysisTaskSECleanupVertexingHF *>(gInterpreter->ProcessLine(Form(".x %s", gSystem->ExpandPathName("$ALICE_PHYSICS/PWGHF/vertexingHF/macros/AddTaskCleanupVertexingHF.C"))));

#else

    gROOT->LoadMacro("$ALICE_PHYSICS/OADB/macros/AddTaskPhysicsSelection.C");
    AliPhysicsSelectionTask *physSelTask= AddTaskPhysicsSelection(isRunOnMC);

    gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
    AliAnalysisTaskPIDResponse *pidResp = AddTaskPIDResponse(isRunOnMC);

    gROOT->LoadMacro("$ALICE_PHYSICS/OADB/COMMON/MULTIPLICITY/macros/AddTaskMultSelection.C");
    AliMultSelectionTask *multSel = AddTaskMultSelection();
    //multSel->SetAlternateOADBforEstimators("LHC15o-DefaultMC-HIJING");

    gROOT->LoadMacro("AliHFCutOptTreeHandler.cxx++g");
    gROOT->LoadMacro("AliAnalysisTaskSEHFTreeCreator.cxx++g");
    gROOT->LoadMacro("AddTaskHFTreeCreator.C");
    AliAnalysisTaskSEHFTreeCreator *task = AddTaskHFTreeCreator(isRunOnMC, 1, "HFTreeCreator", cutFile.Data());

    gROOT->LoadMacro("$ALICE_PHYSICS/PWGHF/vertexingHF/macros/AddTaskCleanupVertexingHF.C");
    AliAnalysisTaskSECleanupVertexingHF *taskclean = AddTaskCleanupVertexingHF();

#endif

    if(!mgr->InitAnalysis()) return;
    mgr->SetDebugLevel(2);
    mgr->PrintStatus();
    mgr->SetUseProgressBar(1, 25);

    if(local) {

        // if you want to run locally, we need to define some input
        TChain* chainAOD = new TChain("aodTree");
        TChain *chainAODfriend = new TChain("aodTree");

        // add a few files to the chain (change this so that your local files are added)
        chainAOD->Add(Form("%s/AliAOD.root",pathToLocalAODfiles.Data()));
        chainAODfriend->Add(Form("%s/AliAOD.VertexingHF.root",pathToLocalAODfiles.Data()));

        chainAOD->AddFriend(chainAODfriend);

        // start the analysis locally, reading the events from the tchain
        mgr->StartAnalysis("local", chainAOD, 1000, 0);

    } else {

        // if we want to run on grid, we create and configure the plugin
        AliAnalysisAlien *alienHandler = new AliAnalysisAlien();

        // also specify the include (header) paths on grid
        alienHandler->AddIncludePath("-I. -I$ROOTSYS/include -I$ALICE_ROOT -I$ALICE_ROOT/include -I$ALICE_PHYSICS/include");

        // make sure your source files get copied to grid
        //alienHandler->SetAdditionalLibs("AliHFCutOptTreeHandler.cxx AliHFCutOptTreeHandler.h");
        alienHandler->SetAdditionalLibs("AliHFCutOptTreeHandler.cxx AliHFCutOptTreeHandler.h AliAnalysisTaskSEHFTreeCreator.cxx AliAnalysisTaskSEHFTreeCreator.h");
        alienHandler->SetAnalysisSource("AliHFCutOptTreeHandler.cxx AliAnalysisTaskSEHFTreeCreator.cxx");

        // select the aliphysics version. all other packages
        // are LOADED AUTOMATICALLY!
        alienHandler->SetAliPhysicsVersion(aliPhysVersion.Data());

        // set the Alien API version
        alienHandler->SetAPIVersion("V1.1x");

        // select the input data
        alienHandler->SetGridDataDir(gridDataDir.Data());
        alienHandler->SetDataPattern(Form("%s/*AliAOD.root",gridDataPattern.Data()));
        alienHandler->SetFriendChainName("AliAOD.VertexingHF.root");

        // MC has no prefix, data has prefix 000
        if(!isRunOnMC)alienHandler->SetRunPrefix("000");

        for(Int_t k=0; k<nruns; k++){
            alienHandler->AddRunNumber(runlist[k]);
        }
        alienHandler->SetNrunsPerMaster(nruns);

        // number of files per subjob
        alienHandler->SetSplitMaxInputFileNumber(1);
        alienHandler->SetExecutable("myTask.sh");

        // specify how many seconds your job may take
        alienHandler->SetTTL(10000);
        alienHandler->SetJDLName("myTask.jdl");

        alienHandler->SetOutputToRunNo(kTRUE);
        alienHandler->SetKeepLogs(kTRUE);

        // merging: run with kTRUE to merge on grid
        // after re-running the jobs in SetRunMode("terminate")
        // (see below) mode, set SetMergeViaJDL(kFALSE)
        // to collect final results
        alienHandler->SetMaxMergeStages(3); //2, 3
        alienHandler->SetMergeViaJDL(kTRUE);

        // define the output folders
        alienHandler->SetGridWorkingDir(gridWorkingDir.Data());
        alienHandler->SetGridOutputDir(gridOutputDir.Data());

        // connect the alien plugin to the manager
        mgr->SetGridHandler(alienHandler);

        if(gridTest) {

            // speficy on how many files you want to run
            alienHandler->SetNtestFiles(1);
            // and launch the analysis
            alienHandler->SetRunMode("test");
            mgr->StartAnalysis("grid");
        }
        else {
            // else launch the full grid analysis
            alienHandler->SetRunMode(runMode.Data()); //terminate
            mgr->StartAnalysis("grid");
        }
    }
}
<commit_msg>Fix for running on data and MC<commit_after>#if !defined (__CINT__) || defined (__CLING__)
#include "AliAnalysisAlien.h"
#include "AliAnalysisManager.h"
#include "AliAODInputHandler.h"

#include "AliPhysicsSelectionTask.h"
#include "AliMultSelectionTask.h"
#include "AliAnalysisTaskPIDResponse.h"

#include "AliAnalysisTaskSEHFTreeCreator.h"
#endif

//SETTINGS
//************************************
Bool_t runLocal=kTRUE;                                  // flag to run locally on AliAOD.root + AliAOD.VertexingHF.root
TString pathToLocalAODfiles;
Bool_t runGridTest=kFALSE;                                // flag to run a grid test: kTRUE (+runLocal=kFALSE). To run job on GRID: runGridTest=kFALSE, runLocal=kFALSE
TString runMode="full";                                  // sets the run grid mode: "full", "terminate"

TString aliPhysVersion="vAN-20180930-1";

//paths on Alien
// Monte Carlo
//TString gridDataDir="/alice/sim/2016/LHC16i2a/";
//TString gridDataPattern="/AOD198";
// Data
TString gridDataDir;
TString gridDataPattern="/pass1/AOD194";

// Alien output directory
TString gridWorkingDir="testNtupleCreator";
TString gridOutputDir="output";

//run numbers
const Int_t nruns = 1;
Int_t runlist[nruns] = {246994};

//Task configuration
TString cutFile="D0DsDplusDstarLcBplusCuts_pp.root";          // file containing the cuts for the different mesons
  														 // to generate the cut file: 1) move to cutfile directory
  														 //                           2) .L makeCutsTreeCreator.C
  														 //                           3) makeCutsTreeCreator();
  														 // to run with ROOT5/6 generate the cut file using AliPhysics built on ROOT5/6

//************************************

void runAnalysis(Bool_t isRunOnMC=kTRUE)
{
  if (isRunOnMC == kTRUE) {
    pathToLocalAODfiles = "/data2/highmultppAOD/mc/LHC18f4a";
    gridDataDir="/alice/sim/2018/LHC18f4a";
    std::cout<<"Running on MC"<<std::endl;
  }
  if (isRunOnMC == kFALSE){
    pathToLocalAODfiles = "/data2/highmultppAOD/data/LHC18f";
    gridDataDir="/alice/data/2018/LHC18f";
  }
    // set if you want to run the analysis locally (kTRUE), or on grid (kFALSE)
    Bool_t local = runLocal;
    // if you run on grid, specify test mode (kTRUE) or full grid model (kFALSE)
    Bool_t gridTest = runGridTest;

    // since we will compile a class, tell root where to look for headers
#if !defined (__CINT__) || defined (__CLING__)
    gInterpreter->ProcessLine(".include $ROOTSYS/include");
    gInterpreter->ProcessLine(".include $ALICE_ROOT/include");
#else
    gROOT->ProcessLine(".include $ROOTSYS/include");
    gROOT->ProcessLine(".include $ALICE_ROOT/include");
#endif

    // create the analysis manager
    AliAnalysisManager *mgr = new AliAnalysisManager("AnalysisTaskExample");
    AliAODInputHandler *aodH = new AliAODInputHandler();
    mgr->SetInputEventHandler(aodH);

    // compile the class and load the add task macro
    // here we have to differentiate between using the just-in-time compiler
    // from root6, or the interpreter of root5
#if !defined (__CINT__) || defined (__CLING__)

    AliPhysicsSelectionTask *physseltask = reinterpret_cast<AliPhysicsSelectionTask *>(gInterpreter->ProcessLine(Form(".x %s (%d)", gSystem->ExpandPathName("$ALICE_PHYSICS/OADB/macros/AddTaskPhysicsSelection.C"),isRunOnMC)));

    AliAnalysisTaskPIDResponse *pidResp = reinterpret_cast<AliAnalysisTaskPIDResponse *>(gInterpreter->ProcessLine(Form(".x %s (%d)", gSystem->ExpandPathName("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C"),isRunOnMC)));

    //AliMultSelectionTask *multSel = reinterpret_cast<AliMultSelectionTask *>(gInterpreter->ProcessLine(Form(".x %s", gSystem->ExpandPathName("$ALICE_PHYSICS/OADB/COMMON/MULTIPLICITY/macros/AddTaskMultSelection.C"))));
    //multSel->SetAlternateOADBforEstimators("LHC15o-DefaultMC-HIJING");

    //gInterpreter->LoadMacro("AliHFCutOptTreeHandler.cxx++g");
    //gInterpreter->LoadMacro("AliAnalysisTaskSEHFTreeCreator.cxx++g");
    AliAnalysisTaskSEHFTreeCreator *task = reinterpret_cast<AliAnalysisTaskSEHFTreeCreator*>(gInterpreter->ProcessLine(Form(".x %s (%d,%d,\"%s\",\"%s\", %d,%d,%d)",gSystem->ExpandPathName("$ALICE_PHYSICS/PWGHF/treeHF/macros/AddTaskHFTreeCreator.C"),isRunOnMC, 0, "HFTreeCreator", cutFile.Data(), 1, kTRUE, kTRUE)));

    AliAnalysisTaskSECleanupVertexingHF *taskclean =reinterpret_cast<AliAnalysisTaskSECleanupVertexingHF *>(gInterpreter->ProcessLine(Form(".x %s", gSystem->ExpandPathName("$ALICE_PHYSICS/PWGHF/vertexingHF/macros/AddTaskCleanupVertexingHF.C"))));

#else

    gROOT->LoadMacro("$ALICE_PHYSICS/OADB/macros/AddTaskPhysicsSelection.C");
    AliPhysicsSelectionTask *physSelTask= AddTaskPhysicsSelection(isRunOnMC);

    gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
    AliAnalysisTaskPIDResponse *pidResp = AddTaskPIDResponse(isRunOnMC);

    gROOT->LoadMacro("$ALICE_PHYSICS/OADB/COMMON/MULTIPLICITY/macros/AddTaskMultSelection.C");
    AliMultSelectionTask *multSel = AddTaskMultSelection();
    //multSel->SetAlternateOADBforEstimators("LHC15o-DefaultMC-HIJING");

    gROOT->LoadMacro("AliHFCutOptTreeHandler.cxx++g");
    gROOT->LoadMacro("AliAnalysisTaskSEHFTreeCreator.cxx++g");
    gROOT->LoadMacro("AddTaskHFTreeCreator.C");
    AliAnalysisTaskSEHFTreeCreator *task = AddTaskHFTreeCreator(isRunOnMC, 0, "HFTreeCreator", cutFile.Data(), 1, kTRUE, kTRUE);

    gROOT->LoadMacro("$ALICE_PHYSICS/PWGHF/vertexingHF/macros/AddTaskCleanupVertexingHF.C");
    AliAnalysisTaskSECleanupVertexingHF *taskclean = AddTaskCleanupVertexingHF();

#endif

    if(!mgr->InitAnalysis()) return;
    mgr->SetDebugLevel(2);
    mgr->PrintStatus();
    mgr->SetUseProgressBar(1, 25);

    if(local) {

        // if you want to run locally, we need to define some input
        TChain* chainAOD = new TChain("aodTree");
        TChain *chainAODfriend = new TChain("aodTree");

        // add a few files to the chain (change this so that your local files are added)
        chainAOD->Add(Form("%s/AliAOD.root",pathToLocalAODfiles.Data()));
        chainAODfriend->Add(Form("%s/AliAOD.VertexingHF.root",pathToLocalAODfiles.Data()));

        chainAOD->AddFriend(chainAODfriend);

        // start the analysis locally, reading the events from the tchain
        mgr->StartAnalysis("local", chainAOD, 1000, 0);

    } else {

        // if we want to run on grid, we create and configure the plugin
        AliAnalysisAlien *alienHandler = new AliAnalysisAlien();

        // also specify the include (header) paths on grid
        alienHandler->AddIncludePath("-I. -I$ROOTSYS/include -I$ALICE_ROOT -I$ALICE_ROOT/include -I$ALICE_PHYSICS/include");

        // make sure your source files get copied to grid
        //alienHandler->SetAdditionalLibs("AliHFCutOptTreeHandler.cxx AliHFCutOptTreeHandler.h");
        alienHandler->SetAdditionalLibs("AliHFCutOptTreeHandler.cxx AliHFCutOptTreeHandler.h AliAnalysisTaskSEHFTreeCreator.cxx AliAnalysisTaskSEHFTreeCreator.h");
        alienHandler->SetAnalysisSource("AliHFCutOptTreeHandler.cxx AliAnalysisTaskSEHFTreeCreator.cxx");

        // select the aliphysics version. all other packages
        // are LOADED AUTOMATICALLY!
        alienHandler->SetAliPhysicsVersion(aliPhysVersion.Data());

        // set the Alien API version
        alienHandler->SetAPIVersion("V1.1x");

        // select the input data
        alienHandler->SetGridDataDir(gridDataDir.Data());
        alienHandler->SetDataPattern(Form("%s/*AliAOD.root",gridDataPattern.Data()));
        alienHandler->SetFriendChainName("AliAOD.VertexingHF.root");

        // MC has no prefix, data has prefix 000
        if(!isRunOnMC)alienHandler->SetRunPrefix("000");

        for(Int_t k=0; k<nruns; k++){
            alienHandler->AddRunNumber(runlist[k]);
        }
        alienHandler->SetNrunsPerMaster(nruns);

        // number of files per subjob
        alienHandler->SetSplitMaxInputFileNumber(1);
        alienHandler->SetExecutable("myTask.sh");

        // specify how many seconds your job may take
        alienHandler->SetTTL(10000);
        alienHandler->SetJDLName("myTask.jdl");

        alienHandler->SetOutputToRunNo(kTRUE);
        alienHandler->SetKeepLogs(kTRUE);

        // merging: run with kTRUE to merge on grid
        // after re-running the jobs in SetRunMode("terminate")
        // (see below) mode, set SetMergeViaJDL(kFALSE)
        // to collect final results
        alienHandler->SetMaxMergeStages(3); //2, 3
        alienHandler->SetMergeViaJDL(kTRUE);

        // define the output folders
        alienHandler->SetGridWorkingDir(gridWorkingDir.Data());
        alienHandler->SetGridOutputDir(gridOutputDir.Data());

        // connect the alien plugin to the manager
        mgr->SetGridHandler(alienHandler);

        if(gridTest) {

            // speficy on how many files you want to run
            alienHandler->SetNtestFiles(1);
            // and launch the analysis
            alienHandler->SetRunMode("test");
            mgr->StartAnalysis("grid");
        }
        else {
            // else launch the full grid analysis
            alienHandler->SetRunMode(runMode.Data()); //terminate
            mgr->StartAnalysis("grid");
        }
    }
}
<|endoftext|>


<commit_before>#include "optionparser.h"
#include <iostream>

enum  optionIndex { UNKNOWN, HELP, PLUS };
const option::Descriptor usage[] =
{
  {UNKNOWN, 0,"", "",option::Arg::None, "USAGE: example [options]\n\n"
   "Options:" },
  {HELP,    0,"", "help",option::Arg::None, "  --help  \tPrint usage and exit." },
  {PLUS,    0,"p", "plus",option::Arg::None, "  --plus, -p  \tIncrement count." },
  {UNKNOWN, 0,"",  "",option::Arg::None, "\nExamples:\n"
   "  example --unknown -- --this_is_no_option\n"
   "  example -unk --plus -ppp file1 file2\n" },
  {0,0,0,0,0,0}
};

int main(int argc, char *argv[])
{

  return 0;
}
<commit_msg>Set up argparser for FastSimulate<commit_after>#include <iostream>
#include "optionparser.h"

enum  optionIndex { UNKNOWN, HELP, RUNS, EXPERIMENTS, TRIALS, OUTPUTNAME };
const option::Descriptor usage[] =
{
 {UNKNOWN, 0,"" , ""    ,option::Arg::None, "USAGE: example [options]\n\n"
                                            "Options:" },
 {HELP,    0,"" , "help",option::Arg::None, "  --help  \tPrint usage and exit." },
 {TRIALS,  0,"t", "trials",option::Arg::Optional, "  --trials, -t  \t(Default 100) Number of TRIALS (times graph will be re-built with new edges)" },
 {EXPERIMENTS,  0,"e", "experiments",option::Arg::Optional, "  --experiments, -e  \t(Default 50) Number of EXPERIMENTS per TRIAL (new start and end nodes, on network with same edges)" },
 {RUNS,  0,"r", "runs",option::Arg::Optional, "  --runs, -r  \t(Default 10) Number of RUNS per EXPERIMENTS (exact same start and end nodes, on network with same edges)" },
 {OUTPUTNAME,  0,"o", "output",option::Arg::Optional, "  --output, -o  \tSpecify output filename (end with .csv)" },
 {UNKNOWN, 0,"" ,  ""   ,option::Arg::None, "Examples:\n"
 "\n"
 "./SimulateP2PNetwork.py 30 randomwalk -o output.csv\n"
 "This will simulate a network of 30 vertices and use the random walk algorithm, outputs in output.csv\n"
 "\n"
 "./SimulateP2PNetwork.py 500 bfs -e 20\n"
 "This will simulate a network of 500 verticies, using the BFS algorithm, and run a"
 "new experiment (assign new start and end nodes) on each graph 20 times.\n"
 "\n"
 "./SimulateP2PNetwork.py 350 randomwalk -e 30 -t 200\n"
 "This will simulate a network of 500 verticies, using the randomwalk algorithm, run a"
 "new trial (assign new start and end nodes) on each graph 30 times and re-build (assign new edges) the graph 200 times.\n"
 "\n"
 "Output: a csv in the following form (one line per experiment);\n"
 "num vertices, num edges, algorithm used, average length of path found\n"
 "Ex:\n"
 "300,543,randomwalk,102,False\n"
 "300,543,randomwalk,34,False\n"
 "300,1120,randomwalk,3,True\n"
 ".\n"
 ".\n"
 "."},
 {0,0,0,0,0,0}
};

int main(int argc, char* argv[])
{
  argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present
  option::Stats  stats(usage, argc, argv);
  option::Option *options = new option::Option[stats.options_max];
  option::Option *buffer = new option::Option[stats.buffer_max];
  option::Parser parse(usage, argc, argv, options, buffer);
  if (parse.error())
    return 1;

  if (options[HELP] || argc == 0) {
    option::printUsage(std::cout, usage);
    return 0;
  }

  for (option::Option* opt = options[UNKNOWN]; opt; opt = opt->next())
    std::cout << "Unknown option: " << opt->name << "\n";

  for (int i = 0; i < parse.nonOptionsCount(); ++i)
    std::cout << "Non-option #" << i << ": " << parse.nonOption(i) << "\n";
printf("Fuck");
}
<|endoftext|>


<commit_before>#include "listmodelvariables.h"

#include <QMimeData>

#include "column.h"

#include <QDebug>

ListModelVariables::ListModelVariables(QObject *parent) :
	QAbstractListModel(parent)
{
	_variableTypesAllowed = Column::ColumnTypeNominal | Column::ColumnTypeOrdinal | Column::ColumnTypeScale;

	_nominalIcon = QIcon(":/icons/variable-nominal.png");
	_ordinalIcon = QIcon(":/icons/variable-ordinal.png");
	_scaleIcon = QIcon(":/icons/variable-scale.png");

	_dropActions = Qt::MoveAction;
	_dragActions = Qt::MoveAction;

	_defaultTarget = NULL;

	_mimeType = "application/vnd.list.variable";
}

void ListModelVariables::setVariableTypesAllowed(int variableTypesAllowed)
{
	_variableTypesAllowed = variableTypesAllowed;
}

int ListModelVariables::variableTypesAllowed()
{
	return _variableTypesAllowed;
}

int ListModelVariables::rowCount(const QModelIndex &) const
{
	return _variables.length();
}

QVariant ListModelVariables::data(const QModelIndex &index, int role) const
{
	int row = index.row();

	if (role == Qt::DisplayRole)
	{
		return QVariant(_variables.at(row).first);
	}
	else if (role == Qt::DecorationRole)
	{
		switch (_variables.at(row).second)
		{
		case Column::ColumnTypeNominal:
			return QVariant(_nominalIcon);
		case Column::ColumnTypeOrdinal:
			return QVariant(_ordinalIcon);
		case Column::ColumnTypeScale:
			return QVariant(_scaleIcon);
		default:
			return QVariant();
		}
	}
	else
	{
		return QVariant();
	}
}

bool ListModelVariables::insertRows(int row, int count, const QModelIndex &parent)
{
	beginInsertRows(parent, row, row + count - 1);
	for (int i = 0; i < count; i++)
		_variables.insert(row, ColumnInfo(QString(), 0));
	endInsertRows();
	return true;
}

Qt::ItemFlags ListModelVariables::flags(const QModelIndex &index) const
{
	if (index.isValid())
	{
		if (isForbidden(_variables.at(index.row()).second))
			return Qt::ItemNeverHasChildren;

		return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemNeverHasChildren | Qt::ItemIsDragEnabled;
	}
	else
		return Qt::ItemIsEnabled | Qt::ItemIsDropEnabled;
}

Qt::DropActions ListModelVariables::supportedDropActions() const
{
	return _dropActions;
}

Qt::DropActions ListModelVariables::supportedDragActions() const
{
	return _dragActions;
}

QStringList ListModelVariables::mimeTypes() const
{
	QStringList types;

	types << _mimeType;

	return types;
}

QMimeData *ListModelVariables::mimeData(const QModelIndexList &indexes) const
{
	QMimeData *mimeData = new QMimeData();
	QByteArray encodedData;

	QDataStream dataStream(&encodedData, QIODevice::WriteOnly);

	dataStream << indexes.length();

	foreach (const QModelIndex &index, indexes)
	{
		if (index.isValid())
		{
			ColumnInfo info = _variables.at(index.row());
			dataStream << info;
		}
	}

	ListModelVariables* th1s = (ListModelVariables*) this;
	th1s->_mimeData = mimeData;

	mimeData->setData(_mimeType, encodedData);

	return mimeData;
}

void ListModelVariables::mimeDataMoved(const QModelIndexList &indexes)
{
	beginResetModel();

	QModelIndexList sorted = indexes;

	qSort(sorted.begin(), sorted.end(), qGreater<QModelIndex>());

	foreach (const QModelIndex &index, sorted)
		_variables.removeAt(index.row());

	endResetModel();
}

bool ListModelVariables::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
{
	if (_dragActions == Qt::CopyAction && _dropActions == Qt::MoveAction && action == Qt::MoveAction) // if delete
		return true;

	if ( ! canDropMimeData(data, action, row, column, parent))
		return false;

	if (action == Qt::IgnoreAction)
		return true;

	if (data->hasFormat(_mimeType))
	{
		QByteArray encodedData = data->data(_mimeType);
		QDataStream stream(&encodedData, QIODevice::ReadOnly);
		QList<ColumnInfo> newItems;
		int rows = 0;

		if (stream.atEnd())
			return false;

		int count;
		stream >> count;

		while (!stream.atEnd())
		{
			ColumnInfo variable;
			stream >> variable;

			if (_variables.contains(variable))
				continue;

			newItems << variable;
			++rows;
		}

		if (rows == 0)
			return false;

		int beginRow;

		if (row != -1)
			beginRow = row;
		else if (parent.isValid())
			beginRow = parent.row();
		else
			beginRow = rowCount(QModelIndex());

		int r = 0;
		foreach (const ColumnInfo &item, _variables)
		{
			if (isForbidden(item.second))
				break;
			r++;
		}

		if (r < beginRow)
			beginRow = r;

		insertRows(beginRow, rows, QModelIndex());

		r = 0;
		foreach (const ColumnInfo &item, newItems)
			_variables[beginRow + r++] = item;

		emit dataChanged(index(beginRow, 0), index(beginRow + r, 0));

		return true;
	}

	return false;
}

bool ListModelVariables::canDropMimeData(const QMimeData *data, Qt::DropAction action, int, int, const QModelIndex &) const
{
	if (_dragActions == Qt::CopyAction && _dropActions == Qt::MoveAction && action == Qt::MoveAction) // if delete
		return true;

	if (data->hasFormat(_mimeType))
	{
		QByteArray encodedData = data->data(_mimeType);
		QDataStream stream(&encodedData, QIODevice::ReadOnly);

		if (stream.atEnd()) // is empty
			return false;

		int count;
		stream >> count;

		while (!stream.atEnd())
		{
			ColumnInfo variable;
			stream >> variable;

			if (isForbidden(variable.second))
				return false;
		}

		return true;
	}
	else
	{
		return false;
	}
}

void ListModelVariables::setSupportedDropActions(Qt::DropActions actions)
{
	_dropActions = actions;
}

void ListModelVariables::setSupportedDragActions(Qt::DropActions actions)
{
	_dragActions = actions;
}

void ListModelVariables::setMimeType(const QString &mimeType)
{
	_mimeType = mimeType;
}

bool ListModelVariables::isForbidden(int variableType) const
{
	return variableType & ~_variableTypesAllowed;
}

bool ListModelVariables::isDroppingToSelf(const QMimeData *mimeData) const
{
	return _mimeData == mimeData;
}
<commit_msg>Remove incompatibles with Qt 5.1<commit_after>#include "listmodelvariables.h"

#include <QMimeData>

#include "column.h"

#include <QDebug>

ListModelVariables::ListModelVariables(QObject *parent) :
	QAbstractListModel(parent)
{
	_variableTypesAllowed = Column::ColumnTypeNominal | Column::ColumnTypeOrdinal | Column::ColumnTypeScale;

	_nominalIcon = QIcon(":/icons/variable-nominal.png");
	_ordinalIcon = QIcon(":/icons/variable-ordinal.png");
	_scaleIcon = QIcon(":/icons/variable-scale.png");

	_dropActions = Qt::MoveAction;
	_dragActions = Qt::MoveAction;

	_defaultTarget = NULL;

	_mimeType = "application/vnd.list.variable";
}

void ListModelVariables::setVariableTypesAllowed(int variableTypesAllowed)
{
	_variableTypesAllowed = variableTypesAllowed;
}

int ListModelVariables::variableTypesAllowed()
{
	return _variableTypesAllowed;
}

int ListModelVariables::rowCount(const QModelIndex &) const
{
	return _variables.length();
}

QVariant ListModelVariables::data(const QModelIndex &index, int role) const
{
	int row = index.row();

	if (role == Qt::DisplayRole)
	{
		return QVariant(_variables.at(row).first);
	}
	else if (role == Qt::DecorationRole)
	{
		switch (_variables.at(row).second)
		{
		case Column::ColumnTypeNominal:
			return QVariant(_nominalIcon);
		case Column::ColumnTypeOrdinal:
			return QVariant(_ordinalIcon);
		case Column::ColumnTypeScale:
			return QVariant(_scaleIcon);
		default:
			return QVariant();
		}
	}
	else
	{
		return QVariant();
	}
}

bool ListModelVariables::insertRows(int row, int count, const QModelIndex &parent)
{
	beginInsertRows(parent, row, row + count - 1);
	for (int i = 0; i < count; i++)
		_variables.insert(row, ColumnInfo(QString(), 0));
	endInsertRows();
	return true;
}

Qt::ItemFlags ListModelVariables::flags(const QModelIndex &index) const
{
	if (index.isValid())
	{
		if (isForbidden(_variables.at(index.row()).second))
            return 0;

        return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled;
	}
	else
		return Qt::ItemIsEnabled | Qt::ItemIsDropEnabled;
}

Qt::DropActions ListModelVariables::supportedDropActions() const
{
	return _dropActions;
}

Qt::DropActions ListModelVariables::supportedDragActions() const
{
	return _dragActions;
}

QStringList ListModelVariables::mimeTypes() const
{
	QStringList types;

	types << _mimeType;

	return types;
}

QMimeData *ListModelVariables::mimeData(const QModelIndexList &indexes) const
{
	QMimeData *mimeData = new QMimeData();
	QByteArray encodedData;

	QDataStream dataStream(&encodedData, QIODevice::WriteOnly);

	dataStream << indexes.length();

	foreach (const QModelIndex &index, indexes)
	{
		if (index.isValid())
		{
			ColumnInfo info = _variables.at(index.row());
			dataStream << info;
		}
	}

	ListModelVariables* th1s = (ListModelVariables*) this;
	th1s->_mimeData = mimeData;

	mimeData->setData(_mimeType, encodedData);

	return mimeData;
}

void ListModelVariables::mimeDataMoved(const QModelIndexList &indexes)
{
	beginResetModel();

	QModelIndexList sorted = indexes;

	qSort(sorted.begin(), sorted.end(), qGreater<QModelIndex>());

	foreach (const QModelIndex &index, sorted)
		_variables.removeAt(index.row());

	endResetModel();
}

bool ListModelVariables::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
{
	if (_dragActions == Qt::CopyAction && _dropActions == Qt::MoveAction && action == Qt::MoveAction) // if delete
		return true;

	if ( ! canDropMimeData(data, action, row, column, parent))
		return false;

	if (action == Qt::IgnoreAction)
		return true;

	if (data->hasFormat(_mimeType))
	{
		QByteArray encodedData = data->data(_mimeType);
		QDataStream stream(&encodedData, QIODevice::ReadOnly);
		QList<ColumnInfo> newItems;
		int rows = 0;

		if (stream.atEnd())
			return false;

		int count;
		stream >> count;

		while (!stream.atEnd())
		{
			ColumnInfo variable;
			stream >> variable;

			if (_variables.contains(variable))
				continue;

			newItems << variable;
			++rows;
		}

		if (rows == 0)
			return false;

		int beginRow;

		if (row != -1)
			beginRow = row;
		else if (parent.isValid())
			beginRow = parent.row();
		else
			beginRow = rowCount(QModelIndex());

		int r = 0;
		foreach (const ColumnInfo &item, _variables)
		{
			if (isForbidden(item.second))
				break;
			r++;
		}

		if (r < beginRow)
			beginRow = r;

		insertRows(beginRow, rows, QModelIndex());

		r = 0;
		foreach (const ColumnInfo &item, newItems)
			_variables[beginRow + r++] = item;

		emit dataChanged(index(beginRow, 0), index(beginRow + r, 0));

		return true;
	}

	return false;
}

bool ListModelVariables::canDropMimeData(const QMimeData *data, Qt::DropAction action, int, int, const QModelIndex &) const
{
	if (_dragActions == Qt::CopyAction && _dropActions == Qt::MoveAction && action == Qt::MoveAction) // if delete
		return true;

	if (data->hasFormat(_mimeType))
	{
		QByteArray encodedData = data->data(_mimeType);
		QDataStream stream(&encodedData, QIODevice::ReadOnly);

		if (stream.atEnd()) // is empty
			return false;

		int count;
		stream >> count;

		while (!stream.atEnd())
		{
			ColumnInfo variable;
			stream >> variable;

			if (isForbidden(variable.second))
				return false;
		}

		return true;
	}
	else
	{
		return false;
	}
}

void ListModelVariables::setSupportedDropActions(Qt::DropActions actions)
{
	_dropActions = actions;
}

void ListModelVariables::setSupportedDragActions(Qt::DropActions actions)
{
	_dragActions = actions;
}

void ListModelVariables::setMimeType(const QString &mimeType)
{
	_mimeType = mimeType;
}

bool ListModelVariables::isForbidden(int variableType) const
{
	return variableType & ~_variableTypesAllowed;
}

bool ListModelVariables::isDroppingToSelf(const QMimeData *mimeData) const
{
	return _mimeData == mimeData;
}
<|endoftext|>