<commit_before>//
//  PhysicsSystem.cpp
//  REngine3
//
//  Created by reworks on 8/11/2016.
//  Copyright (c) 2016 reworks. All rights reserved.
//

#include <SFML/System/Time.hpp>

#include "re/app/World.hpp"
#include "re/mapping/TMXMap.hpp"
#include "re/physics/Box2DSFMLBridge.hpp"
#include "re/component/PhysicsComponent.hpp"
#include "re/component/TransformComponent.hpp"
#include "re/component/AnimationComponent.hpp"

#include "PhysicsSystem.hpp"

namespace re
{
	PhysicsSystem::PhysicsSystem(Box2DManager* manager, double ups, double vi, double pi)
	{
		m_manager = manager;
		m_ups = ups;
		m_velocityIterations = vi;
		m_positionIterations = pi;
	}

	PhysicsSystem::~PhysicsSystem()
	{
		m_entitys.clear();

		for (auto& v : m_mapCollisions)
		{
			m_manager->m_world.DestroyBody(v);
		}

		m_mapCollisions.clear();
		m_manager = nullptr;
	}

	void PhysicsSystem::AutoSubmit(World* world)
	{
		for (auto& it : world->GetAlive())
		{
			if (it.second.Has<PhysicsComponent>() && it.second.Has<TransformComponent>())
			{
				AddEntity(&it.second);
			}
		}
	}

	void PhysicsSystem::SubmitTiles(TMXMap* map)
	{
		for (auto& v : map->GetCollisions())
		{
			b2BodyDef bodyDef;
			bodyDef.position.Set((double)v.left, (double)v.top);

			bodyDef.type = b2BodyType::b2_staticBody;

			b2PolygonShape b2shape;
			b2shape.SetAsBox((double)v.width / 2.0, (double)v.height / 2.0);

			b2FixtureDef fixtureDef;
			fixtureDef.density = 0;
			fixtureDef.friction = 0;
			fixtureDef.restitution = 0;
			fixtureDef.shape = &b2shape;

			b2Body* body = m_manager->m_world.CreateBody(&bodyDef);
			body->CreateFixture(&fixtureDef);
			m_mapCollisions.push_back(body);
		}
	}

	void PhysicsSystem::AddEntity(Entity* e)
	{
		e->m_systemIds.emplace("PhysicsSystem", std::type_index(typeid(PhysicsSystem)));
		// we need to set the body's user data to the entity.
		e->Get<PhysicsComponent>()->m_body->SetUserData(static_cast<void*>(e));
		m_entitys.emplace(e->m_name, e);
	}

	void PhysicsSystem::RemoveEntity(const std::string& name)
	{
		m_entitys.erase(name);
	}

	void PhysicsSystem::Update(sf::Time dt)
	{
		m_manager->m_world.Step(1.0 / m_ups, m_velocityIterations, m_positionIterations);

		for (auto& e : m_entitys)
		{
			auto phys = e.second->Get<PhysicsComponent>();
			auto transf = e.second->Get<TransformComponent>();

			transf->setPosition(b2::MetersToPixels<double>(phys->m_body->GetPosition().x), b2::MetersToPixels<double>(phys->m_body->GetPosition().y));
			transf->setRotation(b2::RadToDeg<double>(phys->m_body->GetAngle()));

			if (e.second->Has<AnimationComponent>() && (!phys->m_isMovingHoritontally))
			{
				e.second->Get<AnimationComponent>()->Pause();
			}

			if (!phys->m_body->GetLinearVelocity().x < 0.3)
			{
				phys->m_isMovingHoritontally = false;
			}
		}
	}

	void PhysicsSystem::Clean()
	{
		m_entitys.clear();

		for (auto& v : m_mapCollisions)
		{
			m_manager->m_world.DestroyBody(v);
		}

		m_mapCollisions.clear();

		// We do not reset the manager pointer because we want to reuse it.
	}
}<commit_msg>fixed math<commit_after>//
//  PhysicsSystem.cpp
//  REngine3
//
//  Created by reworks on 8/11/2016.
//  Copyright (c) 2016 reworks. All rights reserved.
//

#include <SFML/System/Time.hpp>

#include "re/app/World.hpp"
#include "re/mapping/TMXMap.hpp"
#include "re/physics/Box2DSFMLBridge.hpp"
#include "re/component/PhysicsComponent.hpp"
#include "re/component/TransformComponent.hpp"
#include "re/component/AnimationComponent.hpp"

#include "PhysicsSystem.hpp"

namespace re
{
	PhysicsSystem::PhysicsSystem(Box2DManager* manager, double ups, double vi, double pi)
	{
		m_manager = manager;
		m_ups = ups;
		m_velocityIterations = vi;
		m_positionIterations = pi;
	}

	PhysicsSystem::~PhysicsSystem()
	{
		m_entitys.clear();

		for (auto& v : m_mapCollisions)
		{
			m_manager->m_world.DestroyBody(v);
		}

		m_mapCollisions.clear();
		m_manager = nullptr;
	}

	void PhysicsSystem::AutoSubmit(World* world)
	{
		for (auto& it : world->GetAlive())
		{
			if (it.second.Has<PhysicsComponent>() && it.second.Has<TransformComponent>())
			{
				AddEntity(&it.second);
			}
		}
	}

	void PhysicsSystem::SubmitTiles(TMXMap* map)
	{
		for (auto& v : map->GetCollisions())
		{
			b2BodyDef bodyDef;
			bodyDef.position.Set((double)v.left, (double)v.top);

			bodyDef.type = b2BodyType::b2_staticBody;

			b2PolygonShape b2shape;
			b2shape.SetAsBox((double)v.width / 2.0, (double)v.height / 2.0);

			b2FixtureDef fixtureDef;
			fixtureDef.density = 0;
			fixtureDef.friction = 0;
			fixtureDef.restitution = 0;
			fixtureDef.shape = &b2shape;

			b2Body* body = m_manager->m_world.CreateBody(&bodyDef);
			body->CreateFixture(&fixtureDef);
			m_mapCollisions.push_back(body);
		}
	}

	void PhysicsSystem::AddEntity(Entity* e)
	{
		e->m_systemIds.emplace("PhysicsSystem", std::type_index(typeid(PhysicsSystem)));
		// we need to set the body's user data to the entity.
		e->Get<PhysicsComponent>()->m_body->SetUserData(static_cast<void*>(e));
		m_entitys.emplace(e->m_name, e);
	}

	void PhysicsSystem::RemoveEntity(const std::string& name)
	{
		m_entitys.erase(name);
	}

	void PhysicsSystem::Update(sf::Time dt)
	{
		m_manager->m_world.Step(1.0 / m_ups, m_velocityIterations, m_positionIterations);

		for (auto& e : m_entitys)
		{
			auto phys = e.second->Get<PhysicsComponent>();
			auto transf = e.second->Get<TransformComponent>();

			transf->setPosition(b2::MetersToPixels<double>(phys->m_body->GetPosition().x), b2::MetersToPixels<double>(phys->m_body->GetPosition().y));
			transf->setRotation(b2::RadToDeg<double>(phys->m_body->GetAngle()));

			if (e.second->Has<AnimationComponent>() && (!phys->m_isMovingHoritontally))
			{
				e.second->Get<AnimationComponent>()->Pause();
			}

			if (phys->m_body->GetLinearVelocity().x < 0.2f)
			{
				phys->m_isMovingHoritontally = false;
			}
		}
	}

	void PhysicsSystem::Clean()
	{
		m_entitys.clear();

		for (auto& v : m_mapCollisions)
		{
			m_manager->m_world.DestroyBody(v);
		}

		m_mapCollisions.clear();

		// We do not reset the manager pointer because we want to reuse it.
	}
}<|endoftext|>


<commit_before>/*
 * String hash map.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "strmap.hxx"
#include "pool.hxx"

#include <string.h>

inline bool
StringMap::Item::Compare::Less(const char *a, const char *b) const
{
    return strcmp(a, b) < 0;
}

StringMap::Item *
StringMap::Item::Cloner::operator()(const Item &src) const
{
    return NewFromPool<Item>(pool,
                             p_strdup(&pool, src.key),
                             p_strdup(&pool, src.value));
}

StringMap::StringMap(struct pool &_pool, const StringMap &src)
    :pool(_pool) {
    map.clone_from(src.map, Item::Cloner(pool), [](Item *){});
}

void
StringMap::Add(const char *key, const char *value)
{
    Item *item = NewFromPool<Item>(pool, key, value);
    map.insert(*item);
}

const char *
StringMap::Set(const char *key, const char *value)
{
    auto i = map.upper_bound(key, Item::Compare());
    if (i != map.end() && strcmp(i->key, key) == 0) {
        const char *old_value = i->value;
        i->value = value;
        return old_value;
    } else {
        map.insert_before(i, *NewFromPool<Item>(pool, key, value));
        return nullptr;
    }
}

const char *
StringMap::Remove(const char *key)
{
    auto i = map.find(key, Item::Compare());
    if (i == map.end())
        return nullptr;

    const char *value = i->value;
    map.erase_and_dispose(i, PoolDisposer(pool));
    return value;
}

void
StringMap::RemoveAll(const char *key)
{
    map.erase_and_dispose(key, Item::Compare(), PoolDisposer(pool));
}

void
StringMap::SecureSet(const char *key, const char *value)
{
    auto r = map.equal_range(key, Item::Compare());
    if (r.first != r.second) {
        if (value != nullptr) {
            /* replace the first value */
            r.first->value = value;
            ++r.first;
        }

        /* and erase all other values with the same key */
        map.erase_and_dispose(r.first, r.second, PoolDisposer(pool));
    } else if (value != nullptr)
        map.insert(r.second, *NewFromPool<Item>(pool, key, value));
}

const char *
StringMap::Get(const char *key) const
{
    auto i = map.find(key, Item::Compare());
    if (i == map.end())
        return nullptr;

    return i->value;
}

std::pair<StringMap::const_iterator, StringMap::const_iterator>
StringMap::EqualRange(const char *key) const
{
    return map.equal_range(key, Item::Compare());
}

StringMap *
strmap_new(struct pool *pool)
{
    return NewFromPool<StringMap>(*pool, *pool);
}

StringMap *gcc_malloc
strmap_dup(struct pool *pool, const StringMap *src)
{
    return NewFromPool<StringMap>(*pool, *pool, *src);
}
<commit_msg>strmap: optimize SecureSet() using insert_before()<commit_after>/*
 * String hash map.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "strmap.hxx"
#include "pool.hxx"

#include <string.h>

inline bool
StringMap::Item::Compare::Less(const char *a, const char *b) const
{
    return strcmp(a, b) < 0;
}

StringMap::Item *
StringMap::Item::Cloner::operator()(const Item &src) const
{
    return NewFromPool<Item>(pool,
                             p_strdup(&pool, src.key),
                             p_strdup(&pool, src.value));
}

StringMap::StringMap(struct pool &_pool, const StringMap &src)
    :pool(_pool) {
    map.clone_from(src.map, Item::Cloner(pool), [](Item *){});
}

void
StringMap::Add(const char *key, const char *value)
{
    Item *item = NewFromPool<Item>(pool, key, value);
    map.insert(*item);
}

const char *
StringMap::Set(const char *key, const char *value)
{
    auto i = map.upper_bound(key, Item::Compare());
    if (i != map.end() && strcmp(i->key, key) == 0) {
        const char *old_value = i->value;
        i->value = value;
        return old_value;
    } else {
        map.insert_before(i, *NewFromPool<Item>(pool, key, value));
        return nullptr;
    }
}

const char *
StringMap::Remove(const char *key)
{
    auto i = map.find(key, Item::Compare());
    if (i == map.end())
        return nullptr;

    const char *value = i->value;
    map.erase_and_dispose(i, PoolDisposer(pool));
    return value;
}

void
StringMap::RemoveAll(const char *key)
{
    map.erase_and_dispose(key, Item::Compare(), PoolDisposer(pool));
}

void
StringMap::SecureSet(const char *key, const char *value)
{
    auto r = map.equal_range(key, Item::Compare());
    if (r.first != r.second) {
        if (value != nullptr) {
            /* replace the first value */
            r.first->value = value;
            ++r.first;
        }

        /* and erase all other values with the same key */
        map.erase_and_dispose(r.first, r.second, PoolDisposer(pool));
    } else if (value != nullptr)
        map.insert_before(r.second, *NewFromPool<Item>(pool, key, value));
}

