<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2016 ETH Zurich
** 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 the ETH Zurich nor the names of its contributors 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 HOLDER 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 "MergeV2.h"

#include "MergePipelineComponent.h"
#include "ConflictUnitComponent.h"
#include "ListMergeComponentV2.h"

#include "../Diff.h"
#include "../GitPiecewiseLoader.h"
#include "../GitRepository.h"
#include "../../simple/GenericNode.h"
#include "../../simple/GenericTree.h"
#include "../../simple/SimpleTextFileStore.h"

namespace FilePersistence {

bool MergeV2::commit(const Signature& author, const Signature& committer, const QString& message)
{
	Q_ASSERT(stage_ == Stage::WroteToIndex);

	QString treeSHA1 = repository_->writeIndexToTree();

	QStringList parents;
	parents.append(headCommitId_);
	parents.append(revisionCommitId_);

	repository_->newCommit(treeSHA1, message, author, committer, parents);

	stage_ = Stage::Committed;

	return true;
}

std::shared_ptr<GenericTree> MergeV2::mergedTree()
{
	Q_ASSERT(stage_ >= Stage::BuiltMergedTree);
	return mergeData_.treeMerged_;
}

MergeV2::MergeV2(QString revision, bool fastForward, GitRepository* repository)
	: repository_{repository}
{
	headCommitId_ = repository_->getSHA1("HEAD");
	revisionCommitId_ = repository_->getSHA1(revision);
	baseCommitId_ = repository_->findMergeBase("HEAD", revision);

	Q_ASSERT(!baseCommitId_.isNull());

	stage_ = Stage::FoundMergeBase;

	Kind kind;
	if (baseCommitId_.compare(revisionCommitId_) == 0) kind = Kind::AlreadyUpToDate;
	else if (baseCommitId_.compare(headCommitId_) == 0) kind = Kind::FastForward;
	else kind = Kind::TrueMerge;

	stage_ = Stage::Classified;

	switch (kind)
	{
		case Kind::AlreadyUpToDate:
		{
			stage_ = MergeV2::Stage::Committed;
			break;
		}
		case Kind::FastForward:
		{
			if (fastForward)
			{
				QString branch = repository_->currentBranch();
				repository_->setReferenceTarget(branch, revisionCommitId_);
				repository_->checkout(revisionCommitId_, true);
				stage_ = Stage::Committed;
			}
			else
			{
				repository_->checkout(revisionCommitId_, true);
				repository_->writeRevisionIntoIndex(revisionCommitId_);
				stage_ = Stage::WroteToIndex;
			}
			break;
		}
		case Kind::TrueMerge:
		{
			performTrueMerge();
			break;
		}
		default:
			Q_ASSERT(false);
	}
}

void MergeV2::initializePipelineComponents()
{
	mergePipeline_.append(std::make_shared<ConflictUnitComponent>());
	mergePipeline_.append(std::make_shared<ListMergeComponentV2>());
}

void MergeV2::performTrueMerge()
{
	mergeData_.treeA_ = std::shared_ptr<GenericTree>(new GenericTree{repository_->projectName()});
	new GitPiecewiseLoader{mergeData_.treeA_, repository_, headCommitId_};
	mergeData_.treeB_ = std::unique_ptr<GenericTree>(new GenericTree{repository_->projectName()});
	new GitPiecewiseLoader{mergeData_.treeB_, repository_, revisionCommitId_};
	mergeData_.treeBase_ = std::unique_ptr<GenericTree>(new GenericTree{repository_->projectName()});
	new GitPiecewiseLoader{mergeData_.treeBase_, repository_, baseCommitId_};

	mergeData_.treeMerged_ = std::shared_ptr<GenericTree>(new GenericTree{repository_->projectName()});
	// If we need to piece-wise load nodes in the merge tree, these will necessarily have to come from the base
	// so we use the base commit bellow
	new GitPiecewiseLoader{mergeData_.treeMerged_, repository_, baseCommitId_};

	repository_->loadGenericTree(mergeData_.treeMerged_, baseCommitId_);
	mergeData_.treeMerged_->buildLookupHash();

	Diff diffA = repository_->diff(baseCommitId_, headCommitId_, mergeData_.treeBase_, mergeData_.treeA_);
	Diff diffB = repository_->diff(baseCommitId_, revisionCommitId_, mergeData_.treeBase_, mergeData_.treeB_);

	mergeData_.cg_.init(diffA, diffB, mergeData_.treeBase_.get());

	// Run the pipeline
	initializePipelineComponents();
	for (auto component : mergePipeline_)
		component->run(mergeData_);

	stage_ = Stage::AutoMerged;

	mergeData_.applyNonConflictingChanges();

	stage_ = Stage::BuiltMergedTree;

	SimpleTextFileStore::saveGenericTree(mergeData_.treeMerged_, repository_->projectName(),
													 repository_->workdirPath(), {"Project", "Module"});

	if (!mergeData_.cg_.hasConflicts())
	{
		stage_ = Stage::WroteToWorkDir;

		repository_->writeWorkdirToIndex();

		stage_ = Stage::WroteToIndex;
	}
	else
	{
		// TODO prepare for manual merge
		// TODO write conflicts to file maybe.
	}
}

bool MergeV2::isNodeInConflict(Model::NodeIdType nodeId) const
{
	//TODO : add soft conflicts
	return !mergeData_.cg_.changesForNode(nodeId).isEmpty();
}

}
<commit_msg>Revert "Enable merge trees to load nodes from the base branch"<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2016 ETH Zurich
** 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 the ETH Zurich nor the names of its contributors 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 HOLDER 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 "MergeV2.h"

#include "MergePipelineComponent.h"
#include "ConflictUnitComponent.h"
#include "ListMergeComponentV2.h"

#include "../Diff.h"
#include "../GitPiecewiseLoader.h"
#include "../GitRepository.h"
#include "../../simple/GenericNode.h"
#include "../../simple/GenericTree.h"
#include "../../simple/SimpleTextFileStore.h"

namespace FilePersistence {

bool MergeV2::commit(const Signature& author, const Signature& committer, const QString& message)
{
	Q_ASSERT(stage_ == Stage::WroteToIndex);

	QString treeSHA1 = repository_->writeIndexToTree();

	QStringList parents;
	parents.append(headCommitId_);
	parents.append(revisionCommitId_);

	repository_->newCommit(treeSHA1, message, author, committer, parents);

	stage_ = Stage::Committed;

	return true;
}

std::shared_ptr<GenericTree> MergeV2::mergedTree()
{
	Q_ASSERT(stage_ >= Stage::BuiltMergedTree);
	return mergeData_.treeMerged_;
}

MergeV2::MergeV2(QString revision, bool fastForward, GitRepository* repository)
	: repository_{repository}
{
	headCommitId_ = repository_->getSHA1("HEAD");
	revisionCommitId_ = repository_->getSHA1(revision);
	baseCommitId_ = repository_->findMergeBase("HEAD", revision);

	Q_ASSERT(!baseCommitId_.isNull());

	stage_ = Stage::FoundMergeBase;

	Kind kind;
	if (baseCommitId_.compare(revisionCommitId_) == 0) kind = Kind::AlreadyUpToDate;
	else if (baseCommitId_.compare(headCommitId_) == 0) kind = Kind::FastForward;
	else kind = Kind::TrueMerge;

	stage_ = Stage::Classified;

	switch (kind)
	{
		case Kind::AlreadyUpToDate:
		{
			stage_ = MergeV2::Stage::Committed;
			break;
		}
		case Kind::FastForward:
		{
			if (fastForward)
			{
				QString branch = repository_->currentBranch();
				repository_->setReferenceTarget(branch, revisionCommitId_);
				repository_->checkout(revisionCommitId_, true);
				stage_ = Stage::Committed;
			}
			else
			{
				repository_->checkout(revisionCommitId_, true);
				repository_->writeRevisionIntoIndex(revisionCommitId_);
				stage_ = Stage::WroteToIndex;
			}
			break;
		}
		case Kind::TrueMerge:
		{
			performTrueMerge();
			break;
		}
		default:
			Q_ASSERT(false);
	}
}

void MergeV2::initializePipelineComponents()
{
	mergePipeline_.append(std::make_shared<ConflictUnitComponent>());
	mergePipeline_.append(std::make_shared<ListMergeComponentV2>());
}

void MergeV2::performTrueMerge()
{
	mergeData_.treeA_ = std::shared_ptr<GenericTree>(new GenericTree{repository_->projectName()});
	new GitPiecewiseLoader{mergeData_.treeA_, repository_, headCommitId_};
	mergeData_.treeB_ = std::unique_ptr<GenericTree>(new GenericTree{repository_->projectName()});
	new GitPiecewiseLoader{mergeData_.treeB_, repository_, revisionCommitId_};
	mergeData_.treeBase_ = std::unique_ptr<GenericTree>(new GenericTree{repository_->projectName()});
	new GitPiecewiseLoader{mergeData_.treeBase_, repository_, baseCommitId_};

	mergeData_.treeMerged_ = std::shared_ptr<GenericTree>(new GenericTree{repository_->projectName()});
	// We will fully load the merge tree. Therefore there is no need to provide a piecewise loader.
	repository_->loadGenericTree(mergeData_.treeMerged_, baseCommitId_);
	mergeData_.treeMerged_->buildLookupHash();

	Diff diffA = repository_->diff(baseCommitId_, headCommitId_, mergeData_.treeBase_, mergeData_.treeA_);
	Diff diffB = repository_->diff(baseCommitId_, revisionCommitId_, mergeData_.treeBase_, mergeData_.treeB_);

	mergeData_.cg_.init(diffA, diffB, mergeData_.treeBase_.get());

	// Run the pipeline
	initializePipelineComponents();
	for (auto component : mergePipeline_)
		component->run(mergeData_);

	stage_ = Stage::AutoMerged;

	mergeData_.applyNonConflictingChanges();

	stage_ = Stage::BuiltMergedTree;

	SimpleTextFileStore::saveGenericTree(mergeData_.treeMerged_, repository_->projectName(),
													 repository_->workdirPath(), {"Project", "Module"});

	if (!mergeData_.cg_.hasConflicts())
	{
		stage_ = Stage::WroteToWorkDir;

		repository_->writeWorkdirToIndex();

		stage_ = Stage::WroteToIndex;
	}
	else
	{
		// TODO prepare for manual merge
		// TODO write conflicts to file maybe.
	}
}

bool MergeV2::isNodeInConflict(Model::NodeIdType nodeId) const
{
	//TODO : add soft conflicts
	return !mergeData_.cg_.changesForNode(nodeId).isEmpty();
}

}
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

//Testing
#include "mitkTestingMacros.h"
#include "mitkTestFixture.h"

//Std includes
#include <iomanip>

//MITK includes
#include "mitkVirtualTrackingDevice.h"
#include "mitkVirtualTrackingDevice.h"
#include "mitkTrackingTool.h"

//ITK includes
#include "itksys/SystemTools.hxx"

class mitkVirtualTrackingDeviceTestSuite : public mitk::TestFixture
{
  CPPUNIT_TEST_SUITE(mitkVirtualTrackingDeviceTestSuite);

  MITK_TEST(NewVirtualTrackingDevice_IsCreated);
  MITK_TEST(StartTracking_NotReady_False);
  MITK_TEST(StopTracking);
  MITK_TEST(StartTracking_Ready_True);
  MITK_TEST(StartTrackingAfterConnectionClosed_False);
  MITK_TEST(GetToolCount_NoToolAdded);
  MITK_TEST(GetToolCount_SeveralToolsAdded);
  MITK_TEST(GetTool);
  MITK_TEST(SettingAndGettingCorrectBounds);

  CPPUNIT_TEST_SUITE_END();

private:

