<commit_before>/// HEADER
#include "random_trees_trainer.h"

/// PROJECT
#include <csapex/msg/io.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/model/node_modifier.h>
#include <csapex/msg/generic_vector_message.hpp>

/// SYSTEM
#include <opencv2/ml/ml.hpp>

CSAPEX_REGISTER_CLASS(csapex::RandomTreesTrainer, csapex::Node)

using namespace csapex;
using namespace csapex::connection_types;

RandomTreesTrainer::RandomTreesTrainer()
    : categories_(0)
{
}

void RandomTreesTrainer::setupParameters(Parameterizable& parameters)
{
    MachineLearningNode::setupParameters(parameters);

    addParameter(csapex::param::ParameterFactory::declareRange<int>
                 ("classes",
                  csapex::param::ParameterDescription("Number of classes to learn."),
                  0, 100, 2, 1),
                 std::bind(&RandomTreesTrainer::updatePriors, this));;

    addParameter(csapex::param::ParameterFactory::declareRange<int>
                 ("max depth",
                  csapex::param::ParameterDescription("the depth of the tree. A low value will likely underfit and conversely a high value will likely overfit.\n"
                                                      "The optimal value can be obtained using cross validation or other suitable methods."),
                  1, 64, 8, 1));;
    addParameter(csapex::param::ParameterFactory::declareRange<int>
                 ("min sample count",
                  csapex::param::ParameterDescription("minimum samples required at a leaf node for it to be split.\n"
                                                      "A reasonable value is a small percentage of the total data e.g. 1%."),
                  0, 64, 10, 1));
    addParameter(csapex::param::ParameterFactory::declareRange<double>
                 ("regression accuracy",
                  csapex::param::ParameterDescription("Termination criteria for regression trees. \n"
                                                      "If all absolute differences between an estimated value in a node and values of train samples in this node \n"
                                                      "are less than this parameter then the node will not be split."),
                  0.0, 255.0, 0.0, 0.01));;
    addParameter(csapex::param::ParameterFactory::declareBool
                 ("use surrogates",
                  csapex::param::ParameterDescription("If true then surrogate splits will be built. \n"
                                                      "These splits allow to work with missing data and compute variable importance correctly."),
                  true));;
    addParameter(csapex::param::ParameterFactory::declareRange<int>
                 ("max categories",
                  csapex::param::ParameterDescription("Cluster possible values of a categorical variable into K <= max_categories clusters to find a suboptimal split.\n"
                                                      "If a discrete variable, on which the training procedure tries to make a split, takes more than max_categories values,\n"
                                                      "the precise best subset estimation may take a very long time because the algorithm is exponential.\n"
                                                      "Instead, many decision trees engines (including ML) try to find sub-optimal split in this case by clustering all\n"
                                                      "the samples into max_categories clusters that is some categories are merged together.\n"
                                                      "The clustering is applied only in n>2-class classification problems for categorical variables\n"
                                                      "with N > max_categories possible values.\n"
                                                      "In case of regression and 2-class classification the optimal split can be found efficiently without employing clustering,\n"
                                                      "thus the parameter is not used in these cases."),
                  0, 100, 15, 1));;

    addParameter(csapex::param::ParameterFactory::declareBool
                 ("calc_var_importance",
                  csapex::param::ParameterDescription("If true then variable importance will be calculated and then it can be retrieved by CvRTrees::get_var_importance()."),
                  false));

    addParameter(csapex::param::ParameterFactory::declareRange<int>
                 ("nactive_vars",
                  csapex::param::ParameterDescription("The size of the randomly selected subset of features at each tree node and that are used to find the best split(s).\n"
                                                      "If you set it to 0 then the size will be set to the square root of the total number of features."),
                  0, 100, 0, 1));
    addParameter(csapex::param::ParameterFactory::declareRange<int>
                 ("max_num_of_trees_in_the_forest",
                  csapex::param::ParameterDescription("The maximum number of trees in the forest (surprise, surprise). Typically the more trees you have the better the accuracy.\n"
                                                      "However, the improvement in accuracy generally diminishes and asymptotes pass a certain number of trees.\n"
                                                      "Also to keep in mind, the number of tree increases the prediction time linearly."),
                  1, 1024, 16, 1));
    addParameter(csapex::param::ParameterFactory::declareRange<double>
                 ("forest_accuracy",
                  csapex::param::ParameterDescription("Sufficient accuracy (OOB error)."),
                  0.0, 1.0, 0.5, 0.01));

    std::map<std::string, int> termcrit_type = {
        {"CV_TERMCRIT_ITER", (int) CV_TERMCRIT_ITER},
        {"CV_TERMCRIT_EPS", (int) CV_TERMCRIT_EPS},
        {"CV_TERMCRIT_ITER | CV_TERMCRIT_EPS", (int) CV_TERMCRIT_ITER | CV_TERMCRIT_EPS}
    };

    csapex::param::Parameter::Ptr termcrit_type_p = csapex::param::ParameterFactory::declareParameterSet
            ("termcrit_type",
             csapex::param::ParameterDescription("The type of the termination criteria:\n"
                                                 "CV_TERMCRIT_ITER Terminate learning by the max_num_of_trees_in_the_forest;\n"
                                                 "CV_TERMCRIT_EPS Terminate learning by the forest_accuracy;\n"
                                                 "CV_TERMCRIT_ITER | CV_TERMCRIT_EPS Use both termination criteria."),
             termcrit_type, (int) (CV_TERMCRIT_ITER | CV_TERMCRIT_EPS));
    parameters.addParameter(termcrit_type_p);
}

void RandomTreesTrainer::updatePriors()
{
    int categories = readParameter<int>("classes");

    if(categories != categories_) {
        if(categories > categories_) {
            for(int c = categories_; c < categories; ++c) {
                std::stringstream name;
                name << "~priors/" << c;
                csapex::param::Parameter::Ptr p = csapex::param::ParameterFactory::declareRange<double>(name.str(), 0.0, 50.0, 1.0, 0.01);
                priors_params_.push_back(p);
                addTemporaryParameter(p, std::bind(&RandomTreesTrainer::udpatePriorValues, this));
            }
        } else {
            for(int c = categories_-1; c >= categories; --c) {
                removeTemporaryParameter(priors_params_[c]);
                priors_params_.pop_back();
            }
        }
        categories_ = categories;
    }
}

void RandomTreesTrainer::udpatePriorValues()
{
    if(priors_.size() != priors_params_.size()) {
        priors_.resize(priors_params_.size());
    }

    for(std::size_t i = 0, total = priors_.size(); i < total; ++i) {
        priors_[i] = priors_params_[i]->as<double>();
    }
}

bool RandomTreesTrainer::processCollection(std::vector<connection_types::FeaturesMessage>& collection)
{
    FeaturesMessage& first_feature = collection[0];
    std::size_t feature_length = first_feature.value.size();
    std::size_t responses_length = first_feature.regression_result.size();
    std::size_t collection_size = collection.size();

    cv::Mat train_data(collection_size, feature_length, CV_32FC1, cv::Scalar());
    cv::Mat missing(collection_size, feature_length, CV_8UC1, cv::Scalar(0));

    cv::Mat responses;
    if(is_classification_){
         // classification problem
        responses = cv::Mat(collection_size, 1, CV_32SC1, cv::Scalar());
    }
    else{
        // regression problem
        responses = cv::Mat(collection_size, responses_length, CV_32FC1, cv::Scalar());
    }

#if CV_MAJOR_VERSION == 2
    int tflag = CV_ROW_SAMPLE;
#elif CV_MAJOR_VERSION == 3
    int tflag = cv::ml::ROW_SAMPLE;
#endif

    std::set<int> classifications;
    for(std::size_t i = 0; i < collection_size; ++i) {
        FeaturesMessage& feature = collection[i];
        for(std::size_t j = 0; j < feature_length; ++j) {
            const float& val = feature.value[j];

            if(std::abs(val) >= FLT_MAX*0.5f) {
                missing.at<uchar>(i,j) = 1;
            } else {
                train_data.at<float>(i,j) = val;
            }
        }
        if(is_classification_){ // classification problem
            responses.at<int>(i,0) = feature.classification;
            classifications.insert(feature.classification);
        }
        else{ // regression problem
            for(std::size_t j = 0; j < responses_length; ++j){
                const float& val = feature.regression_result[j];

                if(std::abs(val) < FLT_MAX*0.5f) {
                    responses.at<float>(i,j) = val;
                }
            }
        }
    }

#if CV_MAJOR_VERSION == 2
    CvRTParams params( readParameter<int>("max depth"),
                       readParameter<int>("min sample count"),
                       readParameter<double>("regression accuracy"),
                       readParameter<bool>("use surrogates"),
                       readParameter<int>("max categories"),
                       priors_.data(),
                       readParameter<bool>("calc_var_importance"),
                       readParameter<int>("nactive_vars"),
                       readParameter<int>("max_num_of_trees_in_the_forest"),
                       readParameter<double>("forest_accuracy"),
                       readParameter<int>("termcrit_type"));

    cv::Mat var_type( train_data.cols + 1, 1, CV_8U, CV_VAR_NUMERICAL);

    cv::RandomTrees rtrees;
    std::cout << "[RandomTrees]: Started training with " << n << " samples!" << std::endl;
    if(rtrees.train(train_data, tflag, responses, cv::Mat(), cv::Mat(), var_type, cv::Mat(), params)) {
        cv::FileStorage fs(file_name_, cv::FileStorage::WRITE);
        rtrees.write(fs.fs, "random_forest");
        fs << "classes" << "[";
        for(int i : classifications) {
            fs << i;
        }
        fs << "]";
        fs.release();
        std::cout << "[RandomTrees]: Finished training!" << std::endl;
    } else {
        return false;
    }

#elif CV_MAJOR_VERSION == 3
    auto rtrees = cv::ml::RTrees::create();
    rtrees->setMaxDepth(readParameter<int>("max depth"));
    rtrees->setMinSampleCount(readParameter<int>("min sample count"));
    rtrees->setRegressionAccuracy(readParameter<double>("regression accuracy"));
    rtrees->setUseSurrogates(readParameter<bool>("use surrogates"));
    rtrees->setMaxCategories(readParameter<int>("max categories"));
    rtrees->setCalculateVarImportance(readParameter<bool>("calc_var_importance"));
    rtrees->setActiveVarCount(readParameter<int>("nactive_vars"));

    cv::TermCriteria term(readParameter<int>("termcrit_type"), readParameter<int>("max_num_of_trees_in_the_forest"), readParameter<double>("forest_accuracy"));
    rtrees->setTermCriteria(term);

    cv::Mat priors(priors_);
    rtrees->setPriors(priors);

    cv::Mat var_type( train_data.cols + 1, 1, CV_8U, cv::ml::VAR_NUMERICAL);

    cv::Ptr<cv::ml::TrainData> train_data_struct = cv::ml::TrainData::create(train_data,
                                                                             tflag,
                                                                             responses,
                                                                             cv::noArray(), cv::noArray(), cv::noArray(),
                                                                             var_type);

    std::cout << "[RandomTrees]: Started training with " << train_data.rows << " samples!" << std::endl;
    if(rtrees->train(train_data_struct)) {
        cv::FileStorage fs(file_name_, cv::FileStorage::WRITE);
        rtrees->write(fs);
        std::cout << "[RandomTrees]: Finished training!" << std::endl;
    } else {
        return false;
    }
#endif

    return true;
}