const char *
StringMap::Get(const char *key) const
{
    auto i = map.find(key, Item::Compare());
    if (i == map.end())
        return nullptr;

    return i->value;
}

std::pair<StringMap::const_iterator, StringMap::const_iterator>
StringMap::EqualRange(const char *key) const
{
    return map.equal_range(key, Item::Compare());
}

StringMap *
strmap_new(struct pool *pool)
{
    return NewFromPool<StringMap>(*pool, *pool);
}

StringMap *gcc_malloc
strmap_dup(struct pool *pool, const StringMap *src)
{
    return NewFromPool<StringMap>(*pool, *pool, *src);
}
<|endoftext|>


<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)
//-- --- standard headers-------------
#include <Riostream.h>
//--------Root headers ---------------
#include <TSystem.h>
#include <TFile.h>
#include <TStopwatch.h>
#include <TObject.h>
#include <TTree.h>
#include <TChain.h>
#include <TF1.h>
#include <TLegend.h>
#include <TLegendEntry.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TCut.h>
#include <TParticle.h>
#include <TCanvas.h>
#include <TStyle.h>
#include <TGraph.h>
//----- AliRoot headers ---------------
//#include "alles.h"
#include "AliRun.h"
#include "AliMagF.h"
#include "AliKalmanTrack.h"
#include "AliESDVertex.h"
#include "AliITSVertexer.h"
#include "AliITSVertexerTracks.h"
#include <AliHeader.h>
#include <AliGenEventHeader.h>
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliITStrackV2.h"
#include "AliITSSimpleVertex.h"
#include "AliITSStrLine.h"
#include "AliITSLoader.h"
#include <AliESD.h>
#include <AliStack.h>
//-------------------------------------
#endif

void AliITSSecondaryVertices(Int_t ntracks, Int_t *pos) {

  // example of usige AliITSVertexerTracks to get a (secodnary) vertex from a set of tracks.

  Double_t field = 0.4;

  AliRunLoader *rl = AliRunLoader::Open("galice.root");
  if (!rl) {
    cerr<<"Can't start session !\n";
  }

  rl->LoadgAlice();
  if (rl->GetAliRun()){
    AliMagF * magf = gAlice->Field();
    AliKalmanTrack:: SetFieldMap(magf);
    AliKalmanTrack::SetUniformFieldTracking();
  }else {
    cerr<<"Can't get AliRun !\n";

  }

  field=rl->GetAliRun()->Field()->SolenoidField()/10.;
  rl->LoadHeader();

  TFile *ef=TFile::Open("AliESDs.root");
  if (!ef || !ef->IsOpen()) {cerr<<"Can't AliESDs.root !n";}
  AliESD* event = new AliESD;
  TTree* tree = (TTree*) ef->Get("esdTree");
  if (!tree) {cerr<<"no ESD tree foundn";};
  tree->SetBranchAddress("ESD", &event);

  Int_t e=0;
  tree->GetEvent(e);
  Int_t ntrk=event->GetNumberOfTracks();
  cout<<"Number of ESD tracks : "<<ntrk<<endl;

  // Open input and output files
  TFile *outFile = TFile::Open("AliITSVertices.root","recreate");

  TTree *trkTree = new TTree("TreeT_ITS","its tracks");
  AliITStrackV2 *itstrack = 0;
  trkTree->Branch("tracks","AliITStrackV2",&itstrack,ntrk,0);
  Int_t pipe=0;
  for(Int_t i=0; i<ntrk; i++) {
    AliESDtrack *esdTrack = (AliESDtrack*)event->GetTrack(i);
    UInt_t status=esdTrack->GetStatus();
    UInt_t flags=AliESDtrack::kTPCin|AliESDtrack::kITSin;
    if ((status&AliESDtrack::kTPCin)==0)continue;
    if ((status&AliESDtrack::kITSin)==0)continue;
    if ((status&AliESDtrack::kITSrefit)==0) continue;
    if ((status&flags)==status) pipe=1;

    itstrack = new AliITStrackV2(*esdTrack);
    if (pipe!=0) {
      itstrack->PropagateTo(3.,0.0028,65.19);
      itstrack->PropagateToVertex();  // This is not "exactly" the vertex
    }
    Int_t nclus=itstrack->GetNumberOfClusters();

    if(nclus<6)continue;
    trkTree->Fill();
    itstrack = 0;
    // delete esdTrack;
  }
  // Primary vertex
  Double_t vtx[3];
  event->GetVertex()->GetXYZ(vtx);
  cout<<"Primary Vertex:"<<endl;
  event->GetVertex()->PrintStatus();
  cout<<"\n\n\n"<<endl;

  // Create vertexer
  AliITSVertexerTracks *vertexer = new AliITSVertexerTracks();
  vertexer->SetDCAcut(0);
  vertexer->SetDebug(0);

  Double_t vertF1[3],vertF2[3],vertF3[3],vertF4[3],vertF5[3];
  Int_t ncombi1,ncombi2,ncombi3,ncombi4,ncombi5;
  Double_t sig1,sig2,sig3,sig4,sig5;
  AliITSSimpleVertex *vert=0;

  // Calculate vertex from tracks in pos
  // BEWARE: the method VertexForSelectedTracks returns the address of the data member fSimpVert
  // which is always the same for all calls to VertexForSelectedTracks.

  cout<<"\nStraight Line Min Dist finder with weights"<<endl;
  vert=(AliITSSimpleVertex*) vertexer->VertexForSelectedTracks(event,ntracks,pos,1);
  vert->Print();
  vert->GetXYZ(vertF1);
  ncombi1=vert->GetNContributors();
  sig1=vert->GetDispersion();

  cout<<"Straight Line Min Dist finder"<<endl;
  vert=(AliITSSimpleVertex*) vertexer->VertexForSelectedTracks(event,ntracks,pos,2);
  vert->Print();
  vert->GetXYZ(vertF2);
  ncombi2=vert->GetNContributors();
  sig2=vert->GetDispersion();

  cout<<"Helix finder"<<endl;
  vert=(AliITSSimpleVertex*) vertexer->VertexForSelectedTracks(event,ntracks,pos,3);
  vert->Print();
  vert->GetXYZ(vertF3);
  ncombi3=vert->GetNContributors();
  sig3=vert->GetDispersion();

  cout<<"Straight Line finder with weights"<<endl;
  vert=(AliITSSimpleVertex*) vertexer->VertexForSelectedTracks(event,ntracks,pos,4);
  vert->Print();
  vert->GetXYZ(vertF4);
  ncombi4=vert->GetNContributors();
  sig4=vert->GetDispersion();

  cout<<"Straight Line finder with weights"<<endl;
  vert=(AliITSSimpleVertex*) vertexer->VertexForSelectedTracks(event,ntracks,pos,5);
  vert->Print();
  vert->GetXYZ(vertF5);
  ncombi5=vert->GetNContributors();
  sig5=vert->GetDispersion();

  delete vertexer;

  outFile->Close();
  return;
}
<commit_msg>Obsolete macro<commit_after><|endoftext|>


<commit_before>/*
 * receiveFromPostProbe.cpp
 * Author: slundquist
 */

#include "ReceiveFromPostProbe.hpp"
#include <include/pv_arch.h>
#include <layers/HyPerLayer.hpp>
#include <assert.h>
#include <string.h>

namespace PV {
ReceiveFromPostProbe::ReceiveFromPostProbe(const char * filename, HyPerLayer * layer, const char * msg)
   : StatsProbe()
{
   initStatsProbe(filename, layer, BufActivity, msg);
}

ReceiveFromPostProbe::ReceiveFromPostProbe(HyPerLayer * layer, const char * msg)
   : StatsProbe()
{
   initStatsProbe(NULL, layer, BufActivity, msg);
}

int ReceiveFromPostProbe::outputState(double timed){
   int status = StatsProbe::outputState(timed);
   const pvdata_t * actLayer = getTargetLayer()->getLayerData();
   const PVLayerLoc * loc = getTargetLayer()->getLayerLoc();
   int numExtNeurons = getTargetLayer()->getNumExtended();
   const pvdata_t * A = getTargetLayer()->getLayerData();
   for (int i = 0; i < numExtNeurons; i++){
      //std::cout<<A[i]<<"\n";
      //For roundoff errors
      assert(abs(A[i]) < 1e-5);
   }
   return status;
}

}
<commit_msg>Eliminating unused-variable warning<commit_after>/*
 * receiveFromPostProbe.cpp
 * Author: slundquist
 */

#include "ReceiveFromPostProbe.hpp"
#include <include/pv_arch.h>
#include <layers/HyPerLayer.hpp>
#include <assert.h>
#include <string.h>

namespace PV {
ReceiveFromPostProbe::ReceiveFromPostProbe(const char * filename, HyPerLayer * layer, const char * msg)
   : StatsProbe()
{
   initStatsProbe(filename, layer, BufActivity, msg);
}

ReceiveFromPostProbe::ReceiveFromPostProbe(HyPerLayer * layer, const char * msg)
   : StatsProbe()
{
   initStatsProbe(NULL, layer, BufActivity, msg);
}

int ReceiveFromPostProbe::outputState(double timed){
   int status = StatsProbe::outputState(timed);
   // const PVLayerLoc * loc = getTargetLayer()->getLayerLoc();
   int numExtNeurons = getTargetLayer()->getNumExtended();
   const pvdata_t * A = getTargetLayer()->getLayerData();
   for (int i = 0; i < numExtNeurons; i++){
      //std::cout<<A[i]<<"\n";
      //For roundoff errors
      assert(abs(A[i]) < 1e-5);
   }
   return status;
}

}
<|endoftext|>