  mitk::VirtualTrackingDevice::Pointer m_TestTracker;

public:

  void setUp()
  {
   m_TestTracker = mitk::VirtualTrackingDevice::New();
  }

  void tearDown()
  {

  }

  void NewVirtualTrackingDevice_IsCreated()
  {
    CPPUNIT_ASSERT_EQUAL(mitk::TrackingDevice::Setup, m_TestTracker->GetState());
  }

  void StartTracking_NotReady_False()
  {
    CPPUNIT_ASSERT_EQUAL(false, m_TestTracker->StartTracking());
  }

  void StopTracking()
  {
    CPPUNIT_ASSERT(m_TestTracker->StopTracking());
  }

  void StartTracking_Ready_True()
  {
    m_TestTracker->OpenConnection();
    CPPUNIT_ASSERT(m_TestTracker->StartTracking());
  }

  void StartTrackingAfterConnectionClosed_False()
  {
    m_TestTracker->OpenConnection();
    m_TestTracker->CloseConnection();
    CPPUNIT_ASSERT_EQUAL(false, m_TestTracker->StartTracking());
  }

  void GetToolCount_NoToolAdded()
  {
    unsigned int zero = 0;
    CPPUNIT_ASSERT_EQUAL(zero, m_TestTracker->GetToolCount());
  }

  void GetToolCount_SeveralToolsAdded()
  {
    unsigned int one = 1;
    unsigned int two = 2;
    unsigned int three = 3;
    m_TestTracker->AddTool("Tool1");
    CPPUNIT_ASSERT_EQUAL(one, m_TestTracker->GetToolCount());
    m_TestTracker->AddTool("Tool2");
    CPPUNIT_ASSERT_EQUAL(two, m_TestTracker->GetToolCount());
    m_TestTracker->AddTool("Tool3");
    CPPUNIT_ASSERT_EQUAL(three, m_TestTracker->GetToolCount());
  }

  void GetTool()
  {
    m_TestTracker->AddTool("Tool1");
    mitk::TrackingTool::Pointer tool = m_TestTracker->GetTool(0);
    CPPUNIT_ASSERT_EQUAL(m_TestTracker->GetToolByName("Tool1"), tool.GetPointer());
  }

  void SettingAndGettingCorrectBounds()
  {
    mitk::ScalarType bounds[6] = { 0.0, 10.0, 1.0, 20.0, 3.0, 30.0 };
    m_TestTracker->SetBounds(bounds);
    CPPUNIT_ASSERT_EQUAL(bounds[0], m_TestTracker->GetBounds()[0]);
    CPPUNIT_ASSERT_EQUAL(bounds[1], m_TestTracker->GetBounds()[1]);
    CPPUNIT_ASSERT_EQUAL(bounds[2], m_TestTracker->GetBounds()[2]);
    CPPUNIT_ASSERT_EQUAL(bounds[3], m_TestTracker->GetBounds()[3]);
    CPPUNIT_ASSERT_EQUAL(bounds[4], m_TestTracker->GetBounds()[4]);
    CPPUNIT_ASSERT_EQUAL(bounds[5], m_TestTracker->GetBounds()[5]);
  }

};

MITK_TEST_SUITE_REGISTRATION(mitkVirtualTrackingDevice)
<commit_msg>Finished Test for Virtual Tracking Device<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

//Testing
#include "mitkTestingMacros.h"
#include "mitkTestFixture.h"

//Std includes
#include <iomanip>

//MITK includes
#include "mitkVirtualTrackingDevice.h"
#include "mitkVirtualTrackingDevice.h"
#include "mitkTrackingTool.h"

//ITK includes
#include "itksys/SystemTools.hxx"

class mitkVirtualTrackingDeviceTestSuite : public mitk::TestFixture
{
  CPPUNIT_TEST_SUITE(mitkVirtualTrackingDeviceTestSuite);

  MITK_TEST(NewVirtualTrackingDevice_IsCreated);
  MITK_TEST(StartTracking_NotReady_False);
  MITK_TEST(StopTracking);
  MITK_TEST(StartTracking_Ready_True);
  MITK_TEST(StartTrackingAfterConnectionClosed_False);
  MITK_TEST(GetToolCount_NoToolAdded);
  MITK_TEST(GetToolCount_SeveralToolsAdded);
  MITK_TEST(GetTool);
  MITK_TEST(SettingAndGettingCorrectBounds);
  MITK_TEST(SetToolSpeed_InvalidSpeed_Error);
  MITK_TEST(SetToolSpeed_InvalidToolNumber_Error);
  MITK_TEST(GetSplineCordLength_ValidToolIndex);
  MITK_TEST(GetSplineCordLength_InvaldiToolIndex_Error);
  MITK_TEST(StartTracking_NewPositionsProduced);
  MITK_TEST(SetParamsForGaussianNoise_GetCorrrectParams);

  CPPUNIT_TEST_SUITE_END();

private:

  mitk::VirtualTrackingDevice::Pointer m_TestTracker;

public:

  void setUp()
  {
    m_TestTracker = mitk::VirtualTrackingDevice::New();
  }

  void tearDown()
  {
    m_TestTracker->CloseConnection();
  }

  void NewVirtualTrackingDevice_IsCreated()
  {
    CPPUNIT_ASSERT_EQUAL(mitk::TrackingDevice::Setup, m_TestTracker->GetState());
  }

  void StartTracking_NotReady_False()
  {
    CPPUNIT_ASSERT_EQUAL(false, m_TestTracker->StartTracking());
  }

  void StopTracking()
  {
    CPPUNIT_ASSERT(m_TestTracker->StopTracking());
  }

  void StartTracking_Ready_True()
  {
    m_TestTracker->OpenConnection();
    CPPUNIT_ASSERT(m_TestTracker->StartTracking());
  }

  void StartTrackingAfterConnectionClosed_False()
  {
    m_TestTracker->OpenConnection();
    m_TestTracker->CloseConnection();
    CPPUNIT_ASSERT_EQUAL(false, m_TestTracker->StartTracking());
  }

  void GetToolCount_NoToolAdded()
  {
    unsigned int zero = 0;
    CPPUNIT_ASSERT_EQUAL(zero, m_TestTracker->GetToolCount());
  }

  void GetToolCount_SeveralToolsAdded()
  {
    unsigned int one = 1;
    unsigned int two = 2;
    unsigned int three = 3;
    m_TestTracker->AddTool("Tool1");
    CPPUNIT_ASSERT_EQUAL(one, m_TestTracker->GetToolCount());
    m_TestTracker->AddTool("Tool2");
    CPPUNIT_ASSERT_EQUAL(two, m_TestTracker->GetToolCount());
    m_TestTracker->AddTool("Tool3");
    CPPUNIT_ASSERT_EQUAL(three, m_TestTracker->GetToolCount());
  }

  void GetTool()
  {
    m_TestTracker->AddTool("Tool1");
    mitk::TrackingTool::Pointer tool = m_TestTracker->GetTool(0);
    CPPUNIT_ASSERT_EQUAL(m_TestTracker->GetToolByName("Tool1"), tool.GetPointer());
  }

  void SettingAndGettingCorrectBounds()
  {
    mitk::ScalarType bounds[6] = { 0.0, 10.0, 1.0, 20.0, 3.0, 30.0 };
    m_TestTracker->SetBounds(bounds);
    CPPUNIT_ASSERT_EQUAL(bounds[0], m_TestTracker->GetBounds()[0]);
    CPPUNIT_ASSERT_EQUAL(bounds[1], m_TestTracker->GetBounds()[1]);
    CPPUNIT_ASSERT_EQUAL(bounds[2], m_TestTracker->GetBounds()[2]);
    CPPUNIT_ASSERT_EQUAL(bounds[3], m_TestTracker->GetBounds()[3]);
    CPPUNIT_ASSERT_EQUAL(bounds[4], m_TestTracker->GetBounds()[4]);
    CPPUNIT_ASSERT_EQUAL(bounds[5], m_TestTracker->GetBounds()[5]);
  }

  void SetToolSpeed_InvalidSpeed_Error()
  {
    m_TestTracker->AddTool("Tool1");
    CPPUNIT_ASSERT_THROW(m_TestTracker->SetToolSpeed(0, -1), std::invalid_argument);
  }

  void SetToolSpeed_InvalidToolNumber_Error()
  {
    m_TestTracker->AddTool("Tool1");
    CPPUNIT_ASSERT_THROW(m_TestTracker->SetToolSpeed(1, 0.1), std::invalid_argument);
  }

  void GetSplineCordLength_ValidToolIndex()
  {
    m_TestTracker->AddTool("Tool1");
    mitk::ScalarType lengthBefore = m_TestTracker->GetSplineChordLength(0);
    m_TestTracker->OpenConnection();
    m_TestTracker->StartTracking();
    m_TestTracker->StopTracking();
    CPPUNIT_ASSERT_EQUAL(lengthBefore, m_TestTracker->GetSplineChordLength(0));
  }

  void GetSplineCordLength_InvaldiToolIndex_Error()
  {
    CPPUNIT_ASSERT_THROW(m_TestTracker->GetSplineChordLength(0), std::invalid_argument);
  }

  void StartTracking_NewPositionsProduced()
  {
    m_TestTracker->AddTool("Tool1");
    mitk::Point3D posBefore;
    mitk::Point3D posAfter;
    mitk::TrackingTool::Pointer tool = m_TestTracker->GetToolByName("Tool1");
    tool->GetPosition(posBefore);
    tool->GetPosition(posAfter);
    CPPUNIT_ASSERT_EQUAL(posBefore, posAfter);
    m_TestTracker->OpenConnection();
    m_TestTracker->StartTracking();
    itksys::SystemTools::Delay(500);  //wait for tracking thread to start generating positions
    tool->GetPosition(posAfter);
    CPPUNIT_ASSERT(posBefore != posAfter);
  }

  void SetParamsForGaussianNoise_GetCorrrectParams()
  {
    double meanDistribution = 2.5;
    double deviationDistribution = 1.2;
    m_TestTracker->SetParamsForGaussianNoise(meanDistribution, deviationDistribution);
    CPPUNIT_ASSERT_EQUAL(meanDistribution, m_TestTracker->GetMeanDistribution());
    CPPUNIT_ASSERT_EQUAL(deviationDistribution, m_TestTracker->GetDeviationDistribution());
  }

};

MITK_TEST_SUITE_REGISTRATION(mitkVirtualTrackingDevice)
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/net/chrome_net_log.h"

#include <algorithm>

#include "base/command_line.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/net/load_timing_observer.h"
#include "chrome/browser/net/net_log_logger.h"
#include "chrome/browser/net/passive_log_collector.h"
#include "chrome/common/chrome_switches.h"

ChromeNetLog::ThreadSafeObserver::ThreadSafeObserver(LogLevel log_level)
    : net_log_(NULL),
      log_level_(log_level) {
}

ChromeNetLog::ThreadSafeObserver::~ThreadSafeObserver() {
  DCHECK(!net_log_);
}

net::NetLog::LogLevel ChromeNetLog::ThreadSafeObserver::log_level() const {
  return log_level_;
}

void ChromeNetLog::ThreadSafeObserver::AssertNetLogLockAcquired() const {
  if (net_log_)
    net_log_->lock_.AssertAcquired();
}

void ChromeNetLog::ThreadSafeObserver::SetLogLevel(
    net::NetLog::LogLevel log_level) {
  DCHECK(net_log_);
  base::AutoLock lock(net_log_->lock_);
  log_level_ = log_level;
  net_log_->UpdateLogLevel_();
}

ChromeNetLog::Entry::Entry(uint32 order,
                           net::NetLog::EventType type,
                           const base::TimeTicks& time,
                           net::NetLog::Source source,
                           net::NetLog::EventPhase phase,
                           net::NetLog::EventParameters* params)
    : order(order),
      type(type),
      time(time),
      source(source),
      phase(phase),
      params(params) {
}

