<commit_before>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file observation_model_interface.hpp
 * \date October 2014
 * \author Jan Issac (jan.issac@gmail.com)
 */

#ifndef FL__MODEL__OBSERVATION__OBSERVATION_MODEL_INTERFACE_HPP
#define FL__MODEL__OBSERVATION__OBSERVATION_MODEL_INTERFACE_HPP

#include <fl/util/traits.hpp>

namespace fl
{

/**
 * \ingroup observation_models
 * \interface ObservationModelInterface
 *
 *
 * Represents the generic observation model interface of the model function
 * \f$h(x, w, \theta)\f$ where \f$x\f$ is the state,
 * \f$w\sim {\cal N}(0, 1)\f$ is a white noise term, and \f$\theta\f$ the
 * model variable parameters.
 *
 * \tparam Obsrv  Measurement type \f$y = h(x, w, \theta)\f$
 * \tparam State        State variate \f$x\f$
 * \tparam Noise        White noise variate term \f$w\sim {\cal N}(0, I)\f$
 * \tparam Id           Model id number
 */
template <
    typename Obsrv,
    typename State,
    typename Noise,
    int Id = 0
>
class ObservationModelInterface
    : public internal::ObsrvModelType
{
public:
    typedef internal::ObsrvModelType ModelType;

    /**
     * Evaluates the model function \f$y = h(x, w)\f$ where \f$x\f$ is the state
     * and \f$w\sim {\cal N}(0, 1)\f$ is a white noise parameter. Put
     * differently, \f$y = h(x, w)\f$ is a sample from the conditional model
     * distribution \f$p(y \mid x)\f$.
     *
     * \param state         The state variable \f$x\f$
     * \param noise         The noise term \f$w\f$
     * \param delta_time    Prediction time
     */
    virtual Obsrv predict_obsrv(const State& state,
                                const Noise& noise,
                                double delta_time) = 0;

    /**
     * \return Dimension of the state variable $\f$x\f$
     */
    virtual int state_dimension() const = 0;

    /**
     * \return Dimension of the noise term \f$w\f$
     */
    virtual int noise_dimension() const = 0;

    /**
     * \return Dimension of the measurement \f$h(x, w)\f$
     */
    virtual int obsrv_dimension() const = 0;

    /**
     * \return Model id number
     *
     * In case of multiple sensors of the same kind, this function returns the
     * id of the individual model.
     */
    virtual int id() const { return Id; }

    /**
     * Sets the model id
     *
     * \param new_id    Model's new ID
     */
    virtual void id(int) { /* const ID */ }
};

/**
 * \ingroup observation_models
 *
 * \brief This is the observation model interface with additive noise. The noise
 * is represented as uncorrelated covariance matrix \f$R\f$. The model function
 * is of the form
 *
 * \f$ y = h(x, \theta) + w \f$
 *
 * with noise term \f$w \sim {\cal N}(0, R)\f$. Since the noise is assumed to
 * be uncorrelated white noise, the \f$R\f$ matrix has a diagonal form \f$diag(
 * \sigma_1, \sigma_2, \ldots, \sigma_M)\f$. The representation of \f$R\f$ is a
 * vector containing the diagonal elements.
 *
 *
 * \copydoc ObservationModelInterface
 */
template <
    typename Obsrv,
    typename State,
    typename Noise,
    int Id = 0
>
class ANObservationModelInterface
    : public ObservationModelInterface<Obsrv, State, Noise, Id>
{
public:
    /**
     * Evaluates the model function \f$y = h(x)\f$ where \f$x\f$ is the state.
     *
     * \param state         The state variable \f$x\f$
     * \param delta_time    Prediction time
     */
    virtual Obsrv predict_obsrv(const State& state,
                                double delta_time) = 0;

    /**
     * \return Noise covariance \f$R = diag(\sigma_1, \sigma_2, \ldots,
     * \sigma_M)\f$ as a column vector containing the \f$\sigma_i\f$. The noise
     * covariance vector type is same as the noise variate type.
     */
    virtual Noise noise_covariance_vector() const = 0;
};

template <
    typename Obsrv_,
    typename State_,
    typename Noise_,
    int Id = 0
>
class ObservationFunction
{
public:
    typedef Obsrv_ Obsrv;
    typedef State_ State;
    typedef Noise_ Noise;

    /**
     * Evaluates the model function \f$y = h(x, w)\f$ where \f$x\f$ is the state
     * and \f$w\sim {\cal N}(0, 1)\f$ is a white noise parameter. Put
     * differently, \f$y = h(x, w)\f$ is a sample from the conditional model
     * distribution \f$p(y \mid x)\f$.
     *
     * \param state         The state variable \f$x\f$
     * \param noise         The noise term \f$w\f$
     * \param delta_time    Prediction time
     */
    virtual Obsrv observation(const State& state,
                              const Noise& noise) const = 0;

    /**
     * \return Dimension of the state variable $\f$x\f$
     */
    virtual int state_dimension() const = 0;

    /**
     * \return Dimension of the noise term \f$w\f$
     */
    virtual int noise_dimension() const = 0;

    /**
     * \return Dimension of the measurement \f$h(x, w)\f$
     */
    virtual int obsrv_dimension() const = 0;

    /**
     * \return Model id number
     *
     * In case of multiple sensors of the same kind, this function returns the
     * id of the individual model.
     */
    virtual int id() const { return Id; }

    /**
     * Sets the model id
     *
     * \param new_id    Model's new ID
     */
    virtual void id(int) { /* const ID */ }
};

}

#endif
<commit_msg>Moved ObservationFunction to the top as the main implementation until the old depricated version is removed<commit_after>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file observation_model_interface.hpp
 * \date October 2014
 * \author Jan Issac (jan.issac@gmail.com)
 */

#ifndef FL__MODEL__OBSERVATION__OBSERVATION_MODEL_INTERFACE_HPP
#define FL__MODEL__OBSERVATION__OBSERVATION_MODEL_INTERFACE_HPP

#include <fl/util/traits.hpp>

namespace fl
{

template <
    typename Obsrv_,
    typename State_,
    typename Noise_,
    int Id = 0
>
class ObservationFunction
{
public:
    typedef Obsrv_ Obsrv;
    typedef State_ State;
    typedef Noise_ Noise;

    /**
     * Evaluates the model function \f$y = h(x, w)\f$ where \f$x\f$ is the state
     * and \f$w\sim {\cal N}(0, 1)\f$ is a white noise parameter. Put
     * differently, \f$y = h(x, w)\f$ is a sample from the conditional model
     * distribution \f$p(y \mid x)\f$.
     *
     * \param state         The state variable \f$x\f$
     * \param noise         The noise term \f$w\f$
     * \param delta_time    Prediction time
     */
    virtual Obsrv observation(const State& state,
                              const Noise& noise) const = 0;

    /**
     * \return Dimension of the state variable $\f$x\f$
     */
    virtual int state_dimension() const = 0;

    /**
     * \return Dimension of the noise term \f$w\f$
     */
    virtual int noise_dimension() const = 0;

    /**
     * \return Dimension of the measurement \f$h(x, w)\f$
     */
    virtual int obsrv_dimension() const = 0;

    /**
     * \return Model id number
     *
     * In case of multiple sensors of the same kind, this function returns the
     * id of the individual model.
     */
    virtual int id() const { return Id; }

    /**
     * Sets the model id
     *
     * \param new_id    Model's new ID
     */
    virtual void id(int) { /* const ID */ }
};

/**
 * \ingroup observation_models
 * \interface ObservationModelInterface
 *
 *
 * Represents the generic observation model interface of the model function
 * \f$h(x, w, \theta)\f$ where \f$x\f$ is the state,
 * \f$w\sim {\cal N}(0, 1)\f$ is a white noise term, and \f$\theta\f$ the
 * model variable parameters.
 *
 * \tparam Obsrv  Measurement type \f$y = h(x, w, \theta)\f$
 * \tparam State        State variate \f$x\f$
 * \tparam Noise        White noise variate term \f$w\sim {\cal N}(0, I)\f$
 * \tparam Id           Model id number
 */
template <
    typename Obsrv,
    typename State,
    typename Noise,
    int Id = 0
>
class ObservationModelInterface
    : public internal::ObsrvModelType
{
public:
    typedef internal::ObsrvModelType ModelType;

    /**
     * Evaluates the model function \f$y = h(x, w)\f$ where \f$x\f$ is the state
     * and \f$w\sim {\cal N}(0, 1)\f$ is a white noise parameter. Put
     * differently, \f$y = h(x, w)\f$ is a sample from the conditional model
     * distribution \f$p(y \mid x)\f$.
     *
     * \param state         The state variable \f$x\f$
     * \param noise         The noise term \f$w\f$
     * \param delta_time    Prediction time
     */
    virtual Obsrv predict_obsrv(const State& state,
                                const Noise& noise,
                                double delta_time) = 0;

    /**
     * \return Dimension of the state variable $\f$x\f$
     */
    virtual int state_dimension() const = 0;

    /**
     * \return Dimension of the noise term \f$w\f$
     */
    virtual int noise_dimension() const = 0;

    /**
     * \return Dimension of the measurement \f$h(x, w)\f$
     */
    virtual int obsrv_dimension() const = 0;

    /**
     * \return Model id number
     *
     * In case of multiple sensors of the same kind, this function returns the
     * id of the individual model.
     */
    virtual int id() const { return Id; }

    /**
     * Sets the model id
     *
     * \param new_id    Model's new ID
     */
    virtual void id(int) { /* const ID */ }
};

/**
 * \ingroup observation_models
 *
 * \brief This is the observation model interface with additive noise. The noise
 * is represented as uncorrelated covariance matrix \f$R\f$. The model function
 * is of the form
 *
 * \f$ y = h(x, \theta) + w \f$
 *
 * with noise term \f$w \sim {\cal N}(0, R)\f$. Since the noise is assumed to
 * be uncorrelated white noise, the \f$R\f$ matrix has a diagonal form \f$diag(
 * \sigma_1, \sigma_2, \ldots, \sigma_M)\f$. The representation of \f$R\f$ is a
 * vector containing the diagonal elements.
 *
 *
 * \copydoc ObservationModelInterface
 */
template <
    typename Obsrv,
    typename State,
    typename Noise,
    int Id = 0
>
class ANObservationModelInterface
    : public ObservationModelInterface<Obsrv, State, Noise, Id>
{
public:
    /**
     * Evaluates the model function \f$y = h(x)\f$ where \f$x\f$ is the state.
     *
     * \param state         The state variable \f$x\f$
     * \param delta_time    Prediction time
     */
    virtual Obsrv predict_obsrv(const State& state,
                                double delta_time) = 0;

    /**
     * \return Noise covariance \f$R = diag(\sigma_1, \sigma_2, \ldots,
     * \sigma_M)\f$ as a column vector containing the \f$\sigma_i\f$. The noise
     * covariance vector type is same as the noise variate type.
     */
    virtual Noise noise_covariance_vector() const = 0;
};

}

#endif
<|endoftext|>


<commit_before><commit_msg>webdav: fix locking in webdav_ucp::Content::getResourceType()<commit_after><|endoftext|>


<commit_before>///
/// @file  S2_easy_libdivide.cpp
/// @brief This is an optimized version of S2_easy which uses
///        libdivide. libdivide allows to replace expensive integer
///        divides with comparatively cheap multiplication and
///        bitshifts.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <PiTable.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <generate.hpp>
#include <int128_t.hpp>
#include <min.hpp>
#include <imath.hpp>
#include <S2Status.hpp>
#include <S2.hpp>
#include <json.hpp>

