text:
#define PCL_NO_PRECOMPILE
#include <vector>
#include <iostream>
#include <Eigen/Core>
#include <pcl/io/pcd_io.h>
#include <pcl/common/transforms.h>
#include <pcl/registration/transforms.h>
#include <pcl/pcl_macros.h>
#include <pcl/console/parse.h>

int angle_ (30);
float division_ (6.0f);
float size_ (1.0f);
int name_number_ (0);

std::string model_filename_;

void
showHelp (char *filename)
{
  std::cout << std::endl;
  std::cout << "***************************************************************************" << std::endl;
  std::cout << "*                                                                         *" << std::endl;
  std::cout << "*             Dataset creation - Usage Guide              *" << std::endl;
  std::cout << "*                                                                         *" << std::endl;
  std::cout << "***************************************************************************" << std::endl << std::endl;
  std::cout << "Usage: " << filename << " model_filename.pcd [Options]" << std::endl << std::endl;
  std::cout << "Options:" << std::endl;
  std::cout << "     --angle val:          rotation angle (degree) (default :"<< angle_ << ")"  << std::endl;
  std::cout << "       every 15 from -90 to 90, for example: -90, -75, -60, -45, etc."  << std::endl;
  std::cout << "     --size val:               size (default :" << size_ << ")" << std::endl;
  std::cout << "       it's better from 0.5 to -2.0 "  << std::endl;
  std::cout << "     --name_number val:        name_number (default :" << name_number_ << ")" << std::endl;
  std::cout << "       The name is : training_model_[name_number].pcd"  << std::endl;
}

void transform_dataset (pcl::PointCloud<pcl::PointXYZ>::Ptr &points1,
                        pcl::PointCloud<pcl::PointXYZ>::Ptr &points1_trans,
                        float & division_,
                        float & size_,
                        int & name_number_)
{
  // to rotate the model grounded //
  pcl::PointCloud<pcl::PointXYZ>::Ptr transformed_cloud_ (new pcl::PointCloud<pcl::PointXYZ> ());
  Eigen::Affine3f transform_1 = Eigen::Affine3f::Identity();

  Eigen::Matrix3f angle;
  angle = Eigen::AngleAxisf(M_PI/2, Eigen::Vector3f::UnitX())
          * Eigen::AngleAxisf(M_PI,  Eigen::Vector3f::UnitY())
          * Eigen::AngleAxisf(M_PI/2, Eigen::Vector3f::UnitZ());

  transform_1.translation() << 108, 234, 2105;
  transform_1.rotate (angle);
  transform_1.scale (150.0);
  pcl::transformPointCloud (*points1, *transformed_cloud_, transform_1);

  ////// do not modify above //////

  Eigen::Affine3f transform_2 = Eigen::Affine3f::Identity();

  Eigen::Matrix3f angle_set;
  angle_set = Eigen::AngleAxisf(0, Eigen::Vector3f::UnitX())
              * Eigen::AngleAxisf(M_PI/division_,  Eigen::Vector3f::UnitY())
              * Eigen::AngleAxisf(0, Eigen::Vector3f::UnitZ());

  transform_2.rotate (angle_set);
  transform_2.scale (size_);
  pcl::transformPointCloud (*transformed_cloud_, *points1_trans, transform_2);

  std::stringstream ss1;
  ss1 << "training_model_"<<name_number_<<".pcd";

  pcl::io::savePCDFileASCII(ss1.str (), *points1_trans);
  std::cout << "save No."<<name_number_<< " to the PCD."<< std::endl;
}

void
parseCommandLine (int argc, char *argv[])
{
  //Show help
  if (pcl::console::find_switch (argc, argv, "-h"))
  {
    showHelp (argv[0]);
    exit (0);
  }

  //Model & scene filenames
  std::vector<int> filenames;
  filenames = pcl::console::parse_file_extension_argument (argc, argv, ".pcd");
  if (filenames.size () != 1)
  {
    std::cout << "Filenames missing.\n";
    showHelp (argv[0]);
    exit (-1);
  }

  model_filename_ = argv[filenames[0]];

  //General parameters
  pcl::console::parse_argument (argc, argv, "--angle", angle_);
  pcl::console::parse_argument (argc, argv, "--size", size_);
  pcl::console::parse_argument (argc, argv, "--name_number", name_number_);

  if (angle_ == -90 )  division_ = 2;
  else if (angle_ == -75 )  division_ = 2.4;
  else if (angle_ == -60 )  division_ = 3;
  else if (angle_ == -45 )  division_ = 4;
  else if (angle_ == -30 )  division_ = 6;
  else if (angle_ == -15 )  division_ = 12;
  else if (angle_ == 0 )  division_ = 10000;
  else if (angle_ == 15 )  division_ = -12;
  else if (angle_ == 30 )  division_ = -6;
  else if (angle_ == 45 )  division_ = -4;
  else if (angle_ == 60 )  division_ = -3;
  else if (angle_ == 75 )  division_ = -2.4;
  else if (angle_ == 90 )  division_ = -2;
  else division_ = 10000;
}

int main (int argc, char *argv[])
{

  parseCommandLine (argc, argv);
  // Create some new point clouds to hold our data
  pcl::PointCloud<pcl::PointXYZ>::Ptr points1 (new pcl::PointCloud<pcl::PointXYZ>);
  pcl::PointCloud<pcl::PointXYZ>::Ptr points1_move (new pcl::PointCloud<pcl::PointXYZ>);

  //  Load clouds
  if (pcl::io::loadPCDFile (model_filename_, *points1) < 0)
  {
    std::cout << "Error loading model cloud." << std::endl;
    showHelp (argv[0]);
    return (-1);
  }

  std::cout << "load " << model_filename_ << " successfully" << std::endl;
  transform_dataset(points1, points1_move, division_, size_, name_number_);

  return (0);
}

ext: cpp

max_stars_repo_name: Siyu-ZOUZOU/Project


text:
/*
MIT License

Copyright (c) 2019 Kalu U. Ogbureke

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.

Authors: Kalu U. Ogbureke
Change Log: 01.04.2019 - Version 1.0.0
*/
#include <iostream>
#include <cmath>
#include <boost/program_options.hpp>
#include "libutil.h"
#include "optimizer.h"

using namespace mlearn;
namespace po = boost::program_options;
/**
    The trainModel functions is responsible for training.

    @param mode Program usage mode: train
    @param optimizer optimization algorithm used: sgd, adagrad, rmsprop
    @param cost_function Cost function used: mse, mae, crossentropy
    @param learning_rate Learning rate used for training
    @param batch_size Batch size used for training
    @param num_epochs Number of training epochs
    @param lambda Regularization parameter used for training
    @param reg Type of regularization (L1, L2 or None)
    @param beta Momentum term/parameter
    @param dataset Path to the train or test file
    @param header Determines whether dataset file contains header
    @param feature_dim Number of input points/features
    @param label_dim Number of output points/labels
    @param test_size % of train dataset used for validation
    @param num_hidden_layers Number of hidden layers
    @param hidden_dim Number of hidden units
    @param hidden_activation Activation function of hidden layers
    @param output_activation Activation function of the output layer
    @param model_file Path to model file (for saving trained model)
*/
int trainModel(
          std::string mode,
          std::string optimizer,
          std::string cost_function,
          double learning_rate,
          uint32_t batch_size,
          uint32_t num_epochs,
          double lambda,
          std::string reg,
          double beta,
          std::string dataset,
          bool header,
          uint64_t feature_dim,
          uint64_t label_dim,
          double test_size,
          uint16_t num_hidden_layers,
          uint64_t hidden_dim,
          std::string hidden_activation,
          std::string output_activation,
          std::string model_file
          );
/**
    The testModel functions is responsible for testing
    on a held-out set with a trained model.

    @param mode Program usage mode: test
    @param cost_function Cost function used: mse, mae, crossentropy
    @param dataset Path to the train or test file
    @param header Determines whether dataset file contains header
    @param feature_dim Number of input points/features
    @param label_dim Number of output points/labels
    @param model_file Path to model file (for saving trained model)
*/
int testModel(
            std::string mode,
            std::string cost_function,
            std::string dataset,
            bool header,
            uint64_t feature_dim,
            uint64_t label_dim,
            std::string model_file
            );