<commit_msg>build fix indigo, jade<commit_after>/// HEADER
#include "random_trees_trainer.h"

/// PROJECT
#include <csapex/msg/io.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/model/node_modifier.h>
#include <csapex/msg/generic_vector_message.hpp>

/// SYSTEM
#include <opencv2/ml/ml.hpp>

CSAPEX_REGISTER_CLASS(csapex::RandomTreesTrainer, csapex::Node)

using namespace csapex;
using namespace csapex::connection_types;

RandomTreesTrainer::RandomTreesTrainer()
    : categories_(0)
{
}

void RandomTreesTrainer::setupParameters(Parameterizable& parameters)
{
    MachineLearningNode::setupParameters(parameters);

    addParameter(csapex::param::ParameterFactory::declareRange<int>
                 ("classes",
                  csapex::param::ParameterDescription("Number of classes to learn."),
                  0, 100, 2, 1),
                 std::bind(&RandomTreesTrainer::updatePriors, this));;

    addParameter(csapex::param::ParameterFactory::declareRange<int>
                 ("max depth",
                  csapex::param::ParameterDescription("the depth of the tree. A low value will likely underfit and conversely a high value will likely overfit.\n"
                                                      "The optimal value can be obtained using cross validation or other suitable methods."),
                  1, 64, 8, 1));;
    addParameter(csapex::param::ParameterFactory::declareRange<int>
                 ("min sample count",
                  csapex::param::ParameterDescription("minimum samples required at a leaf node for it to be split.\n"
                                                      "A reasonable value is a small percentage of the total data e.g. 1%."),
                  0, 64, 10, 1));
    addParameter(csapex::param::ParameterFactory::declareRange<double>
                 ("regression accuracy",
                  csapex::param::ParameterDescription("Termination criteria for regression trees. \n"
                                                      "If all absolute differences between an estimated value in a node and values of train samples in this node \n"
                                                      "are less than this parameter then the node will not be split."),
                  0.0, 255.0, 0.0, 0.01));;
    addParameter(csapex::param::ParameterFactory::declareBool
                 ("use surrogates",
                  csapex::param::ParameterDescription("If true then surrogate splits will be built. \n"
                                                      "These splits allow to work with missing data and compute variable importance correctly."),
                  true));;
    addParameter(csapex::param::ParameterFactory::declareRange<int>
                 ("max categories",
                  csapex::param::ParameterDescription("Cluster possible values of a categorical variable into K <= max_categories clusters to find a suboptimal split.\n"
                                                      "If a discrete variable, on which the training procedure tries to make a split, takes more than max_categories values,\n"
                                                      "the precise best subset estimation may take a very long time because the algorithm is exponential.\n"
                                                      "Instead, many decision trees engines (including ML) try to find sub-optimal split in this case by clustering all\n"
                                                      "the samples into max_categories clusters that is some categories are merged together.\n"
                                                      "The clustering is applied only in n>2-class classification problems for categorical variables\n"
                                                      "with N > max_categories possible values.\n"
                                                      "In case of regression and 2-class classification the optimal split can be found efficiently without employing clustering,\n"
                                                      "thus the parameter is not used in these cases."),
                  0, 100, 15, 1));;

    addParameter(csapex::param::ParameterFactory::declareBool
                 ("calc_var_importance",
                  csapex::param::ParameterDescription("If true then variable importance will be calculated and then it can be retrieved by CvRTrees::get_var_importance()."),
                  false));

    addParameter(csapex::param::ParameterFactory::declareRange<int>
                 ("nactive_vars",
                  csapex::param::ParameterDescription("The size of the randomly selected subset of features at each tree node and that are used to find the best split(s).\n"
                                                      "If you set it to 0 then the size will be set to the square root of the total number of features."),
                  0, 100, 0, 1));
    addParameter(csapex::param::ParameterFactory::declareRange<int>
                 ("max_num_of_trees_in_the_forest",
                  csapex::param::ParameterDescription("The maximum number of trees in the forest (surprise, surprise). Typically the more trees you have the better the accuracy.\n"
                                                      "However, the improvement in accuracy generally diminishes and asymptotes pass a certain number of trees.\n"
                                                      "Also to keep in mind, the number of tree increases the prediction time linearly."),
                  1, 1024, 16, 1));
    addParameter(csapex::param::ParameterFactory::declareRange<double>
                 ("forest_accuracy",
                  csapex::param::ParameterDescription("Sufficient accuracy (OOB error)."),
                  0.0, 1.0, 0.5, 0.01));

    std::map<std::string, int> termcrit_type = {
        {"CV_TERMCRIT_ITER", (int) CV_TERMCRIT_ITER},
        {"CV_TERMCRIT_EPS", (int) CV_TERMCRIT_EPS},
        {"CV_TERMCRIT_ITER | CV_TERMCRIT_EPS", (int) CV_TERMCRIT_ITER | CV_TERMCRIT_EPS}
    };

    csapex::param::Parameter::Ptr termcrit_type_p = csapex::param::ParameterFactory::declareParameterSet
            ("termcrit_type",
             csapex::param::ParameterDescription("The type of the termination criteria:\n"
                                                 "CV_TERMCRIT_ITER Terminate learning by the max_num_of_trees_in_the_forest;\n"
                                                 "CV_TERMCRIT_EPS Terminate learning by the forest_accuracy;\n"
                                                 "CV_TERMCRIT_ITER | CV_TERMCRIT_EPS Use both termination criteria."),
             termcrit_type, (int) (CV_TERMCRIT_ITER | CV_TERMCRIT_EPS));
    parameters.addParameter(termcrit_type_p);
}

void RandomTreesTrainer::updatePriors()
{
    int categories = readParameter<int>("classes");

    if(categories != categories_) {
        if(categories > categories_) {
            for(int c = categories_; c < categories; ++c) {
                std::stringstream name;
                name << "~priors/" << c;
                csapex::param::Parameter::Ptr p = csapex::param::ParameterFactory::declareRange<double>(name.str(), 0.0, 50.0, 1.0, 0.01);
                priors_params_.push_back(p);
                addTemporaryParameter(p, std::bind(&RandomTreesTrainer::udpatePriorValues, this));
            }
        } else {
            for(int c = categories_-1; c >= categories; --c) {
                removeTemporaryParameter(priors_params_[c]);
                priors_params_.pop_back();
            }
        }
        categories_ = categories;
    }
}

void RandomTreesTrainer::udpatePriorValues()
{
    if(priors_.size() != priors_params_.size()) {
        priors_.resize(priors_params_.size());
    }

    for(std::size_t i = 0, total = priors_.size(); i < total; ++i) {
        priors_[i] = priors_params_[i]->as<double>();
    }
}

bool RandomTreesTrainer::processCollection(std::vector<connection_types::FeaturesMessage>& collection)
{
    FeaturesMessage& first_feature = collection[0];
    std::size_t feature_length = first_feature.value.size();
    std::size_t responses_length = first_feature.regression_result.size();
    std::size_t collection_size = collection.size();

    cv::Mat train_data(collection_size, feature_length, CV_32FC1, cv::Scalar());
    cv::Mat missing(collection_size, feature_length, CV_8UC1, cv::Scalar(0));

    cv::Mat responses;
    if(is_classification_){
         // classification problem
        responses = cv::Mat(collection_size, 1, CV_32SC1, cv::Scalar());
    }
    else{
        // regression problem
        responses = cv::Mat(collection_size, responses_length, CV_32FC1, cv::Scalar());
    }

#if CV_MAJOR_VERSION == 2
    int tflag = CV_ROW_SAMPLE;
#elif CV_MAJOR_VERSION == 3
    int tflag = cv::ml::ROW_SAMPLE;
#endif

    std::set<int> classifications;
    for(std::size_t i = 0; i < collection_size; ++i) {
        FeaturesMessage& feature = collection[i];
        for(std::size_t j = 0; j < feature_length; ++j) {
            const float& val = feature.value[j];

            if(std::abs(val) >= FLT_MAX*0.5f) {
                missing.at<uchar>(i,j) = 1;
            } else {
                train_data.at<float>(i,j) = val;
            }
        }
        if(is_classification_){ // classification problem
            responses.at<int>(i,0) = feature.classification;
            classifications.insert(feature.classification);
        }
        else{ // regression problem
            for(std::size_t j = 0; j < responses_length; ++j){
                const float& val = feature.regression_result[j];

                if(std::abs(val) < FLT_MAX*0.5f) {
                    responses.at<float>(i,j) = val;
                }
            }
        }
    }

#if CV_MAJOR_VERSION == 2
    CvRTParams params( readParameter<int>("max depth"),
                       readParameter<int>("min sample count"),
                       readParameter<double>("regression accuracy"),
                       readParameter<bool>("use surrogates"),
                       readParameter<int>("max categories"),
                       priors_.data(),
                       readParameter<bool>("calc_var_importance"),
                       readParameter<int>("nactive_vars"),
                       readParameter<int>("max_num_of_trees_in_the_forest"),
                       readParameter<double>("forest_accuracy"),
                       readParameter<int>("termcrit_type"));

    cv::Mat var_type( train_data.cols + 1, 1, CV_8U, CV_VAR_NUMERICAL);

    cv::RandomTrees rtrees;
    std::cout << "[RandomTrees]: Started training with " << collection_size << " samples!" << std::endl;
    if(rtrees.train(train_data, tflag, responses, cv::Mat(), cv::Mat(), var_type, cv::Mat(), params)) {
        cv::FileStorage fs(file_name_, cv::FileStorage::WRITE);
        rtrees.write(fs.fs, "random_forest");
        fs << "classes" << "[";
        for(int i : classifications) {
            fs << i;
        }
        fs << "]";
        fs.release();
        std::cout << "[RandomTrees]: Finished training!" << std::endl;
    } else {
        return false;
    }

#elif CV_MAJOR_VERSION == 3
    auto rtrees = cv::ml::RTrees::create();
    rtrees->setMaxDepth(readParameter<int>("max depth"));
    rtrees->setMinSampleCount(readParameter<int>("min sample count"));
    rtrees->setRegressionAccuracy(readParameter<double>("regression accuracy"));
    rtrees->setUseSurrogates(readParameter<bool>("use surrogates"));
    rtrees->setMaxCategories(readParameter<int>("max categories"));
    rtrees->setCalculateVarImportance(readParameter<bool>("calc_var_importance"));
    rtrees->setActiveVarCount(readParameter<int>("nactive_vars"));

    cv::TermCriteria term(readParameter<int>("termcrit_type"), readParameter<int>("max_num_of_trees_in_the_forest"), readParameter<double>("forest_accuracy"));
    rtrees->setTermCriteria(term);

    cv::Mat priors(priors_);
    rtrees->setPriors(priors);

    cv::Mat var_type( train_data.cols + 1, 1, CV_8U, cv::ml::VAR_NUMERICAL);

    cv::Ptr<cv::ml::TrainData> train_data_struct = cv::ml::TrainData::create(train_data,
                                                                             tflag,
                                                                             responses,
                                                                             cv::noArray(), cv::noArray(), cv::noArray(),
                                                                             var_type);

    std::cout << "[RandomTrees]: Started training with " << train_data.rows << " samples!" << std::endl;
    if(rtrees->train(train_data_struct)) {
        cv::FileStorage fs(file_name_, cv::FileStorage::WRITE);
        rtrees->write(fs);
        std::cout << "[RandomTrees]: Finished training!" << std::endl;
    } else {
        return false;
    }
#endif

    return true;
}