#include <libdivide.h>
#include <stdint.h>
#include <vector>

#ifdef _OPENMP
  #include <omp.h>
#endif

using namespace std;
using namespace primecount;

namespace {

template <typename T>
void backup(T x,
            int64_t y,
            int64_t z,
            int64_t c,
            int64_t start,
            int64_t pi_x13,
            T s2_easy,
            double percent,
            double time)
{
  auto j = load_backup();

  j["S2_easy"]["x"] = to_string(x);
  j["S2_easy"]["y"] = y;
  j["S2_easy"]["z"] = z;
  j["S2_easy"]["c"] = c;
  j["S2_easy"]["start"] = start;
  j["S2_easy"]["pi_x13"] = pi_x13;
  j["S2_easy"]["s2_easy"] = to_string(s2_easy);
  j["S2_easy"]["percent"] = percent;
  j["S2_easy"]["seconds"] = get_wtime() - time;

  store_backup(j);
}

template <typename T>
void print_resume(T x,
                  int64_t start,
                  int64_t pi_x13,
                  T s2_easy,
                  double seconds,
                  double percent)
{
  if (!print_variables())
    print_log("");

  print_log("=== Resuming from " + backup_file() + " ===");
  print_log("start", start);
  print_log("pi_x13", pi_x13);
  print_log("s2_easy", s2_easy);
  print_log_seconds(seconds);
  print_status(percent, x);
}

template <typename T>
bool resume(T x,
            int64_t y,
            int64_t z,
            int64_t c,
            int64_t& start,
            int64_t& pi_x13,
            T& s2_easy,
            double& time)
{
  auto j = load_backup();

  if (is_resume(j, "S2_easy", x, y, z))
  {
    double percent = j["S2_easy"]["percent"];
    double seconds = j["S2_easy"]["seconds"];

    start = j["S2_easy"]["start"];
    pi_x13 = j["S2_easy"]["pi_x13"];
    s2_easy = calculator::eval<T>(j["S2_easy"]["s2_easy"]);
    time = get_wtime() - seconds;
    print_resume(x, start, pi_x13, s2_easy, seconds, percent);

    return true;
  }

  return false;
}

using fastdiv_t = libdivide::divider<uint64_t, libdivide::BRANCHFREE>;

template <typename T>
bool is_libdivide(T x)
{
  return x <= numeric_limits<uint64_t>::max();
}

template <typename Primes>
vector<fastdiv_t>
libdivide_vector(Primes& primes)
{
  return vector<fastdiv_t>(primes.begin(), primes.end());
}

/// Calculate the contribution of the clustered easy
/// leaves and the sparse easy leaves.
///
template <typename T, typename Primes>
T S2_easy_OpenMP(T x,
                 int64_t y,
                 int64_t z,
                 int64_t c,
                 Primes& primes,
                 int threads,
                 double& time)
{
  T s2_easy = 0;
  int64_t start;
  int64_t pi_x13;
  double backup_time = get_wtime();
  bool is_resume = resume(x, y, z, c, start, pi_x13, s2_easy, time);

  if (is_resume && start >= pi_x13)
    return s2_easy;

  PiTable pi(y);
  S2Status status(x);
  auto fastdiv = libdivide_vector(primes);

  int64_t pi_sqrty = pi[isqrt(y)];
  int64_t x13 = iroot<3>(x);
  int64_t max_dist = 1;
  threads = ideal_num_threads(threads, x13, 1000);

  if (!is_resume)
  {
    start = max(c, pi_sqrty) + 1;
    pi_x13 = pi[x13];
  }

  while (start <= pi_x13)
  {
    int64_t stop = min(start + max_dist * threads, pi_x13);

    #pragma omp parallel for schedule(dynamic) num_threads(threads) reduction(+: s2_easy)
    for (int64_t b = start; b <= stop; b++)
    {
      int64_t prime = primes[b];
      T x2 = x / prime;
      int64_t min_trivial = min(x2 / prime, y);
      int64_t min_clustered = (int64_t) isqrt(x2);
      int64_t min_sparse = z / prime;

      min_clustered = in_between(prime, min_clustered, y);
      min_sparse = in_between(prime, min_sparse, y);

      int64_t l = pi[min_trivial];
      int64_t pi_min_clustered = pi[min_clustered];
      int64_t pi_min_sparse = pi[min_sparse];

      if (is_libdivide(x2))
      {
        // Find all clustered easy leaves:
        // n = primes[b] * primes[l]
        // x / n <= y && phi(x / n, b - 1) == phi(x / m, b - 1)
        // where phi(x / n, b - 1) = pi(x / n) - b + 2
        while (l > pi_min_clustered)
        {
          int64_t xn = (uint64_t) x2 / fastdiv[l];
          int64_t phi_xn = pi[xn] - b + 2;
          int64_t xm = (uint64_t) x2 / fastdiv[b + phi_xn - 1];
          int64_t l2 = pi[xm];
          s2_easy += phi_xn * (l - l2);
          l = l2;
        }

        // Find all sparse easy leaves:
        // n = primes[b] * primes[l]
        // x / n <= y && phi(x / n, b - 1) = pi(x / n) - b + 2
        for (; l > pi_min_sparse; l--)
        {
          int64_t xn = (uint64_t) x2 / fastdiv[l];
          s2_easy += pi[xn] - b + 2;
        }
      }
      else
      {
        // Find all clustered easy leaves:
        // n = primes[b] * primes[l]
        // x / n <= y && phi(x / n, b - 1) == phi(x / m, b - 1)
        // where phi(x / n, b - 1) = pi(x / n) - b + 2
        while (l > pi_min_clustered)
        {
          int64_t xn = (int64_t) (x2 / primes[l]);
          int64_t phi_xn = pi[xn] - b + 2;
          int64_t xm = (int64_t) (x2 / primes[b + phi_xn - 1]);
          int64_t l2 = pi[xm];
          s2_easy += phi_xn * (l - l2);
          l = l2;
        }

        // Find all sparse easy leaves:
        // n = primes[b] * primes[l]
        // x / n <= y && phi(x / n, b - 1) = pi(x / n) - b + 2
        for (; l > pi_min_sparse; l--)
        {
          int64_t xn = (int64_t) (x2 / primes[l]);
          s2_easy += pi[xn] - b + 2;
        }
      }

      if (is_print())
        status.print(b, pi_x13);
    }

    start = stop + 1;

    if (get_wtime() - backup_time < 300)
      max_dist *= 2;
    else
    {
      max_dist = ceil_div(max_dist, 2);
      double percent = status.getPercent(start, pi_x13, start, pi_x13);
      backup(x, y, z, c, start, pi_x13, s2_easy, percent, time);
      backup_time = get_wtime();
    }
  }

  backup(x, y, z, c, pi_x13, pi_x13, s2_easy, 100, time);

  return s2_easy;
}

} // namespace

namespace primecount {

int64_t S2_easy(int64_t x,
                int64_t y,
                int64_t z,
                int64_t c,
                int threads)
{
#ifdef HAVE_MPI
  if (mpi_num_procs() > 1)
    return S2_easy_mpi(x, y, z, c, threads);
#endif

  print("");
  print("=== S2_easy(x, y) ===");
  print("Computation of the easy special leaves");
  print(x, y, c, threads);

  double time = get_wtime();
  auto primes = generate_primes<int32_t>(y);
  int64_t s2_easy = S2_easy_OpenMP((intfast64_t) x, y, z, c, primes, threads, time);

  print("S2_easy", s2_easy, time);
  return s2_easy;
}

#ifdef HAVE_INT128_T

int128_t S2_easy(int128_t x,
                 int64_t y,
                 int64_t z,
                 int64_t c,
                 int threads)
{
#ifdef HAVE_MPI
  if (mpi_num_procs() > 1)
    return S2_easy_mpi(x, y, z, c, threads);
#endif

  print("");
  print("=== S2_easy(x, y) ===");
  print("Computation of the easy special leaves");
  print(x, y, c, threads);

  double time = get_wtime();
  int128_t s2_easy;

  // uses less memory
  if (y <= numeric_limits<uint32_t>::max())
  {
    auto primes = generate_primes<uint32_t>(y);
    s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time);
  }
  else
  {
    auto primes = generate_primes<int64_t>(y);
    s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time);
  }

  print("S2_easy", s2_easy, time);
  return s2_easy;
}

#endif

} // namespace
<commit_msg>Fix S2_easy logging<commit_after>///
/// @file  S2_easy_libdivide.cpp
/// @brief This is an optimized version of S2_easy which uses
///        libdivide. libdivide allows to replace expensive integer
///        divides with comparatively cheap multiplication and
///        bitshifts.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <PiTable.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <generate.hpp>
#include <int128_t.hpp>
#include <min.hpp>
#include <imath.hpp>
#include <S2Status.hpp>
#include <S2.hpp>
#include <json.hpp>

#include <libdivide.h>
#include <stdint.h>
#include <vector>

#ifdef _OPENMP
  #include <omp.h>
#endif

using namespace std;
using namespace primecount;