/**
    The is the entry point of the program. It processes user
    command line options and implements the train or test functions.
*/
int main(int argc, char** argv)
{
    std::string mode = "train";
    std::string optimizer = "sgd";
    std::string cost_function = "MSE";
    double learning_rate = 0.1;
    uint32_t batch_size = 10;
    uint32_t num_epochs = 20;
    double lambda = 0.0;
    std::string reg = "None";
    double beta = 0.0;
    std::string dataset = "mnist";
    bool header = false;
    uint64_t feature_dim = 0;
    uint64_t label_dim = 0;
    double test_size = 0;
    uint16_t num_hidden_layers = 1;
    uint64_t hidden_dim = 0;
    std::string hidden_activation = "sigmoid";
    std::string output_activation = "sigmoid";
    std::string model_file = "temp.bin";
    po::variables_map vm;
    try
    {

        po::options_description desc("Training Options");
        desc.add_options()
            ("help,h", "gives information about usage")
            ("mode,m", po::value<std::string>(&mode)->default_value("train"), "program usage mode: either train or test")
            ("optimizer,o", po::value<std::string>(&optimizer)->default_value("sgd"), "optimization algorithm used: sgd, adagrad, rmsprop")
            ("cost_function,c", po::value<std::string>(&cost_function)->default_value("crossentropy"), "cost function used: mse, mae, crossentropy")
            ("learning_rate,r", po::value<double>(&learning_rate)->default_value(0.05), "learning rate used for training")
            ("batch_size,s", po::value<uint32_t>(&batch_size)->default_value(10), "batch size used for training")
            ("num_epochs,n", po::value<uint32_t>(&num_epochs)->default_value(20), "number of training epochs")
            ("lambda,l", po::value<double>(&lambda)->default_value(0.0), "regularization parameter used for training")
            ("reg,R", po::value<std::string>(&reg)->default_value("None"), "type of regularization (L1, L2 or None)")
            ("beta,b", po::value<double>(&beta)->default_value(0.0), "momentum term/parameter")
            ("dataset,d", po::value<std::string>(&dataset)->default_value("mnist"), "the path to the train or test file")
            ("header,H", po::value<bool>(&header)->default_value(false), "determines whether dataset file contains header")
            ("feature_dim,F", po::value<uint64_t>(&feature_dim)->default_value(784), "number of input points/features")
            ("label_dim,L", po::value<uint64_t>(&label_dim)->default_value(10), "number of output points/labels")
            ("test_size,t", po::value<double>(&test_size)->default_value(0.0), "% of train dataset used for validation")
            ("num_hidden_layers,N", po::value<uint16_t>(&num_hidden_layers)->default_value(1), "number of hidden layers")
            ("hidden_dim,D", po::value<uint64_t>(&hidden_dim)->default_value(100), "number of hidden units")
            ("hidden_activation,a", po::value<std::string>(&hidden_activation)->default_value("sigmoid"), "activation function of hidden layers")
            ("output_activation,A", po::value<std::string>(&output_activation)->default_value("softmax"), "activation function of output layer")
            ("model_file,f", po::value<std::string>(&model_file)->default_value("temp.bin"), "path to model file")
            ;

        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);

        if (vm.count("help"))
        {
            std::cout << desc << std::endl;
            return 0;
        }
        if (vm.count("mode"))mode = vm["mode"].as<std::string>();
        if (vm.count("optimizer"))optimizer = vm["optimizer"].as<std::string>();
        if (vm.count("cost_function"))cost_function = vm["cost_function"].as<std::string>();
        if (vm.count("learning_rate"))learning_rate = vm["learning_rate"].as<double>();
        if (vm.count("batch_size"))batch_size = vm["batch_size"].as<uint32_t>();
        if (vm.count("num_epochs"))num_epochs = vm["num_epochs"].as<uint32_t>();
        if (vm.count("lambda"))lambda = vm["lambda"].as<double>();
        if (vm.count("reg"))reg = vm["reg"].as<std::string>();
        if (vm.count("beta"))beta = vm["beta"].as<double>();
        if (vm.count("dataset"))dataset = vm["dataset"].as<std::string>();
        if (vm.count("header"))header = vm["header"].as<bool>();
        if (vm.count("feature_dim"))feature_dim = vm["feature_dim"].as<uint64_t>();
        if (vm.count("label_dim"))label_dim = vm["label_dim"].as<uint64_t>();
        if (vm.count("test_size"))test_size = vm["test_size"].as<double>();
        if (vm.count("num_hidden_layers"))num_hidden_layers = vm["num_hidden_layers"].as<uint16_t>();
        if (vm.count("hidden_dim"))hidden_dim = vm["hidden_dim"].as<uint64_t>();
        if (vm.count("hidden_activation"))hidden_activation = vm["hidden_activation"].as<std::string>();
        if (vm.count("output_activation"))output_activation = vm["output_activation"].as<std::string>();
        if (vm.count("model_file"))model_file = vm["model_file"].as<std::string>();

    }
    catch(std::exception& e)
    {
        std::cerr << "error: " << e.what() << std::endl;
        exit(EXIT_FAILURE);
    }

    if(vm["mode"].as<std::string>() == "train")
    {
        std::set<std::string> optimizers{"sgd", "adagrad", "rmsprop", "psdsquare"};
        std::set<std::string> cost_functions{"mse", "mae", "crossentropy"};
        if (optimizers.count(optimizer) == 0)
        {
            std::cerr << "optimizer error: sgd, adagrad, rmsprop, psdsquare" << std::endl;
            exit(EXIT_FAILURE);
        }
        if (cost_functions.count(cost_function) == 0)
        {
            std::cerr << "cost function error: mse, mse, crossentropy" << std::endl;
            exit(EXIT_FAILURE);
        }
        if (cost_function == "crossentropy" && output_activation != "softmax")
        {

            std::cerr << "cost function/output activation error: crossentropy goes with softmax!" << std::endl;
            exit(EXIT_FAILURE);
        }
        std::cout << "-----T r a i n   C o n f i g u r a t i o n-----" << std::endl << std::endl;
        std::cout << "program usage mode: " << vm["mode"].as<std::string>() << std::endl;
        std::cout << "optimization algorithm used: " << vm["optimizer"].as<std::string>() << std::endl;
        std::cout << "cost function used: " << vm["cost_function"].as<std::string>() << std::endl;
        std::cout << "learning rate: " << vm["learning_rate"].as<double>() << std::endl;
        std::cout << "batch size: " << vm["batch_size"].as<uint32_t>() << std::endl;
        std::cout << "number of training epochs: " << vm["num_epochs"].as<uint32_t>() << std::endl;
        std::cout << "regularization parameter lambda: " << vm["lambda"].as<double>() << std::endl;
        std::cout << "type of regularization: " << vm["reg"].as<std::string>() << std::endl;
        std::cout << "momentum term/parameter beta: " << vm["beta"].as<double>() << std::endl;
        std::cout << "dataset: " << vm["dataset"].as<std::string>() << std::endl;
        std::cout << "dataset header info: " << vm["header"].as<bool>() << std::endl;
        std::cout << "input feature dimension: " << vm["feature_dim"].as<uint64_t>() << std::endl;
        std::cout << "output label dimension: " << vm["label_dim"].as<uint64_t>() << std::endl;
        std::cout << "% validation: " << vm["test_size"].as<double>() << std::endl;
        std::cout << "number of hidden layers: " << vm["num_hidden_layers"].as<uint16_t>() << std::endl;
        std::cout << "number of hidden units: " << vm["hidden_dim"].as<uint64_t>() << std::endl;
        std::cout << "activation function of hidden layers: " << vm["hidden_activation"].as<std::string>() << std::endl;
        std::cout << "activation function of output layer: " << vm["output_activation"].as<std::string>() << std::endl;
        std::cout << "path to model file: " << vm["model_file"].as<std::string>() << std::endl;

        trainModel(
                mode,
                optimizer,
                cost_function,
                learning_rate,
                batch_size,
                num_epochs,
                lambda,
                reg,
                beta,
                dataset,
                header,
                feature_dim,
                label_dim,
                test_size,
                num_hidden_layers,
                hidden_dim,
                hidden_activation,
                output_activation,
                model_file
                );
    }
    else if(vm["mode"].as<std::string>() == "test")
    {
        std::cout << "-----T e s t   C o n f i g u r a t i o n-----" << std::endl << std::endl;
        std::cout << "program usage mode: " << vm["mode"].as<std::string>() << std::endl;
        std::cout << "dataset: " << vm["dataset"].as<std::string>() << std::endl;
        std::cout << "dataset header info: " << vm["header"].as<bool>() << std::endl;
        std::cout << "input feature dimension: " << vm["feature_dim"].as<uint64_t>() << std::endl;
        std::cout << "output label dimension: " << vm["label_dim"].as<uint64_t>() << std::endl;
        std::cout << "path to model file: " << vm["model_file"].as<std::string>() << std::endl;

        testModel(mode, cost_function, dataset, header, feature_dim, label_dim, model_file);
    }
    else
    {
        std::cerr << "error: program mode not set/wrong mode" << std::endl;
        exit(EXIT_FAILURE);
    }

    return 0;
}

