text:
/*
 * This is part of the fl library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2015 Max Planck Society,
 * 				 Autonomous Motion Department,
 * 			     Institute for Intelligent Systems
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file sigma_point_update_policy.hpp
 * \date July 2015
 * \author Jan Issac (jan.issac@gmail.com)
 */

#pragma once

#include <Eigen/Dense>

#include <fl/util/meta.hpp>
#include <fl/util/traits.hpp>
#include <fl/util/descriptor.hpp>
#include <fl/filter/gaussian/transform/point_set.hpp>
#include <fl/filter/gaussian/quadrature/sigma_point_quadrature.hpp>

namespace fl
{

// Forward declarations
template <typename...> class SigmaPointUpdatePolicy;

template <
    typename SigmaPointQuadrature,
    typename SensorFunction
>
class SigmaPointUpdatePolicy<
          SigmaPointQuadrature,
          SensorFunction>
    : public SigmaPointUpdatePolicy<
                SigmaPointQuadrature,
                NonAdditive<SensorFunction>>
{ };

template <
    typename SigmaPointQuadrature,
    typename SensorFunction
>
class SigmaPointUpdatePolicy<
          SigmaPointQuadrature,
          NonAdditive<SensorFunction>>
    : public Descriptor
{
public:
    typedef typename SensorFunction::State State;
    typedef typename SensorFunction::Obsrv Obsrv;
    typedef typename SensorFunction::Noise Noise;

    enum : signed int
    {
        NumberOfPoints = SigmaPointQuadrature::number_of_points(
                             JoinSizes<
                                 SizeOf<State>::Value,
                                 SizeOf<Noise>::Value
                             >::Size)
    };

    typedef PointSet<State, NumberOfPoints> StatePointSet;
    typedef PointSet<Noise, NumberOfPoints> NoisePointSet;
    typedef PointSet<Obsrv, NumberOfPoints> ObsrvPointSet;

    template <
        typename Belief
    >
    void operator()(const SensorFunction& obsrv_function,
                    const SigmaPointQuadrature& quadrature,
                    const Belief& prior_belief,
                    const Obsrv& obsrv,
                    Belief& posterior_belief)
    {
        // static_assert() is non-additive

        noise_distr_.dimension(obsrv_function.noise_dimension());

        auto&& h = [&](const State& x, const Noise& w)
        {
           return obsrv_function.observation(x, w);
        };

        quadrature.propergate_gaussian(h, prior_belief, noise_distr_, X, Y, Z);

        auto&& prediction = Z.center();
        auto&& Z_c = Z.points();
        auto&& W = X.covariance_weights_vector();
        auto&& X_c = X.centered_points();

        auto innovation = (obsrv - prediction).eval();
        auto cov_xx = (X_c * W.asDiagonal() * X_c.transpose()).eval();
        auto cov_yy = (Z_c * W.asDiagonal() * Z_c.transpose()).eval();
        auto cov_xy = (X_c * W.asDiagonal() * Z_c.transpose()).eval();
        auto cov_yx = cov_xy.transpose().eval();

        auto x_updated = (X.mean() + cov_xy * solve(cov_yy, innovation)).eval();
        auto cov_xx_updated = (cov_xx - cov_xy * solve(cov_yy, cov_yx)).eval();

        posterior_belief.dimension(prior_belief.dimension());
        posterior_belief.mean(x_updated);
        posterior_belief.covariance(cov_xx_updated);

        //        auto K = (cov_xy * cov_yy.inverse()).eval();
        //        posterior_belief.mean(X.mean() + K * innovation);
        //        posterior_belief.covariance(cov_xx - K * cov_yy * K.transpose());
    }

    virtual std::string name() const
    {
        return "SigmaPointUpdatePolicy<"
                + this->list_arguments(
                       "SigmaPointQuadrature",
                       "NonAdditive<SensorFunction>")
                + ">";
    }

    virtual std::string description() const
    {
        return "Sigma Point based filter update policy for observation model"
               " with non-additive noise";
    }

protected:
    StatePointSet X;
    NoisePointSet Y;
    ObsrvPointSet Z;
    Gaussian<Noise> noise_distr_;
};

}

ext: hpp

max_stars_repo_name: aeolusbot-tommyliu/fl

max_issues_repo_name: aeolusbot-tommyliu/fl

max_forks_repo_name: aeolusbot-tommyliu/fl


