<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "iterator_pack.h"
#include "termwise_helper.h"
#include <vespa/searchlib/fef/matchdata.h>

namespace search::queryeval {

SearchIteratorPack::~SearchIteratorPack() { }

SearchIteratorPack::SearchIteratorPack() : _children(), _childMatch(), _md() {}

SearchIteratorPack::SearchIteratorPack(SearchIteratorPack &&rhs)
    : _children(std::move(rhs._children)),
      _childMatch(std::move(rhs._childMatch)),
      _md(std::move(rhs._md))
{}

SearchIteratorPack &
SearchIteratorPack::operator=(SearchIteratorPack &&rhs) {
    _children = std::move(rhs._children);
    _childMatch = std::move(rhs._childMatch);
    _md = std::move(rhs._md);
    return *this;
}

SearchIteratorPack::SearchIteratorPack(const std::vector<SearchIterator*> &children,
                                       const std::vector<fef::TermFieldMatchData*> &childMatch,
                                       MatchDataUP md)
    : _children(),
      _childMatch(childMatch),
      _md(std::move(md))
{
    _children.reserve(children.size());
    for (auto child: children) {
        _children.emplace_back(child);
    }
    assert((_children.size() == _childMatch.size()) || _childMatch.empty());
}

SearchIteratorPack::SearchIteratorPack(const std::vector<SearchIterator*> &children, MatchDataUP md)
    : SearchIteratorPack(children, std::vector<fef::TermFieldMatchData*>(), MatchDataUP(std::move(md)))
{ }

std::unique_ptr<BitVector>
SearchIteratorPack::get_hits(uint32_t begin_id, uint32_t end_id) const {

    BitVector::UP result = TermwiseHelper::orChildren(_children.begin(), _children.end(), begin_id);
    if (! result ) {
        result = BitVector::create(begin_id, end_id);
    }
    return result;
}

void
SearchIteratorPack::or_hits_into(BitVector &result, uint32_t begin_id) const {
    TermwiseHelper::orChildren(result, _children.begin(), _children.end(), begin_id);
}

}
<commit_msg>= default<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "iterator_pack.h"
#include "termwise_helper.h"
#include <vespa/searchlib/fef/matchdata.h>

namespace search::queryeval {

SearchIteratorPack::~SearchIteratorPack() = default;

SearchIteratorPack::SearchIteratorPack() : _children(), _childMatch(), _md() {}

SearchIteratorPack::SearchIteratorPack(SearchIteratorPack &&rhs)
    : _children(std::move(rhs._children)),
      _childMatch(std::move(rhs._childMatch)),
      _md(std::move(rhs._md))
{}

SearchIteratorPack &
SearchIteratorPack::operator=(SearchIteratorPack &&rhs) {
    _children = std::move(rhs._children);
    _childMatch = std::move(rhs._childMatch);
    _md = std::move(rhs._md);
    return *this;
}

SearchIteratorPack::SearchIteratorPack(const std::vector<SearchIterator*> &children,
                                       const std::vector<fef::TermFieldMatchData*> &childMatch,
                                       MatchDataUP md)
    : _children(),
      _childMatch(childMatch),
      _md(std::move(md))
{
    _children.reserve(children.size());
    for (auto child: children) {
        _children.emplace_back(child);
    }
    assert((_children.size() == _childMatch.size()) || _childMatch.empty());
}

SearchIteratorPack::SearchIteratorPack(const std::vector<SearchIterator*> &children, MatchDataUP md)
    : SearchIteratorPack(children, std::vector<fef::TermFieldMatchData*>(), MatchDataUP(std::move(md)))
{ }

std::unique_ptr<BitVector>
SearchIteratorPack::get_hits(uint32_t begin_id, uint32_t end_id) const {

    BitVector::UP result = TermwiseHelper::orChildren(_children.begin(), _children.end(), begin_id);
    if (! result ) {
        result = BitVector::create(begin_id, end_id);
    }
    return result;
}

void
SearchIteratorPack::or_hits_into(BitVector &result, uint32_t begin_id) const {
    TermwiseHelper::orChildren(result, _children.begin(), _children.end(), begin_id);
}

}
<|endoftext|>


<commit_before>#include "types.h"
#include "amd64.h"
#include "kernel.hh"

void*
memset(void *dst, int c, size_t n)
{
  stosb(dst, c, n);
  return dst;
}

int
memcmp(const void *v1, const void *v2, size_t n)
{
  const u8 *s1, *s2;

  s1 = (const u8*) v1;
  s2 = (const u8*) v2;
  while(n-- > 0){
    if(*s1 != *s2)
      return *s1 - *s2;
    s1++, s2++;
  }

  return 0;
}

void*
memmove(void *dst, const void *src, size_t n)
{
  const char *s;
  char *d;

  s = (const char*) src;
  d = (char*) dst;
  if(s < d && s + n > d){
    s += n;
    d += n;
    while(n-- > 0)
      *--d = *--s;
  } else
    while(n-- > 0)
      *d++ = *s++;

  return dst;
}

// memcpy exists to placate GCC.  Use memmove.
void*
memcpy(void *dst, const void *src, size_t n)
{
  return memmove(dst, src, n);
}

int
strncmp(const char *p, const char *q, size_t n)
{
  while(n > 0 && *p && *p == *q)
    n--, p++, q++;
  if(n == 0)
    return 0;
  return (u8)*p - (u8)*q;
}

char*
strncpy(char *s, const char *t, size_t n)
{
  char *os;

  os = s;
  while(n-- > 0 && (*s++ = *t++) != 0)
    ;
  while(n-- > 0)
    *s++ = 0;
  return os;
}

// Like strncpy but guaranteed to NUL-terminate.
char*
safestrcpy(char *s, const char *t, size_t n)
{
  char *os;

  os = s;
  if(n <= 0)
    return os;
  while(--n > 0 && (*s++ = *t++) != 0)
    ;
  *s = 0;
  return os;
}

unsigned int
strlen(const char *s)
{
  int n;

  for(n = 0; s[n]; n++)
    ;
  return n;
}

int
strcmp(const char *p, const char *q)
{
  while(*p && *p == *q)
    p++, q++;
  return (u8)*p - (u8)*q;
}
<commit_msg>fix strncpy<commit_after>#include "types.h"
#include "amd64.h"
#include "kernel.hh"

void*
memset(void *dst, int c, size_t n)
{
  stosb(dst, c, n);
  return dst;
}

int
memcmp(const void *v1, const void *v2, size_t n)
{
  const u8 *s1, *s2;

  s1 = (const u8*) v1;
  s2 = (const u8*) v2;
  while(n-- > 0){
    if(*s1 != *s2)
      return *s1 - *s2;
    s1++, s2++;
  }

  return 0;
}

void*
memmove(void *dst, const void *src, size_t n)
{
  const char *s;
  char *d;

  s = (const char*) src;
  d = (char*) dst;
  if(s < d && s + n > d){
    s += n;
    d += n;
    while(n-- > 0)
      *--d = *--s;
  } else
    while(n-- > 0)
      *d++ = *s++;

  return dst;
}

// memcpy exists to placate GCC.  Use memmove.
void*
memcpy(void *dst, const void *src, size_t n)
{
  return memmove(dst, src, n);
}

int
strncmp(const char *p, const char *q, size_t n)
{
  while(n > 0 && *p && *p == *q)
    n--, p++, q++;
  if(n == 0)
    return 0;
  return (u8)*p - (u8)*q;
}

char*
strncpy(char *s, const char *t, size_t n)
{
  char *os;

  os = s;
  while(n > 0 && (*s++ = *t++) != 0)
    n--;
  if (n > 0)
    *s = 0;
  return os;
}

// Like strncpy but guaranteed to NUL-terminate.
char*
safestrcpy(char *s, const char *t, size_t n)
{
  char *os;

  os = s;
  if(n <= 0)
    return os;
  while(--n > 0 && (*s++ = *t++) != 0)
    ;
  *s = 0;
  return os;
}

unsigned int
strlen(const char *s)
{
  int n;

  for(n = 0; s[n]; n++)
    ;
  return n;
}

int
strcmp(const char *p, const char *q)
{
  while(*p && *p == *q)
    p++, q++;
  return (u8)*p - (u8)*q;
}
<|endoftext|>


<commit_before>#ifndef optional_hh_INCLUDED
#define optional_hh_INCLUDED

#include "assert.hh"

namespace Kakoune
{

template<typename T>
struct Optional
{
public:
    constexpr Optional() : m_valid(false) {}
    Optional(const T& other) : m_valid(true) { new (&m_value) T(other); }
    Optional(T&& other) : m_valid(true) { new (&m_value) T(std::move(other)); }

    Optional(const Optional& other)
        : m_valid(other.m_valid)
    {
        if (m_valid)
            new (&m_value) T(other.m_value);
    }

    Optional(Optional&& other)
        noexcept(noexcept(new (nullptr) T(std::move(other.m_value))))
        : m_valid(other.m_valid)
    {
        if (m_valid)
            new (&m_value) T(std::move(other.m_value));
    }

    Optional& operator=(const Optional& other)
    {
        destruct_ifn();
        if ((m_valid = other.m_valid))
            new (&m_value) T(other.m_value);
        return *this;
    }

    Optional& operator=(Optional&& other)
    {
        destruct_ifn();
        if ((m_valid = other.m_valid))
            new (&m_value) T(std::move(other.m_value));
        return *this;
    }

    ~Optional() { destruct_ifn(); }

    constexpr explicit operator bool() const noexcept { return m_valid; }

    bool operator==(const Optional& other) const
    {
        if (m_valid == other.m_valid)
        {
            if (m_valid)
                return m_value == other.m_value;
            return true;
        }
        return false;
    }

    template<typename... Args>
    void emplace(Args&&... args)
    {
        destruct_ifn();
        new (&m_value) T{std::forward<Args>(args)...};
        m_valid = true;
    }

    T& operator*()
    {
        kak_assert(m_valid);
        return m_value;
    }
    const T& operator*() const { return *const_cast<Optional&>(*this); }

    T* operator->()
    {
        kak_assert(m_valid);
        return &m_value;
    }
    const T* operator->() const { return const_cast<Optional&>(*this).operator->(); }

