#define BOOST_TEST_MAIN
#include <boost/test/included/unit_test.hpp>
#include "bayesian/graph.hpp"

BOOST_AUTO_TEST_CASE( graph_trace_liner )
{
    bn::graph_t graph;
    auto vertex_a = graph.add_vertex();
    auto vertex_b = graph.add_vertex();
    auto vertex_c = graph.add_vertex();
    auto vertex_d = graph.add_vertex();
    auto edge_ab = graph.add_edge(vertex_a, vertex_b);
    auto edge_bc = graph.add_edge(vertex_b, vertex_c);
    auto edge_cd = graph.add_edge(vertex_c, vertex_d);

    BOOST_CHECK(graph.is_able_trace(vertex_a, vertex_d) == true);
    BOOST_CHECK(graph.is_able_trace(vertex_b, vertex_d) == true);
    BOOST_CHECK(graph.is_able_trace(vertex_c, vertex_d) == true);
    BOOST_CHECK(graph.is_able_trace(vertex_b, vertex_a) == false);
    BOOST_CHECK(graph.is_able_trace(vertex_c, vertex_a) == false);
    BOOST_CHECK(graph.is_able_trace(vertex_d, vertex_a) == false);
}

BOOST_AUTO_TEST_CASE( graph_trace_zigzag )
{
    bn::graph_t graph;
    auto vertex_a = graph.add_vertex();
    auto vertex_b = graph.add_vertex();
    auto vertex_c = graph.add_vertex();
    auto vertex_d = graph.add_vertex();
    auto edge_ab = graph.add_edge(vertex_a, vertex_b);
    auto edge_ac = graph.add_edge(vertex_a, vertex_c);
    auto edge_dc = graph.add_edge(vertex_d, vertex_c);

    BOOST_CHECK(graph.is_able_trace(vertex_a, vertex_d) == false);
    BOOST_CHECK(graph.is_able_trace(vertex_b, vertex_d) == false);
    BOOST_CHECK(graph.is_able_trace(vertex_d, vertex_b) == false);
}

BOOST_AUTO_TEST_CASE( graph_dag )
{
    bn::graph_t graph;
    auto vertex_a = graph.add_vertex();
    auto vertex_b = graph.add_vertex();
    auto vertex_c = graph.add_vertex();
    auto vertex_d = graph.add_vertex();

    // a -> b -> c -> d -> a
    BOOST_CHECK(graph.add_edge(vertex_a, vertex_b) != nullptr);
    BOOST_CHECK(graph.add_edge(vertex_b, vertex_c) != nullptr);
    BOOST_CHECK(graph.add_edge(vertex_c, vertex_d) != nullptr);
    BOOST_CHECK(graph.add_edge(vertex_d, vertex_a) == nullptr); // ERROR: nullptr
}


// Boost.Geometry
// Unit Test

// Copyright (c) 2021, Oracle and/or its affiliates.

// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle

// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html

#ifndef BOOST_GEOMETRY_TEST_ALGORITHMS_CLOSEST_POINTS_COMMON_HPP
#define BOOST_GEOMETRY_TEST_ALGORITHMS_CLOSEST_POINTS_COMMON_HPP

#define BOOST_GEOMETRY_TEST_DEBUG_CLOSEST_POINTS

#include <boost/geometry/core/tags.hpp>

#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/algorithms/closest_points.hpp>
#include <boost/geometry/strategies/strategies.hpp>

#include <boost/test/included/unit_test.hpp>

#include <from_wkt.hpp>

namespace bg = boost::geometry;

//===========================================================================
// point types

using car_point = bg::model::point<double, 2, bg::cs::cartesian>;

using sph_point = bg::model::point
        <
            double, 2,
            bg::cs::spherical_equatorial<bg::degree>
        >;

using geo_point = bg::model::point
        <
            double, 2,
            bg::cs::geographic<bg::degree>
        >;

//===========================================================================

using cartesian = bg::strategies::closest_points::cartesian<double>;

//using spherical = bg::strategy::closest_points::spherical<double>;

//using = bg::strategy::closest_points::geographic
//                      <bg::strategy::andoyer> andoyer;
//using = bg::strategy::closest_points::geographic
//                      <bg::strategy::thomas> thomas;
//using = bg::strategy::closest_points::geographic
//                      <bg::strategy::vincenty> vincenty;

//===========================================================================

template <typename Segment>
static inline Segment swap(Segment const& s)
{
    Segment swapped;

    bg::set<0, 0>(swapped, bg::get<1, 0>(s));
    bg::set<0, 1>(swapped, bg::get<1, 1>(s));
    bg::set<1, 0>(swapped, bg::get<0, 0>(s));
    bg::set<1, 1>(swapped, bg::get<0, 1>(s));

    return swapped;
}

template <int i, int j, typename Segment>
void compare_result_with_expected(Segment const& expected_resulting_segment,
                                  Segment const& resulting_segment)
{
    double expected = bg::get<i, j>(expected_resulting_segment);
    double resulting = bg::get<i, j>(resulting_segment);
    BOOST_CHECK_CLOSE(expected, resulting, 0.01);
}

template <typename Segment>
void compare_result_with_expected(Segment const& exp_resulting_segment,
                                  Segment const& resulting_segment)
{
    compare_result_with_expected<0,0>(exp_resulting_segment, resulting_segment);
    compare_result_with_expected<1,0>(exp_resulting_segment, resulting_segment);
    compare_result_with_expected<0,1>(exp_resulting_segment, resulting_segment);
    compare_result_with_expected<1,1>(exp_resulting_segment, resulting_segment);
}

//==============================================================================

template
<
    typename Geometry1,
    typename Geometry2,
    typename Segment,
    typename Strategy
>
void compute_result(Geometry1 const& geometry1,
                    Geometry2 const& geometry2,
                    Segment const& exp_resulting_segment,
                    Strategy const& strategy,
                    bool default_strategy)
{
#ifdef BOOST_GEOMETRY_TEST_DEBUG_CLOSEST_POINTS
    //std::cout << "CS: " << typeid(typename bg::cs_tag<Geometry1>::type).name()
    //          << std::endl;
    std::cout << bg::wkt(geometry1) << " --- " << bg::wkt(geometry2)
              << std::endl;
#endif
    Segment resulting_segment;
    if (default_strategy)
    {
        bg::closest_points(geometry1, geometry2, resulting_segment);
    }
    else
    {
        bg::closest_points(geometry1, geometry2, resulting_segment, strategy);
    }
#ifdef BOOST_GEOMETRY_TEST_DEBUG_CLOSEST_POINTS
    std::cout << "closest_points : " << bg::wkt(resulting_segment)
              << std::endl << std::endl;
#endif
    compare_result_with_expected(exp_resulting_segment, resulting_segment);
}

template
<
    typename Geometry1,
    typename Geometry2,
    typename Segment,
    typename Strategy
>
void compute_result(Geometry1 const& geometry1,
                    Geometry2 const& geometry2,
                    Segment const& exp_resulting_segment,
                    Strategy const& strategy,
                    bool swap_geometries,
                    bool default_strategy)
{
    compute_result(geometry1, geometry2, exp_resulting_segment, strategy,
                   default_strategy);
    if (swap_geometries)
    {
        // swap input geometries and expected segment
        compute_result(geometry2, geometry1,
                       swap(exp_resulting_segment), strategy,
                       default_strategy);
    }
}

//==============================================================================

template <typename CS_tag>
struct test_closest_points_dispatch
{};

template <>
struct test_closest_points_dispatch<bg::cartesian_tag>
{
    template
    <
        typename OutputSegment,
        typename Geometry1,
        typename Geometry2,
        typename Strategy
    >
    void static apply(Geometry1 const& geometry1,
                      Geometry2 const& geometry2,
                      std::string const& expected_resulting_segment_car,
                      std::string const& expected_resulting_segment_sph,
                      std::string const& expected_resulting_segment_geo,
                      Strategy const& strategy,
                      bool swap_geometries,
                      bool default_strategy)
    {
        boost::ignore_unused(expected_resulting_segment_sph);
        boost::ignore_unused(expected_resulting_segment_geo);

        OutputSegment expected_resulting_segment;
        bg::read_wkt(expected_resulting_segment_car,
                     expected_resulting_segment);
        compute_result(geometry1,
                       geometry2,
                       expected_resulting_segment,
                       strategy,
                       swap_geometries,
                       default_strategy);
    }
};

template <>
struct test_closest_points_dispatch<bg::spherical_equatorial_tag>
{
    template
    <
        typename OutputSegment,
        typename Geometry1,
        typename Geometry2,
        typename Strategy
    >
    void static apply(Geometry1 const& geometry1,
                      Geometry2 const& geometry2,
                      std::string const& expected_resulting_segment_car,
                      std::string const& expected_resulting_segment_sph,
                      std::string const& expected_resulting_segment_geo,
                      Strategy const& strategy,
                      bool swap_geometries,
                      bool default_strategy)
    {
        boost::ignore_unused(expected_resulting_segment_car);
        boost::ignore_unused(expected_resulting_segment_geo);

        OutputSegment expected_resulting_segment;
        bg::read_wkt(expected_resulting_segment_sph,
                     expected_resulting_segment);
        compute_result(geometry1,
                       geometry2,
                       expected_resulting_segment,
                       strategy,
                       swap_geometries,
                       default_strategy);
    }
};

template <>
struct test_closest_points_dispatch<bg::geographic_tag>
{
    template
    <
        typename OutputSegment,
        typename Geometry1,
        typename Geometry2,
        typename Strategy
    >
    void static apply(Geometry1 const& geometry1,
                      Geometry2 const& geometry2,
                      std::string const& expected_resulting_segment_car,
                      std::string const& expected_resulting_segment_sph,
                      std::string const& expected_resulting_segment_geo,
                      Strategy const& strategy,
                      bool swap_geometries,
                      bool default_strategy)
    {
        boost::ignore_unused(expected_resulting_segment_car);
        boost::ignore_unused(expected_resulting_segment_sph);

        OutputSegment expected_resulting_segment;
        bg::read_wkt(expected_resulting_segment_geo,
                     expected_resulting_segment);
        compute_result(geometry1,
                       geometry2,
                       expected_resulting_segment,
                       strategy,
                       swap_geometries,
                       default_strategy);
    }
};

//==============================================================================

template <typename Geometry1, typename Geometry2, typename OutputSegment>
struct test_geometry
{
    template <typename Strategy>
    inline static void apply(std::string const& wkt1,
                             std::string const& wkt2,
                             std::string const& expected_resulting_segment_car,
                             std::string const& expected_resulting_segment_sph,
                             std::string const& expected_resulting_segment_geo,
                             Strategy const& strategy,
                             bool swap_geometries = true,
                             bool default_strategy = false)
    {
        using CS_tag = typename bg::cs_tag<Geometry1>::type;

        Geometry1 geometry1;
        bg::read_wkt(wkt1, geometry1);
        Geometry2 geometry2;
        bg::read_wkt(wkt2, geometry2);

        test_closest_points_dispatch<CS_tag>
               ::template apply<OutputSegment>(geometry1,
                                               geometry2,
                                               expected_resulting_segment_car,
                                               expected_resulting_segment_sph,
                                               expected_resulting_segment_geo,
                                               strategy,
                                               swap_geometries,
                                               default_strategy);
    }

    template <typename Strategy>
    inline static void apply(std::string const& wkt1,
                             std::string const& wkt2,
                             std::string const& expected_resulting_segment_car,
                             std::string const& expected_resulting_segment_sph_geo,
                             Strategy const& strategy,
                             bool swap_geometries = true,
                             bool default_strategy = false)
    {
        apply(wkt1,
              wkt2,
              expected_resulting_segment_car,
              expected_resulting_segment_sph_geo,
              expected_resulting_segment_sph_geo,
              strategy,
              swap_geometries,
              default_strategy);
    }

    template <typename Strategy>
    inline static void apply(std::string const& wkt1,
                             std::string const& wkt2,
                             std::string const& expected_resulting_segment,
                             Strategy const& strategy,
                             bool swap_geometries = true,
                             bool default_strategy = false)
    {
        apply(wkt1,
              wkt2,
              expected_resulting_segment,
              expected_resulting_segment,
              expected_resulting_segment,
              strategy,
              swap_geometries,
              default_strategy);
    }
};

#endif // BOOST_GEOMETRY_TEST_ALGORITHMS_CLOSEST_POINTS_COMMON_HPP


#pragma once

#include <Eigen/Dense>
#include "base/array_buffer.hpp"
#include "fft/shift.hpp"

/**
 * @brief fold operation,
 *
 *
 * @param[out] dst (resized)
 *  dim == 0: width x m matrix
 *  dim == 1: n x width matrix
 * @param[in]  src   Fourier coefficients of f(x), matrix of size n x m
 * @param[in]  width
 * @param[in]  dim   dimension along which to fold
 *
 */
