<commit_before>/* vim: set ts=2 expandtab: */
/**
 *       @file  test.cpp
 *      @brief
 *
 *     @author  Josh King (jheretic), jking@chambana.net
 *
 *   @internal
 *      Created  11/17/2013 06:01:11 PM
 *     Compiler  gcc/g++
 * Organization  The Open Technology Institute
 *    Copyright  Copyright (c) 2013, Josh King
 *
 * This file is part of Commotion, Copyright (c) 2013, Josh King
 *
 * Commotion 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.
 *
 * Commotion 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 Commotion.  If not, see <http://www.gnu.org/licenses/>.
 *
 * =====================================================================================
 */
extern "C" {
#include "../src/obj.h"
#include "../src/list.h"
#include "../src/tree.h"
}
#include "gtest/gtest.h"

/*
 * NOTE: Inserting keys with different length values will be interpreted as different keys (eg insert("test", 5) and insert("test", 6) are not the same
 * and their values will be stored in different nodes in the tree
 *
 *
 */

class TreeTest : public ::testing::Test
{
  protected:
    co_obj_t *Tree16;
    co_obj_t *Tree32;
    void InsertObj();
    void DeleteObj();
    void UpdateObj();
    co_obj_t *TestString1;
    co_obj_t *TestString2;
    co_obj_t *ReplaceString1;

    co_obj_t *ptr;
    int ret;

    TreeTest()
    {
      Tree16 = co_tree16_create();
      Tree32 = co_tree32_create();

      TestString1 = co_str8_create("1TESTVALUE1", 11, 0);
      TestString2 = co_str8_create("2TESTVALUE2", 12, 0);
      ReplaceString1 = co_str8_create("REPLACESTRING", 14, 0);

      int ret = NULL;

    }

    virtual void SetUp()
    {
    }

    ~TreeTest()
    {
      co_obj_free(Tree16);
      co_obj_free(Tree32);
    }
};

void TreeTest::InsertObj()
{
  ret = co_tree_insert(Tree16, "1TESTKEY1", 10, TestString1);
  ASSERT_EQ(1, ret);

ptr = co_tree_find(Tree16, "1TESTKEY1", 10);
  ASSERT_EQ(TestString1, ptr);

  ret = co_tree_insert(Tree16, "2TESTKEY2", 10, TestString2);
  ASSERT_EQ(1, ret);

  ptr = co_tree_find(Tree16, "2TESTKEY2", 10);
  ASSERT_EQ(TestString2, ptr);

  // repeat for Tree 32
  ret = co_tree_insert(Tree32, "1TESTKEY1", 10, TestString1);
  ASSERT_EQ(1, ret);

  ptr = co_tree_find(Tree32, "1TESTKEY1", 10);
  ASSERT_EQ(TestString1, ptr);

  ret = co_tree_insert(Tree32, "2TESTKEY2", 10, TestString2);
  ASSERT_EQ(1, ret);

  ptr = co_tree_find(Tree32, "2TESTKEY2", 10);
  ASSERT_EQ(TestString2, ptr);
}