<commit_before>void MakeITSRecoParam_pp2009(AliRecoParam::EventSpecie_t default=AliRecoParam::kLowMult) {
//========================================================================
//
// Steering macro for ITS reconstruction parameters
//
// Author: A.Dainese
// Contact: andrea.dainese@lnl.infn.it
//
//========================================================================

  const char* macroname = "MakeITSRecoParam_pp2009.C";

  // Activate CDB storage and load geometry from CDB
  AliCDBManager* cdb = AliCDBManager::Instance();
  if(!cdb->IsDefaultStorageSet()) cdb->SetDefaultStorage("raw://");

  TObjArray *recoParamArray = new TObjArray();

  {
    AliITSRecoParam * itsRecoParam = AliITSRecoParam::GetCosmicTestParam();
    itsRecoParam->SetFactorSAWindowSizes(20);
    itsRecoParam->SetClusterErrorsParam(2);
    itsRecoParam->SetFindV0s(kFALSE);
    itsRecoParam->SetAddVirtualClustersInDeadZone(kFALSE);
    itsRecoParam->SetUseAmplitudeInfo(kFALSE);
    // In case we want to switch off a layer
    //  itsRecoParam->SetLayerToSkip(<N>);
    //  itsRecoParam->SetLayerToSkip(4);
    //  itsRecoParam->SetLayerToSkip(5);
    //    itsRecoParam->SetLayerToSkip(2);
    //    itsRecoParam->SetLayerToSkip(3);
    //itsRecoParam->SetSAOnePointTracks();
    itsRecoParam->SetClusterMisalError(0.1); // [cm]
    itsRecoParam->SetSAUseAllClusters();
    itsRecoParam->SetEventSpecie(AliRecoParam::kCosmic);
    recoParamArray->AddLast(itsRecoParam);
  }
  {
    AliITSRecoParam * itsRecoParam = AliITSRecoParam::GetLowFluxParam();
    itsRecoParam->SetClusterErrorsParam(2);
    //****** FIRST PHYSICS 2009 (same as COSMICS 2009) *********************

    // find independently ITS SA tracks
    param->SetSAUseAllClusters();
    param->SetOuterStartLayerSA(AliITSgeomTGeo::GetNLayers()-2);

    // to maximize efficiency
    param->SetAllowProlongationWithEmptyRoad();

    // larger seach windows for SA (in case of large misalignments)
    param->SetNLoopsSA(33);
    param->SetFactorSAWindowSizes(20);

    // additional error due to misal (B off)
    param->SetClusterMisalErrorY(1.0,1.0,1.0,1.0,1.0,1.0); // [cm]
    param->SetClusterMisalErrorZ(1.0,1.0,1.0,1.0,1.0,1.0); // [cm]
    // additional error due to misal (B on)
    param->SetClusterMisalErrorYBOn(0.0,0.0,0.1,0.1,0.1,0.1); // [cm]
    param->SetClusterMisalErrorZBOn(0.1,0.1,0.1,0.1,0.1,0.1); // [cm]

    // SDD configuration
    param->fUseSDDCorrectionMaps = kFALSE;
    param->fUseSDDClusterSizeSelection=kTRUE;
    param->fMinClusterChargeSDD=30.;

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

    itsRecoParam->SetEventSpecie(AliRecoParam::kLowMult);
    recoParamArray->AddLast(itsRecoParam);
  }
  {
    AliITSRecoParam * itsRecoParam = AliITSRecoParam::GetHighFluxParam();
    itsRecoParam->SetClusterErrorsParam(2);
    itsRecoParam->SetEventSpecie(AliRecoParam::kHighMult);
    recoParamArray->AddLast(itsRecoParam);
  }

  // Set the default
  Bool_t defaultIsSet = kFALSE;
  for(Int_t i =0; i < recoParamArray->GetEntriesFast(); i++) {
    AliDetectorRecoParam *param = (AliDetectorRecoParam *)recoParamArray->UncheckedAt(i);
    if (!param) continue;
    if (default & param->GetEventSpecie()) {
      param->SetAsDefault();
      defaultIsSet = kTRUE;
    }
  }

  if (!defaultIsSet) {
    Error(macroname,"The default reconstruction parameters are not set! Exiting...");
    return;
  }

  // save in CDB storage
  AliCDBMetaData *md= new AliCDBMetaData();
  md->SetResponsible("Andrea Dainese");
  md->SetComment("Reconstruction parameters ITS. Use large misal errors for cosmics and lowflux, 18 Nov 2009");
  md->SetAliRootVersion(gSystem->Getenv("ARVERSION"));
  md->SetBeamPeriod(0);
  AliCDBId id("ITS/Calib/RecoParam",0,AliCDBRunRange::Infinity());
  cdb->GetDefaultStorage()->Put(recoParamArray,id, md);

  return;
}

<commit_msg>Bug fix (R. Grosso)<commit_after>void MakeITSRecoParam_pp2009(AliRecoParam::EventSpecie_t default=AliRecoParam::kLowMult, const char* cdbURI) {
//========================================================================
//
// Steering macro for ITS reconstruction parameters
//
// Author: A.Dainese
// Contact: andrea.dainese@lnl.infn.it
//
//========================================================================

  const char* macroname = "MakeITSRecoParam_pp2009.C";

  // Activate CDB storage and load geometry from CDB
  AliCDBManager* cdb = AliCDBManager::Instance();
  cdb->SetDefaultStorage(cdbURI);

  TObjArray *recoParamArray = new TObjArray();

  {
    AliITSRecoParam * itsRecoParam = AliITSRecoParam::GetCosmicTestParam();
    itsRecoParam->SetFactorSAWindowSizes(20);
    itsRecoParam->SetClusterErrorsParam(2);
    itsRecoParam->SetFindV0s(kFALSE);
    itsRecoParam->SetAddVirtualClustersInDeadZone(kFALSE);
    itsRecoParam->SetUseAmplitudeInfo(kFALSE);
    // In case we want to switch off a layer
    //  itsRecoParam->SetLayerToSkip(<N>);
    //  itsRecoParam->SetLayerToSkip(4);
    //  itsRecoParam->SetLayerToSkip(5);
    //    itsRecoParam->SetLayerToSkip(2);
    //    itsRecoParam->SetLayerToSkip(3);
    //itsRecoParam->SetSAOnePointTracks();
    itsRecoParam->SetClusterMisalError(0.1); // [cm]
    itsRecoParam->SetSAUseAllClusters();
    itsRecoParam->SetEventSpecie(AliRecoParam::kCosmic);
    recoParamArray->AddLast(itsRecoParam);
  }
  {
    AliITSRecoParam * itsRecoParam = AliITSRecoParam::GetLowFluxParam();
    itsRecoParam->SetClusterErrorsParam(2);
    //****** FIRST PHYSICS 2009 (same as COSMICS 2009) *********************

    // find independently ITS SA tracks
    itsRecoParam->SetSAUseAllClusters();
    itsRecoParam->SetOuterStartLayerSA(AliITSgeomTGeo::GetNLayers()-2);

    // to maximize efficiency
    itsRecoParam->SetAllowProlongationWithEmptyRoad();

    // larger seach windows for SA (in case of large misalignments)
    itsRecoParam->SetNLoopsSA(33);
    itsRecoParam->SetFactorSAWindowSizes(20);

    // additional error due to misal (B off)
    itsRecoParam->SetClusterMisalErrorY(1.0,1.0,1.0,1.0,1.0,1.0); // [cm]
    itsRecoParam->SetClusterMisalErrorZ(1.0,1.0,1.0,1.0,1.0,1.0); // [cm]
    // additional error due to misal (B on)
    itsRecoParam->SetClusterMisalErrorYBOn(0.0,0.0,0.1,0.1,0.1,0.1); // [cm]
    itsRecoParam->SetClusterMisalErrorZBOn(0.1,0.1,0.1,0.1,0.1,0.1); // [cm]

    // SDD configuration
    itsRecoParam->SetUseSDDCorrectionMaps(kFALSE);
    itsRecoParam->SetUseSDDClusterSizeSelection(kTRUE);
    itsRecoParam->SetMinClusterChargeSDD(30.);

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

    itsRecoParam->SetEventSpecie(AliRecoParam::kLowMult);
    recoParamArray->AddLast(itsRecoParam);
  }
  {
    AliITSRecoParam * itsRecoParam = AliITSRecoParam::GetHighFluxParam();
    itsRecoParam->SetClusterErrorsParam(2);
    itsRecoParam->SetEventSpecie(AliRecoParam::kHighMult);
    recoParamArray->AddLast(itsRecoParam);
  }

  // Set the default
  Bool_t defaultIsSet = kFALSE;
  for(Int_t i =0; i < recoParamArray->GetEntriesFast(); i++) {
    AliDetectorRecoParam *param = (AliDetectorRecoParam *)recoParamArray->UncheckedAt(i);
    if (!param) continue;
    if (default & param->GetEventSpecie()) {
      param->SetAsDefault();
      defaultIsSet = kTRUE;
    }
  }

  if (!defaultIsSet) {
    Error(macroname,"The default reconstruction parameters are not set! Exiting...");
    return;
  }

  // save in CDB storage
  AliCDBMetaData *md= new AliCDBMetaData();
  md->SetResponsible("Andrea Dainese");
  md->SetComment("Reconstruction parameters ITS. Use large misal errors for cosmics and lowflux, 18 Nov 2009");
  md->SetAliRootVersion(gSystem->Getenv("ARVERSION"));
  md->SetBeamPeriod(0);
  AliCDBId id("ITS/Calib/RecoParam",0,AliCDBRunRange::Infinity());
  cdb->GetDefaultStorage()->Put(recoParamArray,id, md);

  return;
}

<|endoftext|>


<commit_before>//===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation  --*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the Owen Anderson and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements an analysis that determines, for a given memory
// operation, what preceding memory operations it depends on.  It builds on
// alias analysis information, and tries to provide a lazy, caching interface to
// a common kind of alias information query.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/MemoryDependenceAnalysis.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/Function.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Target/TargetData.h"

using namespace llvm;

char MemoryDependenceAnalysis::ID = 0;

Instruction* MemoryDependenceAnalysis::NonLocal = (Instruction*)0;
Instruction* MemoryDependenceAnalysis::None = (Instruction*)~0;

// Register this pass...
static RegisterPass<MemoryDependenceAnalysis> X("memdep",
                                                "Memory Dependence Analysis");

/// getAnalysisUsage - Does not modify anything.  It uses Alias Analysis.
///
void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
  AU.setPreservesAll();
  AU.addRequiredTransitive<AliasAnalysis>();
  AU.addRequiredTransitive<TargetData>();
}

// Find the dependency of a CallSite
Instruction* MemoryDependenceAnalysis::getCallSiteDependency(CallSite C, Instruction* start,
                                                             bool local) {
  assert(local && "Non-local memory dependence analysis not yet implemented");

  AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
  TargetData& TD = getAnalysis<TargetData>();
  BasicBlock::iterator blockBegin = C.getInstruction()->getParent()->begin();
  BasicBlock::iterator QI = C.getInstruction();

  while (QI != blockBegin) {
    --QI;

    // If this inst is a memory op, get the pointer it accessed
    Value* pointer = 0;
    uint64_t pointerSize = 0;
    if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
      pointer = S->getPointerOperand();
      pointerSize = TD.getTypeSize(S->getOperand(0)->getType());
    } else if (LoadInst* L = dyn_cast<LoadInst>(QI)) {
      pointer = L->getPointerOperand();
      pointerSize = TD.getTypeSize(L->getType());
    } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
      pointer = AI;
      if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
        pointerSize = C->getZExtValue() * TD.getTypeSize(AI->getAllocatedType());
      else
        pointerSize = ~0UL;
    } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
      pointer = V->getOperand(0);
      pointerSize = TD.getTypeSize(V->getType());
    } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
      pointer = F->getPointerOperand();

      // FreeInsts erase the entire structure
      pointerSize = ~0UL;
    } else if (CallSite::get(QI).getInstruction() != 0) {
      if (AA.getModRefInfo(C, CallSite::get(QI)) != AliasAnalysis::NoModRef) {
        depGraphLocal.insert(std::make_pair(C.getInstruction(), std::make_pair(QI, true)));
        reverseDep.insert(std::make_pair(QI, C.getInstruction()));
        return QI;
      } else {
        continue;
      }
    } else
      continue;

    if (AA.getModRefInfo(C, pointer, pointerSize) != AliasAnalysis::NoModRef) {
      depGraphLocal.insert(std::make_pair(C.getInstruction(), std::make_pair(QI, true)));
      reverseDep.insert(std::make_pair(QI, C.getInstruction()));
      return QI;
    }
  }

  // No dependence found
  depGraphLocal.insert(std::make_pair(C.getInstruction(), std::make_pair(NonLocal, true)));
  reverseDep.insert(std::make_pair(NonLocal, C.getInstruction()));
  return NonLocal;
}