text:
/**
 * Copyright Soramitsu Co., Ltd. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#include "consensus/validation/babe_block_validator.hpp"

#include <algorithm>
#include <boost/assert.hpp>

#include "common/mp_utils.hpp"
#include "crypto/sr25519_provider.hpp"
#include "scale/scale.hpp"

OUTCOME_CPP_DEFINE_CATEGORY(kagome::consensus,
                            BabeBlockValidator::ValidationError,
                            e) {
  using E = kagome::consensus::BabeBlockValidator::ValidationError;
  switch (e) {
    case E::NO_AUTHORITIES:
      return "no authorities are provided for the validation";
    case E::INVALID_DIGESTS:
      return "the block does not contain valid BABE digests";
    case E::INVALID_SIGNATURE:
      return "SR25519 signature, which is in BABE header, is invalid";
    case E::INVALID_VRF:
      return "VRF value and output are invalid";
    case E::TWO_BLOCKS_IN_SLOT:
      return "peer tried to distribute several blocks in one slot";
    case E::INVALID_TRANSACTIONS:
      return "one or more transactions in the block are invalid";
  }
  return "unknown error";
}

namespace kagome::consensus {
  using common::Buffer;

  BabeBlockValidator::BabeBlockValidator(
      std::shared_ptr<blockchain::BlockTree> block_tree,
      std::shared_ptr<runtime::TaggedTransactionQueue> tx_queue,
      std::shared_ptr<crypto::Hasher> hasher,
      std::shared_ptr<crypto::VRFProvider> vrf_provider,
      std::shared_ptr<crypto::SR25519Provider> sr25519_provider)
      : block_tree_{std::move(block_tree)},
        tx_queue_{std::move(tx_queue)},
        hasher_{std::move(hasher)},
        vrf_provider_{std::move(vrf_provider)},
        sr25519_provider_{std::move(sr25519_provider)},
        log_{common::createLogger("BabeBlockValidator")} {
    BOOST_ASSERT(block_tree_);
    BOOST_ASSERT(tx_queue_);
    BOOST_ASSERT(vrf_provider_);
    BOOST_ASSERT(sr25519_provider_);
  }

  outcome::result<void> BabeBlockValidator::validate(
      const primitives::Block &block, const Epoch &epoch) const {
    if (epoch.authorities.empty()) {
      return ValidationError::NO_AUTHORITIES;
    }

    log_->debug("Epoch contains authority: {}",
                epoch.authorities.front().id.id.toHex());

    // get BABE-specific digests, which must be inside of this block
    OUTCOME_TRY(babe_digests, getBabeDigests(block));
    auto [seal, babe_header] = babe_digests;

    // signature in seal of the header must be valid
    if (!verifySignature(block, babe_header, seal, epoch.authorities)) {
      return ValidationError::INVALID_SIGNATURE;
    }

    // VRF must prove that the peer is the leader of the slot
    if (!verifyVRF(babe_header, epoch)) {
      return ValidationError::INVALID_VRF;
    }

    // peer must not send two blocks in one slot
    if (!verifyProducer(babe_header)) {
      return ValidationError::TWO_BLOCKS_IN_SLOT;
    }

    // all transactions in the block must be valid
    if (!verifyTransactions(block.body)) {
      return ValidationError::INVALID_TRANSACTIONS;
    }

    // there must exist a chain with the block in our storage, which is
    // specified as a parent of the block we are validating; BlockTree takes
    // care of this check and returns a specific error, if it fails
    return outcome::success();
  }

  template <typename T, typename VarT>
  boost::optional<T> getFromVariant(VarT &&v) {
    return visit_in_place(
        v,
        [](const T &expected_val) -> boost::optional<T> {
          return boost::get<T>(expected_val);
        },
        [](const auto &) -> boost::optional<T> { return boost::none; });
  }

  outcome::result<std::pair<Seal, BabeBlockHeader>>
  BabeBlockValidator::getBabeDigests(const primitives::Block &block) const {
    // valid BABE block has at least two digests: BabeHeader and a seal
    if (block.header.digest.size() < 2) {
      log_->info(
          "valid BABE block must have at least 2 digests, this one have {}",
          block.header.digest.size());
      return ValidationError::INVALID_DIGESTS;
    }
    const auto &digests = block.header.digest;

    // last digest of the block must be a seal - signature
    auto seal_res = getFromVariant<primitives::Seal>(digests.back());
    if (!seal_res) {
      log_->info("last digest of the block is not a Seal");
      return ValidationError::INVALID_DIGESTS;
    }

    OUTCOME_TRY(babe_seal_res, scale::decode<Seal>(seal_res.value().data));

    for (const auto &digest :
         gsl::make_span(digests).subspan(0, digests.size() - 1)) {
      if (auto consensus_dig = getFromVariant<primitives::PreRuntime>(digest);
          consensus_dig) {
        if (auto header = scale::decode<BabeBlockHeader>(consensus_dig->data);
            header) {
          // found the BabeBlockHeader digest; return
          return {babe_seal_res, header.value()};
        }
      }
    }

    log_->warn("there is no BabeBlockHeader digest in the block");
    return ValidationError::INVALID_DIGESTS;
  }

  bool BabeBlockValidator::verifySignature(
      const primitives::Block &block,
      const BabeBlockHeader &babe_header,
      const Seal &seal,
      gsl::span<const primitives::Authority> authorities) const {
    // firstly, take hash of the block's header without Seal, which is the last
    // digest
    auto block_copy = block;
    block_copy.header.digest.pop_back();

    auto block_copy_encoded = scale::encode(block_copy.header).value();

    auto block_hash = hasher_->blake2b_256(block_copy_encoded);

    // secondly, retrieve public key of the peer by its authority id
    if (static_cast<uint64_t>(authorities.size())
        <= babe_header.authority_index.index) {
      log_->info("don't know about authority with index {}",
                 babe_header.authority_index.index);
      return false;
    }
    const auto &key = authorities[babe_header.authority_index.index].id;

    // thirdly, use verify function to check the signature
    auto res = sr25519_provider_->verify(seal.signature, block_hash, key.id);
    return res && res.value();
  }

  bool BabeBlockValidator::verifyVRF(const BabeBlockHeader &babe_header,
                                     const Epoch &epoch) const {
    // verify VRF output
    auto randomness_with_slot =
        Buffer{}
            .put(epoch.randomness)
            .put(common::uint64_t_to_bytes(babe_header.slot_number));
    auto verify_res = vrf_provider_->verify(
        randomness_with_slot,
        babe_header.vrf_output,
        epoch.authorities[babe_header.authority_index.index].id.id,
        epoch.threshold);
    if (not verify_res.is_valid) {
      log_->error("VRF proof in block is not valid");
      return false;
    }

    // verify threshold
    if (not verify_res.is_less) {
      log_->error("VRF value is not less than the threshold");
      return false;
    }

    return true;
  }

  bool BabeBlockValidator::verifyProducer(
      const BabeBlockHeader &babe_header) const {
    auto peer = babe_header.authority_index;

    auto slot_it = blocks_producers_.find(babe_header.slot_number);
    if (slot_it == blocks_producers_.end()) {
      // this peer is the first producer in this slot
      blocks_producers_.insert({babe_header.slot_number, {peer}});
      return true;
    }

    auto &slot = slot_it->second;
    auto peer_in_slot = slot.find(peer);
    if (peer_in_slot != slot.end()) {
      log_->info("authority {} has already produced a block in the slot {}",
                 peer.index,
                 babe_header.slot_number);
      return false;
    }

    // OK
    slot.insert(peer);
    return true;
  }

  bool BabeBlockValidator::verifyTransactions(
      const primitives::BlockBody &block_body) const {
    return std::all_of(
        block_body.cbegin(), block_body.cend(), [this](const auto &ext) {
          auto &&[block_number, _] = block_tree_->deepestLeaf();
          auto validation_res =
              tx_queue_->validate_transaction(block_number, ext);
          if (!validation_res) {
            log_->info("extrinsic validation failed: {}",
                       validation_res.error());
            return false;
          }
          return visit_in_place(validation_res.value(),
                                [](const primitives::Valid &) { return true; },
                                [](primitives::Invalid) { return false; },
                                [](primitives::Unknown) { return false; });
        });
  }
}  // namespace kagome::consensus

ext: cpp

max_stars_repo_name: Lederstrumpf/kagome

max_issues_repo_name: Lederstrumpf/kagome

max_forks_repo_name: Lederstrumpf/kagome


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

#include "ImageLogReader.h"

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <boost/filesystem.hpp>
#include <boost/algorithm/algorithm.hpp>
#include <boost/algorithm/string.hpp>
#include <stdexcept>
#include <iomanip>
#include <fstream>

# define WAYNE_DEBUG

static std::string cvTypeToString(int type) {
  std::string r;
  uchar depth = type & CV_MAT_DEPTH_MASK;
  uchar chans = 1 + (type >> CV_CN_SHIFT);
  switch (depth) {
    case CV_8U:
      r = "8U";
      break;
    case CV_8S:
      r = "8S";
      break;
    case CV_16U:
      r = "16U";
      break;
    case CV_16S:
      r = "16S";
      break;
    case CV_32S:
      r = "32S";
      break;
    case CV_32F:
      r = "32F";
      break;
    case CV_64F:
      r = "64F";
      break;
    default:
      r = "User";
      break;
  }
  r += "C";
  r += (chans + '0');
  return r;
}

ImageLogReader::ImageLogReader(std::string colorDirectory, std::string depthDirectory, std::string maskDirectory, unsigned indexWidth,
                               std::string colorPrefix, std::string depthPrefix, std::string maskPrefix, bool flipColors)
    : LogReader(colorDirectory, flipColors),
      depthImagesDir(depthDirectory),
      maskImagesDir(maskDirectory),
      colorPre(colorPrefix),
      depthPre(depthPrefix),
      maskPre(maskPrefix),
      indexW(indexWidth) {
  using namespace boost::filesystem;
  using namespace boost::algorithm;

  const std::vector<std::string> rgbExtensions = {".jpg", ".png", ".ppm"};
  const std::vector<std::string> depthExtensions = {".exr", ".png"};
  const std::vector<std::string> maskExtensions = {".png", ".pgm"};

  // Overlapping directories but no distinct prefixes? Try default prefixes..
  if (((depthDirectory == colorDirectory) || (maskDirectory == colorDirectory) || (maskDirectory == depthDirectory)) &&
      ((depthPre == colorPre) && (maskPre == colorPre) && (maskPre == depthPre))) {
    colorPre = "Color";
    depthPre = "Depth";
    maskPre = "Mask";
  }

  auto countFilesInDir = [](const std::string& path, const std::string& prefix, const std::vector<std::string>& extension,
                            std::string& outExt) -> unsigned {
    unsigned result = 0;
    outExt = "";
    for (auto it = directory_iterator(path); it != directory_iterator(); ++it) {
      if (is_regular_file(it->status())) {
        std::string ext = it->path().extension().string();
        std::string name = it->path().stem().string();
        to_lower(ext);

        if (name.substr(0, prefix.length()) == prefix) {
          for (const std::string& e : extension) {
            if (e == ext) {
              if (outExt == "")
                outExt = ext;
              else if (outExt != ext)
                throw std::invalid_argument("Error: Files in the dataset ( " + path + ", " + prefix +
                                            ") are required to have the same extension.");
              result++;
              break;
            }
          }
        }
      }
    }
    return result;
  };

  unsigned numColorImages = countFilesInDir(colorDirectory, colorPre, rgbExtensions, colorExt);
  unsigned numDepthImages = countFilesInDir(depthDirectory, depthPre, depthExtensions, depthExt);
  unsigned numMaskImages = countFilesInDir(maskDirectory, maskPre, maskExtensions, maskExt);

  if (numMaskImages > 0) {
    hasMasksGT = true;
    maxMasks = numMaskImages;
  }

  if (numColorImages != numDepthImages) throw std::invalid_argument("Error: Number of RGB-frames != Depth-frames!");
  if (hasMasksGT && (numColorImages != numMaskImages)) throw std::invalid_argument("Error: Number of RGB-frames != Mask-frames!");

  numFrames = numColorImages;

  // Find start index
  int index = 0;
  for (; index < 2; index++) {
    std::stringstream ss;
    ss << std::setw(indexW) << std::setfill('0') << index;
    std::string path = colorDirectory + colorPre + ss.str() + colorExt;
    if (exists(path)) {
      startIndex = index;
      break;
    }
  }
  if (index == 2) throw std::invalid_argument("Error: Could not find start index.");

  std::cout << "Opened dataset with " << numFrames << " frames, starting with index: " << startIndex;
  if (hasMasksGT) std::cout << " The dataset also provides masks.";
  std::cout << std::endl;

  // Try to find calibration file in color directory
  const std::string calibrationFile = colorDirectory + "/calibration.txt";
  if (exists(calibrationFile)) LogReader::calibrationFile = calibrationFile;

  currentFrame = -1;
  frames.resize(numFrames);
  startBufferLoop();
}

ImageLogReader::~ImageLogReader() { stopBufferLoop(); }

void ImageLogReader::getPrevious() { assert(0); }

void ImageLogReader::getNext() {
  if (bufferingLoopActive)
    bufferingCondition.notify_one();
  else
    assert(0);  // bufferFrames();

  currentFrame += 1;
}

void ImageLogReader::fastForward(int frame) {
  stopBufferLoop();
  //frames.clear();

  currentFrame = frame;
  nextBufferIndex = frame;

  startBufferLoop();
  bufferFrames();
}

void ImageLogReader::bufferFrames() {
  std::cout << "bufferFrames()" << std::endl;
  if (bufferingLoopActive)
    bufferingCondition.notify_one();
  else
    bufferFramesImpl();
}

void ImageLogReader::startBufferLoop() {
  std::cout << "startBufferLoop()" << std::endl;
  bufferingLoopActive = true;
  bufferingThread = std::thread(&ImageLogReader::bufferLoop, this);
}

void ImageLogReader::stopBufferLoop() {
  std::cout << "stopBufferLoop()" << std::endl;
  while (bufferingLoopActive || !bufferingThread.joinable()) {
    bufferingLoopActive = false;
    bufferingCondition.notify_one();
  }
  bufferingThread.join();
}

void ImageLogReader::bufferLoop() {
  std::cout << "Started data-buffering thread with id: " << std::this_thread::get_id() << std::endl;

  std::unique_lock<std::mutex> lock(bufferingMutex);
  while (bufferingLoopActive) {
    bufferFramesImpl();
    if (bufferingLoopActive) bufferingCondition.wait(lock);
  }

  // note show some log here
}

void ImageLogReader::bufferFramesImpl() {
  if (int(nextBufferIndex) - minBuffered + 1 > int(currentFrame)) return;
  for (unsigned i = 0; i < 15 && nextBufferIndex < frames.size(); ++i, ++nextBufferIndex) {
    frames[nextBufferIndex] = loadFrameFromDrive(nextBufferIndex);
  }

  std::cout<<"\nLog : After buffer frames num : "<<int(nextBufferIndex)<<std::endl;

  # ifdef WAYNE_DEBUG
  std::cout<<"\nLog : After buffer frames num : "<<int(nextBufferIndex)<<std::endl;
  # endif
}

FrameDataPointer ImageLogReader::loadFrameFromDrive(const size_t& index) {
  FrameDataPointer result = std::make_shared<FrameData>();

  // Get path to image files
  std::stringstream ss;
  ss << std::setw(indexW) << std::setfill('0') << index + startIndex;
  std::string indexStr = ss.str();

  std::string depthImagePath = depthImagesDir + depthPre + indexStr + depthExt;
  if (!boost::filesystem::exists(depthImagePath)) throw std::invalid_argument("Could not find depth-image file: " + depthImagePath);

  std::string rgbImagePath = file + colorPre + indexStr + colorExt;
  if (!boost::filesystem::exists(rgbImagePath)) throw std::invalid_argument("Could not find rgb-image file: " + rgbImagePath);

  // Load mask ids
  //std::string maskImagePath = maskImagesDir + maskPre + std::to_string(index);
  std::string maskImagePath = maskImagesDir + maskPre + indexStr;
  std::string maskDescrPath = maskImagePath + ".txt";
  maskImagePath += maskExt;
  if (hasMasksGT) {
    if (!boost::filesystem::exists(maskImagePath)) throw std::invalid_argument("Could not find mask-image file: " + maskImagePath);
    if (boost::filesystem::exists(maskDescrPath)) loadMaskIDs(maskDescrPath, &result->classIDs, &result->rois);
  }

  // Load RGB
  result->rgb = cv::imread(rgbImagePath);
  if (result->rgb.total() == 0) throw std::invalid_argument("Could not read rgb-image file.");
  result->flipColors();

  // Load Depth
  result->depth = cv::imread(depthImagePath, cv::IMREAD_UNCHANGED);
  if (result->depth.total() == 0) throw std::invalid_argument("Could not read depth-image file. (Empty)");
  if (result->depth.type() != CV_32FC1) {
    cv::Mat newDepth(result->depth.rows, result->depth.cols, CV_32FC1);
    if (result->depth.type() == CV_32FC3) {
      unsigned depthIdx = 0;
      for (int i = 0; i < result->depth.rows; ++i) {
        cv::Vec3f* pixel = result->depth.ptr<cv::Vec3f>(i);
        for (int j = 0; j < result->depth.cols; ++j) ((float*)newDepth.data)[depthIdx++] = pixel[j][0];
      }

    } else if (result->depth.type() == CV_16UC1) {
      //std::cout << "Warning -- your depth scale is likely to mismatch. Check ImageLogReader.cpp!" << std::endl;
      unsigned depthIdx = 0;
      for (int i = 0; i < result->depth.rows; ++i) {
        unsigned short* pixel = result->depth.ptr<unsigned short>(i);
        for (int j = 0; j < result->depth.cols; ++j) ((float*)newDepth.data)[depthIdx++] = 0.001f * pixel[j];
        //for (int j = 0; j < result->depth.cols; ++j) ((float*)newDepth.data)[depthIdx++] = 0.0002f * pixel[j]; // FIXME
      }
    } else {
      throw std::invalid_argument("Unsupported depth-files: " + cvTypeToString(result->depth.type()));
    }
    result->depth = newDepth;
  }

  // Load Mask
  if (hasMasksGT && (index < maxMasks)) {
    result->mask = cv::imread(maskImagePath, cv::IMREAD_GRAYSCALE);
    if (result->mask.total() != result->rgb.total()) throw std::invalid_argument("Could not read mask-image file.");
    if (!result->mask.isContinuous() || result->mask.type() != CV_8UC1) throw std::invalid_argument("Incompatible mask image.");
  }

  result->timestamp = index * 1000.0f / rateHz;
  result->index = index;

  # ifdef WAYNE_DEBUG
  std::cout<<"\nLog : Imagelog results have been returned.\n";
  # endif

  return result;
}

FrameDataPointer ImageLogReader::getFrameData() {
  // assert(frames[currentFrame] != 0);
  if (currentFrame < 0) return NULL;

  bool bufferFail = false;
  while (!frames[currentFrame] || frames[currentFrame]->depth.total() == 0) {
    usleep(1);
    bufferFail = true;
  }
  if (bufferFail) std::cout << "Buffering failure." << std::endl;
  return frames[currentFrame];
}

void ImageLogReader::loadMaskIDs(const std::string &descrFile, std::vector<int>* outClassIds, std::vector<cv::Rect>* outROIs) const {
    assert(outClassIds->size() == 0 && outROIs->size() == 0);
    std::ifstream file(descrFile);
    std::string item, line;
    outClassIds->push_back(0); // Mask==0 ist always background
    std::getline(file, line);
    std::stringstream ss(line);
    while (getline(ss, item, ' ')) if(item.size() > 0) outClassIds->push_back(stoi(item));

    // get bounding-boxes
    while (std::getline(file, line)){
        std::istringstream iss(line);
        int a, b, c, d;
        if (!(iss >> a >> b >> c >> d))
            throw std::invalid_argument("Extracting bounding-box failed.");
        outROIs->push_back(cv::Rect(b,a,d-b,c-a));
    }
    if(outROIs->size()>0 && outROIs->size()!=outClassIds->size()-1) throw std::invalid_argument("Bounding-boxes provided, but number does not match class ids.");
}

int ImageLogReader::getNumFrames() { return numFrames; }

bool ImageLogReader::hasMore() { return currentFrame + 1 < numFrames; }

bool ImageLogReader::rewind() {
  assert(0 && "rewind");

  return false;
}

max_stars_repo_name: Wayne-Mai/DynSLAM

max_issues_repo_name: Wayne-Mai/DynSLAM

max_forks_repo_name: Wayne-Mai/DynSLAM


text:
/**
 * @file program_options.hpp
 * @copyright Copyright 2019-2020 Tobias Hienzsch. MIT license.
 */