void TreeTest::DeleteObj()
{

  ret = co_tree_insert(Tree16, "1TESTKEY1", 9, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_tree_insert(Tree16, "2TESTKEY2", 9, TestString2);
  ASSERT_EQ(1, ret);

  ptr = co_tree_delete(Tree16, "1TESTKEY1", 9);
  ASSERT_EQ(TestString1, ptr);

  ptr = co_tree_delete(Tree16, "2TESTKEY2", 9);
  ASSERT_EQ(TestString2, ptr);

  ptr = co_tree_find(Tree16, "1TESTKEY1", 9);

  // repeat for Tree32
  ret = co_tree_insert(Tree32, "1TESTKEY1", 9, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_tree_insert(Tree32, "2TESTKEY2", 9, TestString2);
  ASSERT_EQ(1, ret);

  ptr = co_tree_delete(Tree32, "1TESTKEY1", 9);
  ASSERT_EQ(TestString1, ptr);

  ptr = co_tree_delete(Tree32, "2TESTKEY2", 9);
  ASSERT_EQ(TestString2, ptr);

}

void TreeTest::UpdateObj()
{
  ret = co_tree_insert(Tree16, "1TESTKEY1", 9, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_tree_set_str(Tree16, "1TESTKEY1", 9, "REPLACESTRING", 14);
  ASSERT_EQ(1, ret);

  ptr = co_tree_find(Tree16, "1TESTKEY1", 9);
  ASSERT_EQ(0, co_str_cmp(ptr, ReplaceString1));

  // repeat for Tree32
  ret = co_tree_insert(Tree32, "1TESTKEY1", 9, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_tree_set_str(Tree32, "1TESTKEY1", 9, "REPLACESTRING", 14);
  ASSERT_EQ(1, ret);

  ptr = co_tree_find(Tree32, "1TESTKEY1", 9);
  ASSERT_EQ(0, co_str_cmp(ptr, ReplaceString1));
}

TEST_F(TreeTest, TreeInsertTest)
{
  InsertObj();
}

TEST_F(TreeTest, TreeDeleteTest)
{
  DeleteObj();
}

TEST_F(TreeTest, TreeUpdateTest)
{
    UpdateObj();
} <commit_msg>added tests to confirm deletions in TreeDelete()<commit_after>/* vim: set ts=2 expandtab: */
/**
 *       @file  test.cpp
 *      @brief
 *
 *     @author  Josh King (jheretic), jking@chambana.net
 *
 *   @internal
 *      Created  11/17/2013 06:01:11 PM
 *     Compiler  gcc/g++
 * Organization  The Open Technology Institute
 *    Copyright  Copyright (c) 2013, Josh King
 *
 * This file is part of Commotion, Copyright (c) 2013, Josh King
 *
 * Commotion 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.
 *
 * Commotion 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 Commotion.  If not, see <http://www.gnu.org/licenses/>.
 *
 * =====================================================================================
 */
extern "C" {
#include "../src/obj.h"
#include "../src/list.h"
#include "../src/tree.h"
}
#include "gtest/gtest.h"

/*
 * NOTE: Inserting keys with different length values will be interpreted as different keys (eg insert("test", 5) and insert("test", 6) are not the same
 * and their values will be stored in different nodes in the tree
 *
 *
 */

class TreeTest : public ::testing::Test
{
  protected:
    co_obj_t *Tree16;
    co_obj_t *Tree32;
    void InsertObj();
    void DeleteObj();
    void UpdateObj();
    co_obj_t *TestString1;
    co_obj_t *TestString2;
    co_obj_t *ReplaceString1;

    co_obj_t *ptr;
    int ret;

    TreeTest()
    {
      Tree16 = co_tree16_create();
      Tree32 = co_tree32_create();

      TestString1 = co_str8_create("1TESTVALUE1", 11, 0);
      TestString2 = co_str8_create("2TESTVALUE2", 12, 0);
      ReplaceString1 = co_str8_create("REPLACESTRING", 14, 0);

      int ret = NULL;

    }

    virtual void SetUp()
    {
    }

    ~TreeTest()
    {
      co_obj_free(Tree16);
      co_obj_free(Tree32);
    }
};

void TreeTest::InsertObj()
{
  ret = co_tree_insert(Tree16, "1TESTKEY1", 10, TestString1);
  ASSERT_EQ(1, ret);

ptr = co_tree_find(Tree16, "1TESTKEY1", 10);
  ASSERT_EQ(TestString1, ptr);

  ret = co_tree_insert(Tree16, "2TESTKEY2", 10, TestString2);
  ASSERT_EQ(1, ret);

  ptr = co_tree_find(Tree16, "2TESTKEY2", 10);
  ASSERT_EQ(TestString2, ptr);

  // repeat for Tree 32
  ret = co_tree_insert(Tree32, "1TESTKEY1", 10, TestString1);
  ASSERT_EQ(1, ret);

  ptr = co_tree_find(Tree32, "1TESTKEY1", 10);
  ASSERT_EQ(TestString1, ptr);

  ret = co_tree_insert(Tree32, "2TESTKEY2", 10, TestString2);
  ASSERT_EQ(1, ret);

  ptr = co_tree_find(Tree32, "2TESTKEY2", 10);
  ASSERT_EQ(TestString2, ptr);
}

void TreeTest::DeleteObj()
{

  ret = co_tree_insert(Tree16, "1TESTKEY1", 9, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_tree_insert(Tree16, "2TESTKEY2", 9, TestString2);
  ASSERT_EQ(1, ret);

  ptr = co_tree_delete(Tree16, "1TESTKEY1", 9);
  ASSERT_EQ(TestString1, ptr);

  ptr = co_tree_delete(Tree16, "2TESTKEY2", 9);
  ASSERT_EQ(TestString2, ptr);

  ptr = co_tree_find(Tree16, "1TESTKEY1", 9);
  ASSERT_EQ(NULL, ptr);

  ptr = co_tree_find(Tree16, "2TESTKEY2", 9);
  ASSERT_EQ(NULL, ptr);

  // repeat for Tree32
  ret = co_tree_insert(Tree32, "1TESTKEY1", 9, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_tree_insert(Tree32, "2TESTKEY2", 9, TestString2);
  ASSERT_EQ(1, ret);

  ptr = co_tree_delete(Tree32, "1TESTKEY1", 9);
  ASSERT_EQ(TestString1, ptr);

  ptr = co_tree_delete(Tree32, "2TESTKEY2", 9);
  ASSERT_EQ(TestString2, ptr);

  ptr = co_tree_find(Tree32, "1TESTKEY1", 9);
  ASSERT_EQ(NULL, ptr);

  ptr = co_tree_find(Tree32, "2TESTKEY2", 9);
  ASSERT_EQ(NULL, ptr);

}

void TreeTest::UpdateObj()
{
  ret = co_tree_insert(Tree16, "1TESTKEY1", 9, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_tree_set_str(Tree16, "1TESTKEY1", 9, "REPLACESTRING", 14);
  ASSERT_EQ(1, ret);

  ptr = co_tree_find(Tree16, "1TESTKEY1", 9);
  ASSERT_EQ(0, co_str_cmp(ptr, ReplaceString1));

  // repeat for Tree32
  ret = co_tree_insert(Tree32, "1TESTKEY1", 9, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_tree_set_str(Tree32, "1TESTKEY1", 9, "REPLACESTRING", 14);
  ASSERT_EQ(1, ret);

  ptr = co_tree_find(Tree32, "1TESTKEY1", 9);
  ASSERT_EQ(0, co_str_cmp(ptr, ReplaceString1));
}

TEST_F(TreeTest, TreeInsertTest)
{
  InsertObj();
}

TEST_F(TreeTest, TreeDeleteTest)
{
  DeleteObj();
}

TEST_F(TreeTest, TreeUpdateTest)
{
    UpdateObj();
} <|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <test/models/utility.hpp>
#include <fstream>
#include <stan/io/dump.hpp>
#include <stan/mcmc/chains.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>

const size_t num_chains = 4;
bool has_R = false;
bool has_jags = false;
std::vector<std::string> model_path;
std::string Rscript;
std::vector<std::string> data_files;

TEST(LogisticSpeedTest,Prerequisites) {
  std::string command;
  command = "Rscript --version";
  try {
    run_command(command);
    has_R = true;
  } catch (...) {
    std::cout << "System does not have Rscript available" << std::endl
              << "Failed to run: " << command << std::endl;
  }

  std::vector<std::string> test_file;
  test_file.push_back("src");
  test_file.push_back("models");
  test_file.push_back("speed");
  test_file.push_back("empty.jags");
  command = "jags ";
  command += convert_model_path(test_file);

  try {
    run_command(command);
    has_jags = true;
  } catch (...) {
    std::cout << "System does not have jags available" << std::endl
              << "Failed to run: " << command << std::endl;
  }

  model_path.push_back("models");
  model_path.push_back("speed");
  model_path.push_back("logistic");
  Rscript = "logistic_generate_data.R";

  data_files.push_back("logistic_128_2");
  data_files.push_back("logistic_1024_2");
  data_files.push_back("logistic_4096_2");
}

TEST(LogisticSpeedTest,GenerateData) {
  if (!has_R) {
    std::cout << "No R available" << std::endl;
    return;  // should this fail?  probably
  }
  bool has_data = true;
  std::string path = convert_model_path(model_path);
  for (size_t i = 0; i < data_files.size() && has_data; i++) {
    std::string data_file = path;
    data_file += get_path_separator();
    data_file += data_files[i];
    data_file += ".Rdata";
    std::ifstream file(data_file.c_str());
    if (!file)
      has_data = false;
  }

  if (has_data)
    return;

  // generate data using R script
  std::string command;
  command = "cd ";
  command += convert_model_path(model_path);
  command += " && ";
  command += "Rscript ";
  command += Rscript;

  // no guarantee here that we have the right files

  ASSERT_NO_THROW(run_command(command))
    << command;
  SUCCEED();
}

// returns number of milliseconds to execute commands;
/**
 * Executes the Stan model and returns elapsed time.
 *
 * The Stan model is executed num_chains times.
 * The command argument has the basic Stan command
 * to run. The filename argument has the basename
 * for the output samples. This is append with the chain id and
 * the suffix '.csv'.
 *
 * The standard output stream and error output stream for each
 * chain is recorded and output in command_outputs.
 *
 *
 * @param[in] command The command to run.
 * @param[in] filename The output filename without a suffix.
 * @param[out] command_outputs The captured output per chain.
 *
 * @return Elapsed time running the commands in milliseconds.
 */
long run_stan(const std::string& command, const std::string& filename, std::vector<std::string> command_outputs) {
  using boost::posix_time::ptime;

  long time = 0;
  std::string path = convert_model_path(model_path);

  for (size_t chain = 0; chain < num_chains; chain++) {
    std::stringstream command_chain;
    command_chain << command;
    command_chain << " --chain_id=" << chain
                  << " --samples=" << path << get_path_separator()
                  << filename << ".chain_" << chain << ".csv";
    std::string command_output;
    try {
      ptime time_start(boost::posix_time::microsec_clock::universal_time()); // start timer
      command_output = run_command(command_chain.str());
      ptime time_end(boost::posix_time::microsec_clock::universal_time());   // end timer
      time += (time_end - time_start).total_milliseconds();
    } catch(...) {
      ADD_FAILURE() << "Failed running command: " << command_chain.str();
    }
    command_outputs.push_back(command_output);
  }
  return time;
}

stan::mcmc::chains<> create_chains(const std::string& filename) {
  std::string path = convert_model_path(model_path);
  std::stringstream samples;
  samples << path << get_path_separator()
          << filename << ".chain_0.csv";

  std::vector<std::string> names;
  std::vector<std::vector<size_t> > dimss;
  stan::mcmc::read_variables(samples.str(), 2U,
                             names, dimss);

  stan::mcmc::chains<> chains(num_chains, names, dimss);
  for (size_t chain = 0; chain < num_chains; chain++) {
    samples.str("");
    samples << path << get_path_separator()
            << filename << ".chain_" << chain << ".csv";
    stan::mcmc::add_chain(chains, chain, samples.str(), 2U);
  }
  return chains;
}
void get_beta(const std::string& filename, std::vector<double>& beta) {
  std::string path = convert_model_path(model_path);
  std::stringstream param_filename;
  param_filename << path << get_path_separator() << filename
                 << "_param.Rdata";
  std::ifstream param_ifstream(param_filename.str().c_str());
  stan::io::dump param_values(param_ifstream);

  beta = param_values.vals_r("beta");
  for (size_t i = 0; i < beta.size(); i++) {
    std::cout << "beta[" << i << "]: " << beta[i] << std::endl;
  }
}
void test_logistic_speed_stan(const std::string& filename, size_t iterations) {
  if (!has_R)
    return;
  std::stringstream command;
  std::string path = convert_model_path(model_path);

  command << path << get_path_separator() << "logistic"
          << " --data=" << path << get_path_separator() << filename << ".Rdata"
          << " --iter=" << iterations
          << " --refresh=" << iterations;

  std::vector<std::string> command_outputs;
  long time = run_stan(command.str(), filename, command_outputs);
  stan::mcmc::chains<> chains = create_chains(filename);

  std::vector<double> beta;
  get_beta(filename, beta);

  std::cout << "************************************************************\n"
            << "milliseconds: " << time << std::endl
            << "************************************************************\n";
  size_t num_params = chains.num_params();
  for (size_t i = 0; i < num_params; i++) {
    std::cout << "------------------------------------------------------------\n";
    std::cout << "beta[" << i << "]" << std::endl;
    std::cout << "\tmean:        " << chains.mean(i) << std::endl;
    std::cout << "\tsd:          " << chains.sd(i) << std::endl;
    std::cout << "\tneff:        " << chains.effective_sample_size(i) << std::endl;
    std::cout << "\tsplit R hat: " << chains.split_potential_scale_reduction(i) << std::endl;
  }
  SUCCEED();
}

TEST(LogisticSpeedTest,Stan_128_2) {
  test_logistic_speed_stan("logistic_128_2", 250U);
}

TEST(LogisticSpeedTest,Stan_1024_2) {
  test_logistic_speed_stan("logistic_1024_2", 250U);
}

TEST(LogisticSpeedTest,Stan_4096_2) {
  test_logistic_speed_stan("logistic_4096_2", 250U);
}

<commit_msg>speed-comparisons: refactored test<commit_after>#include <gtest/gtest.h>
#include <test/models/utility.hpp>
#include <fstream>
#include <stan/io/dump.hpp>
#include <stan/mcmc/chains.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>

class LogisticSpeedTest :
  public testing::Test {
public:
  static void SetUpTestCase() {
    std::cout << "-----\n\n";
  }
};

const size_t num_chains = 4;
bool has_R = false;
bool has_jags = false;
std::vector<std::string> model_path;
std::string Rscript;
std::vector<std::string> data_files;

TEST_F(LogisticSpeedTest,Prerequisites) {
  std::string command;
  command = "Rscript --version";
  try {
    run_command(command);
    has_R = true;
  } catch (...) {
    std::cout << "System does not have Rscript available" << std::endl
              << "Failed to run: " << command << std::endl;
  }

  std::vector<std::string> test_file;
  test_file.push_back("src");
  test_file.push_back("models");
  test_file.push_back("speed");
  test_file.push_back("empty.jags");
  command = "jags ";
  command += convert_model_path(test_file);

  try {
    run_command(command);
    has_jags = true;
  } catch (...) {
    std::cout << "System does not have jags available" << std::endl
              << "Failed to run: " << command << std::endl;
  }

  model_path.push_back("models");
  model_path.push_back("speed");
  model_path.push_back("logistic");
  Rscript = "logistic_generate_data.R";

  data_files.push_back("logistic_128_2");
  data_files.push_back("logistic_1024_2");
  data_files.push_back("logistic_4096_2");
}

TEST_F(LogisticSpeedTest,GenerateData) {
  if (!has_R) {
    std::cout << "No R available" << std::endl;
    return;  // should this fail?  probably
  }
  bool has_data = true;
  std::string path = convert_model_path(model_path);
  for (size_t i = 0; i < data_files.size() && has_data; i++) {
    std::string data_file = path;
    data_file += get_path_separator();
    data_file += data_files[i];
    data_file += ".Rdata";
    std::ifstream file(data_file.c_str());
    if (!file)
      has_data = false;
  }

  if (has_data)
    return;

  // generate data using R script
  std::string command;
  command = "cd ";
  command += convert_model_path(model_path);
  command += " && ";
  command += "Rscript ";
  command += Rscript;

  // no guarantee here that we have the right files

  ASSERT_NO_THROW(run_command(command))
    << command;
  SUCCEED();
}

// returns number of milliseconds to execute commands;
/**
 * Executes the Stan model and returns elapsed time.
 *
 * The Stan model is executed num_chains times.
 * The command argument has the basic Stan command
 * to run. The filename argument has the basename
 * for the output samples. This is append with the chain id and
 * the suffix '.csv'.
 *
 * The standard output stream and error output stream for each
 * chain is recorded and output in command_outputs.
 *
 *
 * @param[in] command The command to run.
 * @param[in] filename The output filename without a suffix.
 * @param[out] command_outputs The captured output per chain.
 *
 * @return Elapsed time running the commands in milliseconds.
 */
long run_stan(const std::string& command, const std::string& filename, std::vector<std::string> command_outputs) {
  using boost::posix_time::ptime;

  long time = 0;
  std::string path = convert_model_path(model_path);

  for (size_t chain = 0; chain < num_chains; chain++) {
    std::stringstream command_chain;
    command_chain << command;
    command_chain << " --chain_id=" << chain
                  << " --samples=" << path << get_path_separator()
                  << filename << ".chain_" << chain << ".csv";
    std::string command_output;
    try {
      ptime time_start(boost::posix_time::microsec_clock::universal_time()); // start timer
      command_output = run_command(command_chain.str());
      ptime time_end(boost::posix_time::microsec_clock::universal_time());   // end timer
      time += (time_end - time_start).total_milliseconds();
    } catch(...) {
      ADD_FAILURE() << "Failed running command: " << command_chain.str();
    }
    command_outputs.push_back(command_output);
  }
  return time;
}

stan::mcmc::chains<> create_chains(const std::string& filename) {
  std::string path = convert_model_path(model_path);
  std::stringstream samples;
  samples << path << get_path_separator()
          << filename << ".chain_0.csv";

  std::vector<std::string> names;
  std::vector<std::vector<size_t> > dimss;
  stan::mcmc::read_variables(samples.str(), 2U,
                             names, dimss);

  stan::mcmc::chains<> chains(num_chains, names, dimss);
  for (size_t chain = 0; chain < num_chains; chain++) {
    samples.str("");
    samples << path << get_path_separator()
            << filename << ".chain_" << chain << ".csv";
    stan::mcmc::add_chain(chains, chain, samples.str(), 2U);
  }
  return chains;
}
void get_beta(const std::string& filename, std::vector<double>& beta) {
  std::string path = convert_model_path(model_path);
  std::stringstream param_filename;
  param_filename << path << get_path_separator() << filename
                 << "_param.Rdata";
  std::ifstream param_ifstream(param_filename.str().c_str());
  stan::io::dump param_values(param_ifstream);

  beta = param_values.vals_r("beta");
  for (size_t i = 0; i < beta.size(); i++) {
    std::cout << "beta[" << i << "]: " << beta[i] << std::endl;
  }
}
void test_logistic_speed_stan(const std::string& filename, size_t iterations) {
  if (!has_R)
    return;
  std::stringstream command;
  std::string path = convert_model_path(model_path);

  command << path << get_path_separator() << "logistic"
          << " --data=" << path << get_path_separator() << filename << ".Rdata"
          << " --iter=" << iterations
          << " --refresh=" << iterations;

  std::vector<std::string> command_outputs;
  long time = run_stan(command.str(), filename, command_outputs);
  stan::mcmc::chains<> chains = create_chains(filename);

  std::vector<double> beta;
  get_beta(filename, beta);

  std::cout << "************************************************************\n"
            << "milliseconds: " << time << std::endl
            << "************************************************************\n";
  size_t num_params = chains.num_params();
  for (size_t i = 0; i < num_params; i++) {
    std::cout << "------------------------------------------------------------\n";
    std::cout << "beta[" << i << "]" << std::endl;
    std::cout << "\tmean:        " << chains.mean(i) << std::endl;
    std::cout << "\tsd:          " << chains.sd(i) << std::endl;
    std::cout << "\tneff:        " << chains.effective_sample_size(i) << std::endl;
    std::cout << "\tsplit R hat: " << chains.split_potential_scale_reduction(i) << std::endl;
  }
  SUCCEED();
}

TEST_F(LogisticSpeedTest,Stan_128_2) {
  test_logistic_speed_stan("logistic_128_2", 250U);
}

TEST_F(LogisticSpeedTest,Stan_1024_2) {
  test_logistic_speed_stan("logistic_1024_2", 250U);
}

TEST_F(LogisticSpeedTest,Stan_4096_2) {
  test_logistic_speed_stan("logistic_4096_2", 250U);
}

<|endoftext|>


<commit_before>#include <stan/agrad/rev/functions/hypot.hpp>
#include <test/unit/agrad/util.hpp>
#include <gtest/gtest.h>

TEST(AgradRev,hypot_vv) {
  AVAR a = 3.0;
  AVAR b = 4.0;
  AVAR f = hypot(a,b);
  EXPECT_FLOAT_EQ(5.0,f.val());

  AVEC x = createAVEC(a,b);
  VEC grad_f;
  f.grad(x,grad_f);
  // arbitrary, but doc this way
  EXPECT_FLOAT_EQ(3.0/5.0,grad_f[0]);
  EXPECT_FLOAT_EQ(4.0/5.0,grad_f[1]);
}

TEST(AgradRev,hypot_vd) {
  AVAR a = 3.0;
  double b = 4.0;
  AVAR f = hypot(a,b);
  EXPECT_FLOAT_EQ(5.0,f.val());

  AVEC x = createAVEC(a);
  VEC grad_f;
  f.grad(x,grad_f);
  // arbitrary, but doc this way
  EXPECT_FLOAT_EQ(3.0/5.0,grad_f[0]);
}

TEST(AgradRev,hypot_dv) {
  double a = 3.0;
  AVAR b = 4.0;
  AVAR f = hypot(a,b);
  EXPECT_FLOAT_EQ(5.0,f.val());

  AVEC x = createAVEC(b);
  VEC grad_f;
  f.grad(x,grad_f);
  // arbitrary, but doc this way
  EXPECT_FLOAT_EQ(4.0/5.0,grad_f[0]);
}
<commit_msg>added NaN test for hypot<commit_after>#include <stan/agrad/rev/functions/hypot.hpp>
#include <test/unit/agrad/util.hpp>
#include <gtest/gtest.h>
#include <test/unit-agrad-rev/nan_util.hpp>
#include <stan/meta/traits.hpp>

TEST(AgradRev,hypot_vv) {
  AVAR a = 3.0;
  AVAR b = 4.0;
  AVAR f = hypot(a,b);
  EXPECT_FLOAT_EQ(5.0,f.val());

  AVEC x = createAVEC(a,b);
  VEC grad_f;
  f.grad(x,grad_f);
  // arbitrary, but doc this way
  EXPECT_FLOAT_EQ(3.0/5.0,grad_f[0]);
  EXPECT_FLOAT_EQ(4.0/5.0,grad_f[1]);
}

TEST(AgradRev,hypot_vd) {
  AVAR a = 3.0;
  double b = 4.0;
  AVAR f = hypot(a,b);
  EXPECT_FLOAT_EQ(5.0,f.val());

  AVEC x = createAVEC(a);
  VEC grad_f;
  f.grad(x,grad_f);
  // arbitrary, but doc this way
  EXPECT_FLOAT_EQ(3.0/5.0,grad_f[0]);
}

TEST(AgradRev,hypot_dv) {
  double a = 3.0;
  AVAR b = 4.0;
  AVAR f = hypot(a,b);
  EXPECT_FLOAT_EQ(5.0,f.val());

  AVEC x = createAVEC(b);
  VEC grad_f;
  f.grad(x,grad_f);
  // arbitrary, but doc this way
  EXPECT_FLOAT_EQ(4.0/5.0,grad_f[0]);
}

struct hypot_fun {
  template <typename T0, typename T1>
  inline
  typename stan::return_type<T0,T1>::type
  operator()(const T0& arg1,
             const T1& arg2) const {
    return hypot(arg1,arg2);
  }
};

TEST(AgradRev, hypot_nan) {
  hypot_fun hypot_;
  test_nan(hypot_,3.0,5.0,false, true);
}
<|endoftext|>


<commit_before>// $Id$
// vim:tabstop=2

/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh

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

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

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
***********************************************************************/

#include "util/check.hh"
#include <algorithm>
#include <sstream>
#include <string>
#include "memory.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "StaticData.h"  // GetMaxNumFactors

#include "util/string_piece.hh"
#include "util/tokenize_piece.hh"

using namespace std;

namespace Moses
{

Phrase::Phrase() {}

Phrase::Phrase(size_t reserveSize)
{
  m_words.reserve(reserveSize);
}

Phrase::Phrase(const vector< const Word* > &mergeWords)
{
  m_words.reserve(mergeWords.size());
  for (size_t currPos = 0 ; currPos < mergeWords.size() ; currPos++) {
    AddWord(*mergeWords[currPos]);
  }
}

Phrase::~Phrase()
{
}

void Phrase::MergeFactors(const Phrase &copy)
{
  CHECK(GetSize() == copy.GetSize());
  size_t size = GetSize();
  const size_t maxNumFactors = MAX_NUM_FACTORS;
  for (size_t currPos = 0 ; currPos < size ; currPos++) {
    for (unsigned int currFactor = 0 ; currFactor < maxNumFactors ; currFactor++) {
      FactorType factorType = static_cast<FactorType>(currFactor);
      const Factor *factor = copy.GetFactor(currPos, factorType);
      if (factor != NULL)
        SetFactor(currPos, factorType, factor);
    }
  }
}

void Phrase::MergeFactors(const Phrase &copy, FactorType factorType)
{
  CHECK(GetSize() == copy.GetSize());
  for (size_t currPos = 0 ; currPos < GetSize() ; currPos++)
    SetFactor(currPos, factorType, copy.GetFactor(currPos, factorType));
}

void Phrase::MergeFactors(const Phrase &copy, const std::vector<FactorType>& factorVec)
{
  CHECK(GetSize() == copy.GetSize());
  for (size_t currPos = 0 ; currPos < GetSize() ; currPos++)
    for (std::vector<FactorType>::const_iterator i = factorVec.begin();
         i != factorVec.end(); ++i) {
      SetFactor(currPos, *i, copy.GetFactor(currPos, *i));
    }
}

Phrase Phrase::GetSubString(const WordsRange &wordsRange) const
{
  Phrase retPhrase(wordsRange.GetNumWordsCovered());

  for (size_t currPos = wordsRange.GetStartPos() ; currPos <= wordsRange.GetEndPos() ; currPos++) {
    Word &word = retPhrase.AddWord();
    word = GetWord(currPos);
  }

  return retPhrase;
}

Phrase Phrase::GetSubString(const WordsRange &wordsRange, FactorType factorType) const
{
  Phrase retPhrase(wordsRange.GetNumWordsCovered());

  for (size_t currPos = wordsRange.GetStartPos() ; currPos <= wordsRange.GetEndPos() ; currPos++) {
    const Factor* f = GetFactor(currPos, factorType);
    Word &word = retPhrase.AddWord();
    word.SetFactor(factorType, f);
  }

  return retPhrase;
}

std::string Phrase::GetStringRep(const vector<FactorType> factorsToPrint) const
{
  bool markUnknown = StaticData::Instance().GetMarkUnknown();

  stringstream strme;
  for (size_t pos = 0 ; pos < GetSize() ; pos++) {
	if(markUnknown && GetWord(pos).IsOOV()) {
	  strme << "UNK";
	}
    strme << GetWord(pos).GetString(factorsToPrint, (pos != GetSize()-1));
  }

  return strme.str();
}

Word &Phrase::AddWord()
{
  m_words.push_back(Word());
  return m_words.back();
}

void Phrase::Append(const Phrase &endPhrase)
{

  for (size_t i = 0; i < endPhrase.GetSize(); i++) {
    AddWord(endPhrase.GetWord(i));
  }
}

void Phrase::PrependWord(const Word &newWord)
{
  AddWord();

  // shift
  for (size_t pos = GetSize() - 1; pos >= 1; --pos) {
    const Word &word = m_words[pos - 1];
    m_words[pos] = word;
  }

  m_words[0] = newWord;
}

void Phrase::CreateFromString(FactorDirection direction
                              ,const std::vector<FactorType> &factorOrder
                              ,const StringPiece &phraseString
                              ,const StringPiece &factorDelimiter
                              ,Word **lhs)
{
  // parse
  vector<StringPiece> annotatedWordVector;
  for (util::TokenIter<util::AnyCharacter, true> it(phraseString, "\t "); it; ++it) {
    annotatedWordVector.push_back(*it);
  }

  if (annotatedWordVector.size() == 0) {
    if (lhs) {
      (*lhs) = NULL;
    }
    return;
  }

  // KOMMA|none ART|Def.Z NN|Neut.NotGen.Sg VVFIN|none
  //    to
  // "KOMMA|none" "ART|Def.Z" "NN|Neut.NotGen.Sg" "VVFIN|none"

  size_t numWords;
  const StringPiece &annotatedWord = annotatedWordVector.back();
  if (annotatedWord.size() >= 2
      && *annotatedWord.data() == '['
      && annotatedWord.data()[annotatedWord.size() - 1] == ']') {
    // hiero/syntax rule
    numWords = annotatedWordVector.size()-1;

    // lhs
    assert(lhs);
    (*lhs) = new Word(true);
    (*lhs)->CreateFromString(direction, factorOrder, annotatedWord.substr(1, annotatedWord.size() - 2), true);
    assert((*lhs)->IsNonTerminal());
  } else {
    numWords = annotatedWordVector.size();
    //CHECK(lhs == NULL);
    if (lhs) {
      (*lhs) = NULL;
    }
  }

  // parse each word
  m_words.reserve(numWords);

  for (size_t phrasePos = 0 ; phrasePos < numWords; phrasePos++) {
    StringPiece &annotatedWord = annotatedWordVector[phrasePos];
    bool isNonTerminal;
    if (annotatedWord.size() >= 2 && *annotatedWord.data() == '[' && annotatedWord.data()[annotatedWord.size() - 1] == ']') {
      // non-term
      isNonTerminal = true;

      size_t nextPos = annotatedWord.find('[', 1);
      CHECK(nextPos != string::npos);

      if (direction == Input)
        annotatedWord = annotatedWord.substr(1, nextPos - 2);
      else
        annotatedWord = annotatedWord.substr(nextPos + 1, annotatedWord.size() - nextPos - 2);
    } else {
      isNonTerminal = false;
    }

    Word &word = AddWord();
    word.CreateFromString(direction, factorOrder, annotatedWord, isNonTerminal);

  }
}

int Phrase::Compare(const Phrase &other) const
{
#ifdef min
#undef min
#endif
  size_t thisSize			= GetSize()
                        ,compareSize	= other.GetSize();
  if (thisSize != compareSize) {
    return (thisSize < compareSize) ? -1 : 1;
  }

  for (size_t pos = 0 ; pos < thisSize ; pos++) {
    const Word &thisWord	= GetWord(pos)
                            ,&otherWord	= other.GetWord(pos);
    int ret = Word::Compare(thisWord, otherWord);

    if (ret != 0)
      return ret;
  }

  return 0;
}

bool Phrase::Contains(const vector< vector<string> > &subPhraseVector
                      , const vector<FactorType> &inputFactor) const
{
  const size_t subSize = subPhraseVector.size()
                         ,thisSize= GetSize();
  if (subSize > thisSize)
    return false;

  // try to match word-for-word
  for (size_t currStartPos = 0 ; currStartPos < (thisSize - subSize + 1) ; currStartPos++) {
    bool match = true;

    for (size_t currFactorIndex = 0 ; currFactorIndex < inputFactor.size() ; currFactorIndex++) {
      FactorType factorType = inputFactor[currFactorIndex];
      for (size_t currSubPos = 0 ; currSubPos < subSize ; currSubPos++) {
        size_t currThisPos = currSubPos + currStartPos;
        const string &subStr	= subPhraseVector[currSubPos][currFactorIndex];
        StringPiece thisStr	= GetFactor(currThisPos, factorType)->GetString();
        if (subStr != thisStr) {
          match = false;
          break;
        }
      }
      if (!match)
        break;
    }

    if (match)
      return true;
  }
  return false;
}

bool Phrase::IsCompatible(const Phrase &inputPhrase) const
{
  if (inputPhrase.GetSize() != GetSize()) {
    return false;
  }

  const size_t size = GetSize();

  const size_t maxNumFactors = MAX_NUM_FACTORS;
  for (size_t currPos = 0 ; currPos < size ; currPos++) {
    for (unsigned int currFactor = 0 ; currFactor < maxNumFactors ; currFactor++) {
      FactorType factorType = static_cast<FactorType>(currFactor);
      const Factor *thisFactor 		= GetFactor(currPos, factorType)
                                    ,*inputFactor	= inputPhrase.GetFactor(currPos, factorType);
      if (thisFactor != NULL && inputFactor != NULL && thisFactor != inputFactor)
        return false;
    }
  }
  return true;

}

bool Phrase::IsCompatible(const Phrase &inputPhrase, FactorType factorType) const
{
  if (inputPhrase.GetSize() != GetSize())	{
    return false;
  }
  for (size_t currPos = 0 ; currPos < GetSize() ; currPos++) {
    if (GetFactor(currPos, factorType) != inputPhrase.GetFactor(currPos, factorType))
      return false;
  }
  return true;
}

bool Phrase::IsCompatible(const Phrase &inputPhrase, const std::vector<FactorType>& factorVec) const
{
  if (inputPhrase.GetSize() != GetSize())	{
    return false;
  }
  for (size_t currPos = 0 ; currPos < GetSize() ; currPos++) {
    for (std::vector<FactorType>::const_iterator i = factorVec.begin();
         i != factorVec.end(); ++i) {
      if (GetFactor(currPos, *i) != inputPhrase.GetFactor(currPos, *i))
        return false;
    }
  }
  return true;
}

size_t Phrase::GetNumTerminals() const
{
  size_t ret = 0;

  for (size_t pos = 0; pos < GetSize(); ++pos) {
    if (!GetWord(pos).IsNonTerminal())
      ret++;
  }
  return ret;
}

void Phrase::InitializeMemPool()
{
}

void Phrase::FinalizeMemPool()
{
}

void Phrase::OnlyTheseFactors(const FactorMask &factors)
{
  for (unsigned int currFactor = 0 ; currFactor < MAX_NUM_FACTORS ; currFactor++) {
    if (!factors[currFactor]) {
      for (size_t pos = 0; pos < GetSize(); ++pos) {
        SetFactor(pos, currFactor, NULL);
      }
    }
  }
}

void Phrase::InitStartEndWord()
{
  FactorCollection &factorCollection = FactorCollection::Instance();

  Word startWord(Input);
  const Factor *factor = factorCollection.AddFactor(Input, 0, BOS_); // TODO - non-factored
  startWord.SetFactor(0, factor);
  PrependWord(startWord);

  Word endWord(Input);
  factor = factorCollection.AddFactor(Input, 0, EOS_); // TODO - non-factored
  endWord.SetFactor(0, factor);
  AddWord(endWord);
}

size_t Phrase::Find(const Phrase &sought, int maxUnknown) const
{
<<<<<<< HEAD
	size_t maxStartPos = GetSize() - sought.GetSize();
	for (size_t startThisPos = 0; startThisPos <= maxStartPos; ++startThisPos) {
		size_t thisPos = startThisPos;
		int currUnknowns = 0;
		size_t soughtPos;
		for (soughtPos = 0; soughtPos < sought.GetSize(); ++soughtPos) {
			const Word &soughtWord = sought.GetWord(soughtPos);
			const Word &thisWord = GetWord(thisPos);

			if (soughtWord == thisWord) {
				++thisPos;
			}
			else if (soughtWord.IsOOV() && (maxUnknown < 0 || currUnknowns < maxUnknown)) {
				// the output has an OOV word. Allow a certain number of OOVs
				++currUnknowns;
				++thisPos;
			}
			else {
				break;
			}
		}

		if (soughtPos == sought.GetSize()) {
			return startThisPos;
		}
	}

	return NOT_FOUND;
=======
  throw "THIS FUNCTION IS NOT IMPLEMENTED YET!";
  return false;
>>>>>>> dynamic-phrase-tables
}

TO_STRING_BODY(Phrase);

// friend
ostream& operator<<(ostream& out, const Phrase& phrase)
{
//	out << "(size " << phrase.GetSize() << ") ";
  for (size_t pos = 0 ; pos < phrase.GetSize() ; pos++) {
    const Word &word = phrase.GetWord(pos);
    out << word;
  }
  return out;
}

}

<commit_msg>Fixed errors introduced during a merge.<commit_after>// $Id$
// vim:tabstop=2

/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh

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

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

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
***********************************************************************/

#include "util/check.hh"
#include <algorithm>
#include <sstream>
#include <string>
#include "memory.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "StaticData.h"  // GetMaxNumFactors

#include "util/string_piece.hh"
#include "util/tokenize_piece.hh"

using namespace std;

namespace Moses
{

Phrase::Phrase() {}

Phrase::Phrase(size_t reserveSize)
{
  m_words.reserve(reserveSize);
}

Phrase::Phrase(const vector< const Word* > &mergeWords)
{
  m_words.reserve(mergeWords.size());
  for (size_t currPos = 0 ; currPos < mergeWords.size() ; currPos++) {
    AddWord(*mergeWords[currPos]);
  }
}

Phrase::~Phrase()
{
}

void Phrase::MergeFactors(const Phrase &copy)
{
  CHECK(GetSize() == copy.GetSize());
  size_t size = GetSize();
  const size_t maxNumFactors = MAX_NUM_FACTORS;
  for (size_t currPos = 0 ; currPos < size ; currPos++) {
    for (unsigned int currFactor = 0 ; currFactor < maxNumFactors ; currFactor++) {
      FactorType factorType = static_cast<FactorType>(currFactor);
      const Factor *factor = copy.GetFactor(currPos, factorType);
      if (factor != NULL)
        SetFactor(currPos, factorType, factor);
    }
  }
}

void Phrase::MergeFactors(const Phrase &copy, FactorType factorType)
{
  CHECK(GetSize() == copy.GetSize());
  for (size_t currPos = 0 ; currPos < GetSize() ; currPos++)
    SetFactor(currPos, factorType, copy.GetFactor(currPos, factorType));
}

void Phrase::MergeFactors(const Phrase &copy, const std::vector<FactorType>& factorVec)
{
  CHECK(GetSize() == copy.GetSize());
  for (size_t currPos = 0 ; currPos < GetSize() ; currPos++)
    for (std::vector<FactorType>::const_iterator i = factorVec.begin();
         i != factorVec.end(); ++i) {
      SetFactor(currPos, *i, copy.GetFactor(currPos, *i));
    }
}

Phrase Phrase::GetSubString(const WordsRange &wordsRange) const
{
  Phrase retPhrase(wordsRange.GetNumWordsCovered());

  for (size_t currPos = wordsRange.GetStartPos() ; currPos <= wordsRange.GetEndPos() ; currPos++) {
    Word &word = retPhrase.AddWord();
    word = GetWord(currPos);
  }

  return retPhrase;
}

Phrase Phrase::GetSubString(const WordsRange &wordsRange, FactorType factorType) const
{
  Phrase retPhrase(wordsRange.GetNumWordsCovered());

  for (size_t currPos = wordsRange.GetStartPos() ; currPos <= wordsRange.GetEndPos() ; currPos++) {
    const Factor* f = GetFactor(currPos, factorType);
    Word &word = retPhrase.AddWord();
    word.SetFactor(factorType, f);
  }

  return retPhrase;
}

std::string Phrase::GetStringRep(const vector<FactorType> factorsToPrint) const
{
  bool markUnknown = StaticData::Instance().GetMarkUnknown();

  stringstream strme;
  for (size_t pos = 0 ; pos < GetSize() ; pos++) {
	if(markUnknown && GetWord(pos).IsOOV()) {
	  strme << "UNK";
	}
    strme << GetWord(pos).GetString(factorsToPrint, (pos != GetSize()-1));
  }

  return strme.str();
}

Word &Phrase::AddWord()
{
  m_words.push_back(Word());
  return m_words.back();
}

void Phrase::Append(const Phrase &endPhrase)
{

  for (size_t i = 0; i < endPhrase.GetSize(); i++) {
    AddWord(endPhrase.GetWord(i));
  }
}

void Phrase::PrependWord(const Word &newWord)
{
  AddWord();

  // shift
  for (size_t pos = GetSize() - 1; pos >= 1; --pos) {
    const Word &word = m_words[pos - 1];
    m_words[pos] = word;
  }

  m_words[0] = newWord;
}

void Phrase::CreateFromString(FactorDirection direction
                              ,const std::vector<FactorType> &factorOrder
                              ,const StringPiece &phraseString
                              ,const StringPiece &factorDelimiter
                              ,Word **lhs)
{
  // parse
  vector<StringPiece> annotatedWordVector;
  for (util::TokenIter<util::AnyCharacter, true> it(phraseString, "\t "); it; ++it) {
    annotatedWordVector.push_back(*it);
  }

  if (annotatedWordVector.size() == 0) {
    if (lhs) {
      (*lhs) = NULL;
    }
    return;
  }

  // KOMMA|none ART|Def.Z NN|Neut.NotGen.Sg VVFIN|none
  //    to
  // "KOMMA|none" "ART|Def.Z" "NN|Neut.NotGen.Sg" "VVFIN|none"

  size_t numWords;
  const StringPiece &annotatedWord = annotatedWordVector.back();
  if (annotatedWord.size() >= 2
      && *annotatedWord.data() == '['
      && annotatedWord.data()[annotatedWord.size() - 1] == ']') {
    // hiero/syntax rule
    numWords = annotatedWordVector.size()-1;

    // lhs
    assert(lhs);
    (*lhs) = new Word(true);
    (*lhs)->CreateFromString(direction, factorOrder, annotatedWord.substr(1, annotatedWord.size() - 2), true);
    assert((*lhs)->IsNonTerminal());
  } else {
    numWords = annotatedWordVector.size();
    //CHECK(lhs == NULL);
    if (lhs) {
      (*lhs) = NULL;
    }
  }

  // parse each word
  m_words.reserve(numWords);

  for (size_t phrasePos = 0 ; phrasePos < numWords; phrasePos++) {
    StringPiece &annotatedWord = annotatedWordVector[phrasePos];
    bool isNonTerminal;
    if (annotatedWord.size() >= 2 && *annotatedWord.data() == '[' && annotatedWord.data()[annotatedWord.size() - 1] == ']') {
      // non-term
      isNonTerminal = true;

      size_t nextPos = annotatedWord.find('[', 1);
      CHECK(nextPos != string::npos);

      if (direction == Input)
        annotatedWord = annotatedWord.substr(1, nextPos - 2);
      else
        annotatedWord = annotatedWord.substr(nextPos + 1, annotatedWord.size() - nextPos - 2);
    } else {
      isNonTerminal = false;
    }

    Word &word = AddWord();
    word.CreateFromString(direction, factorOrder, annotatedWord, isNonTerminal);

  }
}

int Phrase::Compare(const Phrase &other) const
{
#ifdef min
#undef min
#endif
  size_t thisSize			= GetSize()
                        ,compareSize	= other.GetSize();
  if (thisSize != compareSize) {
    return (thisSize < compareSize) ? -1 : 1;
  }

  for (size_t pos = 0 ; pos < thisSize ; pos++) {
    const Word &thisWord	= GetWord(pos)
                            ,&otherWord	= other.GetWord(pos);
    int ret = Word::Compare(thisWord, otherWord);

    if (ret != 0)
      return ret;
  }

  return 0;
}

bool Phrase::Contains(const vector< vector<string> > &subPhraseVector
                      , const vector<FactorType> &inputFactor) const
{
  const size_t subSize = subPhraseVector.size()
                         ,thisSize= GetSize();
  if (subSize > thisSize)
    return false;

  // try to match word-for-word
  for (size_t currStartPos = 0 ; currStartPos < (thisSize - subSize + 1) ; currStartPos++) {
    bool match = true;

    for (size_t currFactorIndex = 0 ; currFactorIndex < inputFactor.size() ; currFactorIndex++) {
      FactorType factorType = inputFactor[currFactorIndex];
      for (size_t currSubPos = 0 ; currSubPos < subSize ; currSubPos++) {
        size_t currThisPos = currSubPos + currStartPos;
        const string &subStr	= subPhraseVector[currSubPos][currFactorIndex];
        StringPiece thisStr	= GetFactor(currThisPos, factorType)->GetString();
        if (subStr != thisStr) {
          match = false;
          break;
        }
      }
      if (!match)
        break;
    }

    if (match)
      return true;
  }
  return false;
}

bool Phrase::IsCompatible(const Phrase &inputPhrase) const
{
  if (inputPhrase.GetSize() != GetSize()) {
    return false;
  }

  const size_t size = GetSize();

  const size_t maxNumFactors = MAX_NUM_FACTORS;
  for (size_t currPos = 0 ; currPos < size ; currPos++) {
    for (unsigned int currFactor = 0 ; currFactor < maxNumFactors ; currFactor++) {
      FactorType factorType = static_cast<FactorType>(currFactor);
      const Factor *thisFactor 		= GetFactor(currPos, factorType)
                                    ,*inputFactor	= inputPhrase.GetFactor(currPos, factorType);
      if (thisFactor != NULL && inputFactor != NULL && thisFactor != inputFactor)
        return false;
    }
  }
  return true;

}

bool Phrase::IsCompatible(const Phrase &inputPhrase, FactorType factorType) const
{
  if (inputPhrase.GetSize() != GetSize())	{
    return false;
  }
  for (size_t currPos = 0 ; currPos < GetSize() ; currPos++) {
    if (GetFactor(currPos, factorType) != inputPhrase.GetFactor(currPos, factorType))
      return false;
  }
  return true;
}

bool Phrase::IsCompatible(const Phrase &inputPhrase, const std::vector<FactorType>& factorVec) const
{
  if (inputPhrase.GetSize() != GetSize())	{
    return false;
  }
  for (size_t currPos = 0 ; currPos < GetSize() ; currPos++) {
    for (std::vector<FactorType>::const_iterator i = factorVec.begin();
         i != factorVec.end(); ++i) {
      if (GetFactor(currPos, *i) != inputPhrase.GetFactor(currPos, *i))
        return false;
    }
  }
  return true;
}

size_t Phrase::GetNumTerminals() const
{
  size_t ret = 0;

  for (size_t pos = 0; pos < GetSize(); ++pos) {
    if (!GetWord(pos).IsNonTerminal())
      ret++;
  }
  return ret;
}

void Phrase::InitializeMemPool()
{
}

void Phrase::FinalizeMemPool()
{
}

void Phrase::OnlyTheseFactors(const FactorMask &factors)
{
  for (unsigned int currFactor = 0 ; currFactor < MAX_NUM_FACTORS ; currFactor++) {
    if (!factors[currFactor]) {
      for (size_t pos = 0; pos < GetSize(); ++pos) {
        SetFactor(pos, currFactor, NULL);
      }
    }
  }
}

void Phrase::InitStartEndWord()
{
  FactorCollection &factorCollection = FactorCollection::Instance();

  Word startWord(Input);
  const Factor *factor = factorCollection.AddFactor(Input, 0, BOS_); // TODO - non-factored
  startWord.SetFactor(0, factor);
  PrependWord(startWord);

  Word endWord(Input);
  factor = factorCollection.AddFactor(Input, 0, EOS_); // TODO - non-factored
  endWord.SetFactor(0, factor);
  AddWord(endWord);
}

size_t Phrase::Find(const Phrase &sought, int maxUnknown) const
{
  size_t maxStartPos = GetSize() - sought.GetSize();
  for (size_t startThisPos = 0; startThisPos <= maxStartPos; ++startThisPos) {
    size_t thisPos = startThisPos;
    int currUnknowns = 0;
    size_t soughtPos;
    for (soughtPos = 0; soughtPos < sought.GetSize(); ++soughtPos) {
      const Word &soughtWord = sought.GetWord(soughtPos);
      const Word &thisWord = GetWord(thisPos);

      if (soughtWord == thisWord) {
	++thisPos;
      }
      else if (soughtWord.IsOOV() && (maxUnknown < 0 || currUnknowns < maxUnknown)) {
	// the output has an OOV word. Allow a certain number of OOVs
	++currUnknowns;
	++thisPos;
      }
      else {
	break;
      }
    }

    if (soughtPos == sought.GetSize()) {
      return startThisPos;
    }
  }

  return NOT_FOUND;
}

TO_STRING_BODY(Phrase);

// friend
ostream& operator<<(ostream& out, const Phrase& phrase)
{
//	out << "(size " << phrase.GetSize() << ") ";
  for (size_t pos = 0 ; pos < phrase.GetSize() ; pos++) {
    const Word &word = phrase.GetWord(pos);
    out << word;
  }
  return out;
}

}

<|endoftext|>


<commit_before>#include "Contour.hpp"
#include <stdlib.h>
#include <vector>
#include <iostream>
#include <queue>
#include <string>
#include <math.h>
#include <values.h>
#include <assert.h>

using namespace std;
namespace scanmatch{

ContourExtractor::ContourExtractor(sm_laser_type_t laser_type):
    laserType(laser_type)
{
  switch (laser_type) {
  case SM_HOKUYO_UTM:
    maxAdjacentDistance = 6;
    maxAdjacentAngularDistance = 3.1 * PI / 180; // radians
    alwaysOkayDistance = 0.33; // 0.20;
    maxDistanceRatio = 2;
    maxFirstDistance = 1;
    alwaysAcceptDistance = 0.1;
    searchRange = 10;
    minDistForDistRatio = .08;
    maxDistForSkippingDistRatio = .4;
    simplifyContourThresh = 0;
    break;

  case SM_HOKUYO_URG:
    //These used to work well for a URG, haven't tested in a while.
    maxAdjacentDistance = 0.3;
    maxAdjacentAngularDistance = 10.0 * PI / 180; // radians
    alwaysOkayDistance = 0.15; // 0.20;
    maxDistanceRatio = 100;
    maxFirstDistance = .2;
    alwaysAcceptDistance = 0.05;
    searchRange = 8;
    minDistForDistRatio = .08;
    maxDistForSkippingDistRatio = .4;
    simplifyContourThresh = 0;
    break;

  case SM_SICK_LMS:
    //THESE ARE WHAT ED USED... PRESUMABLY WITH A SICK
    maxAdjacentDistance = 5;
    maxAdjacentAngularDistance = 3.1 * PI / 180; // radians
    alwaysOkayDistance = 0.33; // 0.20;
    maxDistanceRatio = 1.8;
    maxFirstDistance = 1;
    alwaysAcceptDistance = 0.1;
    searchRange = 4;
    minDistForDistRatio = .08;
    maxDistForSkippingDistRatio = .4;
    simplifyContourThresh = 0;
    break;

  default:
    fprintf(stderr, "ERROR: unknown laser type (%d) for ContourExtraction!\n", laser_type);
    exit(1);

  }
}

ContourExtractor::~ContourExtractor()
{

}

void ContourExtractor::findContours(smPoint * points, unsigned numValidPoints, std::vector<Contour*> &contours)
{

  priority_queue<Join*, std::vector<Join*>, JoinCompare> joins;

  std::vector<PointRecord> pointrecs;

  int range = searchRange;

  pointrecs.resize(numValidPoints);
  //  int i = 0;
  // create the point record table, one for every point.
  for (unsigned int parent = 0; parent < numValidPoints; parent++) {
    pointrecs[parent].point = points[parent];
  }

  // build the joins...
  // everybody gets their first pick to begin with.
  int numJoins = 0;
  for (unsigned int parent = 0; parent < pointrecs.size(); parent++) {
    Join *j;
    j = findClosestPoint(pointrecs, parent, parent - range, parent - 1);
    if (j != NULL) {
      joins.push(j);
      numJoins++;
    }

    j = findClosestPoint(pointrecs, parent, parent + 1, parent + range);
    if (j != NULL) {
      joins.push(j);
      numJoins++;
    }
  }

  // now we start plucking the best joins. If someone's best choice is
  // taken, we let them
  // pick a new partner and reinsert them into the queue.
  Join j;
  while (joins.size() > 0) {
    Join *jtmp = joins.top();
    joins.pop();
    j = *jtmp;
    delete jtmp;

    //    printf("JOIN cost=%f, parent=%d, victim=%d\n",j.cost,j.parent,j.victim);
    //    continue;

    // victim <--> parent
    if (j.parent > j.victim) {
      // if this parent has already been joined, we're done.
      if (pointrecs[j.parent].left >= 0)
        continue;

      // is the victim still available?
      if (pointrecs[j.victim].right < 0) {
        if (j.cost > alwaysOkayDistance) {
          if (pointrecs[j.victim].leftDistance > minDistForDistRatio && j.cost / pointrecs[j.victim].leftDistance
              > maxDistanceRatio)
            continue;
          else if (pointrecs[j.victim].leftDistance < minDistForDistRatio && j.cost > maxDistForSkippingDistRatio)
            continue;
          if (pointrecs[j.parent].rightDistance > minDistForDistRatio && j.cost / pointrecs[j.parent].rightDistance
              > maxDistanceRatio)
            continue;
          else if (pointrecs[j.parent].rightDistance < minDistForDistRatio && j.cost > maxDistForSkippingDistRatio)
            continue;

          if (pointrecs[j.victim].leftDistance < 0 && pointrecs[j.parent].rightDistance < 0 && j.cost
              > maxFirstDistance)
            continue;
        }

        // yes, join.
        pointrecs[j.victim].right = j.parent;
        pointrecs[j.parent].left = j.victim;
        pointrecs[j.parent].leftDistance = j.cost;
        pointrecs[j.victim].rightDistance = j.cost;
      }
      else {
        // search for a new point.
        jtmp = findClosestPoint(pointrecs, j.parent, j.parent - range, j.parent - 1);
        if (jtmp != NULL)
          joins.push(jtmp);
      }

      continue;
    }

    // parent <--> victim. Same as above, roles reversed.
    if (j.parent < j.victim) {
      if (pointrecs[j.parent].right >= 0)
        continue;

      if (pointrecs[j.victim].left < 0) {
        if (j.cost > alwaysOkayDistance) {

          if (pointrecs[j.parent].leftDistance > minDistForDistRatio && j.cost / pointrecs[j.parent].leftDistance
              > maxDistanceRatio)
            continue;
          else if (pointrecs[j.parent].leftDistance < minDistForDistRatio && j.cost > maxDistForSkippingDistRatio)
            continue;
          if (pointrecs[j.victim].rightDistance > minDistForDistRatio && j.cost / pointrecs[j.victim].rightDistance
              > maxDistanceRatio)
            continue;
          else if (pointrecs[j.victim].rightDistance < minDistForDistRatio && j.cost > maxDistForSkippingDistRatio)
            continue;

          if (pointrecs[j.parent].leftDistance < 0 && pointrecs[j.victim].rightDistance < 0 && j.cost
              > maxFirstDistance)
            continue;
        }

        pointrecs[j.victim].left = j.parent;
        pointrecs[j.parent].right = j.victim;
        pointrecs[j.parent].rightDistance = j.cost;
        pointrecs[j.victim].leftDistance = j.cost;

      }
      else {
        jtmp = findClosestPoint(pointrecs, j.parent, j.parent + 1, j.parent + range);
        if (jtmp != NULL)
          joins.push(jtmp);
      }
      continue;
    }

  }

  int contour = 0;

  // pull out the contours.
  for (unsigned int i = 0; i < pointrecs.size(); i++) {
    // we have a new contour.
    if (pointrecs[i].contour < 0) {
      //      if (debug)
      //        System.out.print("contour " + contour + " " + pointrecs[i].left + ": ");

      assert(pointrecs[i].left == -1);

      Contour * c = new Contour();
      int p = i;
      while (p >= 0) {
        //        if (debug)
        //          System.out.print(p + " ");
        c->points.push_back(pointrecs[p].point);
        pointrecs[p].contour = contour;
        p = pointrecs[p].right;
      }

      //      if (debug)
      //        System.out.println("");
      contour++;

      if (c->points.size() == 0) {
        printf("*Adding empty contour!?\n");
      }

      if (simplifyContourThresh > 0 && c->points.size() > 2) {
        c->simplify(simplifyContourThresh);
      }
      contours.push_back(c);

    }
  }

  pointrecs.clear();

}

Join *
ContourExtractor::findClosestPoint(std::vector<PointRecord> &pointrecs, int parent, int a, int b)
{
  if (a < 0)
    a = 0;
  if (a >= (int) pointrecs.size())
    a = pointrecs.size() - 1;

  if (b < 0)
    b = 0;
  if (b >= (int) pointrecs.size())
    b = pointrecs.size() - 1;

  if (a == parent || b == parent)
    return NULL;

  int bestvictim = -1;
  double bestcost = MAXDOUBLE;

  // how far a span was there in this contour between the last two points?

  // parent better not already have children on both left & right.
  assert(!(pointrecs[parent].left >= 0 && pointrecs[parent].right >= 0));

  smPoint parentp = pointrecs[parent].point;
  for (int i = a; i <= b; i++) {
    PointRecord victim = pointrecs[i];
    if (i == parent)
      continue; //shouldn't happen
    if (victim.left >= 0 && parent < i)
      continue;
    if (victim.right >= 0 && parent > i)
      continue;

    double cost = sm_dist(&parentp, &victim.point);

    if (cost <= alwaysAcceptDistance) {// && i == parent + 1) {
      // stop looking.
      //      bestcost = cost / 4;
      bestcost = cost; //ed had this division by 4... not sure  why.
      bestvictim = i;
      break;
    }

    if (cost < bestcost && cost < maxAdjacentDistance) {
      //      double angularDistance = fabs(sm_angle_subtract(atan2(parentp.y, parentp.x), atan2(victim.point.y, victim.point.x)));
      //
      //      if (angularDistance > maxAdjacentAngularDistance) {
      //        printf("rejected due to Angular distance\n");
      //        continue;
      //      }

      bestcost = cost;
      bestvictim = i;
    }
  }

  // ///////////////////////////////////////////////////
  if (bestvictim < 0)
    return NULL;

  return new Join(parent, bestvictim, bestcost);
}

// Copyright 2002, softSurfer (www.softsurfer.com)
// This code may be freely used and modified for any purpose
// providing that this copyright notice is included with it.
// SoftSurfer makes no warranty for this code, and cannot be held
// liable for any real or imagined damage resulting from its use.
// Users of this code must verify correctness for their application.

//  simplify():
//    Input:  tol = approximation tolerance
//      allPoints should contain the complete set of points
//    Output:
//      points will contain the simplified set of points

void Contour::simplify(float tol)
{
  int n = points.size();
  int pv; // misc counters
  points.reserve(n);

  // STAGE 1.  Vertex Reduction within tolerance of prior vertex cluster
  int m = 1;// first point always kept
  for (int i = 1, pv = 0; i < n - 1; i++) {
    if (sm_dist(&points[i], &points[pv]) < tol)
      continue;
    points[m] = points[i];
    pv = m++;
  }
  points[m++] = points[n - 1]; //make sure end is added
  //m vertices in vertex reduced polyline
  points.resize(m);

  // STAGE 2.  Douglas-Peucker polyline simplification
  vector<bool> mk(points.size(), false);
  mk[0] = mk.back() = 1; // mark the first and last vertices
  simplifyDP(tol, points, 0, points.size() - 1, mk);

  // copy marked vertices to the output simplified polyline
  m = 0;
  for (int i = 0; i < points.size(); i++) {
    if (mk[i])
      points[m++] = points[i]; //m<=i;
  }
  //m vertices in simplified polyline
  points.resize(m);

}

// simplifyDP():
//  This is the Douglas-Peucker recursive simplification routine
//  It just marks vertices that are part of the simplified polyline
//  for approximating the polyline subchain v[j] to v[k].
//    Input:  tol = approximation tolerance
//            v[] = polyline array of vertex points
//            j,k = indices for the subchain v[j] to v[k]
//    Output: mk[] = array of markers matching vertex array v[]
void Contour::simplifyDP(float tol, std::vector<smPoint> &v, int j, int k, std::vector<bool> &mk)
{
  if (k <= j + 1) // there is nothing to simplify
    return;

  // check for adequate approximation by segment S from v[j] to v[k]
  int maxi = j; // index of vertex farthest from segment
  float max_dist_to_seg = 0;
  // test each vertex v[i] for max distance from segment v[j]-v[k]
  for (int i = j + 1; i < k; i++) {
    double dist_to_seg = sm_dist_to_segment(&v[j], &v[j], &v[k]);
    if (dist_to_seg <= max_dist_to_seg)
      continue;
    else {
      // v[i] is a new max vertex
      maxi = i;
      max_dist_to_seg = dist_to_seg;
    }
  }
  if (max_dist_to_seg > tol) // error is worse than the tolerance
  {
    // split the polyline at the farthest vertex
    mk[maxi] = true; // mark v[maxi] for the simplified polyline
    // recursively simplify the two subpolylines at v[maxi]
    simplifyDP(tol, v, j, maxi, mk); // polyline v[j] to v[maxi]
    simplifyDP(tol, v, maxi, k, mk); // polyline v[maxi] to v[k]
  }
  // else the approximation is OK, so ignore intermediate vertices
  return;
}
//===================================================================

}//namespace scanmatch
<commit_msg>fix bug in contour simplification... was not  working at all previously<commit_after>#include "Contour.hpp"
#include <stdlib.h>
#include <vector>
#include <iostream>
#include <queue>
#include <string>
#include <math.h>
#include <values.h>
#include <assert.h>

using namespace std;
namespace scanmatch{

ContourExtractor::ContourExtractor(sm_laser_type_t laser_type):
    laserType(laser_type)
{
  switch (laser_type) {
  case SM_HOKUYO_UTM:
    maxAdjacentDistance = 6;
    maxAdjacentAngularDistance = 3.1 * PI / 180; // radians
    alwaysOkayDistance = 0.33; // 0.20;
    maxDistanceRatio = 2;
    maxFirstDistance = 1;
    alwaysAcceptDistance = 0.1;
    searchRange = 10;
    minDistForDistRatio = .08;
    maxDistForSkippingDistRatio = .4;
    simplifyContourThresh = 0;
    break;

  case SM_HOKUYO_URG:
    //These used to work well for a URG, haven't tested in a while.
    maxAdjacentDistance = 0.3;
    maxAdjacentAngularDistance = 10.0 * PI / 180; // radians
    alwaysOkayDistance = 0.15; // 0.20;
    maxDistanceRatio = 100;
    maxFirstDistance = .2;
    alwaysAcceptDistance = 0.05;
    searchRange = 8;
    minDistForDistRatio = .08;
    maxDistForSkippingDistRatio = .4;
    simplifyContourThresh = 0;
    break;

  case SM_SICK_LMS:
    //THESE ARE WHAT ED USED... PRESUMABLY WITH A SICK
    maxAdjacentDistance = 5;
    maxAdjacentAngularDistance = 3.1 * PI / 180; // radians
    alwaysOkayDistance = 0.33; // 0.20;
    maxDistanceRatio = 1.8;
    maxFirstDistance = 1;
    alwaysAcceptDistance = 0.1;
    searchRange = 4;
    minDistForDistRatio = .08;
    maxDistForSkippingDistRatio = .4;
    simplifyContourThresh = 0;
    break;

  default:
    fprintf(stderr, "ERROR: unknown laser type (%d) for ContourExtraction!\n", laser_type);
    exit(1);

  }
}

ContourExtractor::~ContourExtractor()
{

}

void ContourExtractor::findContours(smPoint * points, unsigned numValidPoints, std::vector<Contour*> &contours)
{

  priority_queue<Join*, std::vector<Join*>, JoinCompare> joins;

  std::vector<PointRecord> pointrecs;

  int range = searchRange;

  pointrecs.resize(numValidPoints);
  //  int i = 0;
  // create the point record table, one for every point.
  for (unsigned int parent = 0; parent < numValidPoints; parent++) {
    pointrecs[parent].point = points[parent];
  }

  // build the joins...
  // everybody gets their first pick to begin with.
  int numJoins = 0;
  for (unsigned int parent = 0; parent < pointrecs.size(); parent++) {
    Join *j;
    j = findClosestPoint(pointrecs, parent, parent - range, parent - 1);
    if (j != NULL) {
      joins.push(j);
      numJoins++;
    }

    j = findClosestPoint(pointrecs, parent, parent + 1, parent + range);
    if (j != NULL) {
      joins.push(j);
      numJoins++;
    }
  }

  // now we start plucking the best joins. If someone's best choice is
  // taken, we let them
  // pick a new partner and reinsert them into the queue.
  Join j;
  while (joins.size() > 0) {
    Join *jtmp = joins.top();
    joins.pop();
    j = *jtmp;
    delete jtmp;

    //    printf("JOIN cost=%f, parent=%d, victim=%d\n",j.cost,j.parent,j.victim);
    //    continue;

    // victim <--> parent
    if (j.parent > j.victim) {
      // if this parent has already been joined, we're done.
      if (pointrecs[j.parent].left >= 0)
        continue;

      // is the victim still available?
      if (pointrecs[j.victim].right < 0) {
        if (j.cost > alwaysOkayDistance) {
          if (pointrecs[j.victim].leftDistance > minDistForDistRatio && j.cost / pointrecs[j.victim].leftDistance
              > maxDistanceRatio)
            continue;
          else if (pointrecs[j.victim].leftDistance < minDistForDistRatio && j.cost > maxDistForSkippingDistRatio)
            continue;
          if (pointrecs[j.parent].rightDistance > minDistForDistRatio && j.cost / pointrecs[j.parent].rightDistance
              > maxDistanceRatio)
            continue;
          else if (pointrecs[j.parent].rightDistance < minDistForDistRatio && j.cost > maxDistForSkippingDistRatio)
            continue;

          if (pointrecs[j.victim].leftDistance < 0 && pointrecs[j.parent].rightDistance < 0 && j.cost
              > maxFirstDistance)
            continue;
        }

        // yes, join.
        pointrecs[j.victim].right = j.parent;
        pointrecs[j.parent].left = j.victim;
        pointrecs[j.parent].leftDistance = j.cost;
        pointrecs[j.victim].rightDistance = j.cost;
      }
      else {
        // search for a new point.
        jtmp = findClosestPoint(pointrecs, j.parent, j.parent - range, j.parent - 1);
        if (jtmp != NULL)
          joins.push(jtmp);
      }

      continue;
    }

    // parent <--> victim. Same as above, roles reversed.
    if (j.parent < j.victim) {
      if (pointrecs[j.parent].right >= 0)
        continue;

      if (pointrecs[j.victim].left < 0) {
        if (j.cost > alwaysOkayDistance) {

          if (pointrecs[j.parent].leftDistance > minDistForDistRatio && j.cost / pointrecs[j.parent].leftDistance
              > maxDistanceRatio)
            continue;
          else if (pointrecs[j.parent].leftDistance < minDistForDistRatio && j.cost > maxDistForSkippingDistRatio)
            continue;
          if (pointrecs[j.victim].rightDistance > minDistForDistRatio && j.cost / pointrecs[j.victim].rightDistance
              > maxDistanceRatio)
            continue;
          else if (pointrecs[j.victim].rightDistance < minDistForDistRatio && j.cost > maxDistForSkippingDistRatio)
            continue;

          if (pointrecs[j.parent].leftDistance < 0 && pointrecs[j.victim].rightDistance < 0 && j.cost
              > maxFirstDistance)
            continue;
        }

        pointrecs[j.victim].left = j.parent;
        pointrecs[j.parent].right = j.victim;
        pointrecs[j.parent].rightDistance = j.cost;
        pointrecs[j.victim].leftDistance = j.cost;

      }
      else {
        jtmp = findClosestPoint(pointrecs, j.parent, j.parent + 1, j.parent + range);
        if (jtmp != NULL)
          joins.push(jtmp);
      }
      continue;
    }

  }

  int contour = 0;

  // pull out the contours.
  for (unsigned int i = 0; i < pointrecs.size(); i++) {
    // we have a new contour.
    if (pointrecs[i].contour < 0) {
      //      if (debug)
      //        System.out.print("contour " + contour + " " + pointrecs[i].left + ": ");

      assert(pointrecs[i].left == -1);

      Contour * c = new Contour();
      int p = i;
      while (p >= 0) {
        //        if (debug)
        //          System.out.print(p + " ");
        c->points.push_back(pointrecs[p].point);
        pointrecs[p].contour = contour;
        p = pointrecs[p].right;
      }

      //      if (debug)
      //        System.out.println("");
      contour++;

      if (c->points.size() == 0) {
        printf("*Adding empty contour!?\n");
      }

      if (simplifyContourThresh > 0 && c->points.size() > 2) {
        c->simplify(simplifyContourThresh);
      }
      contours.push_back(c);

    }
  }

  pointrecs.clear();

}

Join *
ContourExtractor::findClosestPoint(std::vector<PointRecord> &pointrecs, int parent, int a, int b)
{
  if (a < 0)
    a = 0;
  if (a >= (int) pointrecs.size())
    a = pointrecs.size() - 1;

  if (b < 0)
    b = 0;
  if (b >= (int) pointrecs.size())
    b = pointrecs.size() - 1;

  if (a == parent || b == parent)
    return NULL;

  int bestvictim = -1;
  double bestcost = MAXDOUBLE;

  // how far a span was there in this contour between the last two points?

  // parent better not already have children on both left & right.
  assert(!(pointrecs[parent].left >= 0 && pointrecs[parent].right >= 0));

  smPoint parentp = pointrecs[parent].point;
  for (int i = a; i <= b; i++) {
    PointRecord victim = pointrecs[i];
    if (i == parent)
      continue; //shouldn't happen
    if (victim.left >= 0 && parent < i)
      continue;
    if (victim.right >= 0 && parent > i)
      continue;

    double cost = sm_dist(&parentp, &victim.point);

    if (cost <= alwaysAcceptDistance) {// && i == parent + 1) {
      // stop looking.
      //      bestcost = cost / 4;
      bestcost = cost; //ed had this division by 4... not sure  why.
      bestvictim = i;
      break;
    }

    if (cost < bestcost && cost < maxAdjacentDistance) {
      //      double angularDistance = fabs(sm_angle_subtract(atan2(parentp.y, parentp.x), atan2(victim.point.y, victim.point.x)));
      //
      //      if (angularDistance > maxAdjacentAngularDistance) {
      //        printf("rejected due to Angular distance\n");
      //        continue;
      //      }

      bestcost = cost;
      bestvictim = i;
    }
  }

  // ///////////////////////////////////////////////////
  if (bestvictim < 0)
    return NULL;

  return new Join(parent, bestvictim, bestcost);
}

// Copyright 2002, softSurfer (www.softsurfer.com)
// This code may be freely used and modified for any purpose
// providing that this copyright notice is included with it.
// SoftSurfer makes no warranty for this code, and cannot be held
// liable for any real or imagined damage resulting from its use.
// Users of this code must verify correctness for their application.

//  simplify():
//    Input:  tol = approximation tolerance
//      allPoints should contain the complete set of points
//    Output:
//      points will contain the simplified set of points

void Contour::simplify(float tol)
{
  int n = points.size();
  int pv; // misc counters

  // STAGE 1.  Vertex Reduction within tolerance of prior vertex cluster
  int m = 1;// first point always kept
  for (int i = 1, pv = 0; i < n - 1; i++) {
    if (sm_dist(&points[i], &points[pv]) < tol)
      continue;
    points[m] = points[i];
    pv = m++;
  }
  points[m++] = points[n - 1]; //make sure end is added
  //m vertices in vertex reduced polyline
  points.resize(m);

  // STAGE 2.  Douglas-Peucker polyline simplification
  vector<bool> mk(points.size(), false);
  mk[0] = mk.back() = 1; // mark the first and last vertices
  simplifyDP(tol, points, 0, points.size() - 1, mk);

  // copy marked vertices to the output simplified polyline
  m = 0;
  for (int i = 0; i < points.size(); i++) {
    if (mk[i])
      points[m++] = points[i]; //m<=i;
  }
  //m vertices in simplified polyline
  points.resize(m);

}

// simplifyDP():
//  This is the Douglas-Peucker recursive simplification routine
//  It just marks vertices that are part of the simplified polyline
//  for approximating the polyline subchain v[j] to v[k].
//    Input:  tol = approximation tolerance
//            v[] = polyline array of vertex points
//            j,k = indices for the subchain v[j] to v[k]
//    Output: mk[] = array of markers matching vertex array v[]
void Contour::simplifyDP(float tol, std::vector<smPoint> &v, int j, int k, std::vector<bool> &mk)
{
  if (k <= j + 1) // there is nothing to simplify
    return;

  // check for adequate approximation by segment S from v[j] to v[k]
  int maxi = j; // index of vertex farthest from segment
  float max_dist_to_seg = 0;
  // test each vertex v[i] for max distance from segment v[j]-v[k]
  for (int i = j + 1; i < k; i++) {
    double dist_to_seg = sm_dist_to_segment(&v[i], &v[j], &v[k]);
    if (dist_to_seg <= max_dist_to_seg)
      continue;
    else {
      // v[i] is a new max vertex
      maxi = i;
      max_dist_to_seg = dist_to_seg;
    }
  }
  if (max_dist_to_seg > tol) // error is worse than the tolerance
  {
    // split the polyline at the farthest vertex
    mk[maxi] = true; // mark v[maxi] for the simplified polyline
    // recursively simplify the two subpolylines at v[maxi]
    simplifyDP(tol, v, j, maxi, mk); // polyline v[j] to v[maxi]
    simplifyDP(tol, v, maxi, k, mk); // polyline v[maxi] to v[k]
  }
  // else the approximation is OK, so ignore intermediate vertices
  return;
}
//===================================================================

}//namespace scanmatch
<|endoftext|>


<commit_before>#ifndef STAN_MATH_FWD_MAT_META_OPERANDS_AND_PARTIALS_HPP
#define STAN_MATH_FWD_MAT_META_OPERANDS_AND_PARTIALS_HPP

#include <stan/math/fwd/mat/fun/typedefs.hpp>
#include <stan/math/fwd/scal/meta/operands_and_partials.hpp>
#include <stan/math/prim/scal/meta/broadcast_array.hpp>
#include <vector>

namespace stan {
  namespace math {
    namespace internal {
      // Vectorized Univariate
      template <typename Dx>
      class ops_partials_edge<Dx, std::vector<fvar<Dx> > > {
      public:
        typedef std::vector<fvar<Dx> > Op;
        typedef Eigen::Matrix<Dx, -1, 1> partials_t;
        partials_t partials_;  // For univariate use-cases
        broadcast_array<partials_t> partials_vec_;  // For multivariate
        explicit ops_partials_edge(const Op& ops)
          : partials_(partials_t::Zero(ops.size())),
            partials_vec_(partials_), operands_(ops) {}

      private:
        template<typename, typename, typename, typename, typename>
        friend class stan::math::operands_and_partials;
        const Op& operands_;

        Dx dx() {
          Dx derivative(0);
          for (size_t i = 0; i < this->operands_.size(); ++i) {
            derivative += this->partials_[i] * this->operands_[i].d_;
          }
          return derivative;
        }
      };

      template <typename Dx, int R, int C>
      class ops_partials_edge<Dx, Eigen::Matrix<fvar<Dx>, R, C> > {
      public:
        typedef Eigen::Matrix<Dx, R, C> partials_t;
        typedef Eigen::Matrix<fvar<Dx>, R, C> Op;
        partials_t partials_;  // For univariate use-cases
        broadcast_array<partials_t> partials_vec_;  // For multivariate
        explicit ops_partials_edge(const Op& ops)
          : partials_(partials_t::Zero(ops.rows(), ops.cols())),
            partials_vec_(partials_), operands_(ops) {}

      private:
        template<typename, typename, typename, typename, typename>
        friend class stan::math::operands_and_partials;
        const Op& operands_;

        Dx dx() {
          Dx derivative(0);
          for (int i = 0; i < this->operands_.size(); ++i) {
            derivative += this->partials_(i) * this->operands_(i).d_;
          }
          return derivative;
        }
      };

      // Multivariate; vectors of eigen types
      template <typename Dx, int R, int C>
      class ops_partials_edge<Dx, std::vector<Eigen::Matrix<fvar<Dx>, R, C> > > {
      public:
        typedef std::vector<Eigen::Matrix<fvar<Dx>, R, C> > Op;
        typedef Eigen::Matrix<Dx, -1, -1> partial_t;
        std::vector<partial_t> partials_vec_;
        explicit ops_partials_edge(const Op& ops)
          : partials_vec_(ops.size()), operands_(ops) {
          for (size_t i = 0; i < ops.size(); ++i) {
            partials_vec_[i] = partial_t::Zero(ops[i].rows(), ops[i].cols());
          }
        }

      private:
        template<typename, typename, typename, typename, typename>
        friend class stan::math::operands_and_partials;
        const Op& operands_;

        Dx dx() {
          Dx derivative(0);
          for (size_t i = 0; i < this->operands_.size(); ++i) {
            for (int j = 0; j < this->operands_[i].size(); ++j) {
              derivative
                += this->partials_vec_[i](j) * this->operands_[i](j).d_;
            }
          }
          return derivative;
        }
      };
    }  // namespace internal
  }  // namespace math
}  // namespace stan
#endif
<commit_msg>cpplint<commit_after>#ifndef STAN_MATH_FWD_MAT_META_OPERANDS_AND_PARTIALS_HPP
#define STAN_MATH_FWD_MAT_META_OPERANDS_AND_PARTIALS_HPP

#include <stan/math/fwd/mat/fun/typedefs.hpp>
#include <stan/math/fwd/scal/meta/operands_and_partials.hpp>
#include <stan/math/prim/scal/meta/broadcast_array.hpp>
#include <vector>

namespace stan {
  namespace math {
    namespace internal {
      // Vectorized Univariate
      template <typename Dx>
      class ops_partials_edge<Dx, std::vector<fvar<Dx> > > {
      public:
        typedef std::vector<fvar<Dx> > Op;
        typedef Eigen::Matrix<Dx, -1, 1> partials_t;
        partials_t partials_;  // For univariate use-cases
        broadcast_array<partials_t> partials_vec_;  // For multivariate
        explicit ops_partials_edge(const Op& ops)
          : partials_(partials_t::Zero(ops.size())),
            partials_vec_(partials_), operands_(ops) {}

      private:
        template<typename, typename, typename, typename, typename>
        friend class stan::math::operands_and_partials;
        const Op& operands_;

        Dx dx() {
          Dx derivative(0);
          for (size_t i = 0; i < this->operands_.size(); ++i) {
            derivative += this->partials_[i] * this->operands_[i].d_;
          }
          return derivative;
        }
      };

      template <typename Dx, int R, int C>
      class ops_partials_edge<Dx, Eigen::Matrix<fvar<Dx>, R, C> > {
      public:
        typedef Eigen::Matrix<Dx, R, C> partials_t;
        typedef Eigen::Matrix<fvar<Dx>, R, C> Op;
        partials_t partials_;  // For univariate use-cases
        broadcast_array<partials_t> partials_vec_;  // For multivariate
        explicit ops_partials_edge(const Op& ops)
          : partials_(partials_t::Zero(ops.rows(), ops.cols())),
            partials_vec_(partials_), operands_(ops) {}

      private:
        template<typename, typename, typename, typename, typename>
        friend class stan::math::operands_and_partials;
        const Op& operands_;

        Dx dx() {
          Dx derivative(0);
          for (int i = 0; i < this->operands_.size(); ++i) {
            derivative += this->partials_(i) * this->operands_(i).d_;
          }
          return derivative;
        }
      };

      // Multivariate; vectors of eigen types
      template <typename Dx, int R, int C>
      class ops_partials_edge
      <Dx, std::vector<Eigen::Matrix<fvar<Dx>, R, C> > > {
      public:
        typedef std::vector<Eigen::Matrix<fvar<Dx>, R, C> > Op;
        typedef Eigen::Matrix<Dx, -1, -1> partial_t;
        std::vector<partial_t> partials_vec_;
        explicit ops_partials_edge(const Op& ops)
          : partials_vec_(ops.size()), operands_(ops) {
          for (size_t i = 0; i < ops.size(); ++i) {
            partials_vec_[i] = partial_t::Zero(ops[i].rows(), ops[i].cols());
          }
        }

      private:
        template<typename, typename, typename, typename, typename>
        friend class stan::math::operands_and_partials;
        const Op& operands_;

        Dx dx() {
          Dx derivative(0);
          for (size_t i = 0; i < this->operands_.size(); ++i) {
            for (int j = 0; j < this->operands_[i].size(); ++j) {
              derivative
                += this->partials_vec_[i](j) * this->operands_[i](j).d_;
            }
          }
          return derivative;
        }
      };
    }  // namespace internal
  }  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: urp_log.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 22:47:03 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
namespace bridges_urp
{
#ifndef PRODUCT
#define BRIDGES_URP_PROT
#endif

#ifdef BRIDGES_URP_PROT
    void urp_logCall( urp_BridgeImpl *pBridgeImpl ,
                      sal_Int32 nSize, sal_Int32 nUseData, sal_Bool bSynchron ,
                      const ::rtl::OUString &sMethodName );

    void urp_logServingRequest( urp_BridgeImpl *pBridgeImpl,
                                sal_Int32 nSize, sal_Int32 nUseData, sal_Bool bSynchron ,
                                const ::rtl::OUString &sMethodName );

    void urp_logGettingReply( urp_BridgeImpl *pBridgeImpl,
                              sal_Int32 nSize, sal_Int32 nUseData,
                              const ::rtl::OUString &sMethodName );

    void urp_logReplying( urp_BridgeImpl *pBridgeImpl,
                          sal_Int32 nSize , sal_Int32 nUseData,
                          const ::rtl::OUString &sMethodName );
#endif
}
<commit_msg>INTEGRATION: CWS changefileheader (1.6.170); FILE MERGED 2008/03/28 16:30:57 rt 1.6.170.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: urp_log.hxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
namespace bridges_urp
{
#ifndef PRODUCT
#define BRIDGES_URP_PROT
#endif

#ifdef BRIDGES_URP_PROT
    void urp_logCall( urp_BridgeImpl *pBridgeImpl ,
                      sal_Int32 nSize, sal_Int32 nUseData, sal_Bool bSynchron ,
                      const ::rtl::OUString &sMethodName );

    void urp_logServingRequest( urp_BridgeImpl *pBridgeImpl,
                                sal_Int32 nSize, sal_Int32 nUseData, sal_Bool bSynchron ,
                                const ::rtl::OUString &sMethodName );

    void urp_logGettingReply( urp_BridgeImpl *pBridgeImpl,
                              sal_Int32 nSize, sal_Int32 nUseData,
                              const ::rtl::OUString &sMethodName );

    void urp_logReplying( urp_BridgeImpl *pBridgeImpl,
                          sal_Int32 nSize , sal_Int32 nUseData,
                          const ::rtl::OUString &sMethodName );
#endif
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: namesort.cxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: np $ $Date: 2002-11-01 17:14:08 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <precomp.h>
#include <namesort.hxx>

// NOT FULLY DEFINED SERVICES

namespace
{

int C_cAryNameOrdering1[256] =
    {   0,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255, //  0 ..
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255, // 32 ..
       71, 72, 73, 74,  75, 76, 77, 78,      79, 80,255,255, 255,255,255,255,

      255, 11, 13, 15,  17, 19, 21, 23,      25, 27, 29, 31,  33, 35, 37, 39, // 64 ..
       41, 43, 45, 47,  49, 51, 53, 55,      57, 59, 61,255, 255,255,255, 63,
      255, 11, 13, 15,  17, 19, 21, 23,      25, 27, 29, 31,  33, 35, 37, 39, // 96 ..
       41, 43, 45, 47,  49, 51, 53, 55,      57, 59, 61,255, 255,255,255,255,

      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255, //128 ..
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255, //160 ..
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,

      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255
    };

int C_cAryNameOrdering2[256] =
    {   0,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255, //  0 ..
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255, // 32 ..
       71, 72, 73, 74,  75, 76, 77, 78,      79, 80,255,255, 255,255,255,255,

      255, 11, 13, 15,  17, 19, 21, 23,      25, 27, 29, 31,  33, 35, 37, 39, // 64 ..
       41, 43, 45, 47,  49, 51, 53, 55,      57, 59, 61,255, 255,255,255, 63,
      255, 12, 14, 16,  18, 20, 22, 24,      26, 28, 30, 32,  34, 36, 38, 40, // 96 ..
       42, 44, 46, 48,  50, 52, 54, 56,      58, 60, 62,255, 255,255,255,255,

      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255, //128 ..
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255, //160 ..
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,

      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255
    };
}

namespace ary
{

CompareCeNames::CompareCeNames()
    :   aOrdering1(C_cAryNameOrdering1),
        aOrdering2(C_cAryNameOrdering2)
{
}

}   // namespace ary

<commit_msg>INTEGRATION: CWS ooo19126 (1.1.132); FILE MERGED 2005/09/05 13:10:29 rt 1.1.132.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: namesort.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 17:13:22 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <precomp.h>
#include <namesort.hxx>

// NOT FULLY DEFINED SERVICES

namespace
{

int C_cAryNameOrdering1[256] =
    {   0,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255, //  0 ..
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255, // 32 ..
       71, 72, 73, 74,  75, 76, 77, 78,      79, 80,255,255, 255,255,255,255,

      255, 11, 13, 15,  17, 19, 21, 23,      25, 27, 29, 31,  33, 35, 37, 39, // 64 ..
       41, 43, 45, 47,  49, 51, 53, 55,      57, 59, 61,255, 255,255,255, 63,
      255, 11, 13, 15,  17, 19, 21, 23,      25, 27, 29, 31,  33, 35, 37, 39, // 96 ..
       41, 43, 45, 47,  49, 51, 53, 55,      57, 59, 61,255, 255,255,255,255,

      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255, //128 ..
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255, //160 ..
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,

      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255
    };

int C_cAryNameOrdering2[256] =
    {   0,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255, //  0 ..
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255, // 32 ..
       71, 72, 73, 74,  75, 76, 77, 78,      79, 80,255,255, 255,255,255,255,

      255, 11, 13, 15,  17, 19, 21, 23,      25, 27, 29, 31,  33, 35, 37, 39, // 64 ..
       41, 43, 45, 47,  49, 51, 53, 55,      57, 59, 61,255, 255,255,255, 63,
      255, 12, 14, 16,  18, 20, 22, 24,      26, 28, 30, 32,  34, 36, 38, 40, // 96 ..
       42, 44, 46, 48,  50, 52, 54, 56,      58, 60, 62,255, 255,255,255,255,

      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255, //128 ..
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255, //160 ..
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,

      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255,
      255,255,255,255, 255,255,255,255,     255,255,255,255, 255,255,255,255
    };
}

namespace ary
{

CompareCeNames::CompareCeNames()
    :   aOrdering1(C_cAryNameOrdering1),
        aOrdering2(C_cAryNameOrdering2)
{
}

}   // namespace ary

<|endoftext|>