ChromeNetLog::Entry::~Entry() {}

ChromeNetLog::ChromeNetLog()
    : last_id_(0),
      log_level_(LOG_BASIC),
      passive_collector_(new PassiveLogCollector),
      load_timing_observer_(new LoadTimingObserver) {
  AddObserver(passive_collector_.get());
  AddObserver(load_timing_observer_.get());

  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  if (command_line.HasSwitch(switches::kLogNetLog)) {
    net_log_logger_.reset(new NetLogLogger());
    AddObserver(net_log_logger_.get());
  }
}

ChromeNetLog::~ChromeNetLog() {
  RemoveObserver(passive_collector_.get());
  RemoveObserver(load_timing_observer_.get());
  if (net_log_logger_.get()) {
    RemoveObserver(net_log_logger_.get());
  }
}

void ChromeNetLog::AddEntry(EventType type,
                            const base::TimeTicks& time,
                            const Source& source,
                            EventPhase phase,
                            EventParameters* params) {
  base::AutoLock lock(lock_);

  // Notify all of the log observers.
  FOR_EACH_OBSERVER(ThreadSafeObserver, observers_,
                    OnAddEntry(type, time, source, phase, params));
}

uint32 ChromeNetLog::NextID() {
  return base::subtle::NoBarrier_AtomicIncrement(&last_id_, 1);
}

net::NetLog::LogLevel ChromeNetLog::GetLogLevel() const {
  base::subtle::Atomic32 log_level = base::subtle::NoBarrier_Load(&log_level_);
  return static_cast<net::NetLog::LogLevel>(log_level);
}

void ChromeNetLog::AddObserver(ThreadSafeObserver* observer) {
  base::AutoLock lock(lock_);
  AddObserverWhileLockHeld(observer);
}

void ChromeNetLog::RemoveObserver(ThreadSafeObserver* observer) {
  base::AutoLock lock(lock_);
  DCHECK_EQ(observer->net_log_, this);
  observer->net_log_ = NULL;
  observers_.RemoveObserver(observer);
  UpdateLogLevel_();
}

void ChromeNetLog::AddObserverAndGetAllPassivelyCapturedEvents(
    ThreadSafeObserver* observer, EntryList* passive_entries) {
  base::AutoLock lock(lock_);
  AddObserverWhileLockHeld(observer);
  passive_collector_->GetAllCapturedEvents(passive_entries);
}

void ChromeNetLog::GetAllPassivelyCapturedEvents(EntryList* passive_entries) {
  base::AutoLock lock(lock_);
  passive_collector_->GetAllCapturedEvents(passive_entries);
}

void ChromeNetLog::ClearAllPassivelyCapturedEvents() {
  base::AutoLock lock(lock_);
  passive_collector_->Clear();
}

void ChromeNetLog::UpdateLogLevel_() {
  lock_.AssertAcquired();

  // Look through all the observers and find the finest granularity
  // log level (higher values of the enum imply *lower* log levels).
  LogLevel new_log_level = LOG_BASIC;
  ObserverListBase<ThreadSafeObserver>::Iterator it(observers_);
  ThreadSafeObserver* observer;
  while ((observer = it.GetNext()) != NULL) {
    new_log_level = std::min(new_log_level, observer->log_level());
  }
  base::subtle::NoBarrier_Store(&log_level_, new_log_level);
}

void ChromeNetLog::AddObserverWhileLockHeld(ThreadSafeObserver* observer) {
  DCHECK(!observer->net_log_);
  observer->net_log_ = this;
  observers_.AddObserver(observer);
  UpdateLogLevel_();
}
<commit_msg>Perf test of disabling ChromeNetLog.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/net/chrome_net_log.h"

#include <algorithm>

#include "base/command_line.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/net/load_timing_observer.h"
#include "chrome/browser/net/net_log_logger.h"
#include "chrome/browser/net/passive_log_collector.h"
#include "chrome/common/chrome_switches.h"

ChromeNetLog::ThreadSafeObserver::ThreadSafeObserver(LogLevel log_level)
    : net_log_(NULL),
      log_level_(log_level) {
}

ChromeNetLog::ThreadSafeObserver::~ThreadSafeObserver() {
  DCHECK(!net_log_);
}

net::NetLog::LogLevel ChromeNetLog::ThreadSafeObserver::log_level() const {
  return log_level_;
}

void ChromeNetLog::ThreadSafeObserver::AssertNetLogLockAcquired() const {
  if (net_log_)
    net_log_->lock_.AssertAcquired();
}

void ChromeNetLog::ThreadSafeObserver::SetLogLevel(
    net::NetLog::LogLevel log_level) {
  DCHECK(net_log_);
  base::AutoLock lock(net_log_->lock_);
  log_level_ = log_level;
  net_log_->UpdateLogLevel_();
}

ChromeNetLog::Entry::Entry(uint32 order,
                           net::NetLog::EventType type,
                           const base::TimeTicks& time,
                           net::NetLog::Source source,
                           net::NetLog::EventPhase phase,
                           net::NetLog::EventParameters* params)
    : order(order),
      type(type),
      time(time),
      source(source),
      phase(phase),
      params(params) {
}

ChromeNetLog::Entry::~Entry() {}

ChromeNetLog::ChromeNetLog()
    : last_id_(0),
      log_level_(LOG_BASIC),
      passive_collector_(new PassiveLogCollector),
      load_timing_observer_(new LoadTimingObserver) {
  AddObserver(passive_collector_.get());
  AddObserver(load_timing_observer_.get());

  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  if (command_line.HasSwitch(switches::kLogNetLog)) {
    net_log_logger_.reset(new NetLogLogger());
    AddObserver(net_log_logger_.get());
  }
}

ChromeNetLog::~ChromeNetLog() {
  RemoveObserver(passive_collector_.get());
  RemoveObserver(load_timing_observer_.get());
  if (net_log_logger_.get()) {
    RemoveObserver(net_log_logger_.get());
  }
}

void ChromeNetLog::AddEntry(EventType type,
                            const base::TimeTicks& time,
                            const Source& source,
                            EventPhase phase,
                            EventParameters* params) {
  base::AutoLock lock(lock_);

  // Notify all of the log observers.
#if 0
  FOR_EACH_OBSERVER(ThreadSafeObserver, observers_,
                    OnAddEntry(type, time, source, phase, params));
#endif
}

uint32 ChromeNetLog::NextID() {
  return base::subtle::NoBarrier_AtomicIncrement(&last_id_, 1);
}

net::NetLog::LogLevel ChromeNetLog::GetLogLevel() const {
  base::subtle::Atomic32 log_level = base::subtle::NoBarrier_Load(&log_level_);
  return static_cast<net::NetLog::LogLevel>(log_level);
}

void ChromeNetLog::AddObserver(ThreadSafeObserver* observer) {
  base::AutoLock lock(lock_);
  AddObserverWhileLockHeld(observer);
}

void ChromeNetLog::RemoveObserver(ThreadSafeObserver* observer) {
  base::AutoLock lock(lock_);
  DCHECK_EQ(observer->net_log_, this);
  observer->net_log_ = NULL;
  observers_.RemoveObserver(observer);
  UpdateLogLevel_();
}

void ChromeNetLog::AddObserverAndGetAllPassivelyCapturedEvents(
    ThreadSafeObserver* observer, EntryList* passive_entries) {
  base::AutoLock lock(lock_);
  AddObserverWhileLockHeld(observer);
  passive_collector_->GetAllCapturedEvents(passive_entries);
}

void ChromeNetLog::GetAllPassivelyCapturedEvents(EntryList* passive_entries) {
  base::AutoLock lock(lock_);
  passive_collector_->GetAllCapturedEvents(passive_entries);
}

void ChromeNetLog::ClearAllPassivelyCapturedEvents() {
  base::AutoLock lock(lock_);
  passive_collector_->Clear();
}

void ChromeNetLog::UpdateLogLevel_() {
  lock_.AssertAcquired();

  // Look through all the observers and find the finest granularity
  // log level (higher values of the enum imply *lower* log levels).
  LogLevel new_log_level = LOG_BASIC;
  ObserverListBase<ThreadSafeObserver>::Iterator it(observers_);
  ThreadSafeObserver* observer;
  while ((observer = it.GetNext()) != NULL) {
    new_log_level = std::min(new_log_level, observer->log_level());
  }
  base::subtle::NoBarrier_Store(&log_level_, new_log_level);
}

void ChromeNetLog::AddObserverWhileLockHeld(ThreadSafeObserver* observer) {
  DCHECK(!observer->net_log_);
  observer->net_log_ = this;
  observers_.AddObserver(observer);
  UpdateLogLevel_();
}
<|endoftext|>


<commit_before>// $Id$

#if !defined(__CINT__) || defined(__MAKECINT__)
#include <Riostream.h>
#include <TH1D.h>
#include <TFile.h>
#include <TTree.h>
#include <TNtuple.h>
#include <TMath.h>
#include <TParticle.h>
#include <TPDGCode.h>
#include <TDatabasePDG.h>
#include <TRandom3.h>
#include <TChain.h>
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliHeader.h"
#include "AliStack.h"
#include "AliPDG.h"
#include "THijing/AliGenHijing.h"
#endif

class MyHeader
{
public:
  MyHeader() : fNATT(0), fEATT(0),fJATT(0),fNT(0),fNP(0),
               fN00(0),fN01(0),fN10(0),fN11(0),fBB(0),fRP(0),
               fPSn(0), fPSp(0), fTSn(0), fTSp(0) {;}
  virtual ~MyHeader() {;}
  Int_t       fNATT;
  Double32_t  fEATT;
  Int_t       fJATT;
  Int_t       fNT;
  Int_t       fNP;
  Int_t       fN00;
  Int_t       fN01;
  Int_t       fN10;
  Int_t       fN11;
  Double32_t  fBB;
  Double32_t  fRP;
  Int_t       fPSn;
  Int_t       fPSp;
  Int_t       fTSn;
  Int_t       fTSp;
  ClassDef(MyHeader,1) // My header class
};

class MyResponse
{
public:
  MyResponse() : fEtch0p(0), fEtch1p(0), fEtch2p(0), fEtch3p(0), fEtch4p(0), fEtch5p(0), fEtchrp(0),
                 fEtch0n(0), fEtch1n(0), fEtch2n(0), fEtch3n(0), fEtch4n(0), fEtch5n(0), fEtchrn(0),
                 fNch0p(0), fNch1p(0), fNch2p(0), fNch3p(0), fNch4p(0), fNch5p(0), fNchrp(0),
                 fNch0n(0), fNch1n(0), fNch2n(0), fNch3n(0), fNch4n(0), fNch5n(0), fNchrn(0) {;}
  virtual ~MyResponse() {;}
  Double32_t  fEtch0p;
  Double32_t  fEtch1p;
  Double32_t  fEtch2p;
  Double32_t  fEtch3p;
  Double32_t  fEtch4p;
  Double32_t  fEtch5p;
  Double32_t  fEtchrp;
  Double32_t  fEtch0n;
  Double32_t  fEtch1n;
  Double32_t  fEtch2n;
  Double32_t  fEtch3n;
  Double32_t  fEtch4n;
  Double32_t  fEtch5n;
  Double32_t  fEtchrn;
  Int_t       fNch0p;
  Int_t       fNch1p;
  Int_t       fNch2p;
  Int_t       fNch3p;
  Int_t       fNch4p;
  Int_t       fNch5p;
  Int_t       fNchrp;
  Int_t       fNch0n;
  Int_t       fNch1n;
  Int_t       fNch2n;
  Int_t       fNch3n;
  Int_t       fNch4n;
  Int_t       fNch5n;
  Int_t       fNchrn;
  ClassDef(MyResponse,1) // My reponse class
};

