text:
#include "data_interface.h"

#include <rosbag/view.h>

#include <boost/filesystem/path.hpp>

using namespace data;

// CONSTRUCTORS
data_interface::data_interface()
{
    // Create new bag instance.
    data_interface::m_bag = std::make_shared<rosbag::Bag>();
}

// BAG METHODS
bool data_interface::load_bag(std::string bag_path)
{
    // Try to load the bag file.
    try
    {
        // Close any open bag files.
        data_interface::m_bag->close();
        // Open the new bag file.
        data_interface::m_bag->open(bag_path, rosbag::bagmode::Read);
    }
    catch(const std::exception& error)
    {
        ROS_ERROR_STREAM("failed to load bag file (" << error.what() << ")");
        return false;
    }

    // Clear any existing datasets.
    data_interface::m_datasets.clear();

    return true;
}
std::string data_interface::bag_name() const
{
    boost::filesystem::path bag_path(data_interface::m_bag->getFileName());
    return bag_path.filename().string();
}
std::set<std::string> data_interface::bag_topics() const
{
    // Create set for tracking unique topic names.
    std::set<std::string> unique_topics;

    if(data_interface::m_bag->isOpen())
    {
        // Use a view to get the connections.
        rosbag::View view(*data_interface::m_bag);
        auto connections = view.getConnections();
        // Iterate through the connections to get the topic names.
        for(auto connection = connections.cbegin(); connection != connections.cend(); ++connection)
        {
            unique_topics.insert((*connection)->topic);
        }
    }

    return unique_topics;
}

// CANDIDATE METHODS
std::shared_ptr<candidate_topic_t> data_interface::get_candidate_topic(const std::string& topic_name) const
{
    // Check if bag file is open.
    if(!data_interface::m_bag->isOpen())
    {
        return nullptr;
    }

    // Use a view to get the connection info for the topic.
    rosbag::View view(*data_interface::m_bag, rosbag::TopicQuery(topic_name));
    auto connections = view.getConnections();

    // Check if the topic exists in the bag.
    if(connections.empty())
    {
        return nullptr;
    }

    // Build a temporary introspector to get the definition tree for the topic.
    auto connection = connections.front();
    message_introspection::introspector introspector;
    introspector.new_message_type(connection->datatype, connection->msg_def, connection->md5sum);

    // Create an output candidate.
    auto output = std::make_shared<candidate_topic_t>();
    output->topic_name = topic_name;
    output->definition_tree = introspector.definition_tree();

    return output;
}

// DATASET MANAGEMENT
bool data_interface::add_dataset(const std::shared_ptr<candidate_field_t>& candidate_field)
{
    // Check if the dataset already exists, and create a set of names.
    // NOTE: Can do this because there won't be a lot of datasets.
    std::unordered_set<std::string> names;
    for(uint32_t i = 0; i < data_interface::m_datasets.size(); ++i)
    {
        // Get reference to dataset.
        auto& entry = data_interface::m_datasets[i];

        // Check if candidate dataset already exists.
        if(entry->topic_name().compare(candidate_field->topic_name()) == 0 && entry->field_path().compare(candidate_field->full_path()) == 0)
        {
            // Dataset already exists, return false.
            return false;
        }

        // Add dataset's name to unique list.
        names.insert(entry->name());
    }

    // Find a new name for the dataset.
    uint32_t name_number = 0;
    std::string dataset_name = "";
    bool name_found = false;
    while(!name_found)
    {
        dataset_name = "var_" + std::to_string(name_number++);
        name_found = names.count(dataset_name) == 0;
    }

    // Create a new dataset.
    auto dataset = std::make_shared<data::dataset>(data_interface::m_bag,
                                                   dataset_name,
                                                   candidate_field->topic_name(),
                                                   candidate_field->full_path(),
                                                   std::bind(&data_interface::dataset_notifier, this, std::placeholders::_1));

    // Add the dataset to the end of the deque.
    data_interface::m_datasets.push_back(dataset);

    // Begin load operation.
    dataset->load();

    return true;
}
bool data_interface::remove_dataset(uint32_t index)
{
    // Check if specified index exists.
    if(index >= data_interface::m_datasets.size())
    {
        return false;
    }

    // Cancel any operations the dataset is running.
    data_interface::m_datasets[index]->cancel();

    // Remove the dataset at the sepcified index.
    data_interface::m_datasets.erase(data_interface::m_datasets.begin() + index);

    return true;
}
bool data_interface::move_dataset(uint32_t old_index, uint32_t new_index)
{
    // Validate old and new indices.
    if(old_index >= data_interface::m_datasets.size() || new_index >= data_interface::m_datasets.size())
    {
        return false;
    }

    // Grab copy of dataset pointer at old index.
    auto move_dataset = data_interface::m_datasets[old_index];

    // Erase from old index.
    data_interface::m_datasets.erase(data_interface::m_datasets.begin() + old_index);

    // Insert at new index.
    data_interface::m_datasets.insert(data_interface::m_datasets.begin() + new_index, move_dataset);

    return true;
}
void data_interface::clear_datasets()
{
    // Iterate through all datasets to cancel and running operations.
    for(auto entry = data_interface::m_datasets.begin(); entry != data_interface::m_datasets.end(); ++entry)
    {
        (*entry)->cancel();
    }

    // Clear all datasets.
    data_interface::m_datasets.clear();
}

// DATASET ACCESS
uint32_t data_interface::n_datasets() const
{
    return data_interface::m_datasets.size();
}
std::shared_ptr<dataset> data_interface::get_dataset(uint32_t index) const
{
    return data_interface::m_datasets[index];
}

// CALLBACKS
void data_interface::dataset_notifier(uint64_t address)
{
    // Find the index of the sending dataset's address
    for(uint32_t i = 0; i < data_interface::m_datasets.size(); ++i)
    {
        if(reinterpret_cast<uint64_t>(data_interface::m_datasets[i].get()) == address)
        {
            // Emit calculation complete signal.
            emit data_interface::dataset_calculated(i);
            // Quit search.
            break;
        }
    }
}

ext: cpp


text:
/**
 * @file Didson.cpp
 * @brief Projection functions for DIDSON
 * @author: Michael Kaess
 * @date: Aug 2014
 */

#include <vector>
#include <utility>

#include <opencv2/opencv.hpp>

#include <Eigen/Dense>

#include "Didson.h"

using namespace boost;
using namespace std;
using namespace isam;
using namespace Eigen;

namespace sonar {

const float degtorad = M_PI / 180.;
const float radtodeg = 180. / M_PI;

class DidsonConstants {
public:
  double bearingFov;
  double elevationFov;
  int numBearings;
  int numRanges;
  double startBase;
  std::vector<double> lengths;
  DidsonConstants() {
    bearingFov = 28.8 * degtorad; // 28.8 or 29? (both are given in the specs)
    elevationFov = 28. * degtorad; // 28 degrees with spreader lens (default without lens is 14 degrees)
    numBearings = 96;
    numRanges = 512;
#if 1 // todo: unknown if DIDSON in CW or XW mode
    // classic window mode (CW)
    startBase = 0.375;
    lengths.resize (4);
    lengths[0] = 1.125; lengths[1] = 2.25; lengths[2] = 4.5; lengths[3] = 9.;
#else
    // extended window mode (XW)
    startBase = 0.42;
    lengths = {1.25, 2.5, 5., 10.};
#endif
  }
};

const DidsonConstants consts;

pair<int, int> DidsonCartesian::bearingRange2Cartesian(int bearing,
    int range) {
  int pos = _invMap[range * consts.numBearings + bearing];
  int col = pos % image.cols;
  int row = (pos - col) / image.cols;
  // HACK: don't just return col, it needs to be flipped
  return make_pair(row, (image.cols - 1) - col);
}

// conversion of Matlab DIDSON code from Soundmetrics ---
int Didson::lensDistortion(int nbeams, double theta) {
  double* a = NULL;
  double factor = 0.0;
  double a48[4] = { 0.0015, -0.0036, 1.3351, 24.0976 };
  double a189[4] = { 0.0015, -0.0036, 1.3351, 24.0978 };
  double a96[4] = { 0.0030, -0.0055, 2.6829, 48.04 };
  double a381[4] = { 0.0030, -0.0055, 2.6829, 48.04 };

  switch (nbeams) {
  case 48:
    factor = 1.0;
    a = a48;
    break;
  case 189:
    factor = 4.026;
    a = a189;
    break;
  case 96:
    factor = 1.012;
    a = a96;
    break;
  case 381:
    factor = 4.05;
    a = a381;
    break;
  }
  return (int) round(
      factor
          * (a[0] * theta * theta * theta + a[1] * theta * theta + a[2] * theta
              + a[3] + 1));
}

// conversion of Matlab DIDSON code from Soundmetrics ---
/**
 * Calculates a map from cartesian to polar coordinates
 *
 * ixsize  - number of pixels in horizontal direction in image space
 * rmax    - maximum range in meters
 * rmin    - minimum range in meters
 * halffov - one-half of sector field of view in radians
 * nbins   - number of range bins in sample space
 */
pair<vector<int>, int> Didson::createMapping(int ixsize, double rmax,
    double rmin, double halffov, int nbeams, int nbins) {
  //double d2 = rmax*cos(halffov); // distance from point scan touches image boundary to origin
  double d3 = rmin * cos(halffov); // bottom of image frame to r,theta origin in meters
  double c1 = (consts.numRanges - 1) / (rmax - rmin); // precalculation of constants used in do loop below
  //double c2 = (nbeams-1)/(2*halffov);
  double gamma = ixsize / (2 * rmax * sin(halffov)); // Ratio of pixel number to position in meters

  int iysize = (int) (gamma * (rmax - d3) + 0.5); // number of pixels in image in vertical direction

  vector<int> map(ixsize * iysize); // Stores the index map

  // ix,iy   - coordinates of a pixel in image space
  for (int iy = 1; iy <= iysize; iy++) {
    for (int ix = 1; ix <= ixsize; ix++) {
      double x = ((ix - 1) - ixsize / 2) / gamma; // Convert from pixels to meters

      double z = 0.0;
      double y = rmax - (iy - 1) / gamma; // Convert from pixels to meters

      double r = sqrt(y * y + x * x + z * z); // Convert to polar coordinates
      double theta = radtodeg * atan2(x, y); // Theta is in degrees
      int binnum = (int) ((r - rmin) * c1 + 1.5); // the rangebin number
      int beamnum = lensDistortion(nbeams, theta); // Remove the lens distortation using empirical formula
      int pos = 0; // invalid == -1, note pos-1 below
      if ((beamnum > 0) && (beamnum <= nbeams) && (binnum > 0)
          && (binnum <= nbins)) {
        pos = (binnum - 1) * nbeams + beamnum;
      }
      map[(iy - 1) * ixsize + ix - 1] = pos - 1;
    }
  }
  return make_pair(map, iysize);
}

// create a Cartesian image suitable for texture mapping from the raw
// bearing/range measurements; also return a mask of valid image regions
shared_ptr<DidsonCartesian> Didson::getCartesian(int width, int widthTmp) const {
  // generate map for Cartesian image
  vector<int> map;
  int height;
  pair<vector<int>, int> tmp1 = createMapping(width, maxRange(), minRange(),
      consts.bearingFov * 0.5, numBearings(), numRanges());
  map = tmp1.first;
  height = tmp1.second;

  // avoid having to write out the inverse mapping function by creating
  // a map with sufficiently high resolution as a lookup table for the inverse map
  // not ideal, but works...
  vector<int> invMap(consts.numRanges * consts.numBearings);
  vector<int> mapTmp;
  int heightTmp;
  pair<vector<int>, int> tmp2 = createMapping(widthTmp, maxRange(), minRange(),
      consts.bearingFov * 0.5, numBearings(), consts.numRanges);
  mapTmp = tmp2.first;
  heightTmp = tmp2.second;

  int c = 0;
  for (int y = 0; y < heightTmp; y++) {
    for (int x = 0; x < widthTmp; x++) {
      int idx = mapTmp[c];
      if (idx != -1) {
        int icol = x * ((double) width / (double) widthTmp);
        int irow = y * ((double) height / (double) heightTmp);
        int i = irow * width + icol;
        invMap[idx] = i;
      }
      c++;
    }
  }

  shared_ptr<DidsonCartesian> cartesian(new DidsonCartesian(map, invMap));
  cartesian->image = cv::Mat(height, width, CV_8UC1);
  cartesian->mask = cv::Mat(height, width, CV_8UC1);
  for (int i = 0; i < width * height; i++) {
    if (map[i] == -1) {
      cartesian->image.data[i] = 0;
      cartesian->mask.data[i] = 0;
    } else {
      cartesian->image.data[i] = _image.data[map[i]];
      cartesian->mask.data[i] = 255;
    }
  }

  return cartesian;
}

// constructor taking a DIDSON frame
Didson::Didson(int windowStart, int windowLength,
               const isam::Pose3d& vehiclePose, double tiltRad, double rollRad,
               const unsigned char* data, bool transformFrame) :
    Sonar(consts.startBase * windowStart,
        consts.startBase * windowStart + consts.lengths[windowLength],
        consts.bearingFov, consts.elevationFov, consts.numBearings,
        consts.numRanges), _tiltRad(tiltRad), _rollRad(
        rollRad), _vehiclePose(vehiclePose) {
  if (windowStart < 1 || windowStart > 31) {
    cout << "ERROR: windowStart out of range" << endl;
    exit(1);
  }
  if (windowLength < 0 || windowLength > 3) {
    cout << "ERROR: windowLength out of range" << endl;
    exit(1);
  }

  _image = cv::Mat(consts.numRanges, consts.numBearings, CV_8UC1);
  if (data)
      memcpy(_image.data, data, consts.numRanges * consts.numBearings);

  // we assume DIDSON facing to the right (DVL in hull lock mode)
  // i.e. 90 degrees yaw and -90 degrees roll configuration + tilt and roll actuators
  if (transformFrame) {
      Pose3d didsonOffset(0, 0.2, 0, 0, 0, 0); // DIDSON is to the right of the DVL along y  // todo: check DIDSON offset
      Pose3d didsonActuators(0, 0, 0, M_PI * 0.5, tiltRad, rollRad - M_PI * 0.5);
      _didsonPose = vehiclePose.oplus(didsonOffset).oplus(didsonActuators);
  } else {
      _didsonPose = vehiclePose;
  }
}

Pose3d Didson::didsonHuls3Pose() const {
  return _didsonPose;
}

vector<Point3d> Didson::getFrustum() const {
  return Sonar::getFrustum(didsonHuls3Pose());
}

bool Didson::project(const isam::Point3d& point,
    isam::Point2d& projection) const {
  return Sonar::project(didsonHuls3Pose(), point, projection);
}

} /* namespace sonar */

max_stars_repo_name: mattjr/structured


text:
#ifndef UUID_9037C300_D4EF_473C_8387_A1A9797069A7
#define UUID_9037C300_D4EF_473C_8387_A1A9797069A7
#pragma once

#include "../dumpable.hpp"
#include "../endian.hpp"
#include "../source.hpp"
#include "../dynamic_struct.hpp"
#include "../txt_serializable.hpp"

#include <libshit/lua/auto_table.hpp>
#include <boost/endian/arithmetic.hpp>
#include <vector>

namespace Neptools
{

  class Gbnl : public Dumpable, public TxtSerializable
  {
    LIBSHIT_DYNAMIC_OBJECT;
  public:
    struct Header // or Footer
    {
      char magic[3];
      char endian;

      std::uint16_t field_04;
      std::uint16_t field_06;
      std::uint32_t field_08;
      std::uint32_t field_0c;
      std::uint32_t flags; // 1 if there's a string, 0 otherwise?
      std::uint32_t descr_offset;
      std::uint32_t count_msgs;
      std::uint32_t msg_descr_size;
      std::uint32_t count_types;
      std::uint32_t offset_types;
      std::uint32_t field_28;
      std::uint32_t offset_msgs;
      std::uint32_t field_30;
      std::uint32_t field_34;
      std::uint32_t field_38;
      std::uint32_t field_3c;

      void Validate(std::size_t chunk_size) const;
    };
    static_assert(sizeof(Header) == 0x40);

    struct TypeDescriptor
    {
      enum Type
      {
        INT32  = 0,
        INT8   = 1,
        INT16  = 2,
        FLOAT  = 3,
        STRING = 5,
        INT64  = 6,
      };
      std::uint16_t type;
      std::uint16_t offset;
    };
    static_assert(sizeof(TypeDescriptor) == 0x04);

    struct OffsetString
    {
      std::string str;
      uint32_t offset;
    };

    struct FixStringTag { char str[1]; };
    struct PaddingTag { char pad[1]; };

    using Struct = DynamicStruct<
      int8_t, int16_t, int32_t, int64_t, float, OffsetString,
      FixStringTag, PaddingTag>;
    using StructPtr = Libshit::NotNull<boost::intrusive_ptr<Struct>>;
    using Messages = std::vector<StructPtr>;

    Gbnl(Source src);
    Gbnl(Endian endian, bool is_gstl, uint32_t flags, uint32_t field_28,
         uint32_t field_30, Libshit::AT<Struct::TypePtr> type)
      : endian{endian}, is_gstl{is_gstl}, flags{flags}, field_28{field_28},
        field_30{field_30}, type{std::move(type.Get())} {}
#if LIBSHIT_WITH_LUA
    Gbnl(Libshit::Lua::StateRef vm, Endian endian, bool is_gstl, uint32_t flags,
         uint32_t field_28, uint32_t field_30, Libshit::AT<Struct::TypePtr> type,
         Libshit::Lua::RawTable messages);
#endif

    void Fixup() override { RecalcSize(); }

    Endian endian;
    bool is_gstl;
    uint32_t flags, field_28, field_30;

    // no setter - it doesn't work how you expect in lua
    LIBSHIT_LUAGEN(get="::Libshit::Lua::GetSmartOwnedMember")
    Messages messages;

    Struct::TypePtr type;

    void RecalcSize();
    FilePosition GetSize() const noexcept override;

    Libshit::NotNullSharedPtr<TxtSerializable> GetDefaultTxtSerializable(
      const Libshit::NotNullSharedPtr<Dumpable>& thiz) override
    { return Libshit::NotNullSharedPtr<TxtSerializable>{thiz.Get(), this}; }

  protected:
    // todo: private after removing GbnlItem
    void Dump_(Sink& sink) const override;
    void InspectGbnl(std::ostream& os, unsigned indent) const;
    void Inspect_(std::ostream& os, unsigned indent) const override;

  private:
    void WriteTxt_(std::ostream& os) const override;
    void ReadTxt_(std::istream& is) override;

    void Parse_(Source& src);
    void DumpHeader(Sink& sink) const;
    void Pad(uint16_t diff, Struct::TypeBuilder& bld, bool& int8_in_progress);
    FilePosition Align(FilePosition x) const noexcept;

    std::optional<std::int32_t> GetId(
      bool simple, const Gbnl::Struct& m, size_t i, size_t j, size_t& k) const;
    size_t FindDst(bool simple, int32_t id, std::vector<StructPtr>& messages,
                   size_t& index) const;

    size_t msg_descr_size, msgs_size;
    size_t real_item_count; // excluding dummy pad items
  };

  void endian_reverse_inplace(Gbnl::Header& hdr);
  void endian_reverse_inplace(Gbnl::TypeDescriptor& desc);
}
#endif

ext: hpp


text:
// MIT License
//
// Copyright (c) 2018 Michal Siedlaczek
//
// 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.

//! \file
//! \author     Michal Siedlaczek
//! \copyright  MIT License

#include <cstdio>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <regex>

#include <CLI/CLI.hpp>
#include <boost/filesystem.hpp>

std::ofstream& new_file(std::ofstream& out,
    const std::string& prefix,
    std::size_t num,
    std::size_t padding)
{
    if (out.is_open()) {
        out.close();
    }
    std::ostringstream filename;
    filename << prefix << "-" << std::setfill('0') << std::setw(padding) << num;
    out.open(filename.str());
    return out;
}

int main(int argc, char** argv)
{
    struct {
        std::size_t padding_width = 4;
        std::string output;
        std::vector<std::string> input_files;
        std::size_t limit = 0;
    } args;

    CLI::App app{"Partition a text file by line number."};
    app.add_flag("--no-header", "the input file has no header");
    app.add_option("-p,--padding-width",
        args.padding_width,
        "number of zeroes to use for padding in names",
        true);
    app.add_option(
        "-o,--output", args.output, "the prefix of the output files");
    app.add_option("limit", args.limit, "the number of lines per file", false)
        ->required();
    app.add_option("input", args.input_files, "input files", false)
        ->check(CLI::ExistingFile);

    CLI11_PARSE(app, argc, argv);

    if (app.count("input") == 0u) {
        args.input_files.emplace_back("");
        if (app.count("--output") != 0u)
        {
            std::cerr << "you must define --output when reading from stdin"
                      << std::endl;
            return 1;
        }
    } else {
        if (app.count("output") != 0u && args.input_files.size() > 1)
        {
            std::cerr << "you must define --output when reading multiple files"
                      << std::endl;
            return 1;
        }
    }

    bool use_header = app.count("--no-header") != 0u;
    std::size_t line_num = 0;
    std::size_t file_num = 0;
    std::string output_prefix = app.count("--output") != 0u
        ? args.output
        : args.input_files[0];

    std::ofstream out;
    std::optional<std::string> header;

    for (std::string& input_file : args.input_files) {
        std::unique_ptr<std::ifstream> file_in = nullptr;
        std::istream* in;
        if (not input_file.empty()) {
            file_in = std::make_unique<std::ifstream>(input_file);
            //in = new std::ifstream(input_file);
            in = file_in.get();
        } else {
            in = &std::cin;
        }

        std::string line;

        if (use_header) {
            std::optional<std::string> old_header = header;
            std::getline(*in, line);
            header = std::make_optional(line);
            if (old_header.has_value() && old_header != header) {
                header = old_header;
            }
        }

        while (std::getline(*in, line)) {
            if (line_num == 0) {
                new_file(out, output_prefix, file_num++, args.padding_width);
                if (header.has_value()) {
                    out << header.value() << std::endl;
                }
            }
            out << line << std::endl;
            line_num = (line_num + 1) % args.limit;
        }
    }
    out.close();
}

max_stars_repo_name: elshize/irkit

max_issues_repo_name: elshize/irkit

max_forks_repo_name: elshize/irkit


text: #include <boost/spirit/home/classic/core/composite/sequential_and.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text: #include <boost/graph/distributed/graphviz.hpp>


text:
// Boost.Geometry

// Copyright (c) 2020, Oracle and/or its affiliates.

// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html

#ifndef BOOST_GEOMETRY_STRATEGIES_INDEX_CARTESIAN_HPP
#define BOOST_GEOMETRY_STRATEGIES_INDEX_CARTESIAN_HPP

// TODO: move to strategy directory
#include <boost/geometry/strategies/cartesian/distance_projected_point.hpp>
#include <boost/geometry/strategies/cartesian/distance_pythagoras.hpp>
#include <boost/geometry/strategies/cartesian/distance_segment_box.hpp>

#include <boost/geometry/strategies/index/services.hpp>
#include <boost/geometry/strategies/relate/cartesian.hpp>

namespace boost { namespace geometry { namespace strategies { namespace index
{

template <typename CalculationType = void>
class cartesian
    : public relate::cartesian<CalculationType>
{
public:
    template <typename Geometry1, typename Geometry2>
    static auto comparable_distance(Geometry1 const&, Geometry2 const&,
                                    std::enable_if_t
                                        <
                                            util::is_pointlike<Geometry1>::value
                                         && util::is_pointlike<Geometry2>::value
                                        > * = nullptr)
    {
        //return geometry::strategy::distance::comparable::pythagoras<CalculationType>();
        return geometry::strategy::distance::pythagoras<CalculationType>();
    }

    template <typename Geometry1, typename Geometry2>
    static auto comparable_distance(Geometry1 const&, Geometry2 const&,
                                    std::enable_if_t
                                        <
                                            (util::is_pointlike<Geometry1>::value
                                            && util::is_segment<Geometry2>::value)
                                         || (util::is_segment<Geometry1>::value
                                            && util::is_pointlike<Geometry2>::value)
                                        > * = nullptr)
    {
        return geometry::strategy::distance::projected_point
            <
                CalculationType,
                //geometry::strategy::distance::comparable::pythagoras<CalculationType>
                geometry::strategy::distance::pythagoras<CalculationType>
            >();
    }

    template <typename Geometry1, typename Geometry2>
    static auto comparable_distance(Geometry1 const&, Geometry2 const&,
                                    std::enable_if_t
                                        <
                                            (util::is_pointlike<Geometry1>::value
                                            && util::is_box<Geometry2>::value)
                                         || (util::is_box<Geometry1>::value
                                            && util::is_pointlike<Geometry2>::value)
                                        > * = nullptr)
    {
        //return geometry::strategy::distance::comparable::pythagoras_point_box<CalculationType>();
        return geometry::strategy::distance::pythagoras_point_box<CalculationType>();
    }

    template <typename Geometry1, typename Geometry2>
    static auto comparable_distance(Geometry1 const&, Geometry2 const&,
                                    std::enable_if_t
                                        <
                                            (util::is_segment<Geometry1>::value
                                            && util::is_box<Geometry2>::value)
                                         || (util::is_box<Geometry1>::value
                                             && util::is_segment<Geometry2>::value)
                                        > * = nullptr)
    {
        return geometry::strategy::distance::cartesian_segment_box
            <
                CalculationType,
                //geometry::strategy::distance::comparable::pythagoras<CalculationType>
                geometry::strategy::distance::pythagoras<CalculationType>
            >();
    }

    template <typename Geometry1, typename Geometry2>
    static auto comparable_distance(Geometry1 const&, Geometry2 const&,
                                    std::enable_if_t
                                        <
                                            util::is_segment<Geometry1>::value
                                         && util::is_segment<Geometry2>::value
                                        > * = nullptr)
    {
        return strategy::distance::projected_point
            <
                CalculationType,
                //strategy::distance::comparable::pythagoras<CalculationType>
                strategy::distance::pythagoras<CalculationType>
            >();
    }
};

namespace services
{

template <typename Geometry>
struct default_strategy<Geometry, cartesian_tag>
{
    using type = strategies::index::cartesian<>;
};

// TEMP - needed in distance until umbrella strategies are supported
template <typename CalculationType, typename SubStrategy>
struct strategy_converter<strategy::distance::projected_point<CalculationType, SubStrategy>>
{
    static auto get(strategy::distance::projected_point<CalculationType, SubStrategy> const& )
    {
        return strategies::index::cartesian<CalculationType>();
    }
};
// TEMP - needed in distance until umbrella strategies are supported
template <typename CalculationType>
struct strategy_converter<strategy::distance::comparable::pythagoras<CalculationType>>
{
    static auto get(strategy::distance::comparable::pythagoras<CalculationType> const&)
    {
        return strategies::index::cartesian<CalculationType>();
    }
};

} // namespace services

}}}} // namespace boost::geometry::strategy::index

#endif // BOOST_GEOMETRY_STRATEGIES_INDEX_CARTESIAN_HPP


text:
//* The MOOS LCM Bridge
/**
 *
 * @file
 *
 * @author Anthony Spears <anthony.spears@eas.gatech.edu>
 *
 * @version 1.0
 *
 * @date June 1, 2018
 *
 * @section LICENSE
 *
 * Georgia Institute of Technology
 *
 * 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 2 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 at
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @section DESCRIPTION
 *
 * The MOOS LCM Bridge allows for communication between a
 * MOOS Database and LCM.
 */

//TODO: Add timestamps to toMoos() calls

// Basic LCM Include
#include <lcm/lcm-cpp.hpp>

// Standard Library Headers
#include <sstream>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <vector>
//#include <map>
#include <string>

// MOOS Includes
#include <MOOS/libMOOS/App/MOOSApp.h>
#include "MOOSNode.h"
#include "MsgContainer.h"

// BOOST Includes
#include <boost/thread.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>

// RapidXML Parser
#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_print.hpp"

// LCM TYPES
#include <lcm/lcm_coretypes.h>
#include "moos_t.hpp"
#include "moos_double_t.hpp"
#include "moos_string_t.hpp"

#define FAIL 1
#define SUCCESS 0

//Declare namespaces in use
using namespace rapidxml;
using namespace std;

vector<MsgContainer> subVec;

/*
 * MOOS to LCM Interface
 */
MOOSNode MOOSApp;
void MOOSInit(const char * sMissionFile){
     const char * sMOOSName = "MOOS_LCM_BRIDGE";

     MOOSApp.Run(sMOOSName, sMissionFile);
}

/*
 * LCM to MOOS Interface
 * LCM doesn't have any native message definitions, so we'll create some for MOOS and add support for any other necessary msgs
 */
class Handler_MOOS
{
public:
  ~Handler_MOOS() {}

  void handleMessage(const lcm::ReceiveBuffer* rbuf,
		     const std::string& chan,
		     const moos_lcm_bridge_types::moos_t* msg)
  {
    int i;
    cout << "Received message on channel \"" << chan.c_str() << "\"" <<endl;
    cout << "  timestamp   = " << (long long)msg->timestamp <<endl;
    cout << "  name    = " << msg->name <<endl;
    cout << "  val_str    = " << msg->val_str <<endl;
    cout <<"  val_dbl    = " << msg->val_dbl <<endl;
    cout << "  source    = " << msg->source <<endl;
    cout << "  data_type    = " << msg->data_type <<endl;
    cout <<"  msg_type    = " << msg->msg_type <<endl;
    cout << "  source_community    = " << msg->source_community <<endl;
    if(msg->data_type == 'S')
      MOOSApp.toMOOS(msg->name, msg->val_str);
    else if(msg->data_type == 'D')
      MOOSApp.toMOOS(msg->name, msg->val_dbl);
  }
};

class Handler_MOOS_Double
{
public:
  ~Handler_MOOS_Double() {}

  void handleMessage(const lcm::ReceiveBuffer* rbuf,
		     const std::string& chan,
		     const moos_lcm_bridge_types::moos_double_t* msg)
  {
    cout << "Received moos_double_t message on channel \"" << chan.c_str() << "\"" <<endl;
    cout << "  timestamp   = " << (long long)msg->timestamp <<endl;
    cout << "  value    = " << msg->value <<endl;

    vector<MsgContainer>::iterator it;
    for ( it = subVec.begin() ; it < subVec.end() ; it++ ){
      if(strcmp(it->lcmName.c_str(), chan.c_str()) == 0)
	MOOSApp.toMOOS(it->moosName,msg->value);
//      MOOSApp.toMOOS(msg->name, msg->value);
    }
  }
};

class Handler_MOOS_String
{
public:
  ~Handler_MOOS_String() {}

  void handleMessage(const lcm::ReceiveBuffer* rbuf,
		     const std::string& chan,
		     const moos_lcm_bridge_types::moos_string_t* msg)
  {
    //    int i;
    cout << "Received moos_string_t message on channel \"" << chan.c_str() << "\"" <<endl;
    cout << "  timestamp   = " << (long long)msg->timestamp <<endl;
    cout << "  value    = " << msg->value <<endl;

    vector<MsgContainer>::iterator it;
    for ( it = subVec.begin() ; it < subVec.end() ; it++ ){
      if(strcmp(it->lcmName.c_str(), chan.c_str()) == 0)
	MOOSApp.toMOOS(it->moosName,msg->value);
      //    MOOSApp.toMOOS(msg->name, msg->value);
    }
  }
};

/*
 * Parse the XML file to search for LCM Subscribers
 * Create LCM Subscribers
 * Also create vectors to hold pointers for publishers and subscribers
 * Send the list of LCM publishers to the MOOS App to create the MOOS subscribers
 */
int CreateLCMSub(xml_node<> *node, vector<MsgContainer> *pubVec, vector<MsgContainer> *subVec, lcm::LCM *n){
     // MOOS Publishers to LCM Subscribers (This MOOS app will need to subscribe to these topics)
     // Just create vector of subscribers and call MOOS subscriptions method later
     if(strcmp(node->first_node("direction")->value(),"toLCM") == SUCCESS){
       if(strcmp(node->first_node("lcmtype")->value(),"moos_t") == SUCCESS){
	 pubVec->push_back(MsgContainer(n,
					node->first_node("moosname")->value(),
					node->first_node("lcmname")->value(),
					node->first_node("moostype")->value(),
					node->first_node("lcmtype")->value()));
       }else if(strcmp(node->first_node("lcmtype")->value(),"moos_double_t") == SUCCESS){
	 pubVec->push_back(MsgContainer(n,
					node->first_node("moosname")->value(),
					node->first_node("lcmname")->value(),
					node->first_node("moostype")->value(),
					node->first_node("lcmtype")->value()));
       }else if(strcmp(node->first_node("lcmtype")->value(),"moos_string_t") == SUCCESS){
	 pubVec->push_back(MsgContainer(n,
					node->first_node("moosname")->value(),
					node->first_node("lcmname")->value(),
					node->first_node("moostype")->value(),
					node->first_node("lcmtype")->value()));
       }else{
	 cout << "ERROR PARSING XML CONFIG FILE (to LCM)\n";
	 return FAIL;
       }

     // LCM Publishers to MOOS Subscribers
     // This LCM App will have to subscribe to these topics and publish them to the MOOSDB
     }else if(strcmp(node->first_node("direction")->value(),"toMOOS") == SUCCESS){
       if(strcmp(node->first_node("lcmtype")->value(),"moos_double_t") == SUCCESS){
	 Handler_MOOS_Double MOOSDoubleHandler;
	 //n->subscribe("LCM2MOOS", &Handler_MOOS_Double::handleMessage, &MOOSDoubleHandler);
	 n->subscribe(node->first_node("lcmname")->value(), &Handler_MOOS_Double::handleMessage, &MOOSDoubleHandler);
	 subVec->push_back(MsgContainer(node->first_node("moosname")->value(),
					node->first_node("lcmname")->value()));
       }else if(strcmp(node->first_node("lcmtype")->value(),"moos_string_t") == SUCCESS){
	 Handler_MOOS_String MOOSStringHandler;
	 //n->subscribe("LCM2MOOS", &Handler_MOOS_Double::handleMessage, &MOOSDoubleHandler);
	 n->subscribe(node->first_node("lcmname")->value(), &Handler_MOOS_String::handleMessage, &MOOSStringHandler);
	 subVec->push_back(MsgContainer(node->first_node("moosname")->value(),
					node->first_node("lcmname")->value()));
       }else if(strcmp(node->first_node("lcmtype")->value(),"moos_t") == SUCCESS){
	 Handler_MOOS MOOShandlerObject;
	 //	    n->subscribe(node->first_node("lcmname")->value(), &Handler_MOOS::handleMessage, &MOOShandlerObject);
	 n->subscribe("LCM2MOOS", &Handler_MOOS::handleMessage, &MOOShandlerObject);
	 subVec->push_back(MsgContainer(node->first_node("moosname")->value(),
					node->first_node("lcmname")->value()));
	 /*
       }else if(strcmp(node->first_node("lcmtype")->value(),"string-binary") == SUCCESS){
	 // Binary-string support
	 subVec->push_back(MsgContainer(//n->subscribe(node->first_node("lcmname")->value(),
					//		&Handler::handleMessage6, &handlerObject),
					node->first_node("moosname")->value(),
	 				node->first_node("lcmname")->value()));
	 */
       }else{
	 cout << "ERROR PARSING XML CONFIG FILE\n";
	 return FAIL;
       }
     }

     return SUCCESS;
}

int main(int argc, char **argv)
{
     if(argc < 3){
       cout << "Invalid number of parameters" << endl;
       cout << "argc is" << argc << ", but it should be at least 3." << endl;
       cout << "Usage:\n\t./moos-lcm-bridge <mooslcmconfig.xml> <mission.moos>" << endl;
       return 0;
     }

     //Initialize LCM Communications
     lcm::LCM lcm;
     if(!lcm.good())
       return 1;
     cout << "LCM STARTED" << endl;

     //Read in complete XML Document
     string str,strTotal;
     ifstream in;

     //Check for existence of config files
     struct stat stFileInfo;
     int intStat;
     intStat = stat(argv[1],&stFileInfo);
     if(intStat != 0) {
       cout << "\n******\nCONFIG FILE MISSING\n" << argv[1] << " does not exist!\n******\n";
       return 0;
     }

     //Open file and read the entire file into the strTotal buffer
     in.open(argv[1]);
     getline(in,str);

     while ( in ) {
          strTotal += str;
          getline(in,str);
     }

     //cout << strTotal << endl;

     //Convert C++ string to char*
     char * xmlDoc = new char [strTotal.size()+1];
     strcpy (xmlDoc, strTotal.c_str());

     //Parse XML Document
     xml_document<> doc;    // character type defaults to char
     doc.parse<0>(xmlDoc);    // 0 means default parse flags

     vector<MsgContainer> pubVec;

     //Get First Topic/Message
     xml_node<> *node = doc.first_node()->first_node();

     //strcmp(node->first_node("direction")->value(),"toLCM")
     //     cout << node->first_node("direction")->value() << endl;
     if(CreateLCMSub(node,&pubVec,&subVec,&lcm) == FAIL)
       return 0;

     //Process all Topics/Messages
     while( (node = node->next_sibling()) != 0 )
          if(CreateLCMSub(node,&pubVec,&subVec,&lcm) == FAIL)
               return 0;

     //Kick off the MOOS Loop in a separate thread
     //before entering the LCM Loop
     //cout << pubVec.size() << endl;
     MOOSApp.AssignPublisher(&pubVec);
     boost::thread MOOSThread(MOOSInit, argv[2]);

     while (0 == lcm.handle());

     return 0;
}


text:
#include "mesh.hpp"
#include "generic/eigen.hpp"
#include "kernel_poly6.hpp"

#include "spatial/2d/neighborhood_spatial_hashing.hpp"

#include <Eigen/Geometry>
#include <iostream>

namespace GooBalls {
namespace d2 {
namespace Physics {

using namespace Spatial;

Mesh::Mesh() :
    linearAcceleration(0,0),
    m_vertices_position_global(new Coordinates()),
    m_triangles(new TriangleList())
    {
    // empty
}

Mesh::Mesh(std::shared_ptr<Mesh::Coordinates> verts, std::shared_ptr<TriangleList> tris) :
    linearAcceleration(0,0),
    m_vertices_position_global(verts),
    m_triangles(tris)
{
    m_vertices_position_local = *verts;
}

const Mesh::Coordinates& Mesh::vertices_position_global() const {
    return *m_vertices_position_global;
}

Mesh::Coordinates& Mesh::vertices_position_global() {
    return *m_vertices_position_global;
}

const Mesh::Coordinates& Mesh::vertices_position_local() const {
    return m_vertices_position_local;
}
Mesh::Coordinates& Mesh::vertices_position_local() {
    return m_vertices_position_local;
}

const TriangleList& Mesh::triangles() const {
    return *m_triangles;
}
TriangleList& Mesh::triangles() {
    return *m_triangles;
}

const Coordinates2d& Mesh::particles_position_local() const {
    return m_particles_position_local;
}

const Coordinates2d& Mesh::particles_velocity() const {
    return m_particles_velocity;
}

const Coordinates1d& Mesh::particles_volume() const {
    return m_particles_volume;
}

const Coordinates1d& Mesh::particles_mass() const {
    return m_particles_mass;
}

Float& Mesh::particles_velocity_correction_coefficient() {
    return m_velocity_correction_coefficient;
}
Float Mesh::particles_velocity_correction_coefficient() const {
    return m_velocity_correction_coefficient;
}

RotationMatrix Mesh::rotation() const {
    Float radianAngle = body->GetAngle();
    // eigen convention: counter-clockwise rotation in radians
    // box2d convention: not clear, only hint is in chapter 8.6 Revolute Joint of the manual -> test
    // TODO: test rotation direction of Box2d
    Eigen::Rotation2D<Float> rot(radianAngle);
    RotationMatrix rotM = rot.toRotationMatrix();
    return rotM;
}

TranslationVector Mesh::translation() const {
    TranslationVector dx;
    dx[0] = body->GetPosition().x;
    dx[1] = body->GetPosition().y;
    return dx;
}

TranslationVector Mesh::linear_velocity() const {
    TranslationVector v;
    v[0] = body->GetLinearVelocity().x;
    v[1] = body->GetLinearVelocity().y;
    return v;
}

RotationMatrix Mesh::angular_velocity() const {
    // box2d: radians/second
    RotationMatrix r;
    Float v = body->GetAngularVelocity();
    Eigen::Rotation2D<Float> rot(v);
    RotationMatrix rotM = rot.toRotationMatrix();
    // TODO: it is not clear, if rotM needs to be transposed here -> test
    return rotM;
}

/// takes the rigid body transformation from the box2D object and applies it locally
void Mesh::update_from_rigid_body() {
    const auto& loc = this->vertices_position_local();
    auto& glob = this->vertices_position_global();
    RotationMatrix rotM = rotation();
    TranslationVector dx = translation();
    rotM.transpose();
    glob = (loc * rotM).rowwise() + dx;
    // speed of particle
    if(m_particles_position_local.rows() > 0){
        m_particles_velocity.resize(m_particles_position_local.rows(), Eigen::NoChange);
        m_particles_velocity.col(0) = -m_particles_position_local.col(1);
        m_particles_velocity.col(1) = m_particles_position_local.col(0);
        m_particles_velocity *= body->GetAngularVelocity();
        m_particles_velocity = m_particles_velocity.rowwise() + linear_velocity();
    }
}

void Mesh::prepare(Float h){
    update_from_rigid_body();
    create_particles(h);
    compute_particles_volume(h);
    compute_particles_mass(h);
}
void Mesh::create_particles(Float h) {
    // most basic particle generation algorithm:
    // for each triangle
    // - add three particles for each corner
    // - look at all edges and sample each edge n additional times
    const auto& tris = triangles();
    const auto& verts = vertices_position_local();
    /*
    std::cout << "pts: \n";
    for(int i = 0; i < verts.rows(); ++i){
        std::cout << verts(i,0) << " " << verts(i, 1) << std::endl;
    }
    std::cout << "body: " << body->GetPosition().x << ", " << body->GetPosition().y << std::endl;
    */
    int totalPoints = 0;
    int inserted = 0;
    auto& pts = m_particles_position_local;
    int sampling = 4;

    for(int t = 0; t < tris.rows(); ++t){
        for(int v = 0; v < 3; v++){
            int vn = (v+1)%3; // next vertex
            // process edge
            auto diffV = verts.row(tris(t, vn)) - verts.row(tris(t, v));
            int n = std::ceil(diffV.norm()/h*sampling)+1;
            totalPoints += 1;
            totalPoints += n;
            pts.conservativeResize(totalPoints, Eigen::NoChange);
            // insert vertex
            pts.row(inserted++) = verts.row(tris(t, v));
            TranslationVector diff = (diffV)/double(n+1);
            for(int ni = 0; ni < n; ni++){
                pts.row(inserted++) = (ni+1) * diff + verts.row(tris(t, v));
            }
        }
    }
}

void Mesh::compute_particles_volume(Float h) {
    // occupied volume according to Versatile Rigid-Fluid Coupling for Incompressible SPH, Akinci et. al
    // V_bi = 1/sum_k W_ik, W: is a kernel
    m_particles_volume.resize(m_particles_position_local.rows(), Eigen::NoChange);
    NeighborhoodSpatialHashing neighbor;
    Poly6 kernel;
    kernel.setH(h);
    neighbor.inRange(m_particles_position_local, h);
    const auto& indexes = neighbor.indexes();
    for(size_t i = 0; i < indexes.size(); ++i){
        Coordinates2d jpos;
        Coordinates1d W;
        pickRows(m_particles_position_local, indexes[i], jpos);
        auto xij = -(jpos.rowwise() - m_particles_position_local.row(i));
        kernel.compute(xij, &W, nullptr, nullptr);
        m_particles_volume[i] = 1/W.sum();
    }
}

void Mesh::compute_particles_mass(Float) {
    int PN = m_particles_position_local.rows();
    m_particles_mass.resize(PN, Eigen::NoChange);
    m_particles_mass.array() = body->GetMass()/PN;//TODO: body->GetMass()/PN;
}

} // Physics
} // d2
} // GooBalls

max_stars_repo_name: Fluci/GooBalls

max_issues_repo_name: Fluci/GooBalls

max_forks_repo_name: Fluci/GooBalls


text:
//
// Copyright (c) 2021 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/CPPAlliance/http_proto
//

#ifndef BOOST_HTTP_PROTO_MIME_MIME_TYPES_HPP
#define BOOST_HTTP_PROTO_MIME_MIME_TYPES_HPP

#include <boost/http_proto/detail/config.hpp>
#include <boost/http_proto/string_view.hpp>

namespace boost {
namespace http_proto {

class BOOST_SYMBOL_VISIBLE
    mime_types
{
public:
    BOOST_HTTP_PROTO_DECL
    virtual ~mime_types() noexcept;

    virtual
    string_view
    content_type(
        string_view s) const noexcept = 0;
};

} // http_proto
} // boost

#endif


text:
#include <boost/mpl/int.hpp>
#include <boost/simd/sdk/simd/native.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/simd/sdk/memory/is_aligned.hpp>

using boost::simd::meta::is_aligned_c;

int main()
{
  BOOST_MPL_ASSERT(( is_aligned_c<0,2>::type ));
  BOOST_MPL_ASSERT(( is_aligned_c<2,2>::type ));
  BOOST_MPL_ASSERT(( is_aligned_c<4,2>::type ));
  BOOST_MPL_ASSERT(( is_aligned_c<8,2>::type ));
  BOOST_MPL_ASSERT_NOT(( is_aligned_c<17,2>::type ));
}


text:
/*
scidb4geo - A SciDB plugin for managing spatially referenced arrays
Copyright (C) 2015 Marius Appel <marius.appel@uni-muenster.de>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
-----------------------------------------------------------------------------*/

#include "../plugin.h" // Must be first

#include "ArraySchemaUtils.h"
#include "../ErrorCodes.h"

#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

#include "query/TypeSystem.h"

namespace scidb4geo
{
    using namespace scidb;
    using namespace std;

    Attributes ArraySchemaUtils::arrayAttributesFromString ( string str )
    {

        boost::trim ( str );
        if ( str[0] != '<' || str[str.length() - 1] != '>' ) {
            //SCIDB4GEO_ERROR("Cannot derive attribute definitions from schema string",SCIDB4GEO_ERR_UNKNOWN);
        }

        string s = str.substr ( 1, str[str.length() - 2] ); // remove < >
        vector<string> single_attr_strings;
        boost::split ( single_attr_strings, s, boost::is_any_of ( "," ) );
        if ( single_attr_strings.size() == 0 ) {
            //SCIDB4GEO_ERROR("Cannot derive attribute definitions from schema string",SCIDB4GEO_ERR_UNKNOWN);
        }

        Attributes outAttrs;
        int i = 0;
        for ( vector<string>::iterator attr_str = single_attr_strings.begin(); attr_str != single_attr_strings.end(); ++attr_str ) {
            bool attr_nullable = false;

            string attr_default = "";
            string attr_typeid = "";
            vector<string> name_def;
            boost::split ( name_def, *attr_str, boost::is_any_of ( ":" ) );
            if ( name_def.size() != 2 ) {
                //SCIDB4GEO_ERROR("Cannot derive attribute definitions from schema string",SCIDB4GEO_ERR_UNKNOWN);
            }
            boost::trim ( name_def[0] );
            boost::trim ( name_def[1] );
            string attr_name = name_def[0];
            string def =  name_def[1];
            attr_typeid = def.substr ( 0, def.find_first_of ( " " ) - 1 );
            int attr_flags = 0;
            if ( attr_nullable ) attr_flags = AttributeDesc::IS_NULLABLE; // TODO: Change to &=

            if ( boost::contains ( def, "NOT NULL" ) ) attr_nullable = false;
            else if ( boost::contains ( def, "NULL" ) ) attr_nullable = true;

            //if (boost::contains(def, "DEFAULT"))  // TODO: Take next word as default value

            outAttrs.push_back ( AttributeDesc ( ( AttributeID ) i++, attr_name , attr_typeid, attr_flags, 0 ) );

        }

        return outAttrs;

    }

}

ext: cxx


text:
#ifndef ASLAM_DESIGN_VARIABLE_HPP
#define ASLAM_DESIGN_VARIABLE_HPP

#include <sm/Id.hpp>
#include <unordered_set>
#include <set>

#include <Eigen/Core>

#include <aslam/Exceptions.hpp>
#include <boost/shared_ptr.hpp>

namespace aslam {
  namespace backend {

    class JacobianContainer;

    class DesignVariable {
    public:
      /**
       * \struct BlockIndexOrdering
       *
       * A comparator to allow design variables to be ordered by block index.
       */
      struct BlockIndexOrdering {
        inline bool operator()(const DesignVariable* lhs, const DesignVariable* rhs) const {
          SM_ASSERT_TRUE_DBG(aslam::Exception, lhs != NULL, "Null value!");
          SM_ASSERT_TRUE_DBG(aslam::Exception, rhs != NULL, "Null value!");
          return lhs->blockIndex() < rhs->blockIndex();
        }
      };

      /**
       * \typedef unordered_set_t
       * \brief A fast unordered set of design variables.
       */
      typedef std::unordered_set< DesignVariable* > set_t;

        typedef boost::shared_ptr< DesignVariable > Ptr;

      /**
       * \typedef blockordered_set_t
       * \brief a set of design variables ordered by block index.
       */
      //      typedef std::unordered_set//set<DesignVariable *, BlockIndexOrdering> blockordered_set_t;

      DesignVariable();

      virtual ~DesignVariable();

      /// \brief what is the number of dimensions of the minimal perturbation.
      virtual int minimalDimensions() const;

      /// \brief update the design variable.
      void update(const double* update, int size);

      /// \brief Revert the last state update
      void revertUpdate();

      /// \brief is this design variable active in the optimization.
      bool isActive() const;

      /// \brief set the active state of this design variable.
      void setActive(bool active);

      /// \brief should this variable be marginalized in the Schur-complement step?
      bool isMarginalized() const;

      /// \brief should this variable be marginalized in the Schur-complement step?
      void setMarginalized(bool marginalized);

      /// \brief get the block index used in the optimization routine. -1 if not being optimized.
      int blockIndex() const;

      /// \brief set the block index used in the optimization routine.
      void setBlockIndex(int blockIndex);

      /// \brief set the scaling of this design variable used in the optimization.
      void setScaling(double scaling);

      /// \brief get the scaling of this design variable used in the optimization.
      double scaling() const;

      /// \brief The column base of this block in the Jacobian matrix
      int columnBase() const;

      /// \brief Set the column base of this block in the Jacobian matrix
      void setColumnBase(int columnBase);

      /// Returns the content of the design variable
      void getParameters(Eigen::MatrixXd& value) const;

      /// Sets the content of the design variable
      void setParameters(const Eigen::MatrixXd& value);

      /// \brief Computes the minimal distance in tangent space between the current value of the DV and xHat
      void minimalDifference(const Eigen::MatrixXd& xHat, Eigen::VectorXd& outDifference) const;

      /// \brief Computes the minimal distance in tangent space between the current value of the DV and xHat and the jacobian
      void minimalDifferenceAndJacobian(const Eigen::MatrixXd& xHat, Eigen::VectorXd& outDifference, Eigen::MatrixXd& outJacobian) const;

    protected:
      /// \brief what is the number of dimensions of the perturbation variable.
      virtual int minimalDimensionsImplementation() const = 0;

      /// \brief Update the design variable.
      virtual void updateImplementation(const double* dp, int size) = 0;

      /// \brief Revert the last state update.
      virtual void revertUpdateImplementation() = 0;

      /// Returns the content of the design variable
      virtual void getParametersImplementation(Eigen::MatrixXd& value)
        const = 0;

      /// Sets the content of the design variable
      virtual void setParametersImplementation(const Eigen::MatrixXd& value)
        = 0;

      /// Computes the minimal distance in tangent space between the current value of the DV and xHat
      virtual void minimalDifferenceImplementation(const Eigen::MatrixXd& xHat, Eigen::VectorXd& outDifference) const;

      /// Computes the minimal distance in tangent space between the current value of the DV and xHat and the jacobian
      virtual void minimalDifferenceAndJacobianImplementation(const Eigen::MatrixXd& xHat, Eigen::VectorXd& outDifference, Eigen::MatrixXd& outJacobian) const;

    private:
      /// \brief The block index used in the optimization routine.
      int _blockIndex;

      /// \brief The column base of this block in the Jacobian matrix
      int _columnBase;

      /// \brief Should this variable be marginalized in the schur-complement step?
      bool _isMarginalized;

      /// \brief is the design variable active in the optimization?
      bool _isActive;

      /// \brief The scaling of this design variable within the optimization.
      double _scaling;

    };

  } // namespace backend
} // namespace aslam

#endif /* ASLAM_DESIGN_VARIABLE_HPP */

max_stars_repo_name: PushyamiKaveti/kalibr

max_issues_repo_name: PushyamiKaveti/kalibr

max_forks_repo_name: PushyamiKaveti/kalibr


text:
// Copyright (c) Prevail Verifier contributors.
// SPDX-License-Identifier: MIT
#include <set>
#include <regex>

#include <boost/lexical_cast.hpp>

#include "string_constraints.hpp"

#include "crab/split_dbm.hpp"
#include "crab/variable.hpp"
#include "crab/linear_constraint.hpp"
#include "crab/dsl_syntax.hpp"

using crab::data_kind_t;
using crab::variable_t;

using std::regex;
using std::string;
using std::map;

#define REG R"_(\s*(r\d\d?)\s*)_"
#define KIND R"_(\s*(type|value|ctx_offset|map_fd|packet_offset|shared_offset|stack_offset|shared_region_size|stack_numeric_size)\s*)_"
#define IMM R"_(\s*\[?([-+]?\d+)\]?\s*)_"
#define INTERVAL R"_(\s*\[([-+]?\d+),\s*([-+]?\d+)\]?\s*)_"
#define ARRAY_RANGE R"_(\s*\[([-+]?\d+)\.\.\.\s*([-+]?\d+)\]?\s*)_"

#define DOT "[.]"
#define TYPE R"_(\s*(shared|number|packet|stack|ctx|map_fd|map_fd_program)\s*)_"

static uint8_t regnum(const string& s) {
    return (uint8_t)boost::lexical_cast<uint16_t>(s.substr(1));
}

static crab::data_kind_t regkind(const string& s) {
    if (s == "type") return crab::data_kind_t::types;
    if (s == "ctx_offset") return crab::data_kind_t::ctx_offsets;
    if (s == "map_fd") return crab::data_kind_t::map_fds;
    if (s == "packet_offset") return crab::data_kind_t::packet_offsets;
    if (s == "shared_offset") return crab::data_kind_t::shared_offsets;
    if (s == "stack_offset") return crab::data_kind_t::stack_offsets;
    if (s == "shared_region_size") return crab::data_kind_t::shared_region_sizes;
    if (s == "stack_numeric_size") return crab::data_kind_t::stack_numeric_sizes;
    if (s == "value") return crab::data_kind_t::values;
    throw std::runtime_error(string() + "Bad kind: " + s);
}

static long number(const string& s) {
    try {
        return (long)boost::lexical_cast<int64_t>(s);
    } catch (const boost::bad_lexical_cast&) {
        throw std::invalid_argument("number too large");
    }
}

static type_encoding_t string_to_type_encoding(const string& s) {
    static map<string, type_encoding_t> string_to_type{
        {string("uninit"), T_UNINIT},
        {string("map_fd_programs"), T_MAP_PROGRAMS},
        {string("map_fd"), T_MAP},
        {string("number"), T_NUM},
        {string("ctx"), T_CTX},
        {string("stack"), T_STACK},
        {string("packet"), T_PACKET},
        {string("shared"), T_SHARED},
    };
    if (string_to_type.count(s)) {
        return string_to_type[s];
    }
    throw std::runtime_error(string("Unsupported type name: ") + s);
}

std::vector<linear_constraint_t> parse_linear_constraints(const std::set<string>& constraints, std::vector<crab::interval_t>& numeric_ranges) {
    using namespace crab::dsl_syntax;

    std::vector<linear_constraint_t> res;
    for (const string& cst_text : constraints) {
        std::smatch m;
        if (regex_match(cst_text, m, regex("meta_offset" "=" IMM))) {
            res.push_back(variable_t::meta_offset() == number(m[1]));
        } else if (regex_match(cst_text, m, regex("packet_size" "=" INTERVAL))) {
            variable_t d = variable_t::packet_size();
            res.push_back(number(m[1]) <= d);
            res.push_back(d <= number(m[2]));
        } else if (regex_match(cst_text, m, regex("packet_size" "=" REG DOT KIND))) {
            variable_t d = variable_t::packet_size();
            variable_t s = variable_t::reg(regkind(m[2]), regnum(m[1]));
            res.push_back(equals(d, s));
        } else if (regex_match(cst_text, m, regex(REG DOT KIND "=" "packet_size"))) {
            variable_t d = variable_t::reg(regkind(m[2]), regnum(m[1]));
            res.push_back(equals(d, variable_t::packet_size()));
        } else if (regex_match(cst_text, m, regex(REG DOT KIND "=" REG DOT KIND))) {
            variable_t d = variable_t::reg(regkind(m[2]), regnum(m[1]));
            variable_t s = variable_t::reg(regkind(m[4]), regnum(m[3]));
            res.push_back(equals(d, s));
        } else if (regex_match(cst_text, m, regex(REG DOT "type" "=" TYPE))) {
            variable_t d = variable_t::reg(data_kind_t::types, regnum(m[1]));
            res.push_back(d == string_to_type_encoding(m[2]));
        } else if (regex_match(cst_text, m, regex(REG DOT KIND "=" IMM))) {
            variable_t d = variable_t::reg(regkind(m[2]), regnum(m[1]));
            res.push_back(d == number(m[3]));
        } else if (regex_match(cst_text, m, regex(REG DOT KIND "=" INTERVAL))) {
            variable_t d = variable_t::reg(regkind(m[2]), regnum(m[1]));
            res.push_back(number(m[3]) <= d);
            res.push_back(d <= number(m[4]));
        } else if (regex_match(cst_text, m, regex(REG DOT KIND "-" REG DOT KIND "<=" IMM))) {
            variable_t d = variable_t::reg(regkind(m[2]), regnum(m[1]));
            variable_t s = variable_t::reg(regkind(m[4]), regnum(m[3]));
            long diff = number(m[5]);
            res.push_back(d - s <= number_t(diff));
        } else if (regex_match(cst_text, m, regex("s" ARRAY_RANGE DOT "type" "=" TYPE))) {
            type_encoding_t type = string_to_type_encoding(m[3]);
            if (type == type_encoding_t::T_NUM) {
                numeric_ranges.push_back(crab::interval_t(number(m[1]), number(m[2])));
            } else {
                long lb = number(m[1]);
                long ub = number(m[2]);
                variable_t d = variable_t::cell_var(data_kind_t::types, lb, ub - lb + 1);
                res.push_back(d == type);
            }
        } else {
            throw std::runtime_error(string("Unknown constraint: ") + cst_text);
        }
    }
    return res;
}

// return a-b, taking account potential optional-none
string_invariant string_invariant::operator-(const string_invariant& b) const {
    if (this->is_bottom()) return string_invariant::bottom();
    string_invariant res = string_invariant::top();
    for (const std::string& cst : this->value()) {
        if (b.is_bottom() || !b.contains(cst))
            res.maybe_inv->insert(cst);
    }
    return res;
}

// return a+b, taking account potential optional-none
string_invariant string_invariant::operator+(const string_invariant& b) const {
    if (this->is_bottom())
        return b;
    string_invariant res = *this;
    for (const std::string& cst : b.value()) {
        if (res.is_bottom() || !res.contains(cst))
            res.maybe_inv->insert(cst);
    }
    return res;
}

std::ostream& operator<<(std::ostream& o, const string_invariant& inv) {
    if (inv.is_bottom()) {
        return o << "_|_";
    }
    // Intervals
    bool first = true;
    o << "[";
    auto& set = inv.maybe_inv.value();
    std::string lastbase;
    for (const auto& item : set) {
        if (first)
            first = false;
        else
            o << ", ";
        size_t pos = item.find_first_of(".=[");
        std::string base = item.substr(0, pos);
        if (base != lastbase) {
            o << "\n    ";
            lastbase = base;
        }
        o << item;
    }
    o << "]";
    return o;
}


text:
#include <boost/test/unit_test.hpp>

// File being tested:
#include "temperature_engine.h"

using namespace scottz0r::temperature;

BOOST_AUTO_TEST_SUITE(temperature_engine)

BOOST_AUTO_TEST_CASE(it_should_vote_agreement)
{
    TemperatureReading temp0{true, 2400};
    TemperatureReading temp1{true, 2425};
    TemperatureReading temp2{true, 2420};

    TemperatureVoteEngine engine(50);
    TemperatureVoteResult result;

    engine.vote_temperature(temp0, temp1, temp2, result);

    BOOST_CHECK(result.status == TemperatureVoteStatus::OK);
    BOOST_TEST(result.is_temp0_agree);
    BOOST_TEST(result.is_temp1_agree);
    BOOST_TEST(result.is_temp2_agree);
    BOOST_TEST(result.temp0 == 2400);
    BOOST_TEST(result.temp1 == 2425);
    BOOST_TEST(result.temp2 == 2420);
    BOOST_TEST(result.average == 2415);
}

BOOST_AUTO_TEST_CASE(it_should_vote_agreement_round_truncate)
{
    TemperatureReading temp0{true, 2400};
    TemperatureReading temp1{true, 2425};
    TemperatureReading temp2{true, 2422};

    // Sum = 7247, which is not divisible by 3.
    TemperatureVoteEngine engine(50);
    TemperatureVoteResult result;

    engine.vote_temperature(temp0, temp1, temp2, result);

    BOOST_CHECK(result.status == TemperatureVoteStatus::OK);
    BOOST_TEST(result.average == 2415);
}

BOOST_AUTO_TEST_CASE(it_should_vote_one_disagree)
{
    TemperatureReading temp0{true, 2400};
    TemperatureReading temp1{true, 5000};
    TemperatureReading temp2{true, 2420};

    TemperatureVoteEngine engine(100);
    TemperatureVoteResult result;

    engine.vote_temperature(temp0, temp1, temp2, result);

    BOOST_CHECK(result.status == TemperatureVoteStatus::OK);
    BOOST_TEST(result.is_temp0_agree);
    BOOST_TEST(!result.is_temp1_agree);
    BOOST_TEST(result.is_temp2_agree);
    BOOST_TEST(result.temp0 == 2400);
    BOOST_TEST(result.temp1 == 5000);
    BOOST_TEST(result.temp2 == 2420);
    BOOST_TEST(result.average == 2410);
}

BOOST_AUTO_TEST_CASE(it_should_vote_all_disagree)
{
    TemperatureReading temp0{true, 2400};
    TemperatureReading temp1{true, 2425};
    TemperatureReading temp2{true, 2375};

    TemperatureVoteEngine engine(20);
    TemperatureVoteResult result;

    engine.vote_temperature(temp0, temp1, temp2, result);

    BOOST_CHECK(result.status == TemperatureVoteStatus::Disagree);
    BOOST_TEST(!result.is_temp0_agree);
    BOOST_TEST(!result.is_temp1_agree);
    BOOST_TEST(!result.is_temp2_agree);
    BOOST_TEST(result.temp0 == 2400);
    BOOST_TEST(result.temp1 == 2425);
    BOOST_TEST(result.temp2 == 2375);
    BOOST_TEST(result.average == 0);
}

BOOST_AUTO_TEST_CASE(it_should_vote_one_invalid)
{
    TemperatureReading temp0{true, 2400};
    TemperatureReading temp1{true, 2424};
    TemperatureReading temp2{false, 9999};

    TemperatureVoteEngine engine(100);
    TemperatureVoteResult result;

    engine.vote_temperature(temp0, temp1, temp2, result);

    BOOST_CHECK(result.status == TemperatureVoteStatus::OK);
    BOOST_TEST(result.is_temp0_agree);
    BOOST_TEST(result.is_temp1_agree);
    BOOST_TEST(!result.is_temp2_agree);
    BOOST_TEST(result.temp0 == 2400);
    BOOST_TEST(result.temp1 == 2424);
    BOOST_TEST(result.temp2 == 0);
    BOOST_TEST(result.average == 2412);
}

BOOST_AUTO_TEST_CASE(it_should_vote_two_invalid)
{
    TemperatureReading temp0{true, 2400};
    TemperatureReading temp1{false, 2400};
    TemperatureReading temp2{false, 9999};

    TemperatureVoteEngine engine(100);
    TemperatureVoteResult result;

    engine.vote_temperature(temp0, temp1, temp2, result);

    BOOST_CHECK(result.status == TemperatureVoteStatus::SensorError);
    BOOST_TEST(!result.is_temp0_agree);
    BOOST_TEST(!result.is_temp1_agree);
    BOOST_TEST(!result.is_temp2_agree);
    BOOST_TEST(result.temp0 == 2400);
    BOOST_TEST(result.temp1 == 0);
    BOOST_TEST(result.temp2 == 0);
    BOOST_TEST(result.average == 0);
}

BOOST_AUTO_TEST_CASE(it_should_vote_three_invalid)
{
    TemperatureReading temp0{false, 2425};
    TemperatureReading temp1{false, 2400};
    TemperatureReading temp2{false, 9999};

    TemperatureVoteEngine engine(100);
    TemperatureVoteResult result;

    engine.vote_temperature(temp0, temp1, temp2, result);

    BOOST_CHECK(result.status == TemperatureVoteStatus::SensorError);
    BOOST_TEST(!result.is_temp0_agree);
    BOOST_TEST(!result.is_temp1_agree);
    BOOST_TEST(!result.is_temp2_agree);
    BOOST_TEST(result.temp0 == 0);
    BOOST_TEST(result.temp1 == 0);
    BOOST_TEST(result.temp2 == 0);
    BOOST_TEST(result.average == 0);
}

BOOST_AUTO_TEST_CASE(it_should_vote_one_invalid_disagree)
{
    TemperatureReading temp0{true, -250};
    TemperatureReading temp1{true, 1000};
    TemperatureReading temp2{false, -16021};

    TemperatureVoteEngine engine(50);
    TemperatureVoteResult result;

    engine.vote_temperature(temp0, temp1, temp2, result);

    BOOST_CHECK(result.status == TemperatureVoteStatus::Disagree);
    BOOST_TEST(!result.is_temp0_agree);
    BOOST_TEST(!result.is_temp1_agree);
    BOOST_TEST(!result.is_temp2_agree);
    BOOST_TEST(result.temp0 == -250);
    BOOST_TEST(result.temp1 == 1000);
    BOOST_TEST(result.temp2 == 0);
    BOOST_TEST(result.average == 0);
}

BOOST_AUTO_TEST_CASE(it_should_set_output_default_values)
{
    TemperatureReading temp0{false, 999};
    TemperatureReading temp1{false, 888};
    TemperatureReading temp2{false, -777};

    TemperatureVoteEngine engine(100);
    TemperatureVoteResult result;

    engine.vote_temperature(temp0, temp1, temp2, result);

    BOOST_CHECK(result.status == TemperatureVoteStatus::SensorError);
    BOOST_TEST(!result.is_temp0_agree);
    BOOST_TEST(!result.is_temp1_agree);
    BOOST_TEST(!result.is_temp2_agree);
    BOOST_TEST(result.temp0 == 0);
    BOOST_TEST(result.temp1 == 0);
    BOOST_TEST(result.temp2 == 0);
    BOOST_TEST(result.average == 0);
}

BOOST_AUTO_TEST_SUITE_END()


text:
#include "partition/partitioner.hpp"
#include "partition/bisection_graph.hpp"
#include "partition/bisection_to_partition.hpp"
#include "partition/cell_storage.hpp"
#include "partition/compressed_node_based_graph_reader.hpp"
#include "partition/edge_based_graph_reader.hpp"
#include "partition/files.hpp"
#include "partition/multi_level_partition.hpp"
#include "partition/recursive_bisection.hpp"
#include "partition/remove_unconnected.hpp"
#include "partition/renumber.hpp"

#include "extractor/files.hpp"

#include "util/coordinate.hpp"
#include "util/geojson_debug_logger.hpp"
#include "util/geojson_debug_policies.hpp"
#include "util/integer_range.hpp"
#include "util/json_container.hpp"
#include "util/log.hpp"
#include "util/mmap_file.hpp"

#include <algorithm>
#include <iterator>
#include <vector>

#include <boost/assert.hpp>
#include <boost/filesystem/operations.hpp>

#include "util/geojson_debug_logger.hpp"
#include "util/geojson_debug_policies.hpp"
#include "util/json_container.hpp"
#include "util/timing_util.hpp"

namespace osrm
{
namespace partition
{

void LogGeojson(const std::string &filename, const std::vector<std::uint32_t> &bisection_ids)
{
    // reload graph, since we destroyed the old one
    auto compressed_node_based_graph = LoadCompressedNodeBasedGraph(filename);

    util::Log() << "Loaded compressed node based graph: "
                << compressed_node_based_graph.edges.size() << " edges, "
                << compressed_node_based_graph.coordinates.size() << " nodes";

    groupEdgesBySource(begin(compressed_node_based_graph.edges),
                       end(compressed_node_based_graph.edges));

    auto graph =
        makeBisectionGraph(compressed_node_based_graph.coordinates,
                           adaptToBisectionEdge(std::move(compressed_node_based_graph.edges)));

    const auto get_level = [](const std::uint32_t lhs, const std::uint32_t rhs) {
        auto xored = lhs ^ rhs;
        std::uint32_t level = log(xored) / log(2.0);
        return level;
    };

    std::vector<std::vector<util::Coordinate>> border_vertices(33);

    for (NodeID nid = 0; nid < graph.NumberOfNodes(); ++nid)
    {
        const auto source_id = bisection_ids[nid];
        for (const auto &edge : graph.Edges(nid))
        {
            const auto target_id = bisection_ids[edge.target];
            if (source_id != target_id)
            {
                auto level = get_level(source_id, target_id);
                border_vertices[level].push_back(graph.Node(nid).coordinate);
                border_vertices[level].push_back(graph.Node(edge.target).coordinate);
            }
        }
    }

    util::ScopedGeojsonLoggerGuard<util::CoordinateVectorToMultiPoint> guard(
        "border_vertices.geojson");
    std::size_t level = 0;
    for (auto &bv : border_vertices)
    {
        if (!bv.empty())
        {
            std::sort(bv.begin(), bv.end(), [](const auto lhs, const auto rhs) {
                return std::tie(lhs.lon, lhs.lat) < std::tie(rhs.lon, rhs.lat);
            });
            bv.erase(std::unique(bv.begin(), bv.end()), bv.end());

            util::json::Object jslevel;
            jslevel.values["level"] = util::json::Number(level++);
            guard.Write(bv, jslevel);
        }
    }
}

auto getGraphBisection(const PartitionConfig &config)
{
    auto compressed_node_based_graph =
        LoadCompressedNodeBasedGraph(config.GetPath(".osrm.cnbg").string());

    util::Log() << "Loaded compressed node based graph: "
                << compressed_node_based_graph.edges.size() << " edges, "
                << compressed_node_based_graph.coordinates.size() << " nodes";

    groupEdgesBySource(begin(compressed_node_based_graph.edges),
                       end(compressed_node_based_graph.edges));

    auto graph =
        makeBisectionGraph(compressed_node_based_graph.coordinates,
                           adaptToBisectionEdge(std::move(compressed_node_based_graph.edges)));

    util::Log() << " running partition: " << config.max_cell_sizes.front() << " " << config.balance
                << " " << config.boundary_factor << " " << config.num_optimizing_cuts << " "
                << config.small_component_size
                << " # max_cell_size balance boundary cuts small_component_size";
    RecursiveBisection recursive_bisection(graph,
                                           config.max_cell_sizes.front(),
                                           config.balance,
                                           config.boundary_factor,
                                           config.num_optimizing_cuts,
                                           config.small_component_size);

    // Return bisection ids, keyed by node based graph nodes
    return recursive_bisection.BisectionIDs();
}

int Partitioner::Run(const PartitionConfig &config)
{
    const std::vector<BisectionID> &node_based_partition_ids = getGraphBisection(config);

    // Up until now we worked on the compressed node based graph.
    // But what we actually need is a partition for the edge based graph to work on.
    // The following loads a mapping from node based graph to edge based graph.
    // Then loads the edge based graph tanslates the partition and modifies it.
    // For details see #3205

    std::vector<extractor::NBGToEBG> mapping;
    extractor::files::readNBGMapping(config.GetPath(".osrm.cnbg_to_ebg").string(), mapping);
    util::Log() << "Loaded node based graph to edge based graph mapping";

    auto edge_based_graph = LoadEdgeBasedGraph(config.GetPath(".osrm.ebg").string());
    util::Log() << "Loaded edge based graph for mapping partition ids: "
                << edge_based_graph.GetNumberOfEdges() << " edges, "
                << edge_based_graph.GetNumberOfNodes() << " nodes";

    // Partition ids, keyed by edge based graph nodes
    std::vector<NodeID> edge_based_partition_ids(edge_based_graph.GetNumberOfNodes(),
                                                 SPECIAL_NODEID);

    // Only resolve all easy cases in the first pass
    for (const auto &entry : mapping)
    {
        const auto u = entry.u;
        const auto v = entry.v;
        const auto forward_node = entry.forward_ebg_node;
        const auto backward_node = entry.backward_ebg_node;

        // This heuristic strategy seems to work best, even beating chosing the minimum
        // border edge bisection ID
        edge_based_partition_ids[forward_node] = node_based_partition_ids[u];
        if (backward_node != SPECIAL_NODEID)
            edge_based_partition_ids[backward_node] = node_based_partition_ids[v];
    }

    std::vector<Partition> partitions;
    std::vector<std::uint32_t> level_to_num_cells;
    std::tie(partitions, level_to_num_cells) =
        bisectionToPartition(edge_based_partition_ids, config.max_cell_sizes);

    auto num_unconnected = removeUnconnectedBoundaryNodes(edge_based_graph, partitions);
    util::Log() << "Fixed " << num_unconnected << " unconnected nodes";

    util::Log() << "Edge-based-graph annotation:";
    for (std::size_t level = 0; level < level_to_num_cells.size(); ++level)
    {
        util::Log() << "  level " << level + 1 << " #cells " << level_to_num_cells[level]
                    << " bit size " << std::ceil(std::log2(level_to_num_cells[level] + 1));
    }

    TIMER_START(renumber);
    auto permutation = makePermutation(edge_based_graph, partitions);
    renumber(edge_based_graph, permutation);
    renumber(partitions, permutation);
    {
        renumber(mapping, permutation);
        extractor::files::writeNBGMapping(config.GetPath(".osrm.cnbg_to_ebg").string(), mapping);
    }
    {
        boost::iostreams::mapped_file segment_region;
        auto segments = util::mmapFile<extractor::EdgeBasedNodeSegment>(
            config.GetPath(".osrm.fileIndex"), segment_region);
        renumber(segments, permutation);
    }
    {
        extractor::EdgeBasedNodeDataContainer node_data;
        extractor::files::readNodeData(config.GetPath(".osrm.ebg_nodes"), node_data);
        renumber(node_data, permutation);
        extractor::files::writeNodeData(config.GetPath(".osrm.ebg_nodes"), node_data);
    }
    if (boost::filesystem::exists(config.GetPath(".osrm.hsgr")))
    {
        util::Log(logWARNING) << "Found existing .osrm.hsgr file, removing. You need to re-run "
                                 "osrm-contract after osrm-partition.";
        boost::filesystem::remove(config.GetPath(".osrm.hsgr"));
    }
    TIMER_STOP(renumber);
    util::Log() << "Renumbered data in " << TIMER_SEC(renumber) << " seconds";

    TIMER_START(packed_mlp);
    MultiLevelPartition mlp{partitions, level_to_num_cells};
    TIMER_STOP(packed_mlp);
    util::Log() << "MultiLevelPartition constructed in " << TIMER_SEC(packed_mlp) << " seconds";

    TIMER_START(cell_storage);
    CellStorage storage(mlp, edge_based_graph);
    TIMER_STOP(cell_storage);
    util::Log() << "CellStorage constructed in " << TIMER_SEC(cell_storage) << " seconds";

    TIMER_START(writing_mld_data);
    files::writePartition(config.GetPath(".osrm.partition"), mlp);
    files::writeCells(config.GetPath(".osrm.cells"), storage);
    extractor::files::writeEdgeBasedGraph(config.GetPath(".osrm.ebg"),
                                          edge_based_graph.GetNumberOfNodes(),
                                          graphToEdges(edge_based_graph));
    TIMER_STOP(writing_mld_data);
    util::Log() << "MLD data writing took " << TIMER_SEC(writing_mld_data) << " seconds";

    return 0;
}

} // namespace partition
} // namespace osrm

max_stars_repo_name: neilbu/osrm-backend

max_issues_repo_name: neilbu/osrm-backend

max_forks_repo_name: neilbu/osrm-backend


text:
#pragma once

#include "interval_tree_fwd.hpp"
#include "interval_types.hpp"

#include "cairo-wrap/cairo_wrap.hpp"

#include <boost/optional.hpp>

#include <vector>

#define PUBLICIZE

namespace lib_interval_tree
{
//#####################################################################################################################
    using defnode = node <int, interval <int, closed>>;
    using deftree = interval_tree <int, closed>;
//#####################################################################################################################
    struct TreeGridNode
    {
        defnode const* node;
        std::pair <int, int> parentCoords;
    };
    struct TreeGrid
    {
        // (row-major)
        std::vector < // rows
            std::vector < // columns
                boost::optional <TreeGridNode>
            >
        > grid;
        int xMax = 0;
        int xMin = 0;
        int yMax = 0;
    };
//#####################################################################################################################
    void drawNode(Cairo::DrawContext* ctx, defnode const* node, double x, double y, bool drawPointers);
//---------------------------------------------------------------------------------------------------------------------
    template <typename NodeT>
    void drawNode(Cairo::DrawContext* ctx, interval_tree_iterator <NodeT> const& iter, double x, double y, bool drawPointers)
    {
        drawNode(ctx, iter.node_, x, y, drawPointers);
    }
//---------------------------------------------------------------------------------------------------------------------
    TreeGrid createGrid(deftree const& tree);
//---------------------------------------------------------------------------------------------------------------------
    void drawGrid(Cairo::DrawContext* ctx, TreeGrid const& grid, bool drawPointers, bool drawEmpty = false);
//---------------------------------------------------------------------------------------------------------------------
    Cairo::Surface createSurface(TreeGrid const& grid);
//---------------------------------------------------------------------------------------------------------------------
    template <typename... List>
    void drawTree(std::string const& fileName, lib_interval_tree::interval_tree <List...> const* tree, bool drawPointers = false)
    {
        auto grid = createGrid(*tree);
        auto surface = createSurface(grid);
        Cairo::DrawContext ctx(&surface);
        drawGrid(&ctx, grid, drawPointers);
        surface.saveToFile(fileName);
    }
//######################################################################################################
}

max_stars_repo_name: WeberNick/interval-tree

max_issues_repo_name: WeberNick/interval-tree

max_forks_repo_name: WeberNick/interval-tree