<commit_before>#include "LogManager.h"
#include <fstream>

using namespace OpenSim;

// Initialize static members
LogBuffer LogManager::out;
LogBuffer LogManager::err;
std::ostream LogManager::cout(std::cout.rdbuf()); // This cout writes to the actual standard out
std::ostream LogManager::cerr(std::cerr.rdbuf()); // This cerr writes to the actual standard error

// Initialize a static log manager to force the constructor to be called
LogManager logManager;

//=============================================================================
// LogBuffer
//=============================================================================
LogBuffer::LogBuffer() :
	_outputStream(0),
	_secondaryOutputStream(0)
{
}

// Assumes caller owns this output stream (will never be deleted)
void LogBuffer::
setOutputStream(std::ostream *aOutputStream)
{
	_outputStream = aOutputStream;
}

// Assumes caller owns this output stream (will never be deleted)
void LogBuffer::
setSecondaryOutputStream(std::ostream *aSecondaryOutputStream)
{
	_secondaryOutputStream = aSecondaryOutputStream;
}

int LogBuffer::
sync()
{
	// Write to up to two output streams
	if (_outputStream) (*_outputStream) << str() << std::flush;
	if (_secondaryOutputStream) (*_secondaryOutputStream) << str() << std::flush;
	// Reset current buffer contents
	str("");
	return std::stringbuf::sync();
}

//=============================================================================
// LogManager
//=============================================================================
LogManager::LogManager()
{
	// Seems to be causing crashes in the GUI... maybe a multithreading issue.
#if 0
	// Change the underlying streambuf for the standard cout/cerr to our custom buffers
	std::cout.rdbuf(&out);
	std::cerr.rdbuf(&err);

	// Example setup: redirect output to both the terminal and an output file
	out.setOutputStream(&cout);
	out.setSecondaryOutputStream(new std::ofstream("out.log"));
	err.setOutputStream(&cerr);
	err.setSecondaryOutputStream(new std::ofstream("err.log"));
#endif
}

LogManager::~LogManager()
{
	std::cout << std::flush;
	std::cerr << std::flush;
}
<commit_msg>Reactivate LogManager to see if it crashes the GUI still or not...<commit_after>#include "LogManager.h"
#include <fstream>

using namespace OpenSim;

// Initialize static members
LogBuffer LogManager::out;
LogBuffer LogManager::err;
std::ostream LogManager::cout(std::cout.rdbuf()); // This cout writes to the actual standard out
std::ostream LogManager::cerr(std::cerr.rdbuf()); // This cerr writes to the actual standard error

// Initialize a static log manager to force the constructor to be called
LogManager logManager;

//=============================================================================
// LogBuffer
//=============================================================================
LogBuffer::LogBuffer() :
	_outputStream(0),
	_secondaryOutputStream(0)
{
}

// Assumes caller owns this output stream (will never be deleted)
void LogBuffer::
setOutputStream(std::ostream *aOutputStream)
{
	_outputStream = aOutputStream;
}

// Assumes caller owns this output stream (will never be deleted)
void LogBuffer::
setSecondaryOutputStream(std::ostream *aSecondaryOutputStream)
{
	_secondaryOutputStream = aSecondaryOutputStream;
}

int LogBuffer::
sync()
{
	// Write to up to two output streams
	if (_outputStream) (*_outputStream) << str() << std::flush;
	if (_secondaryOutputStream) (*_secondaryOutputStream) << str() << std::flush;
	// Reset current buffer contents
	str("");
	return std::stringbuf::sync();
}

//=============================================================================
// LogManager
//=============================================================================
LogManager::LogManager()
{
	// Seems to be causing crashes in the GUI... maybe a multithreading issue.
#if 1
	// Change the underlying streambuf for the standard cout/cerr to our custom buffers
	std::cout.rdbuf(&out);
	std::cerr.rdbuf(&err);

	// Example setup: redirect output to both the terminal and an output file
	out.setOutputStream(&cout);
	out.setSecondaryOutputStream(new std::ofstream("out.log"));
	err.setOutputStream(&cerr);
	err.setSecondaryOutputStream(new std::ofstream("err.log"));
#endif
}

LogManager::~LogManager()
{
	std::cout << std::flush;
	std::cerr << std::flush;
}
<|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 "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/ref_counted.h"
#include "base/scoped_temp_dir.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/in_process_webkit/indexed_db_context.h"
#include "chrome/browser/in_process_webkit/webkit_context.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/testing_profile.h"
#include "chrome/test/thread_test_helper.h"
#include "chrome/test/ui_test_utils.h"

// This browser test is aimed towards exercising the IndexedDB bindings and
// the actual implementation that lives in the browser side (in_process_webkit).
class IndexedDBBrowserTest : public InProcessBrowserTest {
 public:
  IndexedDBBrowserTest() {
    EnableDOMAutomation();
  }

  GURL testUrl(const FilePath& file_path) {
    const FilePath kTestDir(FILE_PATH_LITERAL("indexeddb"));
    return ui_test_utils::GetTestUrl(kTestDir, file_path);
  }

  void SimpleTest(const GURL& test_url) {
    // The test page will perform tests on IndexedDB, then navigate to either
    // a #pass or #fail ref.
    LOG(INFO) << "Navigating to URL and blocking.";
    ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
        browser(), test_url, 2);
    LOG(INFO) << "Navigation done.";
    std::string result = browser()->GetSelectedTabContents()->GetURL().ref();
    if (result != "pass") {
      std::string js_result;
      ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
          browser()->GetSelectedTabContents()->render_view_host(), L"",
          L"window.domAutomationController.send(getLog())", &js_result));
      FAIL() << "Failed: " << js_result;
    }
  }
};

IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) {
  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html"))));
}

IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, IndexTest) {
  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("index_test.html"))));
}

// Flaky on windows, see http://crbug.com/67422 and http://crbug.com/69293.
#if defined(OS_WIN)
#define MAYBE_KeyPathTest FLAKY_KeyPathTest
#else
#define MAYBE_KeyPathTest KeyPathTest
#endif

IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, MAYBE_KeyPathTest) {
  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_path_test.html"))));
}

IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) {
  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_get_test.html"))));
}

IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ObjectStoreTest) {
  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("object_store_test.html"))));
}

IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) {
  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("database_test.html"))));
}

IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionTest) {
  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}

IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DoesntHangTest) {
  SimpleTest(testUrl(FilePath(
      FILE_PATH_LITERAL("transaction_run_forever.html"))));
  ui_test_utils::CrashTab(browser()->GetSelectedTabContents());
  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}

// In proc browser test is needed here because ClearLocalState indirectly calls
// WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearLocalState) {
  // Create test files.
  ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  FilePath indexeddb_dir = temp_dir.path().Append(
      IndexedDBContext::kIndexedDBDirectory);
  ASSERT_TRUE(file_util::CreateDirectory(indexeddb_dir));

  FilePath::StringType file_name_1(FILE_PATH_LITERAL("http_foo_0"));
  file_name_1.append(IndexedDBContext::kIndexedDBExtension);
  FilePath::StringType file_name_2(FILE_PATH_LITERAL("chrome-extension_foo_0"));
  file_name_2.append(IndexedDBContext::kIndexedDBExtension);
  FilePath temp_file_path_1 = indexeddb_dir.Append(file_name_1);
  FilePath temp_file_path_2 = indexeddb_dir.Append(file_name_2);

  ASSERT_EQ(1, file_util::WriteFile(temp_file_path_1, ".", 1));
  ASSERT_EQ(1, file_util::WriteFile(temp_file_path_2, "o", 1));

  // Create the scope which will ensure we run the destructor of the webkit
  // context which should trigger the clean up.
  {
    TestingProfile profile;
    WebKitContext *webkit_context = profile.GetWebKitContext();
    webkit_context->indexed_db_context()->set_data_path(indexeddb_dir);
    webkit_context->set_clear_local_state_on_exit(true);
  }
  // Make sure we wait until the destructor has run.
  scoped_refptr<ThreadTestHelper> helper(
      new ThreadTestHelper(BrowserThread::WEBKIT));
  ASSERT_TRUE(helper->Run());

  // Because we specified https for scheme to be skipped the second file
  // should survive and the first go into vanity.
  ASSERT_FALSE(file_util::PathExists(temp_file_path_1));
  ASSERT_TRUE(file_util::PathExists(temp_file_path_2));
}
<commit_msg>Mark some IndexedDB browser tests as flaky.<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 "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/ref_counted.h"
#include "base/scoped_temp_dir.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/in_process_webkit/indexed_db_context.h"
#include "chrome/browser/in_process_webkit/webkit_context.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/testing_profile.h"
#include "chrome/test/thread_test_helper.h"
#include "chrome/test/ui_test_utils.h"

// This browser test is aimed towards exercising the IndexedDB bindings and
// the actual implementation that lives in the browser side (in_process_webkit).
class IndexedDBBrowserTest : public InProcessBrowserTest {
 public:
  IndexedDBBrowserTest() {
    EnableDOMAutomation();
  }

  GURL testUrl(const FilePath& file_path) {
    const FilePath kTestDir(FILE_PATH_LITERAL("indexeddb"));
    return ui_test_utils::GetTestUrl(kTestDir, file_path);
  }

  void SimpleTest(const GURL& test_url) {
    // The test page will perform tests on IndexedDB, then navigate to either
    // a #pass or #fail ref.
    LOG(INFO) << "Navigating to URL and blocking.";
    ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
        browser(), test_url, 2);
    LOG(INFO) << "Navigation done.";
    std::string result = browser()->GetSelectedTabContents()->GetURL().ref();
    if (result != "pass") {
      std::string js_result;
      ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
          browser()->GetSelectedTabContents()->render_view_host(), L"",
          L"window.domAutomationController.send(getLog())", &js_result));
      FAIL() << "Failed: " << js_result;
    }
  }
};

IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) {
  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html"))));
}

// Flaky. See http://crbug.com/70643.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_IndexTest) {
  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("index_test.html"))));
}

// Flaky on windows, see http://crbug.com/67422 and http://crbug.com/69293.
#if defined(OS_WIN)
#define MAYBE_KeyPathTest FLAKY_KeyPathTest
#else
#define MAYBE_KeyPathTest KeyPathTest
#endif

IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, MAYBE_KeyPathTest) {
  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_path_test.html"))));
}

IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) {
  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_get_test.html"))));
}

// Flaky. See http://crbug.com/70643.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_ObjectStoreTest) {
  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("object_store_test.html"))));
}

IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) {
  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("database_test.html"))));
}

// Flaky. See http://crbug.com/70643.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_TransactionTest) {
  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}

// Flaky. See http://crbug.com/70643.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_DoesntHangTest) {
  SimpleTest(testUrl(FilePath(
      FILE_PATH_LITERAL("transaction_run_forever.html"))));
  ui_test_utils::CrashTab(browser()->GetSelectedTabContents());
  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}