    template<typename U>
    T value_or(U&& fallback) const { return m_valid ? m_value : T{fallback}; }

private:
    void destruct_ifn() { if (m_valid) m_value.~T(); }

    struct Empty {};
    union
    {
        Empty m_empty; // disable default construction of value
        T m_value;
    };
    bool m_valid;
};

}

#endif // optional_hh_INCLUDED
<commit_msg>Refactor Optional::operator==<commit_after>#ifndef optional_hh_INCLUDED
#define optional_hh_INCLUDED

#include "assert.hh"

namespace Kakoune
{

template<typename T>
struct Optional
{
public:
    constexpr Optional() : m_valid(false) {}
    Optional(const T& other) : m_valid(true) { new (&m_value) T(other); }
    Optional(T&& other) : m_valid(true) { new (&m_value) T(std::move(other)); }

    Optional(const Optional& other)
        : m_valid(other.m_valid)
    {
        if (m_valid)
            new (&m_value) T(other.m_value);
    }

    Optional(Optional&& other)
        noexcept(noexcept(new (nullptr) T(std::move(other.m_value))))
        : m_valid(other.m_valid)
    {
        if (m_valid)
            new (&m_value) T(std::move(other.m_value));
    }

    Optional& operator=(const Optional& other)
    {
        destruct_ifn();
        if ((m_valid = other.m_valid))
            new (&m_value) T(other.m_value);
        return *this;
    }

    Optional& operator=(Optional&& other)
    {
        destruct_ifn();
        if ((m_valid = other.m_valid))
            new (&m_value) T(std::move(other.m_value));
        return *this;
    }

    ~Optional() { destruct_ifn(); }

    constexpr explicit operator bool() const noexcept { return m_valid; }

    bool operator==(const Optional& other) const
    {
        return m_valid == other.m_valid and
               (not m_valid or m_value == other.m_value);
    }

    template<typename... Args>
    void emplace(Args&&... args)
    {
        destruct_ifn();
        new (&m_value) T{std::forward<Args>(args)...};
        m_valid = true;
    }

    T& operator*()
    {
        kak_assert(m_valid);
        return m_value;
    }
    const T& operator*() const { return *const_cast<Optional&>(*this); }

    T* operator->()
    {
        kak_assert(m_valid);
        return &m_value;
    }
    const T* operator->() const { return const_cast<Optional&>(*this).operator->(); }

    template<typename U>
    T value_or(U&& fallback) const { return m_valid ? m_value : T{fallback}; }

private:
    void destruct_ifn() { if (m_valid) m_value.~T(); }

    struct Empty {};
    union
    {
        Empty m_empty; // disable default construction of value
        T m_value;
    };
    bool m_valid;
};

}

#endif // optional_hh_INCLUDED
<|endoftext|>


<commit_before>/* Optional packages.  You might want to integrate this with your build system e.g. config.h from ./configure. */
#ifndef UTIL_HAVE__
#define UTIL_HAVE__

#ifndef HAVE_ICU
//#define HAVE_ICU
#endif

#ifndef HAVE_BOOST
//#define HAVE_BOOST
#endif

#endif // UTIL_HAVE__
<commit_msg>Get macros from config.h, break build for Chris to fix by linking libs<commit_after>/* Optional packages.  You might want to integrate this with your build system e.g. config.h from ./configure. */
#ifndef UTIL_HAVE__
#define UTIL_HAVE__

#ifndef HAVE_ICU
//#define HAVE_ICU
#endif

#ifndef HAVE_BOOST
//#define HAVE_BOOST
#endif

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#endif // UTIL_HAVE__
<|endoftext|>


<commit_before>/*
    Copyright (C) 2016 Volker Krause <vkrause@kde.org>

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

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

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "test-config.h"

#include <syntaxrepository.h>
#include <syntaxdefinition.h>
#include <htmlhighlighter.h>

#include <QObject>
#include <QtTest/qtest.h>

using namespace KateSyntax;

class HighlighterBenchmark : public QObject
{
    Q_OBJECT
public:
    explicit HighlighterBenchmark(QObject *parent = nullptr) : QObject(parent), m_repo(nullptr) {}

private:
    SyntaxRepository *m_repo;

private slots:
    void initTestCase()
    {
        m_repo = new SyntaxRepository;
    }

    void cleanupTestCase()
    {
        delete m_repo;
        m_repo = nullptr;
    }

    void benchmarkHighlight_data()
    {
        QTest::addColumn<QString>("inFile");
        QTest::addColumn<QString>("syntax");

        QTest::newRow("mimedb") << QStringLiteral(":/qt-project.org/qmime/freedesktop.org.xml") << QStringLiteral("XML");
    }

    void benchmarkHighlight()
    {
        QFETCH(QString, inFile);
        QFETCH(QString, syntax);
        QVERIFY(m_repo);

        HtmlHighlighter highlighter;
        auto def = m_repo->definitionForFileName(inFile);
        if (!syntax.isEmpty())
            def = m_repo->definitionForName(syntax);
        QVERIFY(def);
        highlighter.setDefinition(def);
        highlighter.setOutputFile(QStringLiteral("/dev/null"));
        QBENCHMARK {
            highlighter.highlightFile(inFile);
        }
    }

};

QTEST_MAIN(HighlighterBenchmark)

#include "highlighter_benchmark.moc"

<commit_msg>Improve benchmark to not measure HTML output overhead.<commit_after>/*
    Copyright (C) 2016 Volker Krause <vkrause@kde.org>

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

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

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "test-config.h"

#include <syntaxrepository.h>
#include <syntaxdefinition.h>
#include <abstracthighlighter.h>

#include <QObject>
#include <QtTest/qtest.h>

using namespace KateSyntax;

class NullHighlighter : public AbstractHighlighter
{
public:
    void highlightFile(const QString &inFileName)
    {
        QFile f(inFileName);
        if (!f.open(QFile::ReadOnly)) {
            qWarning() << "Failed to open input file" << inFileName << ":" << f.errorString();
            return;
        }

        reset();
        QTextStream in(&f);
        while (!in.atEnd())
            highlightLine(in.readLine());
    }

protected:
    void setFormat(int, int, const Format&) override {}
};

class HighlighterBenchmark : public QObject
{
    Q_OBJECT
public:
    explicit HighlighterBenchmark(QObject *parent = nullptr) : QObject(parent), m_repo(nullptr) {}

private:
    SyntaxRepository *m_repo;

private slots:
    void initTestCase()
    {
        m_repo = new SyntaxRepository;
    }

    void cleanupTestCase()
    {
        delete m_repo;
        m_repo = nullptr;
    }

    void benchmarkHighlight_data()
    {
        QTest::addColumn<QString>("inFile");
        QTest::addColumn<QString>("syntax");

        QTest::newRow("mimedb") << QStringLiteral(":/qt-project.org/qmime/freedesktop.org.xml") << QStringLiteral("XML");
    }

    void benchmarkHighlight()
    {
        QFETCH(QString, inFile);
        QFETCH(QString, syntax);
        QVERIFY(m_repo);

        NullHighlighter highlighter;
        auto def = m_repo->definitionForFileName(inFile);
        if (!syntax.isEmpty())
            def = m_repo->definitionForName(syntax);
        QVERIFY(def);
        highlighter.setDefinition(def);
        QBENCHMARK {
            highlighter.highlightFile(inFile);
        }
    }

};

QTEST_MAIN(HighlighterBenchmark)

#include "highlighter_benchmark.moc"

<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// cache_test.cpp
//
// Identification: tests/common/cache_test.cpp
//
// Copyright (c) 201CACHE_SIZE, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "harness.h"
#include "backend/common/thread_manager.h"

namespace peloton {
namespace test {

//===--------------------------------------------------------------------===//
// Thread Manager Test
//===--------------------------------------------------------------------===//

class ThreadManagerTests : public PelotonTest {};

TEST_F(ThreadManagerTests, BasicTest) {

  auto& thread_manager = ThreadManager::GetInstance();
  std::shared_ptr<std::thread> t1(new std::thread);

  bool status = thread_manager.AttachThread(t1);
  EXPECT_EQ(status, true);

  status = thread_manager.AttachThread(t1);
  EXPECT_EQ(status, false);

  status = thread_manager.DetachThread(t1);
  EXPECT_EQ(status, true);

  status = thread_manager.DetachThread(t1);
  EXPECT_EQ(status, false);

}

}  // End test namespace
}  // End peloton namespace
<commit_msg>add thread_manager_test<commit_after>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// cache_test.cpp
//
// Identification: tests/common/cache_test.cpp
//
// Copyright (c) 201CACHE_SIZE, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "harness.h"
#include "backend/common/thread_manager.h"

namespace peloton {
namespace test {

//===--------------------------------------------------------------------===//
// Thread Manager Test
//===--------------------------------------------------------------------===//

class ThreadManagerTests : public PelotonTest {};

/* this is the old test
TEST_F(ThreadManagerTests, BasicTest) {
  auto& thread_manager = ThreadManager::GetInstance();
  std::shared_ptr<std::thread> t1(new std::thread);
  bool status = thread_manager.AttachThread(t1);
  EXPECT_EQ(status, true);
  status = thread_manager.AttachThread(t1);
  EXPECT_EQ(status, false);
  status = thread_manager.DetachThread(t1);
  EXPECT_EQ(status, true);
  status = thread_manager.DetachThread(t1);
  EXPECT_EQ(status, false);
}
*/

TEST_F(ThreadManagerTests, BasicTest) {

  auto& server_thread_manager1 = ThreadManager::GetServerThreadPool();
  auto& server_thread_manager2 = ThreadManager::GetServerThreadPool();

  bool status = (&server_thread_manager1 == &server_thread_manager2);
  EXPECT_EQ(status, true);

  auto& client_thread_manager1 = ThreadManager::GetClientThreadPool();
  auto& client_thread_manager2 = ThreadManager::GetClientThreadPool();

  status = (&client_thread_manager1 == &client_thread_manager2);
  EXPECT_EQ(status, true);

  status = (&server_thread_manager1 == &client_thread_manager2);
  EXPECT_EQ(status, false);

}

}  // End test namespace
}  // End peloton namespace
<|endoftext|>