#pragma once

#include <boost/program_options.hpp>

#include "fmt/format.h"
#include "fmt/ostream.h"
namespace po = boost::program_options;

#include <cstdlib>

namespace tcvm
{

struct ProgramOptions
{
    static auto parse(int argc, char** argv, po::variables_map& outputVariableMap) -> bool
    {
        try
        {
            auto const* text = "tcc: tobante's crappy virtual machine";
            po::options_description desc(text);
            auto options = desc.add_options();
            options("help,h", "produce this help message");
            options("input,i", po::value<std::int64_t>(), "input argument");
            options("file,f", po::value<std::string>(), "binary file path");
            options("version,v", "print version string");

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

            if (outputVariableMap.count("help") != 0)
            {
                fmt::print("{}\n", desc);
                std::exit(0);
            }

            if (outputVariableMap.count("version") != 0)
            {
                fmt::print("{}\n", "0.1.0");
                std::exit(0);
            }
        }
        catch (std::exception& e)
        {
            fmt::print("error: {}\n", e.what());
            return false;
        }
        catch (...)
        {
            fmt::print("Exception of unknown type!\n");
            return false;
        }

        return true;
    }
};

}  // namespace tcvm

max_stars_repo_name: tobiashienzsch/tcc

max_issues_repo_name: tobiashienzsch/tcc

max_forks_repo_name: tobiashienzsch/tcc