// In proc browser test is needed here because ClearLocalState indirectly calls
// WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearLocalState) {
  // Create test files.
  ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  FilePath indexeddb_dir = temp_dir.path().Append(
      IndexedDBContext::kIndexedDBDirectory);
  ASSERT_TRUE(file_util::CreateDirectory(indexeddb_dir));

  FilePath::StringType file_name_1(FILE_PATH_LITERAL("http_foo_0"));
  file_name_1.append(IndexedDBContext::kIndexedDBExtension);
  FilePath::StringType file_name_2(FILE_PATH_LITERAL("chrome-extension_foo_0"));
  file_name_2.append(IndexedDBContext::kIndexedDBExtension);
  FilePath temp_file_path_1 = indexeddb_dir.Append(file_name_1);
  FilePath temp_file_path_2 = indexeddb_dir.Append(file_name_2);

  ASSERT_EQ(1, file_util::WriteFile(temp_file_path_1, ".", 1));
  ASSERT_EQ(1, file_util::WriteFile(temp_file_path_2, "o", 1));

  // Create the scope which will ensure we run the destructor of the webkit
  // context which should trigger the clean up.
  {
    TestingProfile profile;
    WebKitContext *webkit_context = profile.GetWebKitContext();
    webkit_context->indexed_db_context()->set_data_path(indexeddb_dir);
    webkit_context->set_clear_local_state_on_exit(true);
  }
  // Make sure we wait until the destructor has run.
  scoped_refptr<ThreadTestHelper> helper(
      new ThreadTestHelper(BrowserThread::WEBKIT));
  ASSERT_TRUE(helper->Run());

  // Because we specified https for scheme to be skipped the second file
  // should survive and the first go into vanity.
  ASSERT_FALSE(file_util::PathExists(temp_file_path_1));
  ASSERT_TRUE(file_util::PathExists(temp_file_path_2));
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 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/ui/ash/launcher/launcher_app_icon_loader.h"

#include "base/stl_util.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"

namespace {

const extensions::Extension* GetExtensionByID(Profile* profile,
                                              const std::string& id) {
  ExtensionService* service = profile->GetExtensionService();
  if (!service)
    return NULL;
  return service->extensions()->GetByID(id);
}

}  // namespace

LauncherAppIconLoader::LauncherAppIconLoader(
    Profile* profile,
    ChromeLauncherController* controller)
    : profile_(profile),
      host_(controller) {
}

LauncherAppIconLoader::~LauncherAppIconLoader() {
  STLDeleteContainerPairFirstPointers(map_.begin(), map_.end());
}

void LauncherAppIconLoader::FetchImage(const std::string& id) {
  for (ImageToExtensionIDMap::const_iterator i = map_.begin();
       i != map_.end(); ++i) {
    if (i->second == id)
      return;  // Already loading the image.
  }

  const extensions::Extension* extension = GetExtensionByID(profile_, id);
  if (!extension)
    return;

  extensions::IconImage* image = new extensions::IconImage(
      extension,
      extension->icons(),
      extension_misc::EXTENSION_ICON_SMALL,
      extensions::Extension::GetDefaultIcon(true),
      this);
  // |map_| takes ownership of |image|.
  map_[image] = id;

  host_->SetAppImage(id, image->image_skia());
}

void LauncherAppIconLoader::ClearImage(const std::string& id) {
  for (ImageToExtensionIDMap::iterator i = map_.begin();
       i != map_.end(); ++i) {
    if (i->second == id) {
      delete i->first;
      map_.erase(i);
      break;
    }
  }
}

void LauncherAppIconLoader::OnExtensionIconImageChanged(
    extensions::IconImage* image) {
  ImageToExtensionIDMap::iterator i = map_.find(image);
  if (i == map_.end())
    return;  // The image has been removed, do nothing.

  host_->SetAppImage(i->second, image->image_skia());
}
<commit_msg>cros: Make launcher explicitly starts app icon loading.<commit_after>// Copyright (c) 2012 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/ui/ash/launcher/launcher_app_icon_loader.h"

#include "base/stl_util.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"

namespace {

const extensions::Extension* GetExtensionByID(Profile* profile,
                                              const std::string& id) {
  ExtensionService* service = profile->GetExtensionService();
  if (!service)
    return NULL;
  return service->extensions()->GetByID(id);
}

}  // namespace

LauncherAppIconLoader::LauncherAppIconLoader(
    Profile* profile,
    ChromeLauncherController* controller)
    : profile_(profile),
      host_(controller) {
}

LauncherAppIconLoader::~LauncherAppIconLoader() {
  STLDeleteContainerPairFirstPointers(map_.begin(), map_.end());
}

void LauncherAppIconLoader::FetchImage(const std::string& id) {
  for (ImageToExtensionIDMap::const_iterator i = map_.begin();
       i != map_.end(); ++i) {
    if (i->second == id)
      return;  // Already loading the image.
  }

  const extensions::Extension* extension = GetExtensionByID(profile_, id);
  if (!extension)
    return;

  extensions::IconImage* image = new extensions::IconImage(
      extension,
      extension->icons(),
      extension_misc::EXTENSION_ICON_SMALL,
      extensions::Extension::GetDefaultIcon(true),
      this);
  // |map_| takes ownership of |image|.
  map_[image] = id;

  // Triggers image loading now instead of depending on paint message. This
  // makes the temp blank image be shown for shorter time and improves user
  // experience. See http://crbug.com/146114.
  image->image_skia().EnsureRepsForSupportedScaleFactors();
}

void LauncherAppIconLoader::ClearImage(const std::string& id) {
  for (ImageToExtensionIDMap::iterator i = map_.begin();
       i != map_.end(); ++i) {
    if (i->second == id) {
      delete i->first;
      map_.erase(i);
      break;
    }
  }
}

void LauncherAppIconLoader::OnExtensionIconImageChanged(
    extensions::IconImage* image) {
  ImageToExtensionIDMap::iterator i = map_.find(image);
  if (i == map_.end())
    return;  // The image has been removed, do nothing.

  host_->SetAppImage(i->second, image->image_skia());
}
<|endoftext|>