<commit_before>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#include "mfem.hpp"
#include "unit_tests.hpp"

#include <iostream>

using namespace mfem;

TEST_CASE("Test order of boundary integrators",
          "[BilinearForm]")
{
   // Create a simple mesh
   int dim = 2, nx = 2, ny = 2, order = 2;
   Element::Type e_type = Element::QUADRILATERAL;
   Mesh mesh = Mesh::MakeCartesian2D(nx, ny, e_type);

   H1_FECollection fec(order, dim);
   FiniteElementSpace fes(&mesh, &fec);

   SECTION("Order of restricted boundary integrators")
   {
      ConstantCoefficient one(1.0);
      ConstantCoefficient two(2.0);
      ConstantCoefficient three(3.0);
      ConstantCoefficient four(4.0);

      Array<int> bdr1(4); bdr1 = 0; bdr1[0] = 1;
      Array<int> bdr2(4); bdr2 = 0; bdr2[1] = 1;
      Array<int> bdr3(4); bdr3 = 0; bdr3[2] = 1;
      Array<int> bdr4(4); bdr4 = 0; bdr4[3] = 1;

      BilinearForm a1234(&fes);
      a1234.AddBoundaryIntegrator(new MassIntegrator(one), bdr1);
      a1234.AddBoundaryIntegrator(new MassIntegrator(two), bdr2);
      a1234.AddBoundaryIntegrator(new MassIntegrator(three), bdr3);
      a1234.AddBoundaryIntegrator(new MassIntegrator(four), bdr4);
      a1234.Assemble(0);
      a1234.Finalize(0);

      BilinearForm a4321(&fes);
      a4321.AddBoundaryIntegrator(new MassIntegrator(four), bdr4);
      a4321.AddBoundaryIntegrator(new MassIntegrator(three), bdr3);
      a4321.AddBoundaryIntegrator(new MassIntegrator(two), bdr2);
      a4321.AddBoundaryIntegrator(new MassIntegrator(one), bdr1);
      a4321.Assemble(0);
      a4321.Finalize(0);

      const SparseMatrix &A1234 = a1234.SpMat();
      const SparseMatrix &A4321 = a4321.SpMat();

      SparseMatrix *D = Add(1.0, A1234, -1.0, A4321);

      REQUIRE(D->MaxNorm() == MFEM_Approx(0.0));

      delete D;
   }
}

TEST_CASE("FormLinearSystem/SolutionScope",
          "[BilinearForm]"
          "[CUDA]")
{
   // Create a simple mesh and FE space
   int dim = 2, nx = 2, ny = 2, order = 2;
   Element::Type e_type = Element::QUADRILATERAL;
   Mesh mesh = Mesh::MakeCartesian2D(nx, ny, e_type);

   H1_FECollection fec(order, dim);
   FiniteElementSpace fes(&mesh, &fec);
   int bdr_dof;

   // Solve a PDE on the conforming mesh and FE space defined above, storing the
   // result in 'sol'.
   auto SolvePDE = [&](AssemblyLevel al, GridFunction &sol)
   {
      // Linear form: rhs
      ConstantCoefficient f(1.0);
      LinearForm b(&fes);
      b.AddDomainIntegrator(new DomainLFIntegrator(f));
      b.Assemble();
      // Bilinear form: matrix
      BilinearForm a(&fes);
      a.AddDomainIntegrator(new DiffusionIntegrator);
      a.SetAssemblyLevel(al);
      a.Assemble();
      // Setup b.c.
      Array<int> ess_tdof_list;
      REQUIRE(mesh.bdr_attributes.Max() > 0);
      Array<int> bdr_attr_is_ess(mesh.bdr_attributes.Max());
      bdr_attr_is_ess = 1;
      fes.GetEssentialTrueDofs(bdr_attr_is_ess, ess_tdof_list);
      REQUIRE(ess_tdof_list.Size() > 0);
      // Setup (on host) solution initial guess satisfying the desired b.c.
      ConstantCoefficient zero(0.0);
      sol.ProjectCoefficient(zero); // performed on host
      // Setup the linear system
      Vector B, X;
      OperatorPtr A;
      const bool copy_interior = true; // interior(sol) --> interior(X)
      a.FormLinearSystem(ess_tdof_list, sol, b, A, X, B, copy_interior);
      // Solve the system
      CGSolver cg;
      cg.SetMaxIter(2000);
      cg.SetRelTol(1e-8);
      cg.SetAbsTol(0.0);
      cg.SetPrintLevel(0);
      cg.SetOperator(*A);
      cg.Mult(B, X);
      // Recover the solution
      a.RecoverFEMSolution(X, b, sol);
      // Initialize the bdr_dof to be checked
      ess_tdof_list.HostRead();
      bdr_dof = AsConst(ess_tdof_list)[0]; // here, L-dof is the same T-dof
   };

   // Legacy full assembly
   {
      GridFunction sol(&fes);
      SolvePDE(AssemblyLevel::LEGACYFULL, sol);
      // Make sure the solution is still accessible after 'X' is destoyed
      sol.HostRead();
      REQUIRE(AsConst(sol)(bdr_dof) == 0.0);
   }

   // Partial assembly
   {
      GridFunction sol(&fes);
      SolvePDE(AssemblyLevel::PARTIAL, sol);
      // Make sure the solution is still accessible after 'X' is destoyed
      sol.HostRead();
      REQUIRE(AsConst(sol)(bdr_dof) == 0.0);
   }
}
<commit_msg>Revert extra tests/unit/fem/test_bilinearform test<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#include "mfem.hpp"
#include "unit_tests.hpp"

#include <iostream>

using namespace mfem;

TEST_CASE("Test order of boundary integrators",
          "[BilinearForm]")
{
   // Create a simple mesh
   int dim = 2, nx = 2, ny = 2, order = 2;
   Element::Type e_type = Element::QUADRILATERAL;
   Mesh mesh = Mesh::MakeCartesian2D(nx, ny, e_type);

   H1_FECollection fec(order, dim);
   FiniteElementSpace fes(&mesh, &fec);

   SECTION("Order of restricted boundary integrators")
   {
      ConstantCoefficient one(1.0);
      ConstantCoefficient two(2.0);
      ConstantCoefficient three(3.0);
      ConstantCoefficient four(4.0);

      Array<int> bdr1(4); bdr1 = 0; bdr1[0] = 1;
      Array<int> bdr2(4); bdr2 = 0; bdr2[1] = 1;
      Array<int> bdr3(4); bdr3 = 0; bdr3[2] = 1;
      Array<int> bdr4(4); bdr4 = 0; bdr4[3] = 1;

      BilinearForm a1234(&fes);
      a1234.AddBoundaryIntegrator(new MassIntegrator(one), bdr1);
      a1234.AddBoundaryIntegrator(new MassIntegrator(two), bdr2);
      a1234.AddBoundaryIntegrator(new MassIntegrator(three), bdr3);
      a1234.AddBoundaryIntegrator(new MassIntegrator(four), bdr4);
      a1234.Assemble(0);
      a1234.Finalize(0);

      BilinearForm a4321(&fes);
      a4321.AddBoundaryIntegrator(new MassIntegrator(four), bdr4);
      a4321.AddBoundaryIntegrator(new MassIntegrator(three), bdr3);
      a4321.AddBoundaryIntegrator(new MassIntegrator(two), bdr2);
      a4321.AddBoundaryIntegrator(new MassIntegrator(one), bdr1);
      a4321.Assemble(0);
      a4321.Finalize(0);

      const SparseMatrix &A1234 = a1234.SpMat();
      const SparseMatrix &A4321 = a4321.SpMat();

      SparseMatrix *D = Add(1.0, A1234, -1.0, A4321);

      REQUIRE(D->MaxNorm() == MFEM_Approx(0.0));

      delete D;
   }
}
<|endoftext|>


<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

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 <string.h>  // for strdup
#include <algorithm>
#include <stdexcept>
#include <string>

#include "paddle/fluid/framework/init.h"
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/place.h"
#include "paddle/fluid/string/piece.h"

namespace paddle {
namespace framework {

std::once_flag gflags_init_flag;
std::once_flag p2p_init_flag;

void InitGflags(std::vector<std::string> argv) {
  std::call_once(gflags_init_flag, [&]() {
    argv.push_back("dummy");
    int argc = argv.size();
    char **arr = new char *[argv.size()];
    std::string line;
    for (size_t i = 0; i < argv.size(); i++) {
      arr[i] = &argv[i][0];
      line += argv[i];
      line += ' ';
    }
    google::ParseCommandLineFlags(&argc, &arr, true);
    VLOG(1) << "Init commandline: " << line;
  });
}

void InitP2P(std::vector<int> devices) {
#ifdef PADDLE_WITH_CUDA
  std::call_once(p2p_init_flag, [&]() {
    int count = devices.size();
    for (int i = 0; i < count; ++i) {
      for (int j = 0; j < count; ++j) {
        if (devices[i] == devices[j]) continue;
        int can_acess = -1;
        PADDLE_ENFORCE(
            cudaDeviceCanAccessPeer(&can_acess, devices[i], devices[j]),
            "Failed to test P2P access.");
        if (can_acess != 1) {
          LOG(WARNING) << "Cannot enable P2P access from " << devices[i]
                       << " to " << devices[j];
        } else {
          cudaSetDevice(devices[i]);
          cudaDeviceEnablePeerAccess(devices[j], 0);
        }
      }
    }
  });
#endif
}

void InitDevices(bool init_p2p) {
/*Init all available devices by default */
#ifdef PADDLE_WITH_CUDA
  std::vector<int> devices;
  try {
    int count = platform::GetCUDADeviceCount();
    for (int i = 0; i < count; ++i) {
      devices.push_back(i);
    }
  } catch (const std::exception &exp) {
    LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime.";
  }
#else
  LOG(WARNING)
      << "'CUDA' is not supported, Please re-compile with WITH_GPU option";
#endif
  InitDevices(init_p2p, devices);
}

void InitDevices(bool init_p2p, const std::vector<int> devices) {
  std::vector<platform::Place> places;
  int count = 0;
#ifdef PADDLE_WITH_CUDA
  try {
    count = platform::GetCUDADeviceCount();
  } catch (const std::exception &exp) {
    LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime.";
  }
#else
  LOG(WARNING)
      << "'CUDA' is not supported, Please re-compile with WITH_GPU option";
#endif

  for (size_t i = 0; i < devices.size(); ++i) {
    if (devices[i] >= count || devices[i] < 0) {
      LOG(WARNING) << "Invalid devices id.";
      continue;
    }
    places.emplace_back(platform::CUDAPlace(devices[i]));
  }
  if (init_p2p) {
    InitP2P(devices);
  }
  places.emplace_back(platform::CPUPlace());
  platform::DeviceContextPool::Init(places);
}

void InitGLOG(const std::string &prog_name) {
  // glog will not hold the ARGV[0] inside.
  // Use strdup to alloc a new string.
  google::InitGoogleLogging(strdup(prog_name.c_str()));
  google::InstallFailureSignalHandler();
}

}  // namespace framework
}  // namespace paddle
<commit_msg>Fix InitGflags.<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

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 <string.h>  // for strdup
#include <algorithm>
#include <stdexcept>
#include <string>