<|endoftext|>


<commit_before>//
// Created by Davide Caroselli on 04/09/16.
//

#include <symal/SymAlignment.h>
#include "FastAligner.h"
#include <thread>
#include <boost/filesystem.hpp>
#include "BidirectionalModel.h"

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

namespace fs = boost::filesystem;

using namespace std;
using namespace mmt;
using namespace mmt::fastalign;

const Vocabulary *LoadVocabulary(const string &path) {
    fs::path filename = fs::absolute(fs::path(path) / fs::path("model.voc"));
    if (!fs::is_regular(filename))
        throw invalid_argument("File not found: " + filename.string());

    return new Vocabulary(filename.string(), true, false);
}

FastAligner::FastAligner(const string &path, int threads) : vocabulary(LoadVocabulary(path)) {
    fs::path model_filename = fs::absolute(fs::path(path) / fs::path("model.dat"));
    if (!fs::is_regular(model_filename))
        throw invalid_argument("File not found: " + model_filename.string());

    BidirectionalModel::Open(model_filename.string(), &forwardModel, &backwardModel);

    this->threads = threads > 0 ? threads : (int) thread::hardware_concurrency();
#ifdef _OPENMP
    omp_set_dynamic(0);
    omp_set_num_threads(this->threads);
#endif
}

FastAligner::~FastAligner() {
    delete forwardModel;
    delete backwardModel;
    delete vocabulary;
}

alignment_t FastAligner::GetAlignment(const sentence_t &_source, const sentence_t &_target,
                                      Symmetrization symmetrization) {
    wordvec_t source, target;
    vocabulary->Encode(_source, source);
    vocabulary->Encode(_target, target);

    return GetAlignment(source, target, symmetrization);
}

alignment_t FastAligner::GetAlignment(const wordvec_t &source, const wordvec_t &target, Symmetrization symmetrization) {
    alignment_t forward = forwardModel->ComputeAlignment(source, target);
    alignment_t backward = backwardModel->ComputeAlignment(source, target);

    SymAlignment symmetrizer(source.size(), target.size());

    switch (symmetrization) {
        case GrowDiagonalFinalAnd:
            symmetrizer.Grow(forward, backward, true, true);
            break;
        case GrowDiagonal:
            symmetrizer.Grow(forward, backward, true, false);
            break;
        case Intersection:
            symmetrizer.Intersection(forward, backward);
            break;
        case Union:
            symmetrizer.Union(forward, backward);
            break;
    }

    return symmetrizer.ToAlignment();
}

void FastAligner::GetAlignments(const std::vector<std::pair<sentence_t, sentence_t>> &_batch,
                                std::vector<alignment_t> &outAlignments, Symmetrization symmetrization) {
    vector<pair<wordvec_t, wordvec_t>> batch;
    batch.resize(_batch.size());

#pragma omp parallel for schedule(dynamic)
    for (size_t i = 0; i < batch.size(); ++i) {
        vocabulary->Encode(_batch[i].first, batch[i].first);
        vocabulary->Encode(_batch[i].second, batch[i].second);
    }

    GetAlignments(batch, outAlignments, symmetrization);
}

void FastAligner::GetAlignments(const std::vector<std::pair<wordvec_t, wordvec_t>> &batch,
                                std::vector<alignment_t> &outAlignments, Symmetrization symmetrization) {
    vector<alignment_t> forwards;
    vector<alignment_t> backwards;

    forwardModel->ComputeAlignments(batch, forwards);
    backwardModel->ComputeAlignments(batch, backwards);

    outAlignments.resize(batch.size());

    vector<SymAlignment> symals((size_t) threads);

#pragma omp parallel for schedule(dynamic)
    for (size_t i = 0; i < batch.size(); ++i) {
#ifdef _OPENMP
        SymAlignment &symal = symals[omp_get_thread_num()];
#else
        SymAlignment &symal = symals[0];
#endif

        symal.Reset(batch[i].first.size(), batch[i].second.size());

        alignment_t &forward = forwards[i];
        alignment_t &backward = backwards[i];

        switch (symmetrization) {
            case GrowDiagonalFinalAnd:
                symal.Grow(forward, backward, true, true);
                break;
            case GrowDiagonal:
                symal.Grow(forward, backward, true, false);
                break;
            case Intersection:
                symal.Intersection(forward, backward);
                break;
            case Union:
                symal.Union(forward, backward);
                break;
        }

        outAlignments[i] = symal.ToAlignment();
    }
}<commit_msg>Fixed a sever BUG causing SIGSEGV: un-initialized SymAlignment pointer (m) made JVM crash on realloc()<commit_after>//
// Created by Davide Caroselli on 04/09/16.
//

#include <symal/SymAlignment.h>
#include "FastAligner.h"
#include <thread>
#include <boost/filesystem.hpp>
#include "BidirectionalModel.h"

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

namespace fs = boost::filesystem;

using namespace std;
using namespace mmt;
using namespace mmt::fastalign;

const Vocabulary *LoadVocabulary(const string &path) {
    fs::path filename = fs::absolute(fs::path(path) / fs::path("model.voc"));
    if (!fs::is_regular(filename))
        throw invalid_argument("File not found: " + filename.string());

    return new Vocabulary(filename.string(), true, false);
}

FastAligner::FastAligner(const string &path, int threads) : vocabulary(LoadVocabulary(path)) {
    fs::path model_filename = fs::absolute(fs::path(path) / fs::path("model.dat"));
    if (!fs::is_regular(model_filename))
        throw invalid_argument("File not found: " + model_filename.string());

    BidirectionalModel::Open(model_filename.string(), &forwardModel, &backwardModel);

    this->threads = threads > 0 ? threads : (int) thread::hardware_concurrency();
#ifdef _OPENMP
    omp_set_dynamic(0);
    omp_set_num_threads(this->threads);
#endif
}

FastAligner::~FastAligner() {
    delete forwardModel;
    delete backwardModel;
    delete vocabulary;
}

alignment_t FastAligner::GetAlignment(const sentence_t &_source, const sentence_t &_target,
                                      Symmetrization symmetrization) {
    wordvec_t source, target;
    vocabulary->Encode(_source, source);
    vocabulary->Encode(_target, target);

    return GetAlignment(source, target, symmetrization);
}

alignment_t FastAligner::GetAlignment(const wordvec_t &source, const wordvec_t &target, Symmetrization symmetrization) {
    alignment_t forward = forwardModel->ComputeAlignment(source, target);
    alignment_t backward = backwardModel->ComputeAlignment(source, target);

    SymAlignment symmetrizer(source.size(), target.size());

    switch (symmetrization) {
        case GrowDiagonalFinalAnd:
            symmetrizer.Grow(forward, backward, true, true);
            break;
        case GrowDiagonal:
            symmetrizer.Grow(forward, backward, true, false);
            break;
        case Intersection:
            symmetrizer.Intersection(forward, backward);
            break;
        case Union:
            symmetrizer.Union(forward, backward);
            break;
    }

    return symmetrizer.ToAlignment();
}

void FastAligner::GetAlignments(const std::vector<std::pair<sentence_t, sentence_t>> &_batch,
                                std::vector<alignment_t> &outAlignments, Symmetrization symmetrization) {
    vector<pair<wordvec_t, wordvec_t>> batch;
    batch.resize(_batch.size());

#pragma omp parallel for schedule(dynamic)
    for (size_t i = 0; i < batch.size(); ++i) {
        vocabulary->Encode(_batch[i].first, batch[i].first);
        vocabulary->Encode(_batch[i].second, batch[i].second);
    }

    GetAlignments(batch, outAlignments, symmetrization);
}

void FastAligner::GetAlignments(const std::vector<std::pair<wordvec_t, wordvec_t>> &batch,
                                std::vector<alignment_t> &outAlignments, Symmetrization symmetrization) {
    vector<alignment_t> forwards;
    vector<alignment_t> backwards;

    forwardModel->ComputeAlignments(batch, forwards);
    backwardModel->ComputeAlignments(batch, backwards);

    outAlignments.resize(batch.size());

    SymAlignment symal;

    for (size_t i = 0; i < batch.size(); ++i) {
        symal.Reset(batch[i].first.size(), batch[i].second.size());

        alignment_t &forward = forwards[i];
        alignment_t &backward = backwards[i];

        switch (symmetrization) {
            case GrowDiagonalFinalAnd:
                symal.Grow(forward, backward, true, true);
                break;
            case GrowDiagonal:
                symal.Grow(forward, backward, true, false);
                break;
            case Intersection:
                symal.Intersection(forward, backward);
                break;
            case Union:
                symal.Union(forward, backward);
                break;
        }

        outAlignments[i] = symal.ToAlignment();
    }
}<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// appleseed.foundation headers.
#include "foundation/math/permutation.h"
#include "foundation/math/primes.h"
#include "foundation/math/qmc.h"
#include "foundation/utility/benchmark.h"

// Standard headers.
#include <cstddef>

using namespace foundation;