<commit_before>/*
 * Medical Image Registration ToolKit (MIRTK)
 *
 * Copyright 2008-2015 Imperial College London
 * Copyright 2008-2013 Daniel Rueckert, Julia Schnabel
 * Copyright 2013-2015 Andreas Schuh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "mirtk/Resampling.h"

#include "mirtk/Parallel.h"
#include "mirtk/Profiling.h"
#include "mirtk/InterpolateImageFunction.h"

namespace mirtk {

// ---------------------------------------------------------------------------
template <class VoxelType>
Resampling<VoxelType>::Resampling(double dx, double dy, double dz)
{
  _X     = 0;
  _Y     = 0;
  _Z     = 0;
  _XSize = dx;
  _YSize = dy;
  _ZSize = dz;
  _Interpolator = NULL;
}

// ---------------------------------------------------------------------------
template <class VoxelType>
Resampling<VoxelType>::Resampling(int x, int y, int z)
{
  _X     = x;
  _Y     = y;
  _Z     = z;
  _XSize = 0;
  _YSize = 0;
  _ZSize = 0;
  _Interpolator = NULL;
}

// ---------------------------------------------------------------------------
template <class VoxelType>
Resampling<VoxelType>::Resampling(int x, int y, int z, double dx, double dy, double dz)
{
  _X     = x;
  _Y     = y;
  _Z     = z;
  _XSize = dx;
  _YSize = dy;
  _ZSize = dz;
  _Interpolator = NULL;
}

// ---------------------------------------------------------------------------
template <class VoxelType>
void Resampling<VoxelType>::Initialize()
{
  // Initialize base class
  ImageToImage<VoxelType>::Initialize(false);

  // Set up interpolator
  if (_Interpolator == NULL) {
    cerr << "Resampling::Initialize: No interpolator found!" << endl;
    exit(1);
  }
  _Interpolator->Input(this->_Input);
  _Interpolator->Initialize();

  // Initialize output image
  this->InitializeOutput();
}

// ---------------------------------------------------------------------------
template <class VoxelType>
void Resampling<VoxelType>::InitializeOutput()
{
  ImageAttributes attr = this->_Input->Attributes();

  if (_X > 0 && _XSize > 0) {
    attr._x  = _X;
    attr._dx = _XSize;
  } else if (_X > 0) {
    attr._x  = _X;
    attr._dx = this->_Input->X() * this->_Input->XSize() / static_cast<double>(_X);
  } else if (_XSize > 0 && this->_Input->XSize() > 0. && this->_Input->X() > 1) {
    attr._x  = iceil(this->_Input->X() * this->_Input->XSize() / this->_XSize);
    attr._dx = _XSize;
  }

  if (_Y > 0 && _YSize > 0) {
    attr._y  = _Y;
    attr._dy = _YSize;
  } else if (_Y > 0) {
    attr._y  = _Y;
    attr._dy = this->_Input->Y() * this->_Input->YSize() / static_cast<double>(_Y);
  } else if (_YSize > 0 && this->_Input->YSize() > 0. && this->_Input->Y() > 1) {
    attr._y  = iceil(this->_Input->Y() * this->_Input->YSize() / this->_YSize);
    attr._dy = _YSize;
  }

  if (_Z > 0 && _ZSize > 0) {
    attr._z  = _Z;
    attr._dz = _ZSize;
  } else if (_Z > 0) {
    attr._z  = _Z;
    attr._dz = this->_Input->Z() * this->_Input->ZSize() / static_cast<double>(_Z);
  } else if (_ZSize > 0 && this->_Input->ZSize() > 0. && this->_Input->Z() > 1) {
    attr._z  = iceil(this->_Input->Z() * this->_Input->ZSize() / this->_ZSize);
    attr._dz = _ZSize;
  }

  this->_Output->Initialize(attr);
}

// ---------------------------------------------------------------------------
// Serial/Multi-threaded body of Resampling::Run method
class ResamplingRun
{
public:
  // -------------------------------------------------------------------------
  // Data members
  const BaseImage          *_Input;
  BaseImage                *_Output;
  InterpolateImageFunction *_Interpolator;
  mutable int               _T;

  // -------------------------------------------------------------------------
  /// Default constructor
  ResamplingRun()
  :
    _Input(NULL),
    _Output(NULL),
    _Interpolator(NULL),
    _T(0)
  {}

  // -------------------------------------------------------------------------
  /// Copy constructor
  ResamplingRun(const ResamplingRun &other)
  :
    _Input(other._Input),
    _Output(other._Output),
    _Interpolator(other._Interpolator),
    _T(other._T)
  {}

  // -------------------------------------------------------------------------
  /// Resamples the image within given output region for frame _T
  void operator() (const blocked_range3d<int> &r) const
  {
    double x, y, z;
    for (int k = r.pages().begin(); k != r.pages().end(); ++k)
    for (int j = r.rows ().begin(); j != r.rows ().end(); ++j)
    for (int i = r.cols ().begin(); i != r.cols ().end(); ++i) {
      x = i, y = j, z = k;
      _Output->ImageToWorld(x, y, z);
      _Input ->WorldToImage(x, y, z);
      _Output->PutAsDouble(i, j, k, _T, _Interpolator->Evaluate(x, y, z, _T));
    }
  }

  // -------------------------------------------------------------------------
  /// Resamples the image for the given range of output frames
  void operator() (const blocked_range<int> &r) const
  {
    blocked_range3d<int> voxels(0, _Output->Z(),
                                0, _Output->Y(),
                                0, _Output->X());

    for (_T = r.begin(); _T != r.end(); _T++) {
      parallel_for(voxels, ResamplingRun(*this));
    }
  }

};

// ---------------------------------------------------------------------------
template <class VoxelType>
void Resampling<VoxelType>::Run()
{
  MIRTK_START_TIMING();

  this->Initialize();

  ResamplingRun body;
  body._Input        = this->_Input;
  body._Output       = this->_Output;
  body._Interpolator = this->_Interpolator;
  body(blocked_range<int>(0, this->_Output->T()));

  this->Finalize();

  MIRTK_DEBUG_TIMING(5, this->NameOfClass());
}

// ---------------------------------------------------------------------------
// Explicit template instantiations
template class Resampling<char>;
template class Resampling<unsigned char>;
template class Resampling<short>;
template class Resampling<unsigned short>;
template class Resampling<int>;
template class Resampling<float>;
template class Resampling<double>;

} // namespace mirtk
<commit_msg>enh: Use Throw instead of exit [Image]<commit_after>/*
 * Medical Image Registration ToolKit (MIRTK)
 *
 * Copyright 2008-2015 Imperial College London
 * Copyright 2008-2013 Daniel Rueckert, Julia Schnabel
 * Copyright 2013-2015 Andreas Schuh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "mirtk/Resampling.h"

#include "mirtk/Parallel.h"
#include "mirtk/Profiling.h"
#include "mirtk/InterpolateImageFunction.h"

namespace mirtk {

// ---------------------------------------------------------------------------
template <class VoxelType>
Resampling<VoxelType>::Resampling(double dx, double dy, double dz)
{
  _X     = 0;
  _Y     = 0;
  _Z     = 0;
  _XSize = dx;
  _YSize = dy;
  _ZSize = dz;
  _Interpolator = NULL;
}

// ---------------------------------------------------------------------------
template <class VoxelType>
Resampling<VoxelType>::Resampling(int x, int y, int z)
{
  _X     = x;
  _Y     = y;
  _Z     = z;
  _XSize = 0;
  _YSize = 0;
  _ZSize = 0;
  _Interpolator = NULL;
}

// ---------------------------------------------------------------------------
template <class VoxelType>
Resampling<VoxelType>::Resampling(int x, int y, int z, double dx, double dy, double dz)
{
  _X     = x;
  _Y     = y;
  _Z     = z;
  _XSize = dx;
  _YSize = dy;
  _ZSize = dz;
  _Interpolator = NULL;
}

// ---------------------------------------------------------------------------
template <class VoxelType>
void Resampling<VoxelType>::Initialize()
{
  // Initialize base class
  ImageToImage<VoxelType>::Initialize(false);

  // Set up interpolator
  if (_Interpolator == nullptr) {
    Throw(ERR_InvalidArgument, __FUNCTION__, "Interpolator must be set");
  }
  _Interpolator->Input(this->_Input);
  _Interpolator->Initialize();

  // Initialize output image
  this->InitializeOutput();
}

// ---------------------------------------------------------------------------
template <class VoxelType>
void Resampling<VoxelType>::InitializeOutput()
{
  ImageAttributes attr = this->_Input->Attributes();

  if (_X > 0 && _XSize > 0) {
    attr._x  = _X;
    attr._dx = _XSize;
  } else if (_X > 0) {
    attr._x  = _X;
    attr._dx = this->_Input->X() * this->_Input->XSize() / static_cast<double>(_X);
  } else if (_XSize > 0 && this->_Input->XSize() > 0. && this->_Input->X() > 1) {
    attr._x  = iceil(this->_Input->X() * this->_Input->XSize() / this->_XSize);
    attr._dx = _XSize;
  }

  if (_Y > 0 && _YSize > 0) {
    attr._y  = _Y;
    attr._dy = _YSize;
  } else if (_Y > 0) {
    attr._y  = _Y;
    attr._dy = this->_Input->Y() * this->_Input->YSize() / static_cast<double>(_Y);
  } else if (_YSize > 0 && this->_Input->YSize() > 0. && this->_Input->Y() > 1) {
    attr._y  = iceil(this->_Input->Y() * this->_Input->YSize() / this->_YSize);
    attr._dy = _YSize;
  }

  if (_Z > 0 && _ZSize > 0) {
    attr._z  = _Z;
    attr._dz = _ZSize;
  } else if (_Z > 0) {
    attr._z  = _Z;
    attr._dz = this->_Input->Z() * this->_Input->ZSize() / static_cast<double>(_Z);
  } else if (_ZSize > 0 && this->_Input->ZSize() > 0. && this->_Input->Z() > 1) {
    attr._z  = iceil(this->_Input->Z() * this->_Input->ZSize() / this->_ZSize);
    attr._dz = _ZSize;
  }

  this->_Output->Initialize(attr);
}

// ---------------------------------------------------------------------------
// Serial/Multi-threaded body of Resampling::Run method
class ResamplingRun
{
public:
  // -------------------------------------------------------------------------
  // Data members
  const BaseImage          *_Input;
  BaseImage                *_Output;
  InterpolateImageFunction *_Interpolator;
  mutable int               _T;

  // -------------------------------------------------------------------------
  /// Default constructor
  ResamplingRun()
  :
    _Input(NULL),
    _Output(NULL),
    _Interpolator(NULL),
    _T(0)
  {}

  // -------------------------------------------------------------------------
  /// Copy constructor
  ResamplingRun(const ResamplingRun &other)
  :
    _Input(other._Input),
    _Output(other._Output),
    _Interpolator(other._Interpolator),
    _T(other._T)
  {}

  // -------------------------------------------------------------------------
  /// Resamples the image within given output region for frame _T
  void operator() (const blocked_range3d<int> &r) const
  {
    double x, y, z;
    for (int k = r.pages().begin(); k != r.pages().end(); ++k)
    for (int j = r.rows ().begin(); j != r.rows ().end(); ++j)
    for (int i = r.cols ().begin(); i != r.cols ().end(); ++i) {
      x = i, y = j, z = k;
      _Output->ImageToWorld(x, y, z);
      _Input ->WorldToImage(x, y, z);
      _Output->PutAsDouble(i, j, k, _T, _Interpolator->Evaluate(x, y, z, _T));
    }
  }

  // -------------------------------------------------------------------------
  /// Resamples the image for the given range of output frames
  void operator() (const blocked_range<int> &r) const
  {
    blocked_range3d<int> voxels(0, _Output->Z(),
                                0, _Output->Y(),
                                0, _Output->X());

    for (_T = r.begin(); _T != r.end(); _T++) {
      parallel_for(voxels, ResamplingRun(*this));
    }
  }

};

// ---------------------------------------------------------------------------
template <class VoxelType>
void Resampling<VoxelType>::Run()
{
  MIRTK_START_TIMING();

  this->Initialize();

  ResamplingRun body;
  body._Input        = this->_Input;
  body._Output       = this->_Output;
  body._Interpolator = this->_Interpolator;
  body(blocked_range<int>(0, this->_Output->T()));

  this->Finalize();

  MIRTK_DEBUG_TIMING(5, this->NameOfClass());
}

// ---------------------------------------------------------------------------
// Explicit template instantiations
template class Resampling<char>;
template class Resampling<unsigned char>;
template class Resampling<short>;
template class Resampling<unsigned short>;
template class Resampling<int>;
template class Resampling<float>;
template class Resampling<double>;

} // namespace mirtk
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
#define DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH

#include <vector>
#include <type_traits>

#include <dune/common/deprecated.hh>

#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container/interfaces.hh>

#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/mapper/interface.hh>

namespace Dune {
namespace GDT {

template <class VectorImp>
class ConstLocalDoFVector
{
  static_assert(
      std::is_base_of<Stuff::LA::VectorInterface<typename VectorImp::Traits, typename VectorImp::Traits::ScalarType>,
                      VectorImp>::value,
      "VectorImp has to be derived from Stuff::LA::VectorInterface!");

public:
  typedef VectorImp VectorType;
  typedef typename VectorType::ScalarType ScalarType;

  template <class M, class EntityType>
  ConstLocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, const VectorType& vector)
    : vector_(vector)
    , indices_(mapper.numDofs(entity))
  {
    mapper.globalIndices(entity, indices_);
  }

  ~ConstLocalDoFVector()
  {
  }

  size_t size() const
  {
    return indices_.size();
  }

  ScalarType get(const size_t ii) const
  {
    assert(ii < indices_.size());
    return vector_.get_entry(indices_[ii]);
  }

private:
  const VectorType& vector_;

protected:
  Dune::DynamicVector<size_t> indices_;

private:
  template <class V>
  friend std::ostream& operator<<(std::ostream& /*out*/, const ConstLocalDoFVector<V>& /*vector*/);
}; // class ConstLocalDoFVector

template <class V>
std::ostream& operator<<(std::ostream& out, const ConstLocalDoFVector<V>& vector)
{
  out << "[";
  const size_t sz = vector.size();
  if (sz > 0) {
    out << vector.get(0);
    for (size_t ii = 1; ii < sz; ++ii)
      out << ", " << vector.get(ii);
  } else
    out << " ";
  out << "]";
  return out;
} // ... operator<<(...)

template <class VectorImp>
class LocalDoFVector : public ConstLocalDoFVector<VectorImp>
{
  typedef ConstLocalDoFVector<VectorImp> BaseType;

public:
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::ScalarType ScalarType;

  template <class M, class EntityType>
  LocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, VectorType& vector)
    : BaseType(mapper, entity, vector)
    , vector_(vector)
  {
  }

  ~LocalDoFVector()
  {
  }

  void set(const size_t ii, const ScalarType& val)
  {
    assert(ii < indices_.size());
    vector_.set_entry(indices_[ii], val);
  }

  void add(const size_t ii, const ScalarType& val)
  {
    assert(ii < indices_.size());
    vector_.add_to_entry(indices_[ii], val);
  }

  template <class OtherVectorImp>
  void add(const OtherVectorImp& vector)
  {
    assert(vector.size() == indices_.size());
    for (size_t ii = 0; ii < indices_.size(); ++ii)
      add(ii, vector[ii]);
  }

private:
  using BaseType::indices_;
  VectorType& vector_;
}; // class LocalDoFVector

template <class SpaceImp, class VectorImp>
class ConstLocalDiscreteFunction
    : public Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                           SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
                                           SpaceImp::dimRangeCols>
{
  static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits, SpaceImp::dimDomain, SpaceImp::dimRange,
                                               SpaceImp::dimRangeCols>,
                                SpaceImp>::value,
                "SpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits,
                                                                 typename VectorImp::Traits::ScalarType>,
                                VectorImp>::value,
                "VectorImp has to be derived from Stuff::LA::VectorInterface!");
  static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value,
                "Types do not match!");
  typedef Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                        SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
                                        SpaceImp::dimRangeCols> BaseType;
  typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef SpaceImp SpaceType;
  typedef VectorImp VectorType;
  typedef typename BaseType::EntityType EntityType;

  typedef typename BaseType::DomainFieldType DomainFieldType;
  static const size_t dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType DomainType;

  typedef typename BaseType::RangeFieldType RangeFieldType;
  static const size_t dimRangeRows = BaseType::dimRangeCols;
  static const size_t dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeType RangeType;

  typedef typename BaseType::JacobianRangeType JacobianRangeType;

private:
  typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;

public:
  typedef ConstLocalDoFVector<VectorType> ConstLocalDoFVectorType;

  ConstLocalDiscreteFunction(const SpaceType& space, const VectorType& globalVector, const EntityType& ent)
    : BaseType(ent)
    , space_(space)
    , base_(new BaseFunctionSetType(space_.base_function_set(this->entity())))
    , localVector_(new ConstLocalDoFVectorType(space_.mapper(), this->entity(), globalVector))
  {
    assert(localVector_->size() == base_->size());
  }

  ConstLocalDiscreteFunction(ThisType&& source) = default;

  ConstLocalDiscreteFunction(const ThisType& other) = delete;

  ThisType& operator=(const ThisType& other) = delete;

  virtual ~ConstLocalDiscreteFunction()
  {
  }

  const SpaceType& space() const
  {
    return space_;
  }

  const DUNE_DEPRECATED_MSG("Use basis() instead (05.07.2015)!") BaseFunctionSetType& base() const
  {
    return basis();
  }

  const BaseFunctionSetType& basis() const
  {
    return *base_;
  }

  const ConstLocalDoFVectorType& vector() const
  {
    return *localVector_;
  }

  virtual size_t order() const override
  {
    return base_->order();
  }

  virtual void evaluate(const DomainType& xx, RangeType& ret) const override
  {
    assert(this->is_a_valid_point(xx));
    ret *= 0.0;
    std::vector<RangeType> tmpBaseValues(base_->size(), RangeType(0));
    assert(localVector_->size() == tmpBaseValues.size());
    base_->evaluate(xx, tmpBaseValues);
    for (size_t ii = 0; ii < localVector_->size(); ++ii) {
      tmpBaseValues[ii] *= localVector_->get(ii);
      ret += tmpBaseValues[ii];
    }
  } // ... evaluate(...)

  virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const override
  {
    assert(this->is_a_valid_point(xx));
    ret *= RangeFieldType(0);
    std::vector<JacobianRangeType> tmpBaseJacobianValues(base_->size(), JacobianRangeType(0));
    assert(localVector_->size() == tmpBaseJacobianValues.size());
    base_->jacobian(xx, tmpBaseJacobianValues);
    for (size_t ii = 0; ii < localVector_->size(); ++ii) {
      tmpBaseJacobianValues[ii] *= localVector_->get(ii);
      ret += tmpBaseJacobianValues[ii];
    }
  } // ... jacobian(...)

  using BaseType::evaluate;
  using BaseType::jacobian;