namespace {

template <typename T>
void backup(T x,
            int64_t y,
            int64_t z,
            int64_t c,
            int64_t start,
            int64_t pi_x13,
            T s2_easy,
            double percent,
            double time)
{
  auto j = load_backup();

  j["S2_easy"]["x"] = to_string(x);
  j["S2_easy"]["y"] = y;
  j["S2_easy"]["z"] = z;
  j["S2_easy"]["c"] = c;
  j["S2_easy"]["start"] = start;
  j["S2_easy"]["pi_x13"] = pi_x13;
  j["S2_easy"]["s2_easy"] = to_string(s2_easy);
  j["S2_easy"]["percent"] = percent;
  j["S2_easy"]["seconds"] = get_wtime() - time;

  store_backup(j);
}

template <typename T>
void print_resume(T x,
                  int64_t start,
                  int64_t pi_x13,
                  T s2_easy,
                  double seconds,
                  double percent)
{
  if (!print_variables())
    print_log("");

  print_log("=== Resuming from " + backup_file() + " ===");
  print_log("start", start);
  print_log("pi_x13", pi_x13);
  print_log("s2_easy", s2_easy);
  print_log_seconds(seconds);
  print_status(percent, x);
}

template <typename T>
bool resume(T x,
            int64_t y,
            int64_t z,
            int64_t c,
            int64_t& start,
            int64_t& pi_x13,
            T& s2_easy,
            double& time)
{
  auto j = load_backup();

  if (is_resume(j, "S2_easy", x, y, z))
  {
    double percent = j["S2_easy"]["percent"];
    double seconds = j["S2_easy"]["seconds"];

    start = j["S2_easy"]["start"];
    pi_x13 = j["S2_easy"]["pi_x13"];
    s2_easy = calculator::eval<T>(j["S2_easy"]["s2_easy"]);
    time = get_wtime() - seconds;
    print_resume(x, start, pi_x13, s2_easy, seconds, percent);

    return true;
  }

  return false;
}

using fastdiv_t = libdivide::divider<uint64_t, libdivide::BRANCHFREE>;

template <typename T>
bool is_libdivide(T x)
{
  return x <= numeric_limits<uint64_t>::max();
}

template <typename Primes>
vector<fastdiv_t>
libdivide_vector(Primes& primes)
{
  return vector<fastdiv_t>(primes.begin(), primes.end());
}

/// Calculate the contribution of the clustered easy
/// leaves and the sparse easy leaves.
///
template <typename T, typename Primes>
T S2_easy_OpenMP(T x,
                 int64_t y,
                 int64_t z,
                 int64_t c,
                 Primes& primes,
                 int threads,
                 double& time)
{
  T s2_easy = 0;
  int64_t start;
  int64_t pi_x13;
  double backup_time = get_wtime();
  bool is_resume = resume(x, y, z, c, start, pi_x13, s2_easy, time);

  if (is_resume && start >= pi_x13)
    return s2_easy;

  PiTable pi(y);
  S2Status status(x);
  auto fastdiv = libdivide_vector(primes);

  int64_t pi_sqrty = pi[isqrt(y)];
  int64_t x13 = iroot<3>(x);
  int64_t max_dist = 1;
  threads = ideal_num_threads(threads, x13, 1000);

  if (!is_resume)
  {
    start = max(c, pi_sqrty) + 1;
    pi_x13 = pi[x13];
  }

  while (start <= pi_x13)
  {
    int64_t stop = min(start + max_dist * threads, pi_x13);

    #pragma omp parallel for schedule(dynamic) num_threads(threads) reduction(+: s2_easy)
    for (int64_t b = start; b <= stop; b++)
    {
      int64_t prime = primes[b];
      T x2 = x / prime;
      int64_t min_trivial = min(x2 / prime, y);
      int64_t min_clustered = (int64_t) isqrt(x2);
      int64_t min_sparse = z / prime;

      min_clustered = in_between(prime, min_clustered, y);
      min_sparse = in_between(prime, min_sparse, y);

      int64_t l = pi[min_trivial];
      int64_t pi_min_clustered = pi[min_clustered];
      int64_t pi_min_sparse = pi[min_sparse];

      if (is_libdivide(x2))
      {
        // Find all clustered easy leaves:
        // n = primes[b] * primes[l]
        // x / n <= y && phi(x / n, b - 1) == phi(x / m, b - 1)
        // where phi(x / n, b - 1) = pi(x / n) - b + 2
        while (l > pi_min_clustered)
        {
          int64_t xn = (uint64_t) x2 / fastdiv[l];
          int64_t phi_xn = pi[xn] - b + 2;
          int64_t xm = (uint64_t) x2 / fastdiv[b + phi_xn - 1];
          int64_t l2 = pi[xm];
          s2_easy += phi_xn * (l - l2);
          l = l2;
        }

        // Find all sparse easy leaves:
        // n = primes[b] * primes[l]
        // x / n <= y && phi(x / n, b - 1) = pi(x / n) - b + 2
        for (; l > pi_min_sparse; l--)
        {
          int64_t xn = (uint64_t) x2 / fastdiv[l];
          s2_easy += pi[xn] - b + 2;
        }
      }
      else
      {
        // Find all clustered easy leaves:
        // n = primes[b] * primes[l]
        // x / n <= y && phi(x / n, b - 1) == phi(x / m, b - 1)
        // where phi(x / n, b - 1) = pi(x / n) - b + 2
        while (l > pi_min_clustered)
        {
          int64_t xn = (int64_t) (x2 / primes[l]);
          int64_t phi_xn = pi[xn] - b + 2;
          int64_t xm = (int64_t) (x2 / primes[b + phi_xn - 1]);
          int64_t l2 = pi[xm];
          s2_easy += phi_xn * (l - l2);
          l = l2;
        }

        // Find all sparse easy leaves:
        // n = primes[b] * primes[l]
        // x / n <= y && phi(x / n, b - 1) = pi(x / n) - b + 2
        for (; l > pi_min_sparse; l--)
        {
          int64_t xn = (int64_t) (x2 / primes[l]);
          s2_easy += pi[xn] - b + 2;
        }
      }

      if (is_print())
        status.print(b, pi_x13);
    }

    start = stop + 1;

    if (get_wtime() - backup_time < 300)
      max_dist *= 2;
    else
    {
      max_dist = ceil_div(max_dist, 2);
      double percent = status.getPercent(start, pi_x13, start, pi_x13);
      backup(x, y, z, c, start, pi_x13, s2_easy, percent, time);
      backup_time = get_wtime();
    }
  }

  backup(x, y, z, c, pi_x13, pi_x13, s2_easy, 100, time);

  return s2_easy;
}

} // namespace

namespace primecount {

int64_t S2_easy(int64_t x,
                int64_t y,
                int64_t z,
                int64_t c,
                int threads)
{
#ifdef HAVE_MPI
  if (mpi_num_procs() > 1)
    return S2_easy_mpi(x, y, z, c, threads);
#endif

  print_log("");
  print_log("=== S2_easy(x, y) ===");
  print_log("Computation of the easy special leaves");
  print_log(x, y, c, threads);

  double time = get_wtime();
  auto primes = generate_primes<int32_t>(y);
  int64_t s2_easy = S2_easy_OpenMP((intfast64_t) x, y, z, c, primes, threads, time);

  print_log("S2_easy", s2_easy, time);
  return s2_easy;
}

#ifdef HAVE_INT128_T

int128_t S2_easy(int128_t x,
                 int64_t y,
                 int64_t z,
                 int64_t c,
                 int threads)
{
#ifdef HAVE_MPI
  if (mpi_num_procs() > 1)
    return S2_easy_mpi(x, y, z, c, threads);
#endif

  print_log("");
  print_log("=== S2_easy(x, y) ===");
  print_log("Computation of the easy special leaves");
  print_log(x, y, c, threads);

  double time = get_wtime();
  int128_t s2_easy;

  // uses less memory
  if (y <= numeric_limits<uint32_t>::max())
  {
    auto primes = generate_primes<uint32_t>(y);
    s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time);
  }
  else
  {
    auto primes = generate_primes<int64_t>(y);
    s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time);
  }

  print_log("S2_easy", s2_easy, time);
  return s2_easy;
}

#endif

} // namespace
<|endoftext|>


<commit_before>#include "middling_player.hpp"

#include <ctime>
#include <limits>

#include <boost/random/discrete_distribution.hpp>

#include "logger.hpp"
#include "walk_move.hpp"
#include "wall_move.hpp"
#include "exception.hpp"

static boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;
static int kLookForward = 2;
static int kMinimaxNodes = 0;

namespace Quoridor {

MiddlingPlayer::MiddlingPlayer(std::shared_ptr<Game> game,
        std::shared_ptr<Pawn> pawn)
    : game_(game), pawn_(pawn), goal_nodes_()
{
    lg.add_attribute("Tag", blattrs::constant<std::string>("middling player"));

    goal_nodes_ = game_->pawn_data(pawn_).goal_nodes;

    BOOST_LOG_DEBUG(lg) << "created new MiddlingPlayer (" << pawn_->color() << ")";
    for (auto node : goal_nodes_) {
        BOOST_LOG_DEBUG(lg) << "goal node: " << node.row() << ":" << node.col();
    }
}

MiddlingPlayer::~MiddlingPlayer()
{
}

IMove *MiddlingPlayer::get_move()
{
    boost::variant<Node, Wall> move;
    kMinimaxNodes = 0;
    double v = get_max_move(*game_, 0, -100, 100, &move);
    BOOST_LOG_DEBUG(lg) << "got k " << v << " (analyzed " << kMinimaxNodes
        << " nodes)";

    if (Node *node = boost::get<Node>(&move)) {
        BOOST_LOG_DEBUG(lg) << "best move is " << *node;
        return new WalkMove(*node);
    }
    else if (Wall *wall = boost::get<Wall>(&move)) {
        BOOST_LOG_DEBUG(lg) << "best move is " << *wall;
        return new WallMove(*wall);
    }

    return NULL;
}

double MiddlingPlayer::get_max_move(const Game &game, int depth,
        double a, double b, boost::variant<Node, Wall> *best_move)
{
    ++kMinimaxNodes;

    std::vector<boost::variant<Node, Wall>> moves = game.possible_moves(pawn_);
    for (auto move : moves) {
        Game game_cp = game;
        if (Node *node = boost::get<Node>(&move)) {
            game_cp.move_pawn(*node);
            if (game_cp.is_finished()) {
                if (best_move != NULL) {
                    *best_move = *node;
                }
                return a;
            }
        }
        else if (Wall *wall = boost::get<Wall>(&move)) {
            if (game_cp.add_wall(*wall) < 0) {
                continue;
            }
        }

        if (depth < kLookForward) {
            game_cp.switch_pawn();
            double val = get_min_move(game_cp, depth + 1, a, b);
            if (val > a) {
                a = val;
                if (best_move != NULL) {
                    if (Node *node = boost::get<Node>(&move)) {
                        *best_move = *node;
                    }
                    else if (Wall *wall = boost::get<Wall>(&move)) {
                        *best_move = *wall;
                    }
                }
            }
            if (b <= a) {
                return a;
            }
        }
        else {
            return evaluate(game_cp);
        }
    }

    return a;
}

double MiddlingPlayer::get_min_move(const Game &game, int depth,
        double a, double b)
{
    ++kMinimaxNodes;

    std::vector<boost::variant<Node, Wall>> moves = game.possible_moves(pawn_);
    for (auto move : moves) {
        Game game_cp = game;
        if (Node *node = boost::get<Node>(&move)) {
            game_cp.move_pawn(*node);
            if (game_cp.is_finished()) {
                b = -1.0f;
                return b;
            }
        }
        else if (Wall *wall = boost::get<Wall>(&move)) {
            if (game_cp.add_wall(*wall) < 0) {
                continue;
            }
        }

        if (depth < kLookForward) {
            game_cp.switch_pawn();
            b = std::min(b, get_max_move(game_cp, depth + 1, a, b, NULL));
            if (b <= a) {
                return b;
            }
        }
        else {
            return evaluate(game_cp);
        }
    }

    return b;
}

double MiddlingPlayer::evaluate(const Game &game) const
{
    double max_k = 0;
    size_t len = game.shortest_path(game.pawn_data(pawn_).node, goal_nodes_, NULL);
    double k = 1 / static_cast<double>(len);
    max_k = std::max(k, max_k);

    double rival_max_k = 0;
    for (auto pawn_data : game.pawn_data_list()) {
        if (pawn_data.pawn == pawn_) {
            continue;
        }
        len = game.shortest_path(pawn_data.node, pawn_data.goal_nodes, NULL);
        double k = 1 / static_cast<double>(len);
        rival_max_k = std::max(k, rival_max_k);
    }

    return max_k - rival_max_k;
}

}  /* namespace Quoridor */
<commit_msg>Fix logging<commit_after>#include "middling_player.hpp"

#include <ctime>
#include <limits>

#include <boost/random/discrete_distribution.hpp>

#include "logger.hpp"
#include "walk_move.hpp"
#include "wall_move.hpp"
#include "exception.hpp"

static boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;
static int kLookForward = 2;
static int kMinimaxNodes = 0;