template <typename DERIVED1, typename DERIVED2>
void
fold(Eigen::DenseBase<DERIVED1> &dst,
     const Eigen::DenseBase<DERIVED2> &src,
     unsigned int width,
     int dim)
{
  const int ncols = src.cols();
  const int nrows = src.rows();

  typedef typename DERIVED1::Scalar numeric_t;
  typedef Eigen::Array<numeric_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> local_array_t;

  thread_local static ArrayBuffer<> buf;

  if (dim == 0) {
    assert(nrows % width == 0);
    if ((src.rows() / width) % 2 == 0) {
      const int s = nrows / width;
      auto tmp = buf.get<local_array_t>(width, ncols);
      tmp.setZero();
      for (int i = 0; i < (int)width; ++i) {
        for (int k = 0; k < s; ++k) {
          tmp.row(i) += src.row(i + k * width);
        }
      }
      // apply fftshift along dim
      fftshift(dst, tmp, dim);
    } else {
      const int s = nrows / width;
      assert(dst.rows() == width);
      assert(dst.cols() == ncols);
      dst.setZero();
      for (int i = 0; i < (int)width; ++i) {
        for (int k = 0; k < s; ++k) {
          dst.row(i) += src.row(i + k * width);
        }
      }
    }
  } else if (dim == 1) {
    assert(ncols % width == 0);
    if ((src.cols() / width) % 2 == 0) {
      const int s = ncols / width;
      auto tmp = buf.get<local_array_t>(nrows, width);
      tmp.setZero();
      for (int j = 0; j < (int)width; ++j) {
        for (int k = 0; k < s; ++k) {
          tmp.col(j) += src.col(j + k * width);
        }
      }
      // apply fftshift along dim
      fftshift(dst, tmp, dim);
    } else {
      const int s = ncols / width;
      assert(dst.rows() == nrows);
      assert(dst.cols() == width);
      dst.setZero();
      for (int j = 0; j < (int)width; ++j) {
        for (int k = 0; k < s; ++k) {
          dst.col(j) += src.col(j + k * width);
        }
      }
    }
  }
}

/**
 * @brief unfold operation.
 *
 * unfold scales src by 1/k where k := width/size(src,dim) and repeats it
 * along dimension dim such that size(src_unfolded, dim) = width.
 * If dim == 0, the rows of src_unfolded are shifted such that the middle row of
 * src
 * becomes the middle row of src_unfolded, where the middle is determined
 * according to the centered-zero-frequency convention. In this case, this
 * function is mathematically equivalent to
 *   temp = zeros(width, size(src,2));
 *   temp(1:width/size(src,1):end, :) = ift(src);
 *   dst = ft(temp);
 * Likewise properties hold for dim == 1.
 *
 *
 * @param[out] dst  (resized)
 *   dim == 0: dst = width x m
 *   dim == 1: dst = n x width
 * @param[in] src of size n x m
 * @param[in] width
 * @param[in] dim
 * @param[in] scale
 */
template <typename DERIVED1, typename DERIVED2>
void
unfold(Eigen::DenseBase<DERIVED1> &dst,
       Eigen::DenseBase<DERIVED2> &src,
       unsigned int width,
       int dim,
       bool scale = false)
{
  typedef typename DERIVED1::Scalar numeric_t;
  typedef Eigen::Array<numeric_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> local_array_t;

  thread_local static ArrayBuffer<> buf1;
  thread_local static ArrayBuffer<> buf2;

  assert(dim == 0 || dim == 1);
  const int nrows = src.rows();
  const int ncols = src.cols();

  if (dim == 0) {
    const int s = width / nrows;
    assert(s > 0);
    if ((width / nrows) % 2 == 0) {
      auto tmp = buf1.get<local_array_t>(src.rows(), src.cols());
      ifftshift(tmp, src, 0);
      auto tmp2 = buf2.get<local_array_t>(width, src.cols());
      tmp2 = tmp.replicate(s, 1);
      assert(dst.rows() == width);
      fftshift(dst, tmp2, 0);
    } else {
      dst.derived() = src.replicate(s, 1);
    }
    if (scale) dst *= src.rows() / double(width);
  } else if (dim == 1) {
    const int s = width / ncols;
    assert(s > 0);
    if (s % 2 == 0) {
      auto tmp = buf1.get<local_array_t>(src.rows(), src.cols());
      ifftshift(tmp, src, 1);
      auto tmp2 = buf2.get<local_array_t>(src.rows(), width);
      tmp2 = tmp.replicate(1, s);
      assert(dst.cols() == width);
      fftshift(dst, tmp2, 1);
    } else {
      dst = src.replicate(1, s);
    }
    if (scale) dst *= src.cols() / double(width);
  }
}


/*
 * GraphBLAS Template Library (GBTL), Version 3.0
 *
 * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and
 * Authors.
 *
 * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF
 * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE
 * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF
 * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR
 * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE
 * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
 * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,
 * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS
 * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED
 * RIGHTS.
 *
 * Released under a BSD-style license, please see LICENSE file or contact
 * permission@sei.cmu.edu for full terms.
 *
 * [DISTRIBUTION STATEMENT A] This material has been approved for public release
 * and unlimited distribution.  Please see Copyright notice for non-US
 * Government use and distribution.
 *
 * This Software includes and/or makes use of the following Third-Party Software
 * subject to its own license:
 *
 * 1. Boost Unit Test Framework
 * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html)
 * Copyright 2001 Boost software license, Gennadiy Rozental.
 *
 * DM20-0442
 */

#include <iostream>

#define GRAPHBLAS_LOGGING_LEVEL 0
#define GRAPHBLAS_BC_DEBUG 0

#include <graphblas/graphblas.hpp>
#include <algorithms/bc.hpp>

using namespace grb;
using namespace algorithms;

#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE bc_test_suite

#include <boost/test/included/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)

//****************************************************************************

static std::vector<double> br={0, 0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 6};
static std::vector<double> bc={1, 2, 3, 2, 4, 4, 2, 4, 5, 6, 7, 7};
static std::vector<double> bv(br.size(), 1);

//static Matrix<double, DirectedMatrixTag> betweenness(
//    {{0, 1, 1, 1, 0, 0, 0, 0},
//     {0, 0, 1, 0, 1, 0, 0, 0},
//     {0, 0, 0, 0, 1, 0, 0, 0},vertex_betweenness_centrality_batch_alt_trans_v2
//     {0, 0, 1, 0, 1, 0, 0, 0},
//     {0, 0, 0, 0, 0, 1, 1, 0},
//     {0, 0, 0, 0, 0, 0, 0, 1},
//     {0, 0, 0, 0, 0, 0, 0, 1},
//     {0, 0, 0, 0, 0, 0, 0, 0}});