/// getDependency - Return the instruction on which a memory operation
/// depends.  The local paramter indicates if the query should only
/// evaluate dependencies within the same basic block.
Instruction* MemoryDependenceAnalysis::getDependency(Instruction* query,
                                                     Instruction* start,
                                                     bool local) {
  if (!local)
    assert(0 && "Non-local memory dependence is not yet supported.");

  // Start looking for dependencies with the queried inst
  BasicBlock::iterator QI = query;

  // Check for a cached result
  std::pair<Instruction*, bool> cachedResult = depGraphLocal[query];
  // If we have a _confirmed_ cached entry, return it
  if (cachedResult.second)
    return cachedResult.first;
  else if (cachedResult.first != NonLocal)
  // If we have an unconfirmed cached entry, we can start our search from there
    QI = cachedResult.first;

  if (start)
    QI = start;

  AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
  TargetData& TD = getAnalysis<TargetData>();

  // Get the pointer value for which dependence will be determined
  Value* dependee = 0;
  uint64_t dependeeSize = 0;
  bool queryIsVolatile = false;
  if (StoreInst* S = dyn_cast<StoreInst>(query)) {
    dependee = S->getPointerOperand();
    dependeeSize = TD.getTypeSize(S->getOperand(0)->getType());
    queryIsVolatile = S->isVolatile();
  } else if (LoadInst* L = dyn_cast<LoadInst>(query)) {
    dependee = L->getPointerOperand();
    dependeeSize = TD.getTypeSize(L->getType());
    queryIsVolatile = L->isVolatile();
  } else if (VAArgInst* V = dyn_cast<VAArgInst>(query)) {
    dependee = V->getOperand(0);
    dependeeSize = TD.getTypeSize(V->getType());
  } else if (FreeInst* F = dyn_cast<FreeInst>(query)) {
    dependee = F->getPointerOperand();

    // FreeInsts erase the entire structure, not just a field
    dependeeSize = ~0UL;
  } else if (CallSite::get(query).getInstruction() != 0)
    return getCallSiteDependency(CallSite::get(query), start);
  else if (isa<AllocationInst>(query))
    return None;
  else
    return None;

  BasicBlock::iterator blockBegin = query->getParent()->begin();

  while (QI != blockBegin) {
    --QI;

    // If this inst is a memory op, get the pointer it accessed
    Value* pointer = 0;
    uint64_t pointerSize = 0;
    if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
      // All volatile loads/stores depend on each other
      if (queryIsVolatile && S->isVolatile()) {
        if (!start) {
          depGraphLocal.insert(std::make_pair(query, std::make_pair(S, true)));
          reverseDep.insert(std::make_pair(S, query));
        }

        return S;
      }

      pointer = S->getPointerOperand();
      pointerSize = TD.getTypeSize(S->getOperand(0)->getType());
    } else if (LoadInst* L = dyn_cast<LoadInst>(QI)) {
      // All volatile loads/stores depend on each other
      if (queryIsVolatile && L->isVolatile()) {
        if (!start) {
          depGraphLocal.insert(std::make_pair(query, std::make_pair(L, true)));
          reverseDep.insert(std::make_pair(L, query));
        }

        return L;
      }

      pointer = L->getPointerOperand();
      pointerSize = TD.getTypeSize(L->getType());
    } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
      pointer = AI;
      if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
        pointerSize = C->getZExtValue() * TD.getTypeSize(AI->getAllocatedType());
      else
        pointerSize = ~0UL;
    } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
      pointer = V->getOperand(0);
      pointerSize = TD.getTypeSize(V->getType());
    } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
      pointer = F->getPointerOperand();

      // FreeInsts erase the entire structure
      pointerSize = ~0UL;
    } else if (CallSite::get(QI).getInstruction() != 0) {
      // Call insts need special handling.  Check is they can modify our pointer
      if (AA.getModRefInfo(CallSite::get(QI), dependee, dependeeSize) !=
          AliasAnalysis::NoModRef) {
        if (!start) {
          depGraphLocal.insert(std::make_pair(query, std::make_pair(QI, true)));
          reverseDep.insert(std::make_pair(QI, query));
        }

        return QI;
      } else {
        continue;
      }
    }

    // If we found a pointer, check if it could be the same as our pointer
    if (pointer) {
      AliasAnalysis::AliasResult R = AA.alias(pointer, pointerSize,
                                              dependee, dependeeSize);

      if (R != AliasAnalysis::NoAlias) {
        if (!start) {
          depGraphLocal.insert(std::make_pair(query, std::make_pair(QI, true)));
          reverseDep.insert(std::make_pair(QI, query));
        }

        return QI;
      }
    }
  }

  // If we found nothing, return the non-local flag
  if (!start) {
    depGraphLocal.insert(std::make_pair(query,
                                        std::make_pair(NonLocal, true)));
    reverseDep.insert(std::make_pair(NonLocal, query));
  }

  return NonLocal;
}

/// removeInstruction - Remove an instruction from the dependence analysis,
/// updating the dependence of instructions that previously depended on it.
void MemoryDependenceAnalysis::removeInstruction(Instruction* rem) {
  // Figure out the new dep for things that currently depend on rem
  Instruction* newDep = NonLocal;
  if (depGraphLocal[rem].first != NonLocal) {
    // If we have dep info for rem, set them to it
    BasicBlock::iterator RI = depGraphLocal[rem].first;
    RI++;
    newDep = RI;
  } else if (depGraphLocal[rem].first == NonLocal &&
             depGraphLocal[rem].second ) {
    // If we have a confirmed non-local flag, use it
    newDep = NonLocal;
  } else {
    // Otherwise, use the immediate successor of rem
    // NOTE: This is because, when getDependence is called, it will first check
    // the immediate predecessor of what is in the cache.
    BasicBlock::iterator RI = rem;
    RI++;
    newDep = RI;
  }

  std::multimap<Instruction*, Instruction*>::iterator I = reverseDep.find(rem);
  while (I->first == rem) {
    // Insert the new dependencies
    // Mark it as unconfirmed as long as it is not the non-local flag
    depGraphLocal[I->second] = std::make_pair(newDep, !newDep);
    reverseDep.erase(I);
    I = reverseDep.find(rem);
  }

  getAnalysis<AliasAnalysis>().deleteValue(rem);
}
<commit_msg>When removing instructions from the analysis, be sure to check the confirmed flag when determining what to do with dependencies.<commit_after>//===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation  --*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the Owen Anderson and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements an analysis that determines, for a given memory
// operation, what preceding memory operations it depends on.  It builds on
// alias analysis information, and tries to provide a lazy, caching interface to
// a common kind of alias information query.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/MemoryDependenceAnalysis.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/Function.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Target/TargetData.h"

using namespace llvm;

char MemoryDependenceAnalysis::ID = 0;

Instruction* MemoryDependenceAnalysis::NonLocal = (Instruction*)0;
Instruction* MemoryDependenceAnalysis::None = (Instruction*)~0;

// Register this pass...
static RegisterPass<MemoryDependenceAnalysis> X("memdep",
                                                "Memory Dependence Analysis");

/// getAnalysisUsage - Does not modify anything.  It uses Alias Analysis.
///
void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
  AU.setPreservesAll();
  AU.addRequiredTransitive<AliasAnalysis>();
  AU.addRequiredTransitive<TargetData>();
}

// Find the dependency of a CallSite
Instruction* MemoryDependenceAnalysis::getCallSiteDependency(CallSite C, Instruction* start,
                                                             bool local) {
  assert(local && "Non-local memory dependence analysis not yet implemented");

  AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
  TargetData& TD = getAnalysis<TargetData>();
  BasicBlock::iterator blockBegin = C.getInstruction()->getParent()->begin();
  BasicBlock::iterator QI = C.getInstruction();

  while (QI != blockBegin) {
    --QI;

    // If this inst is a memory op, get the pointer it accessed
    Value* pointer = 0;
    uint64_t pointerSize = 0;
    if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
      pointer = S->getPointerOperand();
      pointerSize = TD.getTypeSize(S->getOperand(0)->getType());
    } else if (LoadInst* L = dyn_cast<LoadInst>(QI)) {
      pointer = L->getPointerOperand();
      pointerSize = TD.getTypeSize(L->getType());
    } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
      pointer = AI;
      if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
        pointerSize = C->getZExtValue() * TD.getTypeSize(AI->getAllocatedType());
      else
        pointerSize = ~0UL;
    } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
      pointer = V->getOperand(0);
      pointerSize = TD.getTypeSize(V->getType());
    } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
      pointer = F->getPointerOperand();

      // FreeInsts erase the entire structure
      pointerSize = ~0UL;
    } else if (CallSite::get(QI).getInstruction() != 0) {
      if (AA.getModRefInfo(C, CallSite::get(QI)) != AliasAnalysis::NoModRef) {
        depGraphLocal.insert(std::make_pair(C.getInstruction(), std::make_pair(QI, true)));
        reverseDep.insert(std::make_pair(QI, C.getInstruction()));
        return QI;
      } else {
        continue;
      }
    } else
      continue;

    if (AA.getModRefInfo(C, pointer, pointerSize) != AliasAnalysis::NoModRef) {
      depGraphLocal.insert(std::make_pair(C.getInstruction(), std::make_pair(QI, true)));
      reverseDep.insert(std::make_pair(QI, C.getInstruction()));
      return QI;
    }
  }

  // No dependence found
  depGraphLocal.insert(std::make_pair(C.getInstruction(), std::make_pair(NonLocal, true)));
  reverseDep.insert(std::make_pair(NonLocal, C.getInstruction()));
  return NonLocal;
}