void createGlauberTree(Int_t nEvents,
                       const char *outFileName = "treeout.root");

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

void createGlauberTree(Int_t nEvents,
                       const char *outFileName)
{
  AliPDG::AddParticlesToPdgDataBase();
  TDatabasePDG::Instance();

  // Run loader
  TFolder *folder = new TFolder("myfolder","myfolder");
  AliRunLoader* rl = new AliRunLoader(folder);
  rl->MakeHeader();
  rl->MakeStack();
  AliStack* stack = rl->Stack();
  //AliHeader* rheader = rl->GetHeader();

  AliGenHijing *genHi = new AliGenHijing(-1);
  genHi->SetStack(stack);
  genHi->SetEnergyCMS(2760);
  genHi->SetReferenceFrame("CMS");
  genHi->SetProjectile("A", 208, 82);
  genHi->SetTarget    ("A", 208, 82);
  genHi->SetPtHardMin (2.3);
  genHi->SetImpactParameterRange(0.,30);
  genHi->SetJetQuenching(0); // enable jet quenching
  genHi->SetShadowing(1);    // enable shadowing
  genHi->SetDecaysOff(1);    // neutral pion and heavy particle decays switched off
  genHi->Init();

  MyHeader  *myheader = new MyHeader;
  MyResponse *myresp  = new MyResponse;

  TFile *outFile = TFile::Open(outFileName, "RECREATE");
  outFile->SetCompressionLevel(5);
  TDirectory::TContext context(outFile);

  TTree *tree = new TTree("glaubertree", "Glauber tree");
  tree->Branch("header",&myheader, 32*1024, 99);
  tree->Branch("response",&myresp, 32*1024, 99);

  TNtuple *ntuple = new TNtuple("gnt", "Glauber ntuple", "npart:ncoll:b");

  Double_t etas[] = {-10,-5,-4,-3,-2,-1,0,1,2,3,4,5,10};
  TH1D *hNEta = new TH1D("hNeta","",12,etas);
  TH1D *hEtEta = new TH1D("hEteta","",12,etas);

  // create events and fill them
  for (Int_t iEvent = 0; iEvent < nEvents; ++iEvent) {

    cout << "Event " << iEvent+1 << "/" << nEvents << endl;;
    stack->Reset();
    hNEta->Reset();
    hEtEta->Reset();
    genHi->Generate();

    AliStack *s = genHi->GetStack();
    const TObjArray *parts = s->Particles();
    Int_t nents = parts->GetEntries();
    for (Int_t i = 0; i<nents; ++i) {
      TParticle *p = (TParticle*)parts->At(i);
      //p->Print();
      TParticlePDG *pdg = p->GetPDG(1);
      Int_t c = (Int_t)(TMath::Abs(pdg->Charge()));
      if (c!=0) {
        hNEta->Fill(p->Eta());
        hEtEta->Fill(p->Eta(),p->Pt());
      }
    }

    AliGenHijingEventHeader *h = (AliGenHijingEventHeader*)genHi->CollisionGeometry();
    myheader->fNATT = nents;
    myheader->fEATT = h->TotalEnergy();
    myheader->fJATT = h->HardScatters();
    myheader->fNT   = h->TargetParticipants();
    myheader->fNP   = h->ProjectileParticipants();
    myheader->fN00  = h->NwNw();
    myheader->fN01  = h->NwN();
    myheader->fN10  = h->NNw();
    myheader->fN11  = h->NN();
    myheader->fBB   = h->ImpactParameter();
    myheader->fRP   = h->ReactionPlaneAngle();
    myheader->fPSn  = h->ProjSpectatorsn();
    myheader->fPSp  = h->ProjSpectatorsp();
    myheader->fTSn  = h->TargSpectatorsn();
    myheader->fTSp  = h->TargSpectatorsn();

    myresp->fEtch0p = hEtEta->GetBinContent(hEtEta->FindBin(0.5));
    myresp->fEtch1p = hEtEta->GetBinContent(hEtEta->FindBin(1.5));
    myresp->fEtch2p = hEtEta->GetBinContent(hEtEta->FindBin(2.5));
    myresp->fEtch3p = hEtEta->GetBinContent(hEtEta->FindBin(3.5));
    myresp->fEtch4p = hEtEta->GetBinContent(hEtEta->FindBin(4.5));
    myresp->fEtch5p = hEtEta->GetBinContent(hEtEta->FindBin(5.5));
    myresp->fEtchrp = hEtEta->GetBinContent(hEtEta->FindBin(10.5));
    myresp->fEtch0n = hEtEta->GetBinContent(hEtEta->FindBin(-0.5));
    myresp->fEtch1n = hEtEta->GetBinContent(hEtEta->FindBin(-1.5));
    myresp->fEtch2n = hEtEta->GetBinContent(hEtEta->FindBin(-2.5));
    myresp->fEtch3n = hEtEta->GetBinContent(hEtEta->FindBin(-3.5));
    myresp->fEtch4n = hEtEta->GetBinContent(hEtEta->FindBin(-4.5));
    myresp->fEtch5n = hEtEta->GetBinContent(hEtEta->FindBin(-5.5));
    myresp->fEtchrn = hEtEta->GetBinContent(hEtEta->FindBin(-10.5));
    myresp->fNch0p  = hNEta->GetBinContent(hNEta->FindBin(0.5));
    myresp->fNch1p  = hNEta->GetBinContent(hNEta->FindBin(1.5));
    myresp->fNch2p  = hNEta->GetBinContent(hNEta->FindBin(2.5));
    myresp->fNch3p  = hNEta->GetBinContent(hNEta->FindBin(3.5));
    myresp->fNch4p  = hNEta->GetBinContent(hNEta->FindBin(4.5));
    myresp->fNch5p  = hNEta->GetBinContent(hNEta->FindBin(5.5));
    myresp->fNchrp  = hNEta->GetBinContent(hNEta->FindBin(10.5));
    myresp->fNch0n  = hNEta->GetBinContent(hNEta->FindBin(-0.5));
    myresp->fNch1n  = hNEta->GetBinContent(hNEta->FindBin(-1.5));
    myresp->fNch2n  = hNEta->GetBinContent(hNEta->FindBin(-2.5));
    myresp->fNch3n  = hNEta->GetBinContent(hNEta->FindBin(-3.5));
    myresp->fNch4n  = hNEta->GetBinContent(hNEta->FindBin(-4.5));
    myresp->fNch5n  = hNEta->GetBinContent(hNEta->FindBin(-5.5));
    myresp->fNchrn  = hNEta->GetBinContent(hNEta->FindBin(-10.5));

    tree->Fill();

    if (ntuple) {
      Int_t np = h->TargetParticipants() + h->ProjectileParticipants();
      Int_t nc = h->NwNw() + h->NwN() + h->NNw() + h->NN();
      Double_t b = h->ImpactParameter();
      ntuple->Fill(np,nc,b);
    }

  } // end of event loop

  tree->Write();
  ntuple->Write();
  outFile->Close();
}
<commit_msg>commit before move<commit_after>// $Id$

#if !defined(__CINT__) || defined(__MAKECINT__)
#include <Riostream.h>
#include <TH1D.h>
#include <TFile.h>
#include <TTree.h>
#include <TNtuple.h>
#include <TMath.h>
#include <TParticle.h>
#include <TPDGCode.h>
#include <TDatabasePDG.h>
#include <TRandom3.h>
#include <TChain.h>
#include <TFolder.h>
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliHeader.h"
#include "AliStack.h"
#include "AliPDG.h"
#include "THijing/AliGenHijing.h"
#endif

class MyHeader
{
public:
  MyHeader() : fNATT(0), fEATT(0),fJATT(0),fNT(0),fNP(0),
               fN00(0),fN01(0),fN10(0),fN11(0),fBB(0),fRP(0),
               fPSn(0), fPSp(0), fTSn(0), fTSp(0) {;}
  virtual ~MyHeader() {;}
  Int_t       fNATT;
  Double32_t  fEATT;
  Int_t       fJATT;
  Int_t       fNT;
  Int_t       fNP;
  Int_t       fN00;
  Int_t       fN01;
  Int_t       fN10;
  Int_t       fN11;
  Double32_t  fBB;
  Double32_t  fRP;
  Int_t       fPSn;
  Int_t       fPSp;
  Int_t       fTSn;
  Int_t       fTSp;
  ClassDef(MyHeader,1) // My header class
};

class MyResponse
{
public:
  MyResponse() : fEtch0p(0), fEtch1p(0), fEtch2p(0), fEtch3p(0), fEtch4p(0), fEtch5p(0), fEtchrp(0),
                 fEtch0n(0), fEtch1n(0), fEtch2n(0), fEtch3n(0), fEtch4n(0), fEtch5n(0), fEtchrn(0),
                 fNch0p(0), fNch1p(0), fNch2p(0), fNch3p(0), fNch4p(0), fNch5p(0), fNchrp(0),
                 fNch0n(0), fNch1n(0), fNch2n(0), fNch3n(0), fNch4n(0), fNch5n(0), fNchrn(0) {;}
  virtual ~MyResponse() {;}
  Double32_t  fEtch0p;
  Double32_t  fEtch1p;
  Double32_t  fEtch2p;
  Double32_t  fEtch3p;
  Double32_t  fEtch4p;
  Double32_t  fEtch5p;
  Double32_t  fEtchrp;
  Double32_t  fEtch0n;
  Double32_t  fEtch1n;
  Double32_t  fEtch2n;
  Double32_t  fEtch3n;
  Double32_t  fEtch4n;
  Double32_t  fEtch5n;
  Double32_t  fEtchrn;
  Int_t       fNch0p;
  Int_t       fNch1p;
  Int_t       fNch2p;
  Int_t       fNch3p;
  Int_t       fNch4p;
  Int_t       fNch5p;
  Int_t       fNchrp;
  Int_t       fNch0n;
  Int_t       fNch1n;
  Int_t       fNch2n;
  Int_t       fNch3n;
  Int_t       fNch4n;
  Int_t       fNch5n;
  Int_t       fNchrn;
  ClassDef(MyResponse,1) // My reponse class
};

void createGlauberTree(Int_t nEvents,
                       const char *outFileName = "treeout.root");

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