BENCHMARK_SUITE(Foundation_Math_QMC)
{
    template <typename T>
    struct Fixture
    {
        T m_x;

        void radical_inverse_base2_payload()
        {
            m_x = T(0.0);

            for (size_t i = 0; i < 128; ++i)
                m_x += radical_inverse_base2<T>(i);
        }

        void radical_inverse_payload()
        {
            m_x = T(0.0);

            for (size_t s = 0, d = 1; d <= 32; ++d)
            {
                for (size_t i = 0; i < 4; ++i, ++s)
                {
                    m_x +=
                        radical_inverse<T>(
                            Primes[d],
                            s);
                }
            }
        }

        void permuted_radical_inverse_payload()
        {
            m_x = T(0.0);

            for (size_t s = 0, d = 1; d <= 32; ++d)
            {
                for (size_t i = 0; i < 4; ++i, ++s)
                {
                    m_x +=
                        permuted_radical_inverse<T>(
                            Primes[d],
                            FaurePermutations[d],
                            s);
                }
            }
        }
    };

    BENCHMARK_CASE_F(RadicalInverseBase2_SinglePrecision, Fixture<float>)
    {
        radical_inverse_base2_payload();
    }

    BENCHMARK_CASE_F(RadicalInverse_SinglePrecision, Fixture<float>)
    {
        radical_inverse_payload();
    }

    BENCHMARK_CASE_F(PermutedRadicalInverse_SinglePrecision, Fixture<float>)
    {
        permuted_radical_inverse_payload();
    }

    BENCHMARK_CASE_F(RadicalInverseBase2_DoublePrecision, Fixture<double>)
    {
        radical_inverse_base2_payload();
    }

    BENCHMARK_CASE_F(RadicalInverse_DoublePrecision, Fixture<double>)
    {
        radical_inverse_payload();
    }

    BENCHMARK_CASE_F(PermutedRadicalInverse_DoublePrecision, Fixture<double>)
    {
        permuted_radical_inverse_payload();
    }

    BENCHMARK_CASE_F(HaltonSequence_Bases2And3_SinglePrecision, Fixture<Vector2f>)
    {
        static const size_t Bases[] = { 2, 3 };

        m_x = Vector2f(0.0f);

        for (size_t i = 0; i < 64; ++i)
            m_x += halton_sequence<float, 2>(Bases, i);
    }

    BENCHMARK_CASE_F(HaltonSequence_Bases2And3_DoublePrecision, Fixture<Vector2d>)
    {
        static const size_t Bases[] = { 2, 3 };

        m_x = Vector2d(0.0);

        for (size_t i = 0; i < 64; ++i)
            m_x += halton_sequence<double, 2>(Bases, i);
    }

    BENCHMARK_CASE_F(HammersleySequence_Bases2And3_SinglePrecision, Fixture<Vector2f>)
    {
        static const size_t Bases[] = { 2, 3 };

        m_x = Vector2f(0.0f);

        for (size_t i = 0; i < 64; ++i)
            m_x += hammersley_sequence<float, 2>(Bases, i, 128);
    }

    BENCHMARK_CASE_F(HammersleySequence_Bases2And3_DoublePrecision, Fixture<Vector2d>)
    {
        static const size_t Bases[] = { 2, 3 };

        m_x = Vector2d(0.0);

        for (size_t i = 0; i < 64; ++i)
            m_x += hammersley_sequence<double, 2>(Bases, i, 128);
    }
}
<commit_msg>minor fix in hammersley sequence benchmarks; factorized code.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// appleseed.foundation headers.
#include "foundation/math/permutation.h"
#include "foundation/math/primes.h"
#include "foundation/math/qmc.h"
#include "foundation/utility/benchmark.h"

// Standard headers.
#include <cstddef>

using namespace foundation;

BENCHMARK_SUITE(Foundation_Math_QMC)
{
    template <typename T>
    struct ScalarFixture
    {
        T m_x;

        void radical_inverse_base2_payload()
        {
            m_x = T(0.0);

            for (size_t i = 0; i < 128; ++i)
                m_x += radical_inverse_base2<T>(i);
        }

        void radical_inverse_payload()
        {
            m_x = T(0.0);

            for (size_t s = 0, d = 1; d <= 32; ++d)
            {
                for (size_t i = 0; i < 4; ++i, ++s)
                {
                    m_x +=
                        radical_inverse<T>(
                            Primes[d],
                            s);
                }
            }
        }

        void permuted_radical_inverse_payload()
        {
            m_x = T(0.0);

            for (size_t s = 0, d = 1; d <= 32; ++d)
            {
                for (size_t i = 0; i < 4; ++i, ++s)
                {
                    m_x +=
                        permuted_radical_inverse<T>(
                            Primes[d],
                            FaurePermutations[d],
                            s);
                }
            }
        }
    };

    template <typename T>
    struct Vector2Fixture
    {
        Vector<T, 2> m_x;

        void halton_payload()
        {
            static const size_t Bases[] = { 2, 3 };

            m_x = Vector<T, 2>(0.0f);

            for (size_t i = 0; i < 64; ++i)
                m_x += halton_sequence<T, 2>(Bases, i);
        }

        void hammersley_payload()
        {
            static const size_t Bases[] = { 2 };

            m_x = Vector<T, 2>(0.0f);

            for (size_t i = 0; i < 64; ++i)
                m_x += hammersley_sequence<T, 2>(Bases, i, 64);
        }
    };

    BENCHMARK_CASE_F(RadicalInverseBase2_SinglePrecision, ScalarFixture<float>)
    {
        radical_inverse_base2_payload();
    }

    BENCHMARK_CASE_F(RadicalInverse_SinglePrecision, ScalarFixture<float>)
    {
        radical_inverse_payload();
    }

    BENCHMARK_CASE_F(PermutedRadicalInverse_SinglePrecision, ScalarFixture<float>)
    {
        permuted_radical_inverse_payload();
    }

    BENCHMARK_CASE_F(RadicalInverseBase2_DoublePrecision, ScalarFixture<double>)
    {
        radical_inverse_base2_payload();
    }

    BENCHMARK_CASE_F(RadicalInverse_DoublePrecision, ScalarFixture<double>)
    {
        radical_inverse_payload();
    }

    BENCHMARK_CASE_F(PermutedRadicalInverse_DoublePrecision, ScalarFixture<double>)
    {
        permuted_radical_inverse_payload();
    }

    BENCHMARK_CASE_F(HaltonSequence_Bases2And3_SinglePrecision, Vector2Fixture<float>)
    {
        halton_payload();
    }

    BENCHMARK_CASE_F(HaltonSequence_Bases2And3_DoublePrecision, Vector2Fixture<double>)
    {
        halton_payload();
    }

    BENCHMARK_CASE_F(HammersleySequence_Base2_SinglePrecision, Vector2Fixture<float>)
    {
        hammersley_payload();
    }

    BENCHMARK_CASE_F(HammersleySequence_Base2_DoublePrecision, Vector2Fixture<double>)
    {
        hammersley_payload();
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"

#include "base/compiler_specific.h"

MSVC_PUSH_WARNING_LEVEL(0);
#include "ContextMenu.h"
#include "Document.h"
#include "DocumentLoader.h"
#include "Editor.h"
#include "FrameLoader.h"
#include "FrameView.h"
#include "HitTestResult.h"
#include "KURL.h"
#include "Widget.h"
MSVC_POP_WARNING();
#undef LOG

#include "webkit/glue/context_menu_client_impl.h"

#include "base/string_util.h"
#include "webkit/glue/context_node_types.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webdocumentloader_impl.h"
#include "webkit/glue/webview_impl.h"

#include "base/word_iterator.h"

// Helper function to determine whether text is a single word or a sentence.
static bool IsASingleWord(const std::wstring& text) {
  WordIterator iter(text, WordIterator::BREAK_WORD);
  int word_count = 0;
  if (!iter.Init()) return false;
  while (iter.Advance()) {
    if (iter.IsWord()) {
      word_count++;
      if (word_count > 1) // More than one word.
        return false;
    }
  }

  // Check for 0 words.
  if (!word_count)
    return false;

  // Has a single word.
  return true;
}

// Helper function to get misspelled word on which context menu
// is to be evolked. This function also sets the word on which context menu
// has been evoked to be the selected word, as required.
static std::wstring GetMisspelledWord(WebCore::ContextMenu* default_menu,
                                      WebCore::Frame* selected_frame) {
  std::wstring misspelled_word_string;

  // First select from selectedText to check for multiple word selection.
  misspelled_word_string = CollapseWhitespace(
      webkit_glue::StringToStdWString(selected_frame->selectedText()),
      false);

  // Don't provide suggestions for multiple words.
  if (!misspelled_word_string.empty() &&
      !IsASingleWord(misspelled_word_string))
    return L"";

  // Expand around the click to see if we clicked a word.
  WebCore::Selection selection;
  WebCore::VisiblePosition pos(default_menu->hitTestResult().innerNode()->
      renderer()->positionForPoint(default_menu->hitTestResult().
                                   localPoint()));

  if (pos.isNotNull()) {
    selection = WebCore::Selection(pos);
    selection.expandUsingGranularity(WebCore::WordGranularity);
  }

  if (selection.isRange()) {
    selected_frame->setSelectionGranularity(WebCore::WordGranularity);
  }

  if (selected_frame->shouldChangeSelection(selection))
    selected_frame->selection()->setSelection(selection);

  misspelled_word_string = CollapseWhitespace(
      webkit_glue::StringToStdWString(selected_frame->selectedText()),
                                      false);

  return misspelled_word_string;
}

ContextMenuClientImpl::~ContextMenuClientImpl() {
}

void ContextMenuClientImpl::contextMenuDestroyed() {
  delete this;
}

// Figure out the URL of a page or subframe. Returns |page_type| as the type,
// which indicates page or subframe, or ContextNode::NONE if the URL could not
// be determined for some reason.
static ContextNode::Type GetTypeAndURLFromFrame(WebCore::Frame* frame,
                                                GURL* url,
                                                ContextNode::Type page_type) {
  ContextNode::Type type = ContextNode::NONE;
  if (frame) {
    WebCore::DocumentLoader* dl = frame->loader()->documentLoader();
    if (dl) {
      WebDataSource* ds = static_cast<WebDocumentLoaderImpl*>(dl)->
          GetDataSource();
      if (ds) {
        type = page_type;
        *url = ds->HasUnreachableURL() ? ds->GetUnreachableURL()
                                       : ds->GetRequest().GetURL();
      }
    }
  }
  return type;
}

WebCore::PlatformMenuDescription
    ContextMenuClientImpl::getCustomMenuFromDefaultItems(
        WebCore::ContextMenu* default_menu) {
  // Displaying the context menu in this function is a big hack as we don't
  // have context, i.e. whether this is being invoked via a script or in
  // response to user input (Mouse event WM_RBUTTONDOWN,
  // Keyboard events KeyVK_APPS, Shift+F10). Check if this is being invoked
  // in response to the above input events before popping up the context menu.
  if (!webview_->context_menu_allowed())
    return NULL;

  WebCore::HitTestResult r = default_menu->hitTestResult();
  WebCore::Frame* selected_frame = r.innerNonSharedNode()->document()->frame();

  WebCore::IntPoint menu_point =
      selected_frame->view()->contentsToWindow(r.point());

  ContextNode::Type type = ContextNode::NONE;

  // Links, Images and Image-Links take preference over all else.
  WebCore::KURL link_url = r.absoluteLinkURL();
  if (!link_url.isEmpty()) {
    type = ContextNode::LINK;
  }
  WebCore::KURL image_url = r.absoluteImageURL();
  if (!image_url.isEmpty()) {
    type = ContextNode::IMAGE;
  }
  if (!image_url.isEmpty() && !link_url.isEmpty())
    type = ContextNode::IMAGE_LINK;

  // If it's not a link, an image or an image link, show a selection menu or a
  // more generic page menu.
  std::wstring selection_text_string;
  std::wstring misspelled_word_string;
  GURL frame_url;
  GURL page_url;
  std::string security_info;

  std::wstring frame_encoding;
  // Send the frame and page URLs in any case.
  ContextNode::Type frame_type = ContextNode::NONE;
  ContextNode::Type page_type =
      GetTypeAndURLFromFrame(webview_->main_frame()->frame(),
                             &page_url,
                             ContextNode::PAGE);
  if (selected_frame != webview_->main_frame()->frame()) {
    frame_type = GetTypeAndURLFromFrame(selected_frame,
                                        &frame_url,
                                        ContextNode::FRAME);
    frame_encoding = webkit_glue::StringToStdWString(
        selected_frame->loader()->encoding());
  }

  if (type == ContextNode::NONE) {
    if (r.isContentEditable()) {
      type = ContextNode::EDITABLE;
      if (webview_->FocusedFrameNeedsSpellchecking()) {
        misspelled_word_string = GetMisspelledWord(default_menu,
                                                   selected_frame);
      }
    } else if (r.isSelected()) {
      type = ContextNode::SELECTION;
      selection_text_string =
          CollapseWhitespace(
              webkit_glue::StringToStdWString(selected_frame->selectedText()),
              false);
    } else if (selected_frame != webview_->main_frame()->frame()) {
      type = frame_type;
    } else {
      type = page_type;
    }
  }

  // Now retrieve the security info.
  WebCore::DocumentLoader* dl = selected_frame->loader()->documentLoader();
  if (dl) {
    WebDataSource* ds = static_cast<WebDocumentLoaderImpl*>(dl)->
        GetDataSource();
    if (ds) {
      const WebResponse& response = ds->GetResponse();
      security_info = response.GetSecurityInfo();
    }
  }

  int edit_flags = ContextNode::CAN_DO_NONE;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canUndo())
    edit_flags |= ContextNode::CAN_UNDO;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canRedo())
    edit_flags |= ContextNode::CAN_REDO;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canCut())
    edit_flags |= ContextNode::CAN_CUT;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canCopy())
    edit_flags |= ContextNode::CAN_COPY;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canPaste())
    edit_flags |= ContextNode::CAN_PASTE;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canDelete())
    edit_flags |= ContextNode::CAN_DELETE;
  // We can always select all...
  edit_flags |= ContextNode::CAN_SELECT_ALL;

  WebViewDelegate* d = webview_->delegate();
  if (d) {
    d->ShowContextMenu(webview_,
                       type,
                       menu_point.x(),
                       menu_point.y(),
                       webkit_glue::KURLToGURL(link_url),
                       webkit_glue::KURLToGURL(image_url),
                       page_url,
                       frame_url,
                       selection_text_string,
                       misspelled_word_string,
                       edit_flags,
                       security_info);
  }
  return NULL;
}