protected:
  const SpaceType& space_;
  std::unique_ptr<const BaseFunctionSetType> base_;
  std::unique_ptr<const ConstLocalDoFVectorType> localVector_;
}; // class ConstLocalDiscreteFunction

template <class SpaceImp, class VectorImp>
class LocalDiscreteFunction : public ConstLocalDiscreteFunction<SpaceImp, VectorImp>
{
  typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> BaseType;
  typedef LocalDiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef typename BaseType::SpaceType SpaceType;
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::EntityType EntityType;

  typedef typename BaseType::DomainFieldType DomainFieldType;
  static const size_t dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType DomainType;

  typedef typename BaseType::RangeFieldType RangeFieldType;
  static const size_t dimRangeRows = BaseType::dimRangeCols;
  static const size_t dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeType RangeType;

  typedef typename BaseType::JacobianRangeType JacobianRangeType;

private:
  typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;

public:
  typedef LocalDoFVector<VectorType> LocalDoFVectorType;

  LocalDiscreteFunction(const SpaceType& space, VectorType& globalVector, const EntityType& ent)
    : BaseType(space, globalVector, ent)
    , localVector_(new LocalDoFVectorType(space_.mapper(), entity_, globalVector))
  {
    assert(localVector_->size() == base_->size());
  }

  //! previous comment questioned validity, defaulting this doesn't touch that question
  LocalDiscreteFunction(ThisType&& source) = default;

  LocalDiscreteFunction(const ThisType& other) = delete;

  ThisType& operator=(const ThisType& other) = delete;

  virtual ~LocalDiscreteFunction()
  {
  }

  LocalDoFVectorType& vector()
  {
    return *localVector_;
  }

private:
  using BaseType::space_;
  using BaseType::entity_;
  using BaseType::base_;
  std::unique_ptr<LocalDoFVectorType> localVector_;
}; // class LocalDiscreteFunction

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
<commit_msg>[discretefunction.local] performance optimization for fv spaces<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
#define DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH

#include <vector>
#include <type_traits>

#include <dune/common/deprecated.hh>

#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container/interfaces.hh>

#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/mapper/interface.hh>

namespace Dune {
namespace GDT {

template <class VectorImp>
class ConstLocalDoFVector
{
  static_assert(
      std::is_base_of<Stuff::LA::VectorInterface<typename VectorImp::Traits, typename VectorImp::Traits::ScalarType>,
                      VectorImp>::value,
      "VectorImp has to be derived from Stuff::LA::VectorInterface!");

public:
  typedef VectorImp VectorType;
  typedef typename VectorType::ScalarType ScalarType;

  template <class M, class EntityType>
  ConstLocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, const VectorType& vector)
    : vector_(vector)
    , indices_(mapper.numDofs(entity))
  {
    mapper.globalIndices(entity, indices_);
  }

  ~ConstLocalDoFVector()
  {
  }

  size_t size() const
  {
    return indices_.size();
  }

  ScalarType get(const size_t ii) const
  {
    assert(ii < indices_.size());
    return vector_.get_entry(indices_[ii]);
  }

private:
  const VectorType& vector_;

protected:
  Dune::DynamicVector<size_t> indices_;

private:
  template <class V>
  friend std::ostream& operator<<(std::ostream& /*out*/, const ConstLocalDoFVector<V>& /*vector*/);
}; // class ConstLocalDoFVector

template <class V>
std::ostream& operator<<(std::ostream& out, const ConstLocalDoFVector<V>& vector)
{
  out << "[";
  const size_t sz = vector.size();
  if (sz > 0) {
    out << vector.get(0);
    for (size_t ii = 1; ii < sz; ++ii)
      out << ", " << vector.get(ii);
  } else
    out << " ";
  out << "]";
  return out;
} // ... operator<<(...)

template <class VectorImp>
class LocalDoFVector : public ConstLocalDoFVector<VectorImp>
{
  typedef ConstLocalDoFVector<VectorImp> BaseType;

public:
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::ScalarType ScalarType;

  template <class M, class EntityType>
  LocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, VectorType& vector)
    : BaseType(mapper, entity, vector)
    , vector_(vector)
  {
  }

  ~LocalDoFVector()
  {
  }

  void set(const size_t ii, const ScalarType& val)
  {
    assert(ii < indices_.size());
    vector_.set_entry(indices_[ii], val);
  }

  void add(const size_t ii, const ScalarType& val)
  {
    assert(ii < indices_.size());
    vector_.add_to_entry(indices_[ii], val);
  }

  template <class OtherVectorImp>
  void add(const OtherVectorImp& vector)
  {
    assert(vector.size() == indices_.size());
    for (size_t ii = 0; ii < indices_.size(); ++ii)
      add(ii, vector[ii]);
  }

private:
  using BaseType::indices_;
  VectorType& vector_;
}; // class LocalDoFVector

template <class SpaceImp, class VectorImp>
class ConstLocalDiscreteFunction
    : public Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                           SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
                                           SpaceImp::dimRangeCols>
{
  static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits, SpaceImp::dimDomain, SpaceImp::dimRange,
                                               SpaceImp::dimRangeCols>,
                                SpaceImp>::value,
                "SpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits,
                                                                 typename VectorImp::Traits::ScalarType>,
                                VectorImp>::value,
                "VectorImp has to be derived from Stuff::LA::VectorInterface!");
  static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value,
                "Types do not match!");
  typedef Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                        SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
                                        SpaceImp::dimRangeCols> BaseType;
  typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef SpaceImp SpaceType;
  typedef VectorImp VectorType;
  typedef typename BaseType::EntityType EntityType;

  typedef typename BaseType::DomainFieldType DomainFieldType;
  static const size_t dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType DomainType;

  typedef typename BaseType::RangeFieldType RangeFieldType;
  static const size_t dimRangeRows = BaseType::dimRangeCols;
  static const size_t dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeType RangeType;

  typedef typename BaseType::JacobianRangeType JacobianRangeType;

private:
  typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;

public:
  typedef ConstLocalDoFVector<VectorType> ConstLocalDoFVectorType;

  ConstLocalDiscreteFunction(const SpaceType& space, const VectorType& globalVector, const EntityType& ent)
    : BaseType(ent)
    , space_(space)
    , base_(new BaseFunctionSetType(space_.base_function_set(this->entity())))
    , localVector_(new ConstLocalDoFVectorType(space_.mapper(), this->entity(), globalVector))
  {
    assert(localVector_->size() == base_->size());
  }

  ConstLocalDiscreteFunction(ThisType&& source) = default;

  ConstLocalDiscreteFunction(const ThisType& other) = delete;

  ThisType& operator=(const ThisType& other) = delete;

  virtual ~ConstLocalDiscreteFunction()
  {
  }

  const SpaceType& space() const
  {
    return space_;
  }

  const DUNE_DEPRECATED_MSG("Use basis() instead (05.07.2015)!") BaseFunctionSetType& base() const
  {
    return basis();
  }

  const BaseFunctionSetType& basis() const
  {
    return *base_;
  }

  const ConstLocalDoFVectorType& vector() const
  {
    return *localVector_;
  }

  virtual size_t order() const override
  {
    return base_->order();
  }

  void evaluate(const DomainType& xx, RangeType& ret) const override final
  {
    assert(this->is_a_valid_point(xx));
    if (!(GDT::is_fv_space<SpaceType>::value || GDT::is_product_fv_space<SpaceType>::value)) {
      std::fill(ret.begin(), ret.end(), RangeFieldType(0));
      std::vector<RangeType> tmpBaseValues(base_->size(), RangeType(0));
      assert(localVector_->size() == tmpBaseValues.size());
      base_->evaluate(xx, tmpBaseValues);
      for (size_t ii = 0; ii < localVector_->size(); ++ii) {
        ret.axpy(localVector_->get(ii), tmpBaseValues[ii]);
      }
    } else {
      for (size_t ii = 0; ii < localVector_->size(); ++ii)
        ret[ii] = localVector_->get(ii);
    }
  } // ... evaluate(...)

  virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const override final
  {
    assert(this->is_a_valid_point(xx));
    if (!(GDT::is_fv_space<SpaceType>::value || GDT::is_product_fv_space<SpaceType>::value)) {
      std::fill(ret.begin(), ret.end(), RangeFieldType(0));
      std::vector<JacobianRangeType> tmpBaseJacobianValues(base_->size(), JacobianRangeType(0));
      assert(localVector_->size() == tmpBaseJacobianValues.size());
      base_->jacobian(xx, tmpBaseJacobianValues);
      for (size_t ii = 0; ii < localVector_->size(); ++ii)
        ret.axpy(localVector_->get(ii), tmpBaseJacobianValues[ii]);
    } else {
      ret = JacobianRangeType(0);
    }
  } // ... jacobian(...)

  using BaseType::evaluate;
  using BaseType::jacobian;

protected:
  const SpaceType& space_;
  std::unique_ptr<const BaseFunctionSetType> base_;
  std::unique_ptr<const ConstLocalDoFVectorType> localVector_;
}; // class ConstLocalDiscreteFunction

template <class SpaceImp, class VectorImp>
class LocalDiscreteFunction : public ConstLocalDiscreteFunction<SpaceImp, VectorImp>
{
  typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> BaseType;
  typedef LocalDiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef typename BaseType::SpaceType SpaceType;
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::EntityType EntityType;

  typedef typename BaseType::DomainFieldType DomainFieldType;
  static const size_t dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType DomainType;

  typedef typename BaseType::RangeFieldType RangeFieldType;
  static const size_t dimRangeRows = BaseType::dimRangeCols;
  static const size_t dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeType RangeType;

  typedef typename BaseType::JacobianRangeType JacobianRangeType;

private:
  typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;

public:
  typedef LocalDoFVector<VectorType> LocalDoFVectorType;

  LocalDiscreteFunction(const SpaceType& space, VectorType& globalVector, const EntityType& ent)
    : BaseType(space, globalVector, ent)
    , localVector_(new LocalDoFVectorType(space_.mapper(), entity_, globalVector))
  {
    assert(localVector_->size() == base_->size());
  }

  //! previous comment questioned validity, defaulting this doesn't touch that question
  LocalDiscreteFunction(ThisType&& source) = default;

  LocalDiscreteFunction(const ThisType& other) = delete;

  ThisType& operator=(const ThisType& other) = delete;

  virtual ~LocalDiscreteFunction()
  {
  }

  LocalDoFVectorType& vector()
  {
    return *localVector_;
  }

private:
  using BaseType::space_;
  using BaseType::entity_;
  using BaseType::base_;
  std::unique_ptr<LocalDoFVectorType> localVector_;
}; // class LocalDiscreteFunction

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
<|endoftext|>


<commit_before>//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------

#include "ConnectionManager.h"
#include "Capture.h"
#include "TcpClient.h"
#include "TcpServer.h"
#include "TimerManager.h"
#include "Serialization.h"
#include "TestRemoteMessages.h"
#include "EventBuffer.h"
#include "ProcessUtils.h"
#include "LinuxPerf.h"