/// getDependency - Return the instruction on which a memory operation
/// depends.  The local paramter indicates if the query should only
/// evaluate dependencies within the same basic block.
Instruction* MemoryDependenceAnalysis::getDependency(Instruction* query,
                                                     Instruction* start,
                                                     bool local) {
  if (!local)
    assert(0 && "Non-local memory dependence is not yet supported.");

  // Start looking for dependencies with the queried inst
  BasicBlock::iterator QI = query;

  // Check for a cached result
  std::pair<Instruction*, bool> cachedResult = depGraphLocal[query];
  // If we have a _confirmed_ cached entry, return it
  if (cachedResult.second)
    return cachedResult.first;
  else if (cachedResult.first != NonLocal)
  // If we have an unconfirmed cached entry, we can start our search from there
    QI = cachedResult.first;

  if (start)
    QI = start;

  AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
  TargetData& TD = getAnalysis<TargetData>();

  // Get the pointer value for which dependence will be determined
  Value* dependee = 0;
  uint64_t dependeeSize = 0;
  bool queryIsVolatile = false;
  if (StoreInst* S = dyn_cast<StoreInst>(query)) {
    dependee = S->getPointerOperand();
    dependeeSize = TD.getTypeSize(S->getOperand(0)->getType());
    queryIsVolatile = S->isVolatile();
  } else if (LoadInst* L = dyn_cast<LoadInst>(query)) {
    dependee = L->getPointerOperand();
    dependeeSize = TD.getTypeSize(L->getType());
    queryIsVolatile = L->isVolatile();
  } else if (VAArgInst* V = dyn_cast<VAArgInst>(query)) {
    dependee = V->getOperand(0);
    dependeeSize = TD.getTypeSize(V->getType());
  } else if (FreeInst* F = dyn_cast<FreeInst>(query)) {
    dependee = F->getPointerOperand();

    // FreeInsts erase the entire structure, not just a field
    dependeeSize = ~0UL;
  } else if (CallSite::get(query).getInstruction() != 0)
    return getCallSiteDependency(CallSite::get(query), start);
  else if (isa<AllocationInst>(query))
    return None;
  else
    return None;

  BasicBlock::iterator blockBegin = query->getParent()->begin();

  while (QI != blockBegin) {
    --QI;

    // If this inst is a memory op, get the pointer it accessed
    Value* pointer = 0;
    uint64_t pointerSize = 0;
    if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
      // All volatile loads/stores depend on each other
      if (queryIsVolatile && S->isVolatile()) {
        if (!start) {
          depGraphLocal.insert(std::make_pair(query, std::make_pair(S, true)));
          reverseDep.insert(std::make_pair(S, query));
        }

        return S;
      }

      pointer = S->getPointerOperand();
      pointerSize = TD.getTypeSize(S->getOperand(0)->getType());
    } else if (LoadInst* L = dyn_cast<LoadInst>(QI)) {
      // All volatile loads/stores depend on each other
      if (queryIsVolatile && L->isVolatile()) {
        if (!start) {
          depGraphLocal.insert(std::make_pair(query, std::make_pair(L, true)));
          reverseDep.insert(std::make_pair(L, query));
        }

        return L;
      }

      pointer = L->getPointerOperand();
      pointerSize = TD.getTypeSize(L->getType());
    } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
      pointer = AI;
      if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
        pointerSize = C->getZExtValue() * TD.getTypeSize(AI->getAllocatedType());
      else
        pointerSize = ~0UL;
    } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
      pointer = V->getOperand(0);
      pointerSize = TD.getTypeSize(V->getType());
    } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
      pointer = F->getPointerOperand();

      // FreeInsts erase the entire structure
      pointerSize = ~0UL;
    } else if (CallSite::get(QI).getInstruction() != 0) {
      // Call insts need special handling.  Check is they can modify our pointer
      if (AA.getModRefInfo(CallSite::get(QI), dependee, dependeeSize) !=
          AliasAnalysis::NoModRef) {
        if (!start) {
          depGraphLocal.insert(std::make_pair(query, std::make_pair(QI, true)));
          reverseDep.insert(std::make_pair(QI, query));
        }

        return QI;
      } else {
        continue;
      }
    }

    // If we found a pointer, check if it could be the same as our pointer
    if (pointer) {
      AliasAnalysis::AliasResult R = AA.alias(pointer, pointerSize,
                                              dependee, dependeeSize);

      if (R != AliasAnalysis::NoAlias) {
        if (!start) {
          depGraphLocal.insert(std::make_pair(query, std::make_pair(QI, true)));
          reverseDep.insert(std::make_pair(QI, query));
        }

        return QI;
      }
    }
  }

  // If we found nothing, return the non-local flag
  if (!start) {
    depGraphLocal.insert(std::make_pair(query,
                                        std::make_pair(NonLocal, true)));
    reverseDep.insert(std::make_pair(NonLocal, query));
  }

  return NonLocal;
}

/// removeInstruction - Remove an instruction from the dependence analysis,
/// updating the dependence of instructions that previously depended on it.
void MemoryDependenceAnalysis::removeInstruction(Instruction* rem) {
  // Figure out the new dep for things that currently depend on rem
  Instruction* newDep = NonLocal;
  if (depGraphLocal[rem].first != NonLocal &&
      depGraphLocal[rem].second) {
    // If we have dep info for rem, set them to it
    BasicBlock::iterator RI = depGraphLocal[rem].first;
    RI++;
    newDep = RI;
  } else if (depGraphLocal[rem].first == NonLocal &&
             depGraphLocal[rem].second ) {
    // If we have a confirmed non-local flag, use it
    newDep = NonLocal;
  } else {
    // Otherwise, use the immediate successor of rem
    // NOTE: This is because, when getDependence is called, it will first check
    // the immediate predecessor of what is in the cache.
    BasicBlock::iterator RI = rem;
    RI++;
    newDep = RI;
  }

  std::multimap<Instruction*, Instruction*>::iterator I = reverseDep.find(rem);
  while (I->first == rem) {
    // Insert the new dependencies
    // Mark it as unconfirmed as long as it is not the non-local flag
    depGraphLocal[I->second] = std::make_pair(newDep, !newDep);
    reverseDep.erase(I);
    I = reverseDep.find(rem);
  }

  getAnalysis<AliasAnalysis>().deleteValue(rem);
}
<|endoftext|>


<commit_before>#include "params.h"
#include "consensus.h"

#include <getopt.h>

/****************************
 *** Consensus parameters ***
 ****************************/

void ococo::params_t::init_default_values() {
    verbose               = false;
    counters_str          = "ococo16";
    counter_configuration = OCOCO16;
    mode                  = BATCH;
    mode_str              = "batch";
    strategy              = MAJORITY;
    strategy_str          = "majority";
    min_mapq              = default_q;
    min_baseq             = default_Q;
    init_ref_weight       = default_w;
    min_coverage          = default_c;
    majority_threshold    = default_M;

    cons_alg[strategy_t::NO_UPDATES]     = &cons_call_no_updates;
    cons_alg[strategy_t::STOCHASTIC]     = &cons_call_stoch;
    cons_alg[strategy_t::STOCHASTIC_AMB] = &cons_call_stoch_amb;
    cons_alg[strategy_t::MAJORITY]       = &cons_call_maj;
    cons_alg[strategy_t::MAJORITY_AMB]   = &cons_call_maj_amb;

    vcf_file       = nullptr;
    pileup_file    = nullptr;
    fasta_out_file = nullptr;
    sam_file       = nullptr;
    log_file       = nullptr;

    n_upd = 0;

    correctly_initialized = true;
    return_code           = 0;
}

ococo::params_t::params_t() { init_default_values(); }

ococo::params_t::params_t(int argc, const char **argv) {
    init_default_values();
    parse_commandline(argc, argv);
}

ococo::params_t::~params_t() {
    /*
     * Close files.
     */

    if (sam_file != nullptr) {
        int error_code = sam_close(sam_file);
        if (error_code != 0) {
            ococo::error("SAM file could not be closed.\n");
            return_code = -1;
        }
    }

    if (vcf_file != nullptr) {
        int error_code = fclose(vcf_file);
        if (error_code != 0) {
            ococo::error("VCF file could not be closed.\n");
            return_code = -1;
        }
    }

    if (pileup_file != nullptr) {
        int error_code = fclose(pileup_file);
        if (error_code != 0) {
            return_code = error_code;
            ococo::error("Pileup file could not be closed.\n");
            return_code = -1;
        }
    }

    if (fasta_out_file != nullptr) {
        int error_code = fclose(fasta_out_file);
        if (error_code != 0) {
            ococo::error("FASTA consensus file could not be closed.\n");
            return_code = -1;
        }
    }

    if (log_file != nullptr) {
        int error_code = fclose(log_file);
    }
}

void ococo::params_t::print_help() {
    print_version();

    std::cerr
        <<
        // clang-format off

        // "---------------------------------------------------------------------------------"
           "Usage:   ococo -i <SAM/BAM file> [other options]\n\n"
        // "---------------------------------------------------------------------------------"
           //"Generic options:\n"
           //"  -h, --help            print this message and exit\n\n"
        // "---------------------------------------------------------------------------------"
           "Input options:\n"
           "  -i, --input FILE      input SAM/BAM file (- for standard input)\n"
           "  -f, --fasta-ref FILE  initial FASTA reference (otherwise seq of N's is used)\n"
           "  -s, --stats-in FILE   input statistics\n\n"
        // "---------------------------------------------------------------------------------"
           "Output options:\n"
           "  -F, --fasta-cons FILE FASTA file with consensus\n"
           "  -S, --stats-out FILE  output statistics\n"
           "  -V, --vcf-cons FILE   VCF file with updates of consensus (- for standard output)\n"
           "  -P, --pileup FILE     truncated pileup (- for standard output)\n"
           //"  --log FILE            auxiliary log file\n"
           "  --verbose             verbose mode (report every update of a counter)\n\n"
        // "---------------------------------------------------------------------------------"
           "Parameters for consensus calling:\n"
           "  -x, --counters STR    counter configuration: [ococo16]\n"
           "                           - ococo16 (3b/counter, 16b/position)\n"
           "                           - ococo32 (7b/counter, 32b/position)\n"
           "                           - ococo64 (15b/counter, 64b/position)\n"
           "  -m, --mode STR        mode: [batch]\n"
           "                           - real-time (updates reported immediately)\n"
           "                           - batch (updates reported after end of algn stream)\n"
           "  -t, --strategy STR    strategy for updates: [majority]\n"
           "                           - majority (update to majority base)\n"
           "                           - stochastic (update to stochastically drawn base)\n"
           "                           - no-updates (no updates, only counters updated)\n"
           //"  -a [ --allow-amb ]                    Allow updates to ambiguous "
           //"nucleotides.\n"
           "  -q, --min-MQ INT      skip alignments with mapping quality smaller than INT [" << default_q << "]\n"
           "  -Q, --min-BQ INT      skip bases with base quality smaller than INT [" << default_Q <<"]\n"
           "  -w, --ref-weight INT  initial counter value for nucleotides from ref ["<< default_w <<"]\n"
           "  -c, --min-cov INT     minimum coverage required for update [" << default_c <<"]\n"
           "  -M, --maj-thres FLOAT majority threshold [" << default_M << "]\n\n"
        // "---------------------------------------------------------------------------------"
           "Examples:\n"
           "   ococo -i test.bam -f test.fa -m real-time -V -\n"
           "   ococo -x ococo64 -i test.bam -f test.fa -P - -V variants.vcf\n"
        // "---------------------------------------------------------------------------------"
        // clang-format on
        << std::endl;
}