void ContextMenuClientImpl::contextMenuItemSelected(
    WebCore::ContextMenuItem*, const WebCore::ContextMenu*) {
}

void ContextMenuClientImpl::downloadURL(const WebCore::KURL&) {
}

void ContextMenuClientImpl::copyImageToClipboard(const WebCore::HitTestResult&) {
}

void ContextMenuClientImpl::searchWithGoogle(const WebCore::Frame*) {
}

void ContextMenuClientImpl::lookUpInDictionary(WebCore::Frame*) {
}

void ContextMenuClientImpl::speak(const WebCore::String&) {
}

void ContextMenuClientImpl::stopSpeaking() {
}

bool ContextMenuClientImpl::shouldIncludeInspectElementItem() {
    return false;  // TODO(jackson): Eventually include the inspector context menu item
}

#if defined(OS_MACOSX)
void ContextMenuClientImpl::searchWithSpotlight() {
  // TODO(pinkerton): write this
}
#endif
<commit_msg>When right clicking in a text area that is scrolled, the wrong word is selected.  This is because we use the wrong node when getting the selection.  We want to use the shadow inner node, but the hit test result provided to the ContextMenu is not the shadow node.  To work around this, we recompute the hit test result.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"

#include "base/compiler_specific.h"

MSVC_PUSH_WARNING_LEVEL(0);
#include "ContextMenu.h"
#include "Document.h"
#include "DocumentLoader.h"
#include "Editor.h"
#include "EventHandler.h"
#include "FrameLoader.h"
#include "FrameView.h"
#include "HitTestResult.h"
#include "KURL.h"
#include "Widget.h"
MSVC_POP_WARNING();
#undef LOG

#include "webkit/glue/context_menu_client_impl.h"

#include "base/string_util.h"
#include "webkit/glue/context_node_types.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webdocumentloader_impl.h"
#include "webkit/glue/webview_impl.h"

#include "base/word_iterator.h"

namespace {

// Helper function to determine whether text is a single word or a sentence.
bool IsASingleWord(const std::wstring& text) {
  WordIterator iter(text, WordIterator::BREAK_WORD);
  int word_count = 0;
  if (!iter.Init()) return false;
  while (iter.Advance()) {
    if (iter.IsWord()) {
      word_count++;
      if (word_count > 1) // More than one word.
        return false;
    }
  }

  // Check for 0 words.
  if (!word_count)
    return false;

  // Has a single word.
  return true;
}

// Helper function to get misspelled word on which context menu
// is to be evolked. This function also sets the word on which context menu
// has been evoked to be the selected word, as required.
std::wstring GetMisspelledWord(const WebCore::ContextMenu* default_menu,
                               WebCore::Frame* selected_frame) {
  std::wstring misspelled_word_string;

  // First select from selectedText to check for multiple word selection.
  misspelled_word_string = CollapseWhitespace(
      webkit_glue::StringToStdWString(selected_frame->selectedText()),
      false);

  // Don't provide suggestions for multiple words.
  if (!misspelled_word_string.empty() &&
      !IsASingleWord(misspelled_word_string))
    return L"";

  // Expand around the click to see if we clicked a word.
  WebCore::Node* inner_node = default_menu->hitTestResult().innerNode();
  if (inner_node->renderer()->isTextArea()) {
    WebCore::HitTestResult real_result = selected_frame->eventHandler()->
        hitTestResultAtPoint(default_menu->hitTestResult().localPoint(), true);
    inner_node = real_result.innerNode();
  }

  WebCore::VisiblePosition pos(inner_node->renderer()->
      positionForPoint(default_menu->hitTestResult().localPoint()));

  WebCore::Selection selection;
  if (pos.isNotNull()) {
    selection = WebCore::Selection(pos);
    selection.expandUsingGranularity(WebCore::WordGranularity);
  }

  if (selection.isRange()) {
    selected_frame->setSelectionGranularity(WebCore::WordGranularity);
  }

  if (selected_frame->shouldChangeSelection(selection))
    selected_frame->selection()->setSelection(selection);

  misspelled_word_string = CollapseWhitespace(
      webkit_glue::StringToStdWString(selected_frame->selectedText()),
                                      false);

  return misspelled_word_string;
}

}  // namespace

ContextMenuClientImpl::~ContextMenuClientImpl() {
}

void ContextMenuClientImpl::contextMenuDestroyed() {
  delete this;
}

// Figure out the URL of a page or subframe. Returns |page_type| as the type,
// which indicates page or subframe, or ContextNode::NONE if the URL could not
// be determined for some reason.
static ContextNode::Type GetTypeAndURLFromFrame(WebCore::Frame* frame,
                                                GURL* url,
                                                ContextNode::Type page_type) {
  ContextNode::Type type = ContextNode::NONE;
  if (frame) {
    WebCore::DocumentLoader* dl = frame->loader()->documentLoader();
    if (dl) {
      WebDataSource* ds = static_cast<WebDocumentLoaderImpl*>(dl)->
          GetDataSource();
      if (ds) {
        type = page_type;
        *url = ds->HasUnreachableURL() ? ds->GetUnreachableURL()
                                       : ds->GetRequest().GetURL();
      }
    }
  }
  return type;
}