namespace Quoridor {

MiddlingPlayer::MiddlingPlayer(std::shared_ptr<Game> game,
        std::shared_ptr<Pawn> pawn)
    : game_(game), pawn_(pawn), goal_nodes_()
{
    lg.add_attribute("Tag", blattrs::constant<std::string>("middling player"));

    goal_nodes_ = game_->pawn_data(pawn_).goal_nodes;

    BOOST_LOG_DEBUG(lg) << "created new MiddlingPlayer (" << pawn_->color() << ")";
    for (auto node : goal_nodes_) {
        BOOST_LOG_DEBUG(lg) << "goal node: " << node.row() << ":" << node.col();
    }
}

MiddlingPlayer::~MiddlingPlayer()
{
}

IMove *MiddlingPlayer::get_move()
{
    boost::variant<Node, Wall> move;
    kMinimaxNodes = 0;
    double v = get_max_move(*game_, 0, -100, 100, &move);

    BOOST_LOG_DEBUG(lg) << "best move: " << move << " (k " << v
        << ", analyzed " << kMinimaxNodes << " nodes)";

    if (Node *node = boost::get<Node>(&move)) {
        return new WalkMove(*node);
    }
    else if (Wall *wall = boost::get<Wall>(&move)) {
        return new WallMove(*wall);
    }

    return NULL;
}

double MiddlingPlayer::get_max_move(const Game &game, int depth,
        double a, double b, boost::variant<Node, Wall> *best_move)
{
    ++kMinimaxNodes;

    std::vector<boost::variant<Node, Wall>> moves = game.possible_moves(pawn_);
    for (auto move : moves) {
        Game game_cp = game;
        if (Node *node = boost::get<Node>(&move)) {
            game_cp.move_pawn(*node);
            if (game_cp.is_finished()) {
                if (best_move != NULL) {
                    *best_move = *node;
                }
                return a;
            }
        }
        else if (Wall *wall = boost::get<Wall>(&move)) {
            if (game_cp.add_wall(*wall) < 0) {
                continue;
            }
        }

        if (depth < kLookForward) {
            game_cp.switch_pawn();
            double val = get_min_move(game_cp, depth + 1, a, b);
            if (val > a) {
                a = val;
                if (best_move != NULL) {
                    if (Node *node = boost::get<Node>(&move)) {
                        *best_move = *node;
                    }
                    else if (Wall *wall = boost::get<Wall>(&move)) {
                        *best_move = *wall;
                    }
                }
            }
            if (b <= a) {
                return a;
            }
        }
        else {
            return evaluate(game_cp);
        }
    }

    return a;
}

double MiddlingPlayer::get_min_move(const Game &game, int depth,
        double a, double b)
{
    ++kMinimaxNodes;

    std::vector<boost::variant<Node, Wall>> moves = game.possible_moves(pawn_);
    for (auto move : moves) {
        Game game_cp = game;
        if (Node *node = boost::get<Node>(&move)) {
            game_cp.move_pawn(*node);
            if (game_cp.is_finished()) {
                b = -1.0f;
                return b;
            }
        }
        else if (Wall *wall = boost::get<Wall>(&move)) {
            if (game_cp.add_wall(*wall) < 0) {
                continue;
            }
        }

        if (depth < kLookForward) {
            game_cp.switch_pawn();
            b = std::min(b, get_max_move(game_cp, depth + 1, a, b, NULL));
            if (b <= a) {
                return b;
            }
        }
        else {
            return evaluate(game_cp);
        }
    }

    return b;
}

double MiddlingPlayer::evaluate(const Game &game) const
{
    double max_k = 0;
    size_t len = game.shortest_path(game.pawn_data(pawn_).node, goal_nodes_, NULL);
    double k = 1 / static_cast<double>(len);
    max_k = std::max(k, max_k);

    double rival_max_k = 0;
    for (auto pawn_data : game.pawn_data_list()) {
        if (pawn_data.pawn == pawn_) {
            continue;
        }
        len = game.shortest_path(pawn_data.node, pawn_data.goal_nodes, NULL);
        double k = 1 / static_cast<double>(len);
        rival_max_k = std::max(k, rival_max_k);
    }

    return max_k - rival_max_k;
}

}  /* namespace Quoridor */
<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_SCAL_FUNCTOR_REDUCE_SUM_HPP
#define STAN_MATH_REV_SCAL_FUNCTOR_REDUCE_SUM_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/rev/fun/typedefs.hpp>

#include <tbb/task_arena.h>
#include <tbb/parallel_reduce.h>
#include <tbb/blocked_range.h>

#include <iostream>
#include <iterator>
#include <vector>

namespace stan {
namespace math {
namespace internal {

template <typename ReduceFunction, typename ReturnType, typename M,
          typename... Args>
struct reduce_sum_impl<ReduceFunction, require_var_t<ReturnType>, ReturnType, M,
                       Args...> {
  struct recursive_reducer {
    size_t num_terms_;
    const std::vector<M>& vmapped_;
    std::tuple<const Args&...> args_tuple_;

    double sum_;
    Eigen::VectorXd args_adjoints_;

    recursive_reducer(size_t num_terms, const std::vector<M>& vmapped,
                      const Args&... args)
        : num_terms_(num_terms),
          vmapped_(vmapped),
          args_tuple_(args...),
          sum_(0.0),
          args_adjoints_(Eigen::VectorXd::Zero(num_terms)) {}

    recursive_reducer(recursive_reducer& other, tbb::split)
        : num_terms_(other.num_terms_),
          vmapped_(other.vmapped_),
          args_tuple_(other.args_tuple_),
          sum_(other.sum_),
          args_adjoints_(other.args_adjoints_) {}

    template <typename T>
    T& deep_copy(T& arg) {
      return arg;
    }

    var deep_copy(const var& arg) { return var(arg.val()); }

    std::vector<var> deep_copy(const std::vector<var>& arg) {
      std::vector<var> copy(arg.size());
      for (size_t i = 0; i < arg.size(); ++i) {
        copy[i] = arg[i].val();
      }
      return copy;
    }

    template <int RowType, int ColType>
    Eigen::Matrix<var, RowType, ColType> deep_copy(
        const Eigen::Matrix<var, RowType, ColType>& arg) {
      Eigen::Matrix<var, RowType, ColType> copy(arg.size());
      for (size_t i = 0; i < arg.size(); ++i) {
        copy(i) = arg(i).val();
      }
      return copy;
    }

    template <typename... Pargs>
    void accumulate_adjoints(double* dest, const var& x, const Pargs&... args) {
      *dest += x.adj();
      accumulate_adjoints(dest + 1, args...);
    }

    template <typename... Pargs>
    void accumulate_adjoints(double* dest, const std::vector<var>& x,
                             const Pargs&... args) {
      for (size_t i = 0; i < x.size(); ++i) {
        dest[i] += x[i].adj();
      }
      accumulate_adjoints(dest + x.size(), args...);
    }

    template <typename... Pargs, int RowType, int ColType>
    void accumulate_adjoints(double* dest,
                             const Eigen::Matrix<var, RowType, ColType>& x,
                             const Pargs&... args) {
      for (size_t i = 0; i < x.size(); ++i) {
        dest[i] += x(i).adj();
      }
      accumulate_adjoints(dest + x.size(), args...);
    }

    template <typename R, typename... Pargs>
    void accumulate_adjoints(double* dest, const R& x, const Pargs&... args) {
      accumulate_adjoints(dest, args...);
    }

    void accumulate_adjoints(double*) {}

    void operator()(const tbb::blocked_range<size_t>& r) {
      if (r.empty())
        return;

      auto start = vmapped_.begin();
      std::advance(start, r.begin());
      auto end = vmapped_.begin();
      std::advance(end, r.end());

      const std::vector<M> sub_slice(start, end);

      try {
        start_nested();

        // create a deep copy of all var's so that these are not
        // linked to any outer AD tree
        auto args_tuple_local_copy = apply(
            [&](auto&&... args) { return std::make_tuple(deep_copy(args)...); },
            args_tuple_);

        var sub_sum_v = apply(
            [&](auto&&... args) {
              return ReduceFunction()(r.begin(), r.end() - 1, sub_slice,
                                      args...);
            },
            args_tuple_local_copy);

        sub_sum_v.grad();

        sum_ += sub_sum_v.val();

        // This should accumulate the adjoints from args_tuple_local_copy into
        //  the memory of args_adjoints_
        apply(
            [&](auto&&... args) {
              accumulate_adjoints(args_adjoints_.data(), args...);
            },
            args_tuple_local_copy);
      } catch (const std::exception& e) {
        recover_memory_nested();
        throw;
      }
      recover_memory_nested();
    }

    void join(const recursive_reducer& rhs) {
      sum_ += rhs.sum_;
      args_adjoints_ += rhs.args_adjoints_;
    }
  };

  // Fails to compile if type T does not have callable member size()
  template <typename T>
  using member_size_t = decltype(std::declval<T>().size());

  // TODO(Steve): add requires for generic containers
  template <typename Container,
            require_t<is_detected<Container, member_size_t>>...,
            require_t<is_var<value_type_t<Container>>>..., typename... Pargs>
  size_t count_var_impl(size_t count, const Container& x,
                        const Pargs&... args) const {
    return count_var_impl(count + x.size(), args...);
  }

  template <typename Container,
            require_t<is_detected<Container, member_size_t>>...,
            require_t<std::is_arithmetic<value_type_t<Container>>>...,
            typename... Pargs>
  size_t count_var_impl(size_t count, const Container& x,
                        const Pargs&... args) const {
    return count_var_impl(count, args...);
  }

  template <typename... Pargs>
  size_t count_var_impl(size_t count, const var& x,
                        const Pargs&... args) const {
    return count_var_impl(count + 1, args...);
  }

  template <typename... Pargs, typename Arith, require_arithmetic_t<Arith>...>
  size_t count_var_impl(size_t count, Arith& x, const Pargs&... args) const {
    return count_var_impl(count, args...);
  }

  size_t count_var_impl(size_t count) const { return count; }

  /**
   * Count the number of scalars of type T in the input argument list
   *
   * @tparam Pargs Types of input arguments
   * @return Number of scalars of type T in input
   */
  template <typename... Pargs>
  size_t count_var(const Pargs&... args) const {
    return count_var_impl(0, args...);
  }

  template <typename... Pargs>
  void save_varis(vari** dest, const var& x, const Pargs&... args) const {
    *dest = x.vi_;
    save_varis(dest + 1, args...);
  }

  template <typename... Pargs>
  void save_varis(vari** dest, const std::vector<var>& x,
                  const Pargs&... args) const {
    for (size_t i = 0; i < x.size(); ++i) {
      dest[i] = x[i].vi_;
    }
    save_varis(dest + x.size(), args...);
  }

  template <typename... Pargs, int RowType, int ColType>
  void save_varis(vari** dest, const Eigen::Matrix<var, RowType, ColType>& x,
                  const Pargs&... args) const {
    for (size_t i = 0; i < x.size(); ++i) {
      dest[i] = x(i).vi_;
    }
    save_varis(dest + x.size(), args...);
  }

  template <typename R, typename... Pargs>
  void save_varis(vari** dest, const R& x, const Pargs&... args) const {
    save_varis(dest, args...);
  }

  void save_varis(vari**) const {}

  var operator()(const std::vector<M>& vmapped, std::size_t grainsize,
                 const Args&... args) const {
    const std::size_t num_jobs = vmapped.size();

    if (num_jobs == 0)
      return var(0.0);

    const std::size_t num_terms = count_var(args...);

    recursive_reducer worker(num_terms, vmapped, args...);

#ifdef STAN_DETERMINISTIC
    tbb::static_partitioner partitioner;
    tbb::parallel_deterministic_reduce(
        tbb::blocked_range<std::size_t>(0, num_jobs, grainsize), worker,
        partitioner);
#else
    tbb::parallel_reduce(
        tbb::blocked_range<std::size_t>(0, num_jobs, grainsize), worker);
#endif

    vari** varis
        = ChainableStack::instance_->memalloc_.alloc_array<vari*>(num_terms);
    double* partials
        = ChainableStack::instance_->memalloc_.alloc_array<double>(num_terms);

    save_varis(varis, args...);

    for (size_t i = 0; i < num_terms; ++i) {
      partials[i] = worker.args_adjoints_(i);
    }

    return var(new precomputed_gradients_vari(worker.sum_, num_terms, varis,
                                              partials));
  }
};
}  // namespace internal

}  // namespace math
}  // namespace stan