int trainModel(
          std::string mode,
          std::string optimizer,
          std::string cost_function,
          double learning_rate,
          uint32_t batch_size,
          uint32_t num_epochs,
          double lambda,
          std::string reg,
          double beta,
          std::string dataset,
          bool header,
          uint64_t feature_dim,
          uint64_t label_dim,
          double test_size,
          uint16_t num_hidden_layers,
          uint64_t hidden_dim,
          std::string hidden_activation,
          std::string output_activation,
          std::string model_file
          )
{

    Activation<double> a_hidden(hidden_activation), a_output(output_activation);
    Network<double>* model(nullptr);
    Optimizer<double>* opt(nullptr);
    Layer<double>* layer(nullptr);
    DataReader<double>* train(nullptr);
    DataReader<double>* validation(nullptr);

    if(cost_function == "mse") model = new Network<double>(new MSE<double>);
    else if(cost_function == "mae") model = new Network<double>(new MAE<double>);
    else if(cost_function == "crossentropy") model =  new Network<double>(new CrossEntropy<double>);
    if(num_hidden_layers > 0)
    {
        layer = new Layer<double>(feature_dim, hidden_dim, "hidden", a_hidden);
        model->addLayer(*layer);
        if(layer)delete layer;
    }

    for(uint16_t i = 1; i < num_hidden_layers; ++i)
    {
        layer = new Layer<double>(hidden_dim, hidden_dim, "hidden", a_hidden);
        model->addLayer(*layer);
        if(layer)delete layer;
    }
    if(num_hidden_layers > 0)layer = new Layer<double>(hidden_dim, label_dim, "output", a_output);
    else layer = new Layer<double>(feature_dim, label_dim, "output", a_output);
    model->addLayer(*layer);
    if(layer)delete layer;
    model->connectLayers();
    if(optimizer == "sgd") opt = new SGD<double>(learning_rate, batch_size, num_epochs, lambda, reg, beta);
    else if(optimizer == "adagrad") opt = new Adagrad<double>(learning_rate, batch_size, num_epochs, lambda, reg, beta);
    else if(optimizer == "rmsprop") opt = new RMSProp<double>(learning_rate, batch_size, num_epochs, lambda, reg, beta);
    else if(optimizer == "psdsquare") opt = new PSDSquare<double>(learning_rate, batch_size, num_epochs, lambda, reg, beta);
    else
    {
        std::cerr << "optimizer is not implemented" << std::endl;
        exit(EXIT_FAILURE);
    }

    if (dataset == "mnist")
    {
        train = new MNISTReader<double>("data/mnist_train.csv", ',',  false);
        train->read();
        if(test_size > 0.0)
        {
            validation = new MNISTReader<double>;
            train->trainTestSplit(*validation, test_size);
            opt->train(*model, model_file, train, validation);
        }
        else opt->train(*model, model_file, train);
    }
    else
    {
        train = new GenericReader<double>(dataset, feature_dim, label_dim, ',',  header);
        train->read();
        if(test_size > 0.0)
        {
            validation = new GenericReader<double>;
            train->trainTestSplit(*validation, test_size);
            opt->train(*model, model_file, train, validation);
        }
        else opt->train(*model, model_file, train);

    }
    if(opt)delete opt;
    if(model)delete model;
    if(train)delete train;
    if(validation)delete validation;
    return 0;

}
int testModel(
            std::string mode,
            std::string cost_function,
            std::string dataset,
            bool header,
            uint64_t feature_dim,
            uint64_t label_dim,
            std::string model_file
            )
{
    std::set<std::string> cost_functions{"mse", "mae", "crossentropy"};
    Optimizer<double>* opt = new SGD<double>;
    DataReader<double>* test(nullptr);
    Network<double>* model(nullptr);
    double accuracy;
    std::string test_info;

    if (cost_functions.count(cost_function) == 0)
    {
        std::cerr << "cost function error: mse, mse, crossentropy" << std::endl;
        exit(EXIT_FAILURE);
    }
    if(cost_function == "mse") model = new Network<double>(new MSE<double>);
    else if(cost_function == "mae") model = new Network<double>(new MAE<double>);
    else if(cost_function == "crossentropy") model =  new Network<double>(new CrossEntropy<double>);

    if (dataset == "mnist")
    {
        try
        {
            test = new MNISTReader<double>("data/mnist_test.csv", ',',  false);
            test->read();
        }catch (std::exception &e){
            std::cerr << e.what() << std::endl;
            exit(EXIT_FAILURE);
        }
    }
    else
    {
        try
        {
            test = new GenericReader<double>(dataset, feature_dim, label_dim, ',',  header);
            test->read();
        }catch (std::exception &e){
            std::cerr << e.what() << std::endl;
            exit(EXIT_FAILURE);
        }
    }
    accuracy = opt->predict(*model, test, model_file);
    if (cost_function == "mse")test_info = "MSE: " + std::to_string(accuracy);
    else if (cost_function == "mae")test_info = "MAE: " + std::to_string(accuracy);
    else if (cost_function == "crossentropy")test_info = "Classification Accuracy: " + std::to_string(accuracy * 100) + " %";
    if(opt)delete opt;
    if(test)delete test;
    if(model)delete model;
    std::cout << test_info << std::endl;

    return 0;
}

max_stars_repo_name: rasbt/mLEARn

max_issues_repo_name: rasbt/mLEARn

max_forks_repo_name: rasbt/mLEARn


text:
/* ============================================================================
 * Copyright (c) 2009-2016 BlueQuartz Software, LLC
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice, this
 * list of conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.
 *
 * Neither the name of BlueQuartz Software, the US Air Force, nor the names of its
 * contributors may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * The code contained herein was partially funded by the followig contracts:
 *    United States Air Force Prime Contract FA8650-07-D-5800
 *    United States Air Force Prime Contract FA8650-10-D-5210
 *    United States Prime Contract Navy N00173-07-C-2068
 *
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

/* ============================================================================
 * DerivativeHelpers re-implements the exterior derivative calculations
 * from the following vtk modules:
 *
 * * vtkLine.cxx
 *   - re-implemented vtkLine::Derivatives to EdgeDeriv::operator()
 * * vtkTriangle.cxx
 *   - re-implemented vtkTriangle::Derivatives to TriangleDeriv::operator()
 * * vtkQuad.cxx
 *   - re-implemented vtkQuad::Derivatives to QuadDeriv::operator()
 * * vtkTetra.cxx
 *   - re-implemented vtkTetra::Derivatives to TetDeriv::operator()
 * * vtkHexahedron.cxx
 *   - re-implemented vtkHexahedron::Derivatives to HexDeriv::operator()
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

#include "DerivativeHelpers.h"

#include <Eigen/Eigenvalues>
#include <Eigen/LU>

#include "SIMPLib/Geometry/EdgeGeom.h"
#include "SIMPLib/Geometry/HexahedralGeom.h"
#include "SIMPLib/Geometry/QuadGeom.h"
#include "SIMPLib/Geometry/TetrahedralGeom.h"
#include "SIMPLib/Geometry/TriangleGeom.h"
#include "SIMPLib/Math/GeometryMath.h"
#include "SIMPLib/Math/MatrixMath.h"

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DerivativeHelpers::EdgeDeriv::operator()(EdgeGeom* edges, size_t edgeId, double values[2], double derivs[3])
{
  float vert0_f[3] = {0.0f, 0.0f, 0.0f};
  float vert1_f[3] = {0.0f, 0.0f, 0.0f};
  double vert0[3] = {0.0, 0.0, 0.0};
  double vert1[3] = {0.0, 0.0, 0.0};
  double delta[3] = {0.0, 0.0, 0.0};
  size_t verts[2] = {0, 0};

  edges->getVertsAtEdge(edgeId, verts);
  edges->getCoords(verts[0], vert0_f);
  edges->getCoords(verts[1], vert1_f);

  std::copy(vert0_f, vert0_f + 3, vert0);
  std::copy(vert1_f, vert1_f + 3, vert1);

  for(size_t i = 0; i < 3; i++)
  {
    delta[i] = vert1[i] - vert0[i];
  }

  for(size_t i = 0; i < 3; i++)
  {
    if(delta[i] != 0.0)
    {
      derivs[i] = (values[1] - values[0]) / delta[i];
    }
    else
    {
      derivs[i] = 0.0;
    }
  }
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DerivativeHelpers::TriangleDeriv::operator()(TriangleGeom* triangles, size_t triId, double values[3], double derivs[3])
{
  float vert0_f[3] = {0.0f, 0.0f, 0.0f};
  float vert1_f[3] = {0.0f, 0.0f, 0.0f};
  float vert2_f[3] = {0.0f, 0.0f, 0.0f};
  double vert0[3] = {0.0, 0.0, 0.0};
  double vert1[3] = {0.0, 0.0, 0.0};
  double vert2[3] = {0.0, 0.0, 0.0};
  double vert0_2d[2] = {0.0, 0.0};
  double vert1_2d[2] = {0.0, 0.0};
  double vert2_2d[2] = {0.0, 0.0};
  double vector20[3] = {0.0, 0.0, 0.0};
  double basis1[3] = {0.0, 0.0, 0.0};
  double basis2[3] = {0.0, 0.0, 0.0};
  double mag_basis1 = 0.0;
  double mag_basis2 = 0.0;
  double normal[3] = {0.0, 0.0, 0.0};
  double shapeFunctions[6] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
  double sum[2] = {0.0, 0.0};
  double dBydx = 0.0;
  double dBydy = 0.0;
  size_t verts[3] = {0, 0, 0};

  triangles->getVertsAtTri(triId, verts);
  triangles->getCoords(verts[0], vert0_f);
  triangles->getCoords(verts[1], vert1_f);
  triangles->getCoords(verts[2], vert2_f);

  std::copy(vert0_f, vert0_f + 3, vert0);
  std::copy(vert1_f, vert1_f + 3, vert1);
  std::copy(vert2_f, vert2_f + 3, vert2);

  GeometryMath::FindPlaneNormalVector(vert0, vert1, vert2, normal);
  MatrixMath::Normalize3x1(normal);

  for(size_t i = 0; i < 3; i++)
  {
    basis1[i] = vert1[i] - vert0[i];
    vector20[i] = vert2[i] - vert0[i];
  }

  MatrixMath::CrossProduct(normal, basis1, basis2);

  mag_basis1 = MatrixMath::Magnitude3x1(basis1);
  mag_basis2 = MatrixMath::Magnitude3x1(basis2);

  if(mag_basis1 <= 0.0 || mag_basis2 <= 0.0)
  {
    for(size_t i = 0; i < 3; i++)
    {
      derivs[i] = 0.0;
    }
    return;
  }

  MatrixMath::Normalize3x1(basis1);
  MatrixMath::Normalize3x1(basis2);

  // Project the 3D triangle onto a 2D local system
  // Basis vectors for 2D system are the vector between triangle vertex 1 and 0 (basis1)
  // and the normal of the plane defined by the triangle normal and basis1 (basis2)
  vert0_2d[0] = vert0_2d[1] = 0.0;
  vert1_2d[0] = mag_basis1;
  vert1_2d[1] = 0.0;
  vert2_2d[0] = MatrixMath::DotProduct3x1(vector20, basis1);
  vert2_2d[1] = MatrixMath::DotProduct3x1(vector20, basis2);

  // Compute interpolation function derivatives
  triangles->getShapeFunctions(nullptr, shapeFunctions);

  // Compute Jacobian and inverse Jacobian using Eigen
  // Jacobian is constant for a triangle, so inverse must exist
  double jPtr[4] = {0.0, 0.0, 0.0, 0.0};

  jPtr[0] = vert1_2d[0] - vert0_2d[0];
  jPtr[1] = vert1_2d[1] - vert0_2d[1];
  jPtr[2] = vert2_2d[0] - vert0_2d[0];
  jPtr[3] = vert2_2d[1] - vert0_2d[1];

  Eigen::Map<TriangleJacobian> jMat(jPtr);
  TriangleJacobian jMatI;

  jMatI = jMat.inverse();

  // Loop over derivative values. For each set of values, compute
  // derivatives in local 2D system and then transform into original 3D system
  for(size_t i = 0; i < 3; i++)
  {
    sum[0] += shapeFunctions[i] * values[i];
    sum[1] += shapeFunctions[3 + i] * values[i];
  }

  dBydx = sum[0] * jMatI(0, 0) + sum[1] * jMatI(0, 1);
  dBydy = sum[0] * jMatI(1, 0) + sum[1] * jMatI(1, 1);

  derivs[0] = dBydx * basis1[0] + dBydy * basis2[0];
  derivs[1] = dBydx * basis1[1] + dBydy * basis2[1];
  derivs[2] = dBydx * basis1[2] + dBydy * basis2[2];
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DerivativeHelpers::QuadDeriv::operator()(QuadGeom* quads, size_t quadId, double values[4], double derivs[3])
{
  float vert0_f[3] = {0.0f, 0.0f, 0.0f};
  float vert1_f[3] = {0.0f, 0.0f, 0.0f};
  float vert2_f[3] = {0.0f, 0.0f, 0.0f};
  float vert3_f[3] = {0.0f, 0.0f, 0.0f};
  double vert0[3] = {0.0, 0.0, 0.0};
  double vert1[3] = {0.0, 0.0, 0.0};
  double vert2[3] = {0.0, 0.0, 0.0};
  double vert3[3] = {0.0, 0.0, 0.0};
  double vert0_2d[2] = {0.0, 0.0};
  double vert1_2d[2] = {0.0, 0.0};
  double vert2_2d[2] = {0.0, 0.0};
  double vert3_2d[2] = {0.0, 0.0};
  double vector20[3] = {0.0, 0.0, 0.0};
  double vector30[3] = {0.0, 0.0, 0.0};
  double basis1[3] = {0.0, 0.0, 0.0};
  double basis2[3] = {0.0, 0.0, 0.0};
  double mag_basis1 = 0.0;
  double mag_basis2 = 0.0;
  double normal[3] = {0.0, 0.0, 0.0};
  double shapeFunctions[8] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
  double pCoords[3]{0.0, 0.0, 0.0};
  double sum[2] = {0.0, 0.0};
  double dBydx = 0.0;
  double dBydy = 0.0;
  size_t verts[4] = {0, 0, 0, 0};

  quads->getVertsAtQuad(quadId, verts);
  quads->getCoords(verts[0], vert0_f);
  quads->getCoords(verts[1], vert1_f);
  quads->getCoords(verts[2], vert2_f);
  quads->getCoords(verts[3], vert3_f);

  std::copy(vert0_f, vert0_f + 3, vert0);
  std::copy(vert1_f, vert1_f + 3, vert1);
  std::copy(vert2_f, vert2_f + 3, vert2);
  std::copy(vert3_f, vert3_f + 3, vert3);

  GeometryMath::FindPlaneNormalVector(vert0, vert1, vert2, normal);
  MatrixMath::Normalize3x1(normal);

  // If vertices 0, 1, & 2 are co-linear, use vertex 3 to find the normal
  if(normal[0] == 0.0 && normal[1] == 0.0 && normal[2] == 0.0)
  {
    GeometryMath::FindPlaneNormalVector(vert0, vert1, vert2, normal);
    MatrixMath::Normalize3x1(normal);
  }

  for(size_t i = 0; i < 3; i++)
  {
    basis1[i] = vert1[i] - vert0[i];
    vector20[i] = vert2[i] - vert0[i];
    vector30[i] = vert3[i] - vert0[i];
  }

  MatrixMath::CrossProduct(normal, basis1, basis2);

  mag_basis1 = MatrixMath::Magnitude3x1(basis1);
  mag_basis2 = MatrixMath::Magnitude3x1(basis2);

  if(mag_basis1 <= 0.0 || mag_basis2 <= 0.0)
  {
    for(size_t i = 0; i < 3; i++)
    {
      derivs[i] = 0.0;
    }
    return;
  }

  MatrixMath::Normalize3x1(basis1);
  MatrixMath::Normalize3x1(basis2);

  // Project the 3D quad onto a 2D local system
  // Basis vectors for 2D system are the vector between quad vertex 1 and 0 (basis1)
  // and the normal of the plane defined by the quad normal and basis1 (basis2)
  vert0_2d[0] = vert0_2d[1] = 0.0;
  vert1_2d[0] = mag_basis1;
  vert1_2d[1] = 0.0;
  vert2_2d[0] = MatrixMath::DotProduct3x1(vector20, basis1);
  vert2_2d[1] = MatrixMath::DotProduct3x1(vector20, basis2);
  vert3_2d[0] = MatrixMath::DotProduct3x1(vector30, basis1);
  vert3_2d[1] = MatrixMath::DotProduct3x1(vector30, basis2);

  quads->getParametricCenter(pCoords);
  quads->getShapeFunctions(pCoords, shapeFunctions);

  // Compute Jacobian and inverse Jacobian using Eigen
  double jPtr[4] = {0.0, 0.0, 0.0, 0.0};

  jPtr[0] = vert0_2d[0] * shapeFunctions[0] + vert1_2d[0] * shapeFunctions[1] + vert2_2d[0] * shapeFunctions[2] + vert3_2d[0] * shapeFunctions[3];
  jPtr[1] = vert0_2d[1] * shapeFunctions[0] + vert1_2d[1] * shapeFunctions[1] + vert2_2d[1] * shapeFunctions[2] + vert3_2d[1] * shapeFunctions[3];
  jPtr[2] = vert0_2d[0] * shapeFunctions[4] + vert1_2d[0] * shapeFunctions[5] + vert2_2d[0] * shapeFunctions[6] + vert3_2d[0] * shapeFunctions[7];
  jPtr[3] = vert0_2d[1] * shapeFunctions[4] + vert1_2d[1] * shapeFunctions[5] + vert2_2d[1] * shapeFunctions[6] + vert3_2d[1] * shapeFunctions[7];

  Eigen::Map<QuadJacobian> jMat(jPtr);
  QuadJacobian jMatI;
  bool invertible = false;

  jMat.computeInverseWithCheck(jMatI, invertible);

  // Jacobian is non-constant for a quad, so must check if inverse exists
  // If the Jacobian is not invertible, set derivatives to 0
  if(!invertible)
  {
    for(size_t i = 0; i < 3; i++)
    {
      derivs[i] = 0.0;
    }
  }

  // Loop over derivative values. For each set of values, compute
  // derivatives in local 2D system and then transform into original 3D system
  for(size_t i = 0; i < 4; i++)
  {
    sum[0] += shapeFunctions[i] * values[i];
    sum[1] += shapeFunctions[4 + i] * values[i];
  }

  dBydx = sum[0] * jMatI(0, 0) + sum[1] * jMatI(0, 1);
  dBydy = sum[0] * jMatI(1, 0) + sum[1] * jMatI(1, 1);

  derivs[0] = dBydx * basis1[0] + dBydy * basis2[0];
  derivs[1] = dBydx * basis1[1] + dBydy * basis2[1];
  derivs[2] = dBydx * basis1[2] + dBydy * basis2[2];
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DerivativeHelpers::TetDeriv::operator()(TetrahedralGeom* tets, size_t tetId, double values[4], double derivs[3])
{
  double shapeFunctions[12] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
  size_t verts[4] = {0, 0, 0, 0};
  double sum[3] = {0.0, 0.0, 0.0};

  tets->getShapeFunctions(nullptr, shapeFunctions);

  // Compute 3x3 Jacobian from vertex coordinates and tet shape functions,
  // then find the inverse Jacobian using Eigen
  double jPtr[9] = {
      0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
  };

  tets->getVertsAtTet(tetId, verts);

  for(size_t i = 0; i < 4; i++)
  {
    float tmpCoords_f[3] = {0.0, 0.0, 0.0};
    double tmpCoords[3] = {0.0, 0.0, 0.0};
    tets->getCoords(verts[i], tmpCoords_f);
    std::copy(tmpCoords_f, tmpCoords_f + 3, tmpCoords);
    for(size_t j = 0; j < 3; j++)
    {
      jPtr[j] += tmpCoords[j] * shapeFunctions[i];
      jPtr[j + 3] += tmpCoords[j] * shapeFunctions[4 + i];
      jPtr[j + 6] += tmpCoords[j] * shapeFunctions[8 + i];
    }
  }

  Eigen::Map<TetJacobian> jMat(jPtr);
  TetJacobian jMatI;
  bool invertible = false;

  jMat.computeInverseWithCheck(jMatI, invertible);

  // Jacobian is non-constant for a tet, so must check if inverse exists
  // If the Jacobian is not invertible, set derivatives to 0
  if(!invertible)
  {
    for(size_t i = 0; i < 3; i++)
    {
      derivs[i] = 0.0;
    }
  }

  for(size_t i = 0; i < 4; i++)
  {
    sum[0] += shapeFunctions[i] * values[i];
    sum[1] += shapeFunctions[4 + i] * values[i];
    sum[2] += shapeFunctions[8 + i] * values[i];
  }

  derivs[0] = sum[0] * jMatI(0, 0) + sum[1] * jMatI(0, 1) + sum[2] * jMatI(0, 2);
  derivs[1] = sum[0] * jMatI(1, 0) + sum[1] * jMatI(1, 1) + sum[2] * jMatI(1, 2);
  derivs[2] = sum[0] * jMatI(2, 0) + sum[1] * jMatI(2, 1) + sum[2] * jMatI(2, 2);
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DerivativeHelpers::HexDeriv::operator()(HexahedralGeom* hexas, size_t hexId, double values[8], double derivs[3])
{
  double shapeFunctions[24] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
  size_t verts[8] = {0, 0, 0, 0, 0, 0, 0, 0};
  double sum[3] = {0.0, 0.0, 0.0};
  double pCoords[3] = {0.0, 0.0, 0.0};

  hexas->getParametricCenter(pCoords);
  hexas->getShapeFunctions(pCoords, shapeFunctions);

  // Compute 3x3 Jacobian from vertex coordinates and tet shape functions,
  // then find the inverse Jacobian using Eigen
  double jPtr[9] = {
      0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
  };

  hexas->getVertsAtHex(hexId, verts);

  for(size_t i = 0; i < 8; i++)
  {
    float tmpCoords_f[3] = {0.0, 0.0, 0.0};
    double tmpCoords[3] = {0.0, 0.0, 0.0};
    hexas->getCoords(verts[i], tmpCoords_f);
    std::copy(tmpCoords_f, tmpCoords_f + 3, tmpCoords);
    for(size_t j = 0; j < 3; j++)
    {
      jPtr[j] += tmpCoords[j] * shapeFunctions[i];
      jPtr[j + 3] += tmpCoords[j] * shapeFunctions[8 + i];
      jPtr[j + 6] += tmpCoords[j] * shapeFunctions[16 + i];
    }
  }

  Eigen::Map<HexJacobian> jMat(jPtr);
  HexJacobian jMatI;
  bool invertible = false;

  jMat.computeInverseWithCheck(jMatI, invertible);

  // Jacobian is non-constant for a tet, so must check if inverse exists
  // If the Jacobian is not invertible, set derivatives to 0
  if(!invertible)
  {
    for(size_t i = 0; i < 3; i++)
    {
      derivs[i] = 0.0;
    }
  }

  for(size_t i = 0; i < 8; i++)
  {
    sum[0] += shapeFunctions[i] * values[i];
    sum[1] += shapeFunctions[8 + i] * values[i];
    sum[2] += shapeFunctions[16 + i] * values[i];
  }

  derivs[0] = sum[0] * jMatI(0, 0) + sum[1] * jMatI(0, 1) + sum[2] * jMatI(0, 2);
  derivs[1] = sum[0] * jMatI(1, 0) + sum[1] * jMatI(1, 1) + sum[2] * jMatI(1, 2);
  derivs[2] = sum[0] * jMatI(2, 0) + sum[1] * jMatI(2, 1) + sum[2] * jMatI(2, 2);
}

max_stars_repo_name: jmarquisbq/SIMPL

max_issues_repo_name: jmarquisbq/SIMPL

max_forks_repo_name: jmarquisbq/SIMPL


text:
#include <boost/python.hpp>

#include "OpenPGP/Packets/Tag12.h"

void Tag12_init()
{
boost::python::class_<Tag12, boost::python::bases<Packet>>("Tag12")
    .def(boost::python::init<std::string &>())
    .def("read", &Tag12::read)
    .def("show", &Tag12::show)
    .def("get_trust", &Tag12::get_trust)
    .def("raw", &Tag12::raw)
    .def("set_trust", &Tag12::set_trust)
    .def("clone", &Tag12::clone)
    ;
}

max_stars_repo_name: mugwort-rc/pyOpenPGP

max_issues_repo_name: mugwort-rc/pyOpenPGP

max_forks_repo_name: mugwort-rc/pyOpenPGP


text:
///////////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2008-2012  Artyom Beilis (Tonkikh) <artyomtnk@yahoo.com>
//
//  See accompanying file COPYING.TXT file for licensing details.
//
///////////////////////////////////////////////////////////////////////////////
#include <cppcms/defs.h>
#include <cppcms/config.h>
#include "test.h"
#include <cppcms/session_storage.h>
#include "session_memory_storage.h"
#ifdef CPPCMS_WIN_NATIVE
#include "session_win32_file_storage.h"
#include <windows.h>
#else
#include "session_posix_file_storage.h"
#include <sys/types.h>
#include <dirent.h>
#endif
#ifndef CPPCMS_NO_TCP_CACHE
#include "tcp_cache_server.h"
#include "session_tcp_storage.h"
#endif
#include <booster/function.h>
#include <booster/backtrace.h>
#include <string.h>
#include <booster/auto_ptr_inc.h>
#include <iostream>
#include <vector>
#include <stdio.h>
#include <time.h>

std::string dir = "./sessions";
std::string bs="0123456789abcdef0123456789abcde";

void do_nothing() {}

void test(booster::shared_ptr<cppcms::sessions::session_storage> storage,cppcms::sessions::session_storage_factory &f)
{
	time_t now=time(0)+3;
	storage->save(bs+"1",now,"");
	std::string out="xx";
	time_t tout;
	TEST(storage->load(bs+"1",tout,out));
	TEST(out.empty());
	TEST(tout==now);
	storage->remove(bs+"1");
	TEST(!storage->load(bs+"1",tout,out));
	storage->save(bs+"1",now-4,"hello world");
	TEST(!storage->load(bs+"1",tout,out));
	storage->save(bs+"1",now,"hello world");
	TEST(storage->load(bs+"1",tout,out));
	TEST(out=="hello world");
	storage->save(bs+"2",now,"x");
	storage->remove(bs+"2");
	TEST(storage->load(bs+"1",tout,out));
	TEST(out=="hello world");
	storage->remove(bs+"1");
	storage->remove(bs+"2");
	f.gc_job();
}

int count_files()
{
#ifndef CPPCMS_WIN_NATIVE
	DIR *d=opendir(dir.c_str());
	TEST(d);
	int counter = 0;
	struct dirent *de;
	while((de=readdir(d))!=0) {
		if(strlen(de->d_name)==32)
			counter++;
	}
	closedir(d);
	return counter;
#else
	WIN32_FIND_DATA entry;
	HANDLE d=FindFirstFile((dir+"/*").c_str(),&entry);
	int counter=0;
	if(d==INVALID_HANDLE_VALUE) {
		return 0;
	}
	do {
		if(strlen(entry.cFileName)==32)
			counter++;
	}while(FindNextFile(d,&entry));
	FindClose(d);
	return counter;
#endif
}

void test_files(booster::shared_ptr<cppcms::sessions::session_storage> storage,
		cppcms::sessions::session_storage_factory &f)
{
	test(storage,f);
	TEST(f.requires_gc());
	time_t now=time(0);
	storage->save(bs+"1",now,"test");
	TEST(count_files()==1);
	storage->remove(bs+"1");
	TEST(count_files()==0);
	storage->save(bs+"1",now-1,"test");
	storage->save(bs+"2",now+1,"test2");
	TEST(count_files()==2);
	f.gc_job();
	TEST(count_files()==1);
	std::string tstr;
	time_t ttime;
	TEST(!storage->load(bs+"1",ttime,tstr));
	TEST(storage->load(bs+"2",ttime,tstr));
	TEST(ttime==now+1 && tstr=="test2");
	storage->save(bs+"2",now-1,"test2");
	TEST(count_files()==1);
	f.gc_job();
	TEST(count_files()==0);
}

int main()
{
	try {

		booster::shared_ptr<cppcms::sessions::session_storage> storage;
		std::auto_ptr<cppcms::sessions::session_storage_factory> storage_factory;
		using namespace cppcms::sessions;

		std::cout << "Testing memory storage" << std::endl;
		session_memory_storage_factory mem;
		storage=mem.get();
		test(storage,mem);
		std::cout << "Testing file storage" << std::endl;
		#ifndef CPPCMS_NO_GZIP
		#ifndef CPPCMS_WIN_NATIVE
		std::cout << "Testing single process" << std::endl;
		session_file_storage_factory f1(dir,5,1,false);
		storage=f1.get();
		test_files(storage,f1);
		std::cout << "Testing multiple process" << std::endl;
		session_file_storage_factory f2(dir,5,5,false);
		storage=f2.get();
		test_files(storage,f2);
		std::cout << "Testing single process over NFS" << std::endl;
		session_file_storage_factory f3(dir,5,1,true);
		storage=f3.get();
		test_files(storage,f3);
		#else
		session_file_storage_factory f(dir);
		storage=f.get();
		test_files(storage,f);
		#endif
        #endif
		#ifndef CPPCMS_NO_TCP_CACHE
		std::cout << "Testing network backend" << std::endl;

		std::vector<std::string> ips;
		ips.push_back("127.0.0.1");
		std::vector<int> ports;
		ports.push_back(8080);
		tcp_factory f4(ips,ports);
		booster::shared_ptr<cppcms::sessions::session_storage_factory>
			mem_ptr(new session_memory_storage_factory());
		cppcms::impl::tcp_cache_service service(0,mem_ptr,1,"127.0.0.1",8080);
		storage=f4.get();
		test(storage,f4);
		service.stop();
		mem_ptr.reset();
		#endif
	}
	catch(std::exception const &e) {
		std::cerr <<"Fail: " << e.what() << std::endl;
		std::cerr << booster::trace(e) << std::endl;
		return 1;
	}
	std::cout << "Ok" << std::endl;
	return 0;
}

max_stars_repo_name: ci-fuzz/cppcms

max_issues_repo_name: ci-fuzz/cppcms

max_forks_repo_name: ci-fuzz/cppcms


text:
// (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
// (C) Copyright 2003-2007 Jonathan Turkanis
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)

// See http://www.boost.org/libs/iostreams for documentation.

#ifndef BOOST_IOSTREAMS_WRITE_HPP_INCLUDED
#define BOOST_IOSTREAMS_WRITE_HPP_INCLUDED

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

#include <boost/config.hpp>  // DEDUCED_TYPENAME, MSVC.
#include <boost/detail/workaround.hpp>
#include <boost/iostreams/categories.hpp>
#include <boost/iostreams/detail/char_traits.hpp>
#include <boost/iostreams/detail/dispatch.hpp>
#include <boost/iostreams/detail/ios.hpp>  // streamsize.
#include <boost/iostreams/detail/streambuf.hpp>
#include <boost/iostreams/detail/wrap_unwrap.hpp>
#include <boost/iostreams/operations_fwd.hpp>
#include <boost/iostreams/traits.hpp>
#include <boost/mpl/if.hpp>

// Must come last.
#include <boost/iostreams/detail/config/disable_warnings.hpp>

#if BOOST_WORKAROUND(BOOST_MSVC, < 1300) //-----------------------------------//
# include <boost/iostreams/detail/vc6/write.hpp>
#else // #if BOOST_WORKAROUND(BOOST_MSVC, < 1300) //--------------------------//

namespace boost { namespace iostreams {

namespace detail {

template<typename T>
struct write_device_impl;

template<typename T>
struct write_filter_impl;

} // End namespace detail.

template<typename T>
bool put(T& t, typename char_type_of<T>::type c)
{ return detail::write_device_impl<T>::put(detail::unwrap(t), c); }

template<typename T>
inline std::streamsize write
    (T& t, const typename char_type_of<T>::type* s, std::streamsize n)
{ return detail::write_device_impl<T>::write(detail::unwrap(t), s, n); }

template<typename T, typename Sink>
inline std::streamsize
write( T& t, Sink& snk, const typename char_type_of<T>::type* s,
       std::streamsize n )
{ return detail::write_filter_impl<T>::write(detail::unwrap(t), snk, s, n); }

namespace detail {

//------------------Definition of write_device_impl---------------------------//

template<typename T>
struct write_device_impl
    : mpl::if_<
          is_custom<T>,
          operations<T>,
          write_device_impl<
              BOOST_DEDUCED_TYPENAME
              dispatch<
                  T, ostream_tag, streambuf_tag, output
              >::type
          >
      >::type
    { };

template<>
struct write_device_impl<ostream_tag> {
    template<typename T>
    static bool put(T& t, typename char_type_of<T>::type c)
    {
        typedef typename char_type_of<T>::type          char_type;
        typedef BOOST_IOSTREAMS_CHAR_TRAITS(char_type)  traits_type;
        return !traits_type::eq_int_type( t.rdbuf()->s.sputc(),
                                          traits_type::eof() );
    }

    template<typename T>
    static std::streamsize write
        (T& t, const typename char_type_of<T>::type* s, std::streamsize n)
    { return t.rdbuf()->sputn(s, n); }
};

template<>
struct write_device_impl<streambuf_tag> {
    template<typename T>
    static bool put(T& t, typename char_type_of<T>::type c)
    {
        typedef typename char_type_of<T>::type          char_type;
        typedef BOOST_IOSTREAMS_CHAR_TRAITS(char_type)  traits_type;
        return !traits_type::eq_int_type(t.sputc(c), traits_type::eof());
    }

    template<typename T>
    static std::streamsize write
        (T& t, const typename char_type_of<T>::type* s, std::streamsize n)
    { return t.sputn(s, n); }
};

template<>
struct write_device_impl<output> {
    template<typename T>
    static bool put(T& t, typename char_type_of<T>::type c)
    { return t.write(&c, 1) == 1; }

    template<typename T>
    static std::streamsize
    write(T& t, const typename char_type_of<T>::type* s, std::streamsize n)
    { return t.write(s, n); }
};

//------------------Definition of write_filter_impl---------------------------//

template<typename T>
struct write_filter_impl
    : mpl::if_<
          is_custom<T>,
          operations<T>,
          write_filter_impl<
              BOOST_DEDUCED_TYPENAME
              dispatch<
                  T, multichar_tag, any_tag
              >::type
          >
      >::type
    { };

template<>
struct write_filter_impl<multichar_tag> {
    template<typename T, typename Sink>
    static std::streamsize
    write( T& t, Sink& snk, const typename char_type_of<T>::type* s,
           std::streamsize n )
    { return t.write(snk, s, n); }
};

template<>
struct write_filter_impl<any_tag> {
    template<typename T, typename Sink>
    static std::streamsize
    write( T& t, Sink& snk, const typename char_type_of<T>::type* s,
           std::streamsize n )
    {
        for (std::streamsize off = 0; off < n; ++off)
            if (!t.put(snk, s[off]))
                return off;
        return n;
    }
};

} // End namespace detail.

} } // End namespaces iostreams, boost.

#endif // #if BOOST_WORKAROUND(BOOST_MSVC, < 1300) //-------------------------//

#include <boost/iostreams/detail/config/enable_warnings.hpp>

#endif // #ifndef BOOST_IOSTREAMS_WRITE_HPP_INCLUDED

ext: hpp

max_stars_repo_name: EricBoittier/vina-carb-docker

max_issues_repo_name: EricBoittier/vina-carb-docker

max_forks_repo_name: EricBoittier/vina-carb-docker


text:
/// DRIVE TO POSE

#include "ros/ros.h"
#include "geometry_msgs/TwistStamped.h"
#include "geometry_msgs/PoseStamped.h"
#include "geometry_msgs/Quaternion.h"
#include "mutex"
#include "kinova_msgs/PoseVelocity.h"
#include "tf/transform_datatypes.h"
#include "angles/angles.h"

#define VEL_LIN_MAX 0.04
#define VEL_ANG_MAX 0.4

//float thresh_lin = 0.01;
//float thresh_ang = 0.05;

//double temp_rol, temp_pit, temp_yaw;
//double goal_rol, goal_pit, goal_yaw;
//double start_rol, start_pit, start_yaw;
//double del_rol, del_pit, del_yaw;

//std::string result;
//std::mutex lock_pose;
//std::mutex lock_status;
//std::mutex lock_proc;
//std::mutex lock_force;
//double force_f, force_b;
//bool processing=false;
//ros::Publisher cmd_pos;
//ros::Publisher cmd_vel;

#include "ros/ros.h"
#include "std_msgs/String.h"
#include "geometry_msgs/PoseStamped.h"
#include "mutex"
#include "angles/angles.h"
#include "std_msgs/Int32.h"

#include "geometry_msgs/Vector3.h"
#include "geometry_msgs/Quaternion.h"
#include "tf/transform_datatypes.h"
#include "tf/transform_listener.h"

#include <hri_package/Sens_Force.h>
#include <kinova_msgs/PoseVelocity.h>

#include <fstream>
#include <vector>
#include <iterator>
#include <string>
#include <algorithm>
#include <boost/algorithm/string.hpp>

#define ARC_DOWN 1
#define ARC_UP 2
#define TRANSLATE_BACK 3
#define RAISE_CUP 4
#define LOWER_CUP 5
#define TRANSLATE_UP 6
#define TRANSLATE_DOWN 7
#define TRANSLATE_FRONT 8
#define END_EFF_FRAME "j2s7s300_end_effector"
#define BASE_FRAME "j2s7s300_link_base"
#define SENSOR_FRAME "forcesensor"
#define FORCE_F_1_2_THRESH 0.2
#define FORCE_F_2_3_THRESH 1.0
#define ROTATION_STEP 10
#define MAX_STEPS 200
#define VEL_LIN_MAX 0.04
#define VEL_ANG_MAX 0.4
#define VEL_CMD_DURATION 0.8
#define UPPER_FEED_ANGLE_THRESH 140 // was 140

#define ACTION_DOWN 0
#define ACTION_STAY 1
#define ACTION_UP 2

double lower_angle_thresh = 85;
float thresh_lin = 0.01;
float thresh_ang = 0.05;

int step_count;

std::string result;
std::mutex lock_pose;
std::mutex lock_status;
std::mutex lock_proc;
std::mutex lock_force;
double force_f, force_b;
bool processing=false;
ros::Publisher cmd_pos;
ros::Publisher cmd_vel;
ros::Publisher pub_kinova_vel;

geometry_msgs::PoseStamped current_pose, start_pose, goal_pose;
std::mutex pose_lock;

void getRPYFromQuaternionMSG(geometry_msgs::Quaternion orientation, double& roll,double& pitch, double& yaw)
{
  tf::Quaternion quat;
  tf::quaternionMsgToTF(orientation,quat);
  quat.normalize();
  tf::Matrix3x3 mat(quat);
  mat.getRPY(roll, pitch,yaw);

  //ROS_INFO_STREAM("Quaternion is : " << quat.x() << " " << quat.y() << " " << quat.z() << " " << quat.w());
  //ROS_INFO_STREAM("Converted R: " << roll << " P: " << pitch << " Y: " << yaw);
}

void poseGrabber(geometry_msgs::PoseStamped pose)
{
  pose_lock.lock();
  current_pose = pose;
  pose_lock.unlock();
  //ROS_INFO_STREAM("Got current pose as x=" << pose << " saved as " << current_pose);
}

void publishTwistForDuration(geometry_msgs::TwistStamped twist_msg, double duration)
{
  ros::Time time_start = ros::Time::now();
  while (ros::Time::now() - time_start < ros::Duration(duration))
  {
    ros::spinOnce();
    cmd_vel.publish(twist_msg);
  }
}

void driveToRollGoalWithVelocity(int direction)
{
  if(direction == RAISE_CUP)
    ROS_INFO_STREAM("Raise cup");
  else if (direction == LOWER_CUP)
    ROS_INFO_STREAM("Lower cup");
  else
  {
    ROS_ERROR_STREAM("Wrong direction given!!");
    return;
  }

  geometry_msgs::PoseStamped start_pose, goal_pose, temp_pose;

  lock_pose.lock();
  start_pose=current_pose;
  lock_pose.unlock();

  double temp_rol, temp_pit, temp_yaw;
  double goal_rol, goal_pit, goal_yaw;
  double start_rol, start_pit, start_yaw;
  double del_rol;

  goal_pose = start_pose;

  tf::Quaternion q_rot = tf::createQuaternionFromRPY(angles::from_degrees( direction==RAISE_CUP?ROTATION_STEP:-ROTATION_STEP),angles::from_degrees(0),angles::from_degrees(0)); // Rotate about x by 20 degrees
  tf::Quaternion q_start; tf::quaternionMsgToTF(start_pose.pose.orientation, q_start);
  tf::Quaternion q_goal = q_start*q_rot;

  tf::quaternionTFToMsg(q_goal,goal_pose.pose.orientation);

  ros::Rate loop_rate(100);
  //ros::Time start = ros::Time::now();
  while(ros::ok())
  {
    ros::spinOnce();
    lock_pose.lock();
    temp_pose = current_pose;
    lock_pose.unlock();

    getRPYFromQuaternionMSG(goal_pose.pose.orientation, goal_rol, goal_pit, goal_yaw);
    getRPYFromQuaternionMSG(temp_pose.pose.orientation, temp_rol, temp_pit, temp_yaw);
    getRPYFromQuaternionMSG(start_pose.pose.orientation, start_rol, start_pit, start_yaw);

    if (goal_rol < 0 ) goal_rol = goal_rol + angles::from_degrees(360);
    if (temp_rol < 0 ) temp_rol = temp_rol + angles::from_degrees(360);

    del_rol = goal_rol - temp_rol;

    if (std::fabs(del_rol)>=thresh_ang)
    {
      geometry_msgs::TwistStamped twist_msg;
      twist_msg.twist.linear.x = 0;
      twist_msg.twist.linear.y = 0;
      twist_msg.twist.linear.z = 0;
      twist_msg.twist.angular.x= del_rol>0?VEL_ANG_MAX:-VEL_ANG_MAX;
      twist_msg.twist.angular.y = 0;
      twist_msg.twist.angular.z= 0;

      ROS_INFO_STREAM("goal_rol: " << angles::to_degrees(goal_rol) << " temp_rol : " << angles::to_degrees(temp_rol) << " del_rol: " << del_rol);
      cmd_vel.publish(twist_msg);
    }
    else
    {
      //ROS_INFO_STREAM("Roll: " << angles::to_degrees(temp_rol)  << " Delta: " << del_rol << " Goal reached, breaking loop");
      break;
    }

    ros::spinOnce();
    loop_rate.sleep();
  }

}

void printRoll(std::string text)
{
  ros::spinOnce();
  lock_pose.lock();
  geometry_msgs::PoseStamped initial_pose=current_pose;
  lock_pose.unlock();

  double r,p,y;
  getRPYFromQuaternionMSG(initial_pose.pose.orientation,r,p,y);
  lower_angle_thresh = r;
  ROS_INFO_STREAM(text << angles::to_degrees(lower_angle_thresh));
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "velocity_drive");
  ros::NodeHandle nh;

  //ros::Publisher cmd_vel = nh.advertise<geometry_msgs::TwistStamped>("/RobotControl/VelocityControl", 1000);
  cmd_vel = nh.advertise<geometry_msgs::TwistStamped>("/RobotControl/VelocityControl", 1000);
  pub_kinova_vel = nh.advertise<kinova_msgs::PoseVelocity>("/j2s7s300_driver/in/cartesian_velocity", 1000);
  ros::Subscriber tool_pose = nh.subscribe("/j2s7s300_driver/out/tool_pose",1000, poseGrabber );

  ros::Rate loop_rate(100);
  geometry_msgs::PoseStamped temp_pose;

  geometry_msgs::TwistStamped vel_msg;

  // This loop to wait until subscriber starts returning valid poses.
  while(ros::ok())
  {
    pose_lock.lock();
    temp_pose = current_pose;
    pose_lock.unlock();
    ros::spinOnce();
    loop_rate.sleep();
    if (temp_pose.pose.position.x > 0) break;
  }

  ROS_INFO("Valid pose available");

//  for (int i =0; i<5; i++)

//  {
//    printRoll("Roll before change ");

//    driveToRollGoalWithVelocity(RAISE_CUP);

//    printRoll("Roll after change, pre pause ");
//    sleep(0.7);
//    printRoll("Roll after change, post pause ");
//    ROS_INFO("----------------------");

//    printRoll("Roll before change");

//    driveToRollGoalWithVelocity(LOWER_CUP);

//    //printRoll("Roll after change, pre pause ");
//    sleep(0.7);
//    printRoll("Roll after change, post pause ");
//    ROS_INFO("----------------------");
//  }

  printRoll("Roll before change ");
  driveToRollGoalWithVelocity(RAISE_CUP);
  printRoll("Roll after change, pre pause ");
  sleep(1.0);
  printRoll("Roll after change, post pause ");

  ros::spinOnce();
  return 0;
}

max_stars_repo_name: Tejas-Shastha/tejas

max_issues_repo_name: Tejas-Shastha/tejas

max_forks_repo_name: Tejas-Shastha/tejas


text:
// Copyright John Maddock 2006.
// Copyright Paul A. Bristow 2007, 2010.

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

// test_gamma_dist.cpp

// http://en.wikipedia.org/wiki/Gamma_distribution
// http://www.itl.nist.gov/div898/handbook/eda/section3/eda366b.htm
// Also:
// Weisstein, Eric W. "Gamma Distribution."
// From MathWorld--A Wolfram Web Resource.
// http://mathworld.wolfram.com/GammaDistribution.html

#include <pch.hpp> // include directory libs/math/src/tr1/ is needed.

#include <boost/math/concepts/real_concept.hpp> // for real_concept
#include <boost/test/test_exec_monitor.hpp> // Boost.Test
#include <boost/test/floating_point_comparison.hpp>

#include <boost/math/distributions/gamma.hpp>
    using boost::math::gamma_distribution;
#include <boost/math/tools/test.hpp>

#include <iostream>
   using std::cout;
   using std::endl;
   using std::setprecision;
#include <limits>
  using std::numeric_limits;

template <class RealType>
RealType NaivePDF(RealType shape, RealType scale, RealType x)
{
   // Deliberately naive PDF calculator again which
   // we'll compare our pdf function.  However some
   // published values to compare against would be better....
   using namespace std;
   RealType result = log(x) * (shape - 1) - x / scale - boost::math::lgamma(shape) - log(scale) * shape;
   return exp(result);
}

template <class RealType>
void check_gamma(RealType shape, RealType scale, RealType x, RealType p, RealType q, RealType tol)
{
   BOOST_CHECK_CLOSE(
      ::boost::math::cdf(
         gamma_distribution<RealType>(shape, scale),    // distribution.
         x),                                            // random variable.
         p,                                             // probability.
         tol);                                          // %tolerance.
   BOOST_CHECK_CLOSE(
      ::boost::math::cdf(
         complement(
            gamma_distribution<RealType>(shape, scale), // distribution.
            x)),                                        // random variable.
         q,                                             // probability complement.
         tol);                                          // %tolerance.
   if(p < 0.999)
   {
      BOOST_CHECK_CLOSE(
         ::boost::math::quantile(
            gamma_distribution<RealType>(shape, scale),    // distribution.
            p),                                            // probability.
            x,                                             // random variable.
            tol);                                          // %tolerance.
   }
   if(q < 0.999)
   {
      BOOST_CHECK_CLOSE(
         ::boost::math::quantile(
            complement(
               gamma_distribution<RealType>(shape, scale), // distribution.
               q)),                                        // probability complement.
            x,                                             // random variable.
            tol);                                          // %tolerance.
   }
   // PDF:
   BOOST_CHECK_CLOSE(
      boost::math::pdf(
         gamma_distribution<RealType>(shape, scale),    // distribution.
         x),                                            // random variable.
         NaivePDF(shape, scale, x),                     // PDF
         tol);                                          // %tolerance.
}

template <class RealType>
void test_spots(RealType)
{
   // Basic sanity checks
   //
   // 15 decimal places expressed as a persentage.
   // The first tests use values generated by MathCAD,
   // and should be accurate to around double precision.
   //
   RealType tolerance = (std::max)(RealType(5e-14f), std::numeric_limits<RealType>::epsilon() * 20) * 100;
   cout << "Tolerance for type " << typeid(RealType).name()  << " is " << tolerance << " %" << endl;

   check_gamma(
      static_cast<RealType>(0.5),
      static_cast<RealType>(1),
      static_cast<RealType>(0.5),
      static_cast<RealType>(0.682689492137085),
      static_cast<RealType>(1-0.682689492137085),
      tolerance);
   check_gamma(
      static_cast<RealType>(2),
      static_cast<RealType>(1),
      static_cast<RealType>(0.5),
      static_cast<RealType>(0.090204010431050),
      static_cast<RealType>(1-0.090204010431050),
      tolerance);
   check_gamma(
      static_cast<RealType>(40),
      static_cast<RealType>(1),
      static_cast<RealType>(10),
      static_cast<RealType>(7.34163631456064E-13),
      static_cast<RealType>(1-7.34163631456064E-13),
      tolerance);

   //
   // Some more test data generated by the online
   // calculator at http://espse.ed.psu.edu/edpsych/faculty/rhale/hale/507Mat/statlets/free/pdist.htm
   // This has the advantage of supporting the scale parameter as well
   // as shape, but has only a few digits accuracy, and produces
   // some deeply suspect values if the shape parameter is < 1
   // (it doesn't agree with MathCAD or this implementation).
   // To be fair the incomplete gamma is tricky to get right in this area...
   //
   tolerance = 1e-5f * 100; // 5 decimal places as a persentage
   cout << "Tolerance for type " << typeid(RealType).name()  << " is " << tolerance << " %" << endl;

   check_gamma(
      static_cast<RealType>(2),
      static_cast<RealType>(1)/5,
      static_cast<RealType>(0.1),
      static_cast<RealType>(0.090204),
      static_cast<RealType>(1-0.090204),
      tolerance);
   check_gamma(
      static_cast<RealType>(2),
      static_cast<RealType>(1)/5,
      static_cast<RealType>(0.5),
      static_cast<RealType>(1-0.287298),
      static_cast<RealType>(0.287298),
      tolerance);
   check_gamma(
      static_cast<RealType>(3),
      static_cast<RealType>(2),
      static_cast<RealType>(1),
      static_cast<RealType>(0.014388),
      static_cast<RealType>(1-0.014388),
      tolerance * 10); // one less decimal place in the test value
   check_gamma(
      static_cast<RealType>(3),
      static_cast<RealType>(2),
      static_cast<RealType>(5),
      static_cast<RealType>(0.456187),
      static_cast<RealType>(1-0.456187),
      tolerance);

    RealType tol2 = boost::math::tools::epsilon<RealType>() * 5 * 100;  // 5 eps as a persentage
    gamma_distribution<RealType> dist(8, 3);
    RealType x = static_cast<RealType>(0.125);
    using namespace std; // ADL of std names.
    // mean:
    BOOST_CHECK_CLOSE(
       mean(dist)
       , static_cast<RealType>(8*3), tol2);
    // variance:
    BOOST_CHECK_CLOSE(
       variance(dist)
       , static_cast<RealType>(8*3*3), tol2);
    // std deviation:
    BOOST_CHECK_CLOSE(
       standard_deviation(dist)
       , sqrt(static_cast<RealType>(8*3*3)), tol2);
    // hazard:
    BOOST_CHECK_CLOSE(
       hazard(dist, x)
       , pdf(dist, x) / cdf(complement(dist, x)), tol2);
    // cumulative hazard:
    BOOST_CHECK_CLOSE(
       chf(dist, x)
       , -log(cdf(complement(dist, x))), tol2);
    // coefficient_of_variation:
    BOOST_CHECK_CLOSE(
       coefficient_of_variation(dist)
       , standard_deviation(dist) / mean(dist), tol2);
    // mode:
    BOOST_CHECK_CLOSE(
       mode(dist)
       , static_cast<RealType>(7 * 3), tol2);
    // skewness:
    BOOST_CHECK_CLOSE(
       skewness(dist)
       , 2 / sqrt(static_cast<RealType>(8)), tol2);
    // kertosis:
    BOOST_CHECK_CLOSE(
       kurtosis(dist)
       , 3 + 6 / static_cast<RealType>(8), tol2);
    // kertosis excess:
    BOOST_CHECK_CLOSE(
       kurtosis_excess(dist)
       , 6 / static_cast<RealType>(8), tol2);

    BOOST_CHECK_CLOSE(
       median(dist), static_cast<RealType>(23.007748327502412), // double precision test value
       (std::max)(tol2, static_cast<RealType>(std::numeric_limits<double>::epsilon() * 2 * 100))); // 2 eps as persent
    // Rely on default definition in derived accessors.

} // template <class RealType>void test_spots(RealType)

int test_main(int, char* [])
{
   // Basic sanity-check spot values.
   // (Parameter value, arbitrarily zero, only communicates the floating point type).
  test_spots(0.0F); // Test float. OK at decdigits = 0 tolerance = 0.0001 %
  test_spots(0.0); // Test double. OK at decdigits 7, tolerance = 1e07 %
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
  test_spots(0.0L); // Test long double.
#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS
  test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.
#endif
#else
   std::cout << "<note>The long double tests have been disabled on this platform "
      "either because the long double overloads of the usual math functions are "
      "not available at all, or because they are too inaccurate for these tests "
      "to pass.</note>" << std::cout;
#endif

   return 0;
} // int test_main(int, char* [])

/*

Output:

Autorun "i:\boost-06-05-03-1300\libs\math\test\Math_test\debug\test_gamma_dist.exe"
Running 1 test case...
Tolerance for type float is 0.000238419 %
Tolerance for type float is 0.001 %
Tolerance for type double is 5e-012 %
Tolerance for type double is 0.001 %
Tolerance for type long double is 5e-012 %
Tolerance for type long double is 0.001 %
Tolerance for type class boost::math::concepts::real_concept is 5e-012 %
Tolerance for type class boost::math::concepts::real_concept is 0.001 %
*** No errors detected

*/

max_stars_repo_name: boostpro/boost-release

max_issues_repo_name: boostpro/boost-release

max_forks_repo_name: boostpro/boost-release


text:
/*
 * @Author: Han
 * @Date: 2018-05-05 20:49:29
 * 相机信息
 */
#include <base/camera.h>

#include <Eigen/Geometry>

namespace h2o {
FrameCamera::FrameCamera() {
    cid_ = INVALID_INDEX;
    iid_ = INVALID_INDEX;
    size_ = Vector2i(-1, -1);
    K = Matrix3d::Zero();
    R = Matrix3d::Zero();
    C = Vector3d::Zero();
    P = Matrix34d::Zero();
}
FrameCamera::FrameCamera(uint32_t cid, uint32_t iid, int width, int height, double delta, double f, double x0,
                         double y0, const Vector3d &r, const Vector3d &X) {
    cid_ = cid;
    iid_ = iid;
    size_(0) = width;
    size_(1) = height;

    K(0, 0) = f / delta;
    K(1, 1) = f / delta;
    double u0 = (width - 1) / 2.0 + x0 / delta;
    double v0 = (height - 1) / 2.0 - y0 / delta;

    K(0, 1) = 0.0;
    K(0, 2) = u0;

    K(1, 0) = 0.0;
    K(1, 2) = v0;

    K(2, 0) = 0.0;
    K(2, 1) = 0.0;
    K(2, 2) = 1.0;

    double angle = r.norm();
    Vector3d axis = r.normalized();
    Matrix3d Rpg = Eigen::AngleAxisd(angle, axis).toRotationMatrix();
    Matrix3d R_x = Eigen::AngleAxisd(M_PI, Vector3d::UnitX()).toRotationMatrix();
    R = Rpg * R_x;
    R.transposeInPlace();

    C = X;
    Vector3d t = -R * C;
    P << R, t;
    P = K * P;
}
FrameCamera::~FrameCamera() {}
} // namespace h2o