WebCore::PlatformMenuDescription
    ContextMenuClientImpl::getCustomMenuFromDefaultItems(
        WebCore::ContextMenu* default_menu) {
  // Displaying the context menu in this function is a big hack as we don't
  // have context, i.e. whether this is being invoked via a script or in
  // response to user input (Mouse event WM_RBUTTONDOWN,
  // Keyboard events KeyVK_APPS, Shift+F10). Check if this is being invoked
  // in response to the above input events before popping up the context menu.
  if (!webview_->context_menu_allowed())
    return NULL;

  WebCore::HitTestResult r = default_menu->hitTestResult();
  WebCore::Frame* selected_frame = r.innerNonSharedNode()->document()->frame();

  WebCore::IntPoint menu_point =
      selected_frame->view()->contentsToWindow(r.point());

  ContextNode::Type type = ContextNode::NONE;

  // Links, Images and Image-Links take preference over all else.
  WebCore::KURL link_url = r.absoluteLinkURL();
  if (!link_url.isEmpty()) {
    type = ContextNode::LINK;
  }
  WebCore::KURL image_url = r.absoluteImageURL();
  if (!image_url.isEmpty()) {
    type = ContextNode::IMAGE;
  }
  if (!image_url.isEmpty() && !link_url.isEmpty())
    type = ContextNode::IMAGE_LINK;

  // If it's not a link, an image or an image link, show a selection menu or a
  // more generic page menu.
  std::wstring selection_text_string;
  std::wstring misspelled_word_string;
  GURL frame_url;
  GURL page_url;
  std::string security_info;

  std::wstring frame_encoding;
  // Send the frame and page URLs in any case.
  ContextNode::Type frame_type = ContextNode::NONE;
  ContextNode::Type page_type =
      GetTypeAndURLFromFrame(webview_->main_frame()->frame(),
                             &page_url,
                             ContextNode::PAGE);
  if (selected_frame != webview_->main_frame()->frame()) {
    frame_type = GetTypeAndURLFromFrame(selected_frame,
                                        &frame_url,
                                        ContextNode::FRAME);
    frame_encoding = webkit_glue::StringToStdWString(
        selected_frame->loader()->encoding());
  }

  if (type == ContextNode::NONE) {
    if (r.isContentEditable()) {
      type = ContextNode::EDITABLE;
      if (webview_->FocusedFrameNeedsSpellchecking()) {
        misspelled_word_string = GetMisspelledWord(default_menu,
                                                   selected_frame);
      }
    } else if (r.isSelected()) {
      type = ContextNode::SELECTION;
      selection_text_string =
          CollapseWhitespace(
              webkit_glue::StringToStdWString(selected_frame->selectedText()),
              false);
    } else if (selected_frame != webview_->main_frame()->frame()) {
      type = frame_type;
    } else {
      type = page_type;
    }
  }

  // Now retrieve the security info.
  WebCore::DocumentLoader* dl = selected_frame->loader()->documentLoader();
  if (dl) {
    WebDataSource* ds = static_cast<WebDocumentLoaderImpl*>(dl)->
        GetDataSource();
    if (ds) {
      const WebResponse& response = ds->GetResponse();
      security_info = response.GetSecurityInfo();
    }
  }

  int edit_flags = ContextNode::CAN_DO_NONE;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canUndo())
    edit_flags |= ContextNode::CAN_UNDO;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canRedo())
    edit_flags |= ContextNode::CAN_REDO;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canCut())
    edit_flags |= ContextNode::CAN_CUT;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canCopy())
    edit_flags |= ContextNode::CAN_COPY;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canPaste())
    edit_flags |= ContextNode::CAN_PASTE;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canDelete())
    edit_flags |= ContextNode::CAN_DELETE;
  // We can always select all...
  edit_flags |= ContextNode::CAN_SELECT_ALL;

  WebViewDelegate* d = webview_->delegate();
  if (d) {
    d->ShowContextMenu(webview_,
                       type,
                       menu_point.x(),
                       menu_point.y(),
                       webkit_glue::KURLToGURL(link_url),
                       webkit_glue::KURLToGURL(image_url),
                       page_url,
                       frame_url,
                       selection_text_string,
                       misspelled_word_string,
                       edit_flags,
                       security_info);
  }
  return NULL;
}

void ContextMenuClientImpl::contextMenuItemSelected(
    WebCore::ContextMenuItem*, const WebCore::ContextMenu*) {
}

void ContextMenuClientImpl::downloadURL(const WebCore::KURL&) {
}

void ContextMenuClientImpl::copyImageToClipboard(const WebCore::HitTestResult&) {
}

void ContextMenuClientImpl::searchWithGoogle(const WebCore::Frame*) {
}

void ContextMenuClientImpl::lookUpInDictionary(WebCore::Frame*) {
}

void ContextMenuClientImpl::speak(const WebCore::String&) {
}

void ContextMenuClientImpl::stopSpeaking() {
}

bool ContextMenuClientImpl::shouldIncludeInspectElementItem() {
    return false;  // TODO(jackson): Eventually include the inspector context menu item
}

#if defined(OS_MACOSX)
void ContextMenuClientImpl::searchWithSpotlight() {
  // TODO(pinkerton): write this
}
#endif
<|endoftext|>


<commit_before><commit_msg>Pull in r163967 from upstream llvm trunk:<commit_after><|endoftext|>


<commit_before>#include "chrono_parallel/constraints/ChConstraintRigidFluid.h"
#include "chrono_parallel/constraints/ChConstraintUtils.h"

using namespace chrono;