//****************************************************************************
BOOST_AUTO_TEST_CASE(bc_test_vertex_betweenness_centrality_gilbert)
{
    IndexType const NUM_NODES = 7;
    std::vector<IndexType> row_indices = {0, 0, 1, 1, 2, 3, 3, 4, 5, 6, 6, 6};
    std::vector<IndexType> col_indices = {1, 3, 4, 6, 5, 0, 2, 5, 2, 2, 3, 4};
    std::vector<double> values(row_indices.size(), 1.);

    Matrix<double> graph(NUM_NODES, NUM_NODES);
    graph.build(row_indices.begin(), col_indices.begin(),
                      values.begin(), values.size());

    IndexArrayType seed_set={0, 1, 2, 3, 4, 5, 6};

    //std::vector<float> result = vertex_betweenness_centrality(graph);
    std::vector<float> answer = {4.0, 4.5, 2, 4.5, 2.0, 1.0, 3.0};

    {
        std::vector<double> result =
            vertex_betweenness_centrality(graph);

        BOOST_CHECK_EQUAL(result.size(), answer.size());
        for (unsigned int ix = 0; ix < result.size(); ++ix)
            BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);
    }
    {
        std::vector<double> result =
            vertex_betweenness_centrality_batch_old(graph, seed_set);

        BOOST_CHECK_EQUAL(result.size(), answer.size());
        for (unsigned int ix = 0; ix < result.size(); ++ix)
            BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);
    }
    {
        std::vector<float> result =
            vertex_betweenness_centrality_batch(graph, seed_set);

        BOOST_CHECK_EQUAL(result.size(), answer.size());
        for (unsigned int ix = 0; ix < result.size(); ++ix)
            BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);
    }
    {
        std::vector<float> result =
            vertex_betweenness_centrality_batch_alt(graph, seed_set);

        BOOST_CHECK_EQUAL(result.size(), answer.size());
        for (unsigned int ix = 0; ix < result.size(); ++ix)
            BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);
    }
    {
        std::vector<float> result =
            vertex_betweenness_centrality_batch_alt_trans(graph, seed_set);

        BOOST_CHECK_EQUAL(result.size(), answer.size());
        for (unsigned int ix = 0; ix < result.size(); ++ix)
            BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);
    }
    {
        std::vector<float> result =
            vertex_betweenness_centrality_batch_alt_trans_v2(graph, seed_set);

        BOOST_CHECK_EQUAL(result.size(), answer.size());
        for (unsigned int ix = 0; ix < result.size(); ++ix)
            BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);
    }
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(bc_test_vertex_betweenness_centrality)
{
    Matrix<double, DirectedMatrixTag> betweenness(8,8);
    betweenness.build(br.begin(), bc.begin(), bv.begin(), bv.size());
    std::vector<double> result = vertex_betweenness_centrality(betweenness);
    std::vector<double> answer = {0.0, 4.0/3, 4.0/3, 4.0/3, 12.0, 2.5, 2.5, 0.0};

    BOOST_CHECK_EQUAL(result.size(), answer.size());
    for (unsigned int ix = 0; ix < result.size(); ++ix)
        BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(bc_test_edge_betweenness_centrality_2)
{
    IndexType const NUM_NODES = 11;
    std::vector<IndexType> row_indices = {0, 0, 0, 0, 1, 1, 2, 3, 3, 4, 4, 5,
                                          5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 10};
    std::vector<IndexType> col_indices = {1, 2, 3, 4, 0, 9, 0, 0, 9, 0, 5, 4,
                                          6, 7, 5, 8, 5, 8, 6, 7, 1, 3, 10, 9};
    std::vector<double> values(row_indices.size(), 1.);

    Matrix<double> graph(NUM_NODES, NUM_NODES);
    graph.build(row_indices.begin(), col_indices.begin(),
                values.begin(), values.size());

    IndexArrayType seed_set={0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    std::vector<float> result =
        vertex_betweenness_centrality_batch_alt_trans_v2(graph, seed_set);
    std::cout << "Milcom 2016 Graph:";
    for (auto a : result)
        std::cout << " " << a;
    std::cout << std::endl;
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(bc_test_edge_betweenness_centrality)
{
    Matrix<double, DirectedMatrixTag> betweenness(8,8);
    Matrix<double, DirectedMatrixTag> result(8,8);
    //Matrix<double, DirectedMatrixTag> answer ({
    //                            {0,  6,  6,  6,  0,  0,  0,  0},
    //                            {0,  0,  1,  0, 10,  0,  0,  0},
    //                            {0,  0,  0,  0, 10,  0,  0,  0},
    //                            {0,  0,  1,  0, 10,  0,  0,  0},
    //                            {0,  0,  0,  0,  0, 14, 14,  0},
    //                            {0,  0,  0,  0,  0,  0,  0,  8},
    //                            {0,  0,  0,  0,  0,  0,  0,  8},
    //                            {0,  0,  0,  0,  0,  0,  0,  0}});

    std::vector<double> ar={0, 0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 6};
    std::vector<double> ac={1, 2, 3, 2, 4, 4, 2, 4, 5, 6, 7, 7};
    std::vector<double> av={6,  6,  6,  1, 10, 10,  1, 10, 14, 14,  8,  8};
    Matrix<double, DirectedMatrixTag> answer(8,8);
    answer.build(ar.begin(), ac.begin(), av.begin(), av.size());

    betweenness.build(br.begin(), bc.begin(), bv.begin(), bv.size());
    result = edge_betweenness_centrality(betweenness);

    BOOST_CHECK_EQUAL(result, answer);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(bc_test_vertex_betweennes_centrality_batch_old)
{
    Matrix<double, DirectedMatrixTag> betweenness(8,8);
    betweenness.build(br.begin(), bc.begin(), bv.begin(), bv.size());

    //IndexArrayType seed_set={0, 1, 2, 3, 4, 5, 6, 7};
    IndexArrayType seed_set={0};
    std::vector<double> answer = {0.0, 4.0/3, 4.0/3, 4.0/3, 3.0, 0.5, 0.5, 0.0};

    std::vector<double> result =
        vertex_betweenness_centrality_batch_old(betweenness, seed_set);

    BOOST_CHECK_EQUAL(result.size(), answer.size());
    for (unsigned int ix = 0; ix < result.size(); ++ix)
        BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);

    //==========
    IndexArrayType seed_set3={3};
    std::vector<double> answer3 = {0.0, 0.0, 0.0, 0.0, 3.0, 0.5, 0.5, 0.0};

    std::vector<double> result3 =
        vertex_betweenness_centrality_batch_old(betweenness, seed_set3);

    BOOST_CHECK_EQUAL(result3.size(), answer3.size());
    for (unsigned int ix = 0; ix < result3.size(); ++ix)
        BOOST_CHECK_CLOSE(result3[ix], answer3[ix], 0.0001);

    //==========
    IndexArrayType seed_set03={0,3};

    std::vector<double> result03 =
        vertex_betweenness_centrality_batch_old(betweenness, seed_set03);

    BOOST_CHECK_EQUAL(result03.size(), answer3.size());
    for (unsigned int ix = 0; ix < result3.size(); ++ix)
        BOOST_CHECK_CLOSE(result03[ix], answer[ix] + answer3[ix], 0.0001);

    //==========
    IndexArrayType seed_set_all={0,1,2,3,4,5,6,7};
    std::vector<double> answer_all = {0.0, 4.0/3, 4.0/3, 4.0/3, 12.0, 2.5, 2.5, 0.0};

    std::vector<double> result_all =
        vertex_betweenness_centrality_batch_old(betweenness, seed_set_all);

    BOOST_CHECK_EQUAL(result_all.size(), answer_all.size());
    for (unsigned int ix = 0; ix < result_all.size(); ++ix)
        BOOST_CHECK_CLOSE(result_all[ix], answer_all[ix], 0.0001);

}

//****************************************************************************
BOOST_AUTO_TEST_CASE(bc_test_vertex_betweennes_centrality_batch)
{
    Matrix<double, DirectedMatrixTag> betweenness(8,8);
    betweenness.build(br.begin(), bc.begin(), bv.begin(), bv.size());

    //IndexArrayType seed_set={0, 1, 2, 3, 4, 5, 6, 7};
    IndexArrayType seed_set={0};
    std::vector<float> answer = {0.0, 4.0/3, 4.0/3, 4.0/3, 3.0, 0.5, 0.5, 0.0};

    std::vector<float> result =
        vertex_betweenness_centrality_batch(betweenness, seed_set);

    BOOST_CHECK_EQUAL(result.size(), answer.size());
    for (unsigned int ix = 0; ix < result.size(); ++ix)
        BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);

    //==========
    IndexArrayType seed_set3={3};
    std::vector<float> answer3 = {0.0, 0.0, 0.0, 0.0, 3.0, 0.5, 0.5, 0.0};

    std::vector<float> result3 =
        vertex_betweenness_centrality_batch(betweenness, seed_set3);

    BOOST_CHECK_EQUAL(result3.size(), answer3.size());
    for (unsigned int ix = 0; ix < result3.size(); ++ix)
        BOOST_CHECK_CLOSE(result3[ix], answer3[ix], 0.0001);

    //==========
    IndexArrayType seed_set03={0,3};

    std::vector<float> result03 =
        vertex_betweenness_centrality_batch(betweenness, seed_set03);

    BOOST_CHECK_EQUAL(result03.size(), answer3.size());
    for (unsigned int ix = 0; ix < result3.size(); ++ix)
        BOOST_CHECK_CLOSE(result03[ix], answer[ix] + answer3[ix], 0.0001);

    //==========
    IndexArrayType seed_set_all={0,1,2,3,4,5,6,7};
    std::vector<double> answer_all = {0.0, 4.0/3, 4.0/3, 4.0/3, 12.0, 2.5, 2.5, 0.0};

    std::vector<float> result_all =
        vertex_betweenness_centrality_batch(betweenness, seed_set_all);

    BOOST_CHECK_EQUAL(result_all.size(), answer_all.size());
    for (unsigned int ix = 0; ix < result_all.size(); ++ix)
        BOOST_CHECK_CLOSE(result_all[ix], answer_all[ix], 0.0001);

}

//****************************************************************************
BOOST_AUTO_TEST_CASE(bc_test_vertex_betweennes_centrality_batch_alt)
{
    // Trying the same graph where each node has self loop.     vvvvvvvvvvvvvvv
    std::vector<double> br1={0, 0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 6,0,1,2,3,4,5,6,7};
    std::vector<double> bc1={1, 2, 3, 2, 4, 4, 2, 4, 5, 6, 7, 7,0,1,2,3,4,5,6,7};
    std::vector<double> bv1(br1.size(), 1);

    Matrix<double, DirectedMatrixTag> betweenness(8,8);
    betweenness.build(br1.begin(), bc1.begin(), bv1.begin(), bv1.size());

    //IndexArrayType seed_set={0, 1, 2, 3, 4, 5, 6, 7};
    IndexArrayType seed_set={0};
    std::vector<float> answer = {0.0, 4.0/3, 4.0/3, 4.0/3, 3.0, 0.5, 0.5, 0.0};

    std::vector<float> result =
        vertex_betweenness_centrality_batch_alt(betweenness, seed_set);

    BOOST_CHECK_EQUAL(result.size(), answer.size());
    for (unsigned int ix = 0; ix < result.size(); ++ix)
        BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);

    //==========
    IndexArrayType seed_set3={3};
    std::vector<float> answer3 = {0.0, 0.0, 0.0, 0.0, 3.0, 0.5, 0.5, 0.0};

    std::vector<float> result3 =
        vertex_betweenness_centrality_batch_alt(betweenness, seed_set3);

    BOOST_CHECK_EQUAL(result3.size(), answer3.size());
    for (unsigned int ix = 0; ix < result3.size(); ++ix)
        BOOST_CHECK_CLOSE(result3[ix], answer3[ix], 0.0001);

    //==========
    IndexArrayType seed_set03={0,3};

    std::vector<float> result03 =
        vertex_betweenness_centrality_batch_alt(betweenness, seed_set03);

    BOOST_CHECK_EQUAL(result03.size(), answer3.size());
    for (unsigned int ix = 0; ix < result3.size(); ++ix)
        BOOST_CHECK_CLOSE(result03[ix], answer[ix] + answer3[ix], 0.0001);

    //==========
    IndexArrayType seed_set_all={0,1,2,3,4,5,6,7};
    std::vector<double> answer_all = {0.0, 4.0/3, 4.0/3, 4.0/3, 12.0, 2.5, 2.5, 0.0};

    std::vector<float> result_all =
        vertex_betweenness_centrality_batch_alt(betweenness, seed_set_all);

    BOOST_CHECK_EQUAL(result_all.size(), answer_all.size());
    for (unsigned int ix = 0; ix < result_all.size(); ++ix)
        BOOST_CHECK_CLOSE(result_all[ix], answer_all[ix], 0.0001);

}

//****************************************************************************
//BOOST_AUTO_TEST_CASE(bc_test_vertex_betweennes_centrality_batch_alt_trans)
BOOST_AUTO_TEST_CASE(bc_batch_alt_trans)
{
    //std::cout << "======================= BEGIN0 ==========================\n";
    Matrix<double, DirectedMatrixTag> betweenness(8,8);
    betweenness.build(br.begin(), bc.begin(), bv.begin(), bv.size());

    //IndexArrayType seed_set={0, 1, 2, 3, 4, 5, 6, 7};
    IndexArrayType seed_set={0};
    std::vector<float> answer = {0.0, 4.0/3, 4.0/3, 4.0/3, 3.0, 0.5, 0.5, 0.0};

    std::vector<float> result =
        vertex_betweenness_centrality_batch_alt_trans(betweenness, seed_set);

    BOOST_CHECK_EQUAL(result.size(), answer.size());
    for (unsigned int ix = 0; ix < result.size(); ++ix)
        BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);

    //==========
    //std::cout << "======================= BEGIN3 ==========================\n";
    IndexArrayType seed_set3={3};
    std::vector<float> answer3 = {0.0, 0.0, 0.0, 0.0, 3.0, 0.5, 0.5, 0.0};

    std::vector<float> result3 =
        vertex_betweenness_centrality_batch_alt_trans(betweenness, seed_set3);

    BOOST_CHECK_EQUAL(result3.size(), answer3.size());
    for (unsigned int ix = 0; ix < result3.size(); ++ix)
        BOOST_CHECK_CLOSE(result3[ix], answer3[ix], 0.0001);

    //==========
    //std::cout << "======================= BEGIN0,3 ==========================\n";
    IndexArrayType seed_set03={0,3};

    std::vector<float> result03 =
        vertex_betweenness_centrality_batch_alt_trans(betweenness, seed_set03);

    BOOST_CHECK_EQUAL(result03.size(), answer3.size());
    for (unsigned int ix = 0; ix < result3.size(); ++ix)
        BOOST_CHECK_CLOSE(result03[ix], answer[ix] + answer3[ix], 0.0001);

    //==========
    //std::cout << "======================= BEGIN0-7 ==========================\n";
    IndexArrayType seed_set_all={0,1,2,3,4,5,6,7};
    std::vector<double> answer_all = {0.0, 4.0/3, 4.0/3, 4.0/3, 12.0, 2.5, 2.5, 0.0};

    std::vector<float> result_all =
        vertex_betweenness_centrality_batch_alt_trans(betweenness, seed_set_all);

    BOOST_CHECK_EQUAL(result_all.size(), answer_all.size());
    for (unsigned int ix = 0; ix < result_all.size(); ++ix)
        BOOST_CHECK_CLOSE(result_all[ix], answer_all[ix], 0.0001);
    //std::cout << "=======================  END  ==========================\n";
}

//****************************************************************************
//BOOST_AUTO_TEST_CASE(bc_test_vertex_betweennes_centrality_batch_alt_trans_v2)
BOOST_AUTO_TEST_CASE(bc_test_batch_alt_trans_v2)
{
    Matrix<double, DirectedMatrixTag> betweenness(8,8);
    betweenness.build(br.begin(), bc.begin(), bv.begin(), bv.size());

    //IndexArrayType seed_set={0, 1, 2, 3, 4, 5, 6, 7};
    IndexArrayType seed_set={0};
    std::vector<float> answer = {0.0, 4.0/3, 4.0/3, 4.0/3, 3.0, 0.5, 0.5, 0.0};

    std::vector<float> result = vertex_betweenness_centrality_batch_alt_trans_v2(
            betweenness, seed_set);

    BOOST_CHECK_EQUAL(result.size(), answer.size());
    for (unsigned int ix = 0; ix < result.size(); ++ix)
        BOOST_CHECK_CLOSE(result[ix], answer[ix], 0.0001);

    //==========
    IndexArrayType seed_set3={3};
    std::vector<float> answer3 = {0.0, 0.0, 0.0, 0.0, 3.0, 0.5, 0.5, 0.0};

    std::vector<float> result3 =
        vertex_betweenness_centrality_batch_alt_trans_v2(betweenness, seed_set3);

    BOOST_CHECK_EQUAL(result3.size(), answer3.size());
    for (unsigned int ix = 0; ix < result3.size(); ++ix)
        BOOST_CHECK_CLOSE(result3[ix], answer3[ix], 0.0001);

    //==========
    IndexArrayType seed_set03={0,3};

    std::vector<float> result03 =
        vertex_betweenness_centrality_batch_alt_trans_v2(betweenness, seed_set03);

    BOOST_CHECK_EQUAL(result03.size(), answer3.size());
    for (unsigned int ix = 0; ix < result3.size(); ++ix)
        BOOST_CHECK_CLOSE(result03[ix], answer[ix] + answer3[ix], 0.0001);

    //==========
    IndexArrayType seed_set_all={0,1,2,3,4,5,6,7};
    std::vector<double> answer_all = {0.0, 4.0/3, 4.0/3, 4.0/3, 12.0, 2.5, 2.5, 0.0};

    std::vector<float> result_all =
        vertex_betweenness_centrality_batch_alt_trans_v2(betweenness, seed_set_all);

    BOOST_CHECK_EQUAL(result_all.size(), answer_all.size());
    for (unsigned int ix = 0; ix < result_all.size(); ++ix)
        BOOST_CHECK_CLOSE(result_all[ix], answer_all[ix], 0.0001);
}

BOOST_AUTO_TEST_SUITE_END()


//
// Created by philipp on 26.12.2019.
//

#ifndef FUNNELS_CPP_DISTANCES_HH
#define FUNNELS_CPP_DISTANCES_HH

#include <cassert>
#include <vector>
#include <Eigen/Core>
#include <cmath>

#ifndef M_PI
  #define M_PI 3.14159265358979323846
#endif

using namespace std;
using namespace Eigen;

double wrap_so2(double x){
  return std::fmod(x, M_PI);
}