void createGlauberTree(Int_t nEvents,
                       const char *outFileName)
{
  AliPDG::AddParticlesToPdgDataBase();
  TDatabasePDG::Instance();

  // Run loader
  TFolder *folder = new TFolder("myfolder","myfolder");
  AliRunLoader* rl = new AliRunLoader(folder);
  rl->MakeHeader();
  rl->MakeStack();
  AliStack* stack = rl->Stack();
  //AliHeader* rheader = rl->GetHeader();

  AliGenHijing *genHi = new AliGenHijing(-1);
  genHi->SetStack(stack);
  genHi->SetEnergyCMS(2760);
  genHi->SetReferenceFrame("CMS");
  genHi->SetProjectile("A", 208, 82);
  genHi->SetTarget    ("A", 208, 82);
  genHi->SetPtHardMin (2.3);
  genHi->SetImpactParameterRange(0.,30);
  genHi->SetJetQuenching(0); // enable jet quenching
  genHi->SetShadowing(1);    // enable shadowing
  genHi->SetDecaysOff(1);    // neutral pion and heavy particle decays switched off
  genHi->Init();

  MyHeader  *myheader = new MyHeader;
  MyResponse *myresp  = new MyResponse;

  TFile *outFile = TFile::Open(outFileName, "RECREATE");
  outFile->SetCompressionLevel(5);
  TDirectory::TContext context(outFile);

  TTree *tree = new TTree("glaubertree", "Glauber tree");
  tree->Branch("header",&myheader, 32*1024, 99);
  tree->Branch("response",&myresp, 32*1024, 99);

  TNtuple *ntuple = new TNtuple("gnt", "Glauber ntuple", "npart:ncoll:b");

  Double_t etas[] = {-10,-5,-4,-3,-2,-1,0,1,2,3,4,5,10};
  TH1D *hNEta = new TH1D("hNeta","",12,etas);
  TH1D *hEtEta = new TH1D("hEteta","",12,etas);

  // create events and fill them
  for (Int_t iEvent = 0; iEvent < nEvents; ++iEvent) {

    cout << "Event " << iEvent+1 << "/" << nEvents << endl;;
    stack->Reset();
    hNEta->Reset();
    hEtEta->Reset();
    genHi->Generate();

    AliStack *s = genHi->GetStack();
    const TObjArray *parts = s->Particles();
    Int_t nents = parts->GetEntries();
    for (Int_t i = 0; i<nents; ++i) {
      TParticle *p = (TParticle*)parts->At(i);
      //p->Print();
      TParticlePDG *pdg = p->GetPDG(1);
      Int_t c = (Int_t)(TMath::Abs(pdg->Charge()));
      if (c!=0) {
        hNEta->Fill(p->Eta());
        hEtEta->Fill(p->Eta(),p->Pt());
      }
    }

    AliGenHijingEventHeader *h = (AliGenHijingEventHeader*)genHi->CollisionGeometry();
    myheader->fNATT = nents;
    myheader->fEATT = h->TotalEnergy();
    myheader->fJATT = h->HardScatters();
    myheader->fNT   = h->TargetParticipants();
    myheader->fNP   = h->ProjectileParticipants();
    myheader->fN00  = h->NwNw();
    myheader->fN01  = h->NwN();
    myheader->fN10  = h->NNw();
    myheader->fN11  = h->NN();
    myheader->fBB   = h->ImpactParameter();
    myheader->fRP   = h->ReactionPlaneAngle();
    myheader->fPSn  = h->ProjSpectatorsn();
    myheader->fPSp  = h->ProjSpectatorsp();
    myheader->fTSn  = h->TargSpectatorsn();
    myheader->fTSp  = h->TargSpectatorsn();

    myresp->fEtch0p = hEtEta->GetBinContent(hEtEta->FindBin(0.5));
    myresp->fEtch1p = hEtEta->GetBinContent(hEtEta->FindBin(1.5));
    myresp->fEtch2p = hEtEta->GetBinContent(hEtEta->FindBin(2.5));
    myresp->fEtch3p = hEtEta->GetBinContent(hEtEta->FindBin(3.5));
    myresp->fEtch4p = hEtEta->GetBinContent(hEtEta->FindBin(4.5));
    myresp->fEtch5p = hEtEta->GetBinContent(hEtEta->FindBin(5.5));
    myresp->fEtchrp = hEtEta->GetBinContent(hEtEta->FindBin(10.5));
    myresp->fEtch0n = hEtEta->GetBinContent(hEtEta->FindBin(-0.5));
    myresp->fEtch1n = hEtEta->GetBinContent(hEtEta->FindBin(-1.5));
    myresp->fEtch2n = hEtEta->GetBinContent(hEtEta->FindBin(-2.5));
    myresp->fEtch3n = hEtEta->GetBinContent(hEtEta->FindBin(-3.5));
    myresp->fEtch4n = hEtEta->GetBinContent(hEtEta->FindBin(-4.5));
    myresp->fEtch5n = hEtEta->GetBinContent(hEtEta->FindBin(-5.5));
    myresp->fEtchrn = hEtEta->GetBinContent(hEtEta->FindBin(-10.5));
    myresp->fNch0p  = hNEta->GetBinContent(hNEta->FindBin(0.5));
    myresp->fNch1p  = hNEta->GetBinContent(hNEta->FindBin(1.5));
    myresp->fNch2p  = hNEta->GetBinContent(hNEta->FindBin(2.5));
    myresp->fNch3p  = hNEta->GetBinContent(hNEta->FindBin(3.5));
    myresp->fNch4p  = hNEta->GetBinContent(hNEta->FindBin(4.5));
    myresp->fNch5p  = hNEta->GetBinContent(hNEta->FindBin(5.5));
    myresp->fNchrp  = hNEta->GetBinContent(hNEta->FindBin(10.5));
    myresp->fNch0n  = hNEta->GetBinContent(hNEta->FindBin(-0.5));
    myresp->fNch1n  = hNEta->GetBinContent(hNEta->FindBin(-1.5));
    myresp->fNch2n  = hNEta->GetBinContent(hNEta->FindBin(-2.5));
    myresp->fNch3n  = hNEta->GetBinContent(hNEta->FindBin(-3.5));
    myresp->fNch4n  = hNEta->GetBinContent(hNEta->FindBin(-4.5));
    myresp->fNch5n  = hNEta->GetBinContent(hNEta->FindBin(-5.5));
    myresp->fNchrn  = hNEta->GetBinContent(hNEta->FindBin(-10.5));

    tree->Fill();

    if (ntuple) {
      Int_t np = h->TargetParticipants() + h->ProjectileParticipants();
      Int_t nc = h->NwNw() + h->NwN() + h->NNw() + h->NN();
      Double_t b = h->ImpactParameter();
      ntuple->Fill(np,nc,b);
    }

  } // end of event loop

  tree->Write();
  ntuple->Write();
  outFile->Close();
}
<|endoftext|>


<commit_before><commit_msg>Fix info messages<commit_after><|endoftext|>


<commit_before>#include <sys/time.h>

#include "marshal.h"

using namespace std;

namespace rpc {

#ifdef PERF_TEST
int _perf_rpc_in_packet_size[PERF_SAMPLE_SIZE];
int _perf_rpc_out_packet_size[PERF_SAMPLE_SIZE];
#endif // PERF_TEST

/**
 * 8kb minimum chunk size.
 * NOTE: this value directly affects how many read/write syscall will be issued.
 */
const int Chunk::min_size = 8192;

Marshal::~Marshal() {
    for (list<Chunk*>::iterator it = chunk_.begin(); it != chunk_.end(); ++it) {
        delete *it;
    }
}

Marshal::Bookmark* Marshal::set_bookmark(int size) {
    verify(write_counter_ == 0);

    // invariant: head of chunk list is not fully read (otherwise it's a waste of memory)
    assert(chunk_.empty() || !chunk_.front()->fully_read());

    Bookmark* bmark = new Bookmark();
    bmark->size_ = size;
    bmark->ptr_ = new char*[bmark->size_];

    for (int i = 0; i < bmark->size_; i++) {
        if (chunk_.empty() || chunk_.back()->fully_written()) {
            chunk_.push_back(new Chunk);
        }
        bmark->ptr_[i] = chunk_.back()->set_bookmark();
    }

    return bmark;
}

void Marshal::write_bookmark(Bookmark* bmark, const void* ptr) {
    char* pc = (char *) ptr;
    verify(bmark != NULL && bmark->ptr_ != NULL && bmark->size_ >= 0);
    for (int i = 0; i < bmark->size_; i++) {
        *(bmark->ptr_[i]) = pc[i];
    }
}

int Marshal::write(const void* p, int n) {
    assert(chunk_.empty() || !chunk_.front()->fully_read());

    if (chunk_.empty() || chunk_.back()->fully_written()) {
        chunk_.push_back(new Chunk(p, n));
    } else {
        int n_write = chunk_.back()->write(p, n);

        // otherwise the above fully_written() will return true
        assert(n_write > 0);

        if (n_write < n) {
            const char* pc = (const char *) p;
            chunk_.push_back(new Chunk(pc + n_write, n - n_write));
        }
    }

    write_counter_ += n;
    return n;
}

int Marshal::read(void* p, int n) {
    assert(chunk_.empty() || !chunk_.front()->fully_read());

    char* pc = (char *) p;
    int n_read = 0;
    while (!chunk_.empty() && n_read < n) {
        int r = chunk_.front()->read(pc + n_read, n - n_read);
        if (chunk_.front()->fully_read()) {
            // remove fully read chunks, avoid unnecessary mem usage
            delete chunk_.front();
            chunk_.pop_front();
        }
        if (r == 0) {
            // currently there's no content for us to read, so stop.
            break;
        }
        n_read += r;
    }

    verify(n_read <= n);
    assert(chunk_.empty() || !chunk_.front()->fully_read());

    return n_read;
}

int Marshal::peek(void* p, int n) const {
    assert(chunk_.empty() || !chunk_.front()->fully_read());

    char* pc = (char *) p;
    int n_peek = 0;

    for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) {
        int r = (*it)->peek(pc + n_peek, n - n_peek);
        if (r == 0) {
            // no more data to peek, so stop
            break;
        }
        n_peek += r;
        if (n_peek == n) {
            // read enough data, so stop
            break;
        }
    }

    assert(n_peek <= n);
    assert(chunk_.empty() || !chunk_.front()->fully_read());

    return n_peek;
}

int Marshal::write_to_fd(int fd) {
    assert(chunk_.empty() || !chunk_.front()->fully_read());

    struct timeval tm;
    gettimeofday(&tm, NULL);
    double now = tm.tv_sec + tm.tv_usec / 1000.0 / 1000.0;
    if (!content_size_gt(512) && now - last_write_fd_tm_ < 0.05) {
        // wait till next batch
        return 0;
    }
    last_write_fd_tm_ = now;

    int n_write = 0;
    while (!chunk_.empty()) {
        int r = chunk_.front()->write_to_fd(fd);
        if (chunk_.front()->fully_read()) {
            // remove useless chunks when they are fully read
            delete chunk_.front();
            chunk_.pop_front();
        }
        if (r <= 0) {
            break;
        }
        n_write += r;
    }

    assert(chunk_.empty() || !chunk_.front()->fully_read());

    return n_write;
}

string Marshal::dump() const {
    string s;
    s.reserve(this->content_size());
    for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) {
        s += string((*it)->content_ptr(), (*it)->content_size());
    }
    assert(s.length() == this->content_size());
    return s;
}

int Marshal::read_from_marshal(Marshal& m, int n /* =? */) {
    assert(chunk_.empty() || !chunk_.front()->fully_read());
    assert(m.chunk_.empty() || !m.chunk_.front()->fully_read());

    int n_read = 0;
    while (n_read < n) {
        if (m.chunk_.empty()) {
            // nothing more to read
            break;
        }
        if (chunk_.empty() || chunk_.back()->fully_written()) {
            int head_size = m.chunk_.front()->content_size();
            if (head_size < n - n_read) {

                // speed up: directly transfer chunk pointer, avoid memory copying
                chunk_.push_back(m.chunk_.front());
                m.chunk_.pop_front();
                n_read += head_size;

                // skip read_from_chunk operations
                continue;

            } else {
                chunk_.push_back(new Chunk);
            }
        }
        int r = chunk_.back()->read_from_chunk(*m.chunk_.front(), n - n_read);

        if (m.chunk_.front()->fully_read()) {
            // remove useless chunks when they are fully read
            delete m.chunk_.front();
            m.chunk_.pop_front();
        }
        if (r == 0) {
            // no more data to read
            break;
        }
        n_read += r;
    }

    assert(chunk_.empty() || !chunk_.front()->fully_read());
    assert(m.chunk_.empty() || !m.chunk_.front()->fully_read());

    return n_read;
}

int Marshal::read_from_fd(int fd) {
    assert(chunk_.empty() || !chunk_.front()->fully_read());

    int n_read = 0;
    for (;;) {
        if (chunk_.empty() || chunk_.back()->fully_written()) {
            chunk_.push_back(new Chunk);
        }
        int r = chunk_.back()->read_from_fd(fd);
        if (r <= 0) {
            break;
        }
        n_read += r;
    }

    assert(chunk_.empty() || !chunk_.front()->fully_read());

    return n_read;
}