#include "paddle/fluid/framework/init.h"
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/place.h"
#include "paddle/fluid/string/piece.h"

namespace paddle {
namespace framework {

std::once_flag gflags_init_flag;
std::once_flag p2p_init_flag;

void InitGflags(std::vector<std::string> argv) {
  std::call_once(gflags_init_flag, [&]() {
    argv.insert(argv.begin(), "dummy");
    int argc = argv.size();
    char **arr = new char *[argv.size()];
    std::string line;
    for (size_t i = 0; i < argv.size(); i++) {
      arr[i] = &argv[i][0];
      line += argv[i];
      line += ' ';
    }
    google::ParseCommandLineFlags(&argc, &arr, true);
    VLOG(1) << "Init commandline: " << line;
  });
}

void InitP2P(std::vector<int> devices) {
#ifdef PADDLE_WITH_CUDA
  std::call_once(p2p_init_flag, [&]() {
    int count = devices.size();
    for (int i = 0; i < count; ++i) {
      for (int j = 0; j < count; ++j) {
        if (devices[i] == devices[j]) continue;
        int can_acess = -1;
        PADDLE_ENFORCE(
            cudaDeviceCanAccessPeer(&can_acess, devices[i], devices[j]),
            "Failed to test P2P access.");
        if (can_acess != 1) {
          LOG(WARNING) << "Cannot enable P2P access from " << devices[i]
                       << " to " << devices[j];
        } else {
          cudaSetDevice(devices[i]);
          cudaDeviceEnablePeerAccess(devices[j], 0);
        }
      }
    }
  });
#endif
}

void InitDevices(bool init_p2p) {
/*Init all available devices by default */
#ifdef PADDLE_WITH_CUDA
  std::vector<int> devices;
  try {
    int count = platform::GetCUDADeviceCount();
    for (int i = 0; i < count; ++i) {
      devices.push_back(i);
    }
  } catch (const std::exception &exp) {
    LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime.";
  }
#else
  LOG(WARNING)
      << "'CUDA' is not supported, Please re-compile with WITH_GPU option";
#endif
  InitDevices(init_p2p, devices);
}

void InitDevices(bool init_p2p, const std::vector<int> devices) {
  std::vector<platform::Place> places;
  int count = 0;
#ifdef PADDLE_WITH_CUDA
  try {
    count = platform::GetCUDADeviceCount();
  } catch (const std::exception &exp) {
    LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime.";
  }
#else
  LOG(WARNING)
      << "'CUDA' is not supported, Please re-compile with WITH_GPU option";
#endif

  for (size_t i = 0; i < devices.size(); ++i) {
    if (devices[i] >= count || devices[i] < 0) {
      LOG(WARNING) << "Invalid devices id.";
      continue;
    }
    places.emplace_back(platform::CUDAPlace(devices[i]));
  }
  if (init_p2p) {
    InitP2P(devices);
  }
  places.emplace_back(platform::CPUPlace());
  platform::DeviceContextPool::Init(places);
}

void InitGLOG(const std::string &prog_name) {
  // glog will not hold the ARGV[0] inside.
  // Use strdup to alloc a new string.
  google::InitGoogleLogging(strdup(prog_name.c_str()));
  google::InstallFailureSignalHandler();
}

}  // namespace framework
}  // namespace paddle
<|endoftext|>


<commit_before>// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// 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 "gflags/gflags.h"
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/platform/cudnn_workspace_helper.h"
#endif

/**
 * NOTE(paddle-dev): This file is designed to define all public FLAGS.
 */

/* Paddle initialization related */
DEFINE_int32(paddle_num_threads, 1,
             "Number of threads for each paddle instance.");

/* Operator related */
DEFINE_bool(check_nan_inf, false,
            "Checking whether operator produce NAN/INF or not. It will be "
            "extremely slow so please use this flag wisely.");

/* CUDA related */
#ifdef PADDLE_WITH_CUDA
DEFINE_bool(
    enable_cublas_tensor_op_math, false,
    "The enable_cublas_tensor_op_math indicate whether to use Tensor Core, "
    "but it may loss precision. Currently, There are two CUDA libraries that"
    " use Tensor Cores, cuBLAS and cuDNN. cuBLAS uses Tensor Cores to speed up"
    " GEMM computations(the matrices must be either half precision or single "
    "precision); cuDNN uses Tensor Cores to speed up both convolutions(the "
    "input and output must be half precision) and recurrent neural networks "
    "(RNNs).");

DEFINE_string(selected_gpus, "",
              "A list of device ids separated by comma, like: 0,1,2,3. "
              "This option is useful when doing multi process training and "
              "each process have only one device (GPU). If you want to use "
              "all visible devices, set this to empty string. NOTE: the "
              "reason of doing this is that we want to use P2P communication"
              "between GPU devices, use CUDA_VISIBLE_DEVICES can only use"
              "share-memory only.");
#endif

/* CUDNN related */
#ifdef PADDLE_WITH_CUDA
DEFINE_bool(cudnn_deterministic, false,
            "Whether allow using an autotuning algorithm for convolution "
            "operator. The autotuning algorithm may be non-deterministic. If "
            "true, the algorithm is deterministic.");

DEFINE_uint64(conv_workspace_size_limit,
              paddle::platform::kDefaultConvWorkspaceSizeLimitMB,
              "cuDNN convolution workspace limit in MB unit.");

DEFINE_bool(cudnn_exhaustive_search, false,
            "Whether enable exhaustive search for cuDNN convolution or "
            "not, default is False.");

DEFINE_int64(cudnn_exhaustive_search_times, -1,
             "Exhaustive search times for cuDNN convolution, "
             "default is -1, not exhaustive search");

// CUDNN_BATCHNORM_SPATIAL_PERSISTENT in batchnorm. This mode can be faster in
// some tasks because an optimized path may be selected for CUDNN_DATA_FLOAT
// and CUDNN_DATA_HALF data types, compute capability 6.0 or higher. The
// reason we set it to false by default is that this mode may use scaled
// atomic integer reduction that may cause a numerical overflow for certain
// input data range.
DEFINE_bool(cudnn_batchnorm_spatial_persistent, false,
            "Whether enable CUDNN_BATCHNORM_SPATIAL_PERSISTENT mode for cudnn "
            "batch_norm, default is False.");
#endif

/* NCCL related */
#ifdef PADDLE_WITH_CUDA
// asynchronous nccl allreduce or synchronous issue:
// https://github.com/PaddlePaddle/Paddle/issues/15049
// If you want to change this default value, why?(gongwb)
DEFINE_bool(
    sync_nccl_allreduce, true,
    "If set true, will call `cudaStreamSynchronize(nccl_stream)`"
    "after allreduce, this mode can get better performance in some scenarios.");
#endif

/* Distributed related */
#ifdef PADDLE_WITH_DISTRIBUTE
DEFINE_int32(communicator_max_merge_var_num, 20,
             "max var num to merge and send");
DEFINE_int32(communicator_send_queue_size, 20,
             "queue size to recv gradient before send");
#endif

DEFINE_int32(dist_threadpool_size, 0,
             "number of threads used for distributed executed.");

/* Garbage collector related */
// Disable gc by default when inference library is built
#ifdef PADDLE_ON_INFERENCE
static const double kDefaultEagerDeleteTensorGB = -1;
#else
static const double kDefaultEagerDeleteTensorGB = 0;
#endif

DEFINE_double(
    eager_delete_tensor_gb, kDefaultEagerDeleteTensorGB,
    "Memory size threshold (GB) when the garbage collector clear tensors."
    "Disabled when this value is less than 0");

DEFINE_bool(fast_eager_deletion_mode, true,
            "Fast eager deletion mode. If enabled, memory would release "
            "immediately without waiting GPU kernel ends.");

DEFINE_double(memory_fraction_of_eager_deletion, 1.0,
              "Fraction of eager deletion. If less than 1.0, all variables in "
              "the program would be sorted according to its memory size, and "
              "only the FLAGS_memory_fraction_of_eager_deletion of the largest "
              "variables would be deleted.");

/* Allocator related */
DEFINE_string(allocator_strategy, "naive_best_fit",
              "The allocation strategy. naive_best_fit means the original best "
              "fit allocator of Fluid. "
              "auto_growth means the experimental auto-growth allocator. "
              "Enum in [naive_best_fit, auto_growth].");

DEFINE_double(fraction_of_cpu_memory_to_use, 1,
              "Default use 100% of CPU memory for PaddlePaddle,"
              "reserve the rest for page tables, etc");
DEFINE_uint64(initial_cpu_memory_in_mb, 500ul,
              "Initial CPU memory for PaddlePaddle, in MD unit.");

DEFINE_double(
    fraction_of_cuda_pinned_memory_to_use, 0.5,
    "Default use 50% of CPU memory as the pinned_memory for PaddlePaddle,"
    "reserve the rest for page tables, etc");

#ifdef PADDLE_WITH_CUDA
#ifndef _WIN32
constexpr static float fraction_of_gpu_memory_to_use = 0.92f;
#else
// fraction_of_gpu_memory_to_use cannot be too high on windows,
// since the win32 graphic sub-system can occupy some GPU memory
// which may lead to insufficient memory left for paddle
constexpr static float fraction_of_gpu_memory_to_use = 0.5f;
#endif

