text:
/**
  * @file det_test.cpp
  * @author Manish Kumar
  *
  * Test mlpackMain() of det_main.cpp
  *
  * mlpack is free software; you may redistribute it and/or modify it under the
  * terms of the 3-clause BSD license.  You should have received a copy of the
  * 3-clause BSD license along with mlpack.  If not, see
  * http://www.opensource.org/licenses/BSD-3-Clause for more information.
  */
#include <string>

#define BINDING_TYPE BINDING_TYPE_TEST

static const std::string testName = "DET";

#include <mlpack/core.hpp>
#include <mlpack/core/util/mlpack_main.hpp>
#include "test_helper.hpp"
#include <mlpack/methods/det/det_main.cpp>

#include <boost/test/unit_test.hpp>
#include "../test_tools.hpp"

using namespace mlpack;

struct DETTestFixture
{
 public:
  DETTestFixture()
  {
    // Cache in the options for this program.
    IO::RestoreSettings(testName);
  }

  ~DETTestFixture()
  {
    // Clear the settings.
    bindings::tests::CleanMemory();
    IO::ClearSettings();
  }
};

BOOST_FIXTURE_TEST_SUITE(DETMainTest, DETTestFixture);

/**
 * Check that number of output training_set_estimates and number of input data
 * points are equal.
 */
BOOST_AUTO_TEST_CASE(DETOutputDimensionTest)
{
  arma::mat trainingData;
  if (!data::Load("iris.csv", trainingData))
    BOOST_FAIL("Unable to load dataset iris.csv!");

  arma::mat testData;
  if (!data::Load("iris_test.csv", testData))
    BOOST_FAIL("Unable to load dataset iris_test.csv!");

  // Input data.
  SetInputParam("training", trainingData);
  SetInputParam("test", testData);

  mlpackMain();

  // Check the training_set_estimates has 100 points.
  BOOST_REQUIRE_EQUAL(IO::GetParam<arma::mat>("training_set_estimates").n_rows,
                      1);
  BOOST_REQUIRE_EQUAL(IO::GetParam<arma::mat>("training_set_estimates").n_cols,
                      trainingData.n_cols);

  // Check the test_set_estimates has 40 points.
  BOOST_REQUIRE_EQUAL(IO::GetParam<arma::mat>("test_set_estimates").n_rows, 1);
  BOOST_REQUIRE_EQUAL(IO::GetParam<arma::mat>("test_set_estimates").n_cols,
                      testData.n_cols);
}

/**
 * Ensure that max_leaf_size & min_leaf_size are always positive and number of
 * folds is always non-negative.
 */
BOOST_AUTO_TEST_CASE(DETParamBoundTest)
{
  arma::mat trainingData;
  if (!data::Load("iris.csv", trainingData))
    BOOST_FAIL("Unable to load dataset iris.csv!");

  // Test for max_leaf_size.

  SetInputParam("training", trainingData);
  SetInputParam("max_leaf_size", (int) 0);

  Log::Fatal.ignoreInput = true;
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);
  Log::Fatal.ignoreInput = false;

  bindings::tests::CleanMemory();

  // Test for min_leaf_size.

  SetInputParam("training", trainingData);
  SetInputParam("min_leaf_size", (int) 0);

  Log::Fatal.ignoreInput = true;
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);
  Log::Fatal.ignoreInput = false;

  bindings::tests::CleanMemory();

  // Test for folds.

  SetInputParam("training", move(trainingData));
  SetInputParam("folds", (int) -1);

  Log::Fatal.ignoreInput = true;
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);
  Log::Fatal.ignoreInput = false;
}

/**
 * Check that saved model can be reused again.
 */
BOOST_AUTO_TEST_CASE(DETModelReuseTest)
{
  arma::mat trainingData;
  if (!data::Load("iris.csv", trainingData))
    BOOST_FAIL("Unable to load dataset iris.csv!");

  arma::mat testData;
  if (!data::Load("iris_test.csv", testData))
    BOOST_FAIL("Unable to load dataset iris_test.csv!");

  // Input data.
  SetInputParam("training", std::move(trainingData));
  SetInputParam("test", testData);

  mlpackMain();

  arma::mat trainingSetEstimates =
      IO::GetParam<arma::mat>("training_set_estimates");
  arma::mat testSetEstimates = IO::GetParam<arma::mat>("test_set_estimates");

  IO::GetSingleton().Parameters()["training"].wasPassed = false;

  SetInputParam("input_model", IO::GetParam<DTree<>*>("output_model"));
  SetInputParam("test", std::move(testData));

  mlpackMain();

  // Check that initial estimates and final estimate using saved model are same.
  CheckMatrices(trainingSetEstimates,
                IO::GetParam<arma::mat>("training_set_estimates"));
  CheckMatrices(testSetEstimates,
                IO::GetParam<arma::mat>("test_set_estimates"));
}

/**
 * Check that number of output variable importance values equals number of
 * features in input data.
 */
BOOST_AUTO_TEST_CASE(DETViDimensionTest)
{
  arma::mat trainingData;
  if (!data::Load("iris.csv", trainingData))
    BOOST_FAIL("Unable to load dataset iris.csv!");

  arma::mat testData;
  if (!data::Load("iris_test.csv", testData))
    BOOST_FAIL("Unable to load dataset iris_test.csv!");

  size_t testRows = testData.n_rows;

  // Input data.
  SetInputParam("training", std::move(trainingData));
  SetInputParam("test", std::move(testData));

  mlpackMain();

  // Check the number of output points equals number of input features.
  BOOST_REQUIRE_EQUAL(IO::GetParam<arma::mat>("vi").n_rows, 1);
  BOOST_REQUIRE_EQUAL(IO::GetParam<arma::mat>("vi").n_cols, testRows);
}

/**
 * Make sure only one of training data or pre-trained model is passed.
 */
BOOST_AUTO_TEST_CASE(DETModelValidityTest)
{
  arma::mat trainingData;
  if (!data::Load("iris.csv", trainingData))
    BOOST_FAIL("Unable to load dataset iris.csv!");

  SetInputParam("training", std::move(trainingData));

  mlpackMain();

  SetInputParam("input_model", IO::GetParam<DTree<>*>("output_model"));

  Log::Fatal.ignoreInput = true;
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);
  Log::Fatal.ignoreInput = false;
}

/**
 * Check learning process using different min_leaf_size.
 */
BOOST_AUTO_TEST_CASE(DETDiffMinLeafTest)
{
  arma::mat trainingData;
  if (!data::Load("iris.csv", trainingData))
    BOOST_FAIL("Unable to load dataset iris.csv!");

  arma::mat testData;
  if (!data::Load("iris_test.csv", testData))
    BOOST_FAIL("Unable to load dataset iris_test.csv!");

  // Input data.
  SetInputParam("training", trainingData);
  SetInputParam("test", testData);

  mlpackMain();

  arma::mat trainingSetEstimates =
      IO::GetParam<arma::mat>("training_set_estimates");
  arma::mat testSetEstimates = IO::GetParam<arma::mat>("test_set_estimates");

  bindings::tests::CleanMemory();

  // Train model using min_leaf_size equals to 10.

  SetInputParam("training", std::move(trainingData));
  SetInputParam("test", std::move(testData));
  SetInputParam("min_leaf_size", (int) 10);

  mlpackMain();

  // Check that initial estimates and final estimates using two models are
  // different.
  BOOST_REQUIRE_LT(arma::accu(trainingSetEstimates ==
      IO::GetParam<arma::mat>("training_set_estimates")),
      trainingSetEstimates.n_elem);

  BOOST_REQUIRE_LT(arma::accu(testSetEstimates ==
      IO::GetParam<arma::mat>("test_set_estimates")),
      testSetEstimates.n_elem);
}

/**
 * Check learning process using different max_leaf_size.
 */
BOOST_AUTO_TEST_CASE(DETDiffMaxLeafTest)
{
  arma::mat trainingData;
  if (!data::Load("iris.csv", trainingData))
    BOOST_FAIL("Unable to load dataset iris.csv!");

  arma::mat testData;
  if (!data::Load("iris_test.csv", testData))
    BOOST_FAIL("Unable to load dataset iris_test.csv!");

  // Input data.
  SetInputParam("training", trainingData);
  SetInputParam("test", testData);

  mlpackMain();

  arma::mat trainingSetEstimates =
      IO::GetParam<arma::mat>("training_set_estimates");
  arma::mat testSetEstimates = IO::GetParam<arma::mat>("test_set_estimates");

  bindings::tests::CleanMemory();

  // Train model using max_leaf_size equals to 40.

  SetInputParam("training", std::move(trainingData));
  SetInputParam("test", std::move(testData));
  SetInputParam("max_leaf_size", (int) 40);

  mlpackMain();

  // Check that initial estimates and final estimates using two models are
  // different.
  BOOST_REQUIRE_LT(arma::accu(trainingSetEstimates ==
      IO::GetParam<arma::mat>("training_set_estimates")),
      trainingSetEstimates.n_elem);

  BOOST_REQUIRE_LT(arma::accu(testSetEstimates ==
      IO::GetParam<arma::mat>("test_set_estimates")),
      testSetEstimates.n_elem);
}

/**
 * Check learning process using different number of folds.
 */
BOOST_AUTO_TEST_CASE(DETDiffFoldsTest)
{
  arma::mat trainingData;
  if (!data::Load("iris.csv", trainingData))
    BOOST_FAIL("Unable to load dataset iris.csv!");

  arma::mat testData;
  if (!data::Load("iris_test.csv", testData))
    BOOST_FAIL("Unable to load dataset iris_test.csv!");

  // Input data.
  SetInputParam("training", trainingData);
  SetInputParam("test", testData);

  mlpackMain();

  arma::mat trainingSetEstimates =
      IO::GetParam<arma::mat>("training_set_estimates");
  arma::mat testSetEstimates = IO::GetParam<arma::mat>("test_set_estimates");

  bindings::tests::CleanMemory();

  // Train model using folds equals to 20.

  SetInputParam("training", std::move(trainingData));
  SetInputParam("test", std::move(testData));
  SetInputParam("folds", (int) 20);

  mlpackMain();

  // Check that initial estimates and final estimates using two models are
  // different.
  BOOST_REQUIRE_LT(arma::accu(trainingSetEstimates ==
      IO::GetParam<arma::mat>("training_set_estimates")),
      trainingSetEstimates.n_elem);

  BOOST_REQUIRE_LT(arma::accu(testSetEstimates ==
      IO::GetParam<arma::mat>("test_set_estimates")),
      testSetEstimates.n_elem);
}

/**
 * Check learning process by bypassing pruning step.
 */
BOOST_AUTO_TEST_CASE(DETSkipPruningTest)
{
  arma::mat trainingData;
  if (!data::Load("iris.csv", trainingData))
    BOOST_FAIL("Unable to load dataset iris.csv!");

  arma::mat testData;
  if (!data::Load("iris_test.csv", testData))
    BOOST_FAIL("Unable to load dataset iris_test.csv!");

  // Input data.
  SetInputParam("training", trainingData);
  SetInputParam("test", testData);

  mlpackMain();

  arma::mat trainingSetEstimates =
      IO::GetParam<arma::mat>("training_set_estimates");
  arma::mat testSetEstimates = IO::GetParam<arma::mat>("test_set_estimates");

  bindings::tests::CleanMemory();

  // Train model by bypassing pruning process.

  SetInputParam("training", std::move(trainingData));
  SetInputParam("test", std::move(testData));
  SetInputParam("skip_pruning", (bool) true);

  mlpackMain();

  // Check that initial estimates and final estimates using two models are
  // different.
  BOOST_REQUIRE_LT(arma::accu(trainingSetEstimates ==
      IO::GetParam<arma::mat>("training_set_estimates")),
      trainingSetEstimates.n_elem);

  BOOST_REQUIRE_LT(arma::accu(testSetEstimates ==
      IO::GetParam<arma::mat>("test_set_estimates")),
      testSetEstimates.n_elem);
}

BOOST_AUTO_TEST_SUITE_END();

max_issues_repo_name: R-Aravind/mlpack

max_forks_repo_name: R-Aravind/mlpack


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2021 Mikhail Komarov <nemo@nil.foundation>
// Copyright (c) 2021 Nikita Kaskov <nbering@nil.foundation>
// Copyright (c) 2022 Ilia Shirobokov <i.shirobokov@nil.foundation>
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//---------------------------------------------------------------------------//

#define BOOST_TEST_MODULE lpc_test