bool Marshal::content_size_gt(int size) const {

    int size_visited = 0;
    for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) {
        size_visited += (*it)->content_size();
        if (size_visited > size) {
            return true;
        }
    }

    return size_visited > size;
}

size_t Marshal::content_size() const {
    size_t size = 0;
    for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) {
        size += (*it)->content_size();
    }
    return size;
}

}
<commit_msg>rpc batching tuning<commit_after>#include <sys/time.h>

#include "marshal.h"

using namespace std;

namespace rpc {

#ifdef PERF_TEST
int _perf_rpc_in_packet_size[PERF_SAMPLE_SIZE];
int _perf_rpc_out_packet_size[PERF_SAMPLE_SIZE];
#endif // PERF_TEST

/**
 * 8kb minimum chunk size.
 * NOTE: this value directly affects how many read/write syscall will be issued.
 */
const int Chunk::min_size = 8192;

Marshal::~Marshal() {
    for (list<Chunk*>::iterator it = chunk_.begin(); it != chunk_.end(); ++it) {
        delete *it;
    }
}

Marshal::Bookmark* Marshal::set_bookmark(int size) {
    verify(write_counter_ == 0);

    // invariant: head of chunk list is not fully read (otherwise it's a waste of memory)
    assert(chunk_.empty() || !chunk_.front()->fully_read());

    Bookmark* bmark = new Bookmark();
    bmark->size_ = size;
    bmark->ptr_ = new char*[bmark->size_];

    for (int i = 0; i < bmark->size_; i++) {
        if (chunk_.empty() || chunk_.back()->fully_written()) {
            chunk_.push_back(new Chunk);
        }
        bmark->ptr_[i] = chunk_.back()->set_bookmark();
    }

    return bmark;
}

void Marshal::write_bookmark(Bookmark* bmark, const void* ptr) {
    char* pc = (char *) ptr;
    verify(bmark != NULL && bmark->ptr_ != NULL && bmark->size_ >= 0);
    for (int i = 0; i < bmark->size_; i++) {
        *(bmark->ptr_[i]) = pc[i];
    }
}

int Marshal::write(const void* p, int n) {
    assert(chunk_.empty() || !chunk_.front()->fully_read());

    if (chunk_.empty() || chunk_.back()->fully_written()) {
        chunk_.push_back(new Chunk(p, n));
    } else {
        int n_write = chunk_.back()->write(p, n);

        // otherwise the above fully_written() will return true
        assert(n_write > 0);

        if (n_write < n) {
            const char* pc = (const char *) p;
            chunk_.push_back(new Chunk(pc + n_write, n - n_write));
        }
    }

    write_counter_ += n;
    return n;
}

int Marshal::read(void* p, int n) {
    assert(chunk_.empty() || !chunk_.front()->fully_read());

    char* pc = (char *) p;
    int n_read = 0;
    while (!chunk_.empty() && n_read < n) {
        int r = chunk_.front()->read(pc + n_read, n - n_read);
        if (chunk_.front()->fully_read()) {
            // remove fully read chunks, avoid unnecessary mem usage
            delete chunk_.front();
            chunk_.pop_front();
        }
        if (r == 0) {
            // currently there's no content for us to read, so stop.
            break;
        }
        n_read += r;
    }

    verify(n_read <= n);
    assert(chunk_.empty() || !chunk_.front()->fully_read());

    return n_read;
}

int Marshal::peek(void* p, int n) const {
    assert(chunk_.empty() || !chunk_.front()->fully_read());

    char* pc = (char *) p;
    int n_peek = 0;

    for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) {
        int r = (*it)->peek(pc + n_peek, n - n_peek);
        if (r == 0) {
            // no more data to peek, so stop
            break;
        }
        n_peek += r;
        if (n_peek == n) {
            // read enough data, so stop
            break;
        }
    }

    assert(n_peek <= n);
    assert(chunk_.empty() || !chunk_.front()->fully_read());

    return n_peek;
}

int Marshal::write_to_fd(int fd) {
    assert(chunk_.empty() || !chunk_.front()->fully_read());

    struct timeval tm;
    gettimeofday(&tm, NULL);
    double now = tm.tv_sec + tm.tv_usec / 1000.0 / 1000.0;
    if (!content_size_gt(512) && now - last_write_fd_tm_ < 0.001) {
        // wait till next batch
        return 0;
    }
    last_write_fd_tm_ = now;

    int n_write = 0;
    while (!chunk_.empty()) {
        int r = chunk_.front()->write_to_fd(fd);
        if (chunk_.front()->fully_read()) {
            // remove useless chunks when they are fully read
            delete chunk_.front();
            chunk_.pop_front();
        }
        if (r <= 0) {
            break;
        }
        n_write += r;
    }

    assert(chunk_.empty() || !chunk_.front()->fully_read());

    return n_write;
}

string Marshal::dump() const {
    string s;
    s.reserve(this->content_size());
    for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) {
        s += string((*it)->content_ptr(), (*it)->content_size());
    }
    assert(s.length() == this->content_size());
    return s;
}

int Marshal::read_from_marshal(Marshal& m, int n /* =? */) {
    assert(chunk_.empty() || !chunk_.front()->fully_read());
    assert(m.chunk_.empty() || !m.chunk_.front()->fully_read());

    int n_read = 0;
    while (n_read < n) {
        if (m.chunk_.empty()) {
            // nothing more to read
            break;
        }
        if (chunk_.empty() || chunk_.back()->fully_written()) {
            int head_size = m.chunk_.front()->content_size();
            if (head_size < n - n_read) {

                // speed up: directly transfer chunk pointer, avoid memory copying
                chunk_.push_back(m.chunk_.front());
                m.chunk_.pop_front();
                n_read += head_size;

                // skip read_from_chunk operations
                continue;

            } else {
                chunk_.push_back(new Chunk);
            }
        }
        int r = chunk_.back()->read_from_chunk(*m.chunk_.front(), n - n_read);

        if (m.chunk_.front()->fully_read()) {
            // remove useless chunks when they are fully read
            delete m.chunk_.front();
            m.chunk_.pop_front();
        }
        if (r == 0) {
            // no more data to read
            break;
        }
        n_read += r;
    }

    assert(chunk_.empty() || !chunk_.front()->fully_read());
    assert(m.chunk_.empty() || !m.chunk_.front()->fully_read());

    return n_read;
}

int Marshal::read_from_fd(int fd) {
    assert(chunk_.empty() || !chunk_.front()->fully_read());

    int n_read = 0;
    for (;;) {
        if (chunk_.empty() || chunk_.back()->fully_written()) {
            chunk_.push_back(new Chunk);
        }
        int r = chunk_.back()->read_from_fd(fd);
        if (r <= 0) {
            break;
        }
        n_read += r;
    }

    assert(chunk_.empty() || !chunk_.front()->fully_read());

    return n_read;
}

bool Marshal::content_size_gt(int size) const {

    int size_visited = 0;
    for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) {
        size_visited += (*it)->content_size();
        if (size_visited > size) {
            return true;
        }
    }

    return size_visited > size;
}

size_t Marshal::content_size() const {
    size_t size = 0;
    for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) {
        size += (*it)->content_size();
    }
    return size;
}

}
<|endoftext|>


<commit_before>#include "Base.h"
#include "Generator.h"

//TRACK_MEMORY();

void printError(const char* format, ...)
{
    va_list argptr;
    va_start(argptr, format);
#ifdef WIN32
    int sz = vfprintf(stderr, format, argptr);
    if (sz > 0)
    {
        char* buf = new char[sz + 1];
        vsprintf(buf, format, argptr);
        buf[sz] = 0;
        OutputDebugStringA(buf);
        SAFE_DELETE_ARRAY(buf);
    }
#else
    vfprintf(stderr, format, argptr);
#endif
    va_end(argptr);
}

int main(int argc, char** argv)
{
    // Ensure the user is calling the program correctly.
    if (argc < 2 || argc > 4)
    {
        GP_ERROR("Usage: gameplay-luagen <doxygen-xml-input-directory> [output-directory] [binding-namespace]");
    }

    // Generate the bindings.
    string* bindingNS = (argc >= 4) ? new string(argv[3]) : NULL;
    Generator::getInstance()->run(argv[1], (argc >= 3) ? argv[2] : argv[1], bindingNS);
    Generator::releaseInstance();
    SAFE_DELETE(bindingNS);

    system("pause");
    return 0;
}
<commit_msg>Updated tinyxml2 for gameplay-luagen on MacOSX<commit_after>#include "Base.h"
#include "Generator.h"

//TRACK_MEMORY();

void printError(const char* format, ...)
{
    va_list argptr;
    va_start(argptr, format);
#ifdef WIN32
    int sz = vfprintf(stderr, format, argptr);
    if (sz > 0)
    {
        char* buf = new char[sz + 1];
        vsprintf(buf, format, argptr);
        buf[sz] = 0;
        OutputDebugStringA(buf);
        SAFE_DELETE_ARRAY(buf);
    }
#else
    vfprintf(stderr, format, argptr);
#endif
    va_end(argptr);
}

int main(int argc, char** argv)
{
    // Ensure the user is calling the program correctly.
    if (argc < 2 || argc > 4)
    {
        GP_ERROR("Usage: gameplay-luagen <doxygen-xml-input-directory> [output-directory] [binding-namespace]");
    }

    // Generate the bindings.
    string* bindingNS = (argc >= 4) ? new string(argv[3]) : NULL;
    Generator::getInstance()->run(argv[1], (argc >= 3) ? argv[2] : argv[1], bindingNS);
    Generator::releaseInstance();
    SAFE_DELETE(bindingNS);

#ifdef WIN32
    system("pause");
#endif

    return 0;
}
<|endoftext|>


<commit_before>/***********************************************************************
 Moses - statistical machine translation system
 Copyright (C) 2006-2011 University of Edinburgh

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
***********************************************************************/
#include <algorithm>
#include <cassert>
#include "AlignmentInfo.h"
#include "TypeDef.h"
#include "StaticData.h"

namespace Moses
{

void AlignmentInfo::BuildNonTermIndexMap()
{
  if (m_collection.empty()) {
    return;
  }
  const_iterator p = begin();
  size_t maxIndex = p->second;
  for (++p;  p != end(); ++p) {
    if (p->second > maxIndex) {
      maxIndex = p->second;
    }
  }
  m_nonTermIndexMap.resize(maxIndex+1, NOT_FOUND);
  size_t i = 0;
  for (p = begin(); p != end(); ++p) {
    m_nonTermIndexMap[p->second] = i++;
  }

}

bool compare_target(const std::pair<size_t,size_t> *a, const std::pair<size_t,size_t> *b) {
  if(a->second < b->second)  return true;
  if(a->second == b->second) return (a->first < b->first);
  return false;
}

std::vector< const std::pair<size_t,size_t>* > AlignmentInfo::GetSortedAlignments() const
{
  std::vector< const std::pair<size_t,size_t>* > ret;

  CollType::const_iterator iter;
  for (iter = m_collection.begin(); iter != m_collection.end(); ++iter)
  {
    const std::pair<size_t,size_t> &alignPair = *iter;
    ret.push_back(&alignPair);
  }

  const StaticData &staticData = StaticData::Instance();
  WordAlignmentSort wordAlignmentSort = staticData.GetWordAlignmentSort();

  switch (wordAlignmentSort)
  {
    case NoSort:
      break;
    case TargetOrder:
      std::sort(ret.begin(), ret.end(), compare_target);

      break;

    default:
      assert(false);
  }

  return ret;

}

std::ostream& operator<<(std::ostream &out, const AlignmentInfo &alignmentInfo)
{
  AlignmentInfo::const_iterator iter;
  for (iter = alignmentInfo.begin(); iter != alignmentInfo.end(); ++iter) {
    out << iter->first << "-" << iter->second << " ";
  }
  return out;
}

}
<commit_msg>option to sort word alignment info, as suggested by arianna bisazza<commit_after>/***********************************************************************
 Moses - statistical machine translation system
 Copyright (C) 2006-2011 University of Edinburgh

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
***********************************************************************/
#include <algorithm>
#include <cassert>
#include "AlignmentInfo.h"
#include "TypeDef.h"
#include "StaticData.h"