class partial_so2_dist_t{
public:
  partial_so2_dist_t(vector<size_t> so2_dims=vector<size_t>()):
      _so2_dims(move(so2_dims)){};

//  template <class DERIVED0, class DERIVED1>
//  MatrixXd &operator()(const MatrixBase<DERIVED0> &x0,
//      const MatrixBase<DERIVED1> &x1){
//    // Multiple possibilities here
//    // so we have to do proper broadcasting
//    assert(x0.rows()==x1.rows());
//
//    if(x0.cols()==1 && x1.cols()==1){
//      // two vectors
//      _tmpMat = x0-x1;
//    }else if(x0.cols()==1 || x1.cols()==1){
//      if (x0.cols()==1){
//        _tmpMat = (-x1).colwise() + x0;
//      }else{
//        _tmpMat = x1.colwise()-x0;
//      }
//    }else if(x0.cols()==x1.cols()){
//      _tmpMat = x0-x1;
//    }
//

//    return _tmpMat;
//  }

  const MatrixXd & cp_vv(const VectorXd & v0, const VectorXd & v1) const {
    _tmpMat = v0-v1;
    do_so2_wrap();
    return _tmpMat;
  }

  const MatrixXd & cp_vM(const VectorXd & v0, const MatrixXd & m1) const {
    _tmpMat = (-m1).colwise() + v0;
    do_so2_wrap();
    return _tmpMat;
  }

  const MatrixXd & cp_Mv(const MatrixXd & m0, const VectorXd & v1) const {
    _tmpMat = m0.colwise() - v1;
    do_so2_wrap();
    return _tmpMat;
  }

  const MatrixXd &cp_MM(const MatrixXd & m0, const MatrixXd & m1) const {
    _tmpMat = m0 - m1;
    do_so2_wrap();
    return _tmpMat;
  }

protected:

  inline void do_so2_wrap()const{
    // Take into account the angles
    for (size_t idx : _so2_dims){
      _tmpMat.col(idx).unaryExpr(&wrap_so2);
    }
  }

  const vector<size_t> _so2_dims;
  mutable MatrixXd _tmpMat;
};

#endif //FUNNELS_CPP_DISTANCES_HH


/* ODE RHS and Jacobian function abstract base class definitions.

   D.R. Reynolds
   Math 6321 @ SMU
   Fall 2020 */

#ifndef ODE_RHS_DEFINED__
#define ODE_RHS_DEFINED__

// Inclusions
#include <armadillo>

// Declare abstract base classes for ODE RHS and its Jacobian, to
// define what the time integrator expects from each.

//   ODE RHS function abstract base class; derived classes
//   must at least implement the Evaluate() routine
class RHSFunction {
 public:
  virtual int Evaluate(double t, arma::vec& y, arma::vec& f) = 0;
};

//   ODE RHS Jacobian function abstract base class; derived
//   classes must at least implement the Evaluate() routine
class RHSJacobian {
 public:
  virtual int Evaluate(double t, arma::vec& y, arma::mat& J) = 0;
};

#endif


#include "custom.h"
#include<QtWidgets>
#include<qdebug.h>
#include<math.h>
#include <armadillo>

Custom::Custom( QWidget * parent)
{
    //initArr();
    initTableWidget();

    calculationBtn = new QPushButton(QStringLiteral("重新计算"),this);
    connect(calculationBtn,&QPushButton::clicked,this,&Custom::calculation);
    QVBoxLayout * Vlayout = new QVBoxLayout(this);
    Vlayout->addWidget(calculationBtn);
    Vlayout->addWidget(tableWidget);
    setLayout(Vlayout);

    QString str = QString::fromStdString(arma::arma_version::as_string());
    qDebug()<<str;

}

void Custom::initTableWidget(){

    tableWidget = new QTableWidget(6,7,this);

    QStringList HHeadList;
    HHeadList<<"A(%)"<<"B(%)"<<"C(%)"<<"D(%)"<<"E(%)"<<"F(%)"<<QStringLiteral("重量(g)");
    tableWidget->setHorizontalHeaderLabels(HHeadList);

    QStringList VHeadList;
    VHeadList<<"1#"<<"2#"<<"3#"<<"4#"<<"5#"<<QStringLiteral("混合后元素含量");
    tableWidget->setVerticalHeaderLabels(VHeadList);

    for( int i = 0 ; i < tableWidget->rowCount() ; i ++){

        for( int j = 0 ; j < tableWidget->columnCount() ;j++){

            tableWidget->setItem(i,j,new QTableWidgetItem("0"));

        }

    }

    tableWidget->setItem(tableWidget->rowCount()-1,tableWidget->columnCount()-1,new QTableWidgetItem("1000"));
    tableWidget->show();
    connect(tableWidget,&QTableWidget::itemChanged,this,&Custom::tableItemChanged);

}