#include <string>

#include <boost/test/unit_test.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/data/monomorphic.hpp>

#include <nil/crypto3/algebra/curves/bls12.hpp>
#include <nil/crypto3/algebra/fields/arithmetic_params/bls12.hpp>
#include <nil/crypto3/algebra/curves/params/multiexp/bls12.hpp>
#include <nil/crypto3/algebra/curves/params/wnaf/bls12.hpp>
#include <nil/crypto3/algebra/random_element.hpp>

#include <nil/crypto3/math/algorithms/unity_root.hpp>
#include <nil/crypto3/math/domains/evaluation_domain.hpp>
#include <nil/crypto3/math/algorithms/make_evaluation_domain.hpp>

#include <nil/crypto3/zk/commitments/polynomial/lpc.hpp>
#include <nil/crypto3/zk/commitments/polynomial/batched_lpc.hpp>
#include <nil/crypto3/zk/commitments/polynomial/fri.hpp>
#include <nil/crypto3/zk/commitments/polynomial/batched_fri.hpp>
#include <nil/crypto3/zk/snark/systems/plonk/placeholder/params.hpp>
#include <nil/crypto3/zk/commitments/type_traits.hpp>

using namespace nil::crypto3;
using namespace nil::crypto3::zk::snark;

BOOST_AUTO_TEST_SUITE(lpc_test_suite)