bool Cone_generalized_rf(real& gamma_n, real& gamma_u, real& gamma_v,
		const real& mu) {
	real f_tang = sqrt(gamma_u * gamma_u + gamma_v * gamma_v);

	// inside upper cone? keep untouched!
	if (f_tang < (mu * gamma_n)) {
		return false;
	}

	// inside lower cone? reset  normal,u,v to zero!
	if ((f_tang) < -(1.0 / mu) * gamma_n || (fabs(gamma_n) < 10e-15)) {
		gamma_n = 0;
		gamma_u = 0;
		gamma_v = 0;
		return false;
	}

	// remaining case: project orthogonally to generator segment of upper cone

	gamma_n = (f_tang * mu + gamma_n) / (mu * mu + 1);
	real tproj_div_t = (gamma_n * mu) / f_tang;
	gamma_u *= tproj_div_t;
	gamma_v *= tproj_div_t;

	return true;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void ChConstraintRigidFluid::Project(real* gamma) {
	// custom_vector<int2>& bids = data_manager->host_data.bids_rigid_fluid;
	uint num_rigid_fluid_contacts = data_manager->num_rigid_fluid_contacts;
	uint num_unilaterals = data_manager->num_unilaterals;
	uint num_bilaterals = data_manager->num_bilaterals;
	real mu = data_manager->settings.fluid.mu;
	real coh = data_manager->settings.fluid.cohesion;

	custom_vector<int>& neighbor_rigid_fluid =
			data_manager->host_data.neighbor_rigid_fluid;
	custom_vector<int>& contact_counts =
			data_manager->host_data.c_counts_rigid_fluid;
	int num_fluid_bodies = data_manager->num_fluid_bodies;

	//#pragma omp parallel for
	int index = 0;
	for (int p = 0; p < num_fluid_bodies; p++) {
		for (int i = 0; i < contact_counts[p]; ++i) {
			int rigid = neighbor_rigid_fluid[p * max_rigid_neighbors + i]; // rigid is stored in the first index
			int fluid = p;                      // fluid body is in second index
			real rigid_fric = data_manager->host_data.fric_data[rigid].x;
			real cohesion = Max(
					(data_manager->host_data.cohesion_data[rigid] + coh) * .5,
					0.0);
			real friction =
					(rigid_fric == 0 || mu == 0) ? 0 : (rigid_fric + mu) * .5;

			real3 gam;
			gam.x = gamma[num_unilaterals + num_bilaterals + index];
			gam.y = gamma[num_unilaterals + num_bilaterals
					+ num_rigid_fluid_contacts + index * 2 + 0];
			gam.z = gamma[num_unilaterals + num_bilaterals
					+ num_rigid_fluid_contacts + index * 2 + 1];

			gam.x += cohesion;

			real mu = friction;
			if (mu == 0) {
				gam.x = gam.x < 0 ? 0 : gam.x - cohesion;
				gam.y = gam.z = 0;

				gamma[num_unilaterals + num_bilaterals + index] = gam.x;
				gamma[num_unilaterals + num_bilaterals
						+ num_rigid_fluid_contacts + index * 2 + 0] = gam.y;
				gamma[num_unilaterals + num_bilaterals
						+ num_rigid_fluid_contacts + index * 2 + 1] = gam.z;

				continue;
			}

			if (Cone_generalized_rf(gam.x, gam.y, gam.z, mu)) {
			}

			gamma[num_unilaterals + num_bilaterals + index] = gam.x - cohesion;
			gamma[num_unilaterals + num_bilaterals + num_rigid_fluid_contacts
					+ index * 2 + 0] = gam.y;
			gamma[num_unilaterals + num_bilaterals + num_rigid_fluid_contacts
					+ index * 2 + 1] = gam.z;
			index++;
		}
	}
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void ChConstraintRigidFluid::Build_D() {
	LOG(INFO) << "ChConstraintRigidFluid::Build_D";

	uint num_rigid_fluid_contacts = data_manager->num_rigid_fluid_contacts;
	uint num_unilaterals = data_manager->num_unilaterals;
	uint num_bilaterals = data_manager->num_bilaterals;
	uint num_rigid_bodies = data_manager->num_rigid_bodies;
	uint num_shafts = data_manager->num_shafts;

	if (num_rigid_fluid_contacts <= 0) {
		return;
	}
	CompressedMatrix < real > &D_T = data_manager->host_data.D_T;

	SubMatrixType D_rfn_T = _DRFNT_;
	SubMatrixType D_rft_T = _DRFTT_;
	custom_vector < real3 > &pos = data_manager->host_data.sorted_pos_fluid;

	custom_vector < real3 > &pos_rigid = data_manager->host_data.pos_rigid;
	custom_vector < quaternion > &rot_rigid = data_manager->host_data.rot_rigid;

	real h = data_manager->settings.fluid.kernel_radius;
	// custom_vector<int2>& bids = data_manager->host_data.bids_rigid_fluid;
	custom_vector < real3 > &cpta = data_manager->host_data.cpta_rigid_fluid;
	custom_vector < real3 > &norm = data_manager->host_data.norm_rigid_fluid;
	data_manager->system_timer.start("ChSolverParallel_solverC");
	custom_vector<int>& neighbor_rigid_fluid =
			data_manager->host_data.neighbor_rigid_fluid;
	custom_vector<int>& contact_counts =
			data_manager->host_data.c_counts_rigid_fluid;
	int num_fluid_bodies = data_manager->num_fluid_bodies;
	//#pragma omp parallel for
	int index = 0;
	for (int p = 0; p < num_fluid_bodies; p++) {
		for (int i = 0; i < contact_counts[p]; i++) {
			int rigid = neighbor_rigid_fluid[p * max_rigid_neighbors + i];
			int fluid = p;  // fluid body is in second index
			real3 U = norm[p * max_rigid_neighbors + i], V, W;
			Orthogonalize(U, V, W);
			real3 T1, T2, T3;
			Compute_Jacobian(rot_rigid[rigid], U, V, W,
					cpta[p * max_rigid_neighbors + i] - pos_rigid[rigid], T1,
					T2, T3);

			SetRow6Check(D_rfn_T, index + 0, rigid * 6, -U, T1);
			SetRow6Check(D_rft_T, index * 2 + 0, rigid * 6, -V, T2);
			SetRow6Check(D_rft_T, index * 2 + 1, rigid * 6, -W, T3);

			SetRow3Check(D_rfn_T, index + 0,
					num_rigid_bodies * 6 + num_shafts + fluid * 3, U);
			SetRow3Check(D_rft_T, index * 2 + 0,
					num_rigid_bodies * 6 + num_shafts + fluid * 3, V);
			SetRow3Check(D_rft_T, index * 2 + 1,
					num_rigid_bodies * 6 + num_shafts + fluid * 3, W);
			index++;
		}
	}
	data_manager->system_timer.stop("ChSolverParallel_solverC");
}
void ChConstraintRigidFluid::Build_b() {
	LOG(INFO) << "ChConstraintRigidFluid::Build_b";
	uint num_rigid_fluid_contacts = data_manager->num_rigid_fluid_contacts;
	uint num_unilaterals = data_manager->num_unilaterals;
	uint num_bilaterals = data_manager->num_bilaterals;
	real step_size = data_manager->settings.step_size;
	if (num_rigid_fluid_contacts <= 0) {
		return;
	}

	custom_vector<int>& neighbor_rigid_fluid =
			data_manager->host_data.neighbor_rigid_fluid;
	custom_vector<int>& contact_counts =
			data_manager->host_data.c_counts_rigid_fluid;
	int num_fluid_bodies = data_manager->num_fluid_bodies;

	//#pragma omp parallel for
	int index = 0;
	for (int p = 0; p < num_fluid_bodies; p++) {
		for (int i = 0; i < contact_counts[p]; i++) {
			real bi = 0;
			real depth = data_manager->host_data.dpth_rigid_fluid[p
					* max_rigid_neighbors + i];

			bi = std::max(real(1.0) / step_size * depth,
					-data_manager->settings.fluid.contact_recovery_speed);
			//
			data_manager->host_data.b[num_unilaterals + num_bilaterals + index
					+ 0] = bi;
			data_manager->host_data.b[num_unilaterals + num_bilaterals
					+ num_rigid_fluid_contacts + index * 2 + 0] = 0;
			data_manager->host_data.b[num_unilaterals + num_bilaterals
					+ num_rigid_fluid_contacts + index * 2 + 1] = 0;
			index++;
		}
	}
}
void ChConstraintRigidFluid::Build_E() {
	LOG(INFO) << "ChConstraintRigidFluid::Build_E";
	uint num_rigid_fluid_contacts = data_manager->num_rigid_fluid_contacts;
	uint num_unilaterals = data_manager->num_unilaterals;
	uint num_bilaterals = data_manager->num_bilaterals;
	real step_size = data_manager->settings.step_size;
	if (num_rigid_fluid_contacts <= 0) {
		return;
	}
	DynamicVector < real > &E = data_manager->host_data.E;

#pragma omp parallel for
	for (int index = 0; index < num_rigid_fluid_contacts; index++) {
		int ind = num_unilaterals + num_bilaterals;
		real epsilon = data_manager->settings.fluid.epsilon;
		real tau = data_manager->settings.fluid.tau;
		real h = data_manager->settings.fluid.kernel_radius;
		real compliance = 4.0 / (step_size * step_size)
				* (epsilon / (1.0 + 4.0 * tau / h));

		E[ind + index + 0] = 0;
		E[ind + num_rigid_fluid_contacts + index * 2 + 0] = 0;
		E[ind + num_rigid_fluid_contacts + index * 2 + 1] = 0;
	}
}

void ChConstraintRigidFluid::GenerateSparsity() {
	LOG(INFO) << "ChConstraintRigidFluid::GenerateSparsity";
	uint num_rigid_fluid_contacts = data_manager->num_rigid_fluid_contacts;
	uint num_unilaterals = data_manager->num_unilaterals;
	uint num_bilaterals = data_manager->num_bilaterals;
	real step_size = data_manager->settings.step_size;
	uint num_rigid_bodies = data_manager->num_rigid_bodies;
	uint num_shafts = data_manager->num_shafts;
	CompressedMatrix < real > &D_T = data_manager->host_data.D_T;
	// custom_vector<int2>& bids = data_manager->host_data.bids_rigid_fluid;
	int index_n = 0;
	int index_t = 0;
	int num_fluid_bodies = data_manager->num_fluid_bodies;
	custom_vector<int>& neighbor_rigid_fluid =
			data_manager->host_data.neighbor_rigid_fluid;
	custom_vector<int>& contact_counts =
			data_manager->host_data.c_counts_rigid_fluid;
	int off = num_unilaterals + num_bilaterals;
	for (int p = 0; p < num_fluid_bodies; p++) {
		for (int i = 0; i < contact_counts[p]; i++) {
			// int2 body_id = bids[index];
			int rigid = neighbor_rigid_fluid[p * max_rigid_neighbors + i];
			int fluid = p;

			AppendRow6(D_T, off + index_n + 0, rigid * 6, 0);
			AppendRow3(D_T, off + index_n + 0,
					num_rigid_bodies * 6 + num_shafts + fluid * 3, 0);
			D_T.finalize(off + index_n + 0);
			index_n++;
		}
	}
	for (int p = 0; p < num_fluid_bodies; p++) {
		for (int i = 0; i < contact_counts[p]; i++) {
			int rigid = neighbor_rigid_fluid[p * max_rigid_neighbors + i];
			int fluid = p;

			AppendRow6(D_T, off + num_rigid_fluid_contacts + index_t * 2 + 0,
					rigid * 6, 0);
			AppendRow3(D_T, off + num_rigid_fluid_contacts + index_t * 2 + 0,
					num_rigid_bodies * 6 + num_shafts + fluid * 3, 0);
			D_T.finalize(off + num_rigid_fluid_contacts + index_t * 2 + 0);

			AppendRow6(D_T, off + num_rigid_fluid_contacts + index_t * 2 + 1,
					rigid * 6, 0);
			AppendRow3(D_T, off + num_rigid_fluid_contacts + index_t * 2 + 1,
					num_rigid_bodies * 6 + num_shafts + fluid * 3, 0);

			D_T.finalize(off + num_rigid_fluid_contacts + index_t * 2 + 1);
			index_t++;
		}
	}
}
<commit_msg><commit_after>#include "chrono_parallel/constraints/ChConstraintRigidFluid.h"
#include "chrono_parallel/constraints/ChConstraintUtils.h"

using namespace chrono;

bool Cone_generalized_rf(real& gamma_n, real& gamma_u, real& gamma_v, const real& mu) {
    real f_tang = sqrt(gamma_u * gamma_u + gamma_v * gamma_v);

    // inside upper cone? keep untouched!
    if (f_tang < (mu * gamma_n)) {
        return false;
    }

    // inside lower cone? reset  normal,u,v to zero!
    if ((f_tang) < -(1.0 / mu) * gamma_n || (fabs(gamma_n) < 10e-15)) {
        gamma_n = 0;
        gamma_u = 0;
        gamma_v = 0;
        return false;
    }

    // remaining case: project orthogonally to generator segment of upper cone

    gamma_n = (f_tang * mu + gamma_n) / (mu * mu + 1);
    real tproj_div_t = (gamma_n * mu) / f_tang;
    gamma_u *= tproj_div_t;
    gamma_v *= tproj_div_t;

    return true;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void ChConstraintRigidFluid::Project(real* gamma) {
    // custom_vector<int2>& bids = data_manager->host_data.bids_rigid_fluid;
    uint num_rigid_fluid_contacts = data_manager->num_rigid_fluid_contacts;
    uint num_unilaterals = data_manager->num_unilaterals;
    uint num_bilaterals = data_manager->num_bilaterals;
    real mu = data_manager->settings.fluid.mu;
    real coh = data_manager->settings.fluid.cohesion;

    custom_vector<int>& neighbor_rigid_fluid = data_manager->host_data.neighbor_rigid_fluid;
    custom_vector<int>& contact_counts = data_manager->host_data.c_counts_rigid_fluid;
    int num_fluid_bodies = data_manager->num_fluid_bodies;

    //#pragma omp parallel for
    int index = 0;
    for (int p = 0; p < num_fluid_bodies; p++) {
        for (int i = 0; i < contact_counts[p]; ++i) {
            int rigid = neighbor_rigid_fluid[p * max_rigid_neighbors + i];  // rigid is stored in the first index
            int fluid = p;                                                  // fluid body is in second index
            real rigid_fric = data_manager->host_data.fric_data[rigid].x;
            real cohesion = Max((data_manager->host_data.cohesion_data[rigid] + coh) * .5, 0.0);
            real friction = (rigid_fric == 0 || mu == 0) ? 0 : (rigid_fric + mu) * .5;

            real3 gam;
            gam.x = gamma[num_unilaterals + num_bilaterals + index];
            gam.y = gamma[num_unilaterals + num_bilaterals + num_rigid_fluid_contacts + index * 2 + 0];
            gam.z = gamma[num_unilaterals + num_bilaterals + num_rigid_fluid_contacts + index * 2 + 1];

            gam.x += cohesion;

            real mu = friction;
            if (mu == 0) {
                gam.x = gam.x < 0 ? 0 : gam.x - cohesion;
                gam.y = gam.z = 0;

                gamma[num_unilaterals + num_bilaterals + index] = gam.x;
                gamma[num_unilaterals + num_bilaterals + num_rigid_fluid_contacts + index * 2 + 0] = gam.y;
                gamma[num_unilaterals + num_bilaterals + num_rigid_fluid_contacts + index * 2 + 1] = gam.z;

                continue;
            }

            if (Cone_generalized_rf(gam.x, gam.y, gam.z, mu)) {
            }

            gamma[num_unilaterals + num_bilaterals + index] = gam.x - cohesion;
            gamma[num_unilaterals + num_bilaterals + num_rigid_fluid_contacts + index * 2 + 0] = gam.y;
            gamma[num_unilaterals + num_bilaterals + num_rigid_fluid_contacts + index * 2 + 1] = gam.z;
            index++;
        }
    }
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void ChConstraintRigidFluid::Build_D() {
    LOG(INFO) << "ChConstraintRigidFluid::Build_D";

    uint num_rigid_fluid_contacts = data_manager->num_rigid_fluid_contacts;
    uint num_unilaterals = data_manager->num_unilaterals;
    uint num_bilaterals = data_manager->num_bilaterals;
    uint num_rigid_bodies = data_manager->num_rigid_bodies;
    uint num_shafts = data_manager->num_shafts;

    if (num_rigid_fluid_contacts <= 0) {
        return;
    }
    CompressedMatrix<real>& D_T = data_manager->host_data.D_T;

    SubMatrixType D_rfn_T = _DRFNT_;
    SubMatrixType D_rft_T = _DRFTT_;
    custom_vector<real3>& pos = data_manager->host_data.sorted_pos_fluid;

    custom_vector<real3>& pos_rigid = data_manager->host_data.pos_rigid;
    custom_vector<quaternion>& rot_rigid = data_manager->host_data.rot_rigid;

    real h = data_manager->settings.fluid.kernel_radius;
    // custom_vector<int2>& bids = data_manager->host_data.bids_rigid_fluid;
    custom_vector<real3>& cpta = data_manager->host_data.cpta_rigid_fluid;
    custom_vector<real3>& norm = data_manager->host_data.norm_rigid_fluid;
    data_manager->system_timer.start("ChSolverParallel_solverC");
    custom_vector<int>& neighbor_rigid_fluid = data_manager->host_data.neighbor_rigid_fluid;
    custom_vector<int>& contact_counts = data_manager->host_data.c_counts_rigid_fluid;
    int num_fluid_bodies = data_manager->num_fluid_bodies;
    //#pragma omp parallel for
    int index = 0;
    for (int p = 0; p < num_fluid_bodies; p++) {
        for (int i = 0; i < contact_counts[p]; i++) {
            int rigid = neighbor_rigid_fluid[p * max_rigid_neighbors + i];
            int fluid = p;  // fluid body is in second index
            real3 U = norm[p * max_rigid_neighbors + i], V, W;
            Orthogonalize(U, V, W);
            real3 T1, T2, T3;
            Compute_Jacobian(rot_rigid[rigid], U, V, W, cpta[p * max_rigid_neighbors + i] - pos_rigid[rigid], T1, T2,
                             T3);

            SetRow6Check(D_rfn_T, index + 0, rigid * 6, -U, T1);
            SetRow6Check(D_rft_T, index * 2 + 0, rigid * 6, -V, T2);
            SetRow6Check(D_rft_T, index * 2 + 1, rigid * 6, -W, T3);

            SetRow3Check(D_rfn_T, index + 0, num_rigid_bodies * 6 + num_shafts + fluid * 3, U);
            SetRow3Check(D_rft_T, index * 2 + 0, num_rigid_bodies * 6 + num_shafts + fluid * 3, V);
            SetRow3Check(D_rft_T, index * 2 + 1, num_rigid_bodies * 6 + num_shafts + fluid * 3, W);
            index++;
        }
    }
    data_manager->system_timer.stop("ChSolverParallel_solverC");
}
void ChConstraintRigidFluid::Build_b() {
    LOG(INFO) << "ChConstraintRigidFluid::Build_b";
    uint num_rigid_fluid_contacts = data_manager->num_rigid_fluid_contacts;
    uint num_unilaterals = data_manager->num_unilaterals;
    uint num_bilaterals = data_manager->num_bilaterals;
    real step_size = data_manager->settings.step_size;
    if (num_rigid_fluid_contacts <= 0) {
        return;
    }

    custom_vector<int>& neighbor_rigid_fluid = data_manager->host_data.neighbor_rigid_fluid;
    custom_vector<int>& contact_counts = data_manager->host_data.c_counts_rigid_fluid;
    int num_fluid_bodies = data_manager->num_fluid_bodies;

    //#pragma omp parallel for
    int index = 0;
    for (int p = 0; p < num_fluid_bodies; p++) {
        for (int i = 0; i < contact_counts[p]; i++) {
            real bi = 0;
            real depth = data_manager->host_data.dpth_rigid_fluid[p * max_rigid_neighbors + i];

            bi = std::max(real(1.0) / step_size * depth, -data_manager->settings.fluid.contact_recovery_speed);
            //
            data_manager->host_data.b[num_unilaterals + num_bilaterals + index + 0] = bi;
            data_manager->host_data.b[num_unilaterals + num_bilaterals + num_rigid_fluid_contacts + index * 2 + 0] = 0;
            data_manager->host_data.b[num_unilaterals + num_bilaterals + num_rigid_fluid_contacts + index * 2 + 1] = 0;
            index++;
        }
    }
}
void ChConstraintRigidFluid::Build_E() {
    LOG(INFO) << "ChConstraintRigidFluid::Build_E";
    uint num_rigid_fluid_contacts = data_manager->num_rigid_fluid_contacts;
    uint num_unilaterals = data_manager->num_unilaterals;
    uint num_bilaterals = data_manager->num_bilaterals;
    real step_size = data_manager->settings.step_size;
    if (num_rigid_fluid_contacts <= 0) {
        return;
    }
    DynamicVector<real>& E = data_manager->host_data.E;

#pragma omp parallel for
    for (int index = 0; index < num_rigid_fluid_contacts; index++) {
        int ind = num_unilaterals + num_bilaterals;
        real epsilon = data_manager->settings.fluid.epsilon;
        real tau = data_manager->settings.fluid.tau;
        real h = data_manager->settings.fluid.kernel_radius;
        real compliance = 4.0 / (step_size * step_size) * (epsilon / (1.0 + 4.0 * tau / h));

        E[ind + index + 0] = 0;
        E[ind + num_rigid_fluid_contacts + index * 2 + 0] = 0;
        E[ind + num_rigid_fluid_contacts + index * 2 + 1] = 0;
    }
}

void ChConstraintRigidFluid::GenerateSparsity() {
    LOG(INFO) << "ChConstraintRigidFluid::GenerateSparsity";
    uint num_rigid_fluid_contacts = data_manager->num_rigid_fluid_contacts;
    uint num_unilaterals = data_manager->num_unilaterals;
    uint num_bilaterals = data_manager->num_bilaterals;
    real step_size = data_manager->settings.step_size;
    uint num_rigid_bodies = data_manager->num_rigid_bodies;
    uint num_shafts = data_manager->num_shafts;
    CompressedMatrix<real>& D_T = data_manager->host_data.D_T;
    // custom_vector<int2>& bids = data_manager->host_data.bids_rigid_fluid;
    int index_n = 0;
    int index_t = 0;
    int num_fluid_bodies = data_manager->num_fluid_bodies;
    custom_vector<int>& neighbor_rigid_fluid = data_manager->host_data.neighbor_rigid_fluid;
    custom_vector<int>& contact_counts = data_manager->host_data.c_counts_rigid_fluid;
    int off = num_unilaterals + num_bilaterals;
    for (int p = 0; p < num_fluid_bodies; p++) {
        for (int i = 0; i < contact_counts[p]; i++) {
            // int2 body_id = bids[index];
            int rigid = neighbor_rigid_fluid[p * max_rigid_neighbors + i];
            int fluid = p;

            AppendRow6(D_T, off + index_n + 0, rigid * 6, 0);
            AppendRow3(D_T, off + index_n + 0, num_rigid_bodies * 6 + num_shafts + fluid * 3, 0);
            D_T.finalize(off + index_n + 0);
            index_n++;
        }
    }
    for (int p = 0; p < num_fluid_bodies; p++) {
        for (int i = 0; i < contact_counts[p]; i++) {
            int rigid = neighbor_rigid_fluid[p * max_rigid_neighbors + i];
            int fluid = p;

            AppendRow6(D_T, off + num_rigid_fluid_contacts + index_t * 2 + 0, rigid * 6, 0);
            AppendRow3(D_T, off + num_rigid_fluid_contacts + index_t * 2 + 0,
                       num_rigid_bodies * 6 + num_shafts + fluid * 3, 0);
            D_T.finalize(off + num_rigid_fluid_contacts + index_t * 2 + 0);

            AppendRow6(D_T, off + num_rigid_fluid_contacts + index_t * 2 + 1, rigid * 6, 0);
            AppendRow3(D_T, off + num_rigid_fluid_contacts + index_t * 2 + 1,
                       num_rigid_bodies * 6 + num_shafts + fluid * 3, 0);

            D_T.finalize(off + num_rigid_fluid_contacts + index_t * 2 + 1);
            index_t++;
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>print_info_error: Use AutoFreePointer<commit_after><|endoftext|>


<commit_before><commit_msg>11517 - Exact Change<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH, Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "iceoryx_posh/runtime/node.hpp"
#include "iceoryx_posh/internal/roudi_environment/roudi_environment.hpp"
#include "iceoryx_posh/runtime/posh_runtime.hpp"

#include "test.hpp"

using namespace ::testing;
using namespace iox::runtime;
using namespace iox::roudi;

namespace iox
{
namespace test
{
/// @brief Test goal: This test suit verifies class node

//bool callbackWasCalled = false;
//PoshRuntime& testFactory(iox::cxx::optional<const iox::ProcessName_t*> name)
//{
//    callbackWasCalled = true;
//    return PoshRuntime::defaultRuntimeFactory(name);
//}

class PoshRuntimeNode_test : public Test
{
  public:
    PoshRuntimeNode_test()
    {
    }

    virtual ~PoshRuntimeNode_test()
    {
    }

    virtual void SetUp()
    {
    };

    virtual void TearDown()
    {
    };

    const ProcessName_t m_runtimeName{"App"};
    RouDiEnvironment m_roudiEnv{iox::RouDiConfig_t().setDefaults()};
    PoshRuntime* m_runtime{&iox::runtime::PoshRuntime::initRuntime(m_runtimeName)};
};

TEST_F(PoshRuntimeNode_test, CreateNode)
{
    const NodeName_t& nodeName{"Node"};
    Node m_node("Node");

    EXPECT_THAT(m_node.getNodeName(),Eq(nodeName));
}

TEST_F(PoshRuntimeNode_test, NodeOperator)
{
    const NodeName_t& nodeNewName{"NewNode"};
    Node m_node("Node");
    m_node = Node("NewNode");

    EXPECT_THAT(m_node.getNodeName(), Eq(nodeNewName));
}

} // namespace test
} // namespace iox
<commit_msg>iox-#496 change year file<commit_after>// Copyright (c) 2021 by Robert Bosch GmbH, Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "iceoryx_posh/runtime/node.hpp"
#include "iceoryx_posh/internal/roudi_environment/roudi_environment.hpp"
#include "iceoryx_posh/runtime/posh_runtime.hpp"

#include "test.hpp"

using namespace ::testing;
using namespace iox::runtime;
using namespace iox::roudi;

namespace iox
{
namespace test
{
/// @brief Test goal: This test suit verifies class node

//bool callbackWasCalled = false;
//PoshRuntime& testFactory(iox::cxx::optional<const iox::ProcessName_t*> name)
//{
//    callbackWasCalled = true;
//    return PoshRuntime::defaultRuntimeFactory(name);
//}

class PoshRuntimeNode_test : public Test
{
  public:
    PoshRuntimeNode_test()
    {
    }

    virtual ~PoshRuntimeNode_test()
    {
    }

    virtual void SetUp()
    {
    };

    virtual void TearDown()
    {
    };

    const ProcessName_t m_runtimeName{"App"};
    RouDiEnvironment m_roudiEnv{iox::RouDiConfig_t().setDefaults()};
    PoshRuntime* m_runtime{&iox::runtime::PoshRuntime::initRuntime(m_runtimeName)};
};

TEST_F(PoshRuntimeNode_test, CreateNode)
{
    const NodeName_t& nodeName{"Node"};
    Node m_node("Node");

    EXPECT_THAT(m_node.getNodeName(),Eq(nodeName));
}

TEST_F(PoshRuntimeNode_test, NodeOperator)
{
    const NodeName_t& nodeNewName{"NewNode"};
    Node m_node("Node");
    m_node = Node("NewNode");

    EXPECT_THAT(m_node.getNodeName(), Eq(nodeNewName));
}

} // namespace test
} // namespace iox
<|endoftext|>