#endif
<commit_msg>Make accumulate adjoints accept more types<commit_after>#ifndef STAN_MATH_REV_SCAL_FUNCTOR_REDUCE_SUM_HPP
#define STAN_MATH_REV_SCAL_FUNCTOR_REDUCE_SUM_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/rev/fun/typedefs.hpp>

#include <tbb/task_arena.h>
#include <tbb/parallel_reduce.h>
#include <tbb/blocked_range.h>

#include <iostream>
#include <iterator>
#include <vector>

namespace stan {
namespace math {
namespace internal {

template <typename ReduceFunction, typename ReturnType, typename M,
          typename... Args>
struct reduce_sum_impl<ReduceFunction, require_var_t<ReturnType>, ReturnType, M,
                       Args...> {
  struct recursive_reducer {
    size_t num_terms_;
    const std::vector<M>& vmapped_;
    std::tuple<const Args&...> args_tuple_;

    double sum_;
    Eigen::VectorXd args_adjoints_;

    recursive_reducer(size_t num_terms, const std::vector<M>& vmapped,
                      const Args&... args)
        : num_terms_(num_terms),
          vmapped_(vmapped),
          args_tuple_(args...),
          sum_(0.0),
          args_adjoints_(Eigen::VectorXd::Zero(num_terms)) {}

    recursive_reducer(recursive_reducer& other, tbb::split)
        : num_terms_(other.num_terms_),
          vmapped_(other.vmapped_),
          args_tuple_(other.args_tuple_),
          sum_(other.sum_),
          args_adjoints_(other.args_adjoints_) {}

    template <typename T>
    T& deep_copy(T& arg) {
      return arg;
    }

    var deep_copy(const var& arg) { return var(arg.val()); }

    std::vector<var> deep_copy(const std::vector<var>& arg) {
      std::vector<var> copy(arg.size());
      for (size_t i = 0; i < arg.size(); ++i) {
        copy[i] = arg[i].val();
      }
      return copy;
    }

    template <int RowType, int ColType>
    Eigen::Matrix<var, RowType, ColType> deep_copy(
        const Eigen::Matrix<var, RowType, ColType>& arg) {
      Eigen::Matrix<var, RowType, ColType> copy(arg.size());
      for (size_t i = 0; i < arg.size(); ++i) {
        copy(i) = arg(i).val();
      }
      return copy;
    }

    template <typename... Pargs>
    void accumulate_adjoints(double* dest, const var& x, const Pargs&... args) {
      *dest += x.adj();
      accumulate_adjoints(dest + 1, args...);
    }

    // Works with anything that has operator[Integral] defined
    template <typename... Pargs, typename Vec, require_vector_like_vt<is_var, Vec>...>
    void accumulate_adjoints(double* dest, const Vec& x,
                             const Pargs&... args) {
      for (size_t i = 0; i < x.size(); ++i) {
        dest[i] += x[i].adj();
      }
      accumulate_adjoints(dest + x.size(), args...);
    }
    // Fails to compile if type T does not have member operator(Integral)
    template <typename T>
    using operator_paren_access_t = decltype(std::declval<T>()(int{}));

    // Works on anything with a operator()
    template <typename... Pargs, typename Mat, require_t<is_detected<Mat, operator_paren_access_t>>...,
    require_t<is_var<value_type_t<Mat>>>...>
    void accumulate_adjoints(double* dest,
                             const Mat& x,
                             const Pargs&... args) {
      for (size_t i = 0; i < x.size(); ++i) {
        dest[i] += x(i).adj();
      }
      accumulate_adjoints(dest + x.size(), args...);
    }

    // Anything with a scalar type of Arithmetic gets tossed
    template <typename Arith, require_arithmetic_t<scalar_type_t<Arith>>..., typename... Pargs>
    void accumulate_adjoints(double* dest, Arith&& x, const Pargs&... args) {
      accumulate_adjoints(dest, args...);
    }

    void accumulate_adjoints(double*) {}

    void operator()(const tbb::blocked_range<size_t>& r) {
      if (r.empty())
        return;

      auto start = vmapped_.begin();
      std::advance(start, r.begin());
      auto end = vmapped_.begin();
      std::advance(end, r.end());

      const std::vector<M> sub_slice(start, end);

      try {
        start_nested();

        // create a deep copy of all var's so that these are not
        // linked to any outer AD tree
        auto args_tuple_local_copy = apply(
            [&](auto&&... args) { return std::make_tuple(deep_copy(args)...); },
            args_tuple_);

        var sub_sum_v = apply(
            [&](auto&&... args) {
              return ReduceFunction()(r.begin(), r.end() - 1, sub_slice,
                                      args...);
            },
            args_tuple_local_copy);

        sub_sum_v.grad();

        sum_ += sub_sum_v.val();

        // This should accumulate the adjoints from args_tuple_local_copy into
        //  the memory of args_adjoints_
        apply(
            [&](auto&&... args) {
              accumulate_adjoints(args_adjoints_.data(), args...);
            },
            args_tuple_local_copy);
      } catch (const std::exception& e) {
        recover_memory_nested();
        throw;
      }
      recover_memory_nested();
    }

    void join(const recursive_reducer& rhs) {
      sum_ += rhs.sum_;
      args_adjoints_ += rhs.args_adjoints_;
    }
  };

  // Fails to compile if type T does not have callable member size()
  template <typename T>
  using member_size_t = decltype(std::declval<T>().size());

  // TODO(Steve): add requires for generic containers
  template <typename Container,
            require_t<is_detected<Container, member_size_t>>...,
            require_t<is_var<value_type_t<Container>>>..., typename... Pargs>
  size_t count_var_impl(size_t count, const Container& x,
                        const Pargs&... args) const {
    return count_var_impl(count + x.size(), args...);
  }

  template <typename Container,
            require_t<is_detected<Container, member_size_t>>...,
            require_t<std::is_arithmetic<value_type_t<Container>>>...,
            typename... Pargs>
  size_t count_var_impl(size_t count, const Container& x,
                        const Pargs&... args) const {
    return count_var_impl(count, args...);
  }

  template <typename... Pargs>
  size_t count_var_impl(size_t count, const var& x,
                        const Pargs&... args) const {
    return count_var_impl(count + 1, args...);
  }

  template <typename... Pargs, typename Arith, require_arithmetic_t<Arith>...>
  size_t count_var_impl(size_t count, Arith& x, const Pargs&... args) const {
    return count_var_impl(count, args...);
  }

  size_t count_var_impl(size_t count) const { return count; }

  /**
   * Count the number of scalars of type T in the input argument list
   *
   * @tparam Pargs Types of input arguments
   * @return Number of scalars of type T in input
   */
  template <typename... Pargs>
  size_t count_var(const Pargs&... args) const {
    return count_var_impl(0, args...);
  }

  template <typename... Pargs>
  void save_varis(vari** dest, const var& x, const Pargs&... args) const {
    *dest = x.vi_;
    save_varis(dest + 1, args...);
  }

  template <typename... Pargs>
  void save_varis(vari** dest, const std::vector<var>& x,
                  const Pargs&... args) const {
    for (size_t i = 0; i < x.size(); ++i) {
      dest[i] = x[i].vi_;
    }
    save_varis(dest + x.size(), args...);
  }

  template <typename... Pargs, int RowType, int ColType>
  void save_varis(vari** dest, const Eigen::Matrix<var, RowType, ColType>& x,
                  const Pargs&... args) const {
    for (size_t i = 0; i < x.size(); ++i) {
      dest[i] = x(i).vi_;
    }
    save_varis(dest + x.size(), args...);
  }

  template <typename R, typename... Pargs>
  void save_varis(vari** dest, const R& x, const Pargs&... args) const {
    save_varis(dest, args...);
  }

  void save_varis(vari**) const {}

  var operator()(const std::vector<M>& vmapped, std::size_t grainsize,
                 const Args&... args) const {
    const std::size_t num_jobs = vmapped.size();

    if (num_jobs == 0)
      return var(0.0);

    const std::size_t num_terms = count_var(args...);

    recursive_reducer worker(num_terms, vmapped, args...);

#ifdef STAN_DETERMINISTIC
    tbb::static_partitioner partitioner;
    tbb::parallel_deterministic_reduce(
        tbb::blocked_range<std::size_t>(0, num_jobs, grainsize), worker,
        partitioner);
#else
    tbb::parallel_reduce(
        tbb::blocked_range<std::size_t>(0, num_jobs, grainsize), worker);
#endif

    vari** varis
        = ChainableStack::instance_->memalloc_.alloc_array<vari*>(num_terms);
    double* partials
        = ChainableStack::instance_->memalloc_.alloc_array<double>(num_terms);

    save_varis(varis, args...);

    for (size_t i = 0; i < num_terms; ++i) {
      partials[i] = worker.args_adjoints_(i);
    }

    return var(new precomputed_gradients_vari(worker.sum_, num_terms, varis,
                                              partials));
  }
};
}  // namespace internal

}  // namespace math
}  // namespace stan

#endif
<|endoftext|>


<commit_before>// Copyright 2021 Google LLC
//
// 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 "src/default_addresses.h"

#include "src/host_manager.hpp"
#include "src/nemora.hpp"

#include <arpa/inet.h>
#include <fmt/format.h>

#include <CLI/CLI.hpp>
#include <phosphor-logging/log.hpp>

#include <csignal>
#include <cstdint>
#include <iostream>
#include <regex>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>

using fmt::format;
using phosphor::logging::level;
using phosphor::logging::log;

namespace
{
volatile std::sig_atomic_t gSignalStatus;
}

void signal_handler(int signal)
{
    gSignalStatus = signal;
}

void NemoraUdpPoll(Nemora* nemora)
{
    while (!gSignalStatus)
    {
        nemora->UdpPoll();
    }
}