text:
#include <iostream>
#include <gtest/gtest.h>

//Gauss Includes
#include <PhysicalSystem.h>
#include <MultiVector.h>
#include <PhysicalSystemParticles.h>
#include <World.h>
#include <Assembler.h>
#include <AssemblerParallel.h>
#include <Utilities.h>
#include <UtilitiesEigen.h>
#include <Assembler.h>
#include <AssemblerMVP.h>
#include <TimeStepperEulerImplicitLinear.h>
#include <ForceSpring.h>
#include <ConstraintFixedPoint.h>

//FEM Stuff
#include <Element.h>
#include <PhysicalSystemFEM.h>
#include <FEMIncludes.h>

//Eigen
#include <Eigen/Dense>
#include <Eigen/Sparse>

//CG Solver
#include <SolverCG.h>

using namespace Gauss;
using namespace ParticleSystem;

//Single Particle Tests
/*TEST (SingleParticleTest, Tests) {
    World<double, std::tuple<PhysicalSystemParticleSingle<double> *>, std::tuple<ForceSpring<double> *> > world;
    PhysicalSystemParticleSingle<double> *test =
    new PhysicalSystemParticleSingle<double>();
    world.addSystem(test);
    world.finalize();

    //check right amount of memory is reported and that position and velocity DOFS are in the right place
    //single particle global id of q and qdot = 0, state offset = 3
    //make sure world is taking up the correct pointer
    ASSERT_EQ(world.getSystemList().get<0>(0)->getQ().getGlobalId(), 0);
    ASSERT_EQ(world.getSystemList().get<0>(0)->getQDot().getGlobalId(), 0);

    //set State using offset state variable pointer
    double q[] = {0.2,5.6,4.2};
    double qDot[] = {7.6,3.1,2.9};

    ASSERT_EQ(3, world.getState().stateSize(0));
    ASSERT_EQ(3, world.getState().stateSize(1));

    world.getState().setState<0>(q, 3);
    world.getState().setState<1>(qDot, 3);

    ASSERT_EQ(world.getState()[0],0.2);
    ASSERT_EQ(world.getState()[1],5.6);
    ASSERT_EQ(world.getState()[2],4.2);

    ASSERT_EQ(world.getState()[3],7.6);
    ASSERT_EQ(world.getState()[4],3.1);
    ASSERT_EQ(world.getState()[5],2.9);

    std::pair<double *, unsigned int> ptr = world.getState().getStatePtr();

    ASSERT_EQ(6, ptr.second);

    Eigen::Map<Eigen::VectorXd> eigenMap(ptr.first, ptr.second);

    //Test Setting and reading state with an Eigen Map
    Eigen::VectorXd testVec(6);
    testVec[0] = 1.99;
    testVec[1] = 67.22;
    testVec[2] = 22.44;
    testVec[3] = 34.23;
    testVec[4] = 187.26;
    testVec[5] = 4001.12;

    eigenMap = testVec;

    ASSERT_EQ(world.getState()[0],1.99);
    ASSERT_EQ(world.getState()[1],67.22);
    ASSERT_EQ(world.getState()[2],22.44);

    ASSERT_EQ(world.getState()[3],34.23);
    ASSERT_EQ(world.getState()[4],187.26);
    ASSERT_EQ(world.getState()[5],4001.12);

    //Test Setting and reading state through dofs
    std::pair<double *, unsigned int> qPtr = world.getSystemList().get<0>(0)->getQ().getPtr(world.getState());
    std::pair<double *, unsigned int> qDotPtr = world.getSystemList().get<0>(0)->getQDot().getPtr(world.getState());

    //set position DOF and check
    Eigen::Map<Eigen::Vector3d> qMap(qPtr.first, qPtr.second);
    Eigen::Map<Eigen::Vector3d> qDotMap(qDotPtr.first, qDotPtr.second);

    qMap[0] = 4534.4;
    qMap[1] = 43573.1;
    qMap[2] = 3570.76;

    ASSERT_EQ(4534.4, world.getState()[0]);
    ASSERT_EQ(43573.1, world.getState()[1]);
    ASSERT_EQ(3570.76, world.getState()[2]);

    ASSERT_EQ(34.23, world.getState()[3]);
    ASSERT_EQ(187.26, world.getState()[4]);
    ASSERT_EQ(4001.12, world.getState()[5]);

    qDotMap[0] = 47384.4;
    qDotMap[1] = 423473.1;
    qDotMap[2] = 2424.76;

    //set Velocity DOF and check
    ASSERT_EQ(4534.4, world.getState()[0]);
    ASSERT_EQ(43573.1, world.getState()[1]);
    ASSERT_EQ(3570.76, world.getState()[2]);

    ASSERT_EQ(47384.4, world.getState()[3]);
    ASSERT_EQ(423473.1, world.getState()[4]);
    ASSERT_EQ(2424.76, world.getState()[5]);

    //Test the assembler
    Assembler<double, AssemblerImplEigenSparseMatrix> testAssembler;
    Eigen::SparseMatrix<double> testMat;
    Eigen::SparseMatrix<double> resultMat(3,3);
    test->getImpl().setMass(22.0);

    resultMat.setIdentity();
    resultMat *= test->getImpl().getMass();

    ASSEMBLEMAT(world, testAssembler, getNumQDotDOFs, getNumQDotDOFs,getMassMatrix);

    //testAssembler.init(world.getNumQDotDOFs(), world.getNumQDotDOFs());
    //forEach(world.getSystemList(), [&world, &testAssembler](auto a) {
      //  a->getMassMatrix(testAssembler, world.getState());
    //});

    testAssembler.finalize();

    ASSERT_EQ(resultMat.valuePtr()[0], testAssembler.getImpl().getMatrix().valuePtr()[0]);
    ASSERT_EQ(resultMat.valuePtr()[1], testAssembler.getImpl().getMatrix().valuePtr()[1]);
    ASSERT_EQ(resultMat.valuePtr()[2], testAssembler.getImpl().getMatrix().valuePtr()[2]);

}

TEST (SingleParticleTest, ImplicitIntegratorTest) {

    //This is broken for now, I pulled gravity from the integrator
    //Start at (0, 5.9,0) with initial velocity (0, -1, 0) check that after one second we're at (0,0,0)
    World<double, std::tuple<PhysicalSystemParticleSingle<double> *>, std::tuple<ForceSpring<double> *> > world;
    PhysicalSystemParticleSingle<double> *test =
    new PhysicalSystemParticleSingle<double>();
    world.addSystem(test);
    world.finalize();

    //Initial State
    Eigen::Map<Eigen::VectorXd> state = mapStateEigen(world);
    state.setZero();
    state[1] = 5.9;
    state[4] = -1.0;

    //Integrate
    TimeStepperEulerImplictLinear<double, Assembler<double, AssemblerImplEigenSparseMatrix>,Assembler<double, AssemblerImplEigenVector> > stepper(0.01);
    for(unsigned int ii=0; ii<10; ++ii) {
        stepper.step(world);
    }

    //Check
    ASSERT_EQ(0, state[0]);
    ASSERT_LE(fabs(state[1]-5.7461), 1e-5);
    ASSERT_EQ(0, state[2]);

    ASSERT_EQ(0, state[3]);
    ASSERT_LE(fabs(state[4]-(-1.98)), 1e-5); //This is failing currently because I removed gravity from the integrator (I want to replace it with a force)
    ASSERT_EQ(0, state[5]);
}

TEST(FEM, InitLinearFEM) {

    //std::array<DOFBase *, 8> dofs;
    //FEM::Element<double, 4, FEM::QuadratureExact, FEM::EnergyKineticNonLumped, FEM::EnergyPotentialNone, FEM::ShapeFunctionLinearTet> femElement(NULL, NULL, dofs);

    //Single tetrahedra mesh
    Eigen::MatrixXd V(4,3);
    Eigen::MatrixXi F(1,4);

    V << 1.00, 1.00, 1.00,
         2.00, 1.00, 1.00,
         1.00, 2.00, 1.00,
         1.00, 1.00, 2.00;

    F<<1, 2, 3, 0;

    FEM::PhysicalSystemFEM<double, LinearTet> fem(V, F);

}*/