int Custom::calculation(){

    arma::mat A1(4,3,arma::fill::zeros);
    arma::vec B1(4,arma::fill::zeros);
    arma::vec X1;

    A1 = {
            {5,4,-4},
            {-4,-3,5},
            {-1,-1,-1},
            {-8,-7,1}
         };
    B1 = {4,-5,1,-1};
    solve(X1, A1, B1);
    A1.print("A1:");
    B1.print("B1:");
    X1.print("X1:");

    return 0;

    qDebug()<<QStringLiteral("点击重新计算按钮");

    arma::mat A(tableWidget->columnCount()-1,tableWidget->rowCount()-1,arma::fill::zeros);
    arma::vec B(tableWidget->columnCount()-1,arma::fill::zeros);
    arma::vec X(tableWidget->rowCount()-1,arma::fill::zeros);

    for( int i = 0 ; i < tableWidget->columnCount()-1; i ++){ //按列顺序优先遍历

        for( int j = 0 ; j < tableWidget->rowCount()-1 ;j++){

            if(tableWidget->item(j,i)!=nullptr){

                QString str = tableWidget->item(j,i)->text();
                double w = str.toDouble();
                A(i,j) = w;

            }

        }

    }

    double a1[10] = {0};

    for(int i = 0 ;  i < tableWidget->columnCount()-1; i++){

        if(tableWidget->item(tableWidget->rowCount()-1,i)!=nullptr){

            QString str = tableWidget->item(tableWidget->rowCount()-1,i)->text();
            double w = str.toDouble();
            B[i] = 1000*w;

        }

    }

    bool status = solve(X, A, B);
    A.print("A:");
    B.print("B:");
    if( status ){

        for(int i = 0 ; i < tableWidget->columnCount()-1;i++){
            qDebug()<<X[i];
        }

    }else{
        QMessageBox::information(NULL, QStringLiteral("提示"), QStringLiteral("无解"),
                                 QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
    }

    /*int a1[10] = {0};

    for(int i = 0 ;  i < tableWidget->columnCount()-1; i++){

        if(tableWidget->item(tableWidget->rowCount()-1,i)!=nullptr){

            QString str = tableWidget->item(tableWidget->rowCount()-1,i)->text();
            int w = str.toInt();
            a1[i] = (1000*w)/100;

        }

    }

    for( int i = 0 ; i < tableWidget->columnCount()-1; i ++){ //按列顺序优先遍历

        for( int j = 0 ; j < tableWidget->rowCount()-1 ;j++){

            if(tableWidget->item(j,i)!=nullptr){

//                if(j==tableWidget->columnCount()-1){

//                    a[i][j] = a1[i];

//                }else{

//                    QString str = tableWidget->item(i,j)->text();
//                    int w = str.toInt();
//                    a[i][j] = w;

//                }
                QString str = tableWidget->item(j,i)->text();
                int w = str.toInt();
                a[i][j] = w;

                //qDebug()<<a[i][j];
            }

        }

    }

    for( int i = 0 ; i < 10 ; i ++){

        int len = tableWidget->columnCount()-1;
        a[len][i] = a1[i];

    }

    for( int i = 0 ; i < 10 ; i ++){

        for( int j = 0; j < 10 ; j++){
            qDebug()<<a[i][j];
        }

    }

    int var = tableWidget->rowCount()-1; //未知数个数
    int free_num = Gauss(tableWidget->columnCount()-1,var);
    if (free_num == -1) {

        QMessageBox::information(NULL, QStringLiteral("提示"), QStringLiteral("无解"),
                                 QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);

    }
    else if (free_num == -2){

        QMessageBox::information(NULL, QStringLiteral("提示"), QStringLiteral("有浮点解,无整数解"),
                                 QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);

    }
    else if (free_num > 0)
    {
//        printf("无穷多解! 自由变元个数为%d\n", free_num);
//        for (i = 0; i < var; i++)
//        {
//            if (free_x[i]) printf("x%d 是不确定的\n", i + 1);
//            else printf("x%d: %d\n", i + 1, x[i]);
//        }
        QMessageBox::information(NULL, QStringLiteral("提示"), QStringLiteral("无穷多解！"),
                                 QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
    }
    else
    {
        for (int i = 0; i < var; i++)
        {
            printf("x%d: %d\n", i + 1, x[i]);
        }
    }*/

    return -1;
}

void Custom::tableItemChanged( QTableWidgetItem * item){

    qDebug()<<QStringLiteral("单元格改变");

}

int Custom::initArr(){

    for( int i = 0 ;  i < 10 ; i ++){
        for( int j = 0;j<10;j++){
            a[i][j] = 0;
        }
    }
    return 0;
}

int Custom::gcd(int a,int b)
{
    int t;
    while(b!=0)
    {
        t=b;
        b=a%b;
        a=t;
    }
    return a;
}

int Custom::lcm(int a,int b)
{
    return a/gcd(a,b)*b;//先除后乘防溢出
}

// 高斯消元法解方程组(Gauss-Jordan elimination).(-2表示有浮点数解，但无整数解，
//-1表示无解，0表示唯一解，大于0表示无穷解，并返回自由变元的个数)
//有equ个方程，var个变元。增广矩阵行数为equ,分别为0到equ-1,列数为var+1,分别为0到var.
int Custom::Gauss(int equ,int var)
{
    int i,j,k;
    int max_r;// 当前这列绝对值最大的行.
    int col;//当前处理的列
    int ta,tb;
    int LCM;
    int temp;
    int free_x_num;
    int free_index;

    for(int i=0; i<=var; i++)
    {
        x[i]=0;
        free_x[i]=true;
    }

    //转换为阶梯阵.
    col=0; // 当前处理的列
    for(k = 0; k < equ && col < var; k++,col++)
    {
        // 枚举当前处理的行.
// 找到该col列元素绝对值最大的那行与第k行交换.(为了在除法时减小误差)
        max_r=k;
        for(i=k+1; i<equ; i++)
        {
            if(abs(a[i][col])>abs(a[max_r][col])) max_r=i;
        }
        if(max_r!=k)
        {
            // 与第k行交换.
            for(j=k; j<var+1; j++) std::swap(a[k][j],a[max_r][j]);
        }
        if(a[k][col]==0)
        {
            // 说明该col列第k行以下全是0了，则处理当前行的下一列.
            k--;
            continue;
        }
        for(i=k+1; i<equ; i++)
        {
            // 枚举要删去的行.
            if(a[i][col]!=0)
            {
                LCM = lcm(abs(a[i][col]),abs(a[k][col]));
                ta = LCM/abs(a[i][col]);
                tb = LCM/abs(a[k][col]);
                if(a[i][col]*a[k][col]<0)tb=-tb;//异号的情况是相加
                for(j=col; j<var+1; j++)
                {
                    a[i][j] = a[i][j]*ta-a[k][j]*tb;
                }
            }
        }
    }

    //  Debug();

    // 1. 无解的情况: 化简的增广阵中存在(0, 0, ..., a)这样的行(a != 0).
    for (i = k; i < equ; i++)
    {
        // 对于无穷解来说，如果要判断哪些是自由变元，那么初等行变换中的交换就会影响，则要记录交换.
        if (a[i][col] != 0) return -1;
    }
    // 2. 无穷解的情况: 在var * (var + 1)的增广阵中出现(0, 0, ..., 0)这样的行，即说明没有形成严格的上三角阵.
    // 且出现的行数即为自由变元的个数.
    if (k < var)
    {
        // 首先，自由变元有var - k个，即不确定的变元至少有var - k个.
        for (i = k - 1; i >= 0; i--)
        {
            // 第i行一定不会是(0, 0, ..., 0)的情况，因为这样的行是在第k行到第equ行.
            // 同样，第i行一定不会是(0, 0, ..., a), a != 0的情况，这样的无解的.
            free_x_num = 0; // 用于判断该行中的不确定的变元的个数，如果超过1个，则无法求解，它们仍然为不确定的变元.
            for (j = 0; j < var; j++)
            {
                if (a[i][j] != 0 && free_x[j]) free_x_num++, free_index = j;
            }
            if (free_x_num > 1) continue; // 无法求解出确定的变元.
            // 说明就只有一个不确定的变元free_index，那么可以求解出该变元，且该变元是确定的.
            temp = a[i][var];
            for (j = 0; j < var; j++)
            {
                if (a[i][j] != 0 && j != free_index) temp -= a[i][j] * x[j];
            }
            x[free_index] = temp / a[i][free_index]; // 求出该变元.
            free_x[free_index] = 0; // 该变元是确定的.
        }
        return var - k; // 自由变元有var - k个.
    }
    // 3. 唯一解的情况: 在var * (var + 1)的增广阵中形成严格的上三角阵.
    // 计算出Xn-1, Xn-2 ... X0.
    for (i = var - 1; i >= 0; i--)
    {
        temp = a[i][var];
        for (j = i + 1; j < var; j++)
        {
            if (a[i][j] != 0) temp -= a[i][j] * x[j];
        }
        if (temp % a[i][i] != 0) return -2; // 说明有浮点数解，但无整数解.
        x[i] = temp / a[i][i];
    }
    return 0;
}


#include "common.h"
#include <limits>
#include <cmath>
#include <ctime>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_01.hpp>

boost::random::mt19937 rng(time(0));
boost::random::uniform_01<elem_t> dist01;
std::ostream* logOut = &std::cout;
LogLevel currentLogLevel = Error;

Color::Modifier red(Color::FG_RED);
Color::Modifier def(Color::FG_DEFAULT);
Color::Modifier green(Color::FG_GREEN);
Color::Modifier yellow(Color::FG_YELLOW);

long double logint[MAX_COUNT + 1];
long double logfactorial[MAX_COUNT + 1];
double Pi = acos(-1.0);
intN bionomial[MAX_N + 1][MAX_N + 1];

std::ostream& operator<< (std::ostream& out, LogLevel level) {
    if (level == Info) {
        out << "Info:";
    } else if (level == Warning) {
        out << "Warning:";
    } else if (level == Error) {
        out << "Error:";
    } else {
        // do nothing.
    }
}

long double LogInt(int n)
{
	if (n == 0) {
		std::cout << "error! log(0)" << std::endl;
		return std::numeric_limits<long double>::max();
	}
	if (n == 1) return 0.0;

	if (logint[n] == 0.0) {
		logint[n] = logl(n);
	}

	return logint[n];
}

long double LogFactorial(int n)
{
	if (n == 1 || n == 0) return 0.0;

	if (logfactorial[n] == 0.0) {
		for (int i = 2; i <= n; i++) {
			logfactorial[n] += LogInt(i);
		}
	}

	return logfactorial[n];
}

elem_t random(elem_t min, elem_t max)
{
    return min + (max - min) * dist01(rng);
}

i64 random64(i64 max)
{
    boost::random::uniform_int_distribution<i64> dist(0, max);
    return dist(rng);
}

u128 random128(u128 max)
{
    boost::random::uniform_int_distribution<u64> high(0, (u64)(max >> 64));
    boost::random::uniform_int_distribution<u64> low(0, (u64)(max & std::numeric_limits<u64>::max()));

    return (((u128)high(rng)) << 64) | low(rng);
}

var_t randomComplex(elem_t minR, elem_t maxR) {
    elem_t r;
    while(true) {
        r = random(minR, maxR);
        if (random(0.0, maxR * maxR - minR * minR) < (r * r - minR * minR)) {
            break;
        }
    }
    elem_t phi = random(0.0, 2 * Pi);
    return var_t(r * cos(phi), r * sin(phi));
}

double EuclideanDist(double x1, double y1, double x2, double y2)
{
	return sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
}

double EuclideanDistSquare(double x1, double y1, double x2, double y2)
{
	return (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2);
}

intN BioCoeff(int n, int k)
{
	if (k > n) return 0;
	if (k == 0 || k == n) return 1;
	intN& ret = bionomial[n][k];
	if (ret == 0) {
		ret = BioCoeff(n - 1, k) + BioCoeff(n - 1, k - 1);
	}

	return ret;
}

bool isSingular(var_t u, elem_t eps) {
    return std::abs(u.real()) < eps && (std::abs(u.imag() + 0.5) < eps || std::abs(u.imag() - 0.5) < eps);
}

var_t e2ip(var_t u, elem_t eps) {
    if (isSingular(u)) {
        if (u.imag() > (elem_t)0.0) {
            return (elem_t)1.0;
        } else {
            return (elem_t)-1.0;
        }
    }
    return (u + var_t(0.0, 0.5))/(u - var_t(0.0, 0.5));
/*    if (abs(u.real()) > EPS) {
        return (u + var_t(0.0, 0.5))/(u - var_t(0.0, 0.5));
    } else {
        if (abs(u.imag() + 0.5) <= EPS) {
            return var_t(0, -EPS);
        } else if (abs(u.imag() - 0.5) <= EPS) {
            return var_t(0, 1/EPS);
        } else {
            return (u + var_t(0.0, 0.5))/(u - var_t(0.0, 0.5));
        }
    }*/
}

var_t e2ip(const Vector &u, elem_t eps) {
    var_t ret((elem_t)1.0);
    for (int i = 0; i < u.size(); i++) {
        ret *= e2ip(u[i], eps);
    }
    return ret;
}

elem_t momentum(Vector u, elem_t eps) {
    var_t ret = e2ip(u, eps);
//    return log(ret) * var_t(0.0, -1.0);
    return std::arg(ret);
}

var_t sMatrix(var_t u1, var_t u2) {
    return (u1 - u2 - var_t(0, 1.0))/(u1 - u2 + var_t(0, 1.0));
}

elem_t floatMod(elem_t num1, elem_t num2) {
    return num1 - floor((num1 + num2 * 0.5)/num2) * num2;
}

bool isZero(const var_t &val) {
    return abs(val.real()) < EPS && abs(val.imag()) < EPS;
}

var_t chop(var_t v, elem_t eps) {
    elem_t re = v.real();
    elem_t im = v.imag();
    if (std::abs(re) < eps) re = 0.0L;
    if (std::abs(im) < eps) im = 0.0L;
    return var_t(re, im);
}

void chop(Vector &v, elem_t eps) {
    for (int i = 0; i < v.size(); i++) {
        v[i] = chop(v[i], eps);
    }
}

Stopwatch::Stopwatch()
{
    start = clock();
}

void Stopwatch::Restart()
{
        start = clock();
}

std::string Stopwatch::Log(bool restart)
{
    double ret = (clock() - start) / (double)CLOCKS_PER_SEC;
    std::string text = ToString(ret) + " seconds elapsed, current time " + Now();

    if (restart) {
        Restart();
    }

    return text;
}

std::string Stopwatch::Now()
{
    time_t t = time(0);   // get time now
    struct tm * now = localtime(&t);
    char buf[80];
    strftime(buf, sizeof(buf), "%Y-%m-%d.%X", now);
    return buf;
}

/// return how much time in second since last Start() function call
double Stopwatch::Elapsed(bool restart)
{
        double ret = (clock() - start) / (double)CLOCKS_PER_SEC;
        if (restart) Restart();
        return ret;
}


//==================================================================================================
/**
  Copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
**/
//==================================================================================================
#include <simd_test.hpp>
#include <boost/simd/function/sincos.hpp>
#include <boost/simd/pack.hpp>
#include <boost/simd/function/std.hpp>
#include <boost/simd/constant/pio_4.hpp>
#include <boost/simd/constant/inf.hpp>
#include <boost/simd/constant/minf.hpp>
#include <boost/simd/constant/nan.hpp>
#include <boost/simd/constant/one.hpp>
#include <boost/simd/constant/mone.hpp>
#include <boost/simd/constant/zero.hpp>
#include <boost/simd/constant/mzero.hpp>
#include <boost/simd/function/sin.hpp>
#include <boost/simd/function/cos.hpp>

namespace bs = boost::simd;

template <typename T, std::size_t N, typename Env>
void test(Env& runtime)
{
  using p_t = bs::pack<T, N>;

  T a1[N], c[N], s[N];
  for(std::size_t i = 0; i < N; ++i)
  {
    a1[i] = (i%2) ? T(i) : -T(i);
    std::tie(s[i], c[i])= bs::sincos(a1[i]);
  }

  p_t aa1(&a1[0], &a1[0]+N);
  p_t ss (&s[0], &s[0]+N);
  p_t cc (&c[0], &c[0]+N);
  p_t ss1, cc1;
  std::tie(ss1, cc1)= bs::sincos(aa1);

  STF_ULP_EQUAL(ss1, ss,0.5);
  STF_ULP_EQUAL(cc1, cc,0.5);
}

STF_CASE_TPL("Check sincos on pack" , STF_IEEE_TYPES)
{
  static const std::size_t N = bs::pack<T>::static_size;

  test<T, N>(runtime);
  test<T, N/2>(runtime);
  test<T, N*2>(runtime);
}

template <typename T, std::size_t N, typename Env>
void testr(Env& runtime)
{
  using p_t = bs::pack<T, N>;

  T a1[N], c[N], s[N];
  for(std::size_t i = 0; i < N; ++i)
  {
    a1[i] = ((i%2) ? T(i) : -T(i))*bs::Pio_4<T>()/N;
    std::tie(s[i], c[i])= bs::restricted_(bs::sincos)(a1[i]);
  }

  p_t aa1(&a1[0], &a1[0]+N);
  p_t ss (&s[0], &s[0]+N);
  p_t cc (&c[0], &c[0]+N);
  p_t ss1, cc1;
  std::tie(ss1, cc1)= bs::restricted_(bs::sincos)(aa1);

  STF_ULP_EQUAL(ss1, ss,0.5);
  STF_ULP_EQUAL(cc1, cc,0.5);
}

STF_CASE_TPL("Check restricted sincos on pack" , STF_IEEE_TYPES)
{
  static const std::size_t N = bs::pack<T>::static_size;

  testr<T, N>(runtime);
  testr<T, N/2>(runtime);
  testr<T, N*2>(runtime);
}

STF_CASE_TPL (" sincos",  STF_IEEE_TYPES)
{
  namespace bs = boost::simd;
  namespace bd = boost::dispatch;
  using p_t = bs::pack<T>;

  using bs::sincos;
  p_t a[] = {bs::Zero<p_t>(), bs::One<p_t>(), bs::Pio2_3<p_t>(), bs::Pi<p_t>(),
           bs::Pio_2<p_t>(), bs::Inf<p_t>(), bs::Minf<p_t>(), bs::Nan<p_t>()};
  size_t N =  sizeof(a)/sizeof(p_t);

  STF_EXPR_IS( (sincos(p_t()))
             , (std::pair<p_t,p_t>)
             );

   {
    for(size_t i=0; i < N; ++i)
    {
      std::pair<p_t,p_t> p = sincos(a[i]);
      STF_IEEE_EQUAL(p.first,  bs::sin(a[i]));
      STF_IEEE_EQUAL(p.second, bs::cos(a[i]));
      std::pair<p_t,p_t> q = bs::restricted_(bs::sincos)(a[i]);
      STF_IEEE_EQUAL(q.first,  bs::restricted_(bs::sin)(a[i]));
      STF_IEEE_EQUAL(q.second, bs::restricted_(bs::cos)(a[i]));
    }
   }

}

template <typename T, std::size_t N, typename Env>
void testc(Env& runtime)
{
  namespace bst = bs::tag;
  using p_t = bs::pack<T, N>;

  T a1[N], c[N], s[N];
  for(std::size_t i = 0; i < N; ++i)
  {
    a1[i] = ((i%2) ? T(i) : -T(i))*bs::Pio_4<T>()/N;
    std::tie(s[i], c[i])= bs::sincos(a1[i], bst::clipped_medium_);
  }

  p_t aa1(&a1[0], &a1[0]+N);
  p_t ss (&s[0], &s[0]+N);
  p_t cc (&c[0], &c[0]+N);
  p_t ss1, cc1;
  std::tie(ss1, cc1)= bs::sincos(aa1, bst::clipped_medium_);

  STF_ULP_EQUAL(ss1, ss,0.5);
  STF_ULP_EQUAL(cc1, cc,0.5);
}

STF_CASE_TPL("Check clipped  sincos on pack" , STF_IEEE_TYPES)
{
  static const std::size_t N = bs::pack<T>::static_size;

  testc<T, N>(runtime);
  testc<T, N/2>(runtime);
  testc<T, N*2>(runtime);
}


//==================================================================================================
/*!
  @file

    @copyright 2016 NumScale SAS

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

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

  /*!
    @ingroup group-trigonometric
    This function object returns the inverse cotangent.

    @par Header <boost/simd/function/acot.hpp>

    @par Note

      For every parameter of floating type `r = acot(x)`
      returns the arc @c r in the interval  \f$[0, \pi[\f$ such that
      <tt>cot(r) == x</tt>.

    @see acotd, acotpi, cot

    @par Example:

      @snippet acot.cpp acot

    @par Possible output:

      @snippet acot.txt acot

  **/
  IEEEValue acot(IEEEValue const & x);
} }
#endif

#include <boost/simd/function/scalar/acot.hpp>
#include <boost/simd/function/simd/acot.hpp>

#endif


// Copyright John Maddock 2006.
// Use, modification and distribution are 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)