int main(int argc, char* argv[])
{
    // Init arg parser
    CLI::App app("gBMC-side Nemora implementation (POST-code only)");

    std::string udp_address_v4_str;
    auto* ipv4_option = app.add_option(
        "--udp4", udp_address_v4_str,
        "Target IPv4 address for UDP communication, i.e., POST streaming.",
        true);

    std::string udp_address_v6_str;
    auto* ipv6_option = app.add_option(
        "--udp6", udp_address_v6_str,
        "Target IPv6 address for UDP communication, i.e., POST streaming.",
        true);

    // interface is last, and required.
    std::string iface_name;
    app.add_option("interface", iface_name,
                   "Network interface for TCP communication. Ex: eth0")
        ->required();

    CLI11_PARSE(app, argc, argv);

    in_addr udp_address_v4;
    udp_address_v4.s_addr = htonl(DEFAULT_ADDRESSES_TARGET_IP);
    if (*ipv4_option &&
        !inet_pton(AF_INET, udp_address_v4_str.c_str(), &udp_address_v4))
    {
        std::cerr << "Invalid IPv4 address supplied: " << udp_address_v4_str
                  << std::endl;
    }

    // The value from default_addresses.h is designed for LWIP which EC uses,
    // and needs to be translated to network byte order.
    in6_addr udp_address_v6;
    uint32_t default_addr_6[4] = DEFAULT_ADDRESSES_TARGET_IP6;

    auto htonl_inplace = [](uint32_t& i) { i = htonl(i); };
    std::for_each(std::begin(default_addr_6), std::end(default_addr_6),
                  htonl_inplace);
    std::memcpy(udp_address_v6.s6_addr, default_addr_6, sizeof(default_addr_6));

    if (*ipv6_option &&
        !inet_pton(AF_INET6, udp_address_v6_str.c_str(), &udp_address_v6))
    {
        std::cerr << "Invalid IPv6 address supplied: " << udp_address_v6_str
                  << std::endl;
    }

    log<level::INFO>("Start Nemora...");
    Nemora nemora(iface_name, udp_address_v4, udp_address_v6);

    // Install a signal handler
    std::signal(SIGINT, signal_handler);

    std::thread udp(NemoraUdpPoll, &nemora);

    udp.join();

    return EXIT_SUCCESS;
}
<commit_msg>nemora-postd: update add_option function<commit_after>// Copyright 2021 Google LLC
//
// 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 "src/default_addresses.h"

#include "src/host_manager.hpp"
#include "src/nemora.hpp"

#include <arpa/inet.h>
#include <fmt/format.h>

#include <CLI/CLI.hpp>
#include <phosphor-logging/log.hpp>

#include <csignal>
#include <cstdint>
#include <iostream>
#include <regex>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>

using fmt::format;
using phosphor::logging::level;
using phosphor::logging::log;

namespace
{
volatile std::sig_atomic_t gSignalStatus;
}

void signal_handler(int signal)
{
    gSignalStatus = signal;
}

void NemoraUdpPoll(Nemora* nemora)
{
    while (!gSignalStatus)
    {
        nemora->UdpPoll();
    }
}

int main(int argc, char* argv[])
{
    // Init arg parser
    CLI::App app("gBMC-side Nemora implementation (POST-code only)");

    std::string udp_address_v4_str;
    auto* ipv4_option = app.add_option("--udp4", udp_address_v4_str,
                                       "Target IPv4 address for UDP "
                                       "communication, i.e., POST streaming.")
                            ->capture_default_str();

    std::string udp_address_v6_str;
    auto* ipv6_option = app.add_option("--udp6", udp_address_v6_str,
                                       "Target IPv6 address for UDP "
                                       "communication, i.e., POST streaming.")
                            ->capture_default_str();

    // interface is last, and required.
    std::string iface_name;
    app.add_option("interface", iface_name,
                   "Network interface for TCP communication. Ex: eth0")
        ->required();

    CLI11_PARSE(app, argc, argv);

    in_addr udp_address_v4;
    udp_address_v4.s_addr = htonl(DEFAULT_ADDRESSES_TARGET_IP);
    if (*ipv4_option &&
        !inet_pton(AF_INET, udp_address_v4_str.c_str(), &udp_address_v4))
    {
        std::cerr << "Invalid IPv4 address supplied: " << udp_address_v4_str
                  << std::endl;
    }

    // The value from default_addresses.h is designed for LWIP which EC uses,
    // and needs to be translated to network byte order.
    in6_addr udp_address_v6;
    uint32_t default_addr_6[4] = DEFAULT_ADDRESSES_TARGET_IP6;

    auto htonl_inplace = [](uint32_t& i) { i = htonl(i); };
    std::for_each(std::begin(default_addr_6), std::end(default_addr_6),
                  htonl_inplace);
    std::memcpy(udp_address_v6.s6_addr, default_addr_6, sizeof(default_addr_6));

    if (*ipv6_option &&
        !inet_pton(AF_INET6, udp_address_v6_str.c_str(), &udp_address_v6))
    {
        std::cerr << "Invalid IPv6 address supplied: " << udp_address_v6_str
                  << std::endl;
    }

    log<level::INFO>("Start Nemora...");
    Nemora nemora(iface_name, udp_address_v4, udp_address_v6);

    // Install a signal handler
    std::signal(SIGINT, signal_handler);

    std::thread udp(NemoraUdpPoll, &nemora);

    udp.join();

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/**
 * @file
 *
 * @brief A listener reacting to matches for the grammar rules defined in `YAML.g4`
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 */

#include <iostream>

#include "YAMLBaseListener.h"

using antlr::YAMLBaseListener;
using KeyContext = antlr::YAMLParser::KeyContext;
using ValueContext = antlr::YAMLParser::ValueContext;

using std::cout;
using std::endl;

class KeyListener : public YAMLBaseListener
{
public:
	void exitKey (KeyContext * context)
	{
		cout << "Found name “" << context->getText () << "”" << endl;
	}

	void exitValue (ValueContext * context)
	{
		cout << "Found value “" << context->getText () << "”" << endl;
	}
};
<commit_msg>Yan LR: Use override specifier<commit_after>/**
 * @file
 *
 * @brief A listener reacting to matches for the grammar rules defined in `YAML.g4`
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 */

#include <iostream>

#include "YAMLBaseListener.h"

using antlr::YAMLBaseListener;
using KeyContext = antlr::YAMLParser::KeyContext;
using ValueContext = antlr::YAMLParser::ValueContext;

using std::cout;
using std::endl;

class KeyListener : public YAMLBaseListener
{
public:
	void exitKey (KeyContext * context) override
	{
		cout << "Found name “" << context->getText () << "”" << endl;
	}

	void exitValue (ValueContext * context) override
	{
		cout << "Found value “" << context->getText () << "”" << endl;
	}
};
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2010 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#include <iostream>
#include <sstream>
#include <vector>
//#include <string>

#include <mapnik/marker.hpp>
#include <mapnik/marker_cache.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/svg/svg_path_adapter.hpp>
#include <mapnik/svg/svg_renderer.hpp>
#include <mapnik/svg/svg_path_attributes.hpp>

#include <boost/algorithm/string.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/program_options.hpp>

#include "agg_rasterizer_scanline_aa.h"
#include "agg_basics.h"
#include "agg_rendering_buffer.h"
#include "agg_renderer_base.h"
#include "agg_pixfmt_rgba.h"
#include "agg_scanline_u.h"

int main (int argc,char** argv)
{
    namespace po = boost::program_options;

    bool verbose=false;
    std::vector<std::string> svg_files;

    try
    {
        po::options_description desc("svg2png utility");
        desc.add_options()
            ("help,h", "produce usage message")
            ("version,V","print version string")
            ("verbose,v","verbose output")
            ("svg",po::value<std::vector<std::string> >(),"svg file to read")
            ;

        po::positional_options_description p;
        p.add("svg",-1);
        po::variables_map vm;
        po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
        po::notify(vm);

        if (vm.count("version"))
        {
            std::clog<<"version 0.3.0" << std::endl;
            return 1;
        }

        if (vm.count("help"))
        {
            std::clog << desc << std::endl;
            return 1;
        }
        if (vm.count("verbose"))
        {
            verbose = true;
        }

        if (vm.count("svg"))
        {
            svg_files=vm["svg"].as< std::vector<std::string> >();
        }
        else
        {
            std::clog << "please provide an svg file!" << std::endl;
            return -1;
        }

        std::vector<std::string>::const_iterator itr = svg_files.begin();
        if (itr == svg_files.end())
        {
            std::clog << "no svg files to render" << std::endl;
            return 0;
        }
        while (itr != svg_files.end())
        {

            std::string svg_name (*itr++);

            boost::optional<mapnik::marker_ptr> marker_ptr = mapnik::marker_cache::instance()->find(svg_name, false);
            if (marker_ptr) {

                mapnik::marker marker  = **marker_ptr;
                if (marker.is_vector()) {

                    typedef agg::pixfmt_rgba32_plain pixfmt;
                    typedef agg::renderer_base<pixfmt> renderer_base;
                    agg::rasterizer_scanline_aa<> ras_ptr;
                    agg::scanline_u8 sl;

                    double opacity = 1;
                    double scale_factor_ = .95;
                    int w = marker.width();
                    int h = marker.height();
                    mapnik::image_32 im(w,h);
                    agg::rendering_buffer buf(im.raw_data(), w, h, w * 4);
                    pixfmt pixf(buf);
                    renderer_base renb(pixf);

                    mapnik::box2d<double> const& bbox = (*marker.get_vector_data())->bounding_box();
                    mapnik::coord<double,2> c = bbox.center();
                    // center the svg marker on '0,0'
                    agg::trans_affine mtx = agg::trans_affine_translation(-c.x,-c.y);
                    // apply symbol transformation to get to map space
                    mtx *= agg::trans_affine_scaling(scale_factor_);
                    // render the marker at the center of the marker box
                    mtx.translate(0.5 * w, 0.5 * h);

                    mapnik::svg::vertex_stl_adapter<mapnik::svg::svg_path_storage> stl_storage((*marker.get_vector_data())->source());
                    mapnik::svg::svg_path_adapter svg_path(stl_storage);
                    mapnik::svg::svg_renderer<mapnik::svg::svg_path_adapter,
                                 agg::pod_bvector<mapnik::svg::path_attributes> > svg_renderer_this(svg_path,
                                         (*marker.get_vector_data())->attributes());

                    svg_renderer_this.render(ras_ptr, sl, renb, mtx, opacity, bbox);

                    boost::algorithm::ireplace_last(svg_name,".svg",".png");
                    mapnik::save_to_file<mapnik::image_data_32>(im.data(),svg_name,"png");
                    std::ostringstream s;
                    s << "open " << svg_name;
                    system(s.str().c_str());
                }
            }
        }
    }
    catch (...)
    {
        std::clog << "Exception of unknown type!" << std::endl;
        return -1;
    }

    return 0;
}

<commit_msg>handle return of system call<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2010 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#include <iostream>
#include <sstream>
#include <vector>
//#include <string>

#include <mapnik/marker.hpp>
#include <mapnik/marker_cache.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/svg/svg_path_adapter.hpp>
#include <mapnik/svg/svg_renderer.hpp>
#include <mapnik/svg/svg_path_attributes.hpp>

#include <boost/algorithm/string.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/program_options.hpp>

#include "agg_rasterizer_scanline_aa.h"
#include "agg_basics.h"
#include "agg_rendering_buffer.h"
#include "agg_renderer_base.h"
#include "agg_pixfmt_rgba.h"
#include "agg_scanline_u.h"

int main (int argc,char** argv)
{
    namespace po = boost::program_options;

    bool verbose=false;
    std::vector<std::string> svg_files;

    try
    {
        po::options_description desc("svg2png utility");
        desc.add_options()
            ("help,h", "produce usage message")
            ("version,V","print version string")
            ("verbose,v","verbose output")
            ("svg",po::value<std::vector<std::string> >(),"svg file to read")
            ;

        po::positional_options_description p;
        p.add("svg",-1);
        po::variables_map vm;
        po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
        po::notify(vm);

        if (vm.count("version"))
        {
            std::clog<<"version 0.3.0" << std::endl;
            return 1;
        }

        if (vm.count("help"))
        {
            std::clog << desc << std::endl;
            return 1;
        }
        if (vm.count("verbose"))
        {
            verbose = true;
        }

        if (vm.count("svg"))
        {
            svg_files=vm["svg"].as< std::vector<std::string> >();
        }
        else
        {
            std::clog << "please provide an svg file!" << std::endl;
            return -1;
        }

        std::vector<std::string>::const_iterator itr = svg_files.begin();
        if (itr == svg_files.end())
        {
            std::clog << "no svg files to render" << std::endl;
            return 0;
        }
        while (itr != svg_files.end())
        {

            std::string svg_name (*itr++);

            boost::optional<mapnik::marker_ptr> marker_ptr = mapnik::marker_cache::instance()->find(svg_name, false);
            if (marker_ptr) {

                mapnik::marker marker  = **marker_ptr;
                if (marker.is_vector()) {

                    typedef agg::pixfmt_rgba32_plain pixfmt;
                    typedef agg::renderer_base<pixfmt> renderer_base;
                    agg::rasterizer_scanline_aa<> ras_ptr;
                    agg::scanline_u8 sl;

                    double opacity = 1;
                    double scale_factor_ = .95;
                    int w = marker.width();
                    int h = marker.height();
                    mapnik::image_32 im(w,h);
                    agg::rendering_buffer buf(im.raw_data(), w, h, w * 4);
                    pixfmt pixf(buf);
                    renderer_base renb(pixf);

                    mapnik::box2d<double> const& bbox = (*marker.get_vector_data())->bounding_box();
                    mapnik::coord<double,2> c = bbox.center();
                    // center the svg marker on '0,0'
                    agg::trans_affine mtx = agg::trans_affine_translation(-c.x,-c.y);
                    // apply symbol transformation to get to map space
                    mtx *= agg::trans_affine_scaling(scale_factor_);
                    // render the marker at the center of the marker box
                    mtx.translate(0.5 * w, 0.5 * h);

                    mapnik::svg::vertex_stl_adapter<mapnik::svg::svg_path_storage> stl_storage((*marker.get_vector_data())->source());
                    mapnik::svg::svg_path_adapter svg_path(stl_storage);
                    mapnik::svg::svg_renderer<mapnik::svg::svg_path_adapter,
                                 agg::pod_bvector<mapnik::svg::path_attributes> > svg_renderer_this(svg_path,
                                         (*marker.get_vector_data())->attributes());

                    svg_renderer_this.render(ras_ptr, sl, renb, mtx, opacity, bbox);

                    boost::algorithm::ireplace_last(svg_name,".svg",".png");
                    mapnik::save_to_file<mapnik::image_data_32>(im.data(),svg_name,"png");
                    std::ostringstream s;
                    s << "open " << svg_name;
                    return system(s.str().c_str());
                }
            }
        }
    }
    catch (...)
    {
        std::clog << "Exception of unknown type!" << std::endl;
        return -1;
    }

    return 0;
}

<|endoftext|>


<commit_before>void loadlibs ()
{
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libminicern");
  gSystem->Load("$(ROOTSYS)/lib/libPhysics");
  gSystem->Load("$(ROOTSYS)/lib/libEG");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTEER");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTGeant3Dummy");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libdummypythia");
  gSystem->Load("$(ROOTSYS)/lib/libEGPythia6");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libEVGEN");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libRALICE");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libFMD");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libMUON");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libPHOS");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libPMD");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libRICH");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTRUCT");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTOF");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTPC");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTRD");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libZDC");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libITS");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libCASTOR");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTART");
}
<commit_msg>Change libdummypythia to libdummypythia6<commit_after>void loadlibs ()
{
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libminicern");
  gSystem->Load("$(ROOTSYS)/lib/libPhysics");
  gSystem->Load("$(ROOTSYS)/lib/libEG");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTEER");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTGeant3Dummy");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libdummypythia6");
  gSystem->Load("$(ROOTSYS)/lib/libEGPythia6");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libEVGEN");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libRALICE");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libFMD");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libMUON");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libPHOS");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libPMD");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libRICH");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTRUCT");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTOF");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTPC");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTRD");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libZDC");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libITS");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libCASTOR");
  gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTART");
}
<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// 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
//
//     https://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 "google/cloud/spanner/internal/status_utils.h"
#include "google/cloud/spanner/database.h"
#include "google/cloud/spanner/testing/status_utils.h"
#include <gmock/gmock.h>

namespace google {
namespace cloud {
namespace spanner_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace {

TEST(StatusUtils, SessionNotFound) {
  Status const session_not_found(StatusCode::kNotFound, "Session not found");
  EXPECT_TRUE(IsSessionNotFound(session_not_found));

  Status const other_not_found(StatusCode::kNotFound, "Other not found");
  EXPECT_FALSE(IsSessionNotFound(other_not_found));

  Status const not_not_found(StatusCode::kUnavailable, "Session not found");
  EXPECT_FALSE(IsSessionNotFound(not_not_found));
}

TEST(StatusUtils, SessionNotFoundResourceInfo) {
  auto db = spanner::Database("project", "instance", "database");
  auto name = db.FullName() + "/sessions/session";
  EXPECT_TRUE(IsSessionNotFound(spanner_testing::SessionNotFoundError(name)));
}

}  // namespace
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace spanner_internal
}  // namespace cloud
}  // namespace google
<commit_msg>test(spanner): additional test for IsSessionNotFound (#9939)<commit_after>// Copyright 2019 Google LLC
//
// 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
//
//     https://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 "google/cloud/spanner/internal/status_utils.h"
#include "google/cloud/spanner/database.h"
#include "google/cloud/spanner/testing/status_utils.h"
#include "google/cloud/internal/status_payload_keys.h"
#include <gmock/gmock.h>

namespace google {
namespace cloud {
namespace spanner_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace {

TEST(StatusUtils, SessionNotFound) {
  Status const session_not_found(StatusCode::kNotFound, "Session not found");
  EXPECT_TRUE(IsSessionNotFound(session_not_found)) << session_not_found;

  Status const other_not_found(StatusCode::kNotFound, "Other not found");
  EXPECT_FALSE(IsSessionNotFound(other_not_found)) << other_not_found;

  Status const not_not_found(StatusCode::kUnavailable, "Session not found");
  EXPECT_FALSE(IsSessionNotFound(not_not_found)) << not_not_found;
}

TEST(StatusUtils, SessionNotFoundResourceInfo) {
  auto db = spanner::Database("project", "instance", "database");
  auto name = db.FullName() + "/sessions/session";
  auto not_found = spanner_testing::SessionNotFoundError(std::move(name));
  EXPECT_TRUE(IsSessionNotFound(not_found)) << not_found;

  // A status with the right ResourceInfo doesn't need a particular message.
  Status still_not_found(not_found.code(), "foo bar", not_found.error_info());
  std::string const key = internal::kStatusPayloadGrpcProto;
  auto payload = internal::GetPayload(not_found, key);
  ASSERT_TRUE(payload.has_value());
  internal::SetPayload(still_not_found, key, *std::move(payload));
  EXPECT_NE(not_found, still_not_found);
  EXPECT_TRUE(IsSessionNotFound(still_not_found)) << still_not_found;
}

}  // namespace
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace spanner_internal
}  // namespace cloud
}  // namespace google
<|endoftext|>


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

#define DUNE_STUFF_FUNCTIONS_DISABLE_CHECKS 1

#ifndef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING
# define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING 1
#endif

// This one has to come first (includes the config.h)!
#include <dune/stuff/test/main.hxx>

#if HAVE_ALUGRID
# include <dune/stuff/common/disable_warnings.hh>
#   include <dune/grid/alugrid.hh>
# include <dune/stuff/common/reenable_warnings.hh>

# include <dune/stuff/common/exceptions.hh>

# include <dune/stuff/common/print.hh>
# include <dune/stuff/common/float_cmp.hh>

# include <dune/hdd/playground/linearelliptic/testcases/ESV2007.hh>

# include "linearelliptic-swipdg.hh"

using namespace Dune;
using namespace HDD;

typedef Dune::ALUGrid< 2, 2, Dune::simplex, Dune::conforming > AluConform2dGridType;

typedef testing::Types< LinearElliptic::TestCases::ESV2007< AluConform2dGridType >
                      > AluConform2dTestCases;

template< class TestCaseType >
struct linearelliptic_SWIPDG_discretization
  : public ::testing::Test
{
  template< GDT::ChooseSpaceBackend space_backend, Stuff::LA::ChooseBackend la_backend >
  static void eoc_study()
  {
    const TestCaseType test_case;
    test_case.print_header(DSC_LOG_INFO);
    DSC_LOG_INFO << std::endl;
    LinearElliptic::Tests::SWIPDGStudy< TestCaseType, 1, space_backend, la_backend > eoc_study(test_case);
    Stuff::Test::check_eoc_study_for_success(eoc_study, eoc_study.run_eoc(DSC_LOG_INFO));
  } // ... eoc_study()

# if HAVE_DUNE_FEM
#   if HAVE_DUNE_ISTL
  static void eoc_study_using_fem_and_istl()
  {
    eoc_study< GDT::ChooseSpaceBackend::fem, Stuff::LA::ChooseBackend::istl_sparse >();
  }
#   endif // HAVE_DUNE_ISTL

#   if HAVE_EIGEN
  static void eoc_study_using_fem_and_eigen_sparse()
  {
    eoc_study< GDT::ChooseSpaceBackend::fem, Stuff::LA::ChooseBackend::eigen_sparse >();
  }
#   endif // HAVE_EIGEN
# endif // HAVE_DUNE_FEM

//  static void eoc_study_using_pdelab_and_istl()
//  {
//    eoc_study< GDT::ChooseSpaceBackend::pdelab, Stuff::LA::ChooseBackend::istl_sparse >();
//  }

//  static void eoc_study_using_pdelab_and_eigen_sparse()
//  {
//    eoc_study< GDT::ChooseSpaceBackend::pdelab, Stuff::LA::ChooseBackend::eigen_sparse >();
//  }
}; // linearelliptic_SWIPDG_discretization

# if HAVE_DUNE_FEM && (HAVE_DUNE_ISTL || HAVE_EIGEN)
TYPED_TEST_CASE(linearelliptic_SWIPDG_discretization, AluConform2dTestCases);
#   if HAVE_DUNE_ISTL
TYPED_TEST(linearelliptic_SWIPDG_discretization, eoc_study_using_fem_and_istl) {
  this->eoc_study_using_fem_and_istl();
}
#   else // HAVE_DUNE_ISTL
TYPED_TEST(DISABLED_linearelliptic_SWIPDG_discretization, eoc_study_using_fem_and_istl) {}
#   endif
#   if HAVE_EIGEN
TYPED_TEST(linearelliptic_SWIPDG_discretization, eoc_study_using_fem_and_eigen_sparse) {
  this->eoc_study_using_fem_and_eigen_sparse();
}
#   else // HAVE_EIGEN
TYPED_TEST(DISABLED_linearelliptic_SWIPDG_discretization, eoc_study_using_fem_and_eigen_sparse) {}
#   endif // HAVE_EIGEN
//TYPED_TEST(linearelliptic_SWIPDG_discretization, eoc_study_using_pdelab_and_istl) {
//  this->eoc_study_using_pdelab_and_istl();
//}
//TYPED_TEST(linearelliptic_SWIPDG_discretization, eoc_study_using_pdelab_and_eigen_sparse) {
//  this->eoc_study_using_pdelab_and_eigen_sparse();
//}
# endif // HAVE_DUNE_FEM && (HAVE_DUNE_ISTL || HAVE_EIGEN)
#else // HAVE_ALUGRID

TYPED_TEST(DISABLED_linearelliptic_SWIPDG_discretization, eoc_study_using_fem_and_istl) {}
TYPED_TEST(DISABLED_linearelliptic_SWIPDG_discretization, eoc_study_using_fem_and_eigen_sparse) {}

#endif // HAVE_ALUGRID
<commit_msg>[test.linearelliptic-swipdg] whitespace<commit_after>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#define DUNE_STUFF_FUNCTIONS_DISABLE_CHECKS 1

#ifndef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING
# define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING 1
#endif

// This one has to come first (includes the config.h)!
#include <dune/stuff/test/main.hxx>

#if HAVE_ALUGRID
# include <dune/stuff/common/disable_warnings.hh>
#   include <dune/grid/alugrid.hh>
# include <dune/stuff/common/reenable_warnings.hh>

# include <dune/stuff/common/exceptions.hh>

# include <dune/stuff/common/print.hh>
# include <dune/stuff/common/float_cmp.hh>

# include <dune/hdd/playground/linearelliptic/testcases/ESV2007.hh>

# include "linearelliptic-swipdg.hh"

using namespace Dune;
using namespace HDD;

typedef ALUGrid< 2, 2, simplex, conforming > AluConform2dGridType;

typedef testing::Types< LinearElliptic::TestCases::ESV2007< AluConform2dGridType >
                      > AluConform2dTestCases;

template< class TestCaseType >
struct linearelliptic_SWIPDG_discretization
  : public ::testing::Test
{
  template< GDT::ChooseSpaceBackend space_backend, Stuff::LA::ChooseBackend la_backend >
  static void eoc_study()
  {
    const TestCaseType test_case;
    test_case.print_header(DSC_LOG_INFO);
    DSC_LOG_INFO << std::endl;
    LinearElliptic::Tests::SWIPDGStudy< TestCaseType, 1, space_backend, la_backend > eoc_study(test_case);
    Stuff::Test::check_eoc_study_for_success(eoc_study, eoc_study.run_eoc(DSC_LOG_INFO));
  } // ... eoc_study()

# if HAVE_DUNE_FEM
#   if HAVE_DUNE_ISTL
  static void eoc_study_using_fem_and_istl()
  {
    eoc_study< GDT::ChooseSpaceBackend::fem, Stuff::LA::ChooseBackend::istl_sparse >();
  }
#   endif // HAVE_DUNE_ISTL

#   if HAVE_EIGEN
  static void eoc_study_using_fem_and_eigen_sparse()
  {
    eoc_study< GDT::ChooseSpaceBackend::fem, Stuff::LA::ChooseBackend::eigen_sparse >();
  }
#   endif // HAVE_EIGEN
# endif // HAVE_DUNE_FEM

//  static void eoc_study_using_pdelab_and_istl()
//  {
//    eoc_study< GDT::ChooseSpaceBackend::pdelab, Stuff::LA::ChooseBackend::istl_sparse >();
//  }

//  static void eoc_study_using_pdelab_and_eigen_sparse()
//  {
//    eoc_study< GDT::ChooseSpaceBackend::pdelab, Stuff::LA::ChooseBackend::eigen_sparse >();
//  }
}; // linearelliptic_SWIPDG_discretization

# if HAVE_DUNE_FEM && (HAVE_DUNE_ISTL || HAVE_EIGEN)

TYPED_TEST_CASE(linearelliptic_SWIPDG_discretization, AluConform2dTestCases);

#   if HAVE_DUNE_ISTL
TYPED_TEST(linearelliptic_SWIPDG_discretization, eoc_study_using_fem_and_istl) {
  this->eoc_study_using_fem_and_istl();
}
#   else // HAVE_DUNE_ISTL
TYPED_TEST(DISABLED_linearelliptic_SWIPDG_discretization, eoc_study_using_fem_and_istl) {}
#   endif

#   if HAVE_EIGEN
TYPED_TEST(linearelliptic_SWIPDG_discretization, eoc_study_using_fem_and_eigen_sparse) {
  this->eoc_study_using_fem_and_eigen_sparse();
}
#   else // HAVE_EIGEN
TYPED_TEST(DISABLED_linearelliptic_SWIPDG_discretization, eoc_study_using_fem_and_eigen_sparse) {}
#   endif // HAVE_EIGEN

//TYPED_TEST(linearelliptic_SWIPDG_discretization, eoc_study_using_pdelab_and_istl) {
//  this->eoc_study_using_pdelab_and_istl();
//}

//TYPED_TEST(linearelliptic_SWIPDG_discretization, eoc_study_using_pdelab_and_eigen_sparse) {
//  this->eoc_study_using_pdelab_and_eigen_sparse();
//}

# endif // HAVE_DUNE_FEM && (HAVE_DUNE_ISTL || HAVE_EIGEN)
#else // HAVE_ALUGRID

TYPED_TEST(DISABLED_linearelliptic_SWIPDG_discretization, eoc_study_using_fem_and_istl) {}
TYPED_TEST(DISABLED_linearelliptic_SWIPDG_discretization, eoc_study_using_fem_and_eigen_sparse) {}

#endif // HAVE_ALUGRID
<|endoftext|>


<commit_before>/*
 * =====================================================================================
 *
 *       Filename:  main.cc
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  03/20/2008 12:34:14 AM EDT
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Nikolaos Vasiloglou (NV), nvasil@ieee.org
 *        Company:  Georgia Tech Fastlab-ESP Lab
 *
 * =====================================================================================
 */

#include <string>
#include "fastlib/fastlib.h"
#include "mvu_objectives.h"
#include "../l_bfgs/l_bfgs.h"

int main(int argc, char *argv[]){
  fx_init(argc, argv);
  std::string optimized_function=fx_param_str(NULL, "optfun", "mvu");
  std::string data_file=fx_param_str_req(NULL, "data_file");
  Matrix data_mat;
  if (data::Load(data_file.c_str(), &data_mat)==SUCCESS_FAIL) {
    FATAL("Didn't manage to load %s", data_file.c_str());
  }
  datanode *optfun_node=fx_param_node(NULL, "optfun");
  datanode *l_bfgs_node=fx_param_node(NULL, "l_bfgs");
  std::string result_file=fx_param_str(NULL, "result_file", "result.csv");
  bool done=false;

  if (optimized_function == "mvu") {
    MaxVariance opt_function;
    opt_function.Init(optfun_node, data_mat);
    LBfgs<MaxVariance> engine;
    engine.Init(&opt_function, l_bfgs_node);
    engine.ComputeLocalOptimumBFGS();
    Matrix result;
    engine.GetResults(&result);
    if (data::Save(result_file.c_str(), result)==SUCCESS_FAIL) {
      FATAL("Didn't manage to save %s", result_file.c_str());
    }
    done=true;
  }
  if (optimized_function=="mfu") {
    MaxVarianceInequalityOnFurthest opt_function;
    opt_function.Init(optfun_node, data_mat);
    LBfgs<MaxVarianceInequalityOnFurthest> engine;
    engine.Init(&opt_function, l_bfgs_node);
    engine.ComputeLocalOptimumBFGS();
    Matrix result;
    engine.GetResults(&result);
    if (data::Save(result_file.c_str(), result)==SUCCESS_FAIL) {
      FATAL("Didn't manage to save %s", result_file.c_str());
    }
    done=true;
  }
  if (optimized_function == "mvuineq"){
    MaxFurthestNeighbors opt_function;
    opt_function.Init(optfun_node, data_mat);
    LBfgs<MaxFurthestNeighbors> engine;
    engine.Init(&opt_function, l_bfgs_node);
    engine.ComputeLocalOptimumBFGS();
    Matrix result;
    engine.GetResults(&result);
    if (data::Save(result_file.c_str(), result)==SUCCESS_FAIL) {
      FATAL("Didn't manage to save %s", result_file.c_str());
    }
    done=true;
  }
  if (done==false) {
    FATAL("The method you provided %s is not supported",
        optimized_function.c_str());
  }
  fx_done();
}
<commit_msg>I need to get rid of some warnings, it is running<commit_after>/*
 * =====================================================================================
 *
 *       Filename:  main.cc
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  03/20/2008 12:34:14 AM EDT
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Nikolaos Vasiloglou (NV), nvasil@ieee.org
 *        Company:  Georgia Tech Fastlab-ESP Lab
 *
 * =====================================================================================
 */

#include <string>
#include "fastlib/fastlib.h"
#include "mvu_objectives.h"
#include "../l_bfgs/l_bfgs.h"

int main(int argc, char *argv[]){
  fx_init(argc, argv);
  std::string optimized_function=fx_param_str(NULL, "optfun", "mvu");
  std::string data_file=fx_param_str_req(NULL, "data_file");
  Matrix data_mat;
  if (data::Load(data_file.c_str(), &data_mat)==SUCCESS_FAIL) {
    FATAL("Didn't manage to load %s", data_file.c_str());
  }
  datanode *optfun_node=fx_param_node(NULL, "optfun");
  datanode *l_bfgs_node=fx_param_node(NULL, "l_bfgs");
  //we need to insert the number of points
  char buffer[128];
  sprintf(buffer, "%i", data_mat.n_cols());
  fx_set_param(l_bfgs_node, "num_of_points", buffer);
  std::string result_file=fx_param_str(NULL, "result_file", "result.csv");
  bool done=false;

  if (optimized_function == "mvu") {
    MaxVariance opt_function;
    opt_function.Init(optfun_node, data_mat);
    LBfgs<MaxVariance> engine;
    engine.Init(&opt_function, l_bfgs_node);
    engine.ComputeLocalOptimumBFGS();
    Matrix result;
    engine.GetResults(&result);
    if (data::Save(result_file.c_str(), result)==SUCCESS_FAIL) {
      FATAL("Didn't manage to save %s", result_file.c_str());
    }
    engine.Destruct();
    done=true;
  }
  if (optimized_function=="mfu") {
    MaxVarianceInequalityOnFurthest opt_function;
    opt_function.Init(optfun_node, data_mat);
    LBfgs<MaxVarianceInequalityOnFurthest> engine;
    engine.Init(&opt_function, l_bfgs_node);
    engine.ComputeLocalOptimumBFGS();
    Matrix result;
    engine.GetResults(&result);
    if (data::Save(result_file.c_str(), result)==SUCCESS_FAIL) {
      FATAL("Didn't manage to save %s", result_file.c_str());
    }
    engine.Destruct();
    done=true;
  }
  if (optimized_function == "mvuineq"){
    MaxFurthestNeighbors opt_function;
    opt_function.Init(optfun_node, data_mat);
    LBfgs<MaxFurthestNeighbors> engine;
    engine.Init(&opt_function, l_bfgs_node);
    engine.ComputeLocalOptimumBFGS();
    Matrix result;
    engine.GetResults(&result);
    if (data::Save(result_file.c_str(), result)==SUCCESS_FAIL) {
      FATAL("Didn't manage to save %s", result_file.c_str());
    }
    engine.Destruct();
    done=true;
  }
  if (done==false) {
    FATAL("The method you provided %s is not supported",
        optimized_function.c_str());
  }
  fx_done();
}
<|endoftext|>