BOOST_AUTO_TEST_CASE(lpc_basic_test) {

    // setup
    typedef algebra::curves::bls12<381> curve_type;
    typedef typename curve_type::scalar_field_type FieldType;

    typedef hashes::sha2<256> merkle_hash_type;
    typedef hashes::sha2<256> transcript_hash_type;

    typedef typename containers::merkle_tree<merkle_hash_type, 2> merkle_tree_type;

    constexpr static const std::size_t lambda = 40;
    constexpr static const std::size_t k = 1;

    constexpr static const std::size_t d = 16;

    constexpr static const std::size_t r = boost::static_log2<(d - k)>::value;
    constexpr static const std::size_t m = 2;

    typedef zk::commitments::fri<FieldType, merkle_hash_type, transcript_hash_type, m> fri_type;

    typedef zk::commitments::list_polynomial_commitment_params<merkle_hash_type, transcript_hash_type, lambda, r, m> lpc_params_type;
    typedef zk::commitments::list_polynomial_commitment<FieldType, lpc_params_type> lpc_type;

    static_assert(zk::is_commitment<fri_type>::value);
    static_assert(zk::is_commitment<lpc_type>::value);
    static_assert(!zk::is_commitment<merkle_hash_type>::value);
    static_assert(!zk::is_commitment<merkle_tree_type>::value);
    static_assert(!zk::is_commitment<std::size_t>::value);

    typedef typename lpc_type::proof_type proof_type;

    constexpr static const std::size_t d_extended = d;
    std::size_t extended_log = boost::static_log2<d_extended>::value;
    std::vector<std::shared_ptr<math::evaluation_domain<FieldType>>> D =
        zk::commitments::detail::calculate_domain_set<FieldType>(extended_log, r);

    typename fri_type::params_type fri_params;

    math::polynomial<typename FieldType::value_type> q = {0, 0, 1};
    fri_params.r = r;
    fri_params.D = D;
    fri_params.q = q;
    fri_params.max_degree = d - 1;

    // commit

    math::polynomial<typename FieldType::value_type> f = {1, 3, 4, 1, 5, 6, 7, 2, 8, 7, 5, 6, 1, 2, 1, 1};

    merkle_tree_type tree = lpc_type::precommit(f, D[0]);

    // TODO: take a point outside of the basic domain
    std::vector<typename FieldType::value_type> evaluation_points = {
        algebra::fields::arithmetic_params<FieldType>::multiplicative_generator};

    std::array<std::uint8_t, 96> x_data {};
    zk::transcript::fiat_shamir_heuristic_sequential<transcript_hash_type> transcript(x_data);

    auto proof = lpc_type::proof_eval(evaluation_points, tree, f, fri_params, transcript);

    // verify
    zk::transcript::fiat_shamir_heuristic_sequential<transcript_hash_type> transcript_verifier(x_data);

    BOOST_CHECK(lpc_type::verify_eval(evaluation_points, proof, fri_params, transcript_verifier));
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE(batched_lpc_test_suite)

BOOST_AUTO_TEST_CASE(batched_lpc_basic_test) {

    // setup
    typedef algebra::curves::bls12<381> curve_type;
    typedef typename curve_type::scalar_field_type FieldType;

    typedef hashes::sha2<256> merkle_hash_type;
    typedef hashes::sha2<256> transcript_hash_type;

    typedef typename containers::merkle_tree<merkle_hash_type, 2> merkle_tree_type;

    constexpr static const std::size_t leaf_size = 1;
    constexpr static const std::size_t lambda = 40;
    constexpr static const std::size_t k = 1;

    constexpr static const std::size_t d = 16;

    constexpr static const std::size_t r = boost::static_log2<(d - k)>::value;
    constexpr static const std::size_t m = 2;

    typedef zk::commitments::batched_fri<FieldType, merkle_hash_type, transcript_hash_type, m, leaf_size> fri_type;

    typedef zk::commitments::list_polynomial_commitment_params<merkle_hash_type, transcript_hash_type, lambda, r, m> lpc_params_type;
    typedef zk::commitments::batched_list_polynomial_commitment<FieldType, lpc_params_type, leaf_size> lpc_type;

    typedef typename lpc_type::proof_type proof_type;

    constexpr static const std::size_t d_extended = d;
    std::size_t extended_log = boost::static_log2<d_extended>::value;
    std::vector<std::shared_ptr<math::evaluation_domain<FieldType>>> D =
        zk::commitments::detail::calculate_domain_set<FieldType>(extended_log, r);

    typename fri_type::params_type fri_params;

    math::polynomial<typename FieldType::value_type> q = {0, 0, 1};
    fri_params.r = r;
    fri_params.D = D;
    fri_params.q = q;
    fri_params.max_degree = d - 1;

    // commit

    std::array<math::polynomial<typename FieldType::value_type>, leaf_size> f =
        {{
            {1, 3, 4, 1, 5, 6, 7, 2, 8, 7, 5, 6, 1, 2, 1, 1}
        }};

    merkle_tree_type tree = lpc_type::precommit(f, D[0]);

    // TODO: take a point outside of the basic domain
    std::array<std::vector<typename FieldType::value_type>, leaf_size> evaluation_points =
        {{
            {algebra::fields::arithmetic_params<FieldType>::multiplicative_generator}
        }};

    std::array<std::uint8_t, 96> x_data {};
    zk::transcript::fiat_shamir_heuristic_sequential<transcript_hash_type> transcript(x_data);

    auto proof = lpc_type::proof_eval(evaluation_points, tree, f, fri_params, transcript);

    // verify
    zk::transcript::fiat_shamir_heuristic_sequential<transcript_hash_type> transcript_verifier(x_data);

    BOOST_CHECK(lpc_type::verify_eval(evaluation_points, proof, fri_params, transcript_verifier));
}

BOOST_AUTO_TEST_CASE(batched_lpc_basic_test_2) {

    // setup
    typedef algebra::curves::bls12<381> curve_type;
    typedef typename curve_type::scalar_field_type FieldType;

    typedef hashes::sha2<256> merkle_hash_type;
    typedef hashes::sha2<256> transcript_hash_type;

    typedef typename containers::merkle_tree<merkle_hash_type, 2> merkle_tree_type;

    constexpr static const std::size_t leaf_size = 2;
    constexpr static const std::size_t lambda = 40;
    constexpr static const std::size_t k = 1;

    constexpr static const std::size_t d = 16;

    constexpr static const std::size_t r = boost::static_log2<(d - k)>::value;
    constexpr static const std::size_t m = 2;

    typedef zk::commitments::batched_fri<FieldType, merkle_hash_type, transcript_hash_type, m, leaf_size> fri_type;

    typedef zk::commitments::list_polynomial_commitment_params<merkle_hash_type, transcript_hash_type, lambda, r, m> lpc_params_type;
    typedef zk::commitments::batched_list_polynomial_commitment<FieldType, lpc_params_type, leaf_size> lpc_type;

    typedef typename lpc_type::proof_type proof_type;

    constexpr static const std::size_t d_extended = d;
    std::size_t extended_log = boost::static_log2<d_extended>::value;
    std::vector<std::shared_ptr<math::evaluation_domain<FieldType>>> D =
        zk::commitments::detail::calculate_domain_set<FieldType>(extended_log, r);

    typename fri_type::params_type fri_params;

    math::polynomial<typename FieldType::value_type> q = {0, 0, 1};
    fri_params.r = r;
    fri_params.D = D;
    fri_params.q = q;
    fri_params.max_degree = d - 1;

    // commit

    std::array<math::polynomial<typename FieldType::value_type>, leaf_size> f =
        {{
            {1, 3, 4, 1, 5, 6, 7, 2, 8, 7, 5, 6, 1, 2, 1, 1},
            {1, 2, 5, 1, 5, 6, 7, 2, 8, 7, 5, 6, 1, 2, 1, 1}
        }};

    merkle_tree_type tree = lpc_type::precommit(f, D[0]);

    // TODO: take a point outside of the basic domain
    std::array<std::vector<typename FieldType::value_type>, leaf_size> evaluation_points =
        {{
            {algebra::fields::arithmetic_params<FieldType>::multiplicative_generator},
            {algebra::fields::arithmetic_params<FieldType>::multiplicative_generator}
        }};

    std::array<std::uint8_t, 96> x_data {};
    zk::transcript::fiat_shamir_heuristic_sequential<transcript_hash_type> transcript(x_data);

    auto proof = lpc_type::proof_eval(evaluation_points, tree, f, fri_params, transcript);

    // verify
    zk::transcript::fiat_shamir_heuristic_sequential<transcript_hash_type> transcript_verifier(x_data);

    BOOST_CHECK(lpc_type::verify_eval(evaluation_points, proof, fri_params, transcript_verifier));
}

BOOST_AUTO_TEST_CASE(batched_lpc_basic_test_runtime_size) {

    // setup
    typedef algebra::curves::bls12<381> curve_type;
    typedef typename curve_type::scalar_field_type FieldType;

    typedef hashes::sha2<256> merkle_hash_type;
    typedef hashes::sha2<256> transcript_hash_type;

    typedef typename containers::merkle_tree<merkle_hash_type, 2> merkle_tree_type;

    constexpr static const std::size_t leaf_size = 2;
    constexpr static const std::size_t lambda = 40;
    constexpr static const std::size_t k = 1;

    constexpr static const std::size_t d = 16;

    constexpr static const std::size_t r = boost::static_log2<(d - k)>::value;
    constexpr static const std::size_t m = 2;

    typedef zk::commitments::batched_fri<FieldType, merkle_hash_type, transcript_hash_type, m, leaf_size> fri_type;

    typedef zk::commitments::list_polynomial_commitment_params<merkle_hash_type, transcript_hash_type, lambda, r, m> lpc_params_type;
    typedef zk::commitments::batched_list_polynomial_commitment<FieldType, lpc_params_type, 0, true> lpc_type;

    typedef typename lpc_type::proof_type proof_type;

    constexpr static const std::size_t d_extended = d;
    std::size_t extended_log = boost::static_log2<d_extended>::value;
    std::vector<std::shared_ptr<math::evaluation_domain<FieldType>>> D =
        zk::commitments::detail::calculate_domain_set<FieldType>(extended_log, r);

    typename fri_type::params_type fri_params;

    math::polynomial<typename FieldType::value_type> q = {0, 0, 1};
    fri_params.r = r;
    fri_params.D = D;
    fri_params.q = q;
    fri_params.max_degree = d - 1;

    // commit

    std::vector<math::polynomial<typename FieldType::value_type>> f =
        {
            {1, 3, 4, 1, 5, 6, 7, 2, 8, 7, 5, 6, 1, 2, 1, 1},
            {1, 2, 5, 1, 5, 6, 7, 2, 8, 7, 5, 6, 1, 2, 1, 1}
        };

    merkle_tree_type tree = lpc_type::precommit(f, D[0]);

    // TODO: take a point outside of the basic domain
    std::vector<std::vector<typename FieldType::value_type>> evaluation_points =
        {
            {algebra::fields::arithmetic_params<FieldType>::multiplicative_generator},
            {algebra::fields::arithmetic_params<FieldType>::multiplicative_generator}
        };

    std::array<std::uint8_t, 96> x_data {};
    zk::transcript::fiat_shamir_heuristic_sequential<transcript_hash_type> transcript(x_data);

    auto proof = lpc_type::proof_eval(evaluation_points, tree, f, fri_params, transcript);

    // verify
    zk::transcript::fiat_shamir_heuristic_sequential<transcript_hash_type> transcript_verifier(x_data);

    BOOST_CHECK(lpc_type::verify_eval(evaluation_points, proof, fri_params, transcript_verifier));
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: NilFoundation/zk

max_issues_repo_name: NilFoundation/zk

max_forks_repo_name: NilFoundation/zk


text:
#include "core/Belief.h"
#include "core/Types.h"
#include "core/Util.h"
#include "core/planning/DespotPlanner.h"
#include "experiments/Config.h"
#include "experiments/Util.h"
#include <algorithm>
#include <boost/program_options.hpp>
#include <iostream>
#include <macaron/Base64.h>
#include <opencv2/highgui.hpp>
namespace po = boost::program_options;

typedef Belief<ExpSimulation> ExpBelief;
typedef planning::DespotPlanner<ExpSimulation, ExpBelief, true> ExpPlanner;

// Specialize for DriveHard. Particle size should be
// 11 + 6 * NUM_EXO_AGENTS + 4 * #PARTICLES * NUM_EXO_AGENTS
template <>
std::string SerializeBelief(const ExpBelief& belief) {
  list_t<float> values;
  for (size_t i = 0; i < BELIEF_SAMPLES; i++) {
    belief.Sample().Encode(values);
  }
  return macaron::Base64::Encode(ToBytes(values));
}

int main(int argc, char** argv) {
  po::options_description desc("Allowed options");
  size_t macro_length;
  desc.add_options()
      ("macro-length", po::value<size_t>(&macro_length))
      ("visualize", "visualize macro-actions")
  ;
  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  // Configure planning time based on macro length.
  ExpSimulation::PLANNING_TIME = static_cast<size_t>(
      1000 * (ExpSimulation::DELTA * static_cast<float>(macro_length) - ExpSimulation::BELIEF_UPDATE_ALLOWANCE));

  while (true) {
    // Initialize simulation.
    ExpSimulation sim = ExpSimulation::CreateRandom();

    // Initialize planner.
    ExpPlanner planner;

    // Initialize belief.
    ExpBelief belief(sim);

    size_t steps = 0;
    list_t<ExpSimulation::Action> macro_action(macro_length, {0, 0});

    list_t<float> speed_statistics;
    list_t<float> steer_statistics;
    list_t<float> max_steer_statistics(1, 0.0f);
    list_t<float> speed_penalty_statistics;
    list_t<float> progress_distance_statistics(1, 0.0f);

    while (true) {

      // Forward belief and plan.
      ExpBelief forward_belief = belief;
      bool has_forward_search_result = false;
      ExpPlanner::SearchResult forward_search_result;
      for (const ExpSimulation::Action& a : macro_action) {
        forward_belief = forward_belief.Predict(a);
        if (forward_belief.IsTerminal()) {
          break;
        }
      }

      if (!forward_belief.IsTerminal()) {

        // Write context.
        list_t<float> serialized_context_values;
        forward_belief.Sample().EncodeContext(serialized_context_values);
        std::string serialized_context = macaron::Base64::Encode(ToBytes(serialized_context_values));
        std::cout << serialized_context << std::endl;

        //std::cout << SerializeContext<ExpSimulation>() << std::endl;

        forward_belief = forward_belief.ResampleNonTerminal();
        std::cout << SerializeBelief(forward_belief) << std::endl;
        list_t<list_t<ExpSimulation::Action>> macro_actions = ExpSimulation::Action::Deserialize(
            FromBytes<float>(macaron::Base64::Decode(get_cin_line())), macro_length);
        forward_search_result = planner.Search(forward_belief, macro_actions);
        has_forward_search_result = true;
      } else {
        std::cout << std::endl;
        std::cout << std::endl;
      }

      // Execute macro-action.
      ExpPlanner::ExecutionResult execution_result = ExpPlanner::ExecuteMacroAction(
          sim, macro_action, ExpSimulation::MAX_STEPS - steps);
      vector_t macro_action_start = sim.observable_state.ego_agent.position;
      for (size_t i = 0; i < execution_result.state_trajectory.size(); i++) {
        belief.Update(macro_action[i], execution_result.observation_trajectory[i]);

        speed_statistics.emplace_back(std::abs(
              execution_result.state_trajectory[i].observable_state.ego_agent.speed));
        steer_statistics.emplace_back(std::abs(
              execution_result.state_trajectory[i].observable_state.ego_agent.steer));
        max_steer_statistics[0] = std::max(max_steer_statistics[0], steer_statistics.back());
        speed_penalty_statistics.emplace_back(execution_result.state_trajectory[i].observable_state.ego_agent.speed < ExpSimulation::LOW_SPEED_THRESHOLD ? 1 : 0);

        sim = execution_result.state_trajectory[i];
        steps++;

        if (vm.count("visualize")) {
          cv::Mat frame = sim.CreateLocal().Render({}, macro_action, macro_action_start);
          cv::imshow("Frame", frame);
          cv::waitKey(1000 * ExpSimulation::DELTA);
        }
      }

      std::cout << (has_forward_search_result ? forward_search_result.value : 10000000.0f) << std::endl; // Seach max value.
      std::cout << execution_result.state_trajectory.size() << std::endl; // Execution num steps.
      std::cout << execution_result.reward << std::endl; // Execution discounted reward.
      std::cout << execution_result.undiscounted_reward << std::endl; // Execution total undiscounted reward.
      std::cout << ((sim.IsTerminal() || steps >= ExpSimulation::MAX_STEPS || forward_belief.IsTerminal()) ? 1 : 0) << std::endl; // Execution terminal.
      std::cout << (sim.IsFailure() ? 1 : 0) << std::endl; // Failure.
      std::cout << macro_action.size() << std::endl; // Macro action length.
      std::cout << (has_forward_search_result ? forward_search_result.num_nodes : 10000000) << std::endl; // Num nodes.
      std::cout << (has_forward_search_result ? forward_search_result.depth : 10000000) << std::endl; // Search depth.

      if (sim.IsTerminal() || steps >= ExpSimulation::MAX_STEPS || forward_belief.IsTerminal()) {
        std::cout << macaron::Base64::Encode(ToBytes(speed_statistics)) << std::endl; // Stat 0.
        std::cout << macaron::Base64::Encode(ToBytes(steer_statistics)) << std::endl; // Stat 1.
        progress_distance_statistics[0] = sim.observable_state.distance;
        std::cout << macaron::Base64::Encode(ToBytes(progress_distance_statistics)) << std::endl; // Stat 2.
        std::cout << macaron::Base64::Encode(ToBytes(max_steer_statistics)) << std::endl; // Stat 3.
        std::cout << macaron::Base64::Encode(ToBytes(speed_penalty_statistics)) << std::endl; // Stat 4.
        break;
      } else {
        std::cout << std::endl; // Stat 0.
        std::cout << std::endl; // Stat 1.
        std::cout << std::endl; // Stat 2.
        std::cout << std::endl; // Stat 3.
        std::cout << std::endl; // Stat 4.
      }

      macro_action = forward_search_result.action;
    }
  }
}

max_stars_repo_name: modanesh/magic

max_issues_repo_name: modanesh/magic

max_forks_repo_name: modanesh/magic


text:
#include <gtest/gtest.h>
#include <libdevcrypto/Common.h>
#include <libp2p/Capability.h>
#include <libp2p/Common.h>
#include <libp2p/Host.h>
#include <libp2p/Network.h>
#include <libp2p/Session.h>

#include <atomic>
#include <boost/thread.hpp>
#include <iostream>
#include <vector>

#include "common/static_init.hpp"
#include "logger/log.hpp"
#include "network/network.hpp"
#include "network/taraxa_capability.hpp"
#include "util/lazy.hpp"
#include "util_test/samples.hpp"
#include "util_test/util.hpp"

namespace taraxa::core_tests {
using namespace dev;
using namespace dev::p2p;

const unsigned NUM_TRX = 9;
auto g_secret = Lazy([] {
  return dev::Secret("3800b2875669d9b2053c1aff9224ecfdc411423aac5b5a73d7a45ced1c3b9dcd",
                     dev::Secret::ConstructFromStringType::FromHex);
});
auto g_signed_trx_samples = Lazy([] { return samples::createSignedTrxSamples(0, NUM_TRX, g_secret); });

struct P2PTest : BaseTest {};

/*
Test creates one boot node and 10 nodes that uses that boot node
to find each other. Test confirm that after a delay each node had found
all other nodes.
*/
TEST_F(P2PTest, p2p_discovery) {
  auto secret = dev::Secret("3800b2875669d9b2053c1aff9224ecfdc411423aac5b5a73d7a45ced1c3b9dcd",
                            dev::Secret::ConstructFromStringType::FromHex);
  auto key = dev::KeyPair(secret);
  const int NUMBER_OF_NODES = 10;
  dev::p2p::NetworkConfig net_conf("127.0.0.1", 20001, false, true);
  TaraxaNetworkConfig taraxa_net_conf;
  taraxa_net_conf.is_boot_node = true;
  auto dummy_capability_constructor = [](auto /*host*/) { return Host::CapabilityList{}; };
  util::ThreadPool tp;
  auto bootHost = Host::make("TaraxaNode", dummy_capability_constructor, key, net_conf, taraxa_net_conf);
  tp.post_loop({}, [=] { bootHost->do_work(); });
  printf("Started Node id: %s\n", bootHost->id().hex().c_str());

  std::vector<std::shared_ptr<dev::p2p::Host>> nodes;
  for (int i = 0; i < NUMBER_OF_NODES; i++) {
    auto node = nodes.emplace_back(Host::make("TaraxaNode", dummy_capability_constructor, dev::KeyPair::create(),
                                              dev::p2p::NetworkConfig("127.0.0.1", 20002 + i, false, true)));
    tp.post_loop({}, [=] { node->do_work(); });
    nodes[i]->addNode(Node(dev::Public("7b1fcf0ec1078320117b96e9e9ad9032c06d030cf4024a598347a4"
                                       "623a14a421d4"
                                       "f030cf25ef368ab394a45e920e14b57a259a09c41767dd50d1da27"
                                       "b627412a"),
                           dev::p2p::NodeIPEndpoint(bi::address::from_string("127.0.0.1"), 20001, 20001)));
    taraxa::thisThreadSleepForMilliSeconds(100);
  }
  // allow more time for p2p discovery
  for (int i = 0; i < 60; i++) {
    bool allNodesFound = true;
    for (int j = 0; j < NUMBER_OF_NODES; j++)
      if (NUMBER_OF_NODES / 2 >= nodes[j]->getNodeCount()) allNodesFound = false;
    if (allNodesFound) break;
    taraxa::thisThreadSleepForSeconds(1);
  }
  for (int i = 0; i < NUMBER_OF_NODES; i++) {
    ASSERT_LT(NUMBER_OF_NODES / 3, nodes[i]->getNodeCount());
  }
}

/*
Test creates two host/network/capability and verifies that host connect
to each other and that a test packet message can be sent from one host
to the other using TaraxaCapability
*/
TEST_F(P2PTest, capability_send_test) {
  int const step = 10;
  const char *const localhost = "127.0.0.1";
  dev::p2p::NetworkConfig prefs1(localhost, 10007, false, true);
  prefs1.discovery = false;
  dev::p2p::NetworkConfig prefs2(localhost, 10003, false, true);
  prefs2.discovery = false;
  NetworkConfig network_conf;
  network_conf.network_simulated_delay = 0;
  network_conf.network_bandwidth = 40;
  network_conf.network_transaction_interval = 1000;
  shared_ptr<TaraxaCapability> thc1, thc2;
  auto host1 = Host::make(
      "Test",
      [&](auto host) {
        thc1 = make_shared<TaraxaCapability>(host, network_conf);
        return Host::CapabilityList{thc1};
      },
      KeyPair::create(), prefs1);
  auto host2 = Host::make(
      "Test",
      [&](auto host) {
        thc2 = make_shared<TaraxaCapability>(host, network_conf);
        return Host::CapabilityList{thc2};
      },
      KeyPair::create(), prefs2);
  util::ThreadPool tp;
  tp.post_loop({}, [=] { host1->do_work(); });
  tp.post_loop({}, [=] { host2->do_work(); });
  thc1->start();
  thc2->start();

  auto port1 = host1->listenPort();
  auto port2 = host2->listenPort();
  EXPECT_NE(port1, 0);
  EXPECT_NE(port2, 0);
  EXPECT_NE(port1, port2);

  host1->addNode(
      Node(host2->id(), NodeIPEndpoint(bi::address::from_string(localhost), port2, port2), PeerType::Required));

  // Wait for up to 12 seconds, to give the hosts time to connect to each
  // other.
  for (unsigned i = 0; i < 12000; i += step) {
    this_thread::sleep_for(chrono::milliseconds(step));

    if ((host1->peer_count() > 0) && (host2->peer_count() > 0)) break;
  }

  EXPECT_GT(host1->peer_count(), 0);
  EXPECT_GT(host2->peer_count(), 0);

  int const target = 5;
  int checksum = 0;
  std::vector<char> dummy_data(10 * 1024 * 1024);  // 10MB memory buffer
  for (int i = 0; i < target; checksum += i++) thc2->sendTestMessage(host1->id(), i, dummy_data);

  this_thread::sleep_for(chrono::seconds(target / 2));
  std::pair<int, int> testData = thc1->retrieveTestData(host2->id());
  EXPECT_EQ(target, testData.first);
  EXPECT_EQ(checksum, testData.second);
}

/*
Test creates two host/network/capability and verifies that host connect
to each other and that a block packet message can be sent from one host
to the other using TaraxaCapability
*/

TEST_F(P2PTest, capability_send_block) {
  int const step = 10;
  const char *const localhost = "127.0.0.1";
  dev::p2p::NetworkConfig prefs1(localhost, 10007, false, true);
  prefs1.discovery = false;
  dev::p2p::NetworkConfig prefs2(localhost, 10003, false, true);
  prefs2.discovery = false;
  NetworkConfig network_conf;
  network_conf.network_simulated_delay = 0;
  network_conf.network_bandwidth = 40;
  network_conf.network_transaction_interval = 1000;
  shared_ptr<TaraxaCapability> thc1, thc2;
  auto host1 = Host::make(
      "Test",
      [&](auto host) {
        thc1 = make_shared<TaraxaCapability>(host, network_conf);
        return Host::CapabilityList{thc1};
      },
      KeyPair::create(), prefs1);
  auto host2 = Host::make(
      "Test",
      [&](auto host) {
        thc2 = make_shared<TaraxaCapability>(host, network_conf);
        return Host::CapabilityList{thc2};
      },
      KeyPair::create(), prefs2);
  util::ThreadPool tp;
  tp.post_loop({}, [=] { host1->do_work(); });
  tp.post_loop({}, [=] { host2->do_work(); });
  thc1->start();
  thc2->start();
  auto port1 = host1->listenPort();
  auto port2 = host2->listenPort();
  EXPECT_NE(port1, 0);
  EXPECT_NE(port2, 0);
  EXPECT_NE(port1, port2);

  host1->addNode(
      Node(host2->id(), NodeIPEndpoint(bi::address::from_string(localhost), port2, port2), PeerType::Required));

  // Wait for up to 12 seconds, to give the hosts time to connect to each
  // other.
  for (unsigned i = 0; i < 12000; i += step) {
    this_thread::sleep_for(chrono::milliseconds(step));

    if ((host1->peer_count() > 0) && (host2->peer_count() > 0)) break;
  }

  EXPECT_GT(host1->peer_count(), 0);
  EXPECT_GT(host2->peer_count(), 0);

  DagBlock blk(blk_hash_t(1111), 0, {blk_hash_t(222), blk_hash_t(333), blk_hash_t(444)},
               {g_signed_trx_samples[0].getHash(), g_signed_trx_samples[1].getHash()}, sig_t(7777), blk_hash_t(888),
               addr_t(999));

  std::vector<taraxa::bytes> transactions;
  transactions.emplace_back(*g_signed_trx_samples[0].rlp());
  transactions.emplace_back(*g_signed_trx_samples[1].rlp());
  thc2->onNewTransactions(transactions, true);
  thc2->sendBlock(host1->id(), blk);

  this_thread::sleep_for(chrono::seconds(1));
  auto blocks = thc1->getBlocks();
  auto rtransactions = thc1->getTransactions();
  EXPECT_EQ(blocks.size(), 1);
  if (blocks.size()) {
    EXPECT_EQ(blk, blocks.begin()->second);
  }
  EXPECT_EQ(rtransactions.size(), 2);
  if (rtransactions.size() == 2) {
    EXPECT_EQ(Transaction(transactions[0]), rtransactions[g_signed_trx_samples[0].getHash()]);
    EXPECT_EQ(Transaction(transactions[1]), rtransactions[g_signed_trx_samples[1].getHash()]);
  }
}

/*
Test creates 50 host/network/capability which connect to each other
using node discovery. Block is created on one host and automatically
propagated to all other hosts. Test verifies that each node has received
the block
*/
TEST_F(P2PTest, block_propagate) {
  int const nodeCount = 10;
  const char *const localhost = "127.0.0.1";
  dev::p2p::NetworkConfig prefs1(localhost, 10007, false, true);
  std::vector<dev::p2p::NetworkConfig> vPrefs;
  for (int i = 0; i < nodeCount; i++) {
    vPrefs.push_back(dev::p2p::NetworkConfig(localhost, 10007 + i + 1, false, true));
  }
  TaraxaNetworkConfig taraxa_net_conf_1;
  taraxa_net_conf_1.is_boot_node = true;
  NetworkConfig network_conf;
  network_conf.network_simulated_delay = 0;
  network_conf.network_bandwidth = 40;
  network_conf.network_transaction_interval = 1000;
  shared_ptr<TaraxaCapability> thc1;
  auto host1 = Host::make(
      "Test",
      [&](auto host) {
        thc1 = make_shared<TaraxaCapability>(host, network_conf);
        thc1->start();
        return Host::CapabilityList{thc1};
      },
      KeyPair::create(), prefs1, taraxa_net_conf_1);
  util::ThreadPool tp;
  tp.post_loop({}, [=] { host1->do_work(); });
  std::vector<shared_ptr<Host>> vHosts;
  std::vector<std::shared_ptr<TaraxaCapability>> vCapabilities;
  for (int i = 0; i < nodeCount; i++) {
    auto host = vHosts.emplace_back(Host::make(
        "Test",
        [&](auto host) {
          auto cap = vCapabilities.emplace_back(make_shared<TaraxaCapability>(host, network_conf));
          cap->start();
          return Host::CapabilityList{cap};
        },
        KeyPair::create(), vPrefs[i]));
    tp.post_loop({}, [=] { host->do_work(); });
  }
  printf("Starting %d hosts\n", nodeCount);
  auto port1 = host1->listenPort();
  EXPECT_NE(port1, 0);
  for (int i = 0; i < nodeCount; i++) {
    EXPECT_NE(vHosts[i]->listenPort(), 0);
    EXPECT_NE(port1, vHosts[i]->listenPort());
    for (int j = 0; j < i; j++) EXPECT_NE(vHosts[j]->listenPort(), vHosts[i]->listenPort());
  }

  for (int i = 0; i < nodeCount; i++) {
    if (i < 10)
      vHosts[i]->addNode(Node(host1->id(), NodeIPEndpoint(bi::address::from_string(localhost), port1, port1)));
    else
      vHosts[i]->addNode(
          Node(vHosts[i % 10]->id(), NodeIPEndpoint(bi::address::from_string(localhost), vHosts[i % 10]->listenPort(),
                                                    vHosts[i % 10]->listenPort())));
    this_thread::sleep_for(chrono::milliseconds(20));
  }

  printf("Addnode %d hosts\n", nodeCount);

  // Wait for to give the hosts time to connect to each
  // other.
  bool connected = false;
  for (unsigned i = 0; i < 500; i++) {
    this_thread::sleep_for(chrono::milliseconds(100));
    connected = true;
    int counterConnected = 0;
    for (int j = 0; j < nodeCount; j++)
      if (vHosts[j]->peer_count() < 1)
        connected = false;
      else
        counterConnected++;
    // printf("Addnode %d connected\n", counterConnected);

    if ((host1->peer_count() > 0) && connected) break;
  }
  EXPECT_TRUE(connected);
  EXPECT_GT(host1->peer_count(), 0);

  DagBlock blk(blk_hash_t(1111), 0, {blk_hash_t(222), blk_hash_t(333), blk_hash_t(444)},
               {g_signed_trx_samples[0].getHash(), g_signed_trx_samples[1].getHash()}, sig_t(7777), blk_hash_t(0),
               addr_t(999));

  std::vector<taraxa::bytes> transactions;
  transactions.emplace_back(*g_signed_trx_samples[0].rlp());
  transactions.emplace_back(*g_signed_trx_samples[1].rlp());
  thc1->onNewTransactions(transactions, true);
  std::vector<Transaction> transactions2;
  thc1->onNewBlockReceived(blk, transactions2);

  for (int i = 0; i < 50; i++) {
    this_thread::sleep_for(chrono::seconds(1));
    bool synced = true;
    for (int j = 0; j < nodeCount; j++)
      if (vCapabilities[j]->getBlocks().size() == 0) {
        synced = false;
      }
    if (synced) break;
  }
  auto blocks1 = thc1->getBlocks();
  for (int i = 0; i < nodeCount; i++) {
    EXPECT_EQ(vCapabilities[i]->getBlocks().size(), 1);
    if (vCapabilities[i]->getBlocks().size() == 1) {
      EXPECT_EQ(vCapabilities[i]->getBlocks().begin()->second, blk);
      EXPECT_EQ(vCapabilities[i]->getBlocks().begin()->second.getHash(), blk.getHash());
    }
    auto rtransactions = vCapabilities[i]->getTransactions();
    EXPECT_EQ(rtransactions.size(), 2);
    if (rtransactions.size() == 2) {
      EXPECT_EQ(Transaction(transactions[0]), rtransactions[g_signed_trx_samples[0].getHash()]);
      EXPECT_EQ(Transaction(transactions[1]), rtransactions[g_signed_trx_samples[1].getHash()]);
    }
  }
  EXPECT_EQ(blocks1.size(), 1);
  if (blocks1.size()) {
    EXPECT_EQ(blk, blocks1.begin()->second);
  }
}
}  // namespace taraxa::core_tests

using namespace taraxa;
int main(int argc, char **argv) {
  static_init();
  auto logging = logger::createDefaultLoggingConfig();
  logging.verbosity = logger::Verbosity::Error;

  addr_t node_addr;
  logger::InitLogging(logging, node_addr);

  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

max_stars_repo_name: agrebin/taraxa-node

max_issues_repo_name: agrebin/taraxa-node

max_forks_repo_name: agrebin/taraxa-node


text:
#include "sleep.hpp"

#include <boost/thread.hpp>

namespace lourdes { namespace cpu {

void sleep(int milliseconds)
{
    boost::this_thread::sleep(boost::posix_time::milliseconds(milliseconds));
}

}}

max_stars_repo_name: perezdidac/lourdes

max_issues_repo_name: perezdidac/lourdes

max_forks_repo_name: perezdidac/lourdes


text:
/**
 * Variable ordering for the independent set problem
 */

#ifndef INDEPSET_ORDERINGS_HPP_
#define INDEPSET_ORDERINGS_HPP_

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/discrete_distribution.hpp>

#include "../../core/order.hpp"
#include "indepset_instance.hpp"
#include "indepset_state.hpp"

using namespace std;

/** Return an ordering for the independent set problem given an id */
Ordering* get_ordering_by_id_indepset(int id, IndepSetInstance* inst, Options& options);

// Vertex that it is in the least number of states - with option to choose randomly with probability (1-prob)
struct MinInState : Ordering {

	IndepSetInstance* inst;
	boost::random::mt19937 gen;
	int* in_state_counter;          /**< number of states containing each variable */
	double prob;			        /**< probability min in state is applied (otherwise random) */

	MinInState(IndepSetInstance* _inst, double _prob = 1) : inst(_inst), prob(_prob)
	{
		sprintf(name, "min_in_state");

		assert(prob >= 0 && prob <= 1);
		if (prob < 1) {
			gen.seed(inst->graph->n_vertices + inst->graph->n_edges);
		}

		in_state_counter = new int[inst->graph->n_vertices];
	}

	~MinInState()
	{
		delete[] in_state_counter;
	}

	int select_next_var(int layer);
	int select_vertex_with_min_in_state(int layer);
	int select_vertex_randomly(int layer);

	void cb_initialize();
	void cb_state_created(State* state);
	void cb_state_removed(State* state);
};

// Maximal Path Decomposition
struct MaximalPathDecomp : Ordering {

	IndepSetInstance* inst;
	vector<int> v_in_layer;   // vertex at each layer

	MaximalPathDecomp(IndepSetInstance* _inst) : inst(_inst)
	{
		sprintf(name, "maxpath");
		construct_ordering();
	}

	int select_next_var(int layer)
	{
		assert(layer >= 0 && layer < inst->graph->n_vertices);
		return v_in_layer[layer];
	}

private:
	void construct_ordering();
};

// Minimum degree ordering
struct MinDegreeOrdering : Ordering {

	IndepSetInstance* inst;
	vector<int> v_in_layer;   // vertex at each layer

	MinDegreeOrdering(IndepSetInstance* _inst) : inst(_inst)
	{
		sprintf(name, "mindegree");
		construct_ordering();
	}

	int select_next_var(int layer)
	{
		assert(layer >= 0 && layer < inst->graph->n_vertices);
		return v_in_layer[layer];
	}

private:
	void construct_ordering();
};

// Cut vertex decomposition
struct CutVertexDecomposition : Ordering {

	IndepSetInstance* inst;
	vector<int> v_in_layer;      // vertex at each layer
	bool** original_adj_matrix;

	CutVertexDecomposition(IndepSetInstance* _inst, bool general = true) : inst(_inst)
	{
		sprintf(name, "cut-vertex");
		v_in_layer.resize(inst->graph->n_vertices);

		// If a general graph (not a tree), take a spanning tree
		if (general) {
			restrict_graph();
		}
		construct_ordering();
		if (general) {
			regenerate_graph();
		}
	}

	int select_next_var(int layer)
	{
		assert(layer >= 0 && layer < inst->graph->n_vertices);
		return v_in_layer[layer];
	}

private:
	void        restrict_graph();
	void        regenerate_graph();
	void        construct_ordering();
	void        identify_components(vector< vector<int> >& comps, vector<bool>& is_in_graph);
	vector<int> find_ordering(vector<bool> is_in_graph);
};

#endif

ext: hpp

max_stars_repo_name: ctjandra/ddopt-cut

max_issues_repo_name: ctjandra/ddopt-cut

max_forks_repo_name: ctjandra/ddopt-cut


text:
//==============================================================================
//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#include <nt2/include/functions/tand.hpp>

#include <boost/dispatch/functor/meta/call.hpp>
#include <nt2/sdk/functor/meta/call.hpp>
#include <nt2/sdk/unit/tests/relation.hpp>
#include <nt2/sdk/unit/tests/type_expr.hpp>
#include <complex>
#include <nt2/sdk/complex/complex.hpp>
#include <nt2/sdk/unit/tests/ulp.hpp>
#include <nt2/sdk/unit/tests/basic.hpp>
#include <nt2/sdk/meta/as_integer.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <boost/simd/sdk/config.hpp>

#include <nt2/include/constants/zero.hpp>
#include <nt2/include/constants/inf.hpp>
#include <nt2/include/constants/minf.hpp>
#include <nt2/include/constants/nan.hpp>
#include <nt2/include/constants/i.hpp>

#include <nt2/include/functions/mul_i.hpp>
#include <nt2/include/functions/mul_minus_i.hpp>

NT2_TEST_CASE_TPL ( tand,  NT2_REAL_TYPES)
{

  using nt2::tand;
  using nt2::tag::tand_;
  typedef std::complex<T> cT;
  typedef typename nt2::meta::call<tand_(cT)>::type r_t;
  typedef typename nt2:: meta::as_complex<T>::type wished_r_t;

  // return type conformity test
  NT2_TEST_TYPE_IS(r_t, wished_r_t);

  // specific values tests
  NT2_TEST_ULP_EQUAL(nt2::tand(cT(nt2::Inf<T>())), cT(nt2::Nan<T>()), 13);
  NT2_TEST_ULP_EQUAL(nt2::tand(cT(nt2::Minf<T>())), cT(nt2::Nan<T>()), 13);
  NT2_TEST_ULP_EQUAL(nt2::tand(cT(1, 1)),std::tan(nt2::Deginrad<T>()*cT(1.0, 1.0)), 13);
  NT2_TEST_ULP_EQUAL(nt2::tand(cT(1, 0.3)),std::tan(nt2::Deginrad<T>()*cT(1.0, 0.3)), 13);
  NT2_TEST_ULP_EQUAL(nt2::tand(cT(0.3, 1)),std::tan(nt2::Deginrad<T>()*cT(0.3, 1.0)), 13);
  NT2_TEST_ULP_EQUAL(nt2::tand(cT(0.3, 0.3)),std::tan(nt2::Deginrad<T>()*cT(0.3, 0.3)), 13);
  NT2_TEST_ULP_EQUAL(nt2::tand(cT(0, 1)),std::tan(nt2::Deginrad<T>()*cT(0.0, 1.0)), 13);
  NT2_TEST_ULP_EQUAL(nt2::tand(cT(0, 0.3)),std::tan(nt2::Deginrad<T>()*cT(0.0, 0.3)), 13);
  NT2_TEST_ULP_EQUAL(nt2::tand(cT(0.3, 0)),std::tan(nt2::Deginrad<T>()*cT(0.3, 0.0)), 13);

  const int N = 20;
  cT inputs[N] =
    { cT(nt2::Zero<T>(),nt2::Zero<T>()),cT(nt2::Inf<T>(),nt2::Zero<T>()),cT(nt2::Minf<T>(),nt2::Zero<T>()),cT(nt2::Nan<T>(),nt2::Zero<T>()),
      cT(nt2::Zero<T>(),nt2::Inf<T>()), cT(nt2::Inf<T>(),nt2::Inf<T>()), cT(nt2::Minf<T>(),nt2::Inf<T>()), cT(nt2::Nan<T>(),nt2::Inf<T>()),
      cT(nt2::Zero<T>(),nt2::Minf<T>()),cT(nt2::Inf<T>(),nt2::Minf<T>()),cT(nt2::Minf<T>(),nt2::Minf<T>()),cT(nt2::Nan<T>(),nt2::Minf<T>()),
      cT(nt2::Zero<T>(),nt2::Nan<T>()), cT(nt2::Inf<T>(),nt2::Nan<T>()), cT(nt2::Minf<T>(),nt2::Nan<T>()), cT(nt2::Nan<T>(),nt2::Nan<T>()),
      cT(nt2::Zero<T>(),180), cT(nt2::Inf<T>(),180), cT(nt2::Minf<T>(),180), cT(nt2::Nan<T>(),180),
    };

  for(int i=0; i < N; i++)
   {
     std::cout << "-------------------" << std::endl;
     std::cout << "inputs  "<< inputs[i] << std::endl;
     NT2_TEST_ULP_EQUAL(nt2::tand(-inputs[i]), -nt2::tand(inputs[i]), 3);
     NT2_TEST_ULP_EQUAL(nt2::tand(inputs[i]), nt2::mul_minus_i(nt2::tanh(nt2::mul_i(nt2::multiplies(nt2::Deginrad<T>(), inputs[i])))), 3);
     std::cout << "=================== " << std::endl;
   }

 } // end of test for floating_


text: #include <boost/mpl/aux_/config/msvc.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#pragma once

#ifndef DATASTREAM_HPP
#define DATASTREAM_HPP

#include <hyper/algorithm.hpp>
#include <hyper/toolkit/clustered_vector.hpp>
#include <hyper/toolkit/string.hpp>

#ifdef AIDA_MODULE_GPU
#include "AIDA/kernel.hpp"
#endif

#include <boost/filesystem.hpp>

#define DATA_READOUT_REFRESH 1.0f/24
#define STREAM_SCAN_BUFFER_SIZE 1000000
#define STREAM_SEARCH_BUFFER_SIZE 300000
#define STREAM_CACHE_SHORT_SEARCH_LIMIT 100

#define ORIENTATION_NONE                0_BIT
#define ORIENTATION_ROW                 1_BIT
#define ORIENTATION_COLUMN              2_BIT
#define ORIENTATION_UNKNOWN             3_BIT

namespace hyperC
{

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

// Typedefs

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

typedef std::vector<unsigned int>                   dimArray;
typedef std::vector<std::vector<unsigned int>>      dimMatrix;
typedef std::vector<unsigned int>                   uint_v;
typedef std::vector<std::vector<unsigned int>>      uint_m;

typedef std::vector<std::string>                    tagList;
typedef hyperC::VectorPair<std::string>                pairedTags;
typedef std::vector<hyperC::Vector2<unsigned int>>     pairedCoords;
typedef hyperC::Vector2<float>                         Vector2f;
typedef hyperC::Vector2<unsigned int>                  Vector2u;

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

// Stream classes

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

class _2Dstream;

class _1Dstream{
protected:

    FILE* stream;
    std::string streamFile;
    unsigned int entrySize, byteSize;
    std::vector<uint16_t> dataSizes;
    std::vector<uint32_t> dataIndex;
    std::vector<std::reference_wrapper<const std::string>> dataRefs;

    char* readBuffer;
    bool bIsReference; // If stream was extracted from another stream, access by data references

    void update();
    void getEntrySize();

public:

    inline const unsigned int& size() const{ return entrySize; }
    inline char *const readbuf() const { return readBuffer; }

    inline bool empty() const{ return entrySize == 0; }

    inline void reset(){
        fclose(stream);
        dataIndex.erase(dataIndex.begin(), dataIndex.end());
        dataSizes.erase(dataSizes.begin(), dataSizes.end());
    }

    void get(const unsigned int& i) const;
    std::string getString(const unsigned int& i) const;
    float getFloat(const unsigned int& i) const;

    void import(std::vector<std::string>& storage) const;

    bool check(const std::string& target) const;
    bool find(uint_v& output, const std::string& target) const;
    unsigned int getIndex(const std::string& query) const;

    std::string operator[](const unsigned int& i) const;
    float operator()(const unsigned int& i) const;
    _1Dstream operator[](const std::vector<unsigned int>& index);
    _1Dstream substream(const std::vector<unsigned int>& index);
    _1Dstream& reduce(const std::vector<unsigned int>& index);

    void openStream(const std::string& streamFile);

    friend std::ostream& operator<<(std::ostream& output, _1Dstream other){
        for(size_t i = 0; i < other.entrySize; ++i){
            output << other.getString(i);
            if(i < other.entrySize - 1) output << '\t';
        }
        return output;
    }

    _1Dstream& operator=(const _1Dstream& other);

    _1Dstream(const _1Dstream& other);
    _1Dstream(const std::string& filename, const std::vector<uint32_t>& dataIndex, const std::vector<uint16_t>& dataSizes);
    _1Dstream(const _2Dstream& dataset, const unsigned int& index, const bool& row);
    _1Dstream(const _1Dstream& other, const std::vector<unsigned int>& index);

    ~_1Dstream(){
        if(readBuffer != nullptr) delete[] readBuffer;
        if(stream != nullptr) fclose(stream); }

};

struct coord_string : public std::string
{
    coord_string(const std::string str,
                 const Vector2u coords):
        std::string(str),
        coords(coords){ }

    coord_string(const std::string& str,
                 const unsigned int& x,
                 const unsigned int& y):
        std::string(str),
        coords(x, y){ }

    inline friend std::ostream& operator<<(std::ostream& output, const coord_string& input)
    {
        return output << input.c_str() << '[' << input.coords.x << ',' << input.coords.y << ']';
    }

    hyperC::Vector2u coords;
};

class _2Dstream{
protected:

    FILE*                       stream;

    std::string                 streamFile;

    unsigned long long          streamSize;

    unsigned int                numRows;
    unsigned int                numColumns;

    char*                       readBuffer;     // Search buffer - pre-allocate for rapid search

    std::string                 delim;          // Delimiting characters (may be more than one)

    uint8_t                     cached_alignment;

    dimArray                    rowSizes;
    dimArray                    rowDataSizes;

    hyperC::vMatrix<uint16_t>      indexSizes;
    hyperC::vMatrix<uint32_t>      indexPos;

    bool verbose;
    bool active;                                // Prevent conflicts between separate processes using this stream
    bool imported;                              // Switch access modes if dataset has been loaded into RAM
    bool bOpen;                                 // Has a connection been established?

    std::vector<coord_string> coord_index;
    hyperC::tree_vector<char, coord_string> *       search_index;

public:

    void reset();
    inline void close(){ reset(); }
    inline const bool& isOpen() const noexcept{ return bOpen; }

    void reload();
    void index(const int& max_levels = 1000);   // Create a search index to speed up repeated find operations

    void update();

    inline bool empty() const{ return rowSizes.empty(); }

    std::vector<std::vector<std::string>> importData; // Import matrix - copy data to RAM for rapid-access tasks, and for writing

    inline char *const readbuf() const{ return readBuffer; }

    inline const bool& isActive() const{ return active; }
    inline const bool& isImported() const{ return imported; }

    inline const unsigned int& rowSize(const unsigned int& row) const{ return rowSizes[row]; }
    inline const unsigned int& rowDataSize(const unsigned int& row) const{ return rowDataSizes[row]; }
    unsigned int maxRowSize() const noexcept;

    size_t getCharCount(const std::string& chars) const;

    unsigned int colSize(const unsigned int& col) const;

    inline const std::vector<uint16_t>& getRowIndexSizes(const unsigned int& row) const{ return indexSizes[row]; }
    inline const std::vector<uint32_t>& getRowIndexPos(const unsigned int& row) const{ return indexPos[row]; }

    inline const uint16_t& size_of(const unsigned int& x, const unsigned int& y) const{ return indexSizes[y][x]; }
    inline const uint32_t& position(const unsigned int& x, const unsigned int& y) const{ return indexPos[y][x]; }

    inline const unsigned int& nrow() const{ return numRows; }
    inline const unsigned int& ncol() const{ return numColumns; }

    inline void setVerbose(bool verboseStatus){ verbose = verboseStatus; }

    const unsigned long long size() const{ return streamSize; }

    _1Dstream getRow(const unsigned int& row) const;
    _1Dstream getCol(const unsigned int& col) const;

    /** @brief Get the index of a column by string matching. */
    size_t column_index(const std::string& header) const;

    /** @brief Get the index of a row by string matching. */
    size_t row_index(const std::string& row_name) const;

    void importRow(std::vector<std::string>& storage, const unsigned int& row) const;
    void importCol(std::vector<std::string>& storage, const unsigned int& col) const;
    void import();  // Load stream data into RAM and perform further operations on it
    void release(); // Deallocate imported data and return to pure stream status

    _1Dstream operator[](const unsigned int& y) const;
    _1Dstream operator[](const std::string& x) const;

    _2Dstream operator[](const std::vector<unsigned int>& rows) const;
    _2Dstream operator[](const hyperC::VectorPair<unsigned int>& bounds) const;

    bool find(hyperC::VectorPairU& output, const std::string& target, const float& size_threshold = 0.1f,
              const float& match_threshold = 1.0f);
    Vector2u getCoords(const std::string& target, const float& threshold = 0.1f);
    unsigned int findRow(const std::string& target, const float& size_threshold = 0.1f);
    unsigned int findCol(const std::string& target, const float& size_threshold = 0.1f);

    bool check(const std::string& target,
               const float& threshold = 0.1f,
               const float& match_threshold = 1.0f) const;
    std::string findMatch(const std::string& target, const float& threshold = 0.1f);
    unsigned int getCount(const std::string& query, bool exact = true, const float& threshold = 0.1f);

    void get(const unsigned int& x, const unsigned int& y) const; // Returns copied data - must delete pointer after every call
    std::string getString(const unsigned int& x,
                          const unsigned int& y) const;
    template<typename T> std::string getString(const hyperC::Vector2<T>& coords) const{
        return getString((unsigned int)coords.x, (unsigned int)coords.y);
    }
    float getFloat(const unsigned int& x, const unsigned int& y) const;

    bool openStream(const boost::filesystem::path& filePath, const bool& update = true,
                    const std::string& delim = ""){
            return openStream(filePath.string(), update); }
    bool openStream(const std::string& filename, const bool& update = true,
                    const std::string& delim = "");
    inline const std::string& getSourceFile() const{ return streamFile; }

    friend std::ostream& operator<<(std::ostream& output, const _2Dstream& other){
        for(size_t i = 0; i < other.nrow(); ++i){
            for(size_t j = 0; j < other.ncol(); ++j){
                if(j >= other.rowSizes[i]) break;
                output << other.getString(j, i);
                if((other.rowSizes[i] > 1) && (j < other.rowSizes[i] - 1)) output << '\t';
            }
            output << '\n';
        }
        return output;
    }

    _2Dstream(const _2Dstream& other); // Copy constructor - duplicates info but opens entirely new stream
    _2Dstream& operator=(const _2Dstream& other);

    explicit _2Dstream();
    explicit _2Dstream(const std::string& filename, const bool& verbose = true,
                       const std::string& delim = "");
    explicit _2Dstream(std::string filename, hyperC::vMatrix<uint32_t>& indexPos,
                       hyperC::vMatrix<uint16_t>& indexSizes,
                    dimArray& rowSizes, dimArray& rowDataSizes,
                    const std::string& delim);

    ~_2Dstream(){
        if(readBuffer) delete[] readBuffer;
        if(stream) fclose(stream);
        if(search_index) delete(search_index);
    }
};

inline size_t nrow(const _2Dstream& stream){
    return stream.nrow();
}

inline size_t ncol(const _2Dstream& stream){
    return stream.ncol();
}

inline size_t rowSize(const _2Dstream& stream, const unsigned int& index){
    return stream.rowSize(index);
}

typedef _2Dstream matrixStream;
typedef _2Dstream m_stream;
typedef _1Dstream vectorStream;
typedef _1Dstream v_stream;

// Datastream functions

inline unsigned int numDelim(char* c, const unsigned int L){
    unsigned int delimCount = 0;
    char* newC = c;
    for(size_t i = 0; i < L; ++i, ++newC){
        if((*newC == '\t') || (*newC == '\n')) ++delimCount;
    }
    return delimCount;
}

bool isNumeric(const _1Dstream& stream, const unsigned int index);

std::string getMatchingString(const std::string& query, _2Dstream& stream);
Vector2u getBestStreamMatch(hyperC::VectorPairU& coords,
                            _2Dstream& stream,
                            const std::string& target,
                            const unsigned char& params = CMP_STR_DEFAULT | CMP_STR_SW,
                            const float& threshold = 0.5f);
void getBestStreamMatchCoords(hyperC::VectorPairU& coords, _2Dstream& stream, const std::string& target);

bool filterStreamMatch(std::vector<std::string>& prompt, _2Dstream& stream, bool getMatches = true);
bool checkAnyStreamMatch(std::vector<std::string>& query, _2Dstream& stream, bool getMatches = false);

// Get orientation of search results relative to data center
uint8_t getSearchOrientation(const std::string& query, _2Dstream& dataSource);

// Assess alignment of coordinates given back by a stream search query
uint8_t assessCoordAlignment(const hyperC::VectorPairU& coords, _2Dstream& dataSource); // Relative to global boundaries
uint8_t assessCoordAlignment(const hyperC::VectorPairU& inCoords, const hyperC::VectorPairU& outCoords); // Relative to other coordinates
uint8_t assessCoordAlignment(const hyperC::VectorPairU& coords); // Relative to self

// Data visualization

//class _2DStreamDataViewer: public CVViewPanel{
//protected:
//public:
//
//    _2DStreamDataViewer()
//};

}

#endif // DATASTREAM_HPP

max_stars_repo_name: DamianTran/hyper

max_issues_repo_name: DamianTran/hyper

max_forks_repo_name: DamianTran/hyper


text:
/******************************************************************************
 * Copyright 2017-2018 Baidu Robotic Vision Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/
#include "stdafx.h"
#include "Intrinsic.h"
#include "Parameter.h"
#include <Eigen/Core>

#include <iostream>
#ifdef CFG_DEBUG
//#define FTR_UNDIST_VERBOSE  1
//#define FTR_UNDIST_VERBOSE  2
#endif
#define FTR_UNDIST_DOG_LEG

void Intrinsic::UndistortionMap::Set(const Intrinsic &K) {
  const float sx = float(FTR_UNDIST_LUT_SIZE - 1) / K.w();
  const float sy = float(FTR_UNDIST_LUT_SIZE - 1) / K.h();
  m_fx = sx * K.k().m_fx; m_fy = sy * K.k().m_fy;//将图片缩放到FTR_UNDIST_LUT_SIZE×FTR_UNDIST_LUT_SIZEsize,然后进行畸变表的存储
  m_cx = sx * K.k().m_cx; m_cy = sy * K.k().m_cy;
  const float fxI = 1.0f / m_fx, fyI = 1.0f / m_fy;
  m_xns.Resize(FTR_UNDIST_LUT_SIZE, FTR_UNDIST_LUT_SIZE);//11*11这个在干吗？

#ifdef FTR_UNDIST_VERBOSE
  UT::PrintSeparator();
#endif
  Point2D xd, xn;
  float v;
  int x[2] = {FTR_UNDIST_LUT_SIZE / 2, FTR_UNDIST_LUT_SIZE / 2};
  int b[2][2] = {{x[0] - 1, x[0] + 1}, {x[1] - 1, x[1] + 1}};
  const int d[2] = {-1, 1};
  const int N = m_xns.Size();
  for(int i = 0, ix = 0, id = 0; i < N; ++i) {
    xd.x() = fxI * (x[0] - m_cx);
    xd.y() = fyI * (x[1] - m_cy);
    if (i == 0) {
      xn = xd;
    } else {
      xn = xd * v;
    }
    if (!K.Undistort(xd, &xn, NULL, NULL, true)) {
        continue;
//      exit(0);
    }
    v = sqrtf(xn.SquaredLength() / xd.SquaredLength());//大概的一个畸变比例
//#ifdef CFG_DEBUG
#if 0
    xn.x() = v;
#endif
    m_xns[x[1]][x[0]] = xn;//对应的无畸变的归一化坐标的值
//#ifdef CFG_DEBUG
#if 0
    //UT::Print("%d %d\n", x[0], x[1]);
    const float s = 0.5f;
    const int _w = K.gyr(), _h = K.h();
    const float _fx = K.fx() * s, _fy = K.fy() * s;
    const float _cx = (_w - 1) * 0.5f, _cy = (_h - 1) * 0.5f;
    CVD::Image<CVD::Rgb<ubyte> > I;
    I.resize(CVD::ImageRef(_w, _h));
    I.zero();
    UT::ImageDrawCross(I, int(_fx * xd.x() + _cx), int(_fy * xd.y() + _cy), 5, CVD::Rgb<ubyte>(255, 0, 0));
    UT::ImageDrawCross(I, int(_fx * xn.x() + _cx), int(_fy * xn.y() + _cy), 5, CVD::Rgb<ubyte>(0, 255, 0));
    UT::ImageSave(UT::String("D:/tmp/test%04d.jpg", i), I);
#endif
    //这里就是把 0,0 - 10,10范围内的都遍历一遍,这些像素点假设是带畸变的,m_xns保存的是对应的无畸变的归一话坐标的值
    if (x[ix] == b[ix][id]) {
      b[ix][id] += d[id];
      ix = 1 - ix;
      if (ix == 0) {
        id = 1 - id;
      }
    }
    x[ix] += d[id];
  }
#ifdef FTR_UNDIST_VERBOSE
  UT::PrintSeparator();
#endif
}
//去畸变,如果没有UndistortionMap畸变对照表的时候,需要将图片缩到FTR_UNDIST_LUT_SIZE*FTR_UNDIST_LUT_SIZE去做畸变对照。
//如果没有UndistortionMap输入或者生成UndistortionMap的时候,会用dogleg方法进行迭代求解。如果用了UndistortionMap作为初值的话,就用G-N求解即可
bool Intrinsic::Undistort(const Point2D &xd/*归一化坐标前两维*/, Point2D *xn/*待优化变量,最终反映的是无失真归一化坐标*/,
        LA::AlignedMatrix2x2f *JT/*畸变的雅克比J.t*/,UndistortionMap *UM/*畸变对应表*/, const bool initialized) const {
#ifdef CFG_DEBUG
  if (FishEye()) {
    UT::Error("TODO (haomin)\n");
  }
#endif
  if (!NeedUndistortion()) {//如果不需要去畸变
    *xn = xd;
    JT->MakeIdentity();
    return true;
  }
  float dr, j, dx2;
  LA::AlignedMatrix2x2f J;
  LA::SymmetricMatrix2x2f A;
  LA::AlignedMatrix2x2f AI;
  LA::Vector2f e, dx;//e就是残差
#ifdef FTR_UNDIST_DOG_LEG
  float dx2GN/*G-N解出的步长的欧式距离*/, dx2GD/*pU点的欧式距离*/, delta2/*信赖域半径*/, beta;
  LA::Vector2f dxGN/*G-N解出的增量*/, dxGD/*pU点*/;
  bool update, converge ,success;
    success = false;
#endif
  if (UM) {//如果预先做了畸变表,然么就用这里的畸变作为初值
    if (UM->Empty()) {
      UM->Set(*this);//如果没有畸变表，需要生成,因为只是做初值,所以就用FTR_UNDIST_LUT_SIZE*FTR_UNDIST_LUT_SIZE去做就好了,
      // key是畸变的像素坐标,value是无畸变的归一化坐标的值
    }
    *xn = UM->Get(xd);//用畸变表里对应的无畸变的归一化坐标作为初值
//#ifdef CFG_DEBUG
#if 0
    *xn = xd * xn->x();
#endif
  } else if (!initialized) {
    *xn = xd;//给个初值
  }
#if defined FTR_UNDIST_VERBOSE && FTR_UNDIST_VERBOSE == 1
  const Point2D _xd = m_k.GetNormalizedToImage(xd);
  UT::Print("x = %03d %03d", int(_xd.x() + 0.5f), int(_xd.y() + 0.5f));
  UT::Print("  e = %f", sqrtf((GetDistorted(*xn) - xd).SquaredLength() * m_k.m_fx * m_k.m_fy));
#endif
  const float *ds/*0_k1,1_k2,2_p1,3_p2,4_k3,5_k4,6_k5,7_k6*/ = m_k.m_ds, *jds = m_k.m_jds;//jds就是为了雅克比计算村的参数
  const float dx2Conv = FTR_UNDIST_CONVERGE * fxyI();//收敛条件
  //const float dx2Conv = FTR_UNDIST_CONVERGE * m_k.m_fxyI;
#ifdef FTR_UNDIST_DOG_LEG
  delta2 = FTR_UNDIST_DL_RADIUS_INITIAL;//初始化一下信赖域半径
#endif
  for (int iIter = 0; iIter < FTR_UNDIST_MAX_ITERATIONS; ++iIter)
  {//最大迭代10次
#if 0
//#if 1
    if (UT::Debugging()) {
      UT::Print("%d %e %e\n", iIter, xn->x(), xn->y());
    }
#endif
    ////针对k1,k2,k3,p1,p2而言 r^2 = x^2 + y^2
    ////残差2*1 归一化坐标的2维： min F(x,y) = 0.5*r(x,y)^2 约束： x^2+y^2 <=
    ///      r.x = x*(1 + k1*r^2 + k2*r^4 + k3*r^6) + 2*p1*x*y + p2*(r^2 + 2*x^2) - x0
    ////     r.y = y*(1 + k1*r^2 + k2*r^4 + k3*r^6) + 2*p2*x*y + p1*(r^2 + 2*y^2) - y0
    ////迭代法求,这里用的狗腿。下面是雅克比矩阵J,代码里是先给J矩阵径向部分然后再给切向部分
    ////J00 = div(r.x)/div(x) = (1 + k1*r^2 + k2*r^4 + k3*r^6) + (k1 + 2*k2*r^2 + 3*k3*r^4)*2*x^2 + 2*p1*y + 6*p2*x
    ////J01 = div(r.x)/div(y) = (k1 + 2*k2*r^2 + 3*k3*r^4)*x*y + 2*p1*x + 2*p2*y
    ////J10 = div(r.y)/div(x) = (k1 + 2*k2*r^2 + 3*k3*r^4)*x*y + 2*p1*x + 2*p2*y
    ////J11 = div(r.y)/div(y) = (1 + k1*r^2 + k2*r^4 + k3*r^6) + (k1 + 2*k2*r^2 + 3*k3*r^4)*2*y^2 + 6*p1*y + 2*p2*x
    const float x = xn->x(), x2 = x * x, y = xn->y(), y2 = y * y, xy = x * y;
    if(!m_fishEye)
    {
        const float r2 = x2 + y2, r4 = r2 * r2, r6 = r2 * r4;
        dr = ds[4] * r6 + ds[1] * r4 + ds[0] * r2 + 1.0f;// 1 + k1*r^2 + k2*r^4 + k3*r^6
        j = jds[4] * r4 + jds[1] * r2 + ds[0];//k1 + 2*k2*r^2 + 3*k3*r^4
        if (m_radial6)
        {
            const float dr2I = 1.0f / (ds[7] * r6 + ds[6] * r4 + ds[5] * r2 + 1.0f);
            dr *= dr2I;
            j = (j - (jds[7] * r4 + jds[6] * r2 + ds[5]) * dr) * dr2I;
        }
        //进行径向畸变
        e.x() = dr * x;//x*(1 + k1*r^2 + k2*r^4 + k3*r^6)
        e.y() = dr * y;//y*(1 + k1*r^2 + k2*r^4 + k3*r^6)
        //先对径向畸变的雅克比进行赋值
        J.m00() = j * (x2 + x2) + dr;//(1 + k1*r^2 + k2*r^4 + k3*r^6) + (k1 + 2*k2*r^2 + 3*k3*r^4)*2*x^2
        J.m01() = j * (xy + xy);//(k1 + 2*k2*r^2 + 3*k3*r^4)*x*y
        J.m11() = j * (y2 + y2) + dr;//(1 + k1*r^2 + k2*r^4 + k3*r^6) + (k1 + 2*k2*r^2 + 3*k3*r^4)*2*y^2
//#ifdef CFG_DEBUG
#if 0
        J.m00() = 1 - 3 * x2 - y2;
    J.m01() = -2 * xy;
    J.m11() = 1 - x2 - 3 * y2;
#endif
        if (m_tangential) {
            //切向畸变部分
            const float dx = jds[2] * xy + ds[3] * (r2 + x2 + x2);//2*p1*x*y + p2*(r^2 + 2*x^2)
            const float dy = jds[3] * xy + ds[2] * (r2 + y2 + y2);//2*p2*x*y + p1*(r^2 + 2*y^2)
            e.x() = dx + e.x();//在径向畸变后进行切向畸变
            e.y() = dy + e.y();
            const float d2x = jds[2] * x, d2y = jds[2] * y;//
            const float d3x = jds[3] * x, d3y = jds[3] * y;
            J.m00() = d3x + d3x + d3x + d2y + J.m00();// 2*p1*y + 6*p2*x + 径向雅克比
            J.m01() = d2x + d3y + J.m01();//2*p1*x + 2*p2*y + 径向雅克比
            J.m11() = d3x + d2y + d2y + d2y + J.m11();//6*p1*y + 2*p2*x + 径向雅克比
        }
        J.m10() = J.m01();
    }else
    {
        ////针对k1,k2,k2,k3的等距投影模型, r^2 = x^2 + y^2
        ////残差2*1 归一化坐标的2维： min F(x,y) = 0.5*r(x,y)^2 约束： x^2+y^2 <=
        ///      r.x = x*(theta*(1 + k1*theta^2 + k2*theta^4 + k3 *theta^6 + k4*theta^8)/r) - x0
        ////     r.x = y*(theta*(1 + k1*theta^2 + k2*theta^4 + k3 *theta^6 + k4*theta^8)/r) - y0
        // distortion first:
        const float u0 = x;//x
        const float u1 = y;//y
        const float r = sqrt(u0 * u0 + u1 * u1);//r = sqrt(x^2 + y^2)
        const float theta = atan(r);
        const float theta2 = theta * theta;
        const float theta4 = theta2 * theta2;
        const float theta6 = theta4 * theta2;
        const float theta8 = theta4 * theta4;
        const float thetad = theta * (1 + ds[0] * theta2 + ds[1] * theta4 + ds[2] * theta6 + ds[3] * theta8);

        const float scaling = (r > 1e-8) ? thetad / r : 1.0;
        e.x() = scaling * u0;
        e.y() = scaling * u1;

        if (r > 1e-8){
            // mostly matlab generated...
            float t2;//x^2
            float t3;//y^2
            float t4;//r^2 = x^2+y^2
            float t6;//theta
            float t7;//theta^2
            float t8;// 1/r
            float t9;//theta^4
            float t11;// 1 / ((x^2+y^2) + 1.0);
            float t17;// (((k1_ * theta^2 + k2_ * theta^4) + k3_ * t7 * t9) + k4_ * (t9 * t9)) + 1.0
            float t18;
            float t19;
            float t20;
            float t25;

            t2 = u0 * u0;
            t3 = u1 * u1;
            t4 = t2 + t3;
            t6 = atan(sqrt(t4));
            t7 = t6 * t6;
            t8 = 1.0 / sqrt(t4);
            t9 = t7 * t7;
            t11 = 1.0 / ((t2 + t3) + 1.0);
            t17 = (((ds[0] * t7 + ds[1] * t9) + ds[2] * t7 * t9) + ds[3] * (t9 * t9)) + 1.0;
            t18 = 1.0 / t4;
            t19 = 1.0 / sqrt(t4 * t4 * t4);
            t20 = t6 * t8 * t17;
            t25 = ((ds[1] * t6 * t7 * t8 * t11 * u1 * 4.0
                    + ds[2] * t6 * t8 * t9 * t11 * u1 * 6.0)
                   + ds[3] * t6 * t7 * t8 * t9 * t11 * u1 * 8.0)
                  + ds[0] * t6 * t8 * t11 * u1 * 2.0;
            t4 = ((ds[1] * t6 * t7 * t8 * t11 * u0 * 4.0
                   + ds[2] * t6 * t8 * t9 * t11 * u0 * 6.0)
                  + ds[3] * t6 * t7 * t8 * t9 * t11 * u0 * 8.0)
                 + ds[0] * t6 * t8 * t11 * u0 * 2.0;
            t7 = t11 * t17 * t18 * u0 * u1;
            J.m01() = (t7 + t6 * t8 * t25 * u0) - t6 * t17 * t19 * u0 * u1;
            J.m11() = ((t20 - t3 * t6 * t17 * t19) + t3 * t11 * t17 * t18)
                      + t6 * t8 * t25 * u1;
            J.m00() = ((t20 - t2 * t6 * t17 * t19) + t2 * t11 * t17 * t18)
                      + t6 * t8 * t4 * u0;
            J.m10() = (t7 + t6 * t8 * t4 * u1) - t6 * t17 * t19 * u0 * u1;
        } else {
            J.m00() = 1;
            J.m01() = 0;
            J.m11() = 1;
            J.m10() = 0;
        }
    }
    e -= xd;//计算残差
    LA::SymmetricMatrix2x2f::AAT(J, A);//构造H矩阵
//#ifdef CFG_DEBUG
#if 0
    A.Set(J.m00(), J.m01(), J.m11());
#endif
    const LA::Vector2f b = J * e;//构造Ax = -b
    if (!A.GetInverse(AI)) {//求解A逆
      //return false;
      break;
    }

    LA::AlignedMatrix2x2f::Ab(AI, b, dx);//求解-x

      dx.MakeMinus();//求出x
      dx2 = dx.SquaredLength();//x的欧式距离
#ifdef FTR_UNDIST_DOG_LEG
    if (!UM)
    {
      dxGN = dx;//G-N法求出的增量
      dx2GN = dx2;//G-N法求出的增量的欧式距离
      dx2GD = 0.0f;//dogleg
      const float F = e.SquaredLength();//dogleg迭代开始前残差的欧式距离
      const Point2D xnBkp = *xn;//待优化变量
      update = true;
      converge = false;//狗腿迭代次数
      for (int iIterDL = 0; iIterDL < FTR_UNDIST_DL_MAX_ITERATIONS; ++iIterDL) {
        if (dx2GN > delta2 && dx2GD == 0.0f) {//如果G-N增量在信赖域外且dx2GD还没有初始化
          const float bl = sqrtf(b.SquaredLength());//模长
          const LA::Vector2f g = b * (1.0f / bl);//梯度方向
          const LA::Vector2f Ag = A * g;
          const float xl = bl / g.Dot(Ag);//计算pU点的步长
          g.GetScaled(-xl, dxGD);//负梯度*步长,pU点
          dx2GD = xl * xl;//pU点的半径
#ifdef CFG_DEBUG
         UT::AssertEqual(dxGD.SquaredLength(), dx2GD);
#endif
        }
        //三种情况,1：GN极值点在域内直接变成无约束条件 2:GN和pU点都在域外,那么就在给pU点的步长一个比例因子(域半径/自己的步长^2（因为用的是最小2乘）),让它刚好落在域半径上
        //3:GN在域外,pU点在域内,那么增量就是GN极值点和pU点的连线与信赖域的交点
        if (dx2GN <= delta2) {//如果G-N的极值在信赖域内,那么就是一个无约束问题,就直接用GN法求出的增量就可以
          dx = dxGN;
          dx2 = dx2GN;
          beta = 1.0f;
        } else if (dx2GD >= delta2) {//如果G-N和pU点求的最优点都在信赖域外
          if (delta2 == 0.0f) {//信赖域为0,直接用pU点求得最优值
            dx = dxGD;
            dx2 = dx2GD;
          } else {
            dxGD.GetScaled(sqrtf(delta2 / dx2GD), dx);//乘比例因子
            dx2 = delta2;
          }
          beta = 0.0f;
        } else {//GN在域外,pU点在域内,那么增量就是GN极值点和pU点的连线与信赖域的交点
          const LA::Vector2f v = dxGN - dxGD;//方向
          const float d = dxGD.Dot(v), v2 = v.SquaredLength();
          //beta = float((-d + sqrt(double(d) * d + (delta2 - dx2GD) * double(v2))) / v2);
          beta = (-d + sqrtf(d * d + (delta2 - dx2GD) * v2)) / v2;//算得是在域外那段连线的长度
          dx = dxGD;
          dx += v * beta;
          dx2 = delta2;
        }
        *xn += dx;//加上这一次的增量
        const float dFa = F - (GetDistorted(*xn) - xd).SquaredLength();//实际下降的
        const float dFp = F - (e + J * dx).SquaredLength();//理论下降值,直接用J*dx近似下降值了
        const float rho = dFa > 0.0f && dFp > 0.0f ? dFa / dFp : -1.0f;//求实际/理论的比值,理论不可能为负,实际为负的时候拒绝这次更新
        //信赖域： Numerical Optimization 第二版 p69

          //rho < 0.25 如果大于0说明近似的不好,需要减小信赖域,减小近似的范围。如果<0就说明是错误的近似,那么就拒绝这次的增量
        if (rho < FTR_UNDIST_DL_GAIN_RATIO_MIN) {
          delta2 *= FTR_UNDIST_DL_RADIUS_FACTOR_DECREASE;
          if (delta2 < FTR_UNDIST_DL_RADIUS_MIN) {
            delta2 = FTR_UNDIST_DL_RADIUS_MIN;
          }
          *xn = xnBkp;//取消这次增量
          update = false;//不更新
          converge = false;
          continue;
        } else if (rho > FTR_UNDIST_DL_GAIN_RATIO_MAX) //rho > 0.75,可以扩大信赖域半径
        {
          delta2 = std::max(delta2, FTR_UNDIST_DL_RADIUS_FACTOR_INCREASE * dx2);
          if (delta2 > FTR_UNDIST_DL_RADIUS_MAX) {//信赖域半径最大值
            delta2 = FTR_UNDIST_DL_RADIUS_MAX;
          }
        }
        update = true;//
          const double chi2 = e.SquaredLength();;
          if (chi2 < dx2Conv * 1e5) {
              success = true;
          }
        converge = dx2 < dx2Conv;//增量小于阈值,认为收敛
        break;
      }
      if (!update || converge) {
          success = true;
        break;
      }
    } else
#endif
    {
      *xn += dx;
//      std::cout<<"iIter:"<<iIter<<" "<<"dx2:"<<dx2<<std::endl;
          const double chi2 = e.SquaredLength();;
          if (chi2 < dx2Conv * 1e5) {
              success = true;
          }
      if (dx2 < dx2Conv) {//收敛
          success = true;
        break;
      }
    }
#if defined FTR_UNDIST_VERBOSE && FTR_UNDIST_VERBOSE == 2
    const std::string str = UT::String("%02d  ", iIter);
    if (iIter == 0) {
      UT::PrintSeparator();
      m_k.GetNormalizedToImage(xd).Print(std::string(str.size(), ' ') + "x = ", false, true);
    }
    GetNormalizedToImage(xnBkp).Print(str + "x = ", false, false);
    UT::Print("  e = %f  dx = %f  beta = %f\n", sqrtf(F * fxy()), sqrtf(dx2 * fxy()), beta);
#endif
  }
  if (JT) {
    J.GetTranspose(*JT);
  }
#if defined FTR_UNDIST_VERBOSE && FTR_UNDIST_VERBOSE == 1
  UT::Print(" --> %f\n", sqrtf((GetDistorted(*xn) - xd).SquaredLength() * m_k.m_fx * m_k.m_fy));
#endif
  return true;
}

max_stars_repo_name: wangyuanbiubiubiu/ICE-BA-ros

max_issues_repo_name: wangyuanbiubiubiu/ICE-BA-Annotation

max_forks_repo_name: wangyuanbiubiubiu/ICE-BA-Annotation


text:
// Copyright (C) 2011, 2012  Strahinja Val Markovic  <val@markovic.io>
//
// This file is part of YouCompleteMe.
//
// YouCompleteMe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// YouCompleteMe is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

#include "Result.h"
#include "standard.h"
#include "Utils.h"
#include <boost/algorithm/string.hpp>
#include <algorithm>

using boost::algorithm::istarts_with;

namespace YouCompleteMe {

namespace {

int LongestCommonSubsequenceLength( const std::string &first,
                                    const std::string &second ) {
  const std::string &longer  = first.size() > second.size() ? first  : second;
  const std::string &shorter = first.size() > second.size() ? second : first;

  int longer_len  = longer.size();
  int shorter_len = shorter.size();

  std::vector<int> previous( shorter_len + 1, 0 );
  std::vector<int> current(  shorter_len + 1, 0 );

  for ( int i = 0; i < longer_len; ++i ) {
    for ( int j = 0; j < shorter_len; ++j ) {
      if ( toupper( longer[ i ] ) == toupper( shorter[ j ] ) )
        current[ j + 1 ] = previous[ j ] + 1;
      else
        current[ j + 1 ] = std::max( current[ j ], previous[ j + 1 ] );
    }

    for ( int j = 0; j < shorter_len; ++j ) {
      previous[ j + 1 ] = current[ j + 1 ];
    }
  }

  return current[ shorter_len ];
}

int NumWordBoundaryCharMatches( const std::string &query,
                                const std::string &word_boundary_chars ) {
  return LongestCommonSubsequenceLength( query, word_boundary_chars );
}

} // unnamed namespace

Result::Result()
  :
  query_is_empty_( true ),
  is_subsequence_( false ),
  first_char_same_in_query_and_text_( false ),
  ratio_of_word_boundary_chars_in_query_( 0 ),
  word_boundary_char_utilization_( 0 ),
  query_is_candidate_prefix_( false ),
  text_is_lowercase_( false ),
  char_match_index_sum_( 0 ),
  text_( NULL ) {
}

Result::Result( bool is_subsequence )
  :
  query_is_empty_( true ),
  is_subsequence_( is_subsequence ),
  first_char_same_in_query_and_text_( false ),
  ratio_of_word_boundary_chars_in_query_( 0 ),
  word_boundary_char_utilization_( 0 ),
  query_is_candidate_prefix_( false ),
  text_is_lowercase_( false ),
  char_match_index_sum_( 0 ),
  text_( NULL ) {
}

Result::Result( bool is_subsequence,
                const std::string *text,
                bool text_is_lowercase,
                int char_match_index_sum,
                const std::string &word_boundary_chars,
                const std::string &query )
  :
  query_is_empty_( true ),
  is_subsequence_( is_subsequence ),
  first_char_same_in_query_and_text_( false ),
  ratio_of_word_boundary_chars_in_query_( 0 ),
  word_boundary_char_utilization_( 0 ),
  query_is_candidate_prefix_( false ),
  text_is_lowercase_( text_is_lowercase ),
  char_match_index_sum_( char_match_index_sum ),
  text_( text ) {
  if ( is_subsequence )
    SetResultFeaturesFromQuery( word_boundary_chars, query );
}

bool Result::operator< ( const Result &other ) const {
  // Yes, this is ugly but it also needs to be fast.  Since this is called a
  // bazillion times, we have to make sure only the required comparisons are
  // made, and no more.

  if ( !query_is_empty_ ) {
    if ( first_char_same_in_query_and_text_ !=
         other.first_char_same_in_query_and_text_ ) {
      return first_char_same_in_query_and_text_;
    }

    bool equal_wb_ratios = AlmostEqual(
                             ratio_of_word_boundary_chars_in_query_,
                             other.ratio_of_word_boundary_chars_in_query_ );

    bool equal_wb_utilization = AlmostEqual(
                                  word_boundary_char_utilization_,
                                  other.word_boundary_char_utilization_ );

    if ( AlmostEqual( ratio_of_word_boundary_chars_in_query_, 1.0 ) ||
         AlmostEqual( other.ratio_of_word_boundary_chars_in_query_, 1.0 ) ) {
      if ( !equal_wb_ratios ) {
        return ratio_of_word_boundary_chars_in_query_ >
               other.ratio_of_word_boundary_chars_in_query_;
      }

      else {
        if ( !equal_wb_utilization )
          return word_boundary_char_utilization_ >
                 other.word_boundary_char_utilization_;
      }
    }

    if ( query_is_candidate_prefix_ != other.query_is_candidate_prefix_ )
      return query_is_candidate_prefix_;

    if ( !equal_wb_ratios ) {
      return ratio_of_word_boundary_chars_in_query_ >
             other.ratio_of_word_boundary_chars_in_query_;
    }

    else {
      if ( !equal_wb_utilization )
        return word_boundary_char_utilization_ >
               other.word_boundary_char_utilization_;
    }

    if ( char_match_index_sum_ != other.char_match_index_sum_ )
      return char_match_index_sum_ < other.char_match_index_sum_;

    if ( text_->length() != other.text_->length() )
      return text_->length() < other.text_->length();

    if ( text_is_lowercase_ != other.text_is_lowercase_ )
      return text_is_lowercase_;
  }

  // Lexicographic comparison
  return *text_ < *other.text_;
}

void Result::SetResultFeaturesFromQuery(
  const std::string &word_boundary_chars,
  const std::string &query ) {
  query_is_empty_ = query.empty();

  if ( query.empty() || text_->empty() )
    return;

  first_char_same_in_query_and_text_ =
    toupper( query[ 0 ] ) == toupper( ( *text_ )[ 0 ] );
  int num_wb_matches = NumWordBoundaryCharMatches( query,
                                                   word_boundary_chars );
  ratio_of_word_boundary_chars_in_query_ =
    num_wb_matches / static_cast< double >( query.length() );
  word_boundary_char_utilization_ =
    num_wb_matches / static_cast< double >( word_boundary_chars.length() );
  query_is_candidate_prefix_ = istarts_with( *text_, query );

}

} // namespace YouCompleteMe

max_stars_repo_name: dinamic/subvim

max_issues_repo_name: dinamic/subvim

max_forks_repo_name: dinamic/subvim


text:
//
// Copyright (c) 2021 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/CPPAlliance/http_proto
//

#ifndef BOOST_HTTP_PROTO_CHAR_SET_HPP
#define BOOST_HTTP_PROTO_CHAR_SET_HPP

#include <boost/http_proto/detail/config.hpp>

namespace boost {
namespace http_proto {
namespace bnf {

/** A table-driven character set
*/
class char_set_table
{
    char const* const tab_;

public:
    char_set_table(
        char const* tab) noexcept
        : tab_(tab)
    {
    }

    bool
    contains(
        char c) const noexcept
    {
        auto const u = static_cast<
            unsigned char>(c);
        return tab_[u] != 0;
    }

    template<class Char>
    Char*
    skip(
        Char* first,
        char const* end) const noexcept
    {
        while(first != end)
        {
            if(! contains(*first))
                break;
            ++first;
        }
        return first;
    }
};

//------------------------------------------------

template<bool (*F)(char)>
class char_set_function
{
public:
    bool
    contains(
        char c) const noexcept
    {
        auto const u = static_cast<
            unsigned char>(c);
        return F(u) != 0;
    }

    template<class Char>
    Char*
    skip(
        Char* first,
        char const* end) const noexcept
    {
        while(first != end)
        {
            if(! contains(*first))
                break;
            ++first;
        }
        return first;
    }
};

} // bnf
} // http_proto
} // boost

#endif