DEFINE_double(fraction_of_gpu_memory_to_use, fraction_of_gpu_memory_to_use,
              "Allocate a trunk of gpu memory that is this fraction of the "
              "total gpu memory size. Future memory usage will be allocated "
              "from the trunk. If the trunk doesn't have enough gpu memory, "
              "additional trunks of the same size will be requested from gpu "
              "until the gpu has no memory left for another trunk.");

DEFINE_uint64(
    initial_gpu_memory_in_mb, 0ul,
    "Allocate a trunk of gpu memory whose byte size is specified by "
    "the flag. Future memory usage will be allocated from the "
    "trunk. If the trunk doesn't have enough gpu memory, additional "
    "trunks of the gpu memory will be requested from gpu with size "
    "specified by FLAGS_reallocate_gpu_memory_in_mb until the gpu has "
    "no memory left for the additional trunk. Note: if you set this "
    "flag, the memory size set by "
    "FLAGS_fraction_of_gpu_memory_to_use will be overrided by this "
    "flag. If you don't set this flag, PaddlePaddle will use "
    "FLAGS_fraction_of_gpu_memory_to_use to allocate gpu memory");

DEFINE_uint64(reallocate_gpu_memory_in_mb, 0ul,
              "If this flag is set, Paddle will reallocate the gpu memory with "
              "size specified by this flag. Else Paddle will reallocate by "
              "FLAGS_fraction_of_gpu_memory_to_use");