#if __linux__
#include "LinuxUtils.h"
#endif

#include <fstream>
#include <streambuf>
#include <sstream>
#include <iostream>

//-----------------------------------------------------------------------------
struct CrossPlatformMessage
{
    CrossPlatformMessage();

    void Fill();
    void Save();
    void Load();
    void Dump();

    std::string ToRaw();
    void FromRaw(const char* data, uint32_t size);

    ORBIT_SERIALIZABLE;
    std::wstring m_WName;
    uint32_t m_Id;
    std::string m_Name;
    std::vector<std::string> m_Strings;
    std::map<uint32_t, std::string> m_StringMap;
    std::string m_SerializationPath;
    uint32_t m_Size;
    uint32_t m_SizeOnSave;
};

//-----------------------------------------------------------------------------
CrossPlatformMessage::CrossPlatformMessage()
{
    static uint32_t id = 0;
    m_Id = ++id;
    m_Size = sizeof(CrossPlatformMessage);
    m_SizeOnSave = 0;
    m_SerializationPath = ws2s( Path::GetBasePath() ) + "xmsg.orbit";
    PRINT_VAR(m_SerializationPath);
}

//-----------------------------------------------------------------------------
ORBIT_SERIALIZE( CrossPlatformMessage, 1 )
{
    ORBIT_NVP_VAL( 0, m_Name );
    ORBIT_NVP_VAL( 0, m_Strings );
    ORBIT_NVP_VAL( 0, m_StringMap );
    ORBIT_NVP_VAL( 1, m_SizeOnSave );
    ORBIT_NVP_VAL( 1, m_Id );
    //ORBIT_NVP_VAL( 1, m_WName );
}

//-----------------------------------------------------------------------------
void CrossPlatformMessage::Fill()
{
    m_Name = "Orbit CrossPlatformMessage";
    m_WName = L"Wname";
    for( int i = 0 ; i < 1000; ++i )
    {
        std::string val = std::to_string(i);
        m_Strings.push_back(val);
        m_StringMap[i] = val;
    }
}

//-----------------------------------------------------------------------------
void CrossPlatformMessage::Save()
{
    std::ofstream myfile( m_SerializationPath, std::ios::binary );
    if( !myfile.fail() )
    {
        m_SizeOnSave = sizeof(CrossPlatformMessage);
        SCOPE_TIMER_LOG( Format( L"Saving cross platform message" ) );
        cereal::BinaryOutputArchive archive( myfile );
        archive(*this);
        myfile.close();
    }
}

//-----------------------------------------------------------------------------
std::string CrossPlatformMessage::ToRaw()
{
    m_SizeOnSave = sizeof(CrossPlatformMessage);
    std::stringstream buffer;
    cereal::BinaryOutputArchive archive( buffer );
    archive(*this);
    PRINT_VAR(buffer.str().size());
    return buffer.str();
}

void CrossPlatformMessage::FromRaw(const char* data, uint32_t size)
{
    PRINT_FUNC;
    PRINT_VAR(size);
    std::istringstream buffer(std::string(data, size));
    cereal::BinaryInputArchive inputAr( buffer );
    inputAr(*this);
}

//-----------------------------------------------------------------------------
void CrossPlatformMessage::Load()
{
    std::ifstream myfile( m_SerializationPath, std::ios::binary );
    if( !myfile.fail() )
    {
        cereal::BinaryInputArchive archive( myfile );
        archive(*this);
        myfile.close();
    }

    Dump();
}

//-----------------------------------------------------------------------------
void CrossPlatformMessage::Dump()
{
    PRINT_VAR(m_Name);
    for( std::string& str : m_Strings )
    {
        PRINT_VAR(str);
    }

    for( auto pair : m_StringMap )
    {
        PRINT_VAR(pair.first);
        PRINT_VAR(pair.second);
    }
}

//-----------------------------------------------------------------------------
ConnectionManager::ConnectionManager() : m_ExitRequested(false), m_IsRemote(false)
{
}

//-----------------------------------------------------------------------------
ConnectionManager::~ConnectionManager()
{
    TerminateThread();
}

//-----------------------------------------------------------------------------
void ConnectionManager::TerminateThread()
{
    if (m_Thread)
    {
        m_ExitRequested = true;
        m_Thread->join();
        m_Thread = nullptr;
    }
}

//-----------------------------------------------------------------------------
ConnectionManager& ConnectionManager::Get()
{
    static ConnectionManager instance;
    return instance;
}

//-----------------------------------------------------------------------------
void ConnectionManager::Init()
{
    SetupTestMessageHandler();
    SetupServerCallbacks();
}

//-----------------------------------------------------------------------------
void ConnectionManager::InitAsRemote(std::string a_Host)
{
    m_IsRemote = true;
    m_Host = a_Host;
    TerminateThread();
    m_Thread = std::make_unique<std::thread>(&ConnectionManager::ConnectionThread, this);

    //CrossPlatformMessage xmsg;
    //xmsg.Fill();
    //xmsg.Load();
}

//-----------------------------------------------------------------------------
void ConnectionManager::StartCaptureAsRemote()
{
    Capture::StartCapture();
}

//-----------------------------------------------------------------------------
void ConnectionManager::StopCaptureAsRemote()
{
    Capture::StopCapture();
}

//-----------------------------------------------------------------------------
void ConnectionManager::Stop()
{
    m_ExitRequested = true;
}

//-----------------------------------------------------------------------------
void ConnectionManager::SetupTestMessageHandler()
{
    GTcpServer->AddCallback( Msg_CrossPlatform, [=]( const Message & a_Msg )
    {
        CrossPlatformMessage msg;
        PRINT_VAR(a_Msg.m_Size);
        msg.FromRaw(a_Msg.m_Data, a_Msg.m_Size);
        msg.Dump();
    } );
}

//-----------------------------------------------------------------------------
void ConnectionManager::SetupClientCallbacks()
{
    GTcpClient->AddCallback( Msg_StartCapture, [=]( const Message & a_Msg )
    {
        StartCaptureAsRemote();
    } );

    GTcpClient->AddCallback( Msg_StopCapture, [=]( const Message & a_Msg )
    {
        StopCaptureAsRemote();
    } );
}

//-----------------------------------------------------------------------------
void ConnectionManager::SetupServerCallbacks()
{
    GTcpServer->AddCallback( Msg_RemotePerf, [=]( const Message & a_Msg )
    {
        PRINT_VAR(a_Msg.m_Size);
        std::istringstream buffer(std::string(a_Msg.m_Data, a_Msg.m_Size));
        LinuxPerf perf(0);
        perf.LoadPerfData(buffer);
    } );
}

//-----------------------------------------------------------------------------
void ConnectionManager::SendTestMessage()
{
    CrossPlatformMessage msg;
    msg.Fill();

    std::string rawMsg = msg.ToRaw();
    GTcpClient->Send(Msg_CrossPlatform, (void*)rawMsg.data(), rawMsg.size());

    //TestRemoteMessages::Get().Run();
}

//-----------------------------------------------------------------------------
void ConnectionManager::SendProcesses()
{
    ProcessList processList;
    std::string processData = SerializeObjectHumanReadable(processList);
    PRINT_VAR(processData);
    GTcpClient->Send(Msg_RemoteProcessList, (void*)processData.data(), processData.size());
}

//-----------------------------------------------------------------------------
void ConnectionManager::ConnectionThread()
{
    while (!m_ExitRequested)
    {
        if (!GTcpClient || !GTcpClient->IsValid())
        {
            GTcpClient = std::make_unique<TcpClient>(m_Host);
            if (GTcpClient->IsValid())
            {
                SetupClientCallbacks();
                GTimerManager = std::make_unique<TimerManager>(true);
            }
        }
        else
        {
            std::string msg("Hello from ConnectionManager");
            GTcpClient->Send(msg);

            SendProcesses();

            Sleep(2000);
        }
    }
}
<commit_msg>Make sure we the remote process list contains cpu utilization.<commit_after>//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------

#include "ConnectionManager.h"
#include "Capture.h"
#include "TcpClient.h"
#include "TcpServer.h"
#include "TimerManager.h"
#include "Serialization.h"
#include "TestRemoteMessages.h"
#include "EventBuffer.h"
#include "ProcessUtils.h"
#include "LinuxPerf.h"

#if __linux__
#include "LinuxUtils.h"
#endif

#include <fstream>
#include <streambuf>
#include <sstream>
#include <iostream>

//-----------------------------------------------------------------------------
struct CrossPlatformMessage
{
    CrossPlatformMessage();

    void Fill();
    void Save();
    void Load();
    void Dump();

    std::string ToRaw();
    void FromRaw(const char* data, uint32_t size);

    ORBIT_SERIALIZABLE;
    std::wstring m_WName;
    uint32_t m_Id;
    std::string m_Name;
    std::vector<std::string> m_Strings;
    std::map<uint32_t, std::string> m_StringMap;
    std::string m_SerializationPath;
    uint32_t m_Size;
    uint32_t m_SizeOnSave;
};

//-----------------------------------------------------------------------------
CrossPlatformMessage::CrossPlatformMessage()
{
    static uint32_t id = 0;
    m_Id = ++id;
    m_Size = sizeof(CrossPlatformMessage);
    m_SizeOnSave = 0;
    m_SerializationPath = ws2s( Path::GetBasePath() ) + "xmsg.orbit";
    PRINT_VAR(m_SerializationPath);
}

//-----------------------------------------------------------------------------
ORBIT_SERIALIZE( CrossPlatformMessage, 1 )
{
    ORBIT_NVP_VAL( 0, m_Name );
    ORBIT_NVP_VAL( 0, m_Strings );
    ORBIT_NVP_VAL( 0, m_StringMap );
    ORBIT_NVP_VAL( 1, m_SizeOnSave );
    ORBIT_NVP_VAL( 1, m_Id );
    //ORBIT_NVP_VAL( 1, m_WName );
}

//-----------------------------------------------------------------------------
void CrossPlatformMessage::Fill()
{
    m_Name = "Orbit CrossPlatformMessage";
    m_WName = L"Wname";
    for( int i = 0 ; i < 1000; ++i )
    {
        std::string val = std::to_string(i);
        m_Strings.push_back(val);
        m_StringMap[i] = val;
    }
}

//-----------------------------------------------------------------------------
void CrossPlatformMessage::Save()
{
    std::ofstream myfile( m_SerializationPath, std::ios::binary );
    if( !myfile.fail() )
    {
        m_SizeOnSave = sizeof(CrossPlatformMessage);
        SCOPE_TIMER_LOG( Format( L"Saving cross platform message" ) );
        cereal::BinaryOutputArchive archive( myfile );
        archive(*this);
        myfile.close();
    }
}

//-----------------------------------------------------------------------------
std::string CrossPlatformMessage::ToRaw()
{
    m_SizeOnSave = sizeof(CrossPlatformMessage);
    std::stringstream buffer;
    cereal::BinaryOutputArchive archive( buffer );
    archive(*this);
    PRINT_VAR(buffer.str().size());
    return buffer.str();
}

void CrossPlatformMessage::FromRaw(const char* data, uint32_t size)
{
    PRINT_FUNC;
    PRINT_VAR(size);
    std::istringstream buffer(std::string(data, size));
    cereal::BinaryInputArchive inputAr( buffer );
    inputAr(*this);
}

//-----------------------------------------------------------------------------
void CrossPlatformMessage::Load()
{
    std::ifstream myfile( m_SerializationPath, std::ios::binary );
    if( !myfile.fail() )
    {
        cereal::BinaryInputArchive archive( myfile );
        archive(*this);
        myfile.close();
    }

    Dump();
}