void ococo::params_t::parse_commandline(int argc, const char **argv) {
    /* Parse cmd parameters */
    std::stringstream cmd;
    for (int32_t i = 0; i < argc; i++) {
        cmd << argv[i];
        if (i != argc - 1) {
            cmd << " ";
        }
    }
    command=cmd.str();

    if (argc == 1) {
        print_help();
        exit(1);
    }

    const struct option lopts[] = {
        {"version", no_argument, nullptr, 'v'},
        {"help", no_argument, nullptr, 'h'},
        //
        {"input", required_argument, nullptr, 'i'},
        {"fasta-ref", required_argument, nullptr, 'f'},
        {"stats-in", required_argument, nullptr, 's'},
        //
        {"fasta-cons", required_argument, nullptr, 'F'},
        {"stats-out", required_argument, nullptr, 'S'},
        {"vcf-cons", required_argument, nullptr, 'V'},
        {"pileup", required_argument, nullptr, 'P'},
        {"log", required_argument, nullptr, 'L'},
        {"verbose", no_argument, nullptr, 'W'},
        //
        {"counters", required_argument, nullptr, 'x'},
        {"mode", required_argument, nullptr, 'm'},
        {"strategy", required_argument, nullptr, 't'},
        {"min-MQ", required_argument, nullptr, 'q'},
        {"min-BQ", required_argument, nullptr, 'Q'},
        {"ref-weight", required_argument, nullptr, 'w'},
        {"min-cov", required_argument, nullptr, 'c'},
        {"min-coverage", required_argument, nullptr, 'c'},  // deprec
        {"maj-thres", required_argument, nullptr, 'M'},
        {"majority-threshold", required_argument, nullptr, 'M'},  // deprec
        //
        {nullptr, 0, nullptr, 0}};

    int c;
    using std::string;
    while ((c = getopt_long(argc, (char *const *)argv,
                            "vhi:f:s:F:S:V:P:L:W:x:m:t:q:Q:w:c:M:", lopts,
                            nullptr)) >= 0) {
        switch (c) {
            case 'v': {
                print_version();
                exit(0);
                break;
            }
            case 'h': {
                print_help();
                exit(0);
                break;
            }
            case 'i': {
                sam_fn = optarg;
                break;
            }
            case 'f': {
                fasta_in_fn = optarg;
                break;
            }
            case 's': {
                stats_in_fn = optarg;
                break;
            }
            case 'F': {
                fasta_out_fn = optarg;
                break;
            }
            case 'S': {
                stats_out_fn = optarg;
                break;
            }
            case 'V': {
                vcf_fn = optarg;
                break;
            }
            case 'P': {
                pileup_fn = optarg;
                break;
            }
            case 'L': {
                log_fn = optarg;
                break;
            }
            case 'W': {
                verbose = true;
                break;
            }
            case 'x': {
                counters_str = optarg;

                if (counters_str.compare("ococo16") == 0) {
                    counter_configuration = OCOCO16;
                    counters_str_descr =
                        "ococo16 (16 bits per position, 3bits per nucleotide "
                        "counter)";
                } else if (counters_str.compare("ococo32") == 0) {
                    counter_configuration = OCOCO32;
                    counters_str_descr =
                        "ococo32 (32 bits per position, 7bits per nucleotide "
                        "counter)";
                } else if (counters_str.compare("ococo64") == 0) {
                    counter_configuration = OCOCO64;
                    counters_str_descr =
                        "ococo64 (64 bits per position, 15bits per nucleotide "
                        "counter)";
                } else {
                    ococo::error(
                        "Unknown counter configuration '%s'. Possible modes "
                        "are 'ococo16', 'ococo32', and 'ococo64'.\n",
                        counters_str.c_str());
                    exit(1);
                }

                break;
            }
            case 'm': {
                mode_str = optarg;

                if (mode_str.compare("batch") == 0) {
                    mode = ococo::mode_t::BATCH;
                } else if (mode_str.compare("real-time") == 0) {
                    mode = ococo::mode_t::REALTIME;
                } else {
                    ococo::error(
                        "Unknown mode '%s'. Possible modes are 'batch' and "
                        "'real-time'.\n",
                        mode_str.c_str());
                    exit(1);
                }

                break;
            }
            case 't': {
                strategy_str = optarg;

                if (strategy_str.compare("stochastic") == 0) {
                    strategy = ococo::strategy_t::STOCHASTIC;
                } else if (strategy_str.compare("no-updates") == 0) {
                    strategy = ococo::strategy_t::NO_UPDATES;
                } else if (strategy_str.compare("majority") == 0) {
                    strategy = ococo::strategy_t::MAJORITY;
                } else {
                    ococo::error(
                        "Unknown strategy '%s'. Possible strategies are "
                        "'majority', 'stochastic', and 'no-updates'.\n",
                        strategy_str.c_str());
                    exit(1);
                }

                break;
            }
            case 'q': {
                min_mapq = atoi(optarg);
                break;
            }
            case 'Q': {
                min_baseq = atoi(optarg);
                break;
            }
            case 'w': {
                init_ref_weight = atoi(optarg);
                break;
            }
            case 'c': {
                min_coverage = atoi(optarg);
                break;
            }
            case 'M': {
                majority_threshold = atof(optarg);
                exit(0);
                break;
            }
            case '?': {
                ococo::error("Unknown error");
                exit(1);
                break;
            }
        }
    }
    if (sam_fn.size()==0){
        ococo::error("SAM/BAM file must be specified (option '-i').\n");
        exit(1);
    }
    ococo::info("Ococo starting: %s\n", counters_str_descr.c_str());
}
<commit_msg>Fix bug with equal files<commit_after>#include "params.h"
#include "consensus.h"

#include <getopt.h>

/****************************
 *** Consensus parameters ***
 ****************************/

void ococo::params_t::init_default_values() {
    verbose               = false;
    counters_str          = "ococo16";
    counter_configuration = OCOCO16;
    mode                  = BATCH;
    mode_str              = "batch";
    strategy              = MAJORITY;
    strategy_str          = "majority";
    min_mapq              = default_q;
    min_baseq             = default_Q;
    init_ref_weight       = default_w;
    min_coverage          = default_c;
    majority_threshold    = default_M;

    cons_alg[strategy_t::NO_UPDATES]     = &cons_call_no_updates;
    cons_alg[strategy_t::STOCHASTIC]     = &cons_call_stoch;
    cons_alg[strategy_t::STOCHASTIC_AMB] = &cons_call_stoch_amb;
    cons_alg[strategy_t::MAJORITY]       = &cons_call_maj;
    cons_alg[strategy_t::MAJORITY_AMB]   = &cons_call_maj_amb;

    vcf_file       = nullptr;
    pileup_file    = nullptr;
    fasta_out_file = nullptr;
    sam_file       = nullptr;
    log_file       = nullptr;

    n_upd = 0;

    correctly_initialized = true;
    return_code           = 0;
}

ococo::params_t::params_t() { init_default_values(); }

ococo::params_t::params_t(int argc, const char **argv) {
    init_default_values();
    parse_commandline(argc, argv);
}

ococo::params_t::~params_t() {
    /*
     * Close files.
     */

    if (sam_file != nullptr) {
        int error_code = sam_close(sam_file);
        if (error_code != 0) {
            ococo::error("SAM file could not be closed.\n");
            return_code = -1;
        }
    }

    if (vcf_file != nullptr) {
        int error_code = fclose(vcf_file);
        if (error_code != 0) {
            ococo::error("VCF file could not be closed.\n");
            return_code = -1;
        }
    }

    if (pileup_file != nullptr) {
        int error_code = fclose(pileup_file);
        if (error_code != 0) {
            return_code = error_code;
            ococo::error("Pileup file could not be closed.\n");
            return_code = -1;
        }
    }

    if (fasta_out_file != nullptr) {
        int error_code = fclose(fasta_out_file);
        if (error_code != 0) {
            ococo::error("FASTA consensus file could not be closed.\n");
            return_code = -1;
        }
    }

    if (log_file != nullptr) {
        int error_code = fclose(log_file);
    }
}

void ococo::params_t::print_help() {
    print_version();

    std::cerr
        <<
        // clang-format off

        // "---------------------------------------------------------------------------------"
           "Usage:   ococo -i <SAM/BAM file> [other options]\n\n"
        // "---------------------------------------------------------------------------------"
           //"Generic options:\n"
           //"  -h, --help            print this message and exit\n\n"
        // "---------------------------------------------------------------------------------"
           "Input options:\n"
           "  -i, --input FILE      input SAM/BAM file (- for standard input)\n"
           "  -f, --fasta-ref FILE  initial FASTA reference (otherwise seq of N's is used)\n"
           "  -s, --stats-in FILE   input statistics\n\n"
        // "---------------------------------------------------------------------------------"
           "Output options:\n"
           "  -F, --fasta-cons FILE FASTA file with consensus\n"
           "  -S, --stats-out FILE  output statistics\n"
           "  -V, --vcf-cons FILE   VCF file with updates of consensus (- for standard output)\n"
           "  -P, --pileup FILE     truncated pileup (- for standard output)\n"
           //"  --log FILE            auxiliary log file\n"
           "  --verbose             verbose mode (report every update of a counter)\n\n"
        // "---------------------------------------------------------------------------------"
           "Parameters for consensus calling:\n"
           "  -x, --counters STR    counter configuration: [ococo16]\n"
           "                           - ococo16 (3b/counter, 16b/position)\n"
           "                           - ococo32 (7b/counter, 32b/position)\n"
           "                           - ococo64 (15b/counter, 64b/position)\n"
           "  -m, --mode STR        mode: [batch]\n"
           "                           - real-time (updates reported immediately)\n"
           "                           - batch (updates reported after end of algn stream)\n"
           "  -t, --strategy STR    strategy for updates: [majority]\n"
           "                           - majority (update to majority base)\n"
           "                           - stochastic (update to stochastically drawn base)\n"
           "                           - no-updates (no updates, only counters updated)\n"
           //"  -a [ --allow-amb ]                    Allow updates to ambiguous "
           //"nucleotides.\n"
           "  -q, --min-MQ INT      skip alignments with mapping quality smaller than INT [" << default_q << "]\n"
           "  -Q, --min-BQ INT      skip bases with base quality smaller than INT [" << default_Q <<"]\n"
           "  -w, --ref-weight INT  initial counter value for nucleotides from ref ["<< default_w <<"]\n"
           "  -c, --min-cov INT     minimum coverage required for update [" << default_c <<"]\n"
           "  -M, --maj-thres FLOAT majority threshold [" << default_M << "]\n\n"
        // "---------------------------------------------------------------------------------"
           "Examples:\n"
           "   ococo -i test.bam -f test.fa -m real-time -V -\n"
           "   ococo -x ococo64 -i test.bam -f test.fa -P - -V variants.vcf\n"
        // "---------------------------------------------------------------------------------"
        // clang-format on
        << std::endl;
}