#include "mp_t.hpp"
#include <boost/math/tools/test_data.hpp>
#include <boost/test/included/prg_exec_monitor.hpp>
#include <boost/math/special_functions/ellint_rj.hpp>
#include <boost/math/special_functions/ellint_rd.hpp>
#include <fstream>
#include <boost/math/tools/test_data.hpp>
#include <boost/random.hpp>

float extern_val;
// confuse the compilers optimiser, and force a truncation to float precision:
float truncate_to_float(float const * pf)
{
   extern_val = *pf;
   return *pf;
}

//
// Archived here is the original implementation of this
// function by Xiaogang Zhang, we can use this to
// generate special test cases for the new version:
//
template <typename T, typename Policy>
T ellint_rj_old(T x, T y, T z, T p, const Policy& pol)
{
   T value, u, lambda, alpha, beta, sigma, factor, tolerance;
   T X, Y, Z, P, EA, EB, EC, E2, E3, S1, S2, S3;
   unsigned long k;

   BOOST_MATH_STD_USING
      using namespace boost::math;

   static const char* function = "boost::math::ellint_rj<%1%>(%1%,%1%,%1%)";

   if(x < 0)
   {
      return policies::raise_domain_error<T>(function,
         "Argument x must be non-negative, but got x = %1%", x, pol);
   }
   if(y < 0)
   {
      return policies::raise_domain_error<T>(function,
         "Argument y must be non-negative, but got y = %1%", y, pol);
   }
   if(z < 0)
   {
      return policies::raise_domain_error<T>(function,
         "Argument z must be non-negative, but got z = %1%", z, pol);
   }
   if(p == 0)
   {
      return policies::raise_domain_error<T>(function,
         "Argument p must not be zero, but got p = %1%", p, pol);
   }
   if(x + y == 0 || y + z == 0 || z + x == 0)
   {
      return policies::raise_domain_error<T>(function,
         "At most one argument can be zero, "
         "only possible result is %1%.", std::numeric_limits<T>::quiet_NaN(), pol);
   }

   // error scales as the 6th power of tolerance
   tolerance = pow(T(1) * tools::epsilon<T>() / 3, T(1) / 6);

   // for p < 0, the integral is singular, return Cauchy principal value
   if(p < 0)
   {
      //
      // We must ensure that (z - y) * (y - x) is positive.
      // Since the integral is symmetrical in x, y and z
      // we can just permute the values:
      //
      if(x > y)
         std::swap(x, y);
      if(y > z)
         std::swap(y, z);
      if(x > y)
         std::swap(x, y);

      T q = -p;
      T pmy = (z - y) * (y - x) / (y + q);  // p - y

      BOOST_ASSERT(pmy >= 0);

      p = pmy + y;
      value = ellint_rj_old(x, y, z, p, pol);
      value *= pmy;
      value -= 3 * boost::math::ellint_rf(x, y, z, pol);
      value += 3 * sqrt((x * y * z) / (x * z + p * q)) * boost::math::ellint_rc(x * z + p * q, p * q, pol);
      value /= (y + q);
      return value;
   }

   // duplication
   sigma = 0;
   factor = 1;
   k = 1;
   do
   {
      u = (x + y + z + p + p) / 5;
      X = (u - x) / u;
      Y = (u - y) / u;
      Z = (u - z) / u;
      P = (u - p) / u;

      if((tools::max)(abs(X), abs(Y), abs(Z), abs(P)) < tolerance)
         break;

      T sx = sqrt(x);
      T sy = sqrt(y);
      T sz = sqrt(z);

      lambda = sy * (sx + sz) + sz * sx;
      alpha = p * (sx + sy + sz) + sx * sy * sz;
      alpha *= alpha;
      beta = p * (p + lambda) * (p + lambda);
      sigma += factor * boost::math::ellint_rc(alpha, beta, pol);
      factor /= 4;
      x = (x + lambda) / 4;
      y = (y + lambda) / 4;
      z = (z + lambda) / 4;
      p = (p + lambda) / 4;
      ++k;
   } while(k < policies::get_max_series_iterations<Policy>());

   // Check to see if we gave up too soon:
   policies::check_series_iterations<T>(function, k, pol);

   // Taylor series expansion to the 5th order
   EA = X * Y + Y * Z + Z * X;
   EB = X * Y * Z;
   EC = P * P;
   E2 = EA - 3 * EC;
   E3 = EB + 2 * P * (EA - EC);
   S1 = 1 + E2 * (E2 * T(9) / 88 - E3 * T(9) / 52 - T(3) / 14);
   S2 = EB * (T(1) / 6 + P * (T(-6) / 22 + P * T(3) / 26));
   S3 = P * ((EA - EC) / 3 - P * EA * T(3) / 22);
   value = 3 * sigma + factor * (S1 + S2 + S3) / (u * sqrt(u));

   return value;
}

template <typename T, typename Policy>
T ellint_rd_imp_old(T x, T y, T z, const Policy& pol)
{
   T value, u, lambda, sigma, factor, tolerance;
   T X, Y, Z, EA, EB, EC, ED, EE, S1, S2;
   unsigned long k;

   BOOST_MATH_STD_USING
   using namespace boost::math;

   static const char* function = "boost::math::ellint_rd<%1%>(%1%,%1%,%1%)";

   if(x < 0)
   {
      return policies::raise_domain_error<T>(function,
         "Argument x must be >= 0, but got %1%", x, pol);
   }
   if(y < 0)
   {
      return policies::raise_domain_error<T>(function,
         "Argument y must be >= 0, but got %1%", y, pol);
   }
   if(z <= 0)
   {
      return policies::raise_domain_error<T>(function,
         "Argument z must be > 0, but got %1%", z, pol);
   }
   if(x + y == 0)
   {
      return policies::raise_domain_error<T>(function,
         "At most one argument can be zero, but got, x + y = %1%", x + y, pol);
   }

   // error scales as the 6th power of tolerance
   tolerance = pow(tools::epsilon<T>() / 3, T(1) / 6);

   // duplication
   sigma = 0;
   factor = 1;
   k = 1;
   do
   {
      u = (x + y + z + z + z) / 5;
      X = (u - x) / u;
      Y = (u - y) / u;
      Z = (u - z) / u;
      if((tools::max)(abs(X), abs(Y), abs(Z)) < tolerance)
         break;
      T sx = sqrt(x);
      T sy = sqrt(y);
      T sz = sqrt(z);
      lambda = sy * (sx + sz) + sz * sx; //sqrt(x * y) + sqrt(y * z) + sqrt(z * x);
      sigma += factor / (sz * (z + lambda));
      factor /= 4;
      x = (x + lambda) / 4;
      y = (y + lambda) / 4;
      z = (z + lambda) / 4;
      ++k;
   } while(k < policies::get_max_series_iterations<Policy>());

   // Check to see if we gave up too soon:
   policies::check_series_iterations<T>(function, k, pol);

   // Taylor series expansion to the 5th order
   EA = X * Y;
   EB = Z * Z;
   EC = EA - EB;
   ED = EA - 6 * EB;
   EE = ED + EC + EC;
   S1 = ED * (ED * T(9) / 88 - Z * EE * T(9) / 52 - T(3) / 14);
   S2 = Z * (EE / 6 + Z * (-EC * T(9) / 22 + Z * EA * T(3) / 26));
   value = 3 * sigma + factor * (1 + S1 + S2) / (u * sqrt(u));

   return value;
}