//-----------------------------------------------------------------------------
void CrossPlatformMessage::Dump()
{
    PRINT_VAR(m_Name);
    for( std::string& str : m_Strings )
    {
        PRINT_VAR(str);
    }

    for( auto pair : m_StringMap )
    {
        PRINT_VAR(pair.first);
        PRINT_VAR(pair.second);
    }
}

//-----------------------------------------------------------------------------
ConnectionManager::ConnectionManager() : m_ExitRequested(false), m_IsRemote(false)
{
}

//-----------------------------------------------------------------------------
ConnectionManager::~ConnectionManager()
{
    TerminateThread();
}

//-----------------------------------------------------------------------------
void ConnectionManager::TerminateThread()
{
    if (m_Thread)
    {
        m_ExitRequested = true;
        m_Thread->join();
        m_Thread = nullptr;
    }
}

//-----------------------------------------------------------------------------
ConnectionManager& ConnectionManager::Get()
{
    static ConnectionManager instance;
    return instance;
}

//-----------------------------------------------------------------------------
void ConnectionManager::Init()
{
    SetupTestMessageHandler();
    SetupServerCallbacks();
}

//-----------------------------------------------------------------------------
void ConnectionManager::InitAsRemote(std::string a_Host)
{
    m_IsRemote = true;
    m_Host = a_Host;
    TerminateThread();
    m_Thread = std::make_unique<std::thread>(&ConnectionManager::ConnectionThread, this);

    //CrossPlatformMessage xmsg;
    //xmsg.Fill();
    //xmsg.Load();
}

//-----------------------------------------------------------------------------
void ConnectionManager::StartCaptureAsRemote()
{
    Capture::StartCapture();
}

//-----------------------------------------------------------------------------
void ConnectionManager::StopCaptureAsRemote()
{
    Capture::StopCapture();
}

//-----------------------------------------------------------------------------
void ConnectionManager::Stop()
{
    m_ExitRequested = true;
}

//-----------------------------------------------------------------------------
void ConnectionManager::SetupTestMessageHandler()
{
    GTcpServer->AddCallback( Msg_CrossPlatform, [=]( const Message & a_Msg )
    {
        CrossPlatformMessage msg;
        PRINT_VAR(a_Msg.m_Size);
        msg.FromRaw(a_Msg.m_Data, a_Msg.m_Size);
        msg.Dump();
    } );
}

//-----------------------------------------------------------------------------
void ConnectionManager::SetupClientCallbacks()
{
    GTcpClient->AddCallback( Msg_StartCapture, [=]( const Message & a_Msg )
    {
        StartCaptureAsRemote();
    } );

    GTcpClient->AddCallback( Msg_StopCapture, [=]( const Message & a_Msg )
    {
        StopCaptureAsRemote();
    } );
}

//-----------------------------------------------------------------------------
void ConnectionManager::SetupServerCallbacks()
{
    GTcpServer->AddCallback( Msg_RemotePerf, [=]( const Message & a_Msg )
    {
        PRINT_VAR(a_Msg.m_Size);
        std::istringstream buffer(std::string(a_Msg.m_Data, a_Msg.m_Size));
        LinuxPerf perf(0);
        perf.LoadPerfData(buffer);
    } );
}

//-----------------------------------------------------------------------------
void ConnectionManager::SendTestMessage()
{
    CrossPlatformMessage msg;
    msg.Fill();

    std::string rawMsg = msg.ToRaw();
    GTcpClient->Send(Msg_CrossPlatform, (void*)rawMsg.data(), rawMsg.size());

    //TestRemoteMessages::Get().Run();
}

//-----------------------------------------------------------------------------
void ConnectionManager::SendProcesses()
{
    ProcessList processList;
    processList.UpdateCpuTimes();
    std::string processData = SerializeObjectHumanReadable(processList);
    PRINT_VAR(processData);
    GTcpClient->Send(Msg_RemoteProcessList, (void*)processData.data(), processData.size());
}

//-----------------------------------------------------------------------------
void ConnectionManager::ConnectionThread()
{
    while (!m_ExitRequested)
    {
        if (!GTcpClient || !GTcpClient->IsValid())
        {
            GTcpClient = std::make_unique<TcpClient>(m_Host);
            if (GTcpClient->IsValid())
            {
                SetupClientCallbacks();
                GTimerManager = std::make_unique<TimerManager>(true);
            }
        }
        else
        {
            std::string msg("Hello from ConnectionManager");
            GTcpClient->Send(msg);

            SendProcesses();

            Sleep(2000);
        }
    }
}
<|endoftext|>


<commit_before>#pragma once
#include <PluginFactory/details/NullPluginService.hpp>
#include <PluginFactory/details/PluginExtensionHelper.hpp>
#include <PluginFactory/details/PluginHandle.hpp>
#include <PluginFactory/details/PolicyHolder.hpp>
#include <PluginFactory/details/PluginLoader.hpp>
#include <PluginFactory/details/PolicyProperties.hpp>
#include <PluginFactory/Exceptions.hpp>

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>

#include <memory>
#include <string>
#include <unordered_map>
#include <vector>

namespace PluginFactory {

    // A tag type to indicate we want to create a std::shared_ptr of the plugin
    // rather than std::unique_ptr
    struct AsSharedTagType {};

    // <PluginInterface> is the abstract interface of the plugin object itself. You'll need
    // a PluginFactory for each different type of plugin you wish to support.
    //
    // <PluginServiceInterface> is the interface given to the plugin to allow it to make
    // modifications to the main program. This is to encourage plugin developers not to
    // engage in crazy behavior like calling willy-nilly into the base process's code.
    //
    // NOTE: lifetime management using plugins can be difficult. It is essential
    // the PluginFactory stays in scope longer than any instanced plugin. Failure
    // to do so will most likely end in the process crashing.
    template<class PluginInterface, class PluginServiceInterface = details::NullPluginService, class PolicyOwnershipProperty = details::PolicyIsInternal>
    class PluginFactory : public details::PolicyHolder<PluginServiceInterface, PolicyOwnershipProperty>
    {
    public:
        static AsSharedTagType create_shared;

        // @pluginDirectory is the directory path to load plugins from.
        template<typename... Args>
        PluginFactory(const boost::filesystem::path& pluginDirectory, Args&&... pluginServiceArguments);

        void load();        // load all found plugins
        void load(const boost::filesystem::path& pluginPath);   // load a specific plugin (@pluginPath)

        void unload();      // unload all loaded plugins
        void unload(const boost::filesystem::path& pluginPath); // unload a specific plugin (@pluginPath)

        std::unique_ptr<PluginInterface> instance(const std::string& plugin);
        std::shared_ptr<PluginInterface> instance(const std::string& pluginName, AsSharedTagType /*create_shared*/);

        std::vector<std::string> availablePlugins() const;

    private:
        using PluginPath = std::string;
        using PluginInstanceMethod = std::function<PluginInterface* (PluginServiceInterface&)>;
        std::unordered_map<PluginPath, PluginHandle<PluginInterface, PluginServiceInterface>> plugins_;

        boost::filesystem::path pluginDirectory_;

        std::string pluginVersion_;
        std::string compilerToken_;
        std::string serviceVersion_;
    };

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    AsSharedTagType PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::create_shared;

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    template<typename... Args>
    PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::PluginFactory(const boost::filesystem::path& pluginDirectory, Args&&... pluginServiceArguments)
        : details::PolicyHolder<PluginServiceInterface, PolicyOwnershipProperty>(std::forward<Args>(pluginServiceArguments)...)
        , pluginDirectory_(pluginDirectory)
    {
        if(!boost::filesystem::exists(pluginDirectory_))
        {
            throw PluginPathDoesntExist(pluginDirectory_);
        }

        if(!boost::filesystem::is_directory(pluginDirectory_))
        {
            throw PluginPathIsntDirectory(pluginDirectory_);
        }
    }

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::load()
    {
        for(boost::filesystem::directory_iterator iter(pluginDirectory_), end; iter != end; ++iter)
        {
            const auto& path = iter->path();

            if(boost::filesystem::is_directory(path))
            {
                continue;
            }

            if(path.extension().string() == details::PluginExtensionHelper::extension())
            {
                load(path);
            }
        }
    }

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::load(const boost::filesystem::path& pluginPath)
    {
        try
        {
            details::PluginLoader loader(pluginPath);

            loader.validateCompiler(compilerToken_);
            loader.validatePluginVersion(pluginVersion_);
            loader.validatePluginServiceVersion(serviceVersion_);

            auto pluginHandle = loader.getPluginCreatorHandle<PluginInterface, PluginServiceInterface>();
            plugins_.emplace(pluginPath.string(), pluginHandle);
        }
        catch(const PluginLoaderValidationException& )
        {
            // ... eat the exception
        }
    }

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::unload()
    {
        plugins_.clear();
    }

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::unload(const boost::filesystem::path& pluginPath)
    {
        auto iter = plugins_.find(pluginPath.string());
        if(iter != plugins_.end())
        {
            plugins_.erase(iter);
        }
    }

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    std::unique_ptr<PluginInterface> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::instance(const std::string& pluginName)
    {
        std::unique_ptr<PluginInterface> p;

        auto iter = plugins_.find(pluginName);
        if(iter != plugins_.end())
        {
            auto& createPlugin = iter->second;
            p.reset(createPlugin(this->policy_));
        }

        return p;
    }

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    std::shared_ptr<PluginInterface> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::instance(const std::string& pluginName, AsSharedTagType)
    {
        std::shared_ptr<PluginInterface> p;

        auto iter = plugins_.find(pluginName);
        if(iter != plugins_.end())
        {
            auto& createPlugin = iter->second;
            p.reset(createPlugin(this->policy_));
        }

        return p;
    }

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    std::vector<std::string> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::availablePlugins() const
    {
        std::vector<std::string> plugins;
        plugins.reserve(plugins_.size());

        for(const auto& info : plugins_)
        {
            const auto& key = info.first;
            plugins.push_back(key);
        }

        return plugins;
    }
}
<commit_msg>PluginHandle -> details::PluginHandle, the namespace should have been there from the get go.<commit_after>#pragma once
#include <PluginFactory/details/NullPluginService.hpp>
#include <PluginFactory/details/PluginExtensionHelper.hpp>
#include <PluginFactory/details/PluginHandle.hpp>
#include <PluginFactory/details/PolicyHolder.hpp>
#include <PluginFactory/details/PluginLoader.hpp>
#include <PluginFactory/details/PolicyProperties.hpp>
#include <PluginFactory/Exceptions.hpp>

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>

#include <memory>
#include <string>
#include <unordered_map>
#include <vector>

namespace PluginFactory {

    // A tag type to indicate we want to create a std::shared_ptr of the plugin
    // rather than std::unique_ptr
    struct AsSharedTagType {};

    // <PluginInterface> is the abstract interface of the plugin object itself. You'll need
    // a PluginFactory for each different type of plugin you wish to support.
    //
    // <PluginServiceInterface> is the interface given to the plugin to allow it to make
    // modifications to the main program. This is to encourage plugin developers not to
    // engage in crazy behavior like calling willy-nilly into the base process's code.
    //
    // NOTE: lifetime management using plugins can be difficult. It is essential
    // the PluginFactory stays in scope longer than any instanced plugin. Failure
    // to do so will most likely end in the process crashing.
    template<class PluginInterface, class PluginServiceInterface = details::NullPluginService, class PolicyOwnershipProperty = details::PolicyIsInternal>
    class PluginFactory : public details::PolicyHolder<PluginServiceInterface, PolicyOwnershipProperty>
    {
    public:
        static AsSharedTagType create_shared;

        // @pluginDirectory is the directory path to load plugins from.
        template<typename... Args>
        PluginFactory(const boost::filesystem::path& pluginDirectory, Args&&... pluginServiceArguments);