TEST(MVP, TestMVP) {

    using namespace Gauss;
    using namespace FEM;

    typedef PhysicalSystemFEM<double, LinearTet> FEMLinearTets;

    typedef World<double, std::tuple<FEMLinearTets *>, std::tuple<ForceSpring<double> *>, std::tuple<ConstraintFixedPoint<double> *> > MyWorld;

    //init FEM system
    //Setup Physics
    MyWorld world;

    //new code -- load tetgen files
    Eigen::MatrixXd V;
    Eigen::MatrixXi F;

    readTetgen(V, F, dataDir()+"/meshesTetgen/Beam/Beam.node", dataDir()+"/meshesTetgen/Beam/Beam.ele");

    FEMLinearTets *test = new FEMLinearTets(V,F);

    world.addSystem(test);
    fixDisplacementMin(world, test);
    world.finalize(); //After this all we're ready to go (clean up the interface a bit later)

    auto q = mapStateEigen(world);
    q.setZero();

    //test using stiffness matrix
    //explicit assembly
    AssemblerEigenSparseMatrix<double> assembler;
    ASSEMBLEMATINIT(assembler, world.getNumQDotDOFs(), world.getNumQDotDOFs());
    ASSEMBLELIST(assembler, world.getSystemList(), getStiffnessMatrix);
    ASSEMBLELIST(assembler, world.getForceList(), getStiffnessMatrix);
    ASSEMBLEEND(assembler);

    AssemblerMVPEigen<double> assemblerMVP;
    Eigen::VectorXd bAssembled;
    Eigen::VectorXd x;

    for(unsigned int ii=0; ii<100; ++ii) {
        x = 10.0*Eigen::MatrixXd::Random(world.getNumQDotDOFs(),1);

        Eigen::VectorXd bAssembled = (*assembler)*x;

        //compare mvp evaluated with random vector to assembly free MVP
        ASSEMBLEMATINIT(assemblerMVP, world.getNumQDotDOFs(), world.getNumQDotDOFs());
        assemblerMVP.getImpl().setX(x);

        //multiplying is happening during assembly (neat huh ? )
        ASSEMBLELIST(assemblerMVP, world.getSystemList(), getStiffnessMatrix);
        ASSEMBLELIST(assemblerMVP, world.getForceList(), getStiffnessMatrix);
        ASSEMBLEEND(assemblerMVP);

        double tol = 1e-8; //we'll consider this close enough

        ASSERT_LE((bAssembled - *assemblerMVP).norm() / x.norm(), tol);
    }

}

// TODO(lawson 19/07/17): Implement version without PARDISO?
#ifdef GAUSS_PARDISO
TEST(MVP, TestCG) {

    //Test CG vs. Direct Solve

    //Form implicit integration matrix solve against some random vectors, check CG vs direct solve
    using namespace FEM;

    typedef PhysicalSystemFEM<double, LinearTet> FEMLinearTets;

    typedef World<double, std::tuple<FEMLinearTets *>, std::tuple<ForceSpring<double> *>, std::tuple<ConstraintFixedPoint<double> *> > MyWorld;

    //init FEM system
    //Setup Physics
    MyWorld world;

    //new code -- load tetgen files
    Eigen::MatrixXd V;
    Eigen::MatrixXi F;

    readTetgen(V, F, dataDir()+"/meshesTetgen/Beam/Beam.node", dataDir()+"/meshesTetgen/Beam/Beam.ele");

    FEMLinearTets *test = new FEMLinearTets(V,F);

    world.addSystem(test);
    fixDisplacementMin(world, test);
    world.finalize(); //After this all we're ready to go (clean up the interface a bit later)

    auto q = mapStateEigen(world);
    q.setZero();

    //test using stiffness matrix
    //explicit assembly
    AssemblerEigenSparseMatrix<double> M, K;
    ASSEMBLEMATINIT(M, world.getNumQDotDOFs(), world.getNumQDotDOFs());
    ASSEMBLELIST(M, world.getSystemList(), getMassMatrix);
    ASSEMBLEEND(M);

    ASSEMBLEMATINIT(K, world.getNumQDotDOFs(), world.getNumQDotDOFs());
    ASSEMBLELIST(K, world.getSystemList(), getStiffnessMatrix);
    ASSEMBLELIST(K, world.getForceList(), getStiffnessMatrix);
    ASSEMBLEEND(K);

    //random force vector
    double dt = 0.01;
    Eigen::VectorXd f;
    Eigen::VectorXd x;
    Eigen::SparseMatrix<double, Eigen::RowMajor> A = ((*M) + dt*dt*(*K)).eval();
    f = 10.0*Eigen::MatrixXd::Random(world.getNumQDotDOFs(),1);
    x = 0*f;

    SolverPardiso<Eigen::SparseMatrix<double, Eigen::RowMajor> > direct;
    direct.solve(A,f);

    SolverCG<double, Eigen::VectorXd> pcg(1e-8);

    std::cout<<"CG\n";
    pcg.solve(x, [&A](auto &y)->auto {return A*y;}, f, 1000000000);

    double tol=1e-10;

    ASSERT_LE((x-direct.getX()).norm()/f.norm(), tol);
}
#endif

// TODO(lawson 19/07/17): Implement version without PARDISO?
#ifdef GAUSS_PARDISO
TEST(MVP, TestCG2) {

    //Test Assembly free CG vs. Direct Solve
    using namespace FEM;

    typedef PhysicalSystemFEM<double, LinearTet> FEMLinearTets;

    typedef World<double, std::tuple<FEMLinearTets *>, std::tuple<ForceSpring<double> *>, std::tuple<ConstraintFixedPoint<double> *> > MyWorld;

    //init FEM system
    //Setup Physics
    MyWorld world;

    //new code -- load tetgen files
    Eigen::MatrixXd V;
    Eigen::MatrixXi F;

    readTetgen(V, F, dataDir()+"/meshesTetgen/Beam/Beam.node", dataDir()+"/meshesTetgen/Beam/Beam.ele");

    FEMLinearTets *test = new FEMLinearTets(V,F);

    world.addSystem(test);
    fixDisplacementMin(world, test);
    world.finalize(); //After this all we're ready to go (clean up the interface a bit later)

    auto q = mapStateEigen(world);
    q.setZero();

    //test using stiffness matrix
    //explicit assembly
    AssemblerEigenSparseMatrix<double> M, K;
    ASSEMBLEMATINIT(M, world.getNumQDotDOFs(), world.getNumQDotDOFs());
    ASSEMBLELIST(M, world.getSystemList(), getMassMatrix);
    ASSEMBLEEND(M);

    ASSEMBLEMATINIT(K, world.getNumQDotDOFs(), world.getNumQDotDOFs());
    ASSEMBLELIST(K, world.getSystemList(), getStiffnessMatrix);
    ASSEMBLELIST(K, world.getForceList(), getStiffnessMatrix);
    ASSEMBLEEND(K);

    //random force vector
    double dt = 0.01;
    Eigen::VectorXd f;
    Eigen::VectorXd x;
    Eigen::SparseMatrix<double, Eigen::RowMajor> A = ((*M) + dt*dt*(*K)).eval();
    f = 10.0*Eigen::MatrixXd::Random(world.getNumQDotDOFs(),1);
    x = 0*f;

    SolverPardiso<Eigen::SparseMatrix<double, Eigen::RowMajor> > direct;
    direct.solve(A,f);

    SolverCG<double, Eigen::VectorXd> pcg(1e-8);

    #ifdef GAUSS_OPENMP
    AssemblerParallel<double, AssemblerMVPEigen<double> > Mv, Kv;
    #else
    AssemblerMVPEigen<double> Mv, Kv;
    #endif

    //assembly-free mvp
    auto mvp = [&world, &Mv, &Kv, &dt](auto &y) {
        ASSEMBLEMATINIT(Kv, world.getNumQDotDOFs(), world.getNumQDotDOFs());
        Kv.getImpl()*=y;

        //multiplying is happening during assembly (neat huh ? )
        ASSEMBLELIST(Kv, world.getSystemList(), getStiffnessMatrix);
        ASSEMBLELIST(Kv, world.getForceList(), getStiffnessMatrix);
        ASSEMBLEEND(Kv);

        ASSEMBLEMATINIT(Mv, world.getNumQDotDOFs(), world.getNumQDotDOFs());
        Mv.getImpl()*=y;

        //multiplying is happening during assembly (neat huh ? )
        ASSEMBLELIST(Mv, world.getSystemList(), getMassMatrix);
        ASSEMBLELIST(Mv, world.getForceList(), getMassMatrix);
        ASSEMBLEEND(Mv);

        return (*Mv) + dt*dt*(*Kv);
    };

    std::cout<<"CG\n";
    pcg.solve(x, mvp, f, 100000000);

    double tol=1e-10;

    std::cout<<f.norm()<<"\n";
    ASSERT_LE((x-direct.getX()).norm()/f.norm(), tol);

}
#endif

int main(int argc, char **argv) {
    std::cout<<"Start Tests ..... \n";

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

    //return 1;
}

max_forks_repo_name: edwinchenyj/GAUSS