namespace Moses
{

void AlignmentInfo::BuildNonTermIndexMap()
{
  if (m_collection.empty()) {
    return;
  }
  const_iterator p = begin();
  size_t maxIndex = p->second;
  for (++p;  p != end(); ++p) {
    if (p->second > maxIndex) {
      maxIndex = p->second;
    }
  }
  m_nonTermIndexMap.resize(maxIndex+1, NOT_FOUND);
  size_t i = 0;
  for (p = begin(); p != end(); ++p) {
    m_nonTermIndexMap[p->second] = i++;
  }

}

bool compare_target(const std::pair<size_t,size_t> *a, const std::pair<size_t,size_t> *b) {
  if(a->second < b->second)  return true;
  if(a->second == b->second) return (a->first < b->first);
  return false;
}

std::vector< const std::pair<size_t,size_t>* > AlignmentInfo::GetSortedAlignments() const
{
  std::vector< const std::pair<size_t,size_t>* > ret;

  CollType::const_iterator iter;
  for (iter = m_collection.begin(); iter != m_collection.end(); ++iter)
  {
    const std::pair<size_t,size_t> &alignPair = *iter;
    ret.push_back(&alignPair);
  }

  const StaticData &staticData = StaticData::Instance();
  WordAlignmentSort wordAlignmentSort = staticData.GetWordAlignmentSort();

  switch (wordAlignmentSort)
  {
    case NoSort:
      break;

    case TargetOrder:
      std::sort(ret.begin(), ret.end(), compare_target);
      break;

    default:
      assert(false);
  }

  return ret;

}

std::ostream& operator<<(std::ostream &out, const AlignmentInfo &alignmentInfo)
{
  AlignmentInfo::const_iterator iter;
  for (iter = alignmentInfo.begin(); iter != alignmentInfo.end(); ++iter) {
    out << iter->first << "-" << iter->second << " ";
  }
  return out;
}

}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2021-present ScyllaDB
 */

/*
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

#include <seastar/core/coroutine.hh>

#include "consumer.hh"
#include "mutation_source_metadata.hh"
#include "service/priority_manager.hh"
#include "db/view/view_update_generator.hh"
#include "db/view/view_update_checks.hh"
#include "sstables/sstables.hh"
#include "sstables/sstables_manager.hh"

namespace streaming {

std::function<future<> (flat_mutation_reader_v2)> make_streaming_consumer(sstring origin,
        sharded<replica::database>& db,
        sharded<db::system_distributed_keyspace>& sys_dist_ks,
        sharded<db::view::view_update_generator>& vug,
        uint64_t estimated_partitions,
        stream_reason reason,
        sstables::offstrategy offstrategy) {
    return [&db, &sys_dist_ks, &vug, estimated_partitions, reason, offstrategy, origin = std::move(origin)] (flat_mutation_reader_v2 reader) -> future<> {
        std::exception_ptr ex;
        try {
            auto cf = db.local().find_column_family(reader.schema()).shared_from_this();
            auto use_view_update_path = co_await db::view::check_needs_view_update_path(sys_dist_ks.local(), *cf, reason);
            //FIXME: for better estimations this should be transmitted from remote
            auto metadata = mutation_source_metadata{};
            auto& cs = cf->get_compaction_strategy();
            const auto adjusted_estimated_partitions = cs.adjust_partition_estimate(metadata, estimated_partitions);
            auto make_interposer_consumer = [&cs, offstrategy] (const mutation_source_metadata& ms_meta, reader_consumer_v2 end_consumer) mutable {
                // postpone data segregation to off-strategy compaction if enabled
                if (offstrategy) {
                    return end_consumer;
                }
                return cs.make_interposer_consumer(ms_meta, std::move(end_consumer));
            };

            auto consumer = make_interposer_consumer(metadata,
                    [cf = std::move(cf), adjusted_estimated_partitions, use_view_update_path, &vug, origin = std::move(origin), offstrategy, reason] (flat_mutation_reader_v2 reader) {
                sstables::shared_sstable sst;
                try {
                    sst = use_view_update_path ? cf->make_streaming_staging_sstable() : cf->make_streaming_sstable_for_write();
                } catch (...) {
                    return current_exception_as_future().finally([reader = std::move(reader)] () mutable {
                        return reader.close();
                    });
                }
                schema_ptr s = reader.schema();
                auto& pc = service::get_local_streaming_priority();

                return sst->write_components(std::move(reader), adjusted_estimated_partitions, s,
                                             cf->get_sstables_manager().configure_writer(origin),
                                             encoding_stats{}, pc).then([sst] {
                    return sst->open_data();
                }).then([cf, sst, offstrategy, reason] {
                    if (offstrategy && (reason == stream_reason::repair)) {
                        sstables::sstlog.debug("Enabled automatic off-strategy trigger for table {}.{}",
                                cf->schema()->ks_name(), cf->schema()->cf_name());
                        cf->enable_off_strategy_trigger();
                    }
                    return cf->add_sstable_and_update_cache(sst, offstrategy);
                }).then([cf, s, sst, use_view_update_path, &vug]() mutable -> future<> {
                    if (!use_view_update_path) {
                        return make_ready_future<>();
                    }
                    return vug.local().register_staging_sstable(sst, std::move(cf));
                });
            });
            co_return co_await consumer(std::move(reader));
        } catch (...) {
            ex = std::current_exception();
        }
        if (ex) {
            co_await reader.close();
            std::rethrow_exception(std::move(ex));
        }
    };
}

}
<commit_msg>streaming: Enable auto off strategy compaction trigger for all rbno ops<commit_after>/*
 * Copyright (C) 2021-present ScyllaDB
 */