#endif
<commit_msg>Add document annotations for FLAGS that need to be open to external developers test=develop (#19692)<commit_after>// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// 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 "gflags/gflags.h"
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/platform/cudnn_workspace_helper.h"
#endif

/**
 * NOTE(paddle-dev): This file is designed to define all public FLAGS.
 */

/**
 * Paddle initialization related FLAG
 * Name: FLAGS_paddle_num_threads
 * Since Version: 0.15.0
 * Value Range: int32, default=1
 * Example: FLAGS_paddle_num_threads=2, set the maximum thread number per
 * instance to 2
 * Note:
 */
DEFINE_int32(paddle_num_threads, 1,
             "Number of threads for each paddle instance.");

/**
 * Operator related FLAG
 * Name: FLAGS_check_nan_inf
 * Since Version: 0.13.0
 * Value Range: bool, default=false
 * Example:
 * Note: Used to debug. Checking whether operator produce NAN/INF or not.
 */
DEFINE_bool(check_nan_inf, false,
            "Checking whether operator produce NAN/INF or not. It will be "
            "extremely slow so please use this flag wisely.");

#ifdef PADDLE_WITH_CUDA

/**
 * CUDA related related FLAG
 * Name: FLAGS_enable_cublas_tensor_op_math
 * Since Version: 1.2.0
 * Value Range: bool, default=false
 * Example:
 * Note: whether to use Tensor Core, faster but it may loss precision.
 */
DEFINE_bool(
    enable_cublas_tensor_op_math, false,
    "The enable_cublas_tensor_op_math indicate whether to use Tensor Core, "
    "but it may loss precision. Currently, There are two CUDA libraries that"
    " use Tensor Cores, cuBLAS and cuDNN. cuBLAS uses Tensor Cores to speed up"
    " GEMM computations(the matrices must be either half precision or single "
    "precision); cuDNN uses Tensor Cores to speed up both convolutions(the "
    "input and output must be half precision) and recurrent neural networks "
    "(RNNs).");

/**
 * CUDA related FLAG
 * Name: FLAGS_selected_gpus
 * Since Version: 1.3.0
 * Value Range: integer list separated by comma, default empty list
 * Example: FLAGS_selected_gpus=0,1,2,3,4,5,6,7 to train or predict with 0~7 gpu
 * cards
 * Note: A list of device ids separated by comma, like: 0,1,2,3
 */
DEFINE_string(selected_gpus, "",
              "A list of device ids separated by comma, like: 0,1,2,3. "
              "This option is useful when doing multi process training and "
              "each process have only one device (GPU). If you want to use "
              "all visible devices, set this to empty string. NOTE: the "
              "reason of doing this is that we want to use P2P communication"
              "between GPU devices, use CUDA_VISIBLE_DEVICES can only use"
              "share-memory only.");
#endif

#ifdef PADDLE_WITH_CUDA

/**
 * CUDNN related FLAG
 * Name: FLAGS_cudnn_deterministic
 * Since Version: 0.13.0
 * Value Range: bool, default=false
 * Example:
 * Note: whether to use deterministic algorithm in cudnn.
 *       If true, it will slow down some operators such as conv and pooling.
 */
DEFINE_bool(cudnn_deterministic, false,
            "Whether allow using an autotuning algorithm for convolution "
            "operator. The autotuning algorithm may be non-deterministic. If "
            "true, the algorithm is deterministic.");

/**
 * CUDNN related FLAG
 * Name: FLAGS_conv_workspace_size_limit
 * Since Version: 0.13.0
 * Value Range: uint64, default=4096 (MB)
 * Example:
 * Note: The internal function of cuDNN obtains the fastest matching algorithm
 *       within this memory limit. Usually, faster algorithms can be chosen in
 *       larger workspaces, but memory space can also be significantly
 * increased.
 *       Users need to balance memory and speed.
 */
DEFINE_uint64(conv_workspace_size_limit,
              paddle::platform::kDefaultConvWorkspaceSizeLimitMB,
              "cuDNN convolution workspace limit in MB unit.");

/**
 * CUDNN related FLAG
 * Name: FLAGS_cudnn_exhaustive_search
 * Since Version: 1.2.0
 * Value Range: bool, default=false
 * Example:
 * Note: Represents whether an exhaustive search method is used to
 *       select a convolution algorithm. There are two search methods in cuDNN,
 *       heuristic search and exhaustive search. Exhaustive search attempts
 *       all cuDNN algorithms to select the fastest. This method is very
 *       time-consuming, and the selected algorithm will be cached for a given
 *       layer specification. Once you change the layer specifications
 *       (such as batch size, feature map size), it will search again.
 */
DEFINE_bool(cudnn_exhaustive_search, false,
            "Whether enable exhaustive search for cuDNN convolution or "
            "not, default is False.");

/**
 * CUDNN related FLAG
 * Name: FLAGS_cudnn_exhaustive_search_times
 * Since Version:
 * Value Range:
 * Example:
 * Note: only used to predict for advanced developer
 */
DEFINE_int64(cudnn_exhaustive_search_times, -1,
             "Exhaustive search times for cuDNN convolution, "
             "default is -1, not exhaustive search");

/**
 * CUDNN related FLAG
 * Name: FLAGS_cudnn_batchnorm_spatial_persistent
 * Since Version: 1.4.0
 * Value Range: bool, default=false
 * Example:
 * Note: CUDNN_BATCHNORM_SPATIAL_PERSISTENT in batchnorm. This mode can be
 * faster in
 *       some tasks because an optimized path may be selected for
 * CUDNN_DATA_FLOAT
 *       and CUDNN_DATA_HALF data types, compute capability 6.0 or higher. The
 *       reason we set it to false by default is that this mode may use scaled
 *       atomic integer reduction that may cause a numerical overflow for
 * certain
 *       input data range.
 */
DEFINE_bool(cudnn_batchnorm_spatial_persistent, false,
            "Whether enable CUDNN_BATCHNORM_SPATIAL_PERSISTENT mode for cudnn "
            "batch_norm, default is False.");
#endif

#ifdef PADDLE_WITH_CUDA

/**
 * NCCL related FLAG
 * Name: FLAGS_enable_cublas_tensor_op_math
 * Since Version:
 * Value Range:
 * Example:
 * Note: asynchronous nccl allreduce or synchronous issue:
 *       https://github.com/PaddlePaddle/Paddle/issues/15049
 *       If you want to change this default value, why?(gongwb)
 */
DEFINE_bool(
    sync_nccl_allreduce, true,
    "If set true, will call `cudaStreamSynchronize(nccl_stream)`"
    "after allreduce, this mode can get better performance in some scenarios.");
#endif

#ifdef PADDLE_WITH_DISTRIBUTE
/**
 * Distributed related FLAG
 * Name: FLAGS_communicator_max_merge_var_num
 * Since Version: 1.5.0
 * Value Range: int32, default=20
 * Example:
 * Note: The maximum number of gradients to be merged into a gradient and
 *       sent through the communicator. The trainer puts all the gradients
 *       into the queue, and then the communicator takes the gradients out
 *       of the queue and sends them after merging.
 */
DEFINE_int32(communicator_max_merge_var_num, 20,
             "max var num to merge and send");

/**
 * Distributed related FLAG
 * Name: FLAGS_communicator_send_queue_size
 * Since Version: 1.5.0
 * Value Range: int32, default=20
 * Example:
 * Note: Size for each gradient queue. The trainer puts the gradient into
 *       the queue, and then the communicator takes it out of the queue and
 *       sends it out. When the communicator is slow, the queue may be full,
 *       and the trainer will be continuously blocked before the queue has
 *       space. It is used to avoid training much faster than communication,
 *       so that too many gradients are not sent out in time.
 */
DEFINE_int32(communicator_send_queue_size, 20,
             "queue size to recv gradient before send");
#endif

/**
 * Distributed related FLAG
 * Name: FLAGS_dist_threadpool_size
 * Since Version: 1.0.0
 * Value Range: int32, default=0
 * Example:
 * Note: Control the number of threads used for distributed modules.
 *       If it is not set, it is set to a hard thread.
 */
DEFINE_int32(dist_threadpool_size, 0,
             "number of threads used for distributed executed.");

/**
 * Garbage collector related FLAG
 * Name: FLAGS_eager_delete_tensor_gb
 * Since Version: 1.0.0
 * Value Range: double, default=kDefaultEagerDeleteTensorGB
 * Example: FLAGS_eager_delete_tensor_gb=0.0, Release memory garbage once it is
 * no longer used.
 *          FLAGS_eager_delete_tensor_gb=1.0, Release memory garbage when
 * garbage occupies 1.0GB of memory.
 *          FLAGS_eager_delete_tensor_gb=-1.0, Disable garbage collection
 * policy.
 * Note: Represents whether a garbage collection strategy is used to optimize
 * network memory usage.
 *       It is recommended that users set FLAGS_eager_delete_tensor_gb=0.0 to
 *       enable garbage collection strategy when training large networks.
 */
// Disable gc by default when inference library is built
#ifdef PADDLE_ON_INFERENCE
static const double kDefaultEagerDeleteTensorGB = -1;
#else
static const double kDefaultEagerDeleteTensorGB = 0;
#endif

DEFINE_double(
    eager_delete_tensor_gb, kDefaultEagerDeleteTensorGB,
    "Memory size threshold (GB) when the garbage collector clear tensors."
    "Disabled when this value is less than 0");

/**
 * Memory related FLAG
 * Name: FLAGS_fast_eager_deletion_mode
 * Since Version: 1.3.0
 * Value Range: bool, default=true
 * Example:
 * Note: Whether to use fast garbage collection strategy.
 *       If not set, the GPU memory is released at the end of the CUDA kernel.
 *       Otherwise, the GPU memory will be released before the CUDA kernel
 *       has finished, which will make the garbage collection strategy faster.
 *       Only works when garbage collection strategy is enabled.
 */
DEFINE_bool(fast_eager_deletion_mode, true,
            "Fast eager deletion mode. If enabled, memory would release "
            "immediately without waiting GPU kernel ends.");

/**
 * Memory related FLAG
 * Name: FLAGS_memory_fraction_of_eager_deletion
 * Since Version: 1.4
 * Value Range: double [0.0, 1.0], default=1.0
 * Example:
 * Note: The percentage of memory size of garbage collection policy
 *       to release variables.
 *       If FLAGS_memory_fraction_of_eager_deletion = 1.0,
 *       all temporary variables in the network will be released.
 *       If FLAGS_memory_fraction_of_eager_deletion = 0.0,
 *       no temporary variables in the network are released.
 *       If 0.0 < FLAGS_memory_fraction_of_eager_deletion < 1.0,
 *       all temporary variables will be sorted in descending order
 *       according to their memory size, and only variables with the
 *       largest FLAGS_memory_fraction_of_eager_deletion ratio will be released.
 *       The flag is only valid when running parallel data compilers.
 */
DEFINE_double(memory_fraction_of_eager_deletion, 1.0,
              "Fraction of eager deletion. If less than 1.0, all variables in "
              "the program would be sorted according to its memory size, and "
              "only the FLAGS_memory_fraction_of_eager_deletion of the largest "
              "variables would be deleted.");

/**
 * Allocator related FLAG
 * Name: FLAGS_allocator_strategy
 * Since Version: 1.2
 * Value Range: string, {naive_best_fit, auto_groth}, default=naive_best_fit
 * Example:
 * Note: Allocator policy for selecting Paddle Paddle.
 *       The allocator strategy is under development and the non-legacy
 *       allocator is not yet stable.
 */
DEFINE_string(allocator_strategy, "naive_best_fit",
              "The allocation strategy. naive_best_fit means the original best "
              "fit allocator of Fluid. "
              "auto_growth means the experimental auto-growth allocator. "
              "Enum in [naive_best_fit, auto_growth].");

/**
 * Memory related FLAG
 * Name: FLAGS_fraction_of_cpu_memory_to_use
 * Since Version:
 * Value Range:
 * Example:
 * Note:
 */
DEFINE_double(fraction_of_cpu_memory_to_use, 1,
              "Default use 100% of CPU memory for PaddlePaddle,"
              "reserve the rest for page tables, etc");

/**
 * Memory related FLAG
 * Name: FLAGS_initial_cpu_memory_in_mb
 * Since Version: 0.14.0
 * Value Range: uint64, default=500 (MB)
 * Example:
 * Note: The CPU memory block size of the initial allocator in MB.
 *       The allocator takes the minimum values of
 *       FLAGS_initial_cpu_memory_in_mb and
 *       FLAGS_fraction_of_cpu_memory_to_use*(total physical memory)
 *       as memory block sizes.
 */
DEFINE_uint64(initial_cpu_memory_in_mb, 500ul,
              "Initial CPU memory for PaddlePaddle, in MD unit.");

/**
 * Memory related FLAG
 * Name: FLAGS_fraction_of_cuda_pinned_memory_to_use
 * Since Version:
 * Value Range:
 * Example:
 * Note:
 */
DEFINE_double(
    fraction_of_cuda_pinned_memory_to_use, 0.5,
    "Default use 50% of CPU memory as the pinned_memory for PaddlePaddle,"
    "reserve the rest for page tables, etc");

#ifdef PADDLE_WITH_CUDA

/**
 * Memory related FLAG
 * Name: FLAGS_fraction_of_gpu_memory_to_use
 * Since Version: 1.2.0
 * Value Range: double, default=0.5 if win32, 0.92 else
 * Example:
 * Note: Represents the proportion of allocated memory blocks to the total
 * memory size
 *       of the GPU. Future memory usage will be allocated from this memory
 * block.
 *       If the memory block does not have enough GPU memory, new memory blocks
 * of
 *       the same size as the memory block will be allocated from the GPU
 * request
 *       until the GPU does not have enough memory.
 */

#ifndef _WIN32
constexpr static float fraction_of_gpu_memory_to_use = 0.92f;
#else
// fraction_of_gpu_memory_to_use cannot be too high on windows,
// since the win32 graphic sub-system can occupy some GPU memory
// which may lead to insufficient memory left for paddle
constexpr static float fraction_of_gpu_memory_to_use = 0.5f;
#endif
DEFINE_double(fraction_of_gpu_memory_to_use, fraction_of_gpu_memory_to_use,
              "Allocate a trunk of gpu memory that is this fraction of the "
              "total gpu memory size. Future memory usage will be allocated "
              "from the trunk. If the trunk doesn't have enough gpu memory, "
              "additional trunks of the same size will be requested from gpu "
              "until the gpu has no memory left for another trunk.");

/**
 * Memory related FLAG
 * Name: FLAGS_initial_gpu_memory_in_mb
 * Since Version: 1.4.0
 * Value Range: uint64, default=0 (MB)
 * Example:
 * Note: Allocate a specified size of GPU memory block. Later memory usage
 *       will be allocated from that memory block. If the memory block does not
 *       have enough GPU memory, the memory block with the size
 *       FLAGS_reallocate_gpu_memory_in_mb will be requested from the GPU until
 *       the GPU has no remaining memory.
 */
DEFINE_uint64(
    initial_gpu_memory_in_mb, 0ul,
    "Allocate a trunk of gpu memory whose byte size is specified by "
    "the flag. Future memory usage will be allocated from the "
    "trunk. If the trunk doesn't have enough gpu memory, additional "
    "trunks of the gpu memory will be requested from gpu with size "
    "specified by FLAGS_reallocate_gpu_memory_in_mb until the gpu has "
    "no memory left for the additional trunk. Note: if you set this "
    "flag, the memory size set by "
    "FLAGS_fraction_of_gpu_memory_to_use will be overrided by this "
    "flag. If you don't set this flag, PaddlePaddle will use "
    "FLAGS_fraction_of_gpu_memory_to_use to allocate gpu memory");

/**
 * Memory related FLAG
 * Name: FLAGS_reallocate_gpu_memory_in_mb
 * Since Version: 1.4.0
 * Value Range: uint64, default=0 (MB)
 * Example:
 * Note: If the allocated GPU memory blocks are exhausted,
 *       additional GPU memory blocks are reallocated
 */
DEFINE_uint64(reallocate_gpu_memory_in_mb, 0ul,
              "If this flag is set, Paddle will reallocate the gpu memory with "
              "size specified by this flag. Else Paddle will reallocate by "
              "FLAGS_fraction_of_gpu_memory_to_use");

#endif
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    $RCSfile: ANTS.cxx,v $
  Language:  C++
  Date:      $Date: 2008/11/15 23:46:05 $
  Version:   $Revision: 1.19 $

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

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

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

#include "itkPICSLAdvancedNormalizationToolKit.h"
#include "itkANTSImageTransformation.h"
#include "itkANTSImageRegistrationOptimizer.h"

#include <string>

template <unsigned int ImageDimension>
int ANTSex(int argc, char *argv[])
{
    typedef itk::PICSLAdvancedNormalizationToolKit<ImageDimension> RegistrationType;
    typename RegistrationType::Pointer registration = RegistrationType::New();
    registration->ParseCommandLine( argc, argv );
    std::cout << " Run Reg " << std::endl;
    try
      {
      registration->RunRegistration();
      }
    catch(...)
      {
      std::cerr << "Exception thrown: ANTS" << std::endl;
      return EXIT_FAILURE;
      }
    registration->GetTransformationModel()->SetWriteComponentImages(true);
    registration->GetTransformationModel()->Write();

    return EXIT_SUCCESS;

}

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

  int  dim = 2;
//  while(argc--) printf("%s\n", *argv++);
    if ( argc < 2 )
    {
    std::cout <<  "  Call  to get detailed usage :  \n    ANTS -h  \n or  \n ANTS --help \n \n  " << std::endl;
    std::cout << " typical use, for a 3D image matching with mutual information : \n  ANTS  3  -m MI[fixedimage.nii,movingimage.nii,1,32] -o MutualInformationMapping.nii -i 30x20x0 -r Gauss[3,1] -t Elast[3] "  << std::endl;
    std::cout << " the value 32 in the metric call ( -m MI[ ...] ) is the joint histogram # of bins " << std::endl;
    std::cout << " the transformation model is elastic with gradient descent step-length of 3 " << std::endl;
    std::cout << "  3 levels of optimization with 30 iterations at the coarsest (fastest) level, 20 at the next and 0 at full resolution " << std::endl;
    std::cout << " \n typical use, for a 3D image matching with correlation : \n  ANTS  3  -m PR[fixedimage.nii,movingimage.nii,1,2] -o CC.nii -i 30x20x0 -r Gauss[3,0] -t SyN[1] "  << std::endl;
    std::cout << " the value 2 in the metric call ( -m PR[ ...] ) is the radius of the correlation window " << std::endl;
    std::cout << " the transformation is the greedy symmetric diffeomorphic mapping  with xgradient descent step-length of  1" << std::endl;
    std::cout << " \n typical use, for a 3D image matching with correlation implementation 2 : \n  ANTS  3  -m CC[fixedimage.nii,movingimage.nii,1,2] -o CC2.nii -i 30x20x0 -r Gauss[3,0.5] -t SyN[1,2,0.1] "  << std::endl;
    std::cout << " the value 2 in the metric call ( -m CC[ ...] ) is the radius of the correlation window " << std::endl;
    std::cout << " the transformation is the symmetric diffeomorphic mapping with time-varying velocity fied - 10 integration points in time and gradient step length of 1 " << std::endl;
    std::cout <<  " \n Call  to get detailed usage :  \n    ANTS -h  \n or  \n ANTS --help \n \n  " << std::endl;
    return 1;
    }
    else  dim = atoi( argv[1] );

    if ( dim <= 1 || dim > 3 )
      {
      std::cout <<" you passed image dimension (first argument) as " << dim << " ANTS does not function with images of this dimension " << std::endl;
      argv[1]=(char*)("--help");
      ANTSex<2>( argc,argv );
      exit(1);
      }
    /**
     * Try the simple case of the call "ANTS fixedImage movingImage"
     */
    if( argc == 3 && ( atoi( argv[1] ) != 2 || atoi( argv[1] ) != 3 ) )
      {
      itk::ImageIOBase::Pointer fixedImageIO
        = itk::ImageIOFactory::CreateImageIO(
          argv[1], itk::ImageIOFactory::ReadMode );
      if( fixedImageIO.IsNull() )
        {
        std::cerr << "Invalid fixed image: " << argv[1] << std::endl;
        return EXIT_FAILURE;
        }
      itk::ImageIOBase::Pointer movingImageIO
        = itk::ImageIOFactory::CreateImageIO(
          argv[2], itk::ImageIOFactory::ReadMode );
      if( movingImageIO.IsNull() )
        {
        std::cerr << "Invalid moving image: " << argv[2] << std::endl;
        return EXIT_FAILURE;
        }
      fixedImageIO->SetFileName( argv[1] );
      fixedImageIO->ReadImageInformation();
      movingImageIO->SetFileName( argv[2] );
      movingImageIO->ReadImageInformation();

      unsigned int fdim = fixedImageIO->GetNumberOfDimensions();
      unsigned int mdim = movingImageIO->GetNumberOfDimensions();

      if( fdim != mdim )
        {
        std::cerr << "Fixed image dimension does not equal "
          << "the moving image dimension (" << fdim << " != " << mdim << ")"
          << std::endl;
        return EXIT_FAILURE;
        }
      if( fdim != 2 && fdim != 3 )
        {
        std::cerr << "Unsupported image dimension" << std::endl;
        return EXIT_FAILURE;
        }

      /**
       * After the checking, we can add the default parameters;
       */
      std::string arguments;

      std::string transformation( " -t SyN[1.0] ");
      std::string regularization( " -r Gauss[3,0.5] ");
      std::string metric = std::string( " -m PR[" ) + std::string( argv[1] )
        + std::string( "," ) + std::string( argv[2] ) + std::string( ",1,3] " );
      std::string outputNaming( " -o ANTS.nii.gz " );

      long maxSize = vnl_math_min( fixedImageIO->GetDimensions( 0 ),
        movingImageIO->GetDimensions( 0 ) );
      for( unsigned int d = 1; d < fdim; d++ )
        {
        long tmpMax = vnl_math_max( fixedImageIO->GetDimensions( d ),
          movingImageIO->GetDimensions( d ) );
        if( maxSize < tmpMax )
          {
          maxSize = tmpMax;
          }
        }

      unsigned int numberOfLevels = static_cast<unsigned int>(
        vcl_log( (double)maxSize / 32 ) / vcl_log( (double) 2 ) ) + 1;
      std::string iterations( " -i " );
      for( int n = numberOfLevels; n > 0; n-- )
        {
        itk::OStringStream buf;
        unsigned long numberOfIterations = ( 5 << (n-1) );
        buf << numberOfIterations << "x";
        iterations += buf.str();
        }
      iterations = iterations.substr( 0, iterations.length()-1 );

      itk::OStringStream dimBuf;
      dimBuf << fdim;
      arguments.clear();
      arguments = std::string( " ANTS " ) + dimBuf.str() + iterations +
        transformation + regularization + metric + outputNaming;

      dim = fdim;

      std::cout << arguments << std::endl;

      unsigned int my_argc = 0;
      std::string::size_type delimPos = 0;
      std::string::size_type tokenPos = 0;
      std::string::size_type pos = 0;
      while( true )
        {
        delimPos = arguments.find_first_of( " ", pos );
        tokenPos = arguments.find_first_not_of( " ", pos );
        if( std::string::npos != delimPos &&
          std::string::npos != tokenPos && tokenPos < delimPos )
          {
          my_argc++;
          }
        else if( std::string::npos == delimPos )
          {
          if( std::string::npos != tokenPos )
            {
            my_argc++;
            }
          else
            {
            break;
            }
          }
        pos = delimPos + 1;
        }

      unsigned int arg_count = 0;
      char **my_argv = new char*[my_argc];
      delimPos = 0;
      tokenPos = 0;
      pos = 0;
      while( true )
        {
        delimPos = arguments.find_first_of( " ", pos );
        tokenPos = arguments.find_first_not_of( " ", pos );
        if( std::string::npos != delimPos &&
          std::string::npos != tokenPos && tokenPos < delimPos )
          {
          std::string arg = arguments.substr( pos, delimPos-pos );
          my_argv[arg_count] = new char[arg.size() + 1];
          strcpy( my_argv[arg_count], arg.c_str() );
          arg_count++;
          }
        else if( std::string::npos == delimPos )
          {
          if( std::string::npos != tokenPos )
            {
            std::string arg = arguments.substr( pos );
            my_argv[arg_count] = new char[arg.size() + 1];
            strcpy( my_argv[arg_count], arg.c_str() );
            arg_count++;
            }
          else
            {
            break;
            }
          }
        pos = delimPos + 1;
        }

      switch ( dim )
        {
        case 3:
          ANTSex<3>( my_argc, my_argv );
          break;
        default:
          ANTSex<2>( my_argc, my_argv );
        }
      }
    else
      {
      switch ( dim )
        {
        case 3:
          ANTSex<3>( argc, argv );
          break;
        default:
          ANTSex<2>( argc, argv );
        }
      }

    return EXIT_SUCCESS;
}