void ococo::params_t::parse_commandline(int argc, const char **argv) {
    /* Parse cmd parameters */
    std::stringstream cmd;
    for (int32_t i = 0; i < argc; i++) {
        cmd << argv[i];
        if (i != argc - 1) {
            cmd << " ";
        }
    }
    command=cmd.str();

    if (argc == 1) {
        print_help();
        exit(1);
    }

    const struct option lopts[] = {
        {"version", no_argument, nullptr, 'v'},
        {"help", no_argument, nullptr, 'h'},
        //
        {"input", required_argument, nullptr, 'i'},
        {"fasta-ref", required_argument, nullptr, 'f'},
        {"stats-in", required_argument, nullptr, 's'},
        //
        {"fasta-cons", required_argument, nullptr, 'F'},
        {"stats-out", required_argument, nullptr, 'S'},
        {"vcf-cons", required_argument, nullptr, 'V'},
        {"pileup", required_argument, nullptr, 'P'},
        {"log", required_argument, nullptr, 'L'},
        {"verbose", no_argument, nullptr, 'W'},
        //
        {"counters", required_argument, nullptr, 'x'},
        {"mode", required_argument, nullptr, 'm'},
        {"strategy", required_argument, nullptr, 't'},
        {"min-MQ", required_argument, nullptr, 'q'},
        {"min-BQ", required_argument, nullptr, 'Q'},
        {"ref-weight", required_argument, nullptr, 'w'},
        {"min-cov", required_argument, nullptr, 'c'},
        {"min-coverage", required_argument, nullptr, 'c'},  // deprec
        {"maj-thres", required_argument, nullptr, 'M'},
        {"majority-threshold", required_argument, nullptr, 'M'},  // deprec
        //
        {nullptr, 0, nullptr, 0}};

    int c;
    using std::string;
    while ((c = getopt_long(argc, (char *const *)argv,
                            "vhi:f:s:F:S:V:P:L:W:x:m:t:q:Q:w:c:M:", lopts,
                            nullptr)) >= 0) {
        switch (c) {
            case 'v': {
                print_version();
                exit(0);
                break;
            }
            case 'h': {
                print_help();
                exit(0);
                break;
            }
            case 'i': {
                sam_fn = optarg;
                break;
            }
            case 'f': {
                fasta_in_fn = optarg;
                break;
            }
            case 's': {
                stats_in_fn = optarg;
                break;
            }
            case 'F': {
                fasta_out_fn = optarg;
                break;
            }
            case 'S': {
                stats_out_fn = optarg;
                break;
            }
            case 'V': {
                vcf_fn = optarg;
                break;
            }
            case 'P': {
                pileup_fn = optarg;
                break;
            }
            case 'L': {
                log_fn = optarg;
                break;
            }
            case 'W': {
                verbose = true;
                break;
            }
            case 'x': {
                counters_str = optarg;

                if (counters_str.compare("ococo16") == 0) {
                    counter_configuration = OCOCO16;
                    counters_str_descr =
                        "ococo16 (16 bits per position, 3bits per nucleotide "
                        "counter)";
                } else if (counters_str.compare("ococo32") == 0) {
                    counter_configuration = OCOCO32;
                    counters_str_descr =
                        "ococo32 (32 bits per position, 7bits per nucleotide "
                        "counter)";
                } else if (counters_str.compare("ococo64") == 0) {
                    counter_configuration = OCOCO64;
                    counters_str_descr =
                        "ococo64 (64 bits per position, 15bits per nucleotide "
                        "counter)";
                } else {
                    ococo::error(
                        "Unknown counter configuration '%s'. Possible modes "
                        "are 'ococo16', 'ococo32', and 'ococo64'.\n",
                        counters_str.c_str());
                    exit(1);
                }

                break;
            }
            case 'm': {
                mode_str = optarg;

                if (mode_str.compare("batch") == 0) {
                    mode = ococo::mode_t::BATCH;
                } else if (mode_str.compare("real-time") == 0) {
                    mode = ococo::mode_t::REALTIME;
                } else {
                    ococo::error(
                        "Unknown mode '%s'. Possible modes are 'batch' and "
                        "'real-time'.\n",
                        mode_str.c_str());
                    exit(1);
                }

                break;
            }
            case 't': {
                strategy_str = optarg;

                if (strategy_str.compare("stochastic") == 0) {
                    strategy = ococo::strategy_t::STOCHASTIC;
                } else if (strategy_str.compare("no-updates") == 0) {
                    strategy = ococo::strategy_t::NO_UPDATES;
                } else if (strategy_str.compare("majority") == 0) {
                    strategy = ococo::strategy_t::MAJORITY;
                } else {
                    ococo::error(
                        "Unknown strategy '%s'. Possible strategies are "
                        "'majority', 'stochastic', and 'no-updates'.\n",
                        strategy_str.c_str());
                    exit(1);
                }

                break;
            }
            case 'q': {
                min_mapq = atoi(optarg);
                break;
            }
            case 'Q': {
                min_baseq = atoi(optarg);
                break;
            }
            case 'w': {
                init_ref_weight = atoi(optarg);
                break;
            }
            case 'c': {
                min_coverage = atoi(optarg);
                break;
            }
            case 'M': {
                majority_threshold = atof(optarg);
                exit(0);
                break;
            }
            case '?': {
                ococo::error("Unknown error");
                exit(1);
                break;
            }
        }
    }
    if (sam_fn.size()==0){
        ococo::error("SAM/BAM file must be specified (option '-i').\n");
        exit(1);
    }

    if(pileup_fn.size()!=0 && pileup_fn.compare(vcf_fn)==0){
        ococo::error("Pileup and VCF files cannot be the same (both currently '%s').\n", pileup_fn.c_str());
        exit(1);
    }

    ococo::info("Ococo starting: %s\n", counters_str_descr.c_str());
}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <assert.h>

#include "GramSorter.hh"
#include "TreeGramArpaReader.hh"
#include "str.hh"
#include "ClusterMap.hh"

TreeGramArpaReader::TreeGramArpaReader()
  : m_lineno(0)
{
}

void
TreeGramArpaReader::read_error()
{
  fprintf(stderr, "TreeGramArpaReader::read(): error on line %d\n", m_lineno);
  exit(1);
}

void
TreeGramArpaReader::read(FILE *file, TreeGram *tree_gram)
{
  std::string line;
  std::vector<std::string> vec;

  // Just for efficiency
  line.reserve(128);
  vec.reserve(16);

  bool ok = true;

  m_lineno = 0;

  // Find header
  while (1) {
    ok = str::read_line(&line, file, true);
    m_lineno++;

    if (!ok) {
      fprintf(stderr, "TreeGramArpaReader::read(): "
	      "error on line %d while waiting \\data\\", m_lineno);
      exit(1);
    }

    if (line.substr(0,11) == "\\clustermap") {
      int ord;
      if (sscanf(line.c_str(),"\\clustermap %d",&ord)!=1) assert(false);
      tree_gram->clmap=new ClusterMap<int, int>;
      m_lineno=tree_gram->clmap->read(file,ord,m_lineno);
      for (int i=0;i<tree_gram->clmap->num_words();i++) {
	tree_gram->add_word(tree_gram->clmap->word(i));
      }
    }

    if (line.substr(0,12) == "\\fclustermap") {
      int ord;
      if (sscanf(line.c_str(),"\\fclustermap %d",&ord)!=1) assert(false);
      tree_gram->clmap=new ClusterFMap<int, int>;
      m_lineno=tree_gram->clmap->read(file,ord,m_lineno);
      for (int i=0;i<tree_gram->clmap->num_words();i++) {
	tree_gram->add_word(tree_gram->clmap->word(i));
      }
    }

    if (line == "\\interpolated")
      tree_gram->set_type(TreeGram::INTERPOLATED);

    if (line == "\\data\\")
      break;
  }

  // Read header
  int order = 1;
  int number_of_nodes = 0;
  int max_order_count = 0;
  while (1) {
    ok = str::read_line(&line, file, true);
    m_lineno++;

    if (!ok) {
      fprintf(stderr, "TreeGramArpaReader::read(): "
	      "error on line %d while reading counts", m_lineno);
      exit(1);
    }

    // Header ends in a \-command
    if (line[0] == '\\')
      break;

    // Skip empty lines
    if (line.find_first_not_of(" \t\n") == line.npos)
      continue;

    // All non-empty header lines must be ngram counts
    if (line.substr(0, 6) != "ngram ")
      read_error();
    {
      std::string tmp(line.substr(6));
      str::split(&tmp, "=", false, &vec);
    }
    if (vec.size() != 2)
      read_error();

    int count = atoi(vec[1].c_str());
    if (count > max_order_count)
      max_order_count = count;
    number_of_nodes += count;
    m_counts.push_back(count);

    if (atoi(vec[0].c_str()) != order || m_counts.back() < 0)
      read_error();
    order++;
  }

  tree_gram->reserve_nodes(number_of_nodes);

  // Read ngrams order by order
  for (order = 1; order <= m_counts.size(); order++) {

    // We must always have the correct header line at this point
    if (line[0] != '\\') {
      fprintf(stderr, "TreeGramArpaReader::read(): "
	      "\\%d-grams expected on line %d\n", order, m_lineno);
      exit(1);
    }
    str::clean(&line, " \t");
    str::split(&line, "-", false, &vec);

    if (atoi(vec[0].substr(1).c_str()) != order || vec[1] != "grams:") {
      fprintf(stderr, "TreeGramArpaReader::read(): "
	      "unexpected command on line %d: %s\n", m_lineno, line.c_str());
      exit(1);
    }

    // Read the grams of each order into the sorter
    GramSorter sorter(order, m_counts[order - 1]);
    TreeGram::Gram gram;
    gram.resize(order);
    for (int w = 0; w < m_counts[order-1]; w++) {

      // Read and split the line
      if (!str::read_line(&line, file))
	read_error();
      str::clean(&line, " \t\n");
      m_lineno++;

      // Ignore empty lines
      if (line.find_first_not_of(" \t\n") == line.npos) {
	w--;
	continue;
      }

      str::split(&line, " \t", true, &vec);

      // Check the number of columns on the line
      if (vec.size() < order + 1 || vec.size() > order + 2) {
	fprintf(stderr, "TreeGramArpaReader::read(): "
		"%d columns on line %d\n", vec.size(), m_lineno);
	exit(1);
      }
      if (order == m_counts.size() && vec.size() != order + 1)
	fprintf(stderr, "WARNING: %d columns on line %d\n", vec.size(),
		m_lineno);

      // FIXME: should we deny new words in higher order ngrams?

      // Parse log-probability, back-off weight and word indices
      // FIXME: check the conversion of floats
      float log_prob = strtod(vec[0].c_str(), NULL);
      float back_off = 0;
      if (vec.size() == order + 2)
	back_off = strtod(vec[order + 1].c_str(), NULL);

      // Add the gram to sorter
      //fprintf(stderr,"add gram [");
      for (int i = 0; i < order; i++) {
#ifdef USE_CL
	if (tree_gram->clmap) gram[i]=atoi(vec[i+1].c_str());
	else
#endif
	gram[i] = tree_gram->add_word(vec[i + 1]);
	//fprintf(stderr," %d", gram[i]);
      }
      sorter.add_gram(gram, log_prob, back_off);
      //fprintf(stderr,"] = [%f %f]\n",log_prob,back_off);
    }

    // Sort all grams read above and add them to the tree gram.
    sorter.sort();
    assert(sorter.num_grams() == m_counts[order - 1]);
    for (int i = 0; i < sorter.num_grams(); i++) {
      GramSorter::Data data = sorter.data(i);
      gram = sorter.gram(i);

      tree_gram->add_gram(gram, data.log_prob, data.back_off);
    }

    // Skip empty lines before the next order.
    while (1) {
      if (!str::read_line(&line, file, true)) {
	if (ferror(file))
	  read_error();
	if (feof(file))
	  break;
      }
      m_lineno++;

      if (line.find_first_not_of(" \t\n") != line.npos)
	break;
    }
  }
}