        void load();        // load all found plugins
        void load(const boost::filesystem::path& pluginPath);   // load a specific plugin (@pluginPath)

        void unload();      // unload all loaded plugins
        void unload(const boost::filesystem::path& pluginPath); // unload a specific plugin (@pluginPath)

        std::unique_ptr<PluginInterface> instance(const std::string& plugin);
        std::shared_ptr<PluginInterface> instance(const std::string& pluginName, AsSharedTagType /*create_shared*/);

        std::vector<std::string> availablePlugins() const;

    private:
        using PluginPath = std::string;
        using PluginInstanceMethod = std::function<PluginInterface* (PluginServiceInterface&)>;
        std::unordered_map<PluginPath, details::PluginHandle<PluginInterface, PluginServiceInterface>> plugins_;

        boost::filesystem::path pluginDirectory_;

        std::string pluginVersion_;
        std::string compilerToken_;
        std::string serviceVersion_;
    };

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    AsSharedTagType PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::create_shared;

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    template<typename... Args>
    PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::PluginFactory(const boost::filesystem::path& pluginDirectory, Args&&... pluginServiceArguments)
        : details::PolicyHolder<PluginServiceInterface, PolicyOwnershipProperty>(std::forward<Args>(pluginServiceArguments)...)
        , pluginDirectory_(pluginDirectory)
    {
        if(!boost::filesystem::exists(pluginDirectory_))
        {
            throw PluginPathDoesntExist(pluginDirectory_);
        }

        if(!boost::filesystem::is_directory(pluginDirectory_))
        {
            throw PluginPathIsntDirectory(pluginDirectory_);
        }
    }

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::load()
    {
        for(boost::filesystem::directory_iterator iter(pluginDirectory_), end; iter != end; ++iter)
        {
            const auto& path = iter->path();

            if(boost::filesystem::is_directory(path))
            {
                continue;
            }

            if(path.extension().string() == details::PluginExtensionHelper::extension())
            {
                load(path);
            }
        }
    }

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::load(const boost::filesystem::path& pluginPath)
    {
        try
        {
            details::PluginLoader loader(pluginPath);

            loader.validateCompiler(compilerToken_);
            loader.validatePluginVersion(pluginVersion_);
            loader.validatePluginServiceVersion(serviceVersion_);

            auto pluginHandle = loader.getPluginCreatorHandle<PluginInterface, PluginServiceInterface>();
            plugins_.emplace(pluginPath.string(), pluginHandle);
        }
        catch(const PluginLoaderValidationException& )
        {
            // ... eat the exception
        }
    }

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::unload()
    {
        plugins_.clear();
    }

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::unload(const boost::filesystem::path& pluginPath)
    {
        auto iter = plugins_.find(pluginPath.string());
        if(iter != plugins_.end())
        {
            plugins_.erase(iter);
        }
    }

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    std::unique_ptr<PluginInterface> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::instance(const std::string& pluginName)
    {
        std::unique_ptr<PluginInterface> p;

        auto iter = plugins_.find(pluginName);
        if(iter != plugins_.end())
        {
            auto& createPlugin = iter->second;
            p.reset(createPlugin(this->policy_));
        }

        return p;
    }

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    std::shared_ptr<PluginInterface> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::instance(const std::string& pluginName, AsSharedTagType)
    {
        std::shared_ptr<PluginInterface> p;

        auto iter = plugins_.find(pluginName);
        if(iter != plugins_.end())
        {
            auto& createPlugin = iter->second;
            p.reset(createPlugin(this->policy_));
        }

        return p;
    }

    template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
    std::vector<std::string> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::availablePlugins() const
    {
        std::vector<std::string> plugins;
        plugins.reserve(plugins_.size());

        for(const auto& info : plugins_)
        {
            const auto& key = info.first;
            plugins.push_back(key);
        }

        return plugins;
    }
}
<|endoftext|>


<commit_before>/*
Author: Vytautas Vislavicius
Extention of Generic Flow (https://arxiv.org/abs/1312.3572)
*/
#include "AliGFWCuts.h"
const Int_t AliGFWCuts::fNTrackFlags=9;
const Int_t AliGFWCuts::fNEventFlags=8;
AliGFWCuts::AliGFWCuts():
  fSystFlag(0),
  fFilterBit(96),
  fDCAxyCut(7),
  fDCAzCut(2),
  fTPCNcls(70),
  fVtxZ(10),
  fEta(0.8),
  fRequiresExtraWeight(kTRUE)
{
};
AliGFWCuts::~AliGFWCuts() {
};
Int_t AliGFWCuts::AcceptTrack(AliAODTrack* l_Tr, Double_t* l_DCA, const Int_t &BitShift, const Bool_t &lDisableDCAxyCheck) {
  if(TMath::Abs(l_Tr->Eta())>fEta) return 0;
  if(!l_Tr->TestFilterBit(fFilterBit)) return 0;
  if(fFilterBit!=2) {//Check is not valid for ITSsa tracks
    if(l_Tr->GetTPCNclsF()<fTPCNcls) return 0;
  } else {
    UInt_t status = l_Tr->GetStatus();
    if ((status&AliESDtrack::kITSrefit)==0) return 0;
    if ((status & AliESDtrack::kITSin) == 0 || (status & AliESDtrack::kTPCin)) return 0;
  };
  if(!l_DCA) return 1<<BitShift;
  if(l_DCA[0]>fDCAzCut) return 0;
  if(lDisableDCAxyCheck) return 1<<BitShift;
  Double_t DCAxycut;
  if(fFilterBit!=2) DCAxycut = 0.0105+0.0350/TMath::Power(l_Tr->Pt(),1.1);//*fDCAxyCut/7.; //TPC tracks and my ITS cuts
  else DCAxycut = 0.0231+0.0315/TMath::Power(l_Tr->Pt(),1.3);
  if(l_DCA[1]>DCAxycut*(fDCAxyCut/7.))
    return 0;
  return 1<<BitShift;
};

Int_t AliGFWCuts::AcceptParticle(AliVParticle *l_Pa, Int_t BitShift, Double_t ptLow, Double_t ptHigh) {
  if(TMath::Abs(l_Pa->Eta())>fEta) return 0;
  if(ptLow>0) if(l_Pa->Pt()<ptLow) return 0;
  if(ptHigh>0) if(l_Pa->Pt()>ptHigh) return 0;
  return 1<<BitShift;
};
Int_t AliGFWCuts::AcceptVertex(AliAODEvent *l_Ev, Int_t BitShift) {
  Double_t lvtxz = TMath::Abs(l_Ev->GetPrimaryVertex()->GetZ());
  if(lvtxz>fVtxZ) return 0;
  return 1<<BitShift;
};
void AliGFWCuts::ResetCuts() {
  fSystFlag=0;
  fFilterBit=96;
  fDCAxyCut=7;
  fDCAzCut=2;
  fTPCNcls=70;
  fVtxZ=10;
  fEta=0.8;
  fRequiresExtraWeight=kTRUE;
};
void AliGFWCuts::PrintSetup() {
  printf("**********\n");
  printf("Syst. flag: %i\n",fSystFlag);
  printf("Eta: %f\n",fEta);
  printf("(Flag 1) Filter bit: %i\n",fFilterBit);
  printf("(Flag 2,3) DCAxy cut: %2.0f sigma\n",fDCAxyCut);
  printf("(Flag 4,5) DCAz cut: %f\n",fDCAzCut);
  printf("(Flag 6-8) TPC Ncls: %i\n",fTPCNcls);
  printf("(Flag 9) ITS tracks\n");
  printf("Rest of the flags are global per event. Total flag = %i + vtx/ev flag\n",fNTrackFlags);
  printf("(Flag 1-3) Vertex selection: |z|<%2.1f\n",fVtxZ);
  printf("(Flag 4-5) CL1, CL2 multi. estimator (no weights)\n");
  printf("(Flag 6) pile-up 15000 (-> 1500) cut\n");
  //printf("(Flag 12, disabled) ITS tracks (filter bit %i, TPC Ncls = %i)\n",fFilterBit,fTPCNcls);
  printf("**********\n");
};
void AliGFWCuts::SetupTrackCuts(Int_t sysflag) {
  switch(sysflag) {
  case 1:
    fFilterBit=768;
    fRequiresExtraWeight=kTRUE;
    break;
  case 2:
    fDCAxyCut=10.;
    fRequiresExtraWeight=kTRUE;
    break;
  case 3:
    fDCAxyCut=4.;
    fRequiresExtraWeight=kTRUE;
    break;
  case 4:
    fDCAzCut=1;
    fRequiresExtraWeight=kTRUE;
    break;
  case 5:
    fDCAzCut=0.5;
    fRequiresExtraWeight=kTRUE;
    break;
  case 6:
    fTPCNcls=80;
    fRequiresExtraWeight=kTRUE;
    break;
  case 7:
    fTPCNcls=90;
    fRequiresExtraWeight=kTRUE;
    break;
  case 8:
    fTPCNcls=100;
    fRequiresExtraWeight=kTRUE;
    break;
  case 9:
    fFilterBit=2;
    fEta=1.6;
    fRequiresExtraWeight=kTRUE;
  default:
    break;
  };
};
void AliGFWCuts::SetupEventCuts(Int_t sysflag) {
  switch(sysflag) {
  case 1:
    fVtxZ = 5;
    fRequiresExtraWeight=kTRUE;
    break;
  case 2:
    fVtxZ = 7;
    fRequiresExtraWeight=kTRUE;
    break;
  case 3:
    fVtxZ = 9;
    fRequiresExtraWeight=kTRUE;
    break;
  case 4:
    printf("Warning! Event flag %i (syst. flag %i), CL1 estmator: make sure the proper estimator is used in the task!\n",sysflag, sysflag+fNTrackFlags);
    fRequiresExtraWeight=kFALSE;
    break;
  case 5:
    printf("Warning! Event flag %i (syst. flag %i), CL0 estmator: make sure the proper estimator is used in the task!\n",sysflag, sysflag+fNTrackFlags);
    fRequiresExtraWeight=kFALSE;
    break;
  case 6:
    printf("Warning! Event flag %i (syst. flag %i), PU cuts: make sure proper PU cuts are used in the task!\n",sysflag, sysflag+fNTrackFlags);
    fRequiresExtraWeight=kTRUE;
    break;
  case 7:
    printf("Warning! Event flag %i (syst. flag %i), magnetic field configuration ++: no cuts here, please make sure the proper runlist is used!\n",sysflag,sysflag+fNTrackFlags);
    fRequiresExtraWeight=kFALSE;
    break;
  case 8:
    printf("Warning! Event flag %i (syst. flag %i), magnetic field configuration --: no cuts here, please make sure the proper runlist is used!\n",sysflag,sysflag+fNTrackFlags);
    fRequiresExtraWeight=kFALSE;
    break;
  default:
    break;
  };
};
void AliGFWCuts::SetupCuts(Int_t sysflag) {
  ResetCuts();
  fSystFlag=sysflag;
  if(sysflag==0 || sysflag>fNTrackFlags+fNEventFlags) return;
  if(sysflag<=fNTrackFlags) SetupTrackCuts(sysflag);
  else SetupEventCuts(sysflag-fNTrackFlags);
};
TString *AliGFWCuts::GetTrackFlagDescriptor(Int_t sysflag) {
  TString *retstr = new TString("");
  switch(sysflag) {
  case 1:
    retstr->Append("Filter bit 768");
    break;
  case 2:
    retstr->Append("DCA_{xy} < 10 (old:8) sigma");
    break;
  case 3:
    retstr->Append("DCA_{xy} < 4 (old:6) sigma");
    break;
  case 4:
    retstr->Append("DCA_{z} < 1 cm");
    break;
  case 5:
    retstr->Append("DCA_{z} < 0.5 cm");
    break;
  case 6:
    retstr->Append("TPC N_{Cls} > 80");
    break;
  case 7:
    retstr->Append("TPC N_{Cls} > 90");
    break;
  case 8:
    retstr->Append("TPC N_{Cls} > 100");
    break;
  case 9:
    retstr->Append("ITS tracklets");
    break;
  default:
    break;
  };
  return retstr;
};
TString* AliGFWCuts::GetEventFlagDescriptor(Int_t sysflag) {
  TString *retstr = new TString("");
  switch(sysflag) {
  case 1:
    retstr->Append("|z_{vtx}| < 5 cm");
    break;
  case 2:
    retstr->Append("|z_{vtx}| < 7 cm");
    break;
  case 3:
    retstr->Append("|z_{vtx}| < 9 cm");
    break;
  case 4:
    retstr->Append("CL1 multi.");
    break;
  case 5:
    retstr->Append("CL0 multi.");
    break;
  case 6:
    retstr->Append("PU cut 1500");
    break;
  case 7:
    retstr->Append("MF ++");
    break;
  case 8:
    retstr->Append("MF --");
    break;
  default:
    break;
  };
  return retstr;
};
TString *AliGFWCuts::GetFlagDescription(Int_t sysflag) {
  if(sysflag>0 && sysflag <= fNTrackFlags + fNEventFlags) {
    if(sysflag>fNTrackFlags) return GetEventFlagDescriptor(sysflag-fNTrackFlags);
    return GetTrackFlagDescriptor(sysflag);
  };
  TString *retst = new TString("");
  if(sysflag==0) retst->Append("Nominal");
  else retst->Append("Unknown_%i",sysflag);
  return retst;
};
<commit_msg>Minor bug fix in AliGFWCut<commit_after>/*
Author: Vytautas Vislavicius
Extention of Generic Flow (https://arxiv.org/abs/1312.3572)
*/
#include "AliGFWCuts.h"
const Int_t AliGFWCuts::fNTrackFlags=9;
const Int_t AliGFWCuts::fNEventFlags=8;
AliGFWCuts::AliGFWCuts():
  fSystFlag(0),
  fFilterBit(96),
  fDCAxyCut(7),
  fDCAzCut(2),
  fTPCNcls(70),
  fVtxZ(10),
  fEta(0.8),
  fRequiresExtraWeight(kTRUE)
{
};
AliGFWCuts::~AliGFWCuts() {
};
Int_t AliGFWCuts::AcceptTrack(AliAODTrack* l_Tr, Double_t* l_DCA, const Int_t &BitShift, const Bool_t &lDisableDCAxyCheck) {
  if(TMath::Abs(l_Tr->Eta())>fEta) return 0;
  if(!l_Tr->TestFilterBit(fFilterBit)) return 0;
  if(fFilterBit!=2) {//Check is not valid for ITSsa tracks
    if(l_Tr->GetTPCNclsF()<fTPCNcls) return 0;
  } else {
    UInt_t status = l_Tr->GetStatus();
    if ((status&AliESDtrack::kITSrefit)==0) return 0;
    if ((status & AliESDtrack::kITSin) == 0 || (status & AliESDtrack::kTPCin)) return 0;
  };
  if(!l_DCA) return 1<<BitShift;
  if(l_DCA[2]>fDCAzCut) return 0;
  if(lDisableDCAxyCheck) return 1<<BitShift;
  Double_t DCAxycut;
  if(fFilterBit!=2) DCAxycut = 0.0105+0.0350/TMath::Power(l_Tr->Pt(),1.1);//*fDCAxyCut/7.; //TPC tracks and my ITS cuts
  else DCAxycut = 0.0231+0.0315/TMath::Power(l_Tr->Pt(),1.3);
  Double_t DCAxyValue = TMath::Sqrt(l_DCA[0]*l_DCA[0] + l_DCA[1]*l_DCA[1]);
  if(DCAxyValue>DCAxycut*(fDCAxyCut/7.))
    return 0;
  return 1<<BitShift;
};