template <typename T, typename Policy>
T ellint_rf_imp_old(T x, T y, T z, const Policy& pol)
{
   T value, X, Y, Z, E2, E3, u, lambda, tolerance;
   unsigned long k;
   BOOST_MATH_STD_USING
   using namespace boost::math;
   static const char* function = "boost::math::ellint_rf<%1%>(%1%,%1%,%1%)";
   if(x < 0 || y < 0 || z < 0)
   {
      return policies::raise_domain_error<T>(function,
         "domain error, all arguments must be non-negative, "
         "only sensible result is %1%.",
         std::numeric_limits<T>::quiet_NaN(), pol);
   }
   if(x + y == 0 || y + z == 0 || z + x == 0)
   {
      return policies::raise_domain_error<T>(function,
         "domain error, at most one argument can be zero, "
         "only sensible result is %1%.",
         std::numeric_limits<T>::quiet_NaN(), pol);
   }
   // Carlson scales error as the 6th power of tolerance,
   // but this seems not to work for types larger than
   // 80-bit reals, this heuristic seems to work OK:
   if(policies::digits<T, Policy>() > 64)
   {
      tolerance = pow(tools::epsilon<T>(), T(1) / 4.25f);
      BOOST_MATH_INSTRUMENT_VARIABLE(tolerance);
   }
   else
   {
      tolerance = pow(4 * tools::epsilon<T>(), T(1) / 6);
      BOOST_MATH_INSTRUMENT_VARIABLE(tolerance);
   }
   // duplication
   k = 1;
   do
   {
      u = (x + y + z) / 3;
      X = (u - x) / u;
      Y = (u - y) / u;
      Z = (u - z) / u;
      // Termination condition:
      if((tools::max)(abs(X), abs(Y), abs(Z)) < tolerance)
         break;
      T sx = sqrt(x);
      T sy = sqrt(y);
      T sz = sqrt(z);
      lambda = sy * (sx + sz) + sz * sx;
      x = (x + lambda) / 4;
      y = (y + lambda) / 4;
      z = (z + lambda) / 4;
      ++k;
   } while(k < policies::get_max_series_iterations<Policy>());
   // Check to see if we gave up too soon:
   policies::check_series_iterations<T>(function, k, pol);
   BOOST_MATH_INSTRUMENT_VARIABLE(k);
   // Taylor series expansion to the 5th order
   E2 = X * Y - Z * Z;
   E3 = X * Y * Z;
   value = (1 + E2*(E2 / 24 - E3*T(3) / 44 - T(0.1)) + E3 / 14) / sqrt(u);
   BOOST_MATH_INSTRUMENT_VARIABLE(value);
   return value;
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rj_data_4e(mp_t n)
{
   mp_t result = ellint_rj_old(n, n, n, n, boost::math::policies::policy<>());
   return boost::math::make_tuple(n, n, n, result);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t, mp_t> generate_rj_data_3e(mp_t x, mp_t p)
{
   mp_t r = ellint_rj_old(x, x, x, p, boost::math::policies::policy<>());
   return boost::math::make_tuple(x, x, x, p, r);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t, mp_t> generate_rj_data_2e_1(mp_t x, mp_t y, mp_t p)
{
   mp_t r = ellint_rj_old(x, x, y, p, boost::math::policies::policy<>());
   return boost::math::make_tuple(x, x, y, p, r);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t, mp_t> generate_rj_data_2e_2(mp_t x, mp_t y, mp_t p)
{
   mp_t r = ellint_rj_old(x, y, x, p, boost::math::policies::policy<>());
   return boost::math::make_tuple(x, y, x, p, r);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t, mp_t> generate_rj_data_2e_3(mp_t x, mp_t y, mp_t p)
{
   mp_t r = ellint_rj_old(y, x, x, p, boost::math::policies::policy<>());
   return boost::math::make_tuple(y, x, x, p, r);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t, mp_t> generate_rj_data_2e_4(mp_t x, mp_t y, mp_t p)
{
   mp_t r = ellint_rj_old(x, y, p, p, boost::math::policies::policy<>());
   return boost::math::make_tuple(x, y, p, p, r);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rd_data_2e_1(mp_t x, mp_t y)
{
   mp_t r = ellint_rd_imp_old(x, y, y, boost::math::policies::policy<>());
   return boost::math::make_tuple(x, y, y, r);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rd_data_2e_2(mp_t x, mp_t y)
{
   mp_t r = ellint_rd_imp_old(x, x, y, boost::math::policies::policy<>());
   return boost::math::make_tuple(x, x, y, r);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rd_data_2e_3(mp_t x)
{
   mp_t r = ellint_rd_imp_old(mp_t(0), x, x, boost::math::policies::policy<>());
   return boost::math::make_tuple(0, x, x, r);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rd_data_3e(mp_t x)
{
   mp_t r = ellint_rd_imp_old(x, x, x, boost::math::policies::policy<>());
   return boost::math::make_tuple(x, x, x, r);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rd_data_0xy(mp_t x, mp_t y)
{
   mp_t r = ellint_rd_imp_old(mp_t(0), x, y, boost::math::policies::policy<>());
   return boost::math::make_tuple(mp_t(0), x, y, r);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rf_data_xxx(mp_t x)
{
   mp_t r = ellint_rf_imp_old(x, x, x, boost::math::policies::policy<>());
   return boost::math::make_tuple(x, x, x, r);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rf_data_xyy(mp_t x, mp_t y)
{
   mp_t r = ellint_rf_imp_old(x, y, y, boost::math::policies::policy<>());
   return boost::math::make_tuple(x, y, y, r);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rf_data_xxy(mp_t x, mp_t y)
{
   mp_t r = ellint_rf_imp_old(x, x, y, boost::math::policies::policy<>());
   return boost::math::make_tuple(x, x, y, r);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rf_data_xyx(mp_t x, mp_t y)
{
   mp_t r = ellint_rf_imp_old(x, y, x, boost::math::policies::policy<>());
   return boost::math::make_tuple(x, y, x, r);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rf_data_0yy(mp_t y)
{
   mp_t r = ellint_rf_imp_old(mp_t(0), y, y, boost::math::policies::policy<>());
   return boost::math::make_tuple(mp_t(0), y, y, r);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rf_data_xy0(mp_t x, mp_t y)
{
   mp_t r = ellint_rf_imp_old(x, y, mp_t(0), boost::math::policies::policy<>());
   return boost::math::make_tuple(x, y, mp_t(0), r);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rf_data(mp_t n)
{
   static boost::mt19937 r;
   boost::uniform_real<float> ur(0, 1);
   boost::uniform_int<int> ui(-100, 100);
   float x = ur(r);
   x = ldexp(x, ui(r));
   mp_t xr(truncate_to_float(&x));
   float y = ur(r);
   y = ldexp(y, ui(r));
   mp_t yr(truncate_to_float(&y));
   float z = ur(r);
   z = ldexp(z, ui(r));
   mp_t zr(truncate_to_float(&z));

   mp_t result = boost::math::ellint_rf(xr, yr, zr);
   return boost::math::make_tuple(xr, yr, zr, result);
}

boost::math::tuple<mp_t, mp_t, mp_t> generate_rc_data(mp_t n)
{
   static boost::mt19937 r;
   boost::uniform_real<float> ur(0, 1);
   boost::uniform_int<int> ui(-100, 100);
   float x = ur(r);
   x = ldexp(x, ui(r));
   mp_t xr(truncate_to_float(&x));
   float y = ur(r);
   y = ldexp(y, ui(r));
   mp_t yr(truncate_to_float(&y));

   mp_t result = boost::math::ellint_rc(xr, yr);
   return boost::math::make_tuple(xr, yr, result);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t, mp_t> generate_rj_data(mp_t n)
{
   static boost::mt19937 r;
   boost::uniform_real<float> ur(0, 1);
   boost::uniform_real<float> nur(-1, 1);
   boost::uniform_int<int> ui(-100, 100);
   float x = ur(r);
   x = ldexp(x, ui(r));
   mp_t xr(truncate_to_float(&x));
   float y = ur(r);
   y = ldexp(y, ui(r));
   mp_t yr(truncate_to_float(&y));
   float z = ur(r);
   z = ldexp(z, ui(r));
   mp_t zr(truncate_to_float(&z));
   float p = nur(r);
   p = ldexp(p, ui(r));
   mp_t pr(truncate_to_float(&p));

   boost::math::ellint_rj(x, y, z, p);

   mp_t result = boost::math::ellint_rj(xr, yr, zr, pr);
   return boost::math::make_tuple(xr, yr, zr, pr, result);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rd_data(mp_t n)
{
   static boost::mt19937 r;
   boost::uniform_real<float> ur(0, 1);
   boost::uniform_int<int> ui(-100, 100);
   float x = ur(r);
   x = ldexp(x, ui(r));
   mp_t xr(truncate_to_float(&x));
   float y = ur(r);
   y = ldexp(y, ui(r));
   mp_t yr(truncate_to_float(&y));
   float z = ur(r);
   z = ldexp(z, ui(r));
   mp_t zr(truncate_to_float(&z));

   mp_t result = boost::math::ellint_rd(xr, yr, zr);
   return boost::math::make_tuple(xr, yr, zr, result);
}

mp_t rg_imp(mp_t x, mp_t y, mp_t z)
{
   using std::swap;
   // If z is zero permute so the call to RD is valid:
   if(z == 0)
      swap(x, z);
   return (z * ellint_rf_imp_old(x, y, z, boost::math::policies::policy<>())
      - (x - z) * (y - z) * ellint_rd_imp_old(x, y, z, boost::math::policies::policy<>()) / 3
      + sqrt(x * y / z)) / 2;
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_data(mp_t n)
{
   static boost::mt19937 r;
   boost::uniform_real<float> ur(0, 1);
   boost::uniform_int<int> ui(-100, 100);
   float x = ur(r);
   x = ldexp(x, ui(r));
   mp_t xr(truncate_to_float(&x));
   float y = ur(r);
   y = ldexp(y, ui(r));
   mp_t yr(truncate_to_float(&y));
   float z = ur(r);
   z = ldexp(z, ui(r));
   mp_t zr(truncate_to_float(&z));

   mp_t result = rg_imp(xr, yr, zr);
   return boost::math::make_tuple(xr, yr, zr, result);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_xxx(mp_t x)
{
   mp_t result = rg_imp(x, x, x);
   return boost::math::make_tuple(x, x, x, result);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_xyy(mp_t x, mp_t y)
{
   mp_t result = rg_imp(x, y, y);
   return boost::math::make_tuple(x, y, y, result);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_xxy(mp_t x, mp_t y)
{
   mp_t result = rg_imp(x, x, y);
   return boost::math::make_tuple(x, x, y, result);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_xyx(mp_t x, mp_t y)
{
   mp_t result = rg_imp(x, y, x);
   return boost::math::make_tuple(x, y, x, result);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_0xx(mp_t x)
{
   mp_t result = rg_imp(mp_t(0), x, x);
   return boost::math::make_tuple(mp_t(0), x, x, result);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_x0x(mp_t x)
{
   mp_t result = rg_imp(x, mp_t(0), x);
   return boost::math::make_tuple(x, mp_t(0), x, result);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_xx0(mp_t x)
{
   mp_t result = rg_imp(x, x, mp_t(0));
   return boost::math::make_tuple(x, x, mp_t(0), result);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_00x(mp_t x)
{
   mp_t result = sqrt(x) / 2;
   return boost::math::make_tuple(mp_t(0), mp_t(0), x, result);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_0x0(mp_t x)
{
   mp_t result = sqrt(x) / 2;
   return boost::math::make_tuple(mp_t(0), x, mp_t(0), result);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_x00(mp_t x)
{
   mp_t result = sqrt(x) / 2;
   return boost::math::make_tuple(x, mp_t(0), mp_t(0), result);
}

boost::math::tuple<mp_t, mp_t, mp_t, mp_t> generate_rg_xy0(mp_t x, mp_t y)
{
   mp_t result = rg_imp(x, y, mp_t(0));
   return boost::math::make_tuple(x, y, mp_t(0), result);
}

int cpp_main(int argc, char*argv[])
{
   using namespace boost::math::tools;

   parameter_info<mp_t> arg1, arg2, arg3;
   test_data<mp_t> data;

   bool cont;
   std::string line;

   if(argc < 1)
      return 1;

   do{
#if 0
      int count;
      std::cout << "Number of points: ";
      std::cin >> count;

      arg1 = make_periodic_param(mp_t(0), mp_t(1), count);
      arg1.type |= dummy_param;

      //
      // Change this next line to get the R variant you want:
      //
      data.insert(&generate_rd_data, arg1);

      std::cout << "Any more data [y/n]?";
      std::getline(std::cin, line);
      boost::algorithm::trim(line);
      cont = (line == "y");
#else
      get_user_parameter_info(arg1, "x");
      get_user_parameter_info(arg2, "y");
      //get_user_parameter_info(arg3, "p");
      arg1.type |= dummy_param;
      arg2.type |= dummy_param;
      //arg3.type |= dummy_param;
      data.insert(generate_rd_data_0xy, arg1, arg2);

      std::cout << "Any more data [y/n]?";
      std::getline(std::cin, line);
      boost::algorithm::trim(line);
      cont = (line == "y");
#endif
   }while(cont);

   std::cout << "Enter name of test data file [default=ellint_rf_data.ipp]";
   std::getline(std::cin, line);
   boost::algorithm::trim(line);
   if(line == "")
      line = "ellint_rf_data.ipp";
   std::ofstream ofs(line.c_str());
   line.erase(line.find('.'));
   ofs << std::scientific << std::setprecision(40);
   write_code(ofs, data, line.c_str());

   return 0;
}


#include "glutil.h"
#include <boost/filesystem.hpp>
#include <cmath>

namespace glow {

Eigen::Matrix4f glTranslate(float x, float y, float z) {
  Eigen::Matrix4f m;
  m << 1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1;
  return m;
}

Eigen::Matrix4f glScale(float x, float y, float z) {
  Eigen::Matrix4f m;
  m << x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1;
  return m;
}

Eigen::Matrix4f glRotateX(float angle) {
  float sin_t = std::sin(angle);
  float cos_t = std::cos(angle);

  Eigen::Matrix4f m;
  m << 1, 0, 0, 0, 0, cos_t, -sin_t, 0, 0, sin_t, cos_t, 0, 0, 0, 0, 1;

  return m;
}

Eigen::Matrix4f glRotateY(float angle) {
  float sin_t = std::sin(angle);
  float cos_t = std::cos(angle);
  Eigen::Matrix4f m;
  m << cos_t, 0, sin_t, 0, 0, 1, 0, 0, -sin_t, 0, cos_t, 0, 0, 0, 0, 1;

  return m;
}

Eigen::Matrix4f glRotateZ(float angle) {
  float sin_t = std::sin(angle);
  float cos_t = std::cos(angle);
  Eigen::Matrix4f m;
  m << cos_t, -sin_t, 0, 0, sin_t, cos_t, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1;
  return m;
}

Eigen::Matrix4f glRotateAxis(float angle, float x, float y, float z) {
  Eigen::Matrix4f m;

  float s = std::sin(angle);
  float c = std::cos(angle);

  m(0, 0) = x * x * (1 - c) + c;
  m(0, 1) = x * y * (1.0f - c) - z * s;
  m(0, 2) = x * z * (1.0f - c) + y * s;
  m(0, 3) = 0.0f;

  m(1, 0) = x * y * (1.0f - c) + z * s;
  m(1, 1) = c + (1.0f - c) * y * y;
  m(1, 2) = y * z * (1.0f - c) - x * s;
  m(1, 3) = 0.0f;

  m(2, 0) = x * z * (1.0f - c) - y * s;
  m(2, 1) = y * z * (1.0f - c) + x * s;
  m(2, 2) = z * z + (1.0f - z * z) * c;
  m(2, 3) = 0.0f;

  m(3, 0) = 0.0f;
  m(3, 1) = 0.0f;
  m(3, 2) = 0.0f;
  m(3, 3) = 1.0f;

  return m;
}

Eigen::Matrix4f glPerspective(float fov, float aspect, float znear, float zfar) {
  // https://www.opengl.org/sdk/docs/man2/xhtml/gluPerspective.xml
  assert(znear > 0.0f);
  Eigen::Matrix4f M = Eigen::Matrix4f::Zero();

  // Copied from gluPerspective
  float f = 1.0f / std::tan(0.5f * fov);

  M(0, 0) = f / aspect;
  M(1, 1) = f;
  M(2, 2) = (znear + zfar) / (znear - zfar);
  M(2, 3) = (2.0f * zfar * znear) / (znear - zfar);
  M(3, 2) = -1.0f;

  return M;
}

Eigen::Matrix4f glOrthographic(float left, float right, float bottom, float top, float znear, float zfar) {

  // copied from https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glOrtho.xml

  Eigen::Matrix4f M = Eigen::Matrix4f::Zero();

  M(0, 0) = 2.0f / (right - left);
  M(1, 1) = 2.0f / (top - bottom);
  M(2, 2) = -2.0f / (zfar - znear);

  M(0, 3) = -(right + left) / (right - left);
  M(1, 3) = -(top + bottom) / (top - bottom);
  M(2, 3) = -(zfar + znear) / (zfar - znear);
  M(3, 3) = 1.0f;

  return M;
}

// clang-format off
Eigen::Matrix4f initializeMatrix(float t00, float t01, float t02, float t03,
                                 float t10, float t11, float t12, float t13,
                                 float t20, float t21, float t22, float t23,
                                 float t30, float t31, float t32, float t33) {
  Eigen::Matrix4f m;
  m << t00, t01, t02, t03, t10, t11, t12, t13, t20, t21, t22, t23, t30, t31, t32, t33;
  return m;
}

Eigen::Matrix4f RoSe2GL::matrix = initializeMatrix(0, -1, 0, 0,
                                                   0,  0, 1, 0,
                                                  -1,  0, 0, 0,
                                                   0,  0, 0, 1);

Eigen::Matrix4f GL2RoSe::matrix = initializeMatrix(0, 0, -1, 0,
                                                  -1, 0,  0, 0,
                                                   0, 1,  0, 0,
                                                   0, 0,  0, 1);
// clang-format on

float rgb2float(float r, float g, float b) {
  int32_t rgb = int32_t(round(r * 255.0f));
  rgb = (rgb << 8) + int32_t(round(g * 255.0f));
  rgb = (rgb << 8) + int32_t(round(b * 255.0f));

  return float(rgb);
}

std::string extension(const std::string& path, int32_t level) {
  std::string filename = boost::filesystem::path(path).filename().string();
  if (filename == "" || filename == "." || filename == "..") return "";

  std::string ext;
  while (level-- > 0) {
    std::string::size_type idx = filename.rfind(".");
    if (idx == std::string::npos) break;
    ext.insert(0, filename.substr(idx));
    filename.resize(idx);
  }

  return ext;
}
}

std::ostream& operator<<(std::ostream& stream, glow::vec2& vec) {
  stream << "(" << vec.x << ", " << vec.y << ")";

  return stream;
}

std::ostream& operator<<(std::ostream& stream, glow::vec3& vec) {
  stream << "(" << vec.x << ", " << vec.y << ", " << vec.z << ")";

  return stream;
}

std::ostream& operator<<(std::ostream& stream, glow::vec4& vec) {
  stream << "(" << vec.x << ", " << vec.y << ", " << vec.z << ", " << vec.w << ")";

  return stream;
}

std::ostream& operator<<(std::ostream& stream, const glow::vec2& vec) {
  stream << "(" << vec.x << ", " << vec.y << ")";

  return stream;
}

std::ostream& operator<<(std::ostream& stream, const glow::vec3& vec) {
  stream << "(" << vec.x << ", " << vec.y << ", " << vec.z << ")";

  return stream;
}

std::ostream& operator<<(std::ostream& stream, const glow::vec4& vec) {
  stream << "(" << vec.x << ", " << vec.y << ", " << vec.z << ", " << vec.w << ")";

  return stream;
}


#include <geometry.h>
#include <tiny.h>

#define BOOST_AUTO_TEST_MAIN
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/test_tools.hpp>

typedef tiny::MathTypes<float> MT;
typedef MT::quaternion_type    Q;
typedef MT::vector3_type       V;
typedef MT::real_type          T;
typedef MT::value_traits       VT;

BOOST_AUTO_TEST_SUITE(geometry);

BOOST_AUTO_TEST_CASE(overlap_obb_capsule_test)
{
  // Separated on plus x-axis of OBB
  {
    V const center   = V::make(0.0, 0.0, 0.0);
    V const half_ext = V::make(1.0, 1.0, 1.0);
    Q const q        = Q::identity();

    V const point0   = V::make(2.1,  0.0, 0.0);
    V const point1   = V::make(3.1,  2.1, 2.1);
    T const radius   = 1.0;

    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);
    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);

    bool const test = geometry::overlap_obb_capsule(obb, cap);

    BOOST_CHECK(!test);
  }
  // Overlap from plus x-side of OBB
  {
    V const center   = V::make(0.0, 0.0, 0.0);
    V const half_ext = V::make(1.0, 1.0, 1.0);
    Q const q        = Q::identity();

    V const point0   = V::make(1.9,  0.0, 0.0);
    V const point1   = V::make(3.1,  2.1, 2.1);
    T const radius   = 1.0;

    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);
    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);

    bool const test = geometry::overlap_obb_capsule(obb, cap);

    BOOST_CHECK(test);
  }
  // Separated on negative x-axis of OBB
  {
    V const center   = V::make(0.0, 0.0, 0.0);
    V const half_ext = V::make(1.0, 1.0, 1.0);
    Q const q        = Q::identity();

    V const point0   = V::make(-2.1,  0.0, 0.0);
    V const point1   = V::make(-3.1,  2.1, 2.1);
    T const radius   = 1.0;

    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);
    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);

    bool const test = geometry::overlap_obb_capsule(obb, cap);

    BOOST_CHECK(!test);
  }
  // Overlap from negative x-side of OBB
  {
    V const center   = V::make(0.0, 0.0, 0.0);
    V const half_ext = V::make(1.0, 1.0, 1.0);
    Q const q        = Q::identity();

    V const point0   = V::make(-1.9,  0.0, 0.0);
    V const point1   = V::make(-3.1,  2.1, 2.1);
    T const radius   = 1.0;

    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);
    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);

    bool const test = geometry::overlap_obb_capsule(obb, cap);

    BOOST_CHECK(test);
  }
  // Separated on plus y-axis of OBB
  {
    V const center   = V::make(0.0, 0.0, 0.0);
    V const half_ext = V::make(1.0, 1.0, 1.0);
    Q const q        = Q::identity();

    V const point0   = V::make(0.0, 2.1,  0.0);
    V const point1   = V::make(2.1, 3.1,  2.1);
    T const radius   = 1.0;

    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);
    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);

    bool const test = geometry::overlap_obb_capsule(obb, cap);

    BOOST_CHECK(!test);
  }
  // Overlap from plus y-side of OBB
  {
    V const center   = V::make(0.0, 0.0, 0.0);
    V const half_ext = V::make(1.0, 1.0, 1.0);
    Q const q        = Q::identity();

    V const point0   = V::make(0.0,  1.9, 0.0);
    V const point1   = V::make(2.1,  3.1, 2.1);
    T const radius   = 1.0;

    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);
    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);

    bool const test = geometry::overlap_obb_capsule(obb, cap);

    BOOST_CHECK(test);
  }
  // Separated on negative y-axis of OBB
  {
    V const center   = V::make(0.0, 0.0, 0.0);
    V const half_ext = V::make(1.0, 1.0, 1.0);
    Q const q        = Q::identity();

    V const point0   = V::make(0.0,  -2.1, 0.0);
    V const point1   = V::make(2.1,  -3.1, 2.1);
    T const radius   = 1.0;

    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);
    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);

    bool const test = geometry::overlap_obb_capsule(obb, cap);

    BOOST_CHECK(!test);
  }
  // Overlap from negative y-side of OBB
  {
    V const center   = V::make(0.0, 0.0, 0.0);
    V const half_ext = V::make(1.0, 1.0, 1.0);
    Q const q        = Q::identity();

    V const point0   = V::make(0.0, -1.9, 0.0);
    V const point1   = V::make(2.1, -3.1, 2.1);
    T const radius   = 1.0;

    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);
    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);

    bool const test = geometry::overlap_obb_capsule(obb, cap);

    BOOST_CHECK(test);
  }
  // Separated on plus z-axis of OBB
  {
    V const center   = V::make(0.0, 0.0, 0.0);
    V const half_ext = V::make(1.0, 1.0, 1.0);
    Q const q        = Q::identity();

    V const point0   = V::make(0.0, 0.0, 2.1);
    V const point1   = V::make(2.1, 2.1, 3.1);
    T const radius   = 1.0;

    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);
    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);

    bool const test = geometry::overlap_obb_capsule(obb, cap);

    BOOST_CHECK(!test);
  }
  // Overlap from plus z-side of OBB
  {
    V const center   = V::make(0.0, 0.0, 0.0);
    V const half_ext = V::make(1.0, 1.0, 1.0);
    Q const q        = Q::identity();

    V const point0   = V::make(0.0, 0.0,  1.9);
    V const point1   = V::make(2.1, 2.1,  3.1);
    T const radius   = 1.0;

    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);
    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);

    bool const test = geometry::overlap_obb_capsule(obb, cap);

    BOOST_CHECK(test);
  }
  // Separated on negative z-axis of OBB
  {
    V const center   = V::make(0.0, 0.0, 0.0);
    V const half_ext = V::make(1.0, 1.0, 1.0);
    Q const q        = Q::identity();

    V const point0   = V::make(0.0, 0.0,  -2.1);
    V const point1   = V::make(2.1, 2.1,  -3.1);
    T const radius   = 1.0;

    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);
    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);

    bool const test = geometry::overlap_obb_capsule(obb, cap);

    BOOST_CHECK(!test);
  }
  // Overlap from negative z-side of OBB
  {
    V const center   = V::make(0.0, 0.0, 0.0);
    V const half_ext = V::make(1.0, 1.0, 1.0);
    Q const q        = Q::identity();

    V const point0   = V::make(0.0, 0.0, -1.9);
    V const point1   = V::make(2.1, 2.1, -3.1);
    T const radius   = 1.0;

    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);
    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);

    bool const test = geometry::overlap_obb_capsule(obb, cap);

    BOOST_CHECK(test);
  }
  // Separated by z-OBB X capsule axis
  {
    V const center   = V::make(0.0, 0.0, 0.0);
    V const half_ext = V::make(1.0, 1.0, 1.0);
    Q const q        = Q::identity();

    V const point0   = V::make( 0.0,  -3.0, 0.0);
    V const point1   = V::make( 3.0,   0.0, 0.0);
    T const radius   = 0.5;

    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);
    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);

    bool const test = geometry::overlap_obb_capsule(obb, cap);

    BOOST_CHECK(!test);
  }
  // Overlap by z-OBB X capsule axis
  {
    V const center   = V::make(0.0, 0.0, 0.0);
    V const half_ext = V::make(1.0, 1.0, 1.0);
    Q const q        = Q::identity();

    V const point0   = V::make( 0.0,  -3.0, 0.0);
    V const point1   = V::make( 3.0,   0.0, 0.0);
    T const radius   = 1.0;

    geometry::OBB<MT>    const & obb = geometry::make_obb<MT>(center, q, half_ext);
    geometry::Capsule<V> const & cap = geometry::make_capsule(radius, point0, point1);

    bool const test = geometry::overlap_obb_capsule(obb, cap);

    BOOST_CHECK(test);
  }
}

BOOST_AUTO_TEST_SUITE_END();


/*
@copyright Louis Dionne 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#include <boost/hana/ext/std/integral_constant.hpp>

#include <boost/hana/tuple.hpp>

#include <laws/enumerable.hpp>
#include <laws/group.hpp>
#include <laws/integral_domain.hpp>
#include <laws/monoid.hpp>
#include <laws/ring.hpp>

#include <type_traits>
using namespace boost::hana;

int main() {
    auto ints = make<Tuple>(
        std::integral_constant<int, -10>{},
        std::integral_constant<int, -2>{},
        std::integral_constant<int, 0>{},
        std::integral_constant<int, 1>{},
        std::integral_constant<int, 3>{}
    );

    //////////////////////////////////////////////////////////////////////////
    // Enumerable, Monoid, Group, Ring, IntegralDomain
    //////////////////////////////////////////////////////////////////////////
    {
        // laws
        test::TestEnumerable<ext::std::IntegralConstant<int>>{ints};
        test::TestMonoid<ext::std::IntegralConstant<int>>{ints};
        test::TestGroup<ext::std::IntegralConstant<int>>{ints};
        test::TestRing<ext::std::IntegralConstant<int>>{ints};
        test::TestIntegralDomain<ext::std::IntegralConstant<int>>{ints};
    }
}


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//  Adaptation to Boost of the libcxx
//  Copyright 2010 Vicente J. Botet Escriba
//  Distributed under the Boost Software License, Version 1.0.
//  See http://www.boost.org/LICENSE_1_0.txt

// test ratio_power

#define BOOST_RATIO_EXTENSIONS
#include <boost/ratio/ratio.hpp>

#if !defined(BOOST_NO_CXX11_STATIC_ASSERT)
#define NOTHING ""
#endif

void test()
{
  {
    typedef boost::ratio<1, 2> R1;
    typedef boost::ratio_power<R1, 1> R;
    BOOST_RATIO_STATIC_ASSERT(R::num == 1 && R::den == 2, NOTHING, ());
  }
  {
    typedef boost::ratio<1, 2> R1;
    typedef boost::ratio_power<R1, -1> R;
    BOOST_RATIO_STATIC_ASSERT(R::num == 2 && R::den == 1, NOTHING, ());
  }
  {
    typedef boost::ratio<1, 2> R1;
    typedef boost::ratio_power<R1, 0> R;
    BOOST_RATIO_STATIC_ASSERT(R::num == 1 && R::den == 1, NOTHING, ());
  }
  {
    typedef boost::ratio<-1, 2> R1;
    typedef boost::ratio_power<R1, 2> R;
    BOOST_RATIO_STATIC_ASSERT(R::num == 1 && R::den == 4, NOTHING, ());
  }
  {
    typedef boost::ratio<1, -2> R1;
    typedef boost::ratio_power<R1, 2> R;
    BOOST_RATIO_STATIC_ASSERT(R::num == 1 && R::den == 4, NOTHING, ());
  }
  {
    typedef boost::ratio<2, 3> R1;
    typedef boost::ratio_power<R1, 2> R;
    BOOST_RATIO_STATIC_ASSERT(R::num == 4 && R::den == 9, NOTHING, ());
  }
  {
    typedef boost::ratio<2, 3> R1;
    typedef boost::ratio_power<R1, -2> R;
    BOOST_RATIO_STATIC_ASSERT(R::num == 9 && R::den == 4, NOTHING, ());
  }
}