void
TreeGramArpaReader::write(FILE *out, TreeGram *tree_gram)
{
  if (tree_gram->get_type()==TreeGram::INTERPOLATED) {
    write_interpolated(out,tree_gram);
    return;
  }

  TreeGram::Iterator iter;

  // Header containing counts for each order
  fprintf(out, "\\data\\\n");
  for (int i = 1; i <= tree_gram->order(); i++)
    fprintf(out, "ngram %d=%d\n", i, tree_gram->gram_count(i));

  // Ngrams for each order
  for (int order = 1; order <= tree_gram->order(); order++) {
    iter.reset(tree_gram);
    fprintf(out, "\n\\%d-grams:\n",order);
    while (iter.next_order(order)) {

      // Log-probability
      fprintf(out, "%g", iter.node().log_prob);

      // Word indices in the ngram
      for (int j = 1; j <= order; j++)
	fprintf(out, " %s", tree_gram->word(iter.node(j).word).c_str());

      // Possible backoff
      if (order != tree_gram->order())
	fprintf(out, " %g\n", iter.node().back_off);
      else
	fprintf(out, "\n");
    }
  }
  fprintf(out, "\n\\end\\\n");
}

void
TreeGramArpaReader::write_interpolated(FILE *out, TreeGram *tree_gram)
{
  TreeGram::Iterator iter;

  // Header containing counts for each order
  fprintf(out, "\\data\\\n");
  for (int i = 1; i <= tree_gram->order(); i++)
    fprintf(out, "ngram %d=%d\n", i, tree_gram->gram_count(i));

  // Ngrams for each order
  TreeGram::Gram indices;
  for (int order = 1; order <= tree_gram->order(); order++) {
    indices.resize(order);
    iter.reset(tree_gram);
    fprintf(out, "\n\\%d-grams:\n",order);
    while (iter.next_order(order)) {
      for (int j = 1; j <= order; j++) {
	indices[j-1]=iter.node(j).word;
      }

      // Log-probability
      float lp=tree_gram->log_prob(indices);
      if (lp>0) {
	fprintf(stderr,"warning, n-gram [");
	for (int j=1;j<=order;j++)
	  fprintf(stderr," %s", tree_gram->word(indices[j-1]).c_str());
	fprintf(stderr,"] had logprob >0 (%e), corrected\n",lp);
	lp=0;
      }
      fprintf(out, "%g", lp);

      // Word indices in the ngram
      for (int j = 1; j <= order; j++)
	fprintf(out, " %s", tree_gram->word(indices[j-1]).c_str());

      // Possible backoff
      float bo=iter.node().back_off;
      if (bo<-0.0000001)
	fprintf(out, " %g\n", bo);
      else
	fprintf(out, "\n");
    }
  }
  fprintf(out, "\n\\end\\\n");
}
<commit_msg>*** empty log message ***<commit_after>#include <stdlib.h>
#include <assert.h>

#include "GramSorter.hh"
#include "TreeGramArpaReader.hh"
#include "str.hh"
#include "ClusterMap.hh"

TreeGramArpaReader::TreeGramArpaReader()
  : m_lineno(0)
{
}

void
TreeGramArpaReader::read_error()
{
  fprintf(stderr, "TreeGramArpaReader::read(): error on line %d\n", m_lineno);
  exit(1);
}

void
TreeGramArpaReader::read(FILE *file, TreeGram *tree_gram)
{
  std::string line;
  std::vector<std::string> vec;

  // Just for efficiency
  line.reserve(128);
  vec.reserve(16);

  bool ok = true;

  m_lineno = 0;

  // Find header
  while (1) {
    ok = str::read_line(&line, file, true);
    m_lineno++;

    if (!ok) {
      fprintf(stderr, "TreeGramArpaReader::read(): "
	      "error on line %d while waiting \\data\\", m_lineno);
      exit(1);
    }

    if (line.substr(0,11) == "\\clustermap") {
      int ord;
      if (sscanf(line.c_str(),"\\clustermap %d",&ord)!=1) assert(false);
      tree_gram->clmap=new ClusterMap<int, int>;
      m_lineno=tree_gram->clmap->read(file,ord,m_lineno);
      for (int i=0;i<tree_gram->clmap->num_words();i++) {
	tree_gram->add_word(tree_gram->clmap->word(i));
      }
    }

    if (line.substr(0,12) == "\\fclustermap") {
      int ord;
      if (sscanf(line.c_str(),"\\fclustermap %d",&ord)!=1) assert(false);
      tree_gram->clmap=new ClusterFMap<int, int>;
      m_lineno=tree_gram->clmap->read(file,ord,m_lineno);
      for (int i=0;i<tree_gram->clmap->num_words();i++) {
	tree_gram->add_word(tree_gram->clmap->word(i));
      }
    }

    if (line == "\\interpolated")
      tree_gram->set_type(TreeGram::INTERPOLATED);

    if (line == "\\data\\")
      break;
  }

  // Read header
  int order = 1;
  int number_of_nodes = 0;
  int max_order_count = 0;
  while (1) {
    ok = str::read_line(&line, file, true);
    m_lineno++;

    if (!ok) {
      fprintf(stderr, "TreeGramArpaReader::read(): "
	      "error on line %d while reading counts", m_lineno);
      exit(1);
    }

    // Header ends in a \-command
    if (line[0] == '\\')
      break;

    // Skip empty lines
    if (line.find_first_not_of(" \t\n") == line.npos)
      continue;

    // All non-empty header lines must be ngram counts
    if (line.substr(0, 6) != "ngram ")
      read_error();
    {
      std::string tmp(line.substr(6));
      str::split(&tmp, "=", false, &vec);
    }
    if (vec.size() != 2)
      read_error();

    int count = atoi(vec[1].c_str());
    if (count > max_order_count)
      max_order_count = count;
    number_of_nodes += count;
    m_counts.push_back(count);

    if (atoi(vec[0].c_str()) != order || m_counts.back() < 0)
      read_error();
    order++;
  }

  tree_gram->reserve_nodes(number_of_nodes);

  // Read ngrams order by order
  for (order = 1; order <= m_counts.size(); order++) {

    // We must always have the correct header line at this point
    if (line[0] != '\\') {
      fprintf(stderr, "TreeGramArpaReader::read(): "
	      "\\%d-grams expected on line %d\n", order, m_lineno);
      exit(1);
    }
    str::clean(&line, " \t");
    str::split(&line, "-", false, &vec);

    if (atoi(vec[0].substr(1).c_str()) != order || vec[1] != "grams:") {
      fprintf(stderr, "TreeGramArpaReader::read(): "
	      "unexpected command on line %d: %s\n", m_lineno, line.c_str());
      exit(1);
    }

    // Read the grams of each order into the sorter
    GramSorter sorter(order, m_counts[order - 1]);
    TreeGram::Gram gram;
    gram.resize(order);
    for (int w = 0; w < m_counts[order-1]; w++) {

      // Read and split the line
      if (!str::read_line(&line, file))
	read_error();
      str::clean(&line, " \t\n");
      m_lineno++;

      // Ignore empty lines
      if (line.find_first_not_of(" \t\n") == line.npos) {
	w--;
	continue;
      }

      str::split(&line, " \t", true, &vec);

      // Check the number of columns on the line
      if (vec.size() < order + 1 || vec.size() > order + 2) {
	fprintf(stderr, "TreeGramArpaReader::read(): "
		"%d columns on line %d\n", vec.size(), m_lineno);
	exit(1);
      }
      if (order == m_counts.size() && vec.size() != order + 1)
	fprintf(stderr, "WARNING: %d columns on line %d\n", vec.size(),
		m_lineno);

      // FIXME: should we deny new words in higher order ngrams?

      // Parse log-probability, back-off weight and word indices
      // FIXME: check the conversion of floats
      float log_prob = strtod(vec[0].c_str(), NULL);
      float back_off = 0;
      if (vec.size() == order + 2)
	back_off = strtod(vec[order + 1].c_str(), NULL);

      // Add the gram to sorter
      //fprintf(stderr,"add gram [");
      for (int i = 0; i < order; i++) {
	if (tree_gram->clmap) gram[i]=atoi(vec[i+1].c_str());
	else
	gram[i] = tree_gram->add_word(vec[i + 1]);
	//fprintf(stderr," %d", gram[i]);
      }
      sorter.add_gram(gram, log_prob, back_off);
      //fprintf(stderr,"] = [%f %f]\n",log_prob,back_off);
    }

    // Sort all grams read above and add them to the tree gram.
    sorter.sort();
    assert(sorter.num_grams() == m_counts[order - 1]);
    for (int i = 0; i < sorter.num_grams(); i++) {
      GramSorter::Data data = sorter.data(i);
      gram = sorter.gram(i);

      tree_gram->add_gram(gram, data.log_prob, data.back_off);
    }

    // Skip empty lines before the next order.
    while (1) {
      if (!str::read_line(&line, file, true)) {
	if (ferror(file))
	  read_error();
	if (feof(file))
	  break;
      }
      m_lineno++;

      if (line.find_first_not_of(" \t\n") != line.npos)
	break;
    }
  }
}

void
TreeGramArpaReader::write(FILE *out, TreeGram *tree_gram)
{
  if (tree_gram->get_type()==TreeGram::INTERPOLATED) {
    write_interpolated(out,tree_gram);
    return;
  }

  TreeGram::Iterator iter;

  // Header containing counts for each order
  fprintf(out, "\\data\\\n");
  for (int i = 1; i <= tree_gram->order(); i++)
    fprintf(out, "ngram %d=%d\n", i, tree_gram->gram_count(i));

  // Ngrams for each order
  for (int order = 1; order <= tree_gram->order(); order++) {
    iter.reset(tree_gram);
    fprintf(out, "\n\\%d-grams:\n",order);
    while (iter.next_order(order)) {

      // Log-probability
      fprintf(out, "%g", iter.node().log_prob);

      // Word indices in the ngram
      for (int j = 1; j <= order; j++)
	fprintf(out, " %s", tree_gram->word(iter.node(j).word).c_str());

      // Possible backoff
      if (order != tree_gram->order())
	fprintf(out, " %g\n", iter.node().back_off);
      else
	fprintf(out, "\n");
    }
  }
  fprintf(out, "\n\\end\\\n");
}

void
TreeGramArpaReader::write_interpolated(FILE *out, TreeGram *tree_gram)
{
  TreeGram::Iterator iter;

  // Header containing counts for each order
  fprintf(out, "\\data\\\n");
  for (int i = 1; i <= tree_gram->order(); i++)
    fprintf(out, "ngram %d=%d\n", i, tree_gram->gram_count(i));

  // Ngrams for each order
  TreeGram::Gram indices;
  for (int order = 1; order <= tree_gram->order(); order++) {
    indices.resize(order);
    iter.reset(tree_gram);
    fprintf(out, "\n\\%d-grams:\n",order);
    while (iter.next_order(order)) {
      for (int j = 1; j <= order; j++) {
	indices[j-1]=iter.node(j).word;
      }

      // Log-probability
      float lp=tree_gram->log_prob(indices);
      if (lp>0) {
	fprintf(stderr,"warning, n-gram [");
	for (int j=1;j<=order;j++)
	  fprintf(stderr," %s", tree_gram->word(indices[j-1]).c_str());
	fprintf(stderr,"] had logprob >0 (%e), corrected\n",lp);
	lp=0;
      }
      fprintf(out, "%g", lp);

      // Word indices in the ngram
      for (int j = 1; j <= order; j++)
	fprintf(out, " %s", tree_gram->word(indices[j-1]).c_str());

      // Possible backoff
      float bo=iter.node().back_off;
      if (bo<-0.0000001)
	fprintf(out, " %g\n", bo);
      else
	fprintf(out, "\n");
    }
  }
  fprintf(out, "\n\\end\\\n");
}
<|endoftext|>