<commit_msg> Thanks NM vanStrien <commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    $RCSfile: ANTS.cxx,v $
  Language:  C++
  Date:      $Date: 2008/11/15 23:46:05 $
  Version:   $Revision: 1.19 $

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

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

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

#include "itkPICSLAdvancedNormalizationToolKit.h"
#include "itkANTSImageTransformation.h"
#include "itkANTSImageRegistrationOptimizer.h"

#include <string>

template <unsigned int ImageDimension>
int ANTSex(int argc, char *argv[])
{
    typedef itk::PICSLAdvancedNormalizationToolKit<ImageDimension> RegistrationType;
    typename RegistrationType::Pointer registration = RegistrationType::New();
    registration->ParseCommandLine( argc, argv );
    std::cout << " Run Reg " << std::endl;
    try
      {
      registration->RunRegistration();
      }
    catch(...)
      {
      std::cerr << "Exception thrown: ANTS" << std::endl;
      return EXIT_FAILURE;
      }
    registration->GetTransformationModel()->SetWriteComponentImages(true);
    registration->GetTransformationModel()->Write();

    return EXIT_SUCCESS;

}

int main(int argc, char *argv[] )
{
  int  dim = 2;
//  while(argc--) printf("%s\n", *argv++);
    if ( argc < 2 )
    {
    std::cout <<  " \n " << std::endl;
    std::cout <<  "Example usage: \n " << std::endl;
    std::cout << argv[0] <<  " ImageDimension -m MI[fixedimage.nii.gz,movingimage.nii.gz,1,32] -o Outputfname.nii.gz -i 30x20x0 -r Gauss[3,1] -t Elast[3] \n \n " << std::endl;
    std::cout << " Compulsory arguments:\n " << std::endl;
    std::cout << " ImageDimension: 2 or 3 (for 2 or 3 Dimensional registration)\n " << std::endl;
    std::cout << " -m:	Type of similarity model used for registration. \n " << std::endl;
    std::cout << "	For intramodal image registration, use: " << std::endl;
    std::cout << "		CC = cross-correlation " << std::endl;
    std::cout << "		MI = mutual information " << std::endl;
    std::cout << "		PR = probability mapping " << std::endl;
    std::cout << "		MSQ = mean square difference " << std::endl;
    std::cout << " \n " << std::endl;
    std::cout << "	For intermodal image registration, use: " << std::endl;
    std::cout << "		MI = mutual information " << std::endl;
    std::cout << "		PR = probability mapping " << std::endl;
    std::cout << " \n " << std::endl;
    std::cout << " -o 	Outputfname.nii.gz: the name of the resulting image.\n " << std::endl;
    std::cout << " -i 	Max-iterations in format: JxKxL, where: " << std::endl;
    std::cout << "		J = max iterations at coarsest resolution (here, reduce by power of 2^2) " << std::endl;
    std::cout << "		K = middle resolution iterations (here,reduce by power of 2) " << std::endl;
    std::cout << "		L = fine resolution iterations (here, full resolution). This level takes much more time per iteration!\n " << std::endl;
    std::cout << "    	Adding an extra value before JxKxL (i.e. resulting in IxJxKxL) would add another iteration level.\n " << std::endl;
    std::cout << " -r 	Regularization \n" << std::endl;
    std::cout << " -t 	Type of transformation model used for registration \n" << std::endl;
    std::cout << "	For elastic image registration, use: " << std::endl;
    std::cout << "		Elast = elastic transformation model (less deformation possible)\n " << std::endl;
    std::cout << "	For diffeomorphic image registration, use: " << std::endl;
    std::cout << "		Syn[GradStep,TimePoints,IntegrationStep] --geodesic 2 = SyN with time with arbitrary number of time points in time discretization  " << std::endl;
    std::cout << "		SyN[GradStep,2,IntegrationStep] = SyN with time optimized specifically for 2 time points in the time discretization " << std::endl;
    std::cout << "		SyN[GradStep] = Greedy SyN, typicall GradStep=0.25  " << std::endl;
    std::cout << "		Exp[GradStep,TimePoints] = Exponential " << std::endl;
    std::cout << "		GreedyExp = Diffeomorphic Demons style exponential mapping " << std::endl;
    std::cout << " \n " << std::endl;
    std::cout << " Please use the "ANTS -h " call or refer to the ANTS.pdf manual or antsIntroduction.sh script for additional information and typical values for transformation models\n " << std::endl;
    return 1;
    }
    else  dim = atoi( argv[1] );

    if ( dim <= 1 || dim > 3 )
      {
      std::cout <<" You passed ImageDimension: " << dim << " . Please use only 2 or 3 (for 2 or 3 Dimensional registration)  " << std::endl;
      argv[1]=(char*)("--help");
      ANTSex<2>( argc,argv );
      exit(1);
      }
    /**
     * Try the simple case of the call "ANTS fixedImage movingImage"
     */
    if( argc == 3 && ( atoi( argv[1] ) != 2 || atoi( argv[1] ) != 3 ) )
      {
      itk::ImageIOBase::Pointer fixedImageIO
        = itk::ImageIOFactory::CreateImageIO(
          argv[1], itk::ImageIOFactory::ReadMode );
      if( fixedImageIO.IsNull() )
        {
        std::cerr << "Invalid fixed image: " << argv[1] << std::endl;
        return EXIT_FAILURE;
        }
      itk::ImageIOBase::Pointer movingImageIO
        = itk::ImageIOFactory::CreateImageIO(
          argv[2], itk::ImageIOFactory::ReadMode );
      if( movingImageIO.IsNull() )
        {
        std::cerr << "Invalid moving image: " << argv[2] << std::endl;
        return EXIT_FAILURE;
        }
      fixedImageIO->SetFileName( argv[1] );
      fixedImageIO->ReadImageInformation();
      movingImageIO->SetFileName( argv[2] );
      movingImageIO->ReadImageInformation();

      unsigned int fdim = fixedImageIO->GetNumberOfDimensions();
      unsigned int mdim = movingImageIO->GetNumberOfDimensions();

      if( fdim != mdim )
        {
        std::cerr << "Fixed image dimension does not equal "
          << "the moving image dimension (" << fdim << " != " << mdim << ")"
          << std::endl;
        return EXIT_FAILURE;
        }
      if( fdim != 2 && fdim != 3 )
        {
        std::cerr << "Unsupported image dimension" << std::endl;
        return EXIT_FAILURE;
        }

      /**
       * After the checking, we can add the default parameters;
       */
      std::string arguments;

      std::string transformation( " -t SyN[1.0] ");
      std::string regularization( " -r Gauss[3,0.5] ");
      std::string metric = std::string( " -m PR[" ) + std::string( argv[1] )
        + std::string( "," ) + std::string( argv[2] ) + std::string( ",1,3] " );
      std::string outputNaming( " -o ANTS.nii.gz " );

      long maxSize = vnl_math_min( fixedImageIO->GetDimensions( 0 ),
        movingImageIO->GetDimensions( 0 ) );
      for( unsigned int d = 1; d < fdim; d++ )
        {
        long tmpMax = vnl_math_max( fixedImageIO->GetDimensions( d ),
          movingImageIO->GetDimensions( d ) );
        if( maxSize < tmpMax )
          {
          maxSize = tmpMax;
          }
        }

      unsigned int numberOfLevels = static_cast<unsigned int>(
        vcl_log( (double)maxSize / 32 ) / vcl_log( (double) 2 ) ) + 1;
      std::string iterations( " -i " );
      for( int n = numberOfLevels; n > 0; n-- )
        {
        itk::OStringStream buf;
        unsigned long numberOfIterations = ( 5 << (n-1) );
        buf << numberOfIterations << "x";
        iterations += buf.str();
        }
      iterations = iterations.substr( 0, iterations.length()-1 );

      itk::OStringStream dimBuf;
      dimBuf << fdim;
      arguments.clear();
      arguments = std::string( " ANTS " ) + dimBuf.str() + iterations +
        transformation + regularization + metric + outputNaming;

      dim = fdim;

      std::cout << arguments << std::endl;

      unsigned int my_argc = 0;
      std::string::size_type delimPos = 0;
      std::string::size_type tokenPos = 0;
      std::string::size_type pos = 0;
      while( true )
        {
        delimPos = arguments.find_first_of( " ", pos );
        tokenPos = arguments.find_first_not_of( " ", pos );
        if( std::string::npos != delimPos &&
          std::string::npos != tokenPos && tokenPos < delimPos )
          {
          my_argc++;
          }
        else if( std::string::npos == delimPos )
          {
          if( std::string::npos != tokenPos )
            {
            my_argc++;
            }
          else
            {
            break;
            }
          }
        pos = delimPos + 1;
        }

      unsigned int arg_count = 0;
      char **my_argv = new char*[my_argc];
      delimPos = 0;
      tokenPos = 0;
      pos = 0;
      while( true )
        {
        delimPos = arguments.find_first_of( " ", pos );
        tokenPos = arguments.find_first_not_of( " ", pos );
        if( std::string::npos != delimPos &&
          std::string::npos != tokenPos && tokenPos < delimPos )
          {
          std::string arg = arguments.substr( pos, delimPos-pos );
          my_argv[arg_count] = new char[arg.size() + 1];
          strcpy( my_argv[arg_count], arg.c_str() );
          arg_count++;
          }
        else if( std::string::npos == delimPos )
          {
          if( std::string::npos != tokenPos )
            {
            std::string arg = arguments.substr( pos );
            my_argv[arg_count] = new char[arg.size() + 1];
            strcpy( my_argv[arg_count], arg.c_str() );
            arg_count++;
            }
          else
            {
            break;
            }
          }
        pos = delimPos + 1;
        }

      switch ( dim )
        {
        case 3:
          ANTSex<3>( my_argc, my_argv );
          break;
        default:
          ANTSex<2>( my_argc, my_argv );
        }
      }
    else
      {
      switch ( dim )
        {
        case 3:
          ANTSex<3>( argc, argv );
          break;
        default:
          ANTSex<2>( argc, argv );
        }
      }

    return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2018 Google Inc.
 *
 * 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 <cstdint>
#include <cstring>
#include <iostream>
#include <string>

#if _WIN32
#include <fcntl.h>
#include <stdio.h>
#endif

#include <google/protobuf/util/json_util.h>
#include "core/os/device/device.pb.h"
#include "core/os/device/deviceinfo/cc/instance.h"

void print_help() {
  std::cout << "Usage: device-info [--binary]" << std::endl;
  std::cout << "Output information about the current device." << std::endl;
  std::cout << " --binary         Output a binary protobuf instead of json"
            << std::endl;
}

int main(int argc, char const *argv[]) {
  bool output_binary = false;
  for (int i = 1; i < argc; ++i) {
    if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-help") == 0 ||
        strcmp(argv[i], "-h") == 0) {
      print_help();
      return 0;
    } else if (strcmp(argv[i], "--binary") == 0) {
      output_binary = true;
    } else {
      print_help();
      return -1;
    }
  }

  device_instance instance = get_device_instance();
  if (output_binary) {
#if _WIN32
    _setmode(_fileno(stdout), _O_BINARY);
#endif
    std::cout << std::string(reinterpret_cast<char *>(instance.data),
                             instance.size);
  } else {
    device::Instance device_inst;
    if (!device_inst.ParseFromArray(instance.data, instance.size)) {
      std::cerr << "Internal error." << std::endl;
      free_device_instance(instance);
      return -1;
    }
    std::string output;
    google::protobuf::util::JsonPrintOptions options;
    options.add_whitespace = true;
    if (google::protobuf::util::Status::OK !=
        google::protobuf::util::MessageToJsonString(device_inst, &output,
                                                    options)) {
      std::cerr << "Internal error: Could not convert to json" << std::endl;
      free_device_instance(instance);
      return -1;
    }
    std::cout << output;
  }

  free_device_instance(instance);

  return 0;
}
<commit_msg>Use logging function for error reporting (#2694)<commit_after>/*
 * Copyright (C) 2018 Google Inc.
 *
 * 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 <cstdint>
#include <cstring>
#include <iostream>
#include <string>

#if _WIN32
#include <fcntl.h>
#include <stdio.h>
#endif

#include <google/protobuf/util/json_util.h>
#include "core/cc/log.h"
#include "core/os/device/device.pb.h"
#include "core/os/device/deviceinfo/cc/instance.h"

void print_help() {
  std::cout << "Usage: device-info [--binary]" << std::endl;
  std::cout << "Output information about the current device." << std::endl;
  std::cout << " --binary         Output a binary protobuf instead of json"
            << std::endl;
}

int main(int argc, char const *argv[]) {
  bool output_binary = false;
  for (int i = 1; i < argc; ++i) {
    if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-help") == 0 ||
        strcmp(argv[i], "-h") == 0) {
      print_help();
      return 0;
    } else if (strcmp(argv[i], "--binary") == 0) {
      output_binary = true;
    } else {
      print_help();
      return -1;
    }
  }

  device_instance instance = get_device_instance();
  if (output_binary) {
#if _WIN32
    _setmode(_fileno(stdout), _O_BINARY);
#endif
    std::cout << std::string(reinterpret_cast<char *>(instance.data),
                             instance.size);
  } else {
    device::Instance device_inst;
    if (!device_inst.ParseFromArray(instance.data, instance.size)) {
      GAPID_ERROR("Internal error");
      free_device_instance(instance);
      return -1;
    }
    std::string output;
    google::protobuf::util::JsonPrintOptions options;
    options.add_whitespace = true;
    if (google::protobuf::util::Status::OK !=
        google::protobuf::util::MessageToJsonString(device_inst, &output,
                                                    options)) {
      GAPID_ERROR("Internal error: Could not convert to json");
      free_device_instance(instance);
      return -1;
    }
    std::cout << output;
  }

  free_device_instance(instance);

  return 0;
}
<|endoftext|>