text: #include <boost/type_traits/add_const.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**
 * \file
 * \copyright
 * Copyright (c) 2012-2022, OpenGeoSys Community (http://www.opengeosys.org)
 *            Distributed under a Modified BSD License.
 *              See accompanying file LICENSE.txt or
 *              http://www.opengeosys.org/project/license
 */

#include "LinearElasticOrthotropic.h"

#include <Eigen/LU>

#include "MaterialLib/MPL/Utils/GetSymmetricTensor.h"

namespace MPL = MaterialPropertyLib;

namespace MaterialLib
{
namespace Solids
{
template <int DisplacementDim>
std::optional<std::tuple<typename MechanicsBase<DisplacementDim>::KelvinVector,
                         std::unique_ptr<typename MechanicsBase<
                             DisplacementDim>::MaterialStateVariables>,
                         typename MechanicsBase<DisplacementDim>::KelvinMatrix>>
LinearElasticOrthotropic<DisplacementDim>::integrateStress(
    MaterialPropertyLib::VariableArray const& variable_array_prev,
    MaterialPropertyLib::VariableArray const& variable_array, double const t,
    ParameterLib::SpatialPosition const& x, double const /*dt*/,
    typename MechanicsBase<DisplacementDim>::
        MaterialStateVariables const& /*material_state_variables*/) const
{
    auto const& eps_m = std::get<MPL::SymmetricTensor<DisplacementDim>>(
        variable_array[static_cast<int>(MPL::Variable::mechanical_strain)]);
    auto const& eps_m_prev = std::get<MPL::SymmetricTensor<DisplacementDim>>(
        variable_array_prev[static_cast<int>(
            MPL::Variable::mechanical_strain)]);
    auto const& sigma_prev = std::get<MPL::SymmetricTensor<DisplacementDim>>(
        variable_array_prev[static_cast<int>(MPL::Variable::stress)]);
    auto const& T = std::get<double>(
        variable_array_prev[static_cast<int>(MPL::Variable::temperature)]);

    KelvinMatrix C = getElasticTensor(t, x, T);

    KelvinVector sigma = sigma_prev + C * (eps_m - eps_m_prev);

    return {std::make_tuple(
        sigma,
        std::make_unique<
            typename MechanicsBase<DisplacementDim>::MaterialStateVariables>(),
        C)};
}

template <int DisplacementDim>
typename LinearElasticOrthotropic<DisplacementDim>::KelvinMatrix
LinearElasticOrthotropic<DisplacementDim>::getElasticTensor(
    double const t, ParameterLib::SpatialPosition const& x,
    double const /*T*/) const
{
    using namespace MathLib::KelvinVector;

    auto const& mp = _mp.evaluate(t, x);
    auto const E = [&mp](int const i) { return mp.E(i); };
    auto const G = [&mp](int const i, int const j) { return mp.G(i, j); };
    auto const nu = [&mp](int const i, int const j) { return mp.nu(i, j); };

    KelvinMatrixType<3> S_ortho = KelvinMatrixType<3>::Zero();
    // clang-format off
    S_ortho.template topLeftCorner<3, 3>() <<
               1. / E(1), -nu(2, 1) / E(2), -nu(3, 1) / E(3),
        -nu(1, 2) / E(1),        1. / E(2), -nu(3, 2) / E(3),
        -nu(1, 3) / E(1), -nu(2, 3) / E(2),        1. / E(3);

    S_ortho.template bottomRightCorner<3, 3>().diagonal() <<
        1. / (2 * G(1, 2)),
        1. / (2 * G(2, 3)),
        1. / (2 * G(1, 3));
    // clang-format on

    KelvinMatrixType<3> const C_ortho = S_ortho.inverse();
    auto const Q = [this, &x]() -> KelvinMatrixType<3>
    {
        if (!_local_coordinate_system)
        {
            return KelvinMatrixType<3>::Identity();
        }
        Eigen::Matrix3d R = Eigen::Matrix3d::Identity();
        R.template topLeftCorner<DisplacementDim, DisplacementDim>().noalias() =
            _local_coordinate_system->transformation<DisplacementDim>(x);
        return fourthOrderRotationMatrix(R);
    }();

    // Rotate the forth-order tenser in Kelvin mapping with Q*C_ortho*Q^T and
    // return the top left corner block of size 4x4 for two-dimensional case or
    // the full 6x6 matrix is returned in the three-dimensional case.
    return (Q * C_ortho * Q.transpose())
        .template topLeftCorner<kelvin_vector_dimensions(DisplacementDim),
                                kelvin_vector_dimensions(DisplacementDim)>();
}

template class LinearElasticOrthotropic<2>;
template class LinearElasticOrthotropic<3>;

}  // namespace Solids
}  // namespace MaterialLib

max_stars_repo_name: garibay-j/ogs

max_issues_repo_name: garibay-j/ogs

max_forks_repo_name: garibay-j/ogs


text:
/*
 * Copyright 2018, LAAS-CNRS
 * Author: Steve Tonneau
 */

#ifndef BEZIER_COM_TRAJ_LIB_DATA_H
#define BEZIER_COM_TRAJ_LIB_DATA_H

#include <hpp/bezier-com-traj/local_config.hh>
#include <hpp/bezier-com-traj/flags.hh>
#include <hpp/bezier-com-traj/definitions.hh>
#include <hpp/bezier-com-traj/utils.hh>
#include <hpp/bezier-com-traj/solver/solver-abstract.hpp>
#include <hpp/spline/bezier_curve.h>
#include <hpp/centroidal-dynamics/centroidal_dynamics.hh>
#include <Eigen/Dense>

#include <vector>

namespace bezier_com_traj
{
    /**
    * @brief Contact data contains all the contact information
    * relative to a contact phase: contact points and normals
    * (within Equilibrium object), as well as any additional
    * kinematic and angular constraints.
    */
    struct BEZIER_COM_TRAJ_DLLAPI ContactData
    {
        ContactData()
            : contactPhase_(0)
            , Kin_(Eigen::Matrix3d::Zero())
            , kin_(VectorX::Zero(0))
            , Ang_(Eigen::Matrix3d::Zero())
            , ang_(VectorX::Zero(0)) {}

        ContactData(const ContactData& other)
            : contactPhase_(new centroidal_dynamics::Equilibrium(*(other.contactPhase_)))
            , Kin_(other.Kin_)
            , kin_(other.kin_)
            , Ang_(other.Ang_)
            , ang_(other.ang_){}

        ContactData(centroidal_dynamics::Equilibrium* contactPhase)
            : contactPhase_(contactPhase)
            , Kin_(Eigen::Matrix3d::Zero())
            , kin_(VectorX::Zero(0))
            , Ang_(Eigen::Matrix3d::Zero())
            , ang_(VectorX::Zero(0)) {}
       ~ContactData(){}

       centroidal_dynamics::Equilibrium* contactPhase_;
       MatrixX3 Kin_; // inequality kinematic constraints
       VectorX  kin_;
       MatrixX3 Ang_; // inequality angular momentum constraints
       VectorX  ang_;
    };

    /**
    * @brief Used to define the constraints on the trajectory generation problem.
    * Flags are used to constrain initial and terminal com positions an derivatives.
    * Additionally, the maximum acceleration can be bounded.
    */
    struct BEZIER_COM_TRAJ_DLLAPI Constraints
    {
        Constraints()
            : flag_(INIT_POS | INIT_VEL | END_VEL | END_POS)
            , constraintAcceleration_(false)
            , maxAcceleration_(10.)
            , reduce_h_(1e-3) {}

        Constraints(ConstraintFlag flag)
            : flag_(flag)
            , constraintAcceleration_(false)
            , maxAcceleration_(10.)
            , reduce_h_(1e-3) {}

        ~Constraints(){}

        ConstraintFlag flag_;
        bool constraintAcceleration_;
        double maxAcceleration_;
        double reduce_h_;
    };

    /**
    * @brief Defines all the inputs of the problem:
    * Initial and terminal constraints, as well as selected
    * cost functions. Also,a list of ContactData defines the
    * different phases of the problem. While the method
    * can handle any phase greater than one, using more
    * than three phases is probably too constraining.
    */
    struct BEZIER_COM_TRAJ_DLLAPI ProblemData
    {
        ProblemData()
            : c0_ (point_t::Zero())
            ,dc0_ (point_t::Zero())
            ,ddc0_(point_t::Zero())
            ,j0_(point_t::Zero())
            , c1_ (point_t::Zero())
            ,dc1_ (point_t::Zero())
            ,ddc1_(point_t::Zero())
            ,j1_(point_t::Zero())
            ,useAngularMomentum_(false)
            ,costFunction_(ACCELERATION)
            ,representation_(DOUBLE_DESCRIPTION) {}

        std::vector<ContactData> contacts_;
        point_t  c0_,dc0_,ddc0_,j0_,c1_,dc1_,ddc1_,j1_;
        point_t  l0_;
        bool useAngularMomentum_;
        Constraints constraints_;
        CostFunction costFunction_;
        GIWCRepresentation representation_;
    };

    typedef solvers::ResultData ResultData;

    /**
    * @brief Specialized ResultData that computes the Bezier curves
    * corresponding to the computed trajectory
    */
    struct BEZIER_COM_TRAJ_DLLAPI ResultDataCOMTraj : public ResultData
    {
        ResultDataCOMTraj():
            ResultData()
          , c_of_t_(bezier_t::zero())
          , dL_of_t_(bezier_t::zero())
          , dc1_(point_t::Zero())
          , ddc1_(point_t::Zero()) {}
        ~ResultDataCOMTraj(){}

        bezier_t c_of_t_; // center of mass trajectory
        bezier_t dL_of_t_; // angular momentum derivative trajectory
        point_t dc1_; // terminal velocity
        point_t ddc1_; //terminal acceleration
    };
} // end namespace bezier_com_traj

#endif

ext: hh

max_stars_repo_name: jmirabel/hpp-bezier-com-traj

max_issues_repo_name: jmirabel/hpp-bezier-com-traj

max_forks_repo_name: jmirabel/hpp-bezier-com-traj


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
 *************************************************************/

#ifndef INCLUDED_SLIDESHOW_CURSORMANAGER_HXX
#define INCLUDED_SLIDESHOW_CURSORMANAGER_HXX

#include <sal/types.h>
#include <boost/shared_ptr.hpp>

/* Definition of CursorManager interface */

namespace slideshow
{
    namespace internal
    {

        /** Interface for handling the view cursor.

        	Classes implementing this interface interact with the
        	View, arbitrating access to the mouse cursor shape.
         */
        class CursorManager
        {
        public:
            virtual ~CursorManager() {}

            /** Request different cursor shape.

            	@param nCursorShape
                Shape ID of the new mouse cursor
             */
            virtual bool requestCursor( sal_Int16 nCursorShape ) = 0;

            /** Reset cursor to default one.

                This method resets the cursor to whatever default to
                manager deems appropriate.
             */
            virtual void resetCursor() = 0;
        };

        typedef ::boost::shared_ptr< CursorManager > CursorManagerSharedPtr;

    }
}

#endif /* INCLUDED_SLIDESHOW_CURSORMANAGER_HXX */

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
//  Copyright (c) 2007-2016 Hartmut Kaiser
//
//  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)

#if !defined(HPX_TRAITS_ACQUIRE_FUTURE_DEC_23_2014_0911AM)
#define HPX_TRAITS_ACQUIRE_FUTURE_DEC_23_2014_0911AM

#include <hpx/config.hpp>
#include <hpx/traits/is_future.hpp>
#include <hpx/traits/is_future_range.hpp>
#include <hpx/util/decay.hpp>

#include <boost/range/functions.hpp>
#include <boost/range/iterator_range.hpp>

#include <cstddef>
#include <iterator>
#include <type_traits>
#include <utility>
#include <vector>

namespace hpx { namespace traits
{
    namespace detail
    {
        template <typename T, typename Enable = void>
        struct acquire_future_impl;
    }

    template <typename T, typename Enable = void>
    struct acquire_future
      : detail::acquire_future_impl<typename util::decay<T>::type>
    {};

    struct acquire_future_disp
    {
        template <typename T>
        HPX_FORCEINLINE typename acquire_future<T>::type
        operator()(T && t) const
        {
            return acquire_future<T>()(std::forward<T>(t));
        }
    };

    namespace detail
    {
        template <typename T>
        struct acquire_future_impl<T,
            typename std::enable_if<
                !is_future_or_future_range<T>::value
            >::type>
        {
            typedef T type;

            template <typename T_>
            HPX_FORCEINLINE
            T operator()(T_ && value) const
            {
                return std::forward<T_>(value);
            }
        };

        template <typename R>
        struct acquire_future_impl<hpx::lcos::future<R> >
        {
            typedef hpx::lcos::future<R> type;

            HPX_FORCEINLINE hpx::lcos::future<R>
            operator()(hpx::lcos::future<R>& future) const
            {
                return std::move(future);
            }

            HPX_FORCEINLINE hpx::lcos::future<R>
            operator()(hpx::lcos::future<R>&& future) const
            {
                return std::move(future);
            }
        };

        template <typename R>
        struct acquire_future_impl<hpx::lcos::shared_future<R> >
        {
            typedef hpx::lcos::shared_future<R> type;

            HPX_FORCEINLINE hpx::lcos::shared_future<R>
            operator()(hpx::lcos::shared_future<R> future) const
            {
                return future;
            }
        };

        // Reserve sufficient space in the given vector if the underlying
        // iterator type of the given range allow calculating the size on O(1).
        template <typename Future, typename Range>
        HPX_FORCEINLINE
        void reserve_if_random_access(std::vector<Future>&, Range const&,
            std::false_type)
        {
        }

        template <typename Future, typename Range>
        HPX_FORCEINLINE
        void reserve_if_random_access(std::vector<Future>& v, Range const& r,
            std::true_type)
        {
            v.reserve(boost::size(r));
        }

        template <typename Range1, typename Range2>
        HPX_FORCEINLINE
        void reserve_if_random_access(Range1&, Range2 const&)
        {
            // do nothing if it's not a vector
        }

        template <typename Future, typename Range>
        HPX_FORCEINLINE
        void reserve_if_random_access(std::vector<Future>& v, Range const& r)
        {
            typedef typename std::iterator_traits<
                    typename Range::iterator
                >::iterator_category iterator_category;

            typedef std::is_same<
                    iterator_category, std::random_access_iterator_tag
                > is_random_access;

            reserve_if_random_access(v, r, is_random_access());
        }

        template <typename Container>
        HPX_FORCEINLINE
        void reserve_if_vector(Container&, std::size_t)
        {
        }

        template <typename Future>
        HPX_FORCEINLINE
        void reserve_if_vector(std::vector<Future>& v, std::size_t n)
        {
            v.reserve(n);
        }

        ///////////////////////////////////////////////////////////////////////
        template <typename Range>
        struct acquire_future_impl<Range,
            typename std::enable_if<
                traits::is_future_range<Range>::value
            >::type>
        {
            typedef typename traits::future_range_traits<Range>::future_type
                future_type;

            typedef Range type;

            HPX_FORCEINLINE Range
            operator()(Range&& futures) const
            {
                return std::move(futures);
            }

            template <typename Range_>
            HPX_FORCEINLINE Range
            operator()(Range_&& futures) const
            {
                Range values;
                detail::reserve_if_random_access(values, futures);

                std::transform(boost::begin(futures), boost::end(futures),
                    std::back_inserter(values), acquire_future_disp());

                return values;
            }
        };
    }
}}

#endif

max_stars_repo_name: brycelelbach/hpx

max_issues_repo_name: brycelelbach/hpx

max_forks_repo_name: brycelelbach/hpx


text:
/**********************************************************************
*  Copyright (c) 2008-2013, Alliance for Sustainable Energy.
*  All rights reserved.
*
*  This library is free software; you can redistribute it and/or
*  modify it under the terms of the GNU Lesser General Public
*  License as published by the Free Software Foundation; either
*  version 2.1 of the License, or (at your option) any later version.
*
*  This library is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*  Lesser General Public License for more details.
*
*  You should have received a copy of the GNU Lesser General Public
*  License along with this library; if not, write to the Free Software
*  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**********************************************************************/

#include <utilities/document/Text.hpp>
#include <utilities/document/Text_Impl.hpp>
#include <utilities/document/DocumentRegex.hpp>

#include <utilities/core/Containers.hpp>

#include <boost/foreach.hpp>
#include <boost/regex.hpp>
#include <boost/archive/archive_exception.hpp>

namespace openstudio {

namespace detail {

  Text_Impl::Text_Impl() {}

  Text_Impl::Text_Impl(const std::string& paragraph) : m_paragraphs(1u,paragraph) {}

  Text_Impl::Text_Impl(const std::vector<std::string>& paragraphs) : m_paragraphs(paragraphs) {}

  DocumentElement Text_Impl::clone() const {
    boost::shared_ptr<Text_Impl> impl(new Text_Impl(*this));
    return Text(impl).cast<DocumentElement>();
  }

  std::vector<std::string> Text_Impl::paragraphs() const { return m_paragraphs; }

  std::string Text_Impl::getParagraph(unsigned index) const {
    if (index >= numParagraphs()) {
      LOG_AND_THROW("Cannot return paragraph " << index << ", as there are only "
        << numParagraphs() << " in this Text object.");
    }
    return m_paragraphs[index];
  }

  // SETTERS

  void Text_Impl::clear() {
    m_paragraphs.clear();
  }

  void Text_Impl::replaceAll(const std::string& paragraph) {
    m_paragraphs = StringVector(1u,paragraph);
  }

  void Text_Impl::replaceAll(const std::vector<std::string>& paragraphs) {
    m_paragraphs = paragraphs;
  }

  void Text_Impl::replace(unsigned index, const std::string& paragraph) {
    unsigned n = numParagraphs();
    if (index > n) {
      LOG_AND_THROW("There is no paragraph at index " << index << " to replace.");
    }
    if (index == n) {
      LOG(Warn,"There is no paragraph at index " << index << ", appending new paragraph instead.");
      append(paragraph);
      return;
    }
    m_paragraphs[index] = paragraph;
  }

  void Text_Impl::append(const std::string& paragraph) {
    m_paragraphs.push_back(paragraph);
  }

  void Text_Impl::append(const std::vector<std::string>& paragraphs) {
    m_paragraphs.insert(m_paragraphs.end(),paragraphs.begin(),paragraphs.end());
  }

  void Text_Impl::insert(unsigned index, const std::string& paragraph) {
    unsigned n = numParagraphs();
    if (index > n) {
      LOG_AND_THROW("Cannot insert a paragraph at index " << index << ", because there are "
          << "currently " << n << " paragraphs in this Text object.");
    }
    if (index == n) {
      append(paragraph);
      return;
    }
    StringVector::iterator it = m_paragraphs.begin();
    for (unsigned i = 0; i < index; ++i, ++it) {}
    m_paragraphs.insert(it,paragraph);
  }

  void Text_Impl::erase(unsigned index) {
    if (index < numParagraphs()) {
      StringVector::iterator it = m_paragraphs.begin();
      for (unsigned i = 0; i < index; ++i, ++it) {}
      m_paragraphs.erase(it);
    }
  }

  unsigned Text_Impl::numParagraphs() const {
    return m_paragraphs.size();
  }

  std::string Text_Impl::print(DocumentFormat fmt) const {
    if (fmt == DocumentFormat::COUT) { return mf_printCOUT(); }
    if (fmt == DocumentFormat::LaTeX) { return mf_printLaTeX(); }
    if (fmt == DocumentFormat::XHTML) { return mf_printXHTML(); }
    return std::string();
  }

  std::ostream& Text_Impl::printToStream(std::ostream& os, DocumentFormat fmt) const {
    os << print(fmt);
    return os;
  }

  // PRIVATE

  std::string Text_Impl::mf_printCOUT() const {
    std::stringstream ss;
    BOOST_FOREACH(const std::string& str,m_paragraphs) {
      ss << std::endl
         << str << std::endl;
    }
    return ss.str();
  }

  std::string Text_Impl::mf_printLaTeX() const {
    std::stringstream ss;
    BOOST_FOREACH(const std::string& str,m_paragraphs) {
      ss << std::endl << formatText(str,DocumentFormat(DocumentFormat::LaTeX)) << std::endl;
    }
    return ss.str();
  }

  std::string Text_Impl::mf_printXHTML() const {
    std::stringstream ss;
    BOOST_FOREACH(const std::string& str,m_paragraphs) {
      ss << std::endl
         << "<p>" << std::endl
         << formatText(str,DocumentFormat(DocumentFormat::XHTML)) << std::endl
         << "</p>" << std::endl;
    }
    return ss.str();
  }

} // detail

Text::Text()
  : SectionElement(boost::shared_ptr<detail::Text_Impl>(new detail::Text_Impl()))
{}

Text::Text(const std::string& paragraph)
  : SectionElement(boost::shared_ptr<detail::Text_Impl>(new detail::Text_Impl(paragraph)))
{}

Text::Text(const std::vector<std::string>& paragraphs)
  : SectionElement(boost::shared_ptr<detail::Text_Impl>(new detail::Text_Impl(paragraphs)))
{}

std::vector<std::string> Text::paragraphs() const {
  return getImpl<detail::Text_Impl>()->paragraphs();
}

std::string Text::getParagraph(unsigned index) const {
  return getImpl<detail::Text_Impl>()->getParagraph(index);
}

void Text::clear() {
  getImpl<detail::Text_Impl>()->clear();
}

void Text::replaceAll(const std::string& paragraph) {
  return getImpl<detail::Text_Impl>()->replaceAll(paragraph);
}

void Text::replaceAll(const std::vector<std::string>& paragraphs) {
  getImpl<detail::Text_Impl>()->replaceAll(paragraphs);
}

void Text::replace(unsigned index, const std::string& paragraph) {
  getImpl<detail::Text_Impl>()->replace(index,paragraph);
}

void Text::append(const std::string& paragraph) {
  getImpl<detail::Text_Impl>()->append(paragraph);
}

void Text::append(const std::vector<std::string>& paragraphs) {
  getImpl<detail::Text_Impl>()->append(paragraphs);
}

void Text::insert(unsigned index, const std::string& paragraph) {
  getImpl<detail::Text_Impl>()->insert(index,paragraph);
}

void Text::erase(unsigned index) {
  getImpl<detail::Text_Impl>()->erase(index);
}

unsigned Text::numParagraphs() const {
  return getImpl<detail::Text_Impl>()->numParagraphs();
}

Text::Text(boost::shared_ptr<detail::Text_Impl> impl)
  : SectionElement(impl)
{}

} // openstudio

max_stars_repo_name: bobzabcik/OpenStudio

max_issues_repo_name: bobzabcik/OpenStudio

max_forks_repo_name: bobzabcik/OpenStudio


text:
#pragma once
#ifndef __FL_METIS_MANAGER_CONFIG_HPP
#define	__FL_METIS_MANAGER_CONFIG_HPP

///////////////////////////////////////////////////////////////////////////////
//
// Copyright Denys Misko <gdraal@gmail.com>, Final Level, 2014.
// Distributed under BSD (3-Clause) License (See
// accompanying file LICENSE)
//
// Description: Metis manager's server configuration class
///////////////////////////////////////////////////////////////////////////////

#include <boost/property_tree/ptree.hpp>

#include <string>
#include <vector>
#include "../global_config.hpp"
#include "socket.hpp"

namespace fl {
	namespace metis {
		using fl::network::Socket;

		const size_t MAX_BUF_SIZE = 300000;
		const size_t DEFAULT_MINIMUM_COPIES = 2;
		const size_t DEFAULT_MAX_CONNECTION_PER_STORAGE = 2;
		const size_t DEFAULT_AVERAGE_ITEM_SIZE = 32000;

		const TCacheLineIndex DEFAULT_ITEMS_IN_LINE = 32 * 1024;

		class Config : public GlobalConfig
		{
		public:
			Config(int argc, char *argv[]);
			const std::string &logPath() const
			{
				return _logPath;
			}
			int logLevel() const
			{
				return _logLevel;
			}
			typedef uint32_t TStatus;
			static const TStatus ST_LOG_STDOUT = 0x1;
			const bool isLogStdout() const
			{
				return _status & ST_LOG_STDOUT;
			}
			const TServerID serverID() const
			{
				return _serverID;
			}
			bool initNetwork();
			Socket &cmdSocket()
			{
				return _cmdSocket;
			}
			Socket &webSocket()
			{
				return _webSocket;
			}
			Socket &webDavSocket()
			{
				return _webDavSocket;
			}

			const int cmdTimeout() const
			{
				return _cmdTimeout;
			}

			const int webTimeout() const
			{
				return _webTimeout;
			}

			const int webDavTimeout() const
			{
				return _webDavTimeout;
			}
			size_t webWorkerQueueLength() const
			{
				return _webWorkerQueueLength;
			}
			size_t webWorkers() const
			{
				return _webWorkers;
			}

			size_t cmdWorkerQueueLength() const
			{
				return _cmdWorkerQueueLength;
			}
			size_t cmdWorkers() const
			{
				return _cmdWorkers;
			}
			size_t minimumCopies() const
			{
				return _minimumCopies;
			}
			size_t maxConnectionPerStorage() const
			{
				return _maxConnectionPerStorage;
			}
			size_t averageItemSize() const
			{
				return _averageItemSize;
			}
			size_t cacheSize() const
			{
				return _cacheSize;
			}
			size_t itemHeadersCacheSize() const
			{
				return _itemHeadersCacheSize;
			}
			TCacheLineIndex itemsInLine() const
			{
				return _itemsInLine;
			}
			uint32_t minHitsToCache() const
			{
				return _minHitsToCache;
			}
		private:
			void _usage();
			void _loadFromDB();
			void _loadCacheParams();

			TServerID _serverID;
			TStatus _status;
			std::string _logPath;
			int _logLevel;

			std::string _cmdIp;
			uint32_t _cmdPort;
			Socket _cmdSocket;

			std::string _webDavIp;
			uint32_t _webDavPort;
			Socket _webDavSocket;

			std::string _webIp;
			uint32_t _webPort;
			Socket _webSocket;

			int _cmdTimeout;
			int _webTimeout;
			int _webDavTimeout;
			size_t _webWorkerQueueLength;
			size_t _webWorkers;

			size_t _cmdWorkerQueueLength;
			size_t _cmdWorkers;

			size_t _bufferSize;
			size_t _maxFreeBuffers;

			size_t _minimumCopies;
			size_t _maxConnectionPerStorage;

			size_t _averageItemSize;

			size_t _cacheSize;
			size_t _itemHeadersCacheSize;
			TCacheLineIndex _itemsInLine;
			uint32_t _minHitsToCache;
		};
	}
}

#endif // __FL_METIS_MANAGER_CONFIG_HPP

max_stars_repo_name: FinalLevel/metis

max_issues_repo_name: FinalLevel/metis

max_forks_repo_name: FinalLevel/metis