Int_t AliGFWCuts::AcceptParticle(AliVParticle *l_Pa, Int_t BitShift, Double_t ptLow, Double_t ptHigh) {
  if(TMath::Abs(l_Pa->Eta())>fEta) return 0;
  if(ptLow>0) if(l_Pa->Pt()<ptLow) return 0;
  if(ptHigh>0) if(l_Pa->Pt()>ptHigh) return 0;
  return 1<<BitShift;
};
Int_t AliGFWCuts::AcceptVertex(AliAODEvent *l_Ev, Int_t BitShift) {
  Double_t lvtxz = TMath::Abs(l_Ev->GetPrimaryVertex()->GetZ());
  if(lvtxz>fVtxZ) return 0;
  return 1<<BitShift;
};
void AliGFWCuts::ResetCuts() {
  fSystFlag=0;
  fFilterBit=96;
  fDCAxyCut=7;
  fDCAzCut=2;
  fTPCNcls=70;
  fVtxZ=10;
  fEta=0.8;
  fRequiresExtraWeight=kTRUE;
};
void AliGFWCuts::PrintSetup() {
  printf("**********\n");
  printf("Syst. flag: %i\n",fSystFlag);
  printf("Eta: %f\n",fEta);
  printf("(Flag 1) Filter bit: %i\n",fFilterBit);
  printf("(Flag 2,3) DCAxy cut: %2.0f sigma\n",fDCAxyCut);
  printf("(Flag 4,5) DCAz cut: %f\n",fDCAzCut);
  printf("(Flag 6-8) TPC Ncls: %i\n",fTPCNcls);
  printf("(Flag 9) ITS tracks\n");
  printf("Rest of the flags are global per event. Total flag = %i + vtx/ev flag\n",fNTrackFlags);
  printf("(Flag 1-3) Vertex selection: |z|<%2.1f\n",fVtxZ);
  printf("(Flag 4-5) CL1, CL2 multi. estimator (no weights)\n");
  printf("(Flag 6) pile-up 15000 (-> 1500) cut\n");
  //printf("(Flag 12, disabled) ITS tracks (filter bit %i, TPC Ncls = %i)\n",fFilterBit,fTPCNcls);
  printf("**********\n");
};
void AliGFWCuts::SetupTrackCuts(Int_t sysflag) {
  switch(sysflag) {
  case 1:
    fFilterBit=768;
    fRequiresExtraWeight=kTRUE;
    break;
  case 2:
    fDCAxyCut=10.;
    fRequiresExtraWeight=kTRUE;
    break;
  case 3:
    fDCAxyCut=4.;
    fRequiresExtraWeight=kTRUE;
    break;
  case 4:
    fDCAzCut=1;
    fRequiresExtraWeight=kTRUE;
    break;
  case 5:
    fDCAzCut=0.5;
    fRequiresExtraWeight=kTRUE;
    break;
  case 6:
    fTPCNcls=80;
    fRequiresExtraWeight=kTRUE;
    break;
  case 7:
    fTPCNcls=90;
    fRequiresExtraWeight=kTRUE;
    break;
  case 8:
    fTPCNcls=100;
    fRequiresExtraWeight=kTRUE;
    break;
  case 9:
    fFilterBit=2;
    fEta=1.6;
    fRequiresExtraWeight=kTRUE;
  default:
    break;
  };
};
void AliGFWCuts::SetupEventCuts(Int_t sysflag) {
  switch(sysflag) {
  case 1:
    fVtxZ = 5;
    fRequiresExtraWeight=kTRUE;
    break;
  case 2:
    fVtxZ = 7;
    fRequiresExtraWeight=kTRUE;
    break;
  case 3:
    fVtxZ = 9;
    fRequiresExtraWeight=kTRUE;
    break;
  case 4:
    printf("Warning! Event flag %i (syst. flag %i), CL1 estmator: make sure the proper estimator is used in the task!\n",sysflag, sysflag+fNTrackFlags);
    fRequiresExtraWeight=kFALSE;
    break;
  case 5:
    printf("Warning! Event flag %i (syst. flag %i), CL0 estmator: make sure the proper estimator is used in the task!\n",sysflag, sysflag+fNTrackFlags);
    fRequiresExtraWeight=kFALSE;
    break;
  case 6:
    printf("Warning! Event flag %i (syst. flag %i), PU cuts: make sure proper PU cuts are used in the task!\n",sysflag, sysflag+fNTrackFlags);
    fRequiresExtraWeight=kTRUE;
    break;
  case 7:
    printf("Warning! Event flag %i (syst. flag %i), magnetic field configuration ++: no cuts here, please make sure the proper runlist is used!\n",sysflag,sysflag+fNTrackFlags);
    fRequiresExtraWeight=kFALSE;
    break;
  case 8:
    printf("Warning! Event flag %i (syst. flag %i), magnetic field configuration --: no cuts here, please make sure the proper runlist is used!\n",sysflag,sysflag+fNTrackFlags);
    fRequiresExtraWeight=kFALSE;
    break;
  default:
    break;
  };
};
void AliGFWCuts::SetupCuts(Int_t sysflag) {
  ResetCuts();
  fSystFlag=sysflag;
  if(sysflag==0 || sysflag>fNTrackFlags+fNEventFlags) return;
  if(sysflag<=fNTrackFlags) SetupTrackCuts(sysflag);
  else SetupEventCuts(sysflag-fNTrackFlags);
};
TString *AliGFWCuts::GetTrackFlagDescriptor(Int_t sysflag) {
  TString *retstr = new TString("");
  switch(sysflag) {
  case 1:
    retstr->Append("Filter bit 768");
    break;
  case 2:
    retstr->Append("DCA_{xy} < 10 (old:8) sigma");
    break;
  case 3:
    retstr->Append("DCA_{xy} < 4 (old:6) sigma");
    break;
  case 4:
    retstr->Append("DCA_{z} < 1 cm");
    break;
  case 5:
    retstr->Append("DCA_{z} < 0.5 cm");
    break;
  case 6:
    retstr->Append("TPC N_{Cls} > 80");
    break;
  case 7:
    retstr->Append("TPC N_{Cls} > 90");
    break;
  case 8:
    retstr->Append("TPC N_{Cls} > 100");
    break;
  case 9:
    retstr->Append("ITS tracklets");
    break;
  default:
    break;
  };
  return retstr;
};
TString* AliGFWCuts::GetEventFlagDescriptor(Int_t sysflag) {
  TString *retstr = new TString("");
  switch(sysflag) {
  case 1:
    retstr->Append("|z_{vtx}| < 5 cm");
    break;
  case 2:
    retstr->Append("|z_{vtx}| < 7 cm");
    break;
  case 3:
    retstr->Append("|z_{vtx}| < 9 cm");
    break;
  case 4:
    retstr->Append("CL1 multi.");
    break;
  case 5:
    retstr->Append("CL0 multi.");
    break;
  case 6:
    retstr->Append("PU cut 1500");
    break;
  case 7:
    retstr->Append("MF ++");
    break;
  case 8:
    retstr->Append("MF --");
    break;
  default:
    break;
  };
  return retstr;
};
TString *AliGFWCuts::GetFlagDescription(Int_t sysflag) {
  if(sysflag>0 && sysflag <= fNTrackFlags + fNEventFlags) {
    if(sysflag>fNTrackFlags) return GetEventFlagDescriptor(sysflag-fNTrackFlags);
    return GetTrackFlagDescriptor(sysflag);
  };
  TString *retst = new TString("");
  if(sysflag==0) retst->Append("Nominal");
  else retst->Append("Unknown_%i",sysflag);
  return retst;
};
<|endoftext|>


<commit_before>#include "ServerException.h"

ServerException::ServerException(int code)
{
}

ServerException::const char* what()const throw()
{
	return "ERROR!"
}
<commit_msg>rebuild exception<commit_after><|endoftext|>