text:
//
// Copyright 2008 Christian Henning
//
// 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
//
#ifndef BOOST_GIL_EXTENSION_IO_BMP_DETAIL_SCANLINE_READ_HPP
#define BOOST_GIL_EXTENSION_IO_BMP_DETAIL_SCANLINE_READ_HPP

#include <boost/gil/extension/io/bmp/detail/is_allowed.hpp>
#include <boost/gil/extension/io/bmp/detail/reader_backend.hpp>

#include <boost/gil/io/base.hpp>
#include <boost/gil/io/bit_operations.hpp>
#include <boost/gil/io/conversion_policies.hpp>
#include <boost/gil/io/device.hpp>
#include <boost/gil/io/reader_base.hpp>
#include <boost/gil/io/row_buffer_helper.hpp>
#include <boost/gil/io/scanline_read_iterator.hpp>
#include <boost/gil/io/typedefs.hpp>

#include <functional>
#include <type_traits>
#include <vector>

namespace boost {
namespace gil {

///
/// BMP Scanline Reader
///
template <typename Device>
class scanline_reader<Device, bmp_tag>
    : public reader_backend<Device, bmp_tag> {
public:
  using tag_t = bmp_tag;
  using backend_t = reader_backend<Device, tag_t>;
  using this_t = scanline_reader<Device, tag_t>;
  using iterator_t = scanline_read_iterator<this_t>;

public:
  //
  // Constructor
  //
  scanline_reader(Device &device, const image_read_settings<bmp_tag> &settings)
      : backend_t(device, settings)

        ,
        _pitch(0) {
    initialize();
  }

  /// Read part of image defined by View and return the data.
  void read(byte_t *dst, int pos) {
    // jump to scanline
    long offset = 0;

    if (this->_info._height > 0) {
      // the image is upside down
      offset =
          this->_info._offset + (this->_info._height - 1 - pos) * this->_pitch;
    } else {
      offset = this->_info._offset + pos * _pitch;
    }

    this->_io_dev.seek(offset);

    // read data
    _read_function(this, dst);
  }

  /// Skip over a scanline.
  void skip(byte_t *, int) {
    // nothing to do.
  }

  iterator_t begin() { return iterator_t(*this); }
  iterator_t end() { return iterator_t(*this, this->_info._height); }

private:
  void initialize() {
    if (this->_info._bits_per_pixel < 8) {
      _pitch = ((this->_info._width * this->_info._bits_per_pixel) + 7) >> 3;
    } else {
      _pitch = this->_info._width * ((this->_info._bits_per_pixel + 7) >> 3);
    }

    _pitch = (_pitch + 3) & ~3;

    //

    switch (this->_info._bits_per_pixel) {
    case 1: {
      this->_scanline_length =
          (this->_info._width * num_channels<rgba8_view_t>::value + 3) & ~3;

      read_palette();
      _buffer.resize(_pitch);

      _read_function = std::mem_fn(&this_t::read_1_bit_row);

      break;
    }

    case 4: {
      switch (this->_info._compression) {
      case bmp_compression::_rle4: {
        io_error("Cannot read run-length encoded images in iterator mode. Try "
                 "to read as whole image.");

        break;
      }

      case bmp_compression::_rgb: {
        this->_scanline_length =
            (this->_info._width * num_channels<rgba8_view_t>::value + 3) & ~3;

        read_palette();
        _buffer.resize(_pitch);

        _read_function = std::mem_fn(&this_t::read_4_bits_row);

        break;
      }

      default: {
        io_error("Unsupported compression mode in BMP file.");
      }
      }

      break;
    }

    case 8: {
      switch (this->_info._compression) {
      case bmp_compression::_rle8: {
        io_error("Cannot read run-length encoded images in iterator mode. Try "
                 "to read as whole image.");

        break;
      }
      case bmp_compression::_rgb: {
        this->_scanline_length =
            (this->_info._width * num_channels<rgba8_view_t>::value + 3) & ~3;

        read_palette();
        _buffer.resize(_pitch);

        _read_function = std::mem_fn(&this_t::read_8_bits_row);

        break;
      }

      default: {
        io_error("Unsupported compression mode in BMP file.");
        break;
      }
      }

      break;
    }

    case 15:
    case 16: {
      this->_scanline_length =
          (this->_info._width * num_channels<rgb8_view_t>::value + 3) & ~3;

      _buffer.resize(_pitch);

      if (this->_info._compression == bmp_compression::_bitfield) {
        this->_mask.red.mask = this->_io_dev.read_uint32();
        this->_mask.green.mask = this->_io_dev.read_uint32();
        this->_mask.blue.mask = this->_io_dev.read_uint32();

        this->_mask.red.width = detail::count_ones(this->_mask.red.mask);
        this->_mask.green.width = detail::count_ones(this->_mask.green.mask);
        this->_mask.blue.width = detail::count_ones(this->_mask.blue.mask);

        this->_mask.red.shift = detail::trailing_zeros(this->_mask.red.mask);
        this->_mask.green.shift =
            detail::trailing_zeros(this->_mask.green.mask);
        this->_mask.blue.shift = detail::trailing_zeros(this->_mask.blue.mask);
      } else if (this->_info._compression == bmp_compression::_rgb) {
        switch (this->_info._bits_per_pixel) {
        case 15:
        case 16: {
          this->_mask.red.mask = 0x007C00;
          this->_mask.red.width = 5;
          this->_mask.red.shift = 10;
          this->_mask.green.mask = 0x0003E0;
          this->_mask.green.width = 5;
          this->_mask.green.shift = 5;
          this->_mask.blue.mask = 0x00001F;
          this->_mask.blue.width = 5;
          this->_mask.blue.shift = 0;

          break;
        }

        case 24:
        case 32: {
          this->_mask.red.mask = 0xFF0000;
          this->_mask.red.width = 8;
          this->_mask.red.shift = 16;
          this->_mask.green.mask = 0x00FF00;
          this->_mask.green.width = 8;
          this->_mask.green.shift = 8;
          this->_mask.blue.mask = 0x0000FF;
          this->_mask.blue.width = 8;
          this->_mask.blue.shift = 0;

          break;
        }
        }
      } else {
        io_error("Unsupported BMP compression.");
      }

      _read_function = std::mem_fn(&this_t::read_15_bits_row);

      break;
    }

    case 24: {
      this->_scanline_length =
          (this->_info._width * num_channels<rgb8_view_t>::value + 3) & ~3;
      _read_function = std::mem_fn(&this_t::read_row);

      break;
    }

    case 32: {
      this->_scanline_length =
          (this->_info._width * num_channels<rgba8_view_t>::value + 3) & ~3;
      _read_function = std::mem_fn(&this_t::read_row);

      break;
    }

    default: {
      io_error("Unsupported bits per pixel.");
    }
    }
  }

  void read_palette() {
    if (this->_palette.size() > 0) {
      // palette has been read already.
      return;
    }

    int entries = this->_info._num_colors;

    if (entries == 0) {
      entries = 1u << this->_info._bits_per_pixel;
    }

    this->_palette.resize(entries, rgba8_pixel_t(0, 0, 0, 0));

    for (int i = 0; i < entries; ++i) {
      get_color(this->_palette[i], blue_t()) = this->_io_dev.read_uint8();
      get_color(this->_palette[i], green_t()) = this->_io_dev.read_uint8();
      get_color(this->_palette[i], red_t()) = this->_io_dev.read_uint8();

      // there are 4 entries when windows header
      // but 3 for os2 header
      if (this->_info._header_size == bmp_header_size::_win32_info_size) {
        this->_io_dev.read_uint8();
      }

    } // for
  }

  template <typename View> void read_bit_row(byte_t *dst) {
    using src_view_t = View;
    using dst_view_t = rgba8_image_t::view_t;

    src_view_t src_view = interleaved_view(
        this->_info._width, 1,
        (typename src_view_t::x_iterator) & _buffer.front(), this->_pitch);

    dst_view_t dst_view = interleaved_view(
        this->_info._width, 1, (typename dst_view_t::value_type *)dst,
        num_channels<dst_view_t>::value * this->_info._width);

    typename src_view_t::x_iterator src_it = src_view.row_begin(0);
    typename dst_view_t::x_iterator dst_it = dst_view.row_begin(0);

    for (dst_view_t::x_coord_t i = 0; i < this->_info._width;
         ++i, src_it++, dst_it++) {
      unsigned char c = get_color(*src_it, gray_color_t());
      *dst_it = this->_palette[c];
    }
  }

  // Read 1 bit image. The colors are encoded by an index.
  void read_1_bit_row(byte_t *dst) {
    this->_io_dev.read(&_buffer.front(), _pitch);
    _mirror_bits(_buffer);

    read_bit_row<gray1_image_t::view_t>(dst);
  }

  // Read 4 bits image. The colors are encoded by an index.
  void read_4_bits_row(byte_t *dst) {
    this->_io_dev.read(&_buffer.front(), _pitch);
    _swap_half_bytes(_buffer);

    read_bit_row<gray4_image_t::view_t>(dst);
  }

  /// Read 8 bits image. The colors are encoded by an index.
  void read_8_bits_row(byte_t *dst) {
    this->_io_dev.read(&_buffer.front(), _pitch);

    read_bit_row<gray8_image_t::view_t>(dst);
  }

  /// Read 15 or 16 bits image.
  void read_15_bits_row(byte_t *dst) {
    using dst_view_t = rgb8_view_t;

    dst_view_t dst_view =
        interleaved_view(this->_info._width, 1,
                         (typename dst_view_t::value_type *)dst, this->_pitch);

    typename dst_view_t::x_iterator dst_it = dst_view.row_begin(0);

    //
    byte_t *src = &_buffer.front();
    this->_io_dev.read(src, _pitch);

    for (dst_view_t::x_coord_t i = 0; i < this->_info._width; ++i, src += 2) {
      int p = (src[1] << 8) | src[0];

      int r = ((p & this->_mask.red.mask) >> this->_mask.red.shift)
              << (8 - this->_mask.red.width);
      int g = ((p & this->_mask.green.mask) >> this->_mask.green.shift)
              << (8 - this->_mask.green.width);
      int b = ((p & this->_mask.blue.mask) >> this->_mask.blue.shift)
              << (8 - this->_mask.blue.width);

      get_color(dst_it[i], red_t()) = static_cast<byte_t>(r);
      get_color(dst_it[i], green_t()) = static_cast<byte_t>(g);
      get_color(dst_it[i], blue_t()) = static_cast<byte_t>(b);
    }
  }

  void read_row(byte_t *dst) { this->_io_dev.read(dst, _pitch); }

private:
  // the row pitch must be multiple of 4 bytes
  int _pitch;

  std::vector<byte_t> _buffer;
  detail::mirror_bits<std::vector<byte_t>, std::true_type> _mirror_bits;
  detail::swap_half_bytes<std::vector<byte_t>, std::true_type> _swap_half_bytes;

  std::function<void(this_t *, byte_t *)> _read_function;
};

} // namespace gil
} // namespace boost