/*
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

#include <seastar/core/coroutine.hh>

#include "consumer.hh"
#include "mutation_source_metadata.hh"
#include "service/priority_manager.hh"
#include "db/view/view_update_generator.hh"
#include "db/view/view_update_checks.hh"
#include "sstables/sstables.hh"
#include "sstables/sstables_manager.hh"

namespace streaming {

std::function<future<> (flat_mutation_reader_v2)> make_streaming_consumer(sstring origin,
        sharded<replica::database>& db,
        sharded<db::system_distributed_keyspace>& sys_dist_ks,
        sharded<db::view::view_update_generator>& vug,
        uint64_t estimated_partitions,
        stream_reason reason,
        sstables::offstrategy offstrategy) {
    return [&db, &sys_dist_ks, &vug, estimated_partitions, reason, offstrategy, origin = std::move(origin)] (flat_mutation_reader_v2 reader) -> future<> {
        std::exception_ptr ex;
        try {
            auto cf = db.local().find_column_family(reader.schema()).shared_from_this();
            auto use_view_update_path = co_await db::view::check_needs_view_update_path(sys_dist_ks.local(), *cf, reason);
            //FIXME: for better estimations this should be transmitted from remote
            auto metadata = mutation_source_metadata{};
            auto& cs = cf->get_compaction_strategy();
            const auto adjusted_estimated_partitions = cs.adjust_partition_estimate(metadata, estimated_partitions);
            auto make_interposer_consumer = [&cs, offstrategy] (const mutation_source_metadata& ms_meta, reader_consumer_v2 end_consumer) mutable {
                // postpone data segregation to off-strategy compaction if enabled
                if (offstrategy) {
                    return end_consumer;
                }
                return cs.make_interposer_consumer(ms_meta, std::move(end_consumer));
            };

            auto consumer = make_interposer_consumer(metadata,
                    [cf = std::move(cf), adjusted_estimated_partitions, use_view_update_path, &vug, origin = std::move(origin), offstrategy, reason] (flat_mutation_reader_v2 reader) {
                sstables::shared_sstable sst;
                try {
                    sst = use_view_update_path ? cf->make_streaming_staging_sstable() : cf->make_streaming_sstable_for_write();
                } catch (...) {
                    return current_exception_as_future().finally([reader = std::move(reader)] () mutable {
                        return reader.close();
                    });
                }
                schema_ptr s = reader.schema();
                auto& pc = service::get_local_streaming_priority();

                return sst->write_components(std::move(reader), adjusted_estimated_partitions, s,
                                             cf->get_sstables_manager().configure_writer(origin),
                                             encoding_stats{}, pc).then([sst] {
                    return sst->open_data();
                }).then([cf, sst, offstrategy, reason, origin] {
                    if (offstrategy && sstables::repair_origin == origin) {
                        sstables::sstlog.debug("Enabled automatic off-strategy trigger for table {}.{}",
                                cf->schema()->ks_name(), cf->schema()->cf_name());
                        cf->enable_off_strategy_trigger();
                    }
                    return cf->add_sstable_and_update_cache(sst, offstrategy);
                }).then([cf, s, sst, use_view_update_path, &vug]() mutable -> future<> {
                    if (!use_view_update_path) {
                        return make_ready_future<>();
                    }
                    return vug.local().register_staging_sstable(sst, std::move(cf));
                });
            });
            co_return co_await consumer(std::move(reader));
        } catch (...) {
            ex = std::current_exception();
        }
        if (ex) {
            co_await reader.close();
            std::rethrow_exception(std::move(ex));
        }
    };
}

}
<|endoftext|>


<commit_before>#include "Image.h"

#include "Utilities.h"

#include <stromx/core/Exception.h>

namespace stromx
{
    namespace base
    {
        const std::string Image::TYPE = "Image";
        const std::string Image::PACKAGE = STROMX_BASE_PACKAGE_NAME;
        const core::Version Image::VERSION = core::Version(BASE_VERSION_MAJOR, BASE_VERSION_MINOR, BASE_VERSION_PATCH);

        Image::Image(const unsigned int width, const unsigned int height, const core::Image::PixelType pixelType)
        {
            try
            {
                m_image = cvCreateImage(cv::Size(width, height), depth(pixelType) * 8, numChannels(pixelType));

                getDataFromCvImage(pixelType);
                setVariant(dataTypeFromPixelType(pixelType));
            }
            catch(cv::Exception&)
            {
                throw core::OutOfMemory("Failed to create new image.");
            }
        }

        Image::Image(const core::Image& image)
        {
            try
            {
                m_image = cvCreateImage(cv::Size(image.width(), image.height()),
                                        depth(image.pixelType()) * 8, numChannels(image.pixelType()));

                getDataFromCvImage(image.pixelType());
                setVariant(image.variant());
            }
            catch(cv::Exception&)
            {
                throw core::OutOfMemory("Failed to create new image.");
            }

            cv::Mat cvInImage = getOpenCvMat(image);
            cv::Mat cvImage(m_image);
            cvInImage.copyTo(cvImage);
        }

        Image::Image()
        : m_image(0)
        {
            setSize(0);
            initialize(0, 0, 0, 0, core::Image::NONE);
            setVariant(core::DataVariant::IMAGE);
        }

        Image::Image(const std::string& filename)
        : m_image(0)
        {
            open(filename);
        }

        Image::Image(const unsigned int size)
        {
            try
            {
                m_image = cvCreateImage(cv::Size(size, 1), 8, 1);

                getDataFromCvImage(core::Image::MONO_8);
                setVariant(core::DataVariant::IMAGE);
            }
            catch(cv::Exception&)
            {
                throw core::OutOfMemory("Failed to allocate image.");
            }
        }

        const std::string Image::serialize(const std::string& name, const std::string& path) const
        {
            try
            {
                std::string filename = name + ".png";
                std::string filepath = path + filename;
                save(filepath);
                return filename;
            }
            catch(core::Exception&)
            {
                throw core::SerializationError(*this, name, path);
            }
        }

        void Image::deserialize(const std::string& data, const std::string& path)
        {
            try
            {
                std::string filepath = path + data;
                open(filepath);
            }
            catch(core::Exception&)
            {
                throw core::DeserializationError(*this, data, path);
            }
        }

        void Image::open(const std::string& filename)
        {
            if(m_image)
                cvReleaseImage(&m_image);

            m_image = cvLoadImage(filename.c_str());

            if(! m_image)
                throw core::FileAccessFailed(filename, "Failed to load image.");

            getDataFromCvImage(pixelTypeFromParameters(m_image->depth, m_image->nChannels));
            setVariant(dataTypeFromPixelType(pixelType()));
        }

        void Image::getDataFromCvImage(const PixelType pixelType)
        {
            setBuffer((uint8_t*)(m_image->imageData));
            setSize(m_image->imageSize);
            initialize(m_image->width, m_image->height, m_image->widthStep, (uint8_t*)(m_image->imageData), pixelType);
        }

        void Image::resize(const unsigned int width, const unsigned int height, const core::Image::PixelType pixelType)
        {
            if(m_image)
                cvReleaseImage(&m_image);

            try
            {
                m_image = cvCreateImage(cv::Size(width, height), depth(pixelType) * 8, numChannels(pixelType));
                getDataFromCvImage(pixelType);
                setVariant(dataTypeFromPixelType(pixelType));
            }
            catch(cv::Exception&)
            {
                throw core::OutOfMemory("Failed to create new image.");
            }
        }

        void Image::resize(const unsigned int size)
        {
            if(m_image)
                cvReleaseImage(&m_image);

            try
            {
                m_image = cvCreateImage(cv::Size(size, 1), 8, 1);

                getDataFromCvImage(pixelTypeFromParameters(m_image->depth, m_image->nChannels));
                setVariant(core::DataVariant::MONO_8_IMAGE);
            }
            catch(cv::Exception&)
            {
                throw core::OutOfMemory("Failed to allocate image.");
            }
        }

        void Image::save(const std::string& filename) const
        {
            cv::Mat inImage = getOpenCvMat(*this);

            switch(pixelType())
            {
            case core::Image::RGB_24:
            {
                Image tempImage(width(), height(), BGR_24);
                cv::Mat cvTempImage(tempImage.m_image);

                cv::cvtColor(inImage, cvTempImage, CV_RGB2BGR);

                if(! cv::imwrite(filename, cv::Mat(tempImage.m_image)))
                    throw core::FileAccessFailed(filename, "Failed to save image.");

                break;
            }
            case core::Image::BGR_24:
            case core::Image::MONO_8:
            case core::Image::BAYERBG_8:
            case core::Image::BAYERGB_8:
            {
                if(! cv::imwrite(filename, inImage))
                    throw core::FileAccessFailed(filename, "Failed to save image.");
                break;
            }
            default:
                throw core::WrongArgument("Unknown pixel type.");
            }
        }

        Image::~Image()
        {
            cvReleaseImage(&m_image);
        }

        const core::DataVariant Image::dataTypeFromPixelType(const core::Image::PixelType pixelType)
        {
            switch(pixelType)
            {
            case core::Image::NONE:
                return core::DataVariant(core::DataVariant::IMAGE);
            case core::Image::MONO_8:
                return core::DataVariant(core::DataVariant::MONO_8_IMAGE);
            case core::Image::BAYERBG_8:
                return core::DataVariant(core::DataVariant::BAYERBG_8_IMAGE);
            case core::Image::BAYERGB_8:
                return core::DataVariant(core::DataVariant::BAYERGB_8_IMAGE);
            case core::Image::RGB_24:
                return core::DataVariant(core::DataVariant::RGB_24_IMAGE);
            case core::Image::BGR_24:
                return core::DataVariant(core::DataVariant::BGR_24_IMAGE);
            default:
                throw core::WrongArgument("Unknown pixel type.");
            }
        }

        const core::Image::PixelType Image::pixelTypeFromParameters(const int depth, const int numChannels)
        {
            switch(depth)
            {
            case 8:
                switch(numChannels)
                {
                case 1:
                    return core::Image::MONO_8;
                case 3:
                    return core::Image::BGR_24;
                default:
                    throw core::WrongArgument("Unknown combination of depth and number of channels.");
                }
            case 16:
                throw core::WrongArgument("Unknown combination of depth and number of channels.");
            default:
                throw core::WrongArgument("Unknown combination of depth and number of channels.");
            }
        }
    }
}
<commit_msg>Base tests pass on Windows -> only python wrappers are untested on Windows.<commit_after>#include "Image.h"

#include "Utilities.h"

#include <stromx/core/Exception.h>

namespace stromx
{
    namespace base
    {
        const std::string Image::TYPE = "Image";
        const std::string Image::PACKAGE = STROMX_BASE_PACKAGE_NAME;
        const core::Version Image::VERSION = core::Version(BASE_VERSION_MAJOR, BASE_VERSION_MINOR, BASE_VERSION_PATCH);

        Image::Image(const unsigned int width, const unsigned int height, const core::Image::PixelType pixelType)
        {
            try
            {
                m_image = cvCreateImage(cv::Size(width, height), depth(pixelType) * 8, numChannels(pixelType));

                getDataFromCvImage(pixelType);
                setVariant(dataTypeFromPixelType(pixelType));
            }
            catch(cv::Exception&)
            {
                throw core::OutOfMemory("Failed to create new image.");
            }
        }

        Image::Image(const core::Image& image)
        {
            try
            {
                m_image = cvCreateImage(cv::Size(image.width(), image.height()),
                                        depth(image.pixelType()) * 8, numChannels(image.pixelType()));

                getDataFromCvImage(image.pixelType());
                setVariant(image.variant());
            }
            catch(cv::Exception&)
            {
                throw core::OutOfMemory("Failed to create new image.");
            }

            cv::Mat cvInImage = getOpenCvMat(image);
            cv::Mat cvImage(m_image);
            cvInImage.copyTo(cvImage);
        }

        Image::Image()
        : m_image(0)
        {
            setSize(0);
            initialize(0, 0, 0, 0, core::Image::NONE);
            setVariant(core::DataVariant::IMAGE);
        }

        Image::Image(const std::string& filename)
        : m_image(0)
        {
            open(filename);
        }

        Image::Image(const unsigned int size)
        {
            try
            {
                m_image = cvCreateImage(cv::Size(size, 1), 8, 1);

                getDataFromCvImage(core::Image::MONO_8);
                setVariant(core::DataVariant::IMAGE);
            }
            catch(cv::Exception&)
            {
                throw core::OutOfMemory("Failed to allocate image.");
            }
        }

        const std::string Image::serialize(const std::string& name, const std::string& path) const
        {
            try
            {
                std::string filename = name + ".png";
                std::string filepath = path + filename;
                save(filepath);
                return filename;
            }
            catch(core::Exception&)
            {
                throw core::SerializationError(*this, name, path);
            }
        }

        void Image::deserialize(const std::string& data, const std::string& path)
        {
            try
            {
                std::string filepath = path + data;
                open(filepath);
            }
            catch(core::Exception&)
            {
                throw core::DeserializationError(*this, data, path);
            }
        }

        void Image::open(const std::string& filename)
        {
            if(m_image)
                cvReleaseImage(&m_image);

            m_image = cvLoadImage(filename.c_str());

            if(! m_image)
                throw core::FileAccessFailed(filename, "Failed to load image.");

            getDataFromCvImage(pixelTypeFromParameters(m_image->depth, m_image->nChannels));
            setVariant(dataTypeFromPixelType(pixelType()));
        }

        void Image::getDataFromCvImage(const PixelType pixelType)
        {
            setBuffer((uint8_t*)(m_image->imageData));
            setSize(m_image->imageSize);
            initialize(m_image->width, m_image->height, m_image->widthStep, (uint8_t*)(m_image->imageData), pixelType);
        }

        void Image::resize(const unsigned int width, const unsigned int height, const core::Image::PixelType pixelType)
        {
            if(m_image)
                cvReleaseImage(&m_image);

            try
            {
                m_image = cvCreateImage(cv::Size(width, height), depth(pixelType) * 8, numChannels(pixelType));
                getDataFromCvImage(pixelType);
                setVariant(dataTypeFromPixelType(pixelType));
            }
            catch(cv::Exception&)
            {
                throw core::OutOfMemory("Failed to create new image.");
            }
        }

        void Image::resize(const unsigned int size)
        {
            if(m_image)
                cvReleaseImage(&m_image);

            try
            {
                m_image = cvCreateImage(cv::Size(size, 1), 8, 1);

                getDataFromCvImage(pixelTypeFromParameters(m_image->depth, m_image->nChannels));
                setVariant(core::DataVariant::MONO_8_IMAGE);
            }
            catch(cv::Exception&)
            {
                throw core::OutOfMemory("Failed to allocate image.");
            }
        }

        void Image::save(const std::string& filename) const
        {
            cv::Mat inImage = getOpenCvMat(*this);

            switch(pixelType())
            {
            case core::Image::RGB_24:
            {
                Image tempImage(width(), height(), BGR_24);
                cv::Mat cvTempImage(tempImage.m_image);

                cv::cvtColor(inImage, cvTempImage, CV_RGB2BGR);

                if(! cvSaveImage(filename.c_str(), &IplImage(cvTempImage)))
                    throw core::FileAccessFailed(filename, "Failed to save image.");

                break;
            }
            case core::Image::BGR_24:
            case core::Image::MONO_8:
            case core::Image::BAYERBG_8:
            case core::Image::BAYERGB_8:
            {
                if(! cvSaveImage(filename.c_str(), &IplImage(inImage)))
                    throw core::FileAccessFailed(filename, "Failed to save image.");
                break;
            }
            default:
                throw core::WrongArgument("Unknown pixel type.");
            }
        }

        Image::~Image()
        {
            cvReleaseImage(&m_image);
        }

        const core::DataVariant Image::dataTypeFromPixelType(const core::Image::PixelType pixelType)
        {
            switch(pixelType)
            {
            case core::Image::NONE:
                return core::DataVariant(core::DataVariant::IMAGE);
            case core::Image::MONO_8:
                return core::DataVariant(core::DataVariant::MONO_8_IMAGE);
            case core::Image::BAYERBG_8:
                return core::DataVariant(core::DataVariant::BAYERBG_8_IMAGE);
            case core::Image::BAYERGB_8:
                return core::DataVariant(core::DataVariant::BAYERGB_8_IMAGE);
            case core::Image::RGB_24:
                return core::DataVariant(core::DataVariant::RGB_24_IMAGE);
            case core::Image::BGR_24:
                return core::DataVariant(core::DataVariant::BGR_24_IMAGE);
            default:
                throw core::WrongArgument("Unknown pixel type.");
            }
        }

        const core::Image::PixelType Image::pixelTypeFromParameters(const int depth, const int numChannels)
        {
            switch(depth)
            {
            case 8:
                switch(numChannels)
                {
                case 1:
                    return core::Image::MONO_8;
                case 3:
                    return core::Image::BGR_24;
                default:
                    throw core::WrongArgument("Unknown combination of depth and number of channels.");
                }
            case 16:
                throw core::WrongArgument("Unknown combination of depth and number of channels.");
            default:
                throw core::WrongArgument("Unknown combination of depth and number of channels.");
            }
        }
    }
}
<|endoftext|>