text:
/*
 * Chaos
 *
 * Copyright 2015 Operating Systems Laboratory EPFL
 *
 * 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 <iostream>
#include <boost/program_options.hpp>
#include "options.h"

namespace po = boost::program_options;

int process_options(int argc, char **argv, bool rmat_generator, struct options *options) {
  // Options common for both generators
  po::options_description common("Common options");
  common.add_options()
      ("help", "print this message")
      ("name", po::value<std::string>(&options->global.graphname), "graph name")
      ("threads", po::value<int>(&options->global.nthreads)->default_value(DEFAULT_NTHREADS), "number of threads")
      ("buffer-size", po::value<size_t>(&options->global.buffer_size), "buffer size in bytes")
      ("bpt", po::value<int>(&options->global.buffers_per_thread)->default_value(DEFAULT_BUFFERS_PER_THREAD),
       "number of buffers per thread")
      ("symmetric", "emit also a reverse edge for each generated edge")
      ("seed1", po::value<uint64_t>(&options->rng.userseed1)->default_value(DEFAULT_RNG_USERSEED1),
       "first 64b of seed for rng")
      ("seed2", po::value<uint64_t>(&options->rng.userseed2)->default_value(DEFAULT_RNG_USERSEED2),
       "second 64b of seed for rng");

  // Options specific to ER
  po::options_description er("Erdos-Renyi");
  er.add_options()
      ("vertices", po::value<vertex_t>(&options->erdos_renyi.vertices)->default_value(DEFAULT_ER_VERTICES),
       "number of vertices")
      ("edges", po::value<edge_t>(&options->erdos_renyi.edges)->default_value(DEFAULT_ER_EDGES), "number of edges")
      ("self-loops", "allow self loops")
      ("bipartite", po::value<vertex_t>(&options->erdos_renyi.bipartite),
       "argument should specify the number of vertices on the left side");

  // Options specific to RMAT
  po::options_description rmat("R-MAT");
  rmat.add_options()
      ("scale", po::value<int>(&options->rmat.scale)->default_value(DEFAULT_RMAT_SCALE),
       "log2 of the number of vertices")
      ("edges", po::value<edge_t>(&options->rmat.edges)->default_value(DEFAULT_RMAT_EDGES), "number of edges")
      ("a", po::value<double>(&options->rmat.a)->default_value(DEFAULT_RMAT_A, "0.57"),
       "a, b, c, d are RMAT probabilities (usually a = 3b = 3c > d)")
      ("b", po::value<double>(&options->rmat.b)->default_value(DEFAULT_RMAT_B, "0.19"), "")
      ("c", po::value<double>(&options->rmat.c)->default_value(DEFAULT_RMAT_C, "0.19"), "")
      ("xscale_interval", po::value < unsigned
  int > (&options->rmat.xscale_interval)->default_value(1), "# xscale machines")
  ("xscale_node", po::value < unsigned
  int > (&options->rmat.xscale_node)->default_value(0), "xscale machine number");

  po::options_description cmdline_options;
  if (rmat_generator)
    cmdline_options.add(common).add(rmat);
  else
    cmdline_options.add(common).add(er);

  // Store options
  bool err = false;
  po::variables_map vm;
  try {
    po::store(po::parse_command_line(argc, argv, cmdline_options), vm);
    po::notify(vm);
  } catch (boost::program_options::error) {
    err = true;
  }

  // Help
  if (vm.count("help") || !vm.count("name") || err) {
    std::cout << "Usage: " << (rmat_generator ? "rmat" : "erdor-renyi") << " --name graphname [options]\n";
    std::cout << "       " << (rmat_generator ? "rmat" : "erdor-renyi") << " --help\n";
    std::cout << cmdline_options << "\n";
    return 1;
  }

  // Process options (where needed)
  if (vm.count("buffer-size")) {
    options->global.buffer_size = vm["buffer-size"].as<size_t>();
  } else {
    options->global.buffer_size = 0;
  }
  if (vm.count("symmetric")) {
    options->global.symmetric = true;
  } else {
    options->global.symmetric = false;
  }
  if (vm.count("self-loops")) {
    options->erdos_renyi.self_loops = true;
  } else {
    options->erdos_renyi.self_loops = false;
  }
  if (!vm.count("bipartite")) {
    options->erdos_renyi.bipartite = 0;
  }

  return 0;
}

ext: cpp

max_stars_repo_name: epfl-labos/chaos

max_issues_repo_name: epfl-labos/chaos

max_forks_repo_name: epfl-labos/chaos


text:
///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (C) 2021, LAAS-CNRS, University of Edinburgh, University of Oxford,
//                     University of Trento
// Copyright note valid unless otherwise stated in individual files.
// All rights reserved.
///////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <typeinfo>
#include <boost/core/demangle.hpp>

#include "crocoddyl/core/utils/exception.hpp"
#include "crocoddyl/core/integ-action-base.hpp"
#include "crocoddyl/core/controls/poly-zero.hpp"

namespace crocoddyl {

template <typename Scalar>
IntegratedActionModelAbstractTpl<Scalar>::IntegratedActionModelAbstractTpl(
    boost::shared_ptr<DifferentialActionModelAbstract> model, const Scalar time_step, const bool with_cost_residual)
    : Base(model->get_state(), model->get_nu(), model->get_nr()),
      differential_(model),
      control_(new ControlParametrizationModelPolyZero(model->get_nu())),
      time_step_(time_step),
      with_cost_residual_(with_cost_residual) {
  init();
}

template <typename Scalar>
IntegratedActionModelAbstractTpl<Scalar>::IntegratedActionModelAbstractTpl(
    boost::shared_ptr<DifferentialActionModelAbstract> model,
    boost::shared_ptr<ControlParametrizationModelAbstract> control, const Scalar time_step,
    const bool with_cost_residual)
    : Base(model->get_state(), control->get_nu(), model->get_nr()),
      differential_(model),
      control_(control),
      time_step_(time_step),
      with_cost_residual_(with_cost_residual) {
  if (control->get_nw() != model->get_nu()) {
    throw_pretty("Invalid argument: "
                 << "control.nw (" + std::to_string(control->get_nw()) + ") is not equals to model.nu (" +
                        std::to_string(model->get_nu()) + ")");
  }
  init();
}

template <typename Scalar>
void IntegratedActionModelAbstractTpl<Scalar>::init() {
  time_step2_ = time_step_ * time_step_;
  enable_integration_ = true;
  VectorXs u_lb(nu_), u_ub(nu_);
  control_->convertBounds(differential_->get_u_lb(), differential_->get_u_ub(), u_lb, u_ub);
  Base::set_u_lb(u_lb);
  Base::set_u_ub(u_ub);
  if (time_step_ < Scalar(0.)) {
    time_step_ = Scalar(1e-3);
    time_step2_ = time_step_ * time_step_;
    std::cerr << "Warning: dt should be positive, set to 1e-3" << std::endl;
  }
  if (time_step_ == Scalar(0.)) {
    enable_integration_ = false;
  }
}

template <typename Scalar>
IntegratedActionModelAbstractTpl<Scalar>::~IntegratedActionModelAbstractTpl() {}

template <typename Scalar>
boost::shared_ptr<ActionDataAbstractTpl<Scalar> > IntegratedActionModelAbstractTpl<Scalar>::createData() {
  if (control_->get_nu() > differential_->get_nu())
    std::cerr
        << "Warning: It is useless to use an Euler integrator with a control parametrization larger than PolyZero"
        << std::endl;
  return boost::allocate_shared<Data>(Eigen::aligned_allocator<Data>(), this);
}

template <typename Scalar>
const boost::shared_ptr<DifferentialActionModelAbstractTpl<Scalar> >&
IntegratedActionModelAbstractTpl<Scalar>::get_differential() const {
  return differential_;
}

template <typename Scalar>
const boost::shared_ptr<ControlParametrizationModelAbstractTpl<Scalar> >&
IntegratedActionModelAbstractTpl<Scalar>::get_control() const {
  return control_;
}

template <typename Scalar>
const Scalar IntegratedActionModelAbstractTpl<Scalar>::get_dt() const {
  return time_step_;
}

template <typename Scalar>
void IntegratedActionModelAbstractTpl<Scalar>::set_dt(const Scalar dt) {
  if (dt < 0.) {
    throw_pretty("Invalid argument: "
                 << "dt has positive value");
  }
  time_step_ = dt;
  time_step2_ = dt * dt;
}

template <typename Scalar>
void IntegratedActionModelAbstractTpl<Scalar>::set_differential(
    boost::shared_ptr<DifferentialActionModelAbstract> model) {
  if (control_->get_nw() != model->get_nu()) {
    throw_pretty("Invalid argument: "
                 << "control.nw (" + std::to_string(control_->get_nw()) + ") is not equals to model.nu (" +
                        std::to_string(model->get_nu()) + ")");
  }

  nr_ = model->get_nr();
  state_ = model->get_state();
  differential_ = model;

  VectorXs p_lb(nu_), p_ub(nu_);
  control_->convertBounds(differential_->get_u_lb(), differential_->get_u_ub(), p_lb, p_ub);
  Base::set_u_lb(p_lb);
  Base::set_u_ub(p_ub);
}

}  // namespace crocoddyl

ext: hxx

max_stars_repo_name: proyan/crocoddyl

max_issues_repo_name: proyan/crocoddyl

max_forks_repo_name: proyan/crocoddyl


text:
/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 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
 *
 *****************************************************************************/

#ifndef CSV_FEATURESET_HPP
#define CSV_FEATURESET_HPP

#include <mapnik/feature.hpp>
#include <mapnik/unicode.hpp>
#include "csv_utils.hpp"
#include "csv_datasource.hpp"
#include <deque>

#if defined(MAPNIK_MEMORY_MAPPED_FILE)
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/streams/bufferstream.hpp>
#pragma GCC diagnostic pop
#include <mapnik/mapped_memory_cache.hpp>
#endif

class csv_featureset : public mapnik::Featureset
{
    using locator_type = csv_utils::geometry_column_locator;
public:
    using array_type = std::deque<csv_datasource::item_type>;
    csv_featureset(std::string const& filename,
                   locator_type const& locator,
                   char separator,
                   char quote,
                   std::vector<std::string> const& headers,
                   mapnik::context_ptr const& ctx,
                   array_type && index_array);
    ~csv_featureset();
    mapnik::feature_ptr next();
private:
    mapnik::feature_ptr parse_feature(char const* beg, char const* end);
#if defined (MAPNIK_MEMORY_MAPPED_FILE)
    using file_source_type = boost::interprocess::ibufferstream;
    mapnik::mapped_region_ptr mapped_region_;
#else
    using file_ptr = std::unique_ptr<std::FILE, int (*)(std::FILE *)>;
    file_ptr file_;
#endif
    char separator_;
    char quote_;
    std::vector<std::string> const& headers_;
    const array_type index_array_;
    array_type::const_iterator index_itr_;
    array_type::const_iterator index_end_;
    mapnik::context_ptr ctx_;
    mapnik::value_integer feature_id_ = 0;
    locator_type const& locator_;
    mapnik::transcoder tr_;
};

#endif // CSV_FEATURESET_HPP

ext: hpp


text:
#ifndef BOOST_GEOMETRY_PROJECTIONS_MBT_FPS_HPP
#define BOOST_GEOMETRY_PROJECTIONS_MBT_FPS_HPP

// Boost.Geometry - extensions-gis-projections (based on PROJ4)
// This file is automatically generated. DO NOT EDIT.

// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.

// This file was modified by Oracle on 2017.
// Modifications copyright (c) 2017, Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

// This file is converted from PROJ4, http://trac.osgeo.org/proj
// PROJ4 is originally written by Gerald Evenden (then of the USGS)
// PROJ4 is maintained by Frank Warmerdam
// PROJ4 is converted to Boost.Geometry by Barend Gehrels

// Last updated version of proj: 4.9.1

// Original copyright notice:

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

#include <boost/geometry/srs/projections/impl/base_static.hpp>
#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>
#include <boost/geometry/srs/projections/impl/projects.hpp>
#include <boost/geometry/srs/projections/impl/factory_entry.hpp>
#include <boost/geometry/srs/projections/impl/aasincos.hpp>

namespace boost { namespace geometry
{

namespace srs { namespace par4
{
    struct mbt_fps {};

}} //namespace srs::par4

namespace projections
{
    #ifndef DOXYGEN_NO_DETAIL
    namespace detail { namespace mbt_fps
    {

            static const int MAX_ITER = 10;
            static const double LOOP_TOL = 1e-7;
            static const double C1 = 0.45503;
            static const double C2 = 1.36509;
            static const double C3 = 1.41546;
            static const double C_x = 0.22248;
            static const double C_y = 1.44492;
            //static const double C1_2 = 0.33333333333333333333333333;

            template <typename T>
            inline T C1_2() { return detail::THIRD<T>(); }

            // template class, using CRTP to implement forward/inverse
            template <typename CalculationType, typename Parameters>
            struct base_mbt_fps_spheroid : public base_t_fi<base_mbt_fps_spheroid<CalculationType, Parameters>,
                     CalculationType, Parameters>
            {

                typedef CalculationType geographic_type;
                typedef CalculationType cartesian_type;

                inline base_mbt_fps_spheroid(const Parameters& par)
                    : base_t_fi<base_mbt_fps_spheroid<CalculationType, Parameters>,
                     CalculationType, Parameters>(*this, par) {}

                // FORWARD(s_forward)  spheroid
                // Project coordinates from geographic (lon, lat) to cartesian (x, y)
                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const
                {
                    static const CalculationType C1_2 = mbt_fps::C1_2<CalculationType>();

                    CalculationType k, V, t;
                    int i;

                    k = C3 * sin(lp_lat);
                    for (i = MAX_ITER; i ; --i) {
                        t = lp_lat / C2;
                        lp_lat -= V = (C1 * sin(t) + sin(lp_lat) - k) /
                            (C1_2 * cos(t) + cos(lp_lat));
                        if (fabs(V) < LOOP_TOL)
                            break;
                    }
                    t = lp_lat / C2;
                    xy_x = C_x * lp_lon * (1. + 3. * cos(lp_lat)/cos(t) );
                    xy_y = C_y * sin(t);
                }

                // INVERSE(s_inverse)  spheroid
                // Project coordinates from cartesian (x, y) to geographic (lon, lat)
                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const
                {
                    CalculationType t;

                    lp_lat = C2 * (t = aasin(xy_y / C_y));
                    lp_lon = xy_x / (C_x * (1. + 3. * cos(lp_lat)/cos(t)));
                    lp_lat = aasin((C1 * sin(t) + sin(lp_lat)) / C3);
                }

                static inline std::string get_name()
                {
                    return "mbt_fps_spheroid";
                }

            };

            // McBryde-Thomas Flat-Pole Sine (No. 2)
            template <typename Parameters>
            inline void setup_mbt_fps(Parameters& par)
            {
                par.es = 0;
            }

    }} // namespace detail::mbt_fps
    #endif // doxygen

    /*!
        \brief McBryde-Thomas Flat-Pole Sine (No. 2) projection
        \ingroup projections
        \tparam Geographic latlong point type
        \tparam Cartesian xy point type
        \tparam Parameters parameter type
        \par Projection characteristics
         - Cylindrical
         - Spheroid
        \par Example
        \image html ex_mbt_fps.gif
    */
    template <typename CalculationType, typename Parameters>
    struct mbt_fps_spheroid : public detail::mbt_fps::base_mbt_fps_spheroid<CalculationType, Parameters>
    {
        inline mbt_fps_spheroid(const Parameters& par) : detail::mbt_fps::base_mbt_fps_spheroid<CalculationType, Parameters>(par)
        {
            detail::mbt_fps::setup_mbt_fps(this->m_par);
        }
    };

    #ifndef DOXYGEN_NO_DETAIL
    namespace detail
    {

        // Static projection
        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::mbt_fps, mbt_fps_spheroid, mbt_fps_spheroid)

        // Factory entry(s)
        template <typename CalculationType, typename Parameters>
        class mbt_fps_entry : public detail::factory_entry<CalculationType, Parameters>
        {
            public :
                virtual base_v<CalculationType, Parameters>* create_new(const Parameters& par) const
                {
                    return new base_v_fi<mbt_fps_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);
                }
        };

        template <typename CalculationType, typename Parameters>
        inline void mbt_fps_init(detail::base_factory<CalculationType, Parameters>& factory)
        {
            factory.add_to_factory("mbt_fps", new mbt_fps_entry<CalculationType, Parameters>);
        }

    } // namespace detail
    #endif // doxygen

} // namespace projections

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_PROJECTIONS_MBT_FPS_HPP


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"
#include <Eigen/LU>

template<typename MatrixType> void inverse(const MatrixType& m)
{
  /* this test covers the following files:
     Inverse.h
  */
  int rows = m.rows();
  int cols = m.cols();

  typedef typename MatrixType::Scalar Scalar;
  typedef typename NumTraits<Scalar>::Real RealScalar;
  typedef Matrix<Scalar, MatrixType::ColsAtCompileTime, 1> VectorType;

  MatrixType m1 = MatrixType::Random(rows, cols),
             m2(rows, cols),
             mzero = MatrixType::Zero(rows, cols),
             identity = MatrixType::Identity(rows, rows);

  while(ei_abs(m1.determinant()) < RealScalar(0.1) && rows <= 8)
  {
    m1 = MatrixType::Random(rows, cols);
  }

  m2 = m1.inverse();
  VERIFY_IS_APPROX(m1, m2.inverse() );

  m1.computeInverse(&m2);
  VERIFY_IS_APPROX(m1, m2.inverse() );

  VERIFY_IS_APPROX((Scalar(2)*m2).inverse(), m2.inverse()*Scalar(0.5));

  VERIFY_IS_APPROX(identity, m1.inverse() * m1 );
  VERIFY_IS_APPROX(identity, m1 * m1.inverse() );

  VERIFY_IS_APPROX(m1, m1.inverse().inverse() );

  // since for the general case we implement separately row-major and col-major, test that
  VERIFY_IS_APPROX(m1.transpose().inverse(), m1.inverse().transpose());
}

void test_eigen2_inverse()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1( inverse(Matrix<double,1,1>()) );
    CALL_SUBTEST_2( inverse(Matrix2d()) );
    CALL_SUBTEST_3( inverse(Matrix3f()) );
    CALL_SUBTEST_4( inverse(Matrix4f()) );
    CALL_SUBTEST_5( inverse(MatrixXf(8,8)) );
    CALL_SUBTEST_6( inverse(MatrixXcd(7,7)) );
  }
}

max_stars_repo_name: subond/tools

max_issues_repo_name: subond/tools

max_forks_repo_name: subond/tools


text:
//  Boost string_algo library predicate.hpp header file  ---------------------------//

//  Copyright Pavol Droba 2002-2003.
//
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/ for updates, documentation, and revision history.

#ifndef BOOST_STRING_PREDICATE_DETAIL_HPP
#define BOOST_STRING_PREDICATE_DETAIL_HPP

#include <iterator>
#include <boost/algorithm/string/find.hpp>

namespace lslboost {
    namespace algorithm {
        namespace detail {

//  ends_with predicate implementation ----------------------------------//

            template<
                typename ForwardIterator1T,
                typename ForwardIterator2T,
                typename PredicateT>
            inline bool ends_with_iter_select(
                ForwardIterator1T Begin,
                ForwardIterator1T End,
                ForwardIterator2T SubBegin,
                ForwardIterator2T SubEnd,
                PredicateT Comp,
                std::bidirectional_iterator_tag)
            {
                ForwardIterator1T it=End;
                ForwardIterator2T pit=SubEnd;
                for(;it!=Begin && pit!=SubBegin;)
                {
                    if( !(Comp(*(--it),*(--pit))) )
                        return false;
                }

                return pit==SubBegin;
            }

            template<
                typename ForwardIterator1T,
                typename ForwardIterator2T,
                typename PredicateT>
            inline bool ends_with_iter_select(
                ForwardIterator1T Begin,
                ForwardIterator1T End,
                ForwardIterator2T SubBegin,
                ForwardIterator2T SubEnd,
                PredicateT Comp,
                std::forward_iterator_tag)
            {
                if ( SubBegin==SubEnd )
                {
                    // empty subsequence check
                    return true;
                }

                iterator_range<ForwardIterator1T> Result
                    =last_finder(
                        ::lslboost::make_iterator_range(SubBegin, SubEnd),
                        Comp)(Begin, End);

                return !Result.empty() && Result.end()==End;
            }

        } // namespace detail
    } // namespace algorithm
} // namespace lslboost

#endif  // BOOST_STRING_PREDICATE_DETAIL_HPP

max_stars_repo_name: samuelpowell/liblsl

max_issues_repo_name: samuelpowell/liblsl

max_forks_repo_name: samuelpowell/liblsl


text:
//
// experimental/channel_error.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2022 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_ASIO_EXPERIMENTAL_CHANNEL_ERROR_HPP
#define BOOST_ASIO_EXPERIMENTAL_CHANNEL_ERROR_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/detail/config.hpp>
#include <boost/system/error_code.hpp>

#include <boost/asio/detail/push_options.hpp>

namespace boost {
namespace asio {
namespace experimental {
namespace error {

enum channel_errors
{
  /// The channel was closed.
  channel_closed = 1,

  /// The channel was cancelled.
  channel_cancelled = 2
};

extern BOOST_ASIO_DECL
const boost::system::error_category& get_channel_category();

static const boost::system::error_category&
  channel_category BOOST_ASIO_UNUSED_VARIABLE
  = boost::asio::experimental::error::get_channel_category();

} // namespace error
namespace channel_errc {
  // Simulates a scoped enum.
  using error::channel_closed;
  using error::channel_cancelled;
} // namespace channel_errc
} // namespace experimental
} // namespace asio
} // namespace boost

namespace boost {
namespace system {

template<> struct is_error_code_enum<
    boost::asio::experimental::error::channel_errors>
{
  static const bool value = true;
};

} // namespace system
} // namespace boost

namespace boost {
namespace asio {
namespace experimental {
namespace error {

inline boost::system::error_code make_error_code(channel_errors e)
{
  return boost::system::error_code(
      static_cast<int>(e), get_channel_category());
}

} // namespace error
} // namespace experimental
} // namespace asio
} // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#if defined(BOOST_ASIO_HEADER_ONLY)
# include <boost/asio/experimental/impl/channel_error.ipp>
#endif // defined(BOOST_ASIO_HEADER_ONLY)

#endif // BOOST_ASIO_EXPERIMENTAL_CHANNEL_ERROR_HPP


text:
#define BOOST_TEST_MODULE base_library_test
#include <boost/test/included/unit_test.hpp>

#include <iostream>
#include "log_test.hpp"
#include "parameters_test.hpp"

void separator()
{
  std::cout << std::endl << "-----------------------------------------------"
  "------------------------------------" << std::endl << std::endl;
}

BOOST_AUTO_TEST_CASE(log_test)
{
  separator();
  BOOST_CHECK(log_test_1());
  separator();
  BOOST_CHECK(log_test_2());
  separator();
  BOOST_CHECK(log_test_3());
  separator();
  BOOST_CHECK(log_test_4());
  separator();
  BOOST_CHECK(log_test_5());
  separator();
}

BOOST_AUTO_TEST_CASE(parameters_test)
{
  BOOST_CHECK(parameters_test_1());
  separator();
  BOOST_CHECK(parameters_test_2());
  separator();
  BOOST_CHECK(parameters_test_3());
  separator();

}

max_stars_repo_name: bartbalaz/gentroller

max_issues_repo_name: bartbalaz/gentroller

max_forks_repo_name: bartbalaz/gentroller


text:
/*=========================================================================
 *
 *  Copyright David Doria 2012 daviddoria@gmail.com
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/

// Custom
#include "Utilities/IndirectPriorityQueue.h"

// Submodules
#include <Helpers/Helpers.h>

// Pixel descriptors
#include "PixelDescriptors/ImagePatchPixelDescriptor.h"

// Descriptor visitors
#include "Visitors/DescriptorVisitors/ImagePatchDescriptorVisitor.hpp"

// Inpainting visitors
#include "Visitors/InpaintingVisitors/InpaintingVisitor.hpp"
#include "Visitors/AcceptanceVisitors/DefaultAcceptanceVisitor.hpp"

// Nearest neighbors
#include "NearestNeighbor/LinearSearchBest/Property.hpp"

// Initializers
#include "Initializers/InitializeFromMaskImage.hpp"
#include "Initializers/InitializePriority.hpp"

// Inpainters
#include "Inpainters/CompositePatchInpainter.hpp"
#include "Inpainters/PatchInpainter.hpp"

// Difference functions
#include "DifferenceFunctions/Patch/ImagePatchDifference.hpp"
#include "DifferenceFunctions/Pixel/SumAbsolutePixelDifference.hpp"
#include "DifferenceFunctions/Pixel/SumSquaredPixelDifference.hpp"

// Utilities
#include "Utilities/PatchHelpers.h"

// Inpainting
#include "Algorithms/InpaintingAlgorithm.hpp"

// Priority
#include "Priority/PriorityCriminisi.h"

// ITK
#include "itkImageFileReader.h"

// Boost
#include <boost/graph/grid_graph.hpp>
#include <boost/property_map/property_map.hpp>

// Run with: Data/trashcan.png Data/trashcan.mask 15 filled.png
int main(int argc, char *argv[])
{
  // Verify arguments
  if(argc != 5)
  {
    std::cerr << "Required arguments: image.png imageMask.mask patchHalfWidth output.png" << std::endl;
    std::cerr << "Input arguments: ";
    for(int i = 1; i < argc; ++i)
    {
      std::cerr << argv[i] << " ";
    }
    return EXIT_FAILURE;
  }

  // Parse arguments
  std::string imageFilename = argv[1];
  std::string maskFilename = argv[2];

  std::stringstream ssPatchHalfWidth;
  ssPatchHalfWidth << argv[3];
  unsigned int patchHalfWidth = 0;
  ssPatchHalfWidth >> patchHalfWidth;

  std::string outputFileName = argv[4];

  // Output arguments
  std::cout << "Reading image: " << imageFilename << std::endl;
  std::cout << "Reading mask: " << maskFilename << std::endl;
  std::cout << "Patch half width: " << patchHalfWidth << std::endl;
  std::cout << "Output: " << outputFileName << std::endl;

  typedef itk::Image<itk::CovariantVector<int, 3>, 2> OriginalImageType;

  typedef  itk::ImageFileReader<OriginalImageType> ImageReaderType;
  ImageReaderType::Pointer imageReader = ImageReaderType::New();
  imageReader->SetFileName(imageFilename);
  imageReader->Update();

  OriginalImageType* originalImage = imageReader->GetOutput();

  Mask::Pointer mask = Mask::New();
  mask->Read(maskFilename);

  itk::ImageRegion<2> fullRegion = originalImage->GetLargestPossibleRegion();

  // Blur the image
  typedef OriginalImageType BlurredImageType; // Usually the blurred image is the same type as the original image.
  typename BlurredImageType::Pointer blurredImage = BlurredImageType::New();
  float blurVariance = 2.0f;
  MaskOperations::MaskedBlur(originalImage, mask, blurVariance, blurredImage.GetPointer());

  ITKHelpers::WriteRGBImage(blurredImage.GetPointer(), "BlurredImage.png");

  typedef ImagePatchPixelDescriptor<OriginalImageType> ImagePatchPixelDescriptorType;

  // Create the graph
  typedef boost::grid_graph<2> VertexListGraphType;
  boost::array<std::size_t, 2> graphSideLengths = { { fullRegion.GetSize()[0],
                                                      fullRegion.GetSize()[1] } };
  VertexListGraphType graph(graphSideLengths);
  typedef boost::graph_traits<VertexListGraphType>::vertex_descriptor VertexDescriptorType;
  typedef boost::graph_traits<VertexListGraphType>::vertex_iterator VertexIteratorType;

  // Queue
  typedef IndirectPriorityQueue<VertexListGraphType> BoundaryNodeQueueType;
  BoundaryNodeQueueType boundaryNodeQueue(graph);

  // Create the descriptor map. This is where the data for each pixel is stored.
  typedef boost::vector_property_map<ImagePatchPixelDescriptorType,
      BoundaryNodeQueueType::IndexMapType> ImagePatchDescriptorMapType;
  ImagePatchDescriptorMapType imagePatchDescriptorMap(num_vertices(graph), boundaryNodeQueue.IndexMap);

  // Create the patch inpainter.
  typedef PatchInpainter<OriginalImageType> OriginalImageInpainterType;
  OriginalImageInpainterType originalImagePatchInpainter(patchHalfWidth, originalImage, mask);
  originalImagePatchInpainter.SetDebugImages(true);
  originalImagePatchInpainter.SetImageName("RGB");

  // Create an inpainter for the blurred image.
  typedef PatchInpainter<BlurredImageType> BlurredImageInpainterType;
  BlurredImageInpainterType blurredImagePatchInpainter(patchHalfWidth, blurredImage, mask);

  // Create a composite inpainter.
  CompositePatchInpainter inpainter;
  inpainter.AddInpainter(&originalImagePatchInpainter);
  inpainter.AddInpainter(&blurredImagePatchInpainter);

  // Create the priority function
  typedef PriorityCriminisi<BlurredImageType> PriorityType;
  PriorityType priorityFunction(blurredImage, mask, patchHalfWidth);

  // Create the descriptor visitor
  typedef ImagePatchDescriptorVisitor<VertexListGraphType, OriginalImageType, ImagePatchDescriptorMapType>
      ImagePatchDescriptorVisitorType;
  ImagePatchDescriptorVisitorType imagePatchDescriptorVisitor(originalImage, mask, imagePatchDescriptorMap, patchHalfWidth);

  typedef DefaultAcceptanceVisitor<VertexListGraphType> AcceptanceVisitorType;
  AcceptanceVisitorType acceptanceVisitor;

  // Create the inpainting visitor
  typedef InpaintingVisitor<VertexListGraphType, BoundaryNodeQueueType,
                            ImagePatchDescriptorVisitorType, AcceptanceVisitorType, PriorityType, OriginalImageType>
                            InpaintingVisitorType;
  InpaintingVisitorType inpaintingVisitor(mask, boundaryNodeQueue,
                                          imagePatchDescriptorVisitor, acceptanceVisitor,
                                          &priorityFunction, patchHalfWidth, "InpaintingVisitor", originalImage);
  inpaintingVisitor.SetAllowNewPatches(false);
  inpaintingVisitor.SetDebugImages(true);

  InitializePriority(mask, boundaryNodeQueue, &priorityFunction);

  // Initialize the boundary node queue from the user provided mask image.
  InitializeFromMaskImage<InpaintingVisitorType, VertexDescriptorType>(mask, &inpaintingVisitor);
  std::cout << "PatchBasedInpaintingNonInteractive: There are " << boundaryNodeQueue.CountValidNodes()
            << " nodes in the boundaryNodeQueue" << std::endl;

  // Create the nearest neighbor finder
  // SAD
//  typedef ImagePatchDifference<ImagePatchPixelDescriptorType,
//      SumAbsolutePixelDifference<typename TImage::PixelType> > PatchDifferenceType;

  // SSD (takes about the same time as SAD)
  typedef ImagePatchDifference<ImagePatchPixelDescriptorType,
      SumSquaredPixelDifference<typename OriginalImageType::PixelType> > PatchDifferenceType;

  typedef LinearSearchBestProperty<ImagePatchDescriptorMapType,
                                   PatchDifferenceType> BestSearchType;
  BestSearchType linearSearchBest(imagePatchDescriptorMap);

  // Perform the inpainting
  InpaintingAlgorithm(graph, inpaintingVisitor, &boundaryNodeQueue,
                      linearSearchBest, &inpainter);

  // If the output filename is a png file, then use the RGBImage writer so that it is first
  // casted to unsigned char. Otherwise, write the file directly.
  if(Helpers::GetFileExtension(outputFileName) == "png")
  {
    ITKHelpers::WriteRGBImage(originalImage, outputFileName);
  }
  else
  {
    ITKHelpers::WriteImage(originalImage, outputFileName);
  }

  return EXIT_SUCCESS;
}

max_stars_repo_name: jingtangliao/ff

max_issues_repo_name: jingtangliao/ff

max_forks_repo_name: jingtangliao/ff


text:
/*=============================================================================
Copyright (c) 2016 Paul W. Bible

Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef ALLOWED_RELATIONSHIP_XML_GO_PARSER
#define ALLOWED_RELATIONSHIP_XML_GO_PARSER

#include <ggtk/GoParserInterface.hpp>
#include <ggtk/GoEnums.hpp>
#include <ggtk/RelationshipPolicyInterface.hpp>

#include <ggtk/xml/rapidxml_utils.hpp>
#include <ggtk/xml/rapidxml.hpp>

#include <vector>
#include <string>

#include <boost/tokenizer.hpp>

/*! \class AllowedRelationshipXmlGoParser
	\brief A class to parse only a specified set of relationships

	This class will read a Gene Ontology XML file and add only those relationship
	 which are specified to the graph. The most important method of this class if the
	 parseGoFile which takes the file name as a parameter.

	 Implements GoParserInterface

*/
class AllowedRelationshipXmlGoParser : public GoParserInterface{

public:

	//! Method to parse the go file, should be an XML file
	/*!
		This method will read a Gene Ontology XML file and add only those relationship
		 which are specified to the graph.

	*/
	inline GoGraph* parseGoFile(std::string filename){

		//graph object to be returned
		GoGraph* graph = new GoGraph();

		//open xmlfile
		rapidxml::file<> xmlFile(filename.c_str());

		//initialize document
		rapidxml::xml_document<> doc;
		doc.parse<0>(xmlFile.data());

		//create an xml node
		rapidxml::xml_node<> *node;

		for(node = doc.first_node("obo")->first_node(); node; node = node->next_sibling()){

			//get node name
			std::string type = node->name();

			//if node is a GO term
			if(type == "term"){

				std::string term,name,description,ontology;

				//vector to hold go accession ids of related terms.
				std::vector<std::string> relatedTerms;
				std::vector<std::string> relatedTermRelationship;

				bool isObsolete = false;

				rapidxml::xml_node<> *childNode;
				for(childNode = node->first_node(); childNode; childNode = childNode->next_sibling()){

					std::string attr = childNode->name();
					//attribute specific action
					if(attr == "id"){
						//go accession id
						term = childNode->value();

					}else if(attr == "name"){
						//go natural language name/title
						name = childNode->value();

					}else if(attr == "namespace"){
						//go ontology, BP,MF,CC
						ontology = childNode->value();

					}else if(attr == "def"){
						//go term definition, long form description
						description = childNode->first_node("defstr")->value();

					}else if(attr == "is_a"){
						//is_a relationship
						std::string relatedTerm = childNode->value();

						//add related term to vector for adding later
						relatedTerms.push_back(relatedTerm);

						//add attr as relationship, attr must = "is_a" here
						relatedTermRelationship.push_back(attr);

					}else if(attr == "is_obsolete"){
						//if obsolete set flag.
						isObsolete = true;
						//early exit from loop
						break;

					}else if(attr == "relationship"){
						//extract relationship
						std::string type = childNode->first_node("type")->value();
						//extract term to which related
						std::string toTerm = childNode->first_node("to")->value();

						//add all types of relationships
						relatedTerms.push_back(toTerm);

						relatedTermRelationship.push_back(type);

					}

				}//for each attribute node

				//if term is obsolete continue, do not add to graph

				///////////////////////////////////////////////////////
				// Main work, add nodes, add related nodes, add edges
				///////////////////////////////////////////////////////

				if(!isObsolete){
					//add the current term to the graph
					graph->insertTerm(term,name,description,ontology);

					//loop over all related terms
					for(std::size_t i = 0; i < relatedTerms.size(); ++i){

						//create a temp variable for readability
						std::string relatedTerm = relatedTerms.at(i);
						//std::cout << relatedTerm << "\t";

						//create a temp variable for readability
						std::string relationship = relatedTermRelationship.at(i);
						//std::cout << relationship << std::endl;

						GO::Relationship relationsihpType = GO::relationshipStringToCode(relationship);
						if(!relationshipPolicy->isAllowed(relationsihpType)){continue;}

						//insert related terms, there are just stubs to be overwritten later on
						graph->insertTerm(relatedTerm,"name","description","ontology");

						//insert edge
						graph->insertRelationship(term,relatedTerm,relationship);

					}//end for, each related term
				}

			}//end if, is term?

		}//end for, for each node in obo, source, header, term

		//call to initialize the graph's vertex to index maps
		graph->initMaps();

		//return the graph pointer
		return graph;

	}//end method parseGoFile

	//! A method to test if a file fits the accepted format
	/*!
	Returns true if the file matches accepted format, false otherwise
	*/
	inline bool isFileGood(const std::string &filename){
		std::ifstream in(filename.c_str());
		if (!in.good()){
			return false;
		}else{
			in.close();
		}

		std::size_t count = 0;

		//open xmlfile
		rapidxml::file<> xmlFile(filename.c_str());

		//initialize document
		rapidxml::xml_document<> doc;
		try{
			doc.parse<0>(xmlFile.data());
		}
		catch (rapidxml::parse_error pe){
			return false;
		}

		//create an xml node
		rapidxml::xml_node<> *node;
		for (node = doc.first_node("obo")->first_node(); node; node = node->next_sibling()){

			std::string type = node->name();
			if (type == "term"){
				count += 1;
				if (count == 3){
					break;
				}
			}
		}

		if (count < 3){
			return false;
		}else{
			return true;
		}
	}

	//! a method to create a new instance of this class for use in a factory
	/*!
		creats a new pointer to the parser, used by the factory for go parsers.
	*/
	inline GoParserInterface* clone(){
		return new AllowedRelationshipXmlGoParser(relationshipPolicy);
	}//end method clone

	//! a method to set the policy
	/*!
		sets the policy of the parser
	*/
	inline void setPolicy(RelationshipPolicyInterface* policy){
		relationshipPolicy = policy;
	}//end method setPolicy

	//! A parameterized constructor
	/*!
		constructor that sets the policy
	*/
	inline AllowedRelationshipXmlGoParser(RelationshipPolicyInterface* policy){
		setPolicy(policy);
	}//end parameterized constructor, AllowedRelationshipXmlGoParser

private:
	//! A RelationshipPolicyInterface
    /*! This RelationshipPolicyInterface holds the relationships to be allowed during parsing */
	RelationshipPolicyInterface* relationshipPolicy;

};
#endif

max_stars_repo_name: paulbible/ggtk

max_issues_repo_name: paulbible/ggtk

max_forks_repo_name: paulbible/ggtk


text:
#include <trajopt_utils/macros.h>
TRAJOPT_IGNORE_WARNINGS_PUSH
#include <cmath>
#include <Eigen/Eigen>
#include <fstream>
#include <signal.h>
TRAJOPT_IGNORE_WARNINGS_POP

#include <trajopt_sco/qpoases_interface.hpp>
#include <trajopt_sco/solver_utils.hpp>
#include <trajopt_utils/logging.hpp>
#include <trajopt_utils/stl_to_string.hpp>

using namespace qpOASES;

namespace sco
{
double QPOASES_INFTY = qpOASES::INFTY;

ModelPtr createqpOASESModel()
{
  ModelPtr out(new qpOASESModel());
  return out;
}

qpOASESModel::qpOASESModel()
{
  // set to be fast. More details at:
  // https://www.coin-or.org/qpOASES/doc/3.2/doxygen/classOptions.html
  // https://projects.coin-or.org/qpOASES/browser/stable/3.2/src/Options.cpp#L191
  qpoases_options_.setToMPC();
  qpoases_options_.printLevel = qpOASES::PL_NONE;
  // enable regularisation to deal with degenerate Hessians
  qpoases_options_.enableRegularisation = qpOASES::BT_TRUE;
  qpoases_options_.ensureConsistency();
}

qpOASESModel::~qpOASESModel()
{
}
Var qpOASESModel::addVar(const std::string& name)
{
  vars_.push_back(new VarRep(vars_.size(), name, this));
  lb_.push_back(-QPOASES_INFTY);
  ub_.push_back(QPOASES_INFTY);
  return vars_.back();
}

Cnt qpOASESModel::addEqCnt(const AffExpr& expr, const std::string& /*name*/)
{
  cnts_.push_back(new CntRep(cnts_.size(), this));
  cnt_exprs_.push_back(expr);
  cnt_types_.push_back(EQ);
  return cnts_.back();
}

Cnt qpOASESModel::addIneqCnt(const AffExpr& expr, const std::string& /*name*/)
{
  cnts_.push_back(new CntRep(cnts_.size(), this));
  cnt_exprs_.push_back(expr);
  cnt_types_.push_back(INEQ);
  return cnts_.back();
}

Cnt qpOASESModel::addIneqCnt(const QuadExpr&, const std::string& /*name*/)
{
  assert(0 && "NOT IMPLEMENTED");
  return 0;
}

void qpOASESModel::removeVars(const VarVector& vars)
{
  IntVec inds = vars2inds(vars);
  for (unsigned i = 0; i < vars.size(); ++i)
    vars[i].var_rep->removed = true;
}

void qpOASESModel::removeCnts(const CntVector& cnts)
{
  IntVec inds = cnts2inds(cnts);
  for (unsigned i = 0; i < cnts.size(); ++i)
    cnts[i].cnt_rep->removed = true;
}

void qpOASESModel::updateObjective()
{
  const size_t n = vars_.size();

  Eigen::SparseMatrix<double> sm;
  exprToEigen(objective_, sm, g_, n, true, true);
  eigenToCSC(sm, H_row_indices_, H_column_pointers_, H_csc_data_);

  H_ = SymSparseMat(vars_.size(), vars_.size(), H_row_indices_.data(), H_column_pointers_.data(), H_csc_data_.data());
  H_.createDiagInfo();
}

void qpOASESModel::updateConstraints()
{
  const size_t n = vars_.size();
  const size_t m = cnts_.size();

  lbA_.clear();
  lbA_.resize(m, -QPOASES_INFTY);
  ubA_.clear();
  ubA_.resize(m, QPOASES_INFTY);

  Eigen::SparseMatrix<double> sm;
  Eigen::VectorXd v;
  exprToEigen(cnt_exprs_, sm, v, n);

  for (int i_cnt = 0; i_cnt < m; ++i_cnt)
  {
    lbA_[i_cnt] = (cnt_types_[i_cnt] == INEQ) ? -QPOASES_INFTY : v[i_cnt];
    ubA_[i_cnt] = v[i_cnt];
  }

  eigenToCSC(sm, A_row_indices_, A_column_pointers_, A_csc_data_);
  A_ = SparseMatrix(cnts_.size(), vars_.size(), A_row_indices_.data(), A_column_pointers_.data(), A_csc_data_.data());
}

bool qpOASESModel::updateSolver()
{
  bool solver_updated = false;
  if (!qpoases_problem_ || vars_.size() != qpoases_problem_->getNV() || cnts_.size() != qpoases_problem_->getNC())
  {
    // Create Problem - this should be called only once
    qpoases_problem_.reset(new SQProblem(vars_.size(), cnts_.size()));
    qpoases_problem_->setOptions(qpoases_options_);
    solver_updated = true;
  }
  return solver_updated;
}

void qpOASESModel::createSolver()
{
  qpoases_problem_.reset();
  updateSolver();
}

void qpOASESModel::update()
{
  {
    int inew = 0;
    for (unsigned iold = 0; iold < vars_.size(); ++iold)
    {
      const Var& var = vars_[iold];
      if (!var.var_rep->removed)
      {
        vars_[inew] = var;
        lb_[inew] = lb_[iold];
        ub_[inew] = ub_[iold];
        var.var_rep->index = inew;
        ++inew;
      }
      else
        delete var.var_rep;
    }
    vars_.resize(inew);
    lb_.resize(inew, QPOASES_INFTY);
    ub_.resize(inew, -QPOASES_INFTY);
  }
  {
    int inew = 0;
    for (unsigned iold = 0; iold < cnts_.size(); ++iold)
    {
      const Cnt& cnt = cnts_[iold];
      if (!cnt.cnt_rep->removed)
      {
        cnts_[inew] = cnt;
        cnt_exprs_[inew] = cnt_exprs_[iold];
        cnt_types_[inew] = cnt_types_[iold];
        cnt.cnt_rep->index = inew;
        ++inew;
      }
      else
        delete cnt.cnt_rep;
    }
    cnts_.resize(inew);
    cnt_exprs_.resize(inew);
    cnt_types_.resize(inew);
  }
}

void qpOASESModel::setVarBounds(const VarVector& vars, const DblVec& lower, const DblVec& upper)
{
  for (unsigned i = 0; i < vars.size(); ++i)
  {
    const int varind = vars[i].var_rep->index;
    lb_[varind] = lower[i];
    ub_[varind] = upper[i];
  }
}
DblVec qpOASESModel::getVarValues(const VarVector& vars) const
{
  DblVec out(vars.size());
  for (unsigned i = 0; i < vars.size(); ++i)
  {
    const int varind = vars[i].var_rep->index;
    out[i] = solution_[varind];
  }
  return out;
}

CvxOptStatus qpOASESModel::optimize()
{
  update();
  updateObjective();
  updateConstraints();
  updateSolver();
  qpOASES::returnValue val = qpOASES::RET_QP_SOLUTION_STARTED;

  // Solve Problem
  int nWSR = 255;
  if (qpoases_problem_->isInitialised())
  {
    val = qpoases_problem_->hotstart(&H_, g_.data(), &A_, lb_.data(), ub_.data(), lbA_.data(), ubA_.data(), nWSR,
                                     nullptr);
  }

  if (val != qpOASES::SUCCESSFUL_RETURN)
  {
    // TODO ATM this means we are creating a new solver even if updateSolver
    //      returned true and the problem is not initialized. Still, it makes
    //      tests pass.
    createSolver();

    val = qpoases_problem_->init(&H_, g_.data(), &A_, lb_.data(), ub_.data(), lbA_.data(), ubA_.data(), nWSR, nullptr);
  }

  if (val == qpOASES::SUCCESSFUL_RETURN)
  {
    // opt += m_objective.affexpr.constant;
    solution_.resize(vars_.size(), 0.);
    val = qpoases_problem_->getPrimalSolution(solution_.data());
    return CVX_SOLVED;
  }
  else if (val == qpOASES::RET_INIT_FAILED_INFEASIBILITY)
  {
    return CVX_INFEASIBLE;
  }
  else
  {
    return CVX_FAILED;
  }
}
void qpOASESModel::setObjective(const AffExpr& expr)
{
  objective_.affexpr = expr;
}
void qpOASESModel::setObjective(const QuadExpr& expr)
{
  objective_ = expr;
}
void qpOASESModel::writeToFile(const std::string& /*fname*/)
{
  return;  // NOT IMPLEMENTED
}
VarVector qpOASESModel::getVars() const
{
  return vars_;
}
}

max_stars_repo_name: adam-vonderviszt/moveit

max_issues_repo_name: adam-vonderviszt/moveit

max_forks_repo_name: adam-vonderviszt/moveit


text:
#ifndef INCLUDED_kinematics_SceneIterator_HH
#define INCLUDED_kinematics_SceneIterator_HH

#include "scheme/types.hh"
#include "scheme/util/meta/util.hh"
#include "scheme/util/meta/util.hh"
#include "scheme/util/meta/print_type.hh"
#include "scheme/util/meta/InstanceMap.hh"
#include "scheme/util/container/ContainerInteractions.hh"

#include <boost/foreach.hpp>
#include <boost/shared_ptr.hpp>
#include <vector>

#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/include/mpl.hpp>

#include <boost/iterator/iterator_facade.hpp>

namespace scheme {
namespace kinematics {

namespace m = boost::mpl;
namespace f = boost::fusion;
using std::cout;
using std::endl;

///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////  1 body /////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////

	namespace impl {
		SCHEME_HAS_MEMBER_TYPE(Position)
	}

	// SymPolicies
	template<class Scene, class Actor>
	struct Symmetric {
		typedef typename Scene::Index Index;
		typedef typename Scene::Conformation Conf;
		typedef typename Scene::Position Pos;
		static Index nbodies(Scene const & s) { return s.nbodies(); }
		static Conf const & conformation(Scene const & s, Index i){ return s.__conformation_unsafe__(i); }
		static Pos  const & position(Scene const & s, Index i){ return s.__position_unsafe__(i); }
	};
	template<class Scene, class Actor>
	struct NotSymmetric {
		typedef typename Scene::Index Index;
		typedef typename Scene::Conformation Conf;
		typedef typename Scene::Position Pos;
		static Index nbodies(Scene const & s) { return s.nbodies_asym(); }
		static Conf const & conformation(Scene const & s, Index i){ return s.__conformation_unsafe_asym__(i); }
		static Pos  const & position(Scene const & s, Index i){ return s.__position_unsafe_asym__(i); }
	};

	// Deref Policies
	template<class Scene, class Actor>
	struct PlaceHolder {
		typedef typename Scene::Index Index;
		typedef std::pair<Index,Index> Value;
		static Value deref(Scene const &, Index ib, Index ia){ return Value(ib,ia); }
	};
	template<class Scene, class Actor>
	struct ActorCopy {
		typedef typename Scene::Index Index;
		typedef Actor Value;
		typedef typename Scene::Position Pos;
		static Value deref(Scene const & s, Index ib, Index ia){
			return s.template get_interaction<Actor>(std::make_pair(ib,ia));
		}
	};

	template<
		class Scene,
		class Interaction,
		template<class,class> class SymPolicy,
		template<class,class> class DerefPolicy
	>
	struct SceneIter1B : boost::iterator_facade<
							SceneIter1B<Scene,Interaction,SymPolicy,DerefPolicy>,
							typename DerefPolicy<Scene,Interaction>::Value const,
							boost::forward_traversal_tag,
							typename DerefPolicy<Scene,Interaction>::Value const
						>
	{
		BOOST_STATIC_ASSERT(( !util::meta::is_pair<Interaction>::value ));
		typedef SceneIter1B<Scene,Interaction,SymPolicy,DerefPolicy> THIS;
		typedef Interaction Actor;
		typedef SymPolicy<Scene,Interaction> Sym;
		typedef DerefPolicy<Scene,Interaction> Deref;
		typedef typename Scene::Index Index;
		SceneIter1B(){}
		SceneIter1B(Scene const & s, Index ib, Index ia) : scene_(&s),ibody_(ib),iactor_(ia){}
		static THIS make_begin(Scene const & s){ return THIS(s,next_nonempty(s,(Index)0),(Index)0); }
		static THIS make_end  (Scene const & s){ return THIS(s,  Sym::nbodies(s)       ,(Index)0); }
		static Index next_nonempty(Scene const & s, Index i) {
			// cout << "next_nonempty " << i;
			while( i < Sym::nbodies(s) && 0==Sym::conformation(s,i).template get<Actor>().size() ) ++i;
			// cout << " -> " << i << endl;
			return i;
		}
	private:
	    friend class boost::iterator_core_access;
		void
		increment(){
            assert( ibody_ < Sym::nbodies(*scene_) );
			++iactor_;
			if( iactor_ == Sym::conformation(*scene_,ibody_).template get<Actor>().size() ){
				iactor_ = 0;
				ibody_ = next_nonempty(*scene_,++ibody_);
			}
		}
		typename Deref::Value const
		dereference() const {
			return Deref::deref(*scene_,ibody_,iactor_);
		}
		bool
		equal(THIS const & o) const {
			return scene_==o.scene_ && ibody_==o.ibody_ && iactor_==o.iactor_;
		}
		Scene const * scene_;
		Index ibody_,iactor_;
	};

///////////////////////////////////////////////////////////////////////////////////////////
////////////////////////// 2 body //////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
	// TODO: fix end generation for speed and correctness

	template<class I> struct  make_pairpair { typedef std::pair<std::pair<I,I>,std::pair<I,I> > type; };

	struct CountPairNoDuplicates {
		template<class Index>
		static
		void
		next(Index & i, Index & j, size_t s0, size_t s1){
			++j;
			j += i==j ? 1 : 0; // skip iff j- == i
			if( j >= ((i>=s0)?s0:s1) ){
				j = 0;
				++i;
			}
			// cout << "NEXT " << i << " " << j << endl;
		}
		// static size_t get_i_end(size_t n){ return n; }
		// static size_t get_j_end(size_t  ){ return 0; }
		// template<class Index>
		// static void get_end(size_t , size_t s1, Index & i, Index & j){
		// 	i = s1;
		// 	j = 0;
		// }
		static size_t max_body1(size_t , size_t s1){ return s1; }
	};
	struct CountPairUpperTriangle {
		template<class Index>
		static
		void
		next(Index & i, Index & j, size_t , size_t s1){
			++j;
			if( j >= s1 ){
				++i;
				j = i+1;
			}
		}
		// // static size_t get_i_end(size_t n){ if(n==1) return 1; return n==0?0:n-1; }
		// // static size_t get_j_end(size_t n){ if(n==1) return 2; return n==0?0:n; }
		// template<class Index>
		// static void get_end(size_t s0, size_t s1, Index & i, Index & j){
		// 	if     ( s0==0 ) { i = j = 0; }
		// 	else if( s0==1 ) { i = 1; j = 2; }
		// 	else {
		// 		i = s0-1;
		// 		j = s0;
		// 		i += s0==s1?0:1;
		// 		j += s0==s1?0:1;
		// 	}
		// }
		static size_t max_body1(size_t s0, size_t ){ return s0; }
	};

	template<class _Scene,class _Interaction, class _CountPair>
	struct SceneIter2B : boost::iterator_facade<
							SceneIter2B<_Scene,std::pair<
								typename _Interaction::first_type,
								typename _Interaction::second_type>,
								_CountPair >,
							typename make_pairpair<typename _Scene::Index>::type const,
							boost::forward_traversal_tag,
							typename make_pairpair<typename _Scene::Index>::type const
						>
	{
		typedef _Scene Scene;
		typedef _Interaction Interaction;
		typedef _CountPair CountPair;
		BOOST_STATIC_ASSERT(( util::meta::is_pair<Interaction>::value ));
		typedef typename Interaction::first_type Actor1;
		typedef typename Interaction::second_type Actor2;
		typedef SceneIter2B<Scene,std::pair<Actor1,Actor2>,CountPair> THIS;
		typedef typename Scene::Index Index;
		typedef typename Scene::Conformation Conf;
		typedef typename f::result_of::value_at_key<Conf,Actor1>::type Container1;
		typedef typename f::result_of::value_at_key<Conf,Actor2>::type Container2;
		typedef util::container::ContainerInteractions<typename Scene::Position,Container1,Container2,Index> ContInter;
		typedef typename ContInter::Range ContRange;

		SceneIter2B(){}
		SceneIter2B(Scene const & s, Index ib1, Index ib2) : scene_(&s),ibody1_(ib1),ibody2_(ib2){}
		void
		update_range(){ // X * A = B, X = B * ~A
			assert( ibody1_ < scene_->nbodies_asym() || ibody2_ < scene_->nbodies_asym() );
			ContInter::get_interaction_range(
				scene_->__position_unsafe__(ibody2_) * inverse( scene_->__position_unsafe__(ibody1_) ) ,
				scene_->__conformation_unsafe__(ibody1_).template get<Actor1>()  ,
				scene_->__conformation_unsafe__(ibody2_).template get<Actor2>()  ,
				range_  );
			iter_ = get_cbegin(range_);
			end_  = get_cend(range_);
			// cout << "UPDATE_RANGE " << ibody1_ << " " << ibody2_ << " beg " << *iter_ << " end " << *end_ << endl;
		}
		static
		THIS
		make_begin(
			Scene const & s
		){
			Index i=0,j=s.nbodies()>1?1:0;
			next_while_empty(s,i,j);
			THIS beg(s,i,j);
			// cout << "MAKE BEGIN " << i << " " << j << " " << *beg << endl;
			if( i < (Index)s.nbodies     () && j < (Index)s.nbodies      () &&
			   (i < (Index)s.nbodies_asym() || j < (Index)s.nbodies_asym()) ) beg.update_range();
			return beg;
		}
		static
		THIS
		make_end(
			Scene const & s
		){
			// Index i,j;
			// CountPair::get_end(s.nbodies_asym(),s.nbodies(),i,j);
			return THIS(s,std::numeric_limits<Index>::max(),std::numeric_limits<Index>::max());
		}
		bool is_universal_end() const {
			return ibody1_ == std::numeric_limits<Index>::max() && ibody2_ == std::numeric_limits<Index>::max();
		}
		static
		void
		next_while_empty(
			Scene const & s,
			Index & i,
			Index & j
		) {
			// cout << "next_while_empty " << i<<"-"<<j << endl;
 			while( i < CountPair::max_body1(s.nbodies_asym(),s.nbodies()) && j < s.nbodies() && (
 				0==s.__conformation_unsafe__(i).template get<Actor1>().size() ||
			    0==s.__conformation_unsafe__(j).template get<Actor2>().size() )
			){
				// cout << "  NEXT " << i << " " << j;
 				CountPair::next(i,j,s.nbodies_asym(),s.nbodies());
 				// cout << " -> " << i << " " << j << endl;
 			}
			// cout << " -> " << i << "-" << j << endl;
		}
	private:
	    friend class boost::iterator_core_access;
		void
		increment(){
			// cout << "INCREMENT iter_ " << *iter_;
			++iter_;
			// cout << " -> " << *iter_ << " end " << *end_ << endl;
			if( iter_==end_ ){ // end_ of body/body inter, must update range_
				CountPair::next(ibody1_,ibody2_,scene_->nbodies_asym(),scene_->nbodies());
				// cout << "NEXT_NONEMPTY " << ibody1_ << " " << ibody2_;
				next_while_empty(*scene_,ibody1_,ibody2_);
				// cout << " -> " << ibody1_ << " " << ibody2_ << endl;
				if( ibody1_ < scene_->nbodies     () && ibody2_ < scene_->nbodies     () &&
				   (ibody1_ < scene_->nbodies_asym() || ibody2_ < scene_->nbodies_asym() )) update_range();
				// std::cout << "redo range_ " << ibody1_ << " " << ibody2_ << std::endl;
				// std::cout << "SceneIter2B NEW BODIES: " << ibody1_ << " " << ibody2_ << std::endl;
			}
			// not valid when at end
			// assert( ibody1_ < scene_->nbodies_asym() );
			// assert( ibody2_ < scene_->nbodies() );
			// assert( iter_->first  < scene_->body(ibody1_).conformation().template get<Actor1>().size() );
			// assert( iter_->second < scene_->body(ibody2_).conformation().template get<Actor2>().size() );
		}
		typename make_pairpair<Index>::type const
		dereference() const {
			return std::make_pair(std::make_pair(ibody1_,ibody2_),*iter_);
		}
		bool
		equal(THIS const & o) const {
			assert(scene_==o.scene_);
			// hacky but works for checking if at end
			if( o.is_universal_end() ){
				return ( ( ibody1_ >= scene_->nbodies     () || ibody2_ >= scene_->nbodies     () ) ||
				         ( ibody1_ >= scene_->nbodies_asym() && ibody2_ >= scene_->nbodies_asym() ) );
			} else if( is_universal_end() ) {
				return ( ( o.ibody1_ >= o.scene_->nbodies     () || o.ibody2_ >= o.scene_->nbodies     () ) ||
				         ( o.ibody1_ >= o.scene_->nbodies_asym() && o.ibody2_ >= o.scene_->nbodies_asym() ) );
			} else {
				std::cerr << "SceneIter2B can only compare to end!" << std::endl;
				std::exit(-1);
			}
			// // std::cout << "EQUAL " << ibody1_ << " " << ibody2_ << " / " << o.ibody1_ << " " << o.ibody2_ << std::endl;
			// return scene_==o.scene_ && ibody1_==o.ibody1_ && ibody2_==o.ibody2_;
		}
		Scene const * scene_;
		Index ibody1_,ibody2_;
		ContRange range_;
		typename util::container::get_citer<ContRange>::type iter_,end_;
	};

}
}

#endif

ext: hh

max_stars_repo_name: YaoYinYing/rifdock

max_issues_repo_name: YaoYinYing/rifdock

max_forks_repo_name: YaoYinYing/rifdock


text:
#ifndef HAMILTONIANS_XXXXMG_HPP
#define HAMILTONIANS_XXXXMG_HPP
#include <Eigen/Eigen>
#include <nlohmann/json.hpp>

class XXXMG
{
private:
	int n_;

public:

	XXXMG(int n)
		: n_(n)
	{
	}

	nlohmann::json params() const
	{
		return nlohmann::json
		{
			{"name", "XXXXMG"},
			{"n", n_},
		};
	}

	template<class State>
	typename State::Scalar operator()(const State& smp) const
	{
		constexpr double J1 = 1.0;
		constexpr double J2 = 0.5;
		typename State::Scalar s = 0.0;

		{
			double yysign = -smp.sigmaAt(0)*smp.sigmaAt(1);
			s += -J1/2*yysign; //zz
			s += J1/2*(1.0+yysign)*smp.ratio(0, 1); //xx+yy
		}
		{
			double yysign = -smp.sigmaAt(n_-2)*smp.sigmaAt(n_-1);
			s += -J1/2*yysign; //zz
			s += J1/2*(1.0+yysign)*smp.ratio(n_-2, n_-1); //xx+yy
		}
		//Nearest-neighbor
		for(int i = 1; i < (n_-3); i++)
		{
			double yysign = -smp.sigmaAt(i)*smp.sigmaAt(i+1);
			s += -J1*yysign; //zz
			s += J1*(1.0+yysign)*smp.ratio(i, i+1); //xx+yy
		}
		//Next-nearest-neighbor
		for(int i = 0; i < n_-3; i++)
		{
			double yysign = -smp.sigmaAt(i)*smp.sigmaAt(i+2);
			s += -J2*yysign; //zz
			s += J2*(1.0+yysign)*smp.ratio(i, i+2); //xx+yy
		}
		return s;
	}

	std::map<uint32_t, double> operator()(uint32_t col) const
	{
		constexpr double J1 = 1.0;
		constexpr double J2 = 0.5;
		std::map<uint32_t, double> m;
		for(int i = 0; i < n_; i++)
		{
			int b1 = (col >> i) & 1;
			int b2 = (col >> ((i+1)%n_)) & 1;
			int sgn = (1-2*b1)*(1-2*b2);
			long long int x = (1 << i) | (1 << ((i+1)%(n_)));
			m[col ^ x] += J1*(1.0 - sgn*1.0);
			m[col] += J1*sgn;
		}
		for(int i = 0; i < n_; i++)
		{
			int b1 = (col >> i) & 1;
			int b2 = (col >> ((i+2)%n_)) & 1;
			int sgn = (1-2*b1)*(1-2*b2);
			long long int x = (1 << i) | (1 << ((i+2)%(n_)));
			m[col ^ x] += J2*(1.0 - sgn*1.0);
			m[col] += J2*sgn;
		}
		return m;
	}
};
#endif//HAMILTONIANS_XXXXMG_HPP

max_stars_repo_name: cecri/yannq

max_issues_repo_name: cecri/yannq

max_forks_repo_name: cecri/yannq


text:
#define BOOST_TEST_MODULE pcraster dal array
#include <boost/test/unit_test.hpp>
#include "dal_MathUtils.h"
#include "dal_Table.h"

struct Fixture
{

    Fixture()
    {
        using namespace dal;

        d_empty = new Table();

        std::vector<std::string> titles;
        std::vector<TypeId> typeIds;

        typeIds.push_back(TI_UINT1);
        typeIds.push_back(TI_INT4);
        typeIds.push_back(TI_NR_TYPES);
        typeIds.push_back(TI_REAL4);

        titles.push_back("UINT1");
        titles.push_back("INT4");
        titles.push_back("NR_TYPES");
        titles.push_back("REAL4");

        d_table1 = new Table("Table1", titles, typeIds);
        d_table1->createCols();

        Array<UINT1>& col1(d_table1->col<UINT1>(0));
        col1.push_back(1);
        col1.push_back(0);
        col1.push_back(1);

        Array<INT4>& col2(d_table1->col<INT4>(1));
        col2.push_back(3);
        col2.push_back(33);
        col2.push_back(333);

        Array<REAL4>& col4(d_table1->col<REAL4>(3));
        col4.push_back(REAL4(3.3));
        col4.push_back(REAL4(4.4));
        col4.push_back(REAL4(5.5));
    }

    ~Fixture()
    {
        delete d_table1;
        delete d_empty;
    }

    void testEmptyTable(
             dal::Table const& table)
    {
      using namespace dal;

      BOOST_CHECK_EQUAL(table.nrCols(), size_t(0));
      BOOST_CHECK_EQUAL(table.nrRecs(), size_t(0));
      BOOST_CHECK(table.title().empty());
    }

    void testTable1(
             dal::Table const& table)
    {
      using namespace dal;

      BOOST_CHECK_EQUAL(table.nrCols(), size_t(4));
      BOOST_CHECK_EQUAL(table.nrRecs(), size_t(3));
      BOOST_CHECK_EQUAL(table.title(), "Table1");
      BOOST_CHECK_EQUAL(table.typeId(0), TI_UINT1);
      BOOST_CHECK_EQUAL(table.typeId(1), TI_INT4);
      BOOST_CHECK_EQUAL(table.typeId(2), TI_NR_TYPES);
      BOOST_CHECK_EQUAL(table.typeId(3), TI_REAL4);
      BOOST_CHECK_EQUAL(table.title(0), "UINT1");
      BOOST_CHECK_EQUAL(table.title(1), "INT4");
      BOOST_CHECK_EQUAL(table.title(2), "NR_TYPES");
      BOOST_CHECK_EQUAL(table.title(3), "REAL4");

      Array<UINT1> const& col1(table.col<UINT1>(0));
      BOOST_CHECK(dal::comparable(col1[0], UINT1(1)));
      BOOST_CHECK(dal::comparable(col1[1], UINT1(0)));
      BOOST_CHECK(dal::comparable(col1[2], UINT1(1)));

      Array<INT4> const& col2(table.col<INT4>(1));
      BOOST_CHECK(dal::comparable(col2[0], INT4(3)));
      BOOST_CHECK(dal::comparable(col2[1], INT4(33)));
      BOOST_CHECK(dal::comparable(col2[2], INT4(333)));

      Array<REAL4> const& col4(table.col<REAL4>(3));
      BOOST_CHECK(dal::comparable(col4[0], REAL4(3.3)));
      BOOST_CHECK(dal::comparable(col4[1], REAL4(4.4)));
      BOOST_CHECK(dal::comparable(col4[2], REAL4(5.5)));
    }

    dal::Table* d_empty;

    dal::Table* d_table1;

};

BOOST_FIXTURE_TEST_SUITE(table, Fixture)

BOOST_AUTO_TEST_CASE(constructor)
{
  using namespace dal;

  // empty
  testEmptyTable(*d_empty);

  // table1
  testTable1(*d_table1);
}

BOOST_AUTO_TEST_CASE(copy)
{
  using namespace dal;

  // Copy construct empty.
  {
    Table copy(*d_empty);
    testEmptyTable(copy);
  }

  // Copy construct table1.
  {
    Table copy(*d_table1);
    testTable1(copy);
  }

  // Assign empty to table1.
  {
    Table copy(*d_table1);
    copy = *d_empty;
    testEmptyTable(copy);
  }

  // Assign table1 to empty.
  {
    Table copy(*d_empty);
    copy = *d_table1;
    testTable1(copy);
  }
}

BOOST_AUTO_TEST_CASE(assign)
{
  using namespace dal;

  {
    Table table1, table2;

    table1.appendCol<INT4>();
    table1.appendCol<INT4>();

    size_t joinFrom = 0;
    size_t colToWrite = 1;

    Array<INT4>& ids1(table1.col<INT4>(joinFrom));
    ids1.resize(5);
    ids1[0] = 1;
    ids1[1] = 3;
    ids1[2] = 5;
    ids1[3] = 7;
    ids1[4] = 9;

    Array<INT4>& values1(table1.col<INT4>(colToWrite));
    values1.resize(5);
    values1[0] = 5;
    values1[1] = 5;
    values1[2] = 5;
    pcr::setMV(values1[3]);
    values1[4] = 5;

    table2.appendCol<INT4>();
    table2.appendCol<INT4>();

    size_t joinTo = 1;
    size_t colToRead = 0;

    Array<INT4>& ids2(table2.col<INT4>(joinTo));
    ids2.resize(5);
    ids2[0] = 9;
    ids2[1] = 3;
    ids2[2] = 1;
    ids2[3] = 7;
    ids2[4] = 5;

    Array<INT4>& values2(table2.col<INT4>(colToRead));
    values2.resize(5);
    values2[0] = 4;
    pcr::setMV(values2[1]);
    values2[2] = 3;
    values2[3] = 2;
    values2[4] = 1;

    table1.assign(colToWrite, joinFrom, table2, colToRead, joinTo);

    BOOST_CHECK_EQUAL(values1[0], 3);
    BOOST_CHECK(pcr::isMV(values1[1]));
    BOOST_CHECK_EQUAL(values1[2], 1);
    BOOST_CHECK_EQUAL(values1[3], 2);
    BOOST_CHECK_EQUAL(values1[4], 4);
  }
}

BOOST_AUTO_TEST_SUITE_END()

ext: cc

max_stars_repo_name: quanpands/wflow

max_issues_repo_name: quanpands/wflow

max_forks_repo_name: quanpands/wflow


text:
#pragma once

#include "Read.hpp"
#include "Tile.hpp"
#include "common/Histogram.hpp"
#include "common/Utility.hpp"

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/variance.hpp>

#include <cstddef>
#include <iostream>
#include <iomanip>
#include <stdint.h>
#include <math.h>

using namespace boost::accumulators;

struct BufferProcessor {
    typedef vector<Read> ReadVector;
    typedef boost::unordered_map<Signature, ReadVector> SignatureMap;

    Histogram<uint64_t> dup_insert_sizes;
    Histogram<uint64_t> nondup_insert_sizes;
    Histogram<uint64_t> distances;
    Histogram<uint64_t> number_of_dups;
    Histogram<Tile> tile_duplicates;
    Histogram<Tile> tile_unique;

    std::size_t total_duplicated; //should include reads normally marked as unique
    std::size_t total_dups;       //will only include those reads typically reported as duplicates (ie # fragments in duplicated cluster -1 )
    std::size_t total_fragments;
    std::size_t total_flow_cell_dups;
    std::size_t dup_on_same_strand;
    std::size_t dup_on_different_strand;

    BufferProcessor()
        : total_duplicated(0)
        , total_dups(0)
        , total_fragments(0)
        , total_flow_cell_dups(0)
        , dup_on_same_strand(0)
        , dup_on_different_strand(0)
    {}

    void update_distances(ReadVector const& reads) {
        // XXX Potential algorithms for distinguishing library duplicates
        // for each read:
        //  scan other reads
        //  if current read is not in the ignore set and scanned read is not in ignore set (will still need other stats so can't just skip) and distance < cutoff
        //      then add scanned read to ignore
        //
        // Count up non-ignored reads. These are our library duplicates. Alternatively, only count dups to ignore. Then could do math...

        std::size_t n = reads.size();
        for (std::size_t i = 0; i < n; ++i) {
            ++dup_insert_sizes[abs(reads[i].insert_size)];
            nondup_insert_sizes[abs(reads[i].insert_size)] += 0;
            ++tile_duplicates[reads[i].tile];
            tile_unique[reads[i].tile] += 0;
            for (std::size_t j = i + 1; j < n; ++j) {
                if (is_on_same_tile(reads[i], reads[j])) {
                    uint64_t flow_cell_distance = euclidean_distance(reads[i], reads[j]);
                    ++distances[flow_cell_distance];
                    if (!reads[i].ignore) {
                        reads[j].ignore = true;
                        ++total_flow_cell_dups;
                    }
                }
                else
                if (is_on_adjacent_tile(reads[i], reads[j])) {
                    if (!reads[i].ignore && !reads[j].ignore) {
                        reads[j].ignore = true;
                        ++total_flow_cell_dups;
                    }
                }
                //Only do the below for paired duplicates. If more than 2 copies, this inflates with pairwise comparisons
                if (n == 2) {
                    if (is_on_same_strand(reads[i], reads[j])) {
                        ++dup_on_same_strand;
                    }
                    else {
                        ++dup_on_different_strand;
                    }
                }
            }
        }
    }

    void operator()(ReadVector const& reads) {
        total_fragments += reads.size();
        if (reads.size() > 1) {
            total_dups += (reads.size() - 1);
            total_duplicated += reads.size();
            ++number_of_dups[reads.size()];
            update_distances(reads);
        }
        else {
            dup_insert_sizes[abs(reads[0].insert_size)] += 0;
            ++nondup_insert_sizes[abs(reads[0].insert_size)];

            ++tile_unique[reads[0].tile];
            tile_duplicates[reads[0].tile] += 0;
        }
    }

    void merge(BufferProcessor& x) {
        dup_insert_sizes.merge(x.dup_insert_sizes);
        nondup_insert_sizes.merge(x.nondup_insert_sizes);
        distances.merge(x.distances);
        number_of_dups.merge(x.number_of_dups);
        total_dups += x.total_dups;
        total_duplicated += x.total_duplicated;
    }

    double standard_deviation_dup_rates() {
        accumulator_set<double, stats<tag::variance(lazy)> > acc;
        typedef Histogram<Tile>::VectorType TVec;
        TVec tiles = tile_unique.as_vector();
        for (TVec::const_iterator i = tiles.begin(); i != tiles.end(); ++i) {
            acc( (double) tile_duplicates[i->name] / (double) (tile_duplicates[i->name] + i->count));
        }
        return sqrt(variance(acc));
    }

    //XXX This is terrible and should abstracted out
    void write_output(std::ostream& os) {

        double std_dev = standard_deviation_dup_rates();

        os << "{\n"; //start json
        os << " \"summary\": [\n";
        os << "    { "
           << "\"total_fragments\": " << total_fragments
           << ", "
           << "\"total_duplicated_fragments\": " << total_duplicated
           << ", "
           << "\"total_duplicate_fragments\": " << total_dups
           << ", "
           << "\"total_flowcell_duplicates\": " << total_flow_cell_dups
           << ", "
           << "\"duplicate_on_same_strand(pairs)\": " << dup_on_same_strand
           << ", "
           << "\"duplicate_on_different_strand(pairs)\": " << dup_on_different_strand
           << ", "
           << "\"subtile_dup_rate_stdev\": " << std::setprecision(7) << std_dev
           << ", "
           << "\"dup_rate\": " << std::setprecision(7) << (float) total_dups / total_fragments
           << ", "
           << "\"estimated_library_dup_rate\": " << std::setprecision(7) << (float) (total_dups - total_flow_cell_dups) / (total_fragments - total_flow_cell_dups)
           << " }\n ],\n";
        typedef Histogram<uint64_t>::VectorType HVec;
        HVec dist = distances.as_sorted_vector();
        os << " \"distance\": [\n";
        for (HVec::const_iterator i = dist.begin(); i != dist.end(); ++i) {
            os << "    { "
               << "\"intratile_distance\": " << i->name
               << ", "
               << "\"count\": " << i->count
               << " }";
            if (i + 1 != dist.end()) {
                os << ",\n";
            }
        }
        os << "\n ],\n";

        os << " \"num_times_duplicated\": [\n";
        HVec ndup = number_of_dups.as_sorted_vector();
        for (HVec::const_iterator i = ndup.begin(); i != ndup.end(); ++i) {
            os << "    { "
               << "\"num_duplicates\": " << i->name
               << ", "
               << "\"count\": " << i->count
               << " }";
            if (i + 1 != ndup.end()) {
                os << ",\n";
            }
        }
        os << "\n ],\n";

        os << " \"insert_size\": [\n";
        HVec isizes = nondup_insert_sizes.as_sorted_vector();
        for (HVec::const_iterator i = isizes.begin(); i != isizes.end(); ++i) {
            os << "    { "
               << "\"insert_size\": " << i->name
               << ", "
               << "\"unique_count\": " << i->count
               << ", "
               << "\"duplicate_count\": " << dup_insert_sizes[i->name]
               << " }";
            if (i + 1 != isizes.end()) {
                os << ",\n";
            }
        }
        os << "\n ],\n";

        typedef Histogram<Tile>::VectorType TVec;
        os << " \"per_tile_stats\": [\n";
        TVec tiles = tile_unique.as_sorted_vector();
        for (TVec::const_iterator i = tiles.begin(); i != tiles.end(); ++i) {
            os << "    { "
               << "\"flowcell\": \"" << i->name.flowcell << "\""
               << ", "
               << "\"lane\": " << i->name.lane
               << ", "
               << "\"tile\": " << i->name.id
               << ", "
               << "\"subtile_x\": " << i->name.subtile_x
               << ", "
               << "\"subtile_y\": " << i->name.subtile_y
               << ", "
               << "\"unique_count\": " << i->count
               << ", "
               << "\"duplicate_count\": " << tile_duplicates[i->name]
               << " }";
            if (i + 1 != tiles.end()) {
                os << ",\n";
            }
        }

        os << "\n ]\n}\n";

        std::cerr << total_dups << " duplicates found out of " << total_fragments << " (" << (float) total_dups / total_fragments * 100.0 << "%).\n";
        std::cerr << total_dups - total_flow_cell_dups << " library duplicates found out of " << total_fragments - total_flow_cell_dups << " total fragments minus flow cell duplicates (" << (float) (total_dups - total_flow_cell_dups) / (total_fragments - total_flow_cell_dups) * 100.0 << "%).\n";
    }
};


text:
#pragma once

#include <optional>
#include <sdbusplus/asio/object_server.hpp>
#include <boost/asio/io_service.hpp>

class Ethernetiface
{
  public:
    Ethernetiface(const std::string& name ,const std::string& linkstatus , const std::string& ipv4addr ,const std::string& MTUsize , const std::string& ipv6addr ,
              sdbusplus::asio::object_server& objectServer,
              std::shared_ptr<sdbusplus::asio::connection>& conn,
              boost::asio::io_service& io);
    ~Ethernetiface();

  private:
    sdbusplus::asio::object_server& objServer;
    std::shared_ptr<sdbusplus::asio::dbus_interface> ethInterface;
    std::shared_ptr<sdbusplus::asio::dbus_interface> statusInterface;
    std::shared_ptr<sdbusplus::asio::dbus_interface> association;

    std::string name;
};

max_stars_repo_name: Eyerunmyden/HWMgmt-MegaRAC-OpenEdition

max_issues_repo_name: Eyerunmyden/HWMgmt-MegaRAC-OpenEdition

max_forks_repo_name: Eyerunmyden/HWMgmt-MegaRAC-OpenEdition


text:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
class printer
{
public:
	printer(boost::asio::io_service& io)
            : strand_(io),
            timer1_(io, boost::posix_time::seconds(1)),
            timer2_(io, boost::posix_time::seconds(1)),
            count_(0)
    {
        timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this)));
        timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this)));
    }
    ~printer()
    {
        std::cout << "Final count is " << count_ << std::endl;
    }
    void print1()
    {
        if (count_ < 10)
        {
            std::cout << "Timer 1: " << count_ << std::endl;
            ++count_;
            timer1_.expires_at(timer1_.expires_at() + boost::posix_time::seconds(1));
            timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this)));
        }
    }
    void print2()
    {
        if (count_ < 10)
        {
            std::cout << "Timer 2: " << count_ << std::endl;
            ++count_;
            timer2_.expires_at(timer2_.expires_at() + boost::posix_time::seconds(1));
            timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this)));
        }
    }
private:
    boost::asio::strand strand_;
    boost::asio::deadline_timer timer1_;
    boost::asio::deadline_timer timer2_;
    int count_;
};

void ThreadFun()
{
    boost::asio::io_service io;
    printer p(io);
    io.run();
    while(1)
    {
        std::cout << "Timer test" << std::endl;
        sleep(1);
    };

}

int main()
{
    // boost::asio::io_service io;
    // printer p(io);
    // boost::thread t(boost::bind(&boost::asio::io_service::run, &io));
    // io.run();
    boost::thread t(ThreadFun);
    sleep(3);
    std::cout << "Timer test xxxxxxxxx" << std::endl;
    t.join();
    return 0;
}


text:
//******************************************************************************
// RCF - Remote Call Framework
//
// Copyright (c) 2005 - 2013, Delta V Software. All rights reserved.
// http://www.deltavsoft.com
//
// RCF is distributed under dual licenses - closed source or GPL.
// Consult your particular license for conditions of use.
//
// If you have not purchased a commercial license, you are using RCF
// under GPL terms.
//
// Version: 2.0
// Contact: support <at> deltavsoft.com
//
//******************************************************************************

#ifndef INCLUDE_RCF_TEST_PROGRAMTIMELIMIT_HPP
#define INCLUDE_RCF_TEST_PROGRAMTIMELIMIT_HPP

#include <iostream>
#include <boost/bind.hpp>
#include <boost/config.hpp>

#include <RCF/ThreadLibrary.hpp>
#include <RCF/ThreadPool.hpp>
#include <RCF/util/CommandLine.hpp>

class ProgramTimeLimit
{
public:
    ProgramTimeLimit(unsigned int timeLimitS)
    {
        mStartTimeMs = RCF::getCurrentTimeMs();
        mTimeLimitMs = timeLimitS*1000;
        mStopFlag = false;
        if (timeLimitS)
        {
            mThreadPtr.reset( new RCF::Thread( boost::bind(&ProgramTimeLimit::poll, this)));
        }
    }

    ~ProgramTimeLimit()
    {
        if (mThreadPtr)
        {
            {
                RCF::Lock lock(mStopMutex);
                mStopFlag = true;
                mStopCondition.notify_all(lock);
            }
            mThreadPtr->join();
        }
    }

private:

    void poll()
    {
        // Set our thread name.
        RCF::setWin32ThreadName("RCF Program Time Limit");

        while (true)
        {
            unsigned int pollIntervalMs = 1000;
            RCF::Lock lock(mStopMutex);
            mStopCondition.timed_wait(lock, pollIntervalMs);
            if (mStopFlag)
            {
                break;
            }
            else
            {
                unsigned int currentTimeMs = RCF::getCurrentTimeMs();
                if (currentTimeMs - mStartTimeMs > mTimeLimitMs)
                {
                    std::cout
                        << "Time limit expired (" << mTimeLimitMs/1000 << " (s) ). Killing this test."
                        << std::endl;

#if defined(_MSC_VER)

                    // By simulating an access violation , we will trigger the
                    // creation  of a minidump, which will aid postmortem analysis.

                    int * pn = 0;
                    *pn = 1;

#elif defined(BOOST_WINDOWS)

                    TerminateProcess(GetCurrentProcess(), 1);

#else

                    abort();

#endif
                }
            }
        }
    }

    unsigned int mStartTimeMs;
    unsigned int mTimeLimitMs;
    RCF::ThreadPtr mThreadPtr;
    bool mStopFlag;

    RCF::Mutex mStopMutex;
    RCF::Condition mStopCondition;
};

ProgramTimeLimit * gpProgramTimeLimit = NULL;

#endif // ! INCLUDE_RCF_TEST_PROGRAMTIMELIMIT_HPP

max_stars_repo_name: ASMlover/study

max_issues_repo_name: ASMlover/study

max_forks_repo_name: ASMlover/study


text:
// -----------------------------------------------------------------------
// RTToolbox - DKFZ radiotherapy quantitative evaluation library
//
// Copyright (c) German Cancer Research Center (DKFZ),
// Software development for Integrated Diagnostics and Therapy (SIDT).
// ALL RIGHTS RESERVED.
// See rttbCopyright.txt or
// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE.  See the above copyright notices for more information.
//
//------------------------------------------------------------------------

#include "rttbDoseStatisticsXMLWriter.h"

#include <cmath>
#include <ostream>

#include <boost/property_tree/xml_parser.hpp>

#include "rttbInvalidParameterException.h"
#include "rttbNullPointerException.h"
#include "rttbVolumeToDoseMeasureCollection.h"
#include "rttbDoseToVolumeMeasureCollection.h"

namespace rttb
{
	namespace io
	{
		namespace other
		{
			static const std::string xmlattrXTag = "<xmlattr>.x";
			static const std::string xmlattrNameTag = "<xmlattr>.name";
			static const std::string statisticsTag = "statistics.results";
			static const std::string propertyTag = "property";
			static const std::string columnSeparator = "@";

			boost::property_tree::ptree DoseStatisticsXMLWriter::writeDoseStatistics(DoseStatisticsPtr aDoseStatistics)
			{
				using boost::property_tree::ptree;
				ptree pt;

                if (aDoseStatistics == nullptr){
                    throw core::NullPointerException("dose statistics is nullptr!");
                }

				ptree numberOfVoxelsNode = createNodeWithNameAttribute(aDoseStatistics->getNumberOfVoxels(),
				                           "numberOfVoxels");
				pt.add_child(statisticsTag + "." + propertyTag, numberOfVoxelsNode);

				ptree volumeNode = createNodeWithNameAttribute(static_cast<float>(aDoseStatistics->getVolume()),
				                   "volume");
				pt.add_child(statisticsTag + "." + propertyTag, volumeNode);

				ptree referenceNode = createNodeWithNameAttribute(static_cast<float>(aDoseStatistics->getReferenceDose()),
					"referenceDose");
				pt.add_child(statisticsTag + "." + propertyTag, referenceNode);

				ptree minimumNode = createNodeWithNameAttribute(static_cast<float>(aDoseStatistics->getMinimum()),
				                    "minimum");

				auto minimumPositions = aDoseStatistics->getMinimumVoxelPositions();
				auto pairItMin = minimumPositions->begin();
				int count = 0;

				for (; pairItMin != minimumPositions->end() && count < 100; ++pairItMin) //output max. 100 minimum
				{
					VoxelGridID voxelID = pairItMin->second;
					ptree voxelMinPositions;
					voxelMinPositions.add("voxelGridID", voxelID);
					minimumNode.add_child("voxel", voxelMinPositions);
					count++;
				}

				pt.add_child(statisticsTag + "." + propertyTag, minimumNode);

				ptree maximumNode = createNodeWithNameAttribute(static_cast<float>(aDoseStatistics->getMaximum()),
				                    "maximum");

				auto maximumPositions = aDoseStatistics->getMaximumVoxelPositions();
				auto pairItMax = maximumPositions->begin();
				count = 0;

				for (; pairItMax != maximumPositions->end() && count < 100; ++pairItMax) //output max. 100 maximum
				{
					VoxelGridID voxelID = pairItMax->second;
					ptree voxelMaxPositions;
					voxelMaxPositions.add("voxelGridID", voxelID);
					maximumNode.add_child("voxel", voxelMaxPositions);

					count++;
				}

				pt.add_child(statisticsTag + "." + propertyTag, maximumNode);

				ptree meanNode = createNodeWithNameAttribute(static_cast<float>(aDoseStatistics->getMean()),
				                 "mean");
				pt.add_child(statisticsTag + "." + propertyTag, meanNode);

				ptree sdNode = createNodeWithNameAttribute(static_cast<float>(aDoseStatistics->getStdDeviation()),
				               "standardDeviation");
				pt.add_child(statisticsTag + "." + propertyTag, sdNode);

				ptree varianceNode = createNodeWithNameAttribute(static_cast<float>(aDoseStatistics->getVariance()),
				                     "variance");
				pt.add_child(statisticsTag + "." + propertyTag, varianceNode);

				double absoluteVolume = aDoseStatistics->getVolume();
				double referenceDose = aDoseStatistics->getReferenceDose();
				rttb::algorithms::DoseToVolumeMeasureCollection::DoseToVolumeFunctionType AllVx = aDoseStatistics->getVx().getAllValues();
				rttb::algorithms::VolumeToDoseMeasureCollection::VolumeToDoseFunctionType AllDx = aDoseStatistics->getDx().getAllValues();
				rttb::algorithms::VolumeToDoseMeasureCollection::VolumeToDoseFunctionType AllMOHx = aDoseStatistics->getMOHx().getAllValues();
				rttb::algorithms::VolumeToDoseMeasureCollection::VolumeToDoseFunctionType AllMOCx = aDoseStatistics->getMOCx().getAllValues();
				rttb::algorithms::VolumeToDoseMeasureCollection::VolumeToDoseFunctionType AllMaxOHx =
				    aDoseStatistics->getMaxOHx().getAllValues();
				rttb::algorithms::VolumeToDoseMeasureCollection::VolumeToDoseFunctionType AllMinOCx =
				    aDoseStatistics->getMinOCx().getAllValues();

				rttb::algorithms::DoseToVolumeMeasureCollection::DoseToVolumeFunctionType::iterator vxIt;
				rttb::algorithms::VolumeToDoseMeasureCollection::VolumeToDoseFunctionType::iterator it;

				for (it = AllDx.begin(); it != AllDx.end(); ++it)
				{
					ptree DxNode = createNodeWithNameAndXAttribute(static_cast<float>(it->second), "Dx",
					               std::lround(convertToPercent(it->first, absoluteVolume)));
					pt.add_child(statisticsTag + "." + propertyTag, DxNode);
				}

				for (vxIt = AllVx.begin(); vxIt != AllVx.end(); ++vxIt)
				{
					ptree VxNode = createNodeWithNameAndXAttribute(static_cast<float>(vxIt->second), "Vx",
                        std::lround(convertToPercent(vxIt->first, referenceDose)));
					pt.add_child(statisticsTag + "." + propertyTag, VxNode);
				}

				for (it = AllMOHx.begin(); it != AllMOHx.end(); ++it)
				{
					ptree mohxNode = createNodeWithNameAndXAttribute(static_cast<float>(it->second), "MOHx",
                        std::lround(convertToPercent(it->first, absoluteVolume)));
					pt.add_child(statisticsTag + "." + propertyTag, mohxNode);
				}

				for (it = AllMOCx.begin(); it != AllMOCx.end(); ++it)
				{
					ptree mocxNode = createNodeWithNameAndXAttribute(static_cast<float>(it->second), "MOCx",
                        std::lround(convertToPercent(it->first, absoluteVolume)));
					pt.add_child(statisticsTag + "." + propertyTag, mocxNode);
				}

				for (it = AllMaxOHx.begin(); it != AllMaxOHx.end(); ++it)
				{
					ptree maxOhxNode = createNodeWithNameAndXAttribute(static_cast<float>(it->second), "MaxOHx",
                        std::lround(convertToPercent(it->first, absoluteVolume)));
					pt.add_child(statisticsTag + "." + propertyTag, maxOhxNode);
				}

				for (it = AllMinOCx.begin(); it != AllMinOCx.end(); ++it)
				{
					ptree minOCxNode = createNodeWithNameAndXAttribute(static_cast<float>(it->second), "MinOCx",
                        std::lround(convertToPercent(it->first, absoluteVolume)));
					pt.add_child(statisticsTag + "." + propertyTag, minOCxNode);
				}

				return pt;

			}

			void DoseStatisticsXMLWriter::writeDoseStatistics(DoseStatisticsPtr aDoseStatistics, FileNameString aFileName)
			{
				boost::property_tree::ptree pt = writeDoseStatistics(aDoseStatistics);

				try
				{
					boost::property_tree::xml_parser::write_xml(aFileName, pt, std::locale(),
					        boost::property_tree::xml_writer_make_settings<std::string>('\t', 1));
				}
				catch (boost::property_tree::xml_parser_error& /*e*/)
				{
					throw core::InvalidParameterException("Write xml failed: xml_parser_error!");
				}
			}

			XMLString DoseStatisticsXMLWriter::writerDoseStatisticsToString(DoseStatisticsPtr aDoseStatistics)
			{
				boost::property_tree::ptree pt = writeDoseStatistics(aDoseStatistics);
				std::stringstream sstr;

				try
				{
					boost::property_tree::xml_parser::write_xml(sstr, pt,
					        boost::property_tree::xml_writer_make_settings<std::string>('\t',
					                1));
				}
				catch (boost::property_tree::xml_parser_error& /*e*/)
				{
					throw core::InvalidParameterException("Write xml to string failed: xml_parser_error!");
				}

				return sstr.str();
			}

			StatisticsString DoseStatisticsXMLWriter::writerDoseStatisticsToTableString(DoseStatisticsPtr aDoseStatistics)
			{
                if (aDoseStatistics == nullptr){
                    throw core::NullPointerException("dose statistics is nullptr!");
                }
				std::stringstream sstr;

				sstr << static_cast<float>(aDoseStatistics->getVolume() * 1000) << columnSeparator; // cm3 to mm3
				sstr << static_cast<float>(aDoseStatistics->getMaximum()) << columnSeparator;
				sstr << static_cast<float>(aDoseStatistics->getMinimum()) << columnSeparator;

				sstr << static_cast<float>(aDoseStatistics->getMean()) << columnSeparator;
				sstr << static_cast<float>(aDoseStatistics->getStdDeviation()) << columnSeparator;
				sstr << static_cast<float>(aDoseStatistics->getVariance()) << columnSeparator;

				rttb::algorithms::DoseToVolumeMeasureCollection::DoseToVolumeFunctionType AllVx = aDoseStatistics->getVx().getAllValues();
				rttb::algorithms::VolumeToDoseMeasureCollection::VolumeToDoseFunctionType AllDx = aDoseStatistics->getDx().getAllValues();
				rttb::algorithms::VolumeToDoseMeasureCollection::VolumeToDoseFunctionType AllMOHx = aDoseStatistics->getMOHx().getAllValues();
				rttb::algorithms::VolumeToDoseMeasureCollection::VolumeToDoseFunctionType AllMOCx = aDoseStatistics->getMOCx().getAllValues();
				rttb::algorithms::VolumeToDoseMeasureCollection::VolumeToDoseFunctionType AllMaxOHx =
					aDoseStatistics->getMaxOHx().getAllValues();
				rttb::algorithms::VolumeToDoseMeasureCollection::VolumeToDoseFunctionType AllMinOCx =
					aDoseStatistics->getMinOCx().getAllValues();

				rttb::algorithms::DoseToVolumeMeasureCollection::DoseToVolumeFunctionType::iterator vxIt;
				rttb::algorithms::VolumeToDoseMeasureCollection::VolumeToDoseFunctionType::iterator it;

				for (it = AllDx.begin(); it != AllDx.end(); ++it)
				{
					sstr << static_cast<float>((*it).second) << columnSeparator;
				}

				for (vxIt = AllVx.begin(); vxIt != AllVx.end(); ++vxIt)
				{
					// *1000 because of conversion cm3 to mm3
					sstr << static_cast<float>((*vxIt).second * 1000) << columnSeparator;
				}

				for (it = AllMOHx.begin(); it != AllMOHx.end(); ++it)
				{
					sstr << static_cast<float>((*it).second) << columnSeparator;
				}

				for (it = AllMOCx.begin(); it != AllMOCx.end(); ++it)
				{
					sstr << static_cast<float>((*it).second) << columnSeparator;
				}

				for (it = AllMaxOHx.begin(); it != AllMaxOHx.end(); ++it)
				{
					sstr << static_cast<float>((*it).second) << columnSeparator;
				}

				for (it = AllMinOCx.begin(); it != AllMinOCx.end(); ++it)
				{
					sstr << static_cast<float>((*it).second) << columnSeparator;
				}

				return sstr.str();

			}

			boost::property_tree::ptree DoseStatisticsXMLWriter::createNodeWithNameAttribute(DoseTypeGy doseValue,
			        const std::string& attributeName)
			{
				boost::property_tree::ptree node;
				node.put("", doseValue);
				node.put(xmlattrNameTag, attributeName);
				return node;
			}

			boost::property_tree::ptree DoseStatisticsXMLWriter::createNodeWithNameAndXAttribute(DoseTypeGy doseValue,
			        const std::string& attributeName,
			        int xValue)
			{
				boost::property_tree::ptree node;
				node.put("", doseValue);
				node.put(xmlattrNameTag, attributeName);
				node.put(xmlattrXTag, xValue);
				return node;
			}

            double DoseStatisticsXMLWriter::convertToPercent(double value, double maximum)
            {
                return (value / maximum) * 100;
            }

		}//end namespace other
	}//end namespace io
}//end namespace rttb

max_stars_repo_name: MIC-DKFZ/RTTB

max_issues_repo_name: MIC-DKFZ/RTTB

max_forks_repo_name: MIC-DKFZ/RTTB