#endif

ext: hpp

max_stars_repo_name: sdebionne/gil-reformated

max_issues_repo_name: sdebionne/gil-reformated

max_forks_repo_name: sdebionne/gil-reformated


text:
#include "PID_3DOF.h"
#include <Eigen/Dense>
using Eigen::Matrix;
//Sets initial errors to zero
void initializePID(PID_3DOF* PID){
	Matrix<float, 3, 1> zeros = Matrix<float, 3, 1>::Zero(3, 1);

	PID->e_prop = zeros;
	PID->e_deriv = zeros;
	PID->e_integ = zeros;
}

//Sets integral error to zero
void resetIntegralErrorPID(PID_3DOF* PID){
	PID->e_integ = Matrix<float, 3, 1>::Zero(3, 1);
}

//Update Kp, Ki and Kd in the PID
void updateControlParamPID(PID_3DOF* PID, Matrix<float, 3, 1> K_p, Matrix<float, 3, 1> K_i, Matrix<float, 3, 1> K_d, Matrix<float, 3, 1> maxInteg){
	PID->K_p = K_p;
	PID->K_d = K_d;
	PID->K_i = K_i;
	PID->maxInteg = maxInteg;
}

//Update all errors
void updateErrorPID(PID_3DOF* PID, Matrix<float, 3, 1> feedForward, Matrix<float, 3, 1> e_prop, Matrix<float, 3, 1> e_deriv, float dt){

	PID->feedForward = feedForward;
	PID->e_prop = e_prop;
	PID->e_deriv = e_deriv;
	PID->e_integ = PID->e_integ+(e_prop*dt); //e_integ = e_integ + e_prop*dt

	//Saturate integral error
	for (int i = 0; i < 3; i++){
		if (PID->e_integ(i) > PID->maxInteg(i)){
			PID->e_integ(i) = PID->maxInteg(i);
		}
		else if (PID->e_integ(i) < -PID->maxInteg(i)){
			PID->e_integ(i) = -PID->maxInteg(i);
		}
	}
}

//Calculate output of PID
Matrix<float, 3, 1> outputPID(PID_3DOF PID){
	Matrix<float, 3, 1> PID_out;
	PID_out =  PID.feedForward +
				PID.e_prop.cwiseProduct(PID.K_p) +
				PID.e_deriv.cwiseProduct(PID.K_d) +
				PID.e_integ.cwiseProduct(PID.K_i);
	return PID_out;
}

//Helper functions to parse the config file
void split(const string &s, char delim, vector<string> &elems) {
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
}

vector<string> split(const string &s, char delim) {
    vector<string> elems;
    split(s, delim, elems);
    return elems;
}

void updatePar(PID_3DOF *PID_att, PID_3DOF *PID_angVel, PID_3DOF *PID_pos,char const *AttFile,char const *PosFile) {
	Matrix<float, 3, 1> Zero_3x1 = Matrix<float, 3, 1>::Zero(3, 1);
	Matrix<float, 3, 1> KP_RPY = Zero_3x1, KD_RPY = Zero_3x1, KI_RPY = Zero_3x1, maxInteg_RPY = Zero_3x1;
	Matrix<float, 3, 1> KP_w = Zero_3x1, KD_w = Zero_3x1, KI_w = Zero_3x1, maxInteg_w = Zero_3x1;
	Matrix<float, 3, 1> KP_Pos = Zero_3x1, KD_Pos = Zero_3x1, KI_Pos = Zero_3x1, maxInteg_Pos = Zero_3x1;
	char AttParamPath[64];
	char PosParamPath[64];
    string line;
    vector<string> line_vec;

    sprintf(AttParamPath,"/home/root/%s",AttFile);
    sprintf(PosParamPath,"/home/root/%s",PosFile);

    // printf("%s\n",AttParamPath);

    //Get parameters for attitude controller
    ifstream myfile (AttParamPath);
    if (myfile.is_open()) {
		while (getline (myfile ,line)) {
		    line_vec = split(line, ' ');
		    if (line_vec[0] == "KP_R") {
	            KP_RPY(0) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KP_P") {
				KP_RPY(1) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KP_Y") {
				KP_RPY(2) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KD_R") {
	            	KD_RPY(0) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KD_P") {
				KD_RPY(1) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KD_Y") {
				KD_RPY(2) = atof(line_vec[2].c_str());
		    }
		    if (line_vec[0] == "KI_R") {
	            KI_RPY(0) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KI_P") {
				KI_RPY(1) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KI_Y") {
				KI_RPY(2) = atof(line_vec[2].c_str());
		    }
		    if (line_vec[0] == "maxInteg_R") {
	            maxInteg_RPY(0) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "maxInteg_P") {
				maxInteg_RPY(1) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "maxInteg_Y") {
				maxInteg_RPY(2) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KP_wx") {
				KP_w(0) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KP_wy") {
				KP_w(1) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KP_wz") {
		        KP_w(2)  = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KD_wx") {
				KD_w(0) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KD_wy") {
				KD_w(1) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KD_wz") {
		        KD_w(2) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KI_wx") {
				KI_w(0) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KI_wy") {
				KI_w(1) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KI_wz") {
		        KI_w(2) = atof(line_vec[2].c_str());
		    }
		    if (line_vec[0] == "maxInteg_wx") {
	            maxInteg_w(0) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "maxInteg_wy") {
				maxInteg_w(1) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "maxInteg_wz") {
				maxInteg_w(2) = atof(line_vec[2].c_str());
		    }
		}
		myfile.close();
		updateControlParamPID(PID_att, KP_RPY, KI_RPY, KD_RPY, maxInteg_RPY);
		updateControlParamPID(PID_angVel, KP_w, KI_w, KD_w, maxInteg_w);
    }
    else {
		printf("Unable to open file %s \n",AttParamPath);
    }

    //Get parameters for position controller
    ifstream myfile2 (PosParamPath);
    if (myfile2.is_open()) {
		while (getline (myfile2 ,line)) {
		    line_vec = split(line, ' ');
		    if (line_vec[0] == "KP_X") {
	            KP_Pos(0) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KP_Y") {
				KP_Pos(1) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KP_Z") {
				KP_Pos(2) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KD_X") {
	            KD_Pos(0) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KD_Y") {
				KD_Pos(1) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KD_Z") {
				KD_Pos(2) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KI_X") {
	            KI_Pos(0) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KI_Y") {
				KI_Pos(1) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "KI_Z") {
				KI_Pos(2) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "maxInteg_X") {
	            maxInteg_Pos(0) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "maxInteg_Y") {
				maxInteg_Pos(1) = atof(line_vec[2].c_str());
		    }
		    else if (line_vec[0] == "maxInteg_Z") {
				maxInteg_Pos(2) = atof(line_vec[2].c_str());
		    }
		}
		myfile2.close();
		updateControlParamPID(PID_pos, KP_Pos, KI_Pos, KD_Pos, maxInteg_Pos);
    }
    else {
		printf("Unable to open file %s \n", PosParamPath);
    }

	printf("Done updating control parameters\n");
}

ext: cpp

max_stars_repo_name: khairulislam/phys

max_issues_repo_name: khairulislam/phys

max_forks_repo_name: khairulislam/phys


text:
/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2015 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   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.
*/

#include <QApplication>
#include <QMessageBox>
#include <Interface/Application/GuiApplication.h>
#include <Interface/Application/MainWindowCollaborators.h>
#include <Core/Logging/Log.h>
#include <boost/make_shared.hpp>
#include <iostream>

using namespace SCIRun::Gui;

int GuiApplication::run(int argc, const char* argv[])
{
  QApplication app(argc, const_cast<char**>(argv));

  try
  {
    SCIRunGuiRunner gui(app);
    return gui.returnCode();
  }
  catch (std::exception& e)
  {
    QMessageBox::critical(0, "Critical error", "Unhandled exception: " + QString(e.what()) + "\nExiting now.");
    logCritical("Unhandled exception: {}", e.what());
    return 1;
  }
  catch (...)
  {
    QMessageBox::critical(0, "Critical error", "Unknown unhandled exception: exiting now.");
    logCritical("Unhandled exception: Unknown type");
    return 1;
  }
}

ext: cc

max_stars_repo_name: Nahusa/SCIRun


text:
/*

Copyright (c) 2005-2015, University of Oxford.
All rights reserved.

University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.

This file is part of Chaste.

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 the University of Oxford 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.

*/

#ifndef ABSTRACTSIMPLECELLCYCLEMODEL_HPP_
#define ABSTRACTSIMPLECELLCYCLEMODEL_HPP_

#include "ChasteSerialization.hpp"
#include "ClassIsAbstract.hpp"
#include <boost/serialization/base_object.hpp>

#include "AbstractCellCycleModel.hpp"

/**
 * This class contains all the functionality shared by 'simple' cell-cycle models,
 * where the duration of each cell cycle phase is determined when the cell-cycle
 * model is created. Note that whether or not the cell should actually divide may
 * still depend on further conditions in subclasses; for example, the cell may only
 * divide if the local concentration of a signalling molecule is sufficiently high/
 *
 * This class of cell-cycle models is distinct from 'ODE-based' cell-cycle models,
 * where the duration of one or more cell cycle phases are evaluated 'on the fly'
 * as the cell ages, according to a system of ordinary differential equations (ODEs)
 * governing (for example) the concentrations of key intracellular proteins.
 */
class AbstractSimpleCellCycleModel : public AbstractCellCycleModel
{
private:

    /** Needed for serialization. */
    friend class boost::serialization::access;
    /**
     * Archive the cell-cycle model.
     *
     * @param archive the archive
     * @param version the current version of this class
     */
    template<class Archive>
    void serialize(Archive & archive, const unsigned int version)
    {
        archive & boost::serialization::base_object<AbstractCellCycleModel>(*this);
    }

protected:

    /**
     * Subclasses can override this function if they wish, this just
     * allocates the default values for each of the different cell
     * types' G1 durations as defined in AbstractCellCycleModel.
     */
    virtual void SetG1Duration();

public:

    /**
     * Default constructor - creates an AbstractSimpleCellCycleModel.
     */
    AbstractSimpleCellCycleModel();

    /**
     * Destructor.
     */
    virtual ~AbstractSimpleCellCycleModel();

    /** See AbstractCellCycleModel::ResetForDivision() */
    virtual void ResetForDivision();

    /**
     * Default UpdateCellCyclePhase() method for a simple cell-cycle model.
     *
     * Can be overridden if they should do something more subtle.
     */
    virtual void UpdateCellCyclePhase();

    /**
     * Set the new cell's G1 duration once it has been created after division.
     * The duration will be based on cell type.
     */
    void InitialiseDaughterCell();

    /** See AbstractCellCycleModel::Initialise() */
    virtual void Initialise();

    /**
     * Outputs cell cycle model parameters to file.
     *
     * @param rParamsFile the file stream to which the parameters are output
     */
    virtual void OutputCellCycleModelParameters(out_stream& rParamsFile);
};

CLASS_IS_ABSTRACT(AbstractSimpleCellCycleModel)

#endif /*ABSTRACTSIMPLECELLCYCLEMODEL_HPP_*/

max_stars_repo_name: ktunya/ChasteMod

max_issues_repo_name: ktunya/ChasteMod

max_forks_repo_name: ktunya/ChasteMod


text: #include <boost/numeric/odeint/util/unit_helper.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**
 * Copyright (C) 2015 Dato, Inc.
 * All rights reserved.
 *
 * This software may be modified and distributed under the terms
 * of the BSD license. See the LICENSE file for details.
 */
/**
 * Copyright (c) 2011 Carnegie Mellon University.
 *     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.
 *
 * For more about this software visit:
 *
 *      http://www.graphlab.ml.cmu.edu
 *
 */

/* *
 * Author: Haijie Gu (haijieg@cs.cmu.edu)
 * Date: 04/08/2013
 *
 * CSR+CSC implementation of a graph storage.
 * */

#ifndef GRAPHLAB_GRAPH_STORAGE_HPP
#define GRAPHLAB_GRAPH_STORAGE_HPP
#ifndef __NO_OPENMP__
#include <omp.h>
#endif

#include <cmath>
#include <string>
#include <list>
#include <vector>
#include <set>
#include <map>

#include <queue>
#include <algorithm>
#include <functional>

#include <boost/version.hpp>
#include <boost/bind.hpp>
#include <boost/unordered_set.hpp>
#include <boost/iterator/zip_iterator.hpp>
#include <boost/iterator/counting_iterator.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/iterator/iterator_facade.hpp>

#include <graph/local_edge_buffer.hpp>
#include <graph/graph_basic_types.hpp>

#include <logger/logger.hpp>
#include <logger/assertions.hpp>

#include <serialization/iarchive.hpp>
#include <serialization/oarchive.hpp>

#include <random/random.hpp>
#include <graphlab/util/generics/shuffle.hpp>
#include <graphlab/util/generics/counting_sort.hpp>
#include <graphlab/util/generics/vector_zip.hpp>
#include <graphlab/util/generics/csr_storage.hpp>

#include <parallel/atomic.hpp>

#include <graphlab/macros_def.hpp>

namespace graphlab {

  template<typename VertexData, typename EdgeData>
  class graph_storage {
  public:
    typedef graphlab::lvid_type lvid_type;
    typedef graphlab::edge_id_type edge_id_type;

    /** The type of the edge data stored in the graph. */
    typedef EdgeData edge_data_type;

    /** The type of the vertex data stored in the graph. */
    typedef VertexData vertex_data_type;

    /**
     * \internal
     * CSR/CSC storage types
     */
    typedef csr_storage<lvid_type, edge_id_type> csr_type;

    typedef csr_storage<std::pair<lvid_type, edge_id_type>, edge_id_type> csc_type;

    /* ----------------------------------------------------------------------------- */
    /* helper data field and structures: edge_data_list, class edge, class edge_list */
    /* ----------------------------------------------------------------------------- */
  class edge_type {
   public:
     edge_type () : _source(-1), _target(-1), _eid(-1) {}
     edge_type(lvid_type _source, lvid_type _target, edge_id_type _eid)
         : _source(_source), _target(_target), _eid(_eid) { }

     inline bool is_empty() { return _eid == -1; }
     lvid_type source() const { return _source; }
     lvid_type target() const { return _target; }
     edge_id_type id() const { return _eid; }

   private:
     lvid_type _source;
     lvid_type _target;
     edge_id_type _eid;
  };

  typedef boost::tuple<typename csr_type::iterator,
                       boost::counting_iterator<edge_id_type> > csr_iterator_tuple;

  typedef boost::zip_iterator<csr_iterator_tuple> csr_zip_iterator;

  csr_zip_iterator make_csr_zip_iterator(typename csr_type::iterator iter,
                                           edge_id_type beginid) {
    return csr_zip_iterator(
             csr_iterator_tuple(iter, boost::counting_iterator<edge_id_type>(beginid)));
  }

  struct make_edge_type_csr_functor {
    typedef typename csr_zip_iterator::value_type const& argument_type;
    typedef edge_type result_type;

    make_edge_type_csr_functor() : sourceid(-1) { }

    make_edge_type_csr_functor(lvid_type sourceid) : sourceid(sourceid) { }

    result_type operator() (argument_type arg) const {
      lvid_type destid = arg.template get<0>();
      edge_id_type eid = arg.template get<1>();
      return edge_type(sourceid, destid, eid);
    }
    lvid_type sourceid;
  };

  struct make_edge_type_csc_functor {
    typedef typename csc_type::value_type& argument_type;
    typedef edge_type result_type;
    make_edge_type_csc_functor() : destid(-1) {}

    make_edge_type_csc_functor(lvid_type destid) : destid(destid) { }

    result_type operator() (argument_type arg) const {
      return edge_type(arg.first, destid, arg.second);
    }
    lvid_type destid;
  };

  typedef boost::transform_iterator<make_edge_type_csr_functor,
          csr_zip_iterator> csr_edge_iterator;
  typedef boost::transform_iterator<make_edge_type_csc_functor,
          typename csc_type::iterator> csc_edge_iterator;

  class edge_iterator :
    public boost::iterator_facade <
        edge_iterator,
        edge_type,
        boost::random_access_traversal_tag,
        edge_type> {
    public:
     edge_iterator() : _type(UNDEFINED) {}
     edge_iterator(csc_edge_iterator iter) : _type(CSC), csc_iter(iter) {}
     edge_iterator(csr_edge_iterator iter) : _type(CSR), csr_iter(iter) {}

    private:
     friend class boost::iterator_core_access;

     void increment() {
       switch (_type) {
        case CSC: ++csc_iter; break;
        case CSR: ++csr_iter; break;
        default: return;
       }
     }
     bool equal(const edge_iterator& other) const
     {
       ASSERT_EQ(_type, other._type);
       switch (_type) {
        case CSC: return csc_iter == other.csc_iter;
        case CSR: return csr_iter == other.csr_iter;
        default: return true;
       }
     }
     edge_type dereference() const {
       switch (_type) {
        case CSC: return *csc_iter;
        case CSR: return *csr_iter;
        default: return edge_type();
       }
     }
     void decrement() {
       switch (_type) {
        case CSC: --csc_iter; break;
        case CSR: --csr_iter; break;
        default: return;
       }
     }
     void advance(int n) {
       switch (_type) {
        case CSC: csc_iter+=n; break;
        case CSR: csr_iter+=n; break;
        default: return;
       }
     }
     int distance_to(const edge_iterator& other) const {
       switch (_type) {
        case CSC: return other.csc_iter - csc_iter;
        case CSR: return other.csr_iter - csr_iter;
        default: return 0;
       }
     }
    private:
     enum list_type {CSR, CSC, UNDEFINED};
     list_type _type;
     csc_edge_iterator csc_iter;
     csr_edge_iterator csr_iter;
  }; // end of edge_iterator

  class edge_list {
   public:
     edge_list(edge_iterator _begin, edge_iterator _end) :
         _begin(_begin), _end(_end) {}

     typedef edge_iterator iterator;
     typedef iterator const_iterator;

     inline size_t size() const {
       return _end - _begin;
     }

     inline edge_type operator[](size_t i) const {
       return *(_begin+i);
     }

     bool is_empty() const { return size() == 0; }

     iterator begin() const { return _begin; }

     iterator end() const { return _end; }

   private:
     edge_iterator _begin;
     edge_iterator _end;
  };

  public:
    // CONSTRUCTORS ============================================================>
    graph_storage() {  }

    // METHODS =================================================================>
    /** \brief Returns the number of edges in the graph. */
    size_t num_edges() const { return _edata_storage.size(); }

    /** \brief Returns the number of vertices in the graph. */
    size_t num_vertices() const { return _csr_storage.num_keys(); }

    /** \brief Returns the number of in edges of the vertex. */
    size_t num_in_edges (const lvid_type v) const {
        return (_csc_storage.end(v) - _csc_storage.begin(v));
    }

    /** \brief Returns the number of out edges of the vertex. */
    size_t num_out_edges (const lvid_type v) const {
        return (_csr_storage.end(v) - _csr_storage.begin(v));
    }

    /** \brief Returns a list of in edges of a vertex. */
    edge_list in_edges(const lvid_type v) {
      make_edge_type_csc_functor functor(v);
      // make_edge_type_csc_functor functor;
      csc_edge_iterator begin =
          boost::make_transform_iterator (_csc_storage.begin(v), functor);
      csc_edge_iterator end =
          boost::make_transform_iterator (_csc_storage.end(v), functor);
      return edge_list ( edge_iterator(begin), edge_iterator(end));
    }

    /** \brief Returns a list of out edges of a vertex. */
    edge_list out_edges(const lvid_type v) {
      make_edge_type_csr_functor functor(v);
      csr_zip_iterator beginiter =
          make_csr_zip_iterator(_csr_storage.begin(v),
                                _csr_storage.begin(v)-_csr_storage.begin(0));
      csr_zip_iterator enditer =
          make_csr_zip_iterator(_csr_storage.end(v),
                                _csr_storage.end(v)-_csr_storage.begin(0));

      csr_edge_iterator begin = boost::make_transform_iterator (
          beginiter, functor);
      csr_edge_iterator end = boost::make_transform_iterator (
          enditer, functor);
      return edge_list ( edge_iterator(begin), edge_iterator(end));
    }

    /** \brief Returns edge data of edge_type e*/
    EdgeData& edge_data(edge_id_type eid) {
      ASSERT_LT(eid, num_edges());
      return _edata_storage[eid];
    }

    const EdgeData& edge_data(edge_id_type eid) const {
      ASSERT_LT(eid, num_edges());
      return _edata_storage[eid];
    }

     /** \brief Finalize the graph storage.
      * Construct the CSC, CSR, by sorting edges to maximize the
      * efficiency of graphlab.
      * This function takes O(|V|log(degree)) time and will
      * fail if there are any duplicate edges.
      */
    void finalize(local_edge_buffer<VertexData, EdgeData> &edges) {
#ifdef DEBUG_GRAPH
      logstream(LOG_DEBUG) << "Graph2 finalize starts." << std::endl;
#endif
      std::vector<edge_id_type> permute;
      std::vector<edge_id_type> src_counting_prefix_sum;
      std::vector<edge_id_type> dest_counting_prefix_sum;

#ifdef DEBUG_GRAPH
      logstream(LOG_DEBUG) << "Graph2 finalize: Sort by source vertex" << std::endl;
#endif
      // Sort edges by source;
      // Begin of counting sort.
      counting_sort(edges.source_arr, permute, &src_counting_prefix_sum);

      // Inplace permute of edge_data, edge_src, edge_target array.
#ifdef DEBUG_GRAPH
      logstream(LOG_DEBUG) << "Graph2 finalize: Inplace permute by source id" << std::endl;
#endif
      lvid_type swap_src; lvid_type swap_target; EdgeData  swap_data;
      for (size_t i = 0; i < permute.size(); ++i) {
        if (i != permute[i]) {
          // Reserve the ith entry;
          size_t j = i;
          swap_data = edges.data[i];
          swap_src = edges.source_arr[i];
          swap_target = edges.target_arr[i];
          // Begin swap cycle:
          while (j != permute[j]) {
            size_t next = permute[j];
            if (next != i) {
              edges.data[j] = edges.data[next];
              edges.source_arr[j] = edges.source_arr[next];
              edges.target_arr[j] = edges.target_arr[next];
              permute[j] = j;
              j = next;
            } else {
              // end of cycle
              edges.data[j] = swap_data;
              edges.source_arr[j] = swap_src;
              edges.target_arr[j] = swap_target;
              permute[j] = j;
              break;
            }
          }
        }
      }
      // Unfortunately the zip iterator does not work as expected. Need more debugging...
      // typedef
      //     boost::tuple< std::vector<lvid_type>::iterator,
      //                   std::vector<lvid_type>::iterator,
      //                   typename std::vector<EdgeData>::iterator> iterator_tuple;

      // typedef boost::zip_iterator<iterator_tuple> zip_iterator;

      // inplace_shuffle( zip_iterator(iterator_tuple(
      //                                 edges.source_arr.begin(),
      //                                 edges.target_arr.begin(),
      //                                 edges.data.begin())),
      //                  zip_iterator(iterator_tuple(
      //                                 edges.source_arr.end(),
      //                                 edges.target_arr.end(),
      //                                 edges.data.end())),
      //                  permute);
#ifdef DEBUG_GRAPH
      logstream(LOG_DEBUG) << "Graph2 finalize: Sort by dest id" << std::endl;
#endif
      counting_sort(edges.target_arr, permute, &dest_counting_prefix_sum);
      // Shuffle source array
#ifdef DEBUG_GRAPH
      logstream(LOG_DEBUG) << "Graph2 finalize: Outofplace permute by dest id" << std::endl;
#endif

      outofplace_shuffle(edges.source_arr, permute);
      // Use inplace shuffle to reduce peak memory footprint:
      // inplace_shuffle(edges.source_arr, permute);
      // counting_sort(edges.target_arr, permute);

      // warp into csr csc storage.
      _csr_storage.wrap(src_counting_prefix_sum, edges.target_arr);
      std::vector<std::pair<lvid_type, edge_id_type> > csc_value = vector_zip(edges.source_arr, permute);
      _csc_storage.wrap(dest_counting_prefix_sum, csc_value);
      _edata_storage.swap(edges.data);
      ASSERT_EQ(_csr_storage.num_values(), _csc_storage.num_values());
      ASSERT_EQ(_csr_storage.num_values(), _edata_storage.size());
#ifdef DEBGU_GRAPH
      logstream(LOG_DEBUG) << "End of finalize." << std::endl;
#endif
    } // end of finalize.

    /** \brief Reset the storage. */
    void clear() {
      _csr_storage.clear();
      _csc_storage.clear();
    }

    size_t estimate_sizeof() const {
      return _csr_storage.estimate_sizeof() + _csc_storage.estimate_sizeof();
    } // end of estimate_sizeof

    // ------------- Private data storage ----------------
  private:
    csr_type _csr_storage;
    csc_type _csc_storage;
    std::vector<EdgeData> _edata_storage;

  public:
    /** \brief Load the graph from an archive */
    void load(iarchive& arc) {
      clear();
      arc >> _csr_storage
          >> _csc_storage
          >> _edata_storage;
    }

    /** \brief Save the graph to an archive */
    void save(oarchive& arc) const {
      arc << _csr_storage
          << _csc_storage
          << _edata_storage;
    }

    /** swap two graph storage*/
    void swap(graph_storage& other) {
      _csr_storage.swap(other._csr_storage);
      _csc_storage.swap(other._csc_storage);
      _edata_storage.swap(other._edata_storage);
    }
  };// End of graph store;
}// End of namespace;

namespace std {
  template<typename VertexData, typename EdgeData>
  inline void swap(graphlab::graph_storage<VertexData,EdgeData>& a,
                   graphlab::graph_storage<VertexData,EdgeData>& b) {
    a.swap(b);
  } // end of swap
}; // end of std namespace
#include <graphlab/macros_undef.hpp>
#endif

max_stars_repo_name: parquette/ParFrame

max_issues_repo_name: parquette/ParFrame

max_forks_repo_name: parquette/ParFrame


text:
/**
 *  testReachset.cpp
 *
 *  Test reachable set computation of the Moore-Greitzer engine model.
 *
 *  Created by Yinan Li on June 9, 2020.
 *  Hybrid Systems Group, University of Waterloo.
 */

#include <iostream>
#include <cmath>

#include <array>
#include <boost/numeric/odeint.hpp>

#include "src/abstraction.hpp"
#include "src/system.hpp"
#include "src/csolver.h"
#include "src/matlabio.h"

typedef std::array<double, 3> state_type;

double a = 1./3.5;
double B = 2.0;
double H = 0.18;
double W = 0.25;
double lc = 8.0;
double cx = 1.0/lc;
double cy = 1.0/(4*lc*B*B);
double aH = a+H;
double H2 = H/(2.0*W*W*W);
double W2 = 3*W*W;

/* user defined dynamics */
struct mgode {
    static const int n = 3;  // system dimension
    static const int nu = 2;  // control dimension

    /* template constructor
     * @param[out] dx
     * @param[in] x
     * @param u
     */
    template<typename S>
    mgode(S *dx, const S *x, rocs::Rn u) {
	dx[0] = cx * (aH+H2*(x[0]-W)*(W2-(x[0]-W)*(x[0]-W)) - x[1]) + u[0];
	dx[1] = cy * (x[0] - x[2]*sqrt(x[1]));
	dx[2] = u[1];
    }
};
struct engine_vf {
    rocs::Rn _u;
    engine_vf(rocs::Rn u) : _u(u) {}
    void operator()(state_type &x, state_type &dxdt, double t) const {
	dxdt[0] = cx * (aH+H2*(x[0]-W)*(W2-(x[0]-W)*(x[0]-W)) - x[1]) + _u[0];
	dxdt[1] = cy * (x[0] - x[2]*sqrt(x[1]));
	dxdt[2] = _u[1];
    }
};

struct mgode2 {

    static const int n = 2;  // system dimension
    static const int nu = 2;  // control dimension

    /* template constructor
     * @param[out] dx
     * @param[in] x
     * @param u
     */
    template<typename S>
    mgode2(S *dx, const S *x, rocs::Rn u) {
	dx[0] = cx * (aH+H2*(x[0]-W)*(W2-(x[0]-W)*(x[0]-W)) - x[1]) + u[0];
	dx[1] = cy * (x[0] - u[1]*sqrt(x[1]));
    }
};
struct engine2d_ode {
    rocs::Rn _u;
    engine2d_ode(rocs::Rn u) : _u(u) {}
    void operator()(rocs::Rn &x, rocs::Rn &dxdt, double t) const {
	dxdt[0] = cx * (aH+H2*(x[0]-W)*(W2-(x[0]-W)*(x[0]-W)) - x[1]) + _u[0];
	dxdt[1] = cy * (x[0] - _u[1]*sqrt(x[1]));
    }
};

int main() {

    // /* set the state space */
    // double xlb[3]{0, 0, 0.5};
    // double xub[3]{1, 1, 0.8};

    // /* set the control values */
    // // double L = 0.0003;
    // // double ulb[2]{-5, -L};
    // // double uub[2]{5, L};
    // // double mu[2]{1, L/10};
    // double Lmu = 0.01;
    // double Lu = 0.05;
    // double ulb[2]{-Lu, -Lmu};
    // double uub[2]{Lu, Lmu};
    // double mu[2]{Lu/5, 2*Lmu/5};

    // /* set the sampling time and disturbance */
    // double t = 0.1;
    // double delta = 0.01;
    // /* parameters for computing the flow */
    // int kmax = 10;
    // double tol = 0.01;
    // double alpha = 0.5;
    // double beta = 2;
    // rocs::params controlparams(kmax, tol, alpha, beta);

    // /* define the control system */
    // rocs::CTCntlSys<mgode> engine("Moore-Greitzer", t, mgode::n, mgode::nu,
    // 				  delta, &controlparams);
    // engine.init_workspace(xlb, xub);
    // engine.init_inputset(mu, ulb, uub);
    // engine.allocate_flows();

    // /* test if reachable set covers the nominal trajectory */
    // /* compute reachable set */
    // double dt{0.001};
    // // state_type y{0.5039, 0.6605, 0.62};
    // state_type y{1.526/2, 0.5, 0.65};
    // // double e[3]{0.2, 0.5, 0.1};
    // // rocs::ivec x0 = {rocs::interval(y[0]-e[0], y[0]+e[0]),
    // // 		     rocs::interval(y[1]-e[1], y[1]+e[1]),
    // // 		     rocs::interval(y[2]-e[2], y[2]+e[2])};
    // rocs::ivec x0 = {rocs::interval(0.526, 1),
    // 		     rocs::interval(0.001, 1),
    // 		     rocs::interval(0.5, 0.8)};
    // std::vector<rocs::ivec> x(engine._ugrid._nv, rocs::ivec(3));
    // std::cout << "The initial interval: " << x0 << '\n';
    // std::cout << "The integrating time: " << t << '\n';
    // engine.get_reach_set(x, x0);

    // for (size_t i = 0; i < x.size(); ++i) {
    // 	/* integrate the nominal trajectory */
    // 	state_type y{1.526/2, 0.5, 0.65};
    // 	rocs::Rn u(engine._ugrid._data[i]);
    // 	boost::numeric::odeint::runge_kutta_cash_karp54<state_type> rk45;
    // 	boost::numeric::odeint::integrate_const(rk45, engine_vf(u),
    // 						y, 0.0, t, dt);
    // 	std::cout << "x(t)= [" << y[0] << ','<< y[1] << ',' << y[2] << "]\n";
    // 	std::cout << "R(t, x0, [" << engine._ugrid._data[i][0] << ','
    // 		  << engine._ugrid._data[i][1] << "])= ";
    // 	std::cout << x[i] <<'\n';
    // 	std::cout << "Check: ";
    // 	for (int j = 0; j < 3; ++j) {
    // 	    if (y[j] > x[i][j].getinf() && y[j] < x[i][j].getsup())
    // 		std::cout << true << ' ';
    // 	    else
    // 		std::cout << false << ' ';
    // 	}
    // 	std::cout << '\n';
    // }

    // engine.release_flows();

    /* set the state space */
    const int xdim = 2;
    double xlb[]{0.44, 0.6};
    double xub[]{0.54, 0.7};

    /* set the control values */
    // double Lmu = 0.01;
    double Lu = 0.05;
    double ulb[]{-Lu, 0.5};
    double uub[]{Lu, 0.8};
    double mu[]{Lu/5, 0.01};

    /* set the sampling time and disturbance */
    double delta = 0.01;
    /* parameters for computing the flow */
    int kmax = 10;
    double tol = 0.01;
    double alpha = 0.5;
    double beta = 2;
    rocs::params controlparams(kmax, tol, alpha, beta);

    /* define the control system */
    double t= 0.1;
    rocs::CTCntlSys<mgode2> engine("Moore-Greitzer", t, mgode2::n, mgode2::nu,
				  delta, &controlparams);
    engine.init_workspace(xlb, xub);
    engine.init_inputset(mu, ulb, uub);
    engine.allocate_flows();

    double eta[xdim]{0.00018, 0.00018};
    std::vector<rocs::ivec> x(engine._ugrid._nv, rocs::ivec(xdim));

    /**
     * Test if reachable set covers the nominal trajectory
     */
    // /* compute reachable set */
    // double dt{0.001};
    // rocs::Rn y{0.599, 0.688};
    // rocs::ivec x0 = {rocs::interval(y[0]-eta[0], y[0]+eta[0]),
    // 		     rocs::interval(y[1]-eta[1], y[1]+eta[1])};
    // std::cout << "The initial interval: " << x0 << '\n';
    // std::cout << "The integrating time: " << t << '\n';
    // engine.get_reach_set(x, x0);

    // boost::numeric::odeint::runge_kutta_cash_karp54<rocs::Rn> rk45;
    // for (size_t i = 0; i < x.size(); ++i) {
    // 	/* integrate the nominal trajectory */
    // 	rocs::Rn y{0.599, 0.688};
    // 	rocs::Rn u(engine._ugrid._data[i]);
    // 	boost::numeric::odeint::integrate_const(rk45, engine2d_ode(u),
    // 						y, 0.0, t, dt);
    // 	std::cout << "x(t)= [" << y[0] << ','<< y[1] << "]\n";
    // 	std::cout << "R(t, x0, [" << engine._ugrid._data[i][0] << ','
    // 		  << engine._ugrid._data[i][1] << "])= ";
    // 	std::cout << x[i] <<'\n';
    // 	std::cout << "Check: ";
    // 	for (int j = 0; j < xdim; ++j) {
    // 	    if (y[j] > x[i][j].getinf() && y[j] < x[i][j].getsup())
    // 		std::cout << true << ' ';
    // 	    else
    // 		std::cout << false << ' ';
    // 	}
    // 	std::cout << '\n';
    // }

    /**
     * Test if there is a box inside the goal area can
     * stay inside the goal area
     */
    rocs::abstraction< rocs::CTCntlSys<mgode2> > abst(&engine);
    abst.init_state(eta, xlb, xub);
    double e = 0.003;
    double goal[][2]{{0.5039-e, 0.5039+e}, {0.6605-e, 0.6605+e}};
    rocs::ivec G{rocs::interval(0.5039-e, 0.5039+e),
		 rocs::interval(0.6605-e, 0.6605+e)};

    double c1= eta[0]/2.0; //+1e-10;
    double c2= eta[1]/2.0; //+1e-10;
    // std::vector<rocs::ivec> y(abst._x._dim);
    rocs::Rn x_test{0.0, 0.0};
    std::cout << "Boxes in goal that stay in goal:\n";
    for(size_t i = 0; i < abst._x._nv; ++i) {
	abst._x.id_to_val(x_test, i);
	if(goal[0][0] <= (x_test[0]-c1) && (x_test[0]+c1) <= goal[0][1] &&
	   goal[1][0] <= (x_test[1]-c2) && (x_test[1]+c2) <= goal[1][1]) {
	    rocs::ivec x0{rocs::interval(x_test[0]-eta[0], x_test[0]+eta[0]),
			  rocs::interval(x_test[1]-eta[1], x_test[1]+eta[1])};
	    engine.get_reach_set(x, x0);
	    for (size_t i = 0; i < x.size(); ++i) {
		if(G.isin(x[i])) {
		    std::cout << "x=" << x[i] << ", u=" << i << '\n';
		}
	    }
	}
    }

    engine.release_flows();

    return 0;
}

max_stars_repo_name: yinanl/rocs

max_issues_repo_name: yinanl/rocs

max_forks_repo_name: yinanl/rocs


text:
// Boost Includes ==============================================================
#include <boost/python.hpp>
#include <boost/cstdint.hpp>

// Includes ====================================================================
#include <Magick++/Include.h>

// Using =======================================================================
using namespace boost::python;

// Module ======================================================================
void Export_pyste_src_CompressionType()
{
    enum_< MagickCore::CompressionType >("CompressionType")
        .value("JPEG2000Compression", MagickCore::JPEG2000Compression)
        .value("DXT5Compression", MagickCore::DXT5Compression)
        .value("LZWCompression", MagickCore::LZWCompression)
        .value("DXT3Compression", MagickCore::DXT3Compression)
        .value("RLECompression", MagickCore::RLECompression)
        .value("Group4Compression", MagickCore::Group4Compression)
        .value("NoCompression", MagickCore::NoCompression)
        .value("LosslessJPEGCompression", MagickCore::LosslessJPEGCompression)
        .value("ZipCompression", MagickCore::ZipCompression)
        .value("BZipCompression", MagickCore::BZipCompression)
        .value("DXT1Compression", MagickCore::DXT1Compression)
        .value("JPEGCompression", MagickCore::JPEGCompression)
        .value("UndefinedCompression", MagickCore::UndefinedCompression)
        .value("FaxCompression", MagickCore::FaxCompression)
    ;

}

max_stars_repo_name: jeikabu/lumberyard

max_issues_repo_name: jeikabu/lumberyard

max_forks_repo_name: jeikabu/lumberyard


text:
#pragma once

#include <iostream>
#include <iomanip>
#include <sstream>
#include <type_traits>
#include <typeinfo>
#include <cstdio>
#include <algorithm>
#include <boost/core/demangle.hpp>
#include "json.hpp"
/*
linux:
Just clone https://github.com/sean-/ossp-uuid.git and do usual install.
Windows:
Clone https://github.com/htaox/ossp_uuid.git and build with VS2015.
*/
// #include <uuid.h>
#include "store.common/src/uuid.hxx"
#include "store.common/src/base64.hpp"

using namespace std;
using namespace boost::core;
using namespace store::common;

using json = nlohmann::json;

namespace store {
  namespace extensions {

    string lower_case(const string& l) {
      string d;
      d.resize(l.size());
      transform(l.begin(), l.end(), d.begin(), ::tolower);
      return move(d);
    }

    string upper_case(const string& l) {
      string d;
      d.resize(l.size());
      transform(l.begin(), l.end(), d.begin(), ::toupper);
      return move(d);
    }

    template<typename U>
    string resolve_type_to_string(bool lowercase = true) {
      const auto& ti = typeid(U);
      string n = ti.name(), d;
      n = demangle(n.c_str());
      auto l = n.substr(n.find_last_of(':') + 1);

      if (!lowercase) return l;

      d.resize(n.size());
      transform(l.begin(), l.end(), d.begin(), ::tolower);
      return move(d);
    }

    template<typename T, typename U>
    bool is_derived_from() {
      // U derived, T base
      return std::is_base_of<T, U>::value;
    }

    template<typename ... Args>
    std::string string_format(const std::string& format, Args ... args) {
      size_t size = snprintf(nullptr, 0, format.c_str(), args ...) + 1; // Extra space for '\0'
      std::unique_ptr<char[]> buf(new char[size]);
      snprintf(buf.get(), size, format.c_str(), args ...);
      return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
    }

    // std::string s=join(array.begin(), array.end(), std::string(","));
    template <class T, class A>
    T join(const A &begin, const A &end, const T &t) {
      T result;
      for (A it = begin;
        it != end;
        it++) {
        if (!result.empty())
          result.append(t);
        result.append(*it);
      }
      return result;
    }

    inline string wrapString(string s, const string& ch = "'") {
      s.insert(0, ch);
      s.insert(s.size(), ch);
      return move(s);
    }

    bool invalid_char(char c) {
      return !(c>=0 && c <128);
    }

    string strip_unicode(string str) {
      str.erase(remove_if(str.begin(),str.end(), invalid_char), str.end());
      return move(str);
    }

    string strip_soh(string str) {
      str.erase(remove_if(str.begin(), str.begin() + 1, [](char c) { return c == 1; }), str.begin() + 1);
      return move(str);
    }

    std::string& ltrim(std::string& str, const std::string& chars = "\t\n\v\f\r ") {
      str.erase(0, str.find_first_not_of(chars));
      return str;
    }

    std::string& rtrim(std::string& str, const std::string& chars = "\t\n\v\f\r ") {
      str.erase(str.find_last_not_of(chars) + 1);
      return str;
    }

    std::string& trim(std::string& str, const std::string& chars = "\t\n\v\f\r ") {
      return ltrim(rtrim(str, chars), chars);
    }

    // find_if(arr.begin(), arr.end(), insensitiveCompare("something")) != arr.end()
    auto insensitiveCompare = [](string a) {
      return [&](string b) {
        return std::equal(a.begin(), a.end(),
          b.begin(), b.end(),
          [](char a, char b) {
            return tolower(a) == tolower(b);
          });
      };
    };

    std::vector<std::string> split(const std::string& s, char delim) {
      std::vector<std::string> tokens;
      std::string tok;
      std::istringstream iss(s);
      while (std::getline(iss, tok, delim))
        tokens.push_back(tok);

      return tokens;
    }

    inline string generate_uuid(int vers = UUID_MAKE_V4) {
      uuid id;
      id.make(vers);
      const char* sid = id.string();
      std::string r(sid);
      delete sid;

      return std::move(r);
    }

    inline string generate_uuid_v3(const char* url) {
      uuid id;
      uuid id_ns;

      id_ns.load("ns:URL");
      id.make(UUID_MAKE_V3, &id_ns, url);
      const char* sid = id.string();
      std::string r(sid);
      delete sid;

      return std::move(r);
    }

    template<typename R, typename... T>
    R getPathValueFromJson(const shared_ptr<json>& j, T&&... args) {
      vector<string> params = { args... };

      stringstream path;
      for (auto& e : params)
        path << "/" << e;
      json::json_pointer pt(path.str());

      R r;

      try {
        r = j->at(pt);
      } catch (...) {

      }
      return r;
    }

    template<typename R, typename... T>
    R getPathValueFromJson(const json& j, T&&... args) {
      const auto jptr = make_shared<json>(j);

      return getPathValueFromJson<R>(jptr, std::forward<T>(args)...);
    }

    std::map<string, string> getMapFromJson(const json& j) {
      auto m = std::map<string, string>{};
      for (auto it = j.begin(); it != j.end(); ++it) {
        m[it.key()] = it.value().get<string>();
      }

      return move(m);
    }

    // Author: https://stackoverflow.com/users/433369/user433369
    // https://stackoverflow.com/questions/4689101/how-do-i-convert-a-base64-string-to-hexadecimal-string-in-c
    string str_to_hex(const string& ssir) {
      std::stringstream ss;
      for (int i=0; i<ssir.size(); ++i)
        ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned int>(ssir[i] & 0xff);

      return ss.str();
    }

    string base64_to_hex(const string& k) {
      auto decoded = base64_decode(k);
      return upper_case(str_to_hex(decoded));
    }

    // Author: https://stackoverflow.com/users/309308/michael-mrozek
    // https://stackoverflow.com/questions/3418231/replace-part-of-a-string-with-another-string
    void string_replace(std::string& str, const std::string& from, const std::string& to) {
      if(from.empty())
        return;
      size_t start_pos = 0;
      while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
      }
    }

  }
}

max_stars_repo_name: once-ler/Store-cpp

max_issues_repo_name: once-ler/Store-cpp

max_forks_repo_name: once-ler/Store-cpp


text:
/*******************************<SCHWARZ LIB LICENSE>***********************
Copyright (c) 2019, the SCHWARZ LIB authors
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. 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.

3. Neither the name of the copyright holder 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.
******************************<SCHWARZ LIB LICENSE>*************************/

#ifndef schwarz_base_hpp
#define schwarz_base_hpp

#include <cmath>
#include <fstream>
#include <memory>

#include <omp.h>

#include <schwarz/config.hpp>

#include <communicate.hpp>
#include <initialization.hpp>
#include <solve.hpp>

#if SCHW_HAVE_DEALII
#include <deal.II/lac/sparse_matrix.h>
#endif

/**
 * The Schwarz wrappers namespace
 *
 * @ingroup schwarz_wrappers
 */
namespace schwz {

/**
 * The Base solver class is meant to be the class implementing the common
 * implementations for all the schwarz methods. It derives from the
 * Initialization class, the Communication class and the Solve class all of
 * which are templated.
 *
 * @tparam ValueType  The type of the floating point values.
 * @tparam IndexType  The type of the index type values.
 *
 * @ingroup schwarz_class
 */
template <typename ValueType = gko::default_precision,
          typename IndexType = gko::int32,
          typename MixedValueType = gko::default_precision>
class SchwarzBase : public Initialize<ValueType, IndexType>,
                    public Communicate<ValueType, IndexType, MixedValueType>,
                    public Solve<ValueType, IndexType, MixedValueType> {
public:
    /**
     * The constructor that takes in the user settings and a metadata struct
     * containing the solver metadata.
     *
     * @param settings  The settings struct.
     * @param metadata  The metadata struct.
     */
    SchwarzBase(Settings &settings, Metadata<ValueType, IndexType> &metadata);

#if SCHW_HAVE_DEALII
    /**
     * Initialize the matrix and vectors obtained from the deal.ii.
     *
     * @param matrix  The system matrix.
     * @param system_rhs  The right hand side vector.
     */
    void initialize(const dealii::SparseMatrix<ValueType> &matrix,
                    const dealii::Vector<ValueType> &system_rhs);
#endif

    /**
     * Initialize the matrix and vectors.
     */
    void initialize();

    /**
     * The function that runs the actual solver and obtains the final solution.
     *
     * @param solution  The solution vector.
     */
    void run(std::shared_ptr<gko::matrix::Dense<ValueType>> &solution);

    /**
     * The auxiliary function that prints a passed in vector.
     *
     * @param vector  The vector to be printed.
     * @param subd  The subdomain on which the vector exists.
     * @param name  The name of the vector as a string.
     */
    void print_vector(
        const std::shared_ptr<gko::matrix::Dense<ValueType>> &vector, int subd,
        std::string name);

    /**
     * The auxiliary function that prints a passed in CSR matrix.
     *
     * @param matrix  The matrix to be printed.
     * @param subd  The subdomain on which the vector exists.
     * @param name  The name of the matrix as a string.
     */
    void print_matrix(
        const std::shared_ptr<gko::matrix::Csr<ValueType, IndexType>> &matrix,
        int rank, std::string name);

    /**
     * The local subdomain matrix.
     */
    std::shared_ptr<gko::matrix::Csr<ValueType, IndexType>> local_matrix;

    /**
     * The local subdomain permutation matrix/array.
     */
    std::shared_ptr<gko::matrix::Permutation<IndexType>> local_perm;

    /**
     * The local subdomain inverse permutation matrix/array.
     */
    std::shared_ptr<gko::matrix::Permutation<IndexType>> local_inv_perm;

    /**
     * The local lower triangular factor used for the triangular solves.
     */
    std::shared_ptr<gko::matrix::Csr<ValueType, IndexType>> triangular_factor_l;

    /**
     * The local upper triangular factor used for the triangular solves.
     */
    std::shared_ptr<gko::matrix::Csr<ValueType, IndexType>> triangular_factor_u;

    /**
     * The local interface matrix.
     */
    std::shared_ptr<gko::matrix::Csr<ValueType, IndexType>> interface_matrix;

    /**
     * The global matrix.
     */
    std::shared_ptr<gko::matrix::Csr<ValueType, IndexType>> global_matrix;

    /**
     * The local right hand side.
     */
    std::shared_ptr<gko::matrix::Dense<ValueType>> local_rhs;

    /**
     * The global right hand side.
     */
    std::shared_ptr<gko::matrix::Dense<ValueType>> global_rhs;

    /**
     * The local solution vector.
     */
    std::shared_ptr<gko::matrix::Dense<ValueType>> local_solution;

    /**
     * The global solution vector.
     */
    std::shared_ptr<gko::matrix::Dense<ValueType>> global_solution;

    /**
     * The global residual vector.
     */
    std::vector<ValueType> local_residual_vector_out;

    /**
     * The local residual vector.
     */
    std::vector<std::vector<ValueType>> global_residual_vector_out;

protected:
    /**
     * The settings struct used to store the solver and other auxiliary
     * settings.
     */
    Settings &settings;

    /**
     * The metadata struct used to store the solver metadata.
     */
    Metadata<ValueType, IndexType> &metadata;

    /**
     * The communication struct used to store the metadata and arrays needed for
     * the communication bewtween subdomains.
     */
    struct Communicate<ValueType, IndexType, MixedValueType>::comm_struct
        comm_struct;
};

}  // namespace schwz

#endif  // schwarz_base.hpp

max_stars_repo_name: soumyadipghosh/schwarz-lib

max_issues_repo_name: soumyadipghosh/schwarz-lib

max_forks_repo_name: soumyadipghosh/schwarz-lib


text:
#ifndef _LDAPLUSPLUS_DOCUMENT_HPP_
#define _LDAPLUSPLUS_DOCUMENT_HPP_

#include <memory>
#include <random>
#include <vector>

#include <Eigen/Core>

namespace ldaplusplus {
namespace corpus {

// Forward declaration for the compiler
class Corpus;

/**
 * A Document is the minimal document needed for any type of LDA
 * implementation.
 *
 * It is meant to abstract away the source of the document data and the storage
 * type etc.
 */
class Document
{
    public:
        /**
         * @return The corpus this document belongs to
         */
        virtual const std::shared_ptr<const Corpus> get_corpus() const = 0;
        /**
         * @return The bag of words dense vector
         */
        virtual const Eigen::VectorXi & get_words() const = 0;

        /**
         * @return The corpus this documents belongs to after casting it to
         *         another pointer type for saving a few keystrokes.
         */
        template <typename T>
        const std::shared_ptr<const T> get_corpus() const {
            return std::static_pointer_cast<const T>(get_corpus());
        }

        virtual ~Document(){};
};

/**
 * The classification Document contains the words and a category in the form of
 * an integer.
 */
class ClassificationDocument : public Document
{
    public:
        /**
         * @return The class of the document
         */
        virtual int get_class() const = 0;
};

/**
 * A corpus is a collection of documents.
 */
class Corpus
{
    public:
        /** The number of documents in the corpus */
        virtual size_t size() const = 0;
        /** The ith document */
        virtual const std::shared_ptr<Document> at(size_t index) const = 0;
        /**
         * Shuffle the documents so that the ith document is any of the
         * documents with probability 1.0/size() .
         */
        virtual void shuffle() = 0;

        virtual ~Corpus(){};
};

/**
 * A corpus that contains information about the documents' classes (namely
 * their priors).
 */
class ClassificationCorpus : public Corpus
{
    public:
        /**
         * @param  y A class
         * @return The count of the documents in class y divided by the count
         *         of all the documents
         */
        virtual float get_prior(int y) const = 0;
};

/**
 * Eigen Document is a document backed by an Eigen::VectorXi.
 */
class EigenDocument : public Document
{
    public:
        EigenDocument(Eigen::VectorXi X) : EigenDocument(X, nullptr) {}
        EigenDocument(Eigen::VectorXi X, std::shared_ptr<const Corpus> corpus);

        const std::shared_ptr<const Corpus> get_corpus() const override;
        const Eigen::VectorXi & get_words() const override;

    private:
        Eigen::VectorXi X_;
        std::shared_ptr<const Corpus> corpus_;
};

/**
 * ClassificationDecorator decorates any Document with classification
 * information.
 */
class ClassificationDecorator : public ClassificationDocument
{
    public:
        /**
         * @param doc The document to be decorated
         * @param y   The class of the document
         */
        ClassificationDecorator(std::shared_ptr<Document> doc, int y);

        const std::shared_ptr<const Corpus> get_corpus() const override;
        const Eigen::VectorXi & get_words() const override;
        int get_class() const override;

    private:
        std::shared_ptr<Document> document_;
        int y_;
};

/**
 * Implement a shuffle method that shuffles indexes and provides them to
 * classes who want to implement the corpus interface.
 */
class CorpusIndexes
{
    public:
        CorpusIndexes(int N, int random_state=0);

        /**
         * Return the document index that corresponds to the sequential index
         * after a shuffle.
         */
        int get_index(int index) const { return indices_[index]; }

        /**
         * Shuffle the indexes around.
         */
        void shuffle();

    private:
        /**
         * A vector of indices that implements the function mapping the ith in
         * sequence document to a jth actual document
         */
        std::vector<int> indices_;

        /** A pseudo random number generator for the shuffling */
        std::mt19937 prng_;
};

/**
 * Wrap a matrix X and implement the corpus interface.
 */
class EigenCorpus : public Corpus
{
    public:
        EigenCorpus(const Eigen::MatrixXi & X, int random_state=0);

        size_t size() const override;
        virtual const std::shared_ptr<Document> at(size_t index) const override;
        void shuffle() override;

    protected:
        /** To implement shuffle */
        CorpusIndexes indices_;

        /**
         * We keep X_ protected instead of private to reduce boilerplate in
         * creating a supervised version of this Corpus.
         */
        const Eigen::MatrixXi & X_;

};

/**
 * EigenClassificationCorpus wraps a pair of matrices X, y and implements the
 * Corpus interface with them using X as the words and y as the classes.
 */
class EigenClassificationCorpus : public ClassificationCorpus
{
    public:
        EigenClassificationCorpus(
            const Eigen::MatrixXi &X,
            const Eigen::VectorXi &y,
            int random_state = 0
        );

        size_t size() const override;
        virtual const std::shared_ptr<Document> at(size_t index) const override;
        void shuffle() override;
        float get_prior(int y) const override;

    private:
        /** To implement shuffle */
        CorpusIndexes indices_;

        // The data
        const Eigen::MatrixXi & X_;
        const Eigen::VectorXi & y_;

        // The class priors
        Eigen::VectorXf priors_;
};

}  // namespace corpus
}  // namespace ldaplusplus

#endif  // _LDAPLUSPLUS_DOCUMENT_HPP_

max_stars_repo_name: angeloskath/supervised-lda

max_issues_repo_name: angeloskath/supervised-lda

max_forks_repo_name: angeloskath/supervised-lda


text:
/*
 * Copyright (c) 2008, Willow Garage, Inc.
 * All rights reserved.
 *
 * 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 the Willow Garage, Inc. 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 OWNER 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.
 */

#include <boost/bind.hpp>

#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreManualObject.h>
#include <OGRE/OgreBillboardSet.h>
#include <OGRE/OgreMatrix4.h>

#include <tf/transform_listener.h>

#include "rviz/display_context.h"
#include "rviz/frame_manager.h"
#include "rviz/properties/color_property.h"
#include "rviz/properties/float_property.h"
#include "rviz/properties/int_property.h"
#include "rviz/validate_floats.h"

#include "rviz/default_plugin/path_display.h"

namespace rviz
{

PathDisplay::PathDisplay()
{
  color_property_ = new ColorProperty( "Color", QColor( 25, 255, 0 ),
                                       "Color to draw the path.", this );

  alpha_property_ = new FloatProperty( "Alpha", 1.0,
                                       "Amount of transparency to apply to the path.", this );

  buffer_length_property_ = new IntProperty( "Buffer Length", 1,
                                             "Number of paths to display.",
                                             this, SLOT( updateBufferLength() ));
  buffer_length_property_->setMin( 1 );
}

PathDisplay::~PathDisplay()
{
  destroyObjects();
}

void PathDisplay::onInitialize()
{
  MFDClass::onInitialize();
  updateBufferLength();
}

void PathDisplay::reset()
{
  MFDClass::reset();
  updateBufferLength();
}

void PathDisplay::destroyObjects()
{
  for( size_t i = 0; i < manual_objects_.size(); i++ )
  {
    Ogre::ManualObject* manual_object = manual_objects_[ i ];
    if( manual_object )
    {
      manual_object->clear();
      scene_manager_->destroyManualObject( manual_object );
    }
  }
}

void PathDisplay::updateBufferLength()
{
  destroyObjects();

  int buffer_length = buffer_length_property_->getInt();
  QColor color = color_property_->getColor();

  manual_objects_.resize( buffer_length );
  for( size_t i = 0; i < manual_objects_.size(); i++ )
  {
    Ogre::ManualObject* manual_object = scene_manager_->createManualObject();
    manual_object->setDynamic( true );
    scene_node_->attachObject( manual_object );

    manual_objects_[ i ] = manual_object;
  }
}

bool validateFloats( const nav_msgs::Path& msg )
{
  bool valid = true;
  valid = valid && validateFloats( msg.poses );
  return valid;
}

void PathDisplay::processMessage( const nav_msgs::Path::ConstPtr& msg )
{
  Ogre::ManualObject* manual_object = manual_objects_[ messages_received_ % buffer_length_property_->getInt() ];
  manual_object->clear();

  if( !validateFloats( *msg ))
  {
    setStatus( StatusProperty::Error, "Topic", "Message contained invalid floating point values (nans or infs)" );
    return;
  }

  Ogre::Vector3 position;
  Ogre::Quaternion orientation;
  if( !context_->getFrameManager()->getTransform( msg->header, position, orientation ))
  {
    ROS_DEBUG( "Error transforming from frame '%s' to frame '%s'", msg->header.frame_id.c_str(), qPrintable( fixed_frame_ ));
  }

  Ogre::Matrix4 transform( orientation );
  transform.setTrans( position );

//  scene_node_->setPosition( position );
//  scene_node_->setOrientation( orientation );

  Ogre::ColourValue color = color_property_->getOgreColor();
  color.a = alpha_property_->getFloat();

  uint32_t num_points = msg->poses.size();
  manual_object->estimateVertexCount( num_points );
  manual_object->begin( "BaseWhiteNoLighting", Ogre::RenderOperation::OT_LINE_STRIP );
  for( uint32_t i=0; i < num_points; ++i)
  {
    const geometry_msgs::Point& pos = msg->poses[ i ].pose.position;
    Ogre::Vector3 xpos = transform * Ogre::Vector3( pos.x, pos.y, pos.z );
    manual_object->position( xpos.x, xpos.y, xpos.z );
    manual_object->colour( color );
  }

  manual_object->end();
}

} // namespace rviz

#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS( rviz::PathDisplay, rviz::Display )


text:
#include <Eigen/Dense>
#include <vtkDelaunay3D.h>
#include <vtkDataSetSurfaceFilter.h>
#include <vtkPolyDataReader.h>
#include <vtkPolyDataWriter.h>
#include <vtkPolyData.h>
#include <vtkPointData.h>
#include <vtkCellArray.h>
#include <vtkDoubleArray.h>
#include <vtkIdFilter.h>
#include <vtkSmartPointer.h>

typedef Eigen::Vector3d Vector3d;
typedef Eigen::VectorXd VectorXd;
typedef Eigen::Matrix3d Matrix3d;
typedef Eigen::Matrix3Xd Matrix3Xd;
typedef Eigen::Map<Matrix3Xd> Map3Xd;

int main(){
    clock_t t1;
    t1 = clock();
    for(auto i=0; i < 10000; ++i){
        vtkNew<vtkPolyDataReader> reader;
        reader->SetFileName("T7.vtk");
        reader->Update();
        auto poly = reader->GetOutput();
        auto N = poly->GetNumberOfPoints();
        auto pts = (double*) poly->GetPoints()->GetData()->GetVoidPointer(0);
        Map3Xd points(pts,3,N);

        // Project points to unit sphere
        points.colwise().normalize();

        // Create a 3D tessellation
        auto idf = vtkSmartPointer<vtkIdFilter>::New();
        idf->PointIdsOn();
        idf->SetIdsArrayName("OrigIds");
        idf->SetInputData(poly);
        auto d3d = vtkSmartPointer<vtkDelaunay3D>::New();
        d3d->SetInputConnection(idf->GetOutputPort());
        auto dssf = vtkSmartPointer<vtkDataSetSurfaceFilter>::New();
        dssf->SetInputConnection(d3d->GetOutputPort());
        dssf->Update();
        auto final = dssf->GetOutput();
        auto interim = final->GetPolys();
        interim->InitTraversal();
        auto origIds = vtkIdTypeArray::SafeDownCast(
                                final->GetPointData()->GetArray("OrigIds"));
        auto pointIds = vtkSmartPointer<vtkIdList>::New();
        auto finalCells = vtkSmartPointer<vtkCellArray>::New();
        while(interim->GetNextCell(pointIds)){
            int numIds = pointIds->GetNumberOfIds();
            finalCells->InsertNextCell(numIds);
            for(auto j=0; j < numIds; j++ ){
                int id = (int)origIds->GetTuple1( pointIds->GetId(j) );
                finalCells->InsertCellPoint(id);
            }
        }
        poly->SetPolys(finalCells);
        auto writer = vtkSmartPointer<vtkPolyDataWriter>::New();
        writer->SetFileName("Mesh.vtk");
        writer->SetInputData(poly);
        writer->Write();

    }

    float diff((float)clock() - (float)t1);
    std::cout << "Time elapsed : " << diff / CLOCKS_PER_SEC
              << " seconds" << std::endl;
    return 0;
}

ext: cxx


text:
// Copyright Nick Thompson, 2017
// 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)

/*
 * This class performs sinh-sinh quadrature over the entire real line.
 *
 * References:
 *
 * 1) Tanaka, Ken'ichiro, et al. "Function classes for double exponential integration formulas." Numerische Mathematik 111.4 (2009): 631-655.
 */

#ifndef BOOST_MATH_QUADRATURE_SINH_SINH_HPP
#define BOOST_MATH_QUADRATURE_SINH_SINH_HPP

#include <cmath>
#include <limits>
#include <memory>
#include <boost/math/quadrature/detail/sinh_sinh_detail.hpp>

namespace boost{ namespace math{ namespace quadrature {

template<class Real, class Policy = boost::math::policies::policy<> >
class sinh_sinh
{
public:
    sinh_sinh(size_t max_refinements = 9)
        : m_imp(std::make_shared<detail::sinh_sinh_detail<Real, Policy> >(max_refinements)) {}

    template<class F>
    auto integrate(const F f, Real tol = boost::math::tools::root_epsilon<Real>(), Real* error = nullptr, Real* L1 = nullptr, std::size_t* levels = nullptr)->decltype(std::declval<F>()(std::declval<Real>())) const
    {
        return m_imp->integrate(f, tol, error, L1, levels);
    }

private:
    std::shared_ptr<detail::sinh_sinh_detail<Real, Policy>> m_imp;
};

}}}
#endif


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

#include <boost/hana/foldable.hpp>
#include <boost/hana/record_macros.hpp>

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

struct moveonly {
    moveonly() = default;
    moveonly(moveonly const&) = delete;
    moveonly(moveonly&&) = default;
};

struct T {
    BOOST_HANA_DEFINE_RECORD_INTRUSIVE(T,
        (moveonly, member1),
        (moveonly, member2)
    );
};

int f(int, moveonly) { return 1; }
int g(moveonly, int) { return 1; }

int main() {
    // Folding a Record with move-only members should work when the
    // Record is an rvalue.
    foldl(T{}, 0, f);
    foldr(T{}, 0, g);
}

max_stars_repo_name: josephwinston/hana

max_issues_repo_name: josephwinston/hana

max_forks_repo_name: josephwinston/hana