text:
#ifndef __GRAPHUTILS_HPP__
#define __GRAPHUTILS_HPP__

#include <string>
#include <unordered_map>
#include <utility>

#include <boost/graph/graphviz.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/range/iterator_range.hpp>

#include "AlignmentUtils.hpp"
#include "Utils.hpp"

struct VerticeProps {
  std::string name;
  std::string role;
};

struct EdgeProps {
  std::string label;
  alignmentGrouping gp;

  std::string lowlink;
};

struct GraphProps {
  std::string name;
};

using Graph_t = boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS,
                                    VerticeProps, EdgeProps, GraphProps>;

namespace Graph {

  using vDesc = Graph_t::vertex_descriptor;
  using eDesc = Graph_t::edge_descriptor;

  using vIter = Graph_t::vertex_iterator;
  using vIterPair = std::pair<vIter, vIter>;

  using eIter = Graph_t::edge_iterator;
  using eIterPair = std::pair<eIter, eIter>;

  using oeIter = Graph_t::out_edge_iterator;
  using oeIterPair = std::pair<oeIter, oeIter>;

  Graph_t parse(const std::string &path);

  bool isFinalState(const Graph_t &g, const Graph::vDesc &vd);

  Graph::vDesc getStart(const Graph_t &g);
  std::vector<Graph::vDesc> getEnds(const Graph_t &g);

  Range<Graph::oeIter> getOutEdges(const Graph_t &g, const Graph::vDesc &v);
  std::vector<Graph::eDesc> getOutEdgesVec(const Graph_t &g, const Graph::vDesc &v);

  Graph::vDesc getVertex(const std::string &vName, const Graph_t &g);
  Graph::vDesc getDst(const Graph::vDesc &v, const std::string &l, const Graph_t &g);

  std::vector<Graph::vDesc> getDestinations(const Graph_t &g, std::vector<Graph::eDesc> edges);

  void print(const Graph_t &g);

  void printVertices(const Graph_t &g);
  void printEdges(const Graph_t &g);

  void printOutEdge(const Graph_t &g, const Graph::eDesc &e);
  void printOutEdges(const Graph_t &g, const Graph::vDesc &vd);

}

#endif // __GRAPHUTILS_HPP__

max_stars_repo_name: flange/esp

max_issues_repo_name: flange/esp

max_forks_repo_name: flange/esp


text:
#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/cycle_canceling.hpp>
#include <boost/graph/push_relabel_max_flow.hpp>
#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>
#include <boost/graph/find_flow_cost.hpp>

// Graph Type with nested interior edge properties for Cost Flow Algorithms
typedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> traits;
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,
                              boost::property<boost::edge_capacity_t, long,
                                              boost::property<boost::edge_residual_capacity_t, long,
                                                              boost::property<boost::edge_reverse_t, traits::edge_descriptor,
                                                                              boost::property<boost::edge_weight_t, long>>>>>
    graph; // new! weightmap corresponds to costs
typedef boost::graph_traits<graph>::edge_descriptor edge_desc;
typedef boost::graph_traits<graph>::out_edge_iterator out_edge_it; // Iterator

// Custom edge adder class
class edge_adder
{
    graph &G;

public:
    explicit edge_adder(graph &G) : G(G) {}
    void add_edge(int from, int to, long capacity, long cost)
    {
        auto c_map = boost::get(boost::edge_capacity, G);
        auto r_map = boost::get(boost::edge_reverse, G);
        auto w_map = boost::get(boost::edge_weight, G); // new!
        const edge_desc e = boost::add_edge(from, to, G).first;
        const edge_desc rev_e = boost::add_edge(to, from, G).first;
        c_map[e] = capacity;
        c_map[rev_e] = 0; // reverse edge has no capacity!
        r_map[e] = rev_e;
        r_map[rev_e] = e;
        w_map[e] = cost;      // new assign cost
        w_map[rev_e] = -cost; // new negative cost
    }
};

using namespace std;

void solve()
{
    int buyers, sites, states;
    cin >> buyers >> sites >> states;

    graph G(states + sites + buyers);
    edge_adder adder(G);
    auto c_map = boost::get(boost::edge_capacity, G);
    auto r_map = boost::get(boost::edge_reverse, G);
    auto rc_map = boost::get(boost::edge_residual_capacity, G);

    auto source = boost::add_vertex(G);
    auto target = boost::add_vertex(G);

    int stateLimit;
    for (int state = 0; state < states; ++state) {
        cin >> stateLimit;
        adder.add_edge(source, state, stateLimit, 0);
    }

    int state;
    int offsetSites = states;
    for (int site = offsetSites; site < offsetSites + sites; ++site) {
        cin >> state; --state; // convert to 0 based
        adder.add_edge(state, site, 1, 0);
    }

    int bid;
    int maxBid = 100;
    int offsetBuyers = states + sites;
    for (int buyer = offsetBuyers; buyer < offsetBuyers + buyers; ++buyer) {
        for (int site = offsetSites; site < offsetSites + sites; ++site) {
            cin >> bid;
            adder.add_edge(site, buyer, 1, maxBid - bid); // Avoid negative costs
        }
        adder.add_edge(buyer, target, 1, 0);
    }

    boost::successive_shortest_path_nonnegative_weights(G, source, target);
    auto cost = boost::find_flow_cost(G);

    int flow = 0;
    out_edge_it e, eend;
    for (boost::tie(e, eend) = boost::out_edges(boost::vertex(source, G), G); e != eend; ++e)
    {
        flow += c_map[*e] - rc_map[*e];
    }
    cost = maxBid * flow - cost; // Convert back to actual cost

    cout << flow << " " << cost << endl;
}

int main()
{
    int t; cin >> t;
    for (int i = 0; i < t; ++i) {
        solve();
    }
    return 0;
}

ext: cpp

max_stars_repo_name: dsparber/algolab

max_issues_repo_name: dsparber/algolab

max_forks_repo_name: dsparber/algolab


text:
//
// Boost.Process
// ~~~~~~~~~~~~~
//
// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Boris Schaeling
//
// 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)
//

#include <boost/process/config.hpp>

#if defined(BOOST_POSIX_API)
#  if defined(__CYGWIN__)
#    undef BOOST_POSIX_API
#    define BOOST_CYGWIN_PATH
#  endif
#endif

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/test/unit_test.hpp>
#include <string>
#include <istream>

enum bp_api_type {
    posix_api,
    win32_api
}
#if defined(BOOST_POSIX_API)
bp_api_type = posix_api;
#elif defined(BOOST_WINDOWS_API)
bp_api_type = win32_api;
#else
#  error "Unsupported platform."
#endif

inline std::string get_helpers_path()
{
    boost::filesystem::path hp = boost::filesystem::initial_path();

#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
    hp /= "../../../bin.v2/libs/process/test/msvc-9.0/debug/link-static/helpers.exe";
#elif defined(sun) || defined(__sun)
#  if defined(__GNUG__)
    hp /= "../../../bin.v2/libs/process/test/gcc-3.4.6/debug/link-static/helpers";
#  elif defined(__SUNPRO_CC)
    hp /= "../../../bin.v2/libs/process/test/sun/debug/link-static/stdlib-sun-stlport/helpers";
#  endif
#elif defined(__CYGWIN__)
    hp /= "../../../bin.v2/libs/process/test/gcc-3.4.4/debug/link-static/helpers.exe";
#elif defined(__APPLE__)
    hp /= "../../../bin.v2/libs/process/test/darwin/debug/link-static/helpers";
#endif

    BOOST_REQUIRE_MESSAGE(boost::filesystem::exists(hp), hp.string() + " not found");

    return hp.string();
}

inline std::istream &portable_getline(std::istream &is, std::string &str)
{
    std::getline(is, str);
    std::string::size_type pos = str.rfind('\r');
    if (pos != std::string::npos)
        str.erase(pos);
    return is;
}

ext: hpp

max_stars_repo_name: Flusspferd/flusspferd

max_issues_repo_name: STEllAR-GROUP/octopus

max_forks_repo_name: STEllAR-GROUP/octopus


text:
/*
 * Copyright 2019 Applied Research Center for Computer Networks
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "SwitchManager.hpp"

#include "OFServer.hpp"
#include "Controller.hpp"
#include "SwitchImpl.hpp"
#include "DpidChecker.hpp"
#include "StatsRulesManager.hpp"

#include <runos/DeviceDb.hpp>
#include <runos/core/logging.hpp>

#include <fluid/of13msg.hh>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/thread/shared_mutex.hpp>

#include <vector>
#include <map>
#include <algorithm> // copy
#include <iterator> // back_inserter

namespace runos {

namespace of13 = fluid_msg::of13;

REGISTER_APPLICATION(SwitchManager, {"controller", "of-server",
                                     "dpid-checker", "stats-rules-manager", ""})

/////////////////
//// Handler ////
/////////////////

struct SwitchManager::implementation final
    : std::enable_shared_from_this<implementation>
    , OFMessageHandler<of13::FeaturesReply>
    , OFMessageHandler<of13::PortStatus>
{
    SwitchManager& app;
    StatsRulesManager* stats_rules_mgr;
    Controller* controller;
    OFServer* ofserver;
    Rc<DeviceDb> propdb;

    std::map<uint64_t, SwitchImplPtr> switches;
    mutable boost::shared_mutex smutex;

    implementation(SwitchManager& app)
        : app(app)
    {
        propdb = std::make_shared<DeviceDb>();
        propdb->add_default();
    }

    void connect_stats_rules_mgr()
    {
        QObject::connect(&app, &SwitchManager::portAdded,
                         stats_rules_mgr, &StatsRulesManager::installRules);
        QObject::connect(&app, &SwitchManager::portDeleted,
                         stats_rules_mgr, &StatsRulesManager::deleteRules);
        QObject::connect(&app, &SwitchManager::switchMaintenanceEnd,
                         stats_rules_mgr, &StatsRulesManager::clearStatsTable);
        QObject::connect(&app, &SwitchManager::portMaintenanceStart,
                         stats_rules_mgr, &StatsRulesManager::deleteRules);
        QObject::connect(&app, &SwitchManager::portMaintenanceEnd,
                         stats_rules_mgr, &StatsRulesManager::installRules);
    }

    safe::shared_ptr<SwitchImpl> switch_(uint64_t dpid) const
    {
        boost::shared_lock< boost::shared_mutex > lock(smutex);
        auto it = switches.find(dpid);
        return (it != switches.end()) ? it->second : nullptr;
    }

    SwitchImplPtr make_switch(of13::FeaturesReply& fr, OFConnectionPtr conn)
    {
        auto ret = std::make_shared<SwitchImpl>(fr, propdb, conn, &app);

        QObject::connect(ret.get(), &Switch::portAdded,
                         &app, &SwitchManager::portAdded);

        QObject::connect(ret.get(), &Switch::portDeleted,
                         &app, &SwitchManager::portDeleted);

        QObject::connect(ret.get(), &Switch::linkUp,
                         &app, &SwitchManager::linkUp);

        QObject::connect(ret.get(), &Switch::linkDown,
                         &app, &SwitchManager::linkDown);

        QObject::connect(ret.get(), &Switch::switchUp,
                         &app, &SwitchManager::switchUp);

        QObject::connect(ret.get(), &Switch::switchDown,
                         &app, &SwitchManager::switchDown);

        QObject::connect(ret.get(), &Switch::portMaintenanceStart,
                         &app, &SwitchManager::portMaintenanceStart);

        QObject::connect(ret.get(), &Switch::portMaintenanceEnd,
                         &app, &SwitchManager::portMaintenanceEnd);

        QObject::connect(ret.get(), &Switch::switchMaintenanceStart,
                         &app, &SwitchManager::switchMaintenanceStart);

        QObject::connect(ret.get(), &Switch::switchMaintenanceEnd,
                         &app, &SwitchManager::switchMaintenanceEnd);

        stats_rules_mgr->clearStatsTable(ret);

        return ret;
    }

    void remove_switch(uint64_t dpid)
    {
        boost::upgrade_lock< boost::shared_mutex > rslock(smutex);
        auto it = switches.find(dpid);
        if (switches.end() != it) {
            it->second.get()->disconnect();
            boost::upgrade_to_unique_lock< boost::shared_mutex > wslock(rslock);
            switches.erase(it);
        }
    }

    bool process(of13::FeaturesReply& fr, OFConnectionPtr conn) override
    {
        boost::upgrade_lock< boost::shared_mutex > rslock(smutex);
        auto it = switches.find(fr.datapath_id());
        if (it != switches.end()) {
            auto dpid = it->first;
            auto sw = it->second;
            if (sw->nbuffers() != fr.n_buffers() ||
                sw->ntables() != fr.n_tables() ||
                sw->capabilites() != fr.capabilities())
            {
                LOG(ERROR) << "Switch features changed for dpid=" << dpid << ". "
                           << "Assign new dpid or restart controller.";
                conn->close();
            } else {
                sw->set_up();
            }
            rslock.unlock();
        } else {
            boost::upgrade_to_unique_lock< boost::shared_mutex >
                wslock(rslock);
            switches.emplace(fr.datapath_id(), make_switch(fr, conn));
        }
        return true;
    }

    bool process(of13::PortStatus& ps, OFConnectionPtr conn) override
    {
        if (auto sw = switch_(conn->dpid())) {
            sw->process_event(ps);
        } else {
            LOG(WARNING) << "Ignoring port status from " << conn->dpid()
                         << " because it Switch instance isn't yet created";
        }
        return false;
    }
};

SwitchManager::SwitchManager() = default;
SwitchManager::~SwitchManager() = default;

void SwitchManager::init(Loader* loader, const Config&)
{
    qRegisterMetaType<runos::SwitchPtr>("SwitchPtr");
    qRegisterMetaType<fluid_msg::of13::Port>("of13::Port");

    impl.reset(new implementation{ *this });

    impl->controller = Controller::get(loader);
    impl->ofserver = OFServer::get(loader);
    impl->stats_rules_mgr = StatsRulesManager::get(loader);

    impl->connect_stats_rules_mgr();
    impl->controller->register_handler(impl, -50);
    QObject::connect(impl->ofserver, &OFServer::connectionDown,
        [this, dpid_checker = DpidChecker::get(loader)](OFConnectionPtr conn) {
            conn->reset_stats();
            SwitchImplPtr sw = impl->switch_(conn->dpid());
            if (sw) {
                sw->set_down();
            }
            if (not dpid_checker->isRegistered(conn->dpid())) {
                impl->remove_switch(sw->dpid());
            }
        }
    );
}

safe::shared_ptr<Switch> SwitchManager::switch_(uint64_t dpid) const
{
    return impl->switch_(dpid);
}

std::vector<SwitchPtr> SwitchManager::switches() const
{
    std::vector<SwitchPtr> ret;
    boost::shared_lock< boost::shared_mutex > lock(impl->smutex);
    boost::copy(impl->switches | boost::adaptors::map_values,
                std::back_inserter(ret));
    return ret;
}

} // namespace runos

ext: cc

max_stars_repo_name: estepanov-lvk/runos

max_issues_repo_name: estepanov-lvk/runos

max_forks_repo_name: estepanov-lvk/runos


text:
/*****************************************************************************************
 Copyright (C) 2020 Arjun Srinivasan Ambalam,Rajeshwar N.S
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
   * Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
   * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
     contributors may be used to endorse or promote products derived from
     this software without specific prior written permission.
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
******************************************************************************************/

/**
 *  @copyright MIT License 2020 Arjun Srinivasan Ambalam,Rajeshwar N.S
 *  @file    Navigatebot.hpp
 *  @author  Arjun Srinivasan Ambalam
 *  @author  Rajeshwar N.S
 *  @date    12/07/2020
 *  @version 1.0
 *
 *  @brief Final Project - wanderer-bot (Search and collect objects)
 *
 *  @section DESCRIPTION
 *  To test Navigation of robot
 */

#include <ros/ros.h>
#include <gtest/gtest.h>
#include <boost/thread.hpp>

/**
 *  @brief  Main Function for running tests
 *  @param  int argc, char argv
 *  @return int
 */
void Spinthread(void) {
    ros::Rate loop_rate(10);

    while (ros::ok()) {
        ros::spinOnce();
        loop_rate.sleep();
    }
}

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  ros::init(argc, argv, "testPlanner");
  ros::NodeHandle nh;
  boost::thread th(Spinthread);

  int ret = RUN_ALL_TESTS();

  if (ret > 0) {
    std::cout <<"Test" <<std::endl;
  }

  ros::shutdown();
  th.join();

  return RUN_ALL_TESTS();
}


text:
#include <gtest/gtest.h>
#include <boost/python.hpp>
#include <iostream>
#include <stdlib.h>
#include <thread>         // std::thread
#include <chrono>         // std::chrono::seconds
#include <string>

#include <https/combined_client.hpp>
#include <https/combined_client.hpp>
#include <https/https_server.hpp>

using namespace boost::python;

std::string g_program_path;

void GetParentPath(char** arg)
{
    g_program_path = arg[0];
    std::size_t found = g_program_path.find_last_of("/\\");
    g_program_path = g_program_path.substr(0,found);
};

void SpawnGSP()
{
    HttpsServer gsp("0.0.0.0", 443, g_program_path);
    try
    {
        gsp.Run();
    }
    catch (const std::exception& e)
    {
        std::cerr << "Error: " << e.what() << std::endl;
    }
};

void SpawnDTM(const std::string &file_path, int argc, wchar_t **wargv)
{
try
    {
        Py_Initialize();
        PySys_SetArgv(argc, wargv);
        object _mainModule = import("__main__");
        object _mainNamespace = _mainModule.attr("__dict__");

        //Testing executing a python script file
        //exec_file("script.py", _mainNamespace, _mainNamespace);
        //Run a simple file
        FILE* PScriptFile = fopen(file_path.c_str(), "r");
        if(PScriptFile){
            PyRun_SimpleFile(PScriptFile, file_path.c_str());
            fclose(PScriptFile);
        }
    }
    catch (error_already_set)
    {
        PyErr_Print();
    }
};

void Demo (size_t dcm_number)
{
    CombinedHttpsClient dcm(
            g_program_path, "0.0.0.0", "443",
            g_program_path, "0.0.0.0", "4430");

    std::cout << dcm.Get("/dcap") << std::endl;
    std::cout << dcm.Get("/tm") << std::endl;
    std::cout << dcm.Get("/edev") << std::endl;

    std::string freq = R"(<?xml version="1.0" encoding="utf-8"?>
    <FlowReservationRequest href="http://uri1" xmlns="urn:ieee:std:2030.5:ns">
    <mRID>0FB7</mRID>
    <description>description1</description>
    <version>0</version>
    <creationTime>1</creationTime>
    <durationRequested>0</durationRequested>
    <energyRequested>
        <multiplier>1</multiplier>
        <value>-140737488355328</value>
    </energyRequested>
    <intervalRequested>
        <duration>0</duration>
        <start>1</start>
    </intervalRequested>
    <powerRequested>
        <multiplier>1</multiplier>
        <value>1</value>
    </powerRequested>
    <RequestStatus>
        <dateTime>1</dateTime>
        <requestStatus>0</requestStatus>
    </RequestStatus>
    </FlowReservationRequest>)";
    std::cout << dcm.Post("/freq", freq) << std::endl;
    std::cout << dcm.Get("/fres") << std::endl;
    std::cout << dcm.Get("/sdev") << std::endl;
};

int main(int argc, char **argv)
{
    if (argc < 2)
    {
        std::cout << "ERROR: must provide number of dcm to demo.\n";
        std::cout << "\tExample: ./dtm_testing 10\n";
        return 0;
    }

    wchar_t** wargv = new wchar_t*[argc];
    for(int i = 0; i < argc; i++)
    {
        wargv[i] = Py_DecodeLocale(argv[i], nullptr);
    }

    GetParentPath(argv);
    size_t client_count = atoi(argv[1]);

    std::string script_path = g_program_path + "/dtm_server.py";
    std::thread dtm(SpawnDTM, script_path, argc, wargv);
    std::this_thread::sleep_for (std::chrono::seconds(1));
    std::thread gsp(SpawnGSP);
    std::this_thread::sleep_for (std::chrono::seconds(1));

    // spawn all the dcm clients
    std::vector <std::thread> dcm_pool;
    dcm_pool.reserve(client_count);
    for (size_t i = 0; i < client_count; i++)
    {
        std::thread t(Demo, i+1);
        dcm_pool.emplace_back(std::move(t));
    }

    // synchronize threads:
    for (auto &t : dcm_pool)
    {
        t.join();
    }

    dtm.detach();
    gsp.detach();
    return 0;
}

max_stars_repo_name: PortlandStatePowerLab/doe-egot-dtm

max_issues_repo_name: PortlandStatePowerLab/doe-egot-system

max_forks_repo_name: PortlandStatePowerLab/doe-egot-system


text:
////////////////////////////////////////////////////////////////////////////////////////////////////
// ParsePageContent.cpp
// Copyright (c) 2018 Pdfix. All Rights Reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////

#include "pdfixsdksamples/ParsePageContent.h"

// system
#include <string>
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
// project
#include "pdfixsdksamples/Utils.h"
#include "Pdfix.h"

using namespace PDFixSDK;
using namespace boost::property_tree;

namespace ParsePageContent {

  // ProcessObject gets the value of the object.
  void ProcessPageObject(PdsPageObject* obj, std::ostream& ss, std::string indent) {

    if (!obj) throw PdfixException();
    indent += "  ";
    ss << indent << "type: ";
    switch (obj->GetObjectType()) {
      case kPdsPageUnknown:
        ss << "unknown" << std::endl; break;
      case kPdsPageText: {
        ss << "text" << std::endl;
        auto text = ((PdsText*)obj);
        auto str = text->GetText();
        ss << indent << "text: " << ToUtf8(str) << std::endl;
        break;
      }
      case kPdsPageImage:{
        auto image = (PdsImage*)obj;
        auto stream = image->GetDataStm();
        ss << "image" << std::endl;
        auto sz = stream->GetSize();
        ss << indent << "image_stream_size: " << sz << std::endl;
        //std::vector<unsigned char> data;
        //data.resize(sz);
        //if (!stream->Read(0, &data[0], sz))
        //  throw PdfixException();
        //auto str = std::string(begin(data), begin(data) + std::min(sz, 100));
        //ss << indent << "image_stream: " << str << std::endl ;
        break;
        }
      case kPdsPagePath:{
        auto path = (PdsPath*)obj;
        auto points_num = path->GetNumPathPoints();
        ss << "path" << std::endl;
        ss << indent << "points_num: " << points_num << std::endl;
        break;
        }

      case kPdsPageShading:{
        auto shading = (PdsShading*)obj;
        auto id = shading->GetId();
        ss << "shading" << std::endl;
        ss << "blend_mode: " << shading->GetGState().blend_mode << std::endl;
        break;
        }
      case kPdsPageForm: {
        ss << "form" << std::endl;
        auto form = (PdsForm*)obj;
        auto content = form->GetContent();
        auto objects_num = content->GetNumObjects();
        if (objects_num > 0) {
          ss << indent << "/kids" << std::endl;
          indent += "  ";
          for (int i = 0; i < content->GetNumObjects(); i++) {
            ss << indent << "/" << i << std::endl;
            auto kid = content->GetObject(i);
            ProcessPageObject(kid, ss, indent );
          }
          indent = indent.substr(0, indent.length() - 2);
        }
        break;
      }
    }

    PdfRect bbox = obj->GetBBox();
    ss << indent << "/bbox" << std::endl;
    indent += "  ";
    ss << indent << "left: " << (float)bbox.left << std::endl;
    ss << indent << "top: " << (float)bbox.top << std::endl;
    ss << indent << "right: " << (float)bbox.right << std::endl;
    ss << indent << "bottom: " << (float)bbox.bottom << std::endl;
    indent = indent.substr(0,indent.length()-2);

    auto content_mark = obj->GetContentMark();
    if (content_mark) {
      for (int i = 0; i < content_mark->GetNumTags(); i++) {
        ss << indent << "/" << ToUtf8(content_mark->GetTagName(i)) << " ";
        auto dict = content_mark->GetTagObject(i);
        if (dict) {
          ss << "<<";
          for (int j = 0; j < dict->GetNumKeys(); j++) {
            auto key = dict->GetKey(j);
            ss << "/" << ToUtf8(key) << "(" << ToUtf8(dict->GetText(key.c_str())) << ") ";
          }
          ss << ">>";
        }
        ss << std::endl;
      }
    }
  }

  // Iterates the content on a page
  void Run(
    const std::wstring& open_path,              // source PDF document
    std::ostream& output,                       // output document
    int page_num
    ) {
    // initialize Pdfix
    if (!Pdfix_init(Pdfix_MODULE_NAME))
      throw std::runtime_error("Pdfix initialization fail");

    Pdfix* pdfix = GetPdfix();
    if (!pdfix)
      throw std::runtime_error("GetPdfix fail");

    PdfDoc* doc = nullptr;
    doc = pdfix->OpenDoc(open_path.c_str(), L"");
    if (!doc)
      throw PdfixException();

    PdfPage* page = doc->AcquirePage(page_num);
    if (!page)
      throw PdfixException();

    std::string indent = "  ";
    // get page content flags
    auto flags = page->GetContentFlags();
    output << "page_num " << page_num << std::endl;
    output << "/content_flags" << std::endl;
    output << indent << "text: " << (((flags & kContentText) != 0) ? "true" : "false") << std::endl;
    output << indent << "image: " << (((flags & kContentImage) != 0) ? "true" : "false") << std::endl;
    output << indent << "path: " << (((flags & kContentPath) != 0) ? "true" : "false") << std::endl;
    output << indent << "form: " << (((flags & kContentForm) != 0) ? "true" : "false") << std::endl;
    output << indent << "shading: " << (((flags & kContentShading) != 0) ? "true" : "false") << std::endl;
    output << indent << "text_transparent: " << (((flags & kContentTextTransparent) != 0) ? "true" : "false") << std::endl;
    output << indent << "text_fill: " << (((flags & kContentTextFill) != 0) ? "true" : "false") << std::endl;
    output << indent << "text_stroke: " << (((flags & kContentTextStroke) != 0) ? "true" : "false") << std::endl;

    output << "/root" << std::endl;
    output << indent << "/kids" << std::endl;
    indent += "  ";
    auto content = page->GetContent();
    auto count = content->GetNumObjects();
    for (int i = 0; i < count; i++) {
      output << indent << "/" << i << std::endl;
      ProcessPageObject(content->GetObject(i), output, indent);
    }

    page->Release();

    doc->Close();
    pdfix->Destroy();
  }
}

max_stars_repo_name: laoola/ProjectCode

max_issues_repo_name: laoola/ProjectCode

max_forks_repo_name: laoola/ProjectCode


text:
// Modified from NetKet source for YANNQ Project
// <Chae-Yeun Park>(chae.yeun.park@gmail.com)
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef YANNQ_ACTIVATIONS_HPP
#define YANNQ_ACTIVATIONS_HPP

#include <Eigen/Dense>
#include <complex>
#include <iostream>
#include <random>
#include <vector>

#include <Utilities/type_traits.hpp>
#include <Utilities/Utility.hpp>

#include <nlohmann/json.hpp>

namespace yannq {

/**
  Abstract class for Activations.
*/
namespace activation
{
template<typename T>
class Identity
{
public:
	using Scalar = T;
	using Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;
	using VectorRef = Eigen::Ref<Vector>;
	using VectorConstRef = Eigen::Ref<const Vector>;

	// A = Z
	inline void operator()(VectorConstRef Z, VectorRef A) const  {
		A.noalias() = Z;
	}

	// Apply the (derivative of activation function) matrix J to a vector F
	// A = Z
	// J = dA / dZ = I
	// G = J * F = F
	inline void ApplyJacobian(VectorConstRef /*Z*/, VectorConstRef /*A*/,
			VectorConstRef F,
			VectorRef G) const  {
		G.noalias() = F;
	}

	std::string name() const {
		return "Identity";
	}

	template<class Archive>
	void serialize(Archive& /*ar*/)
	{
	}
};

template<typename T>
class LnCosh
{
public:
	using Scalar = T;
	using Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;
	using VectorRef = Eigen::Ref<Vector>;
	using VectorConstRef = Eigen::Ref<const Vector>;

	// A = Lncosh(Z)
	inline void operator()(VectorConstRef Z, VectorRef A) const  {
		for (int i = 0; i < A.size(); ++i) {
			A(i) = logCosh(Z(i));
		}
	}

	// Apply the (derivative of activation function) matrix J to a vector F
	// A = Lncosh(Z)
	// J = dA / dZ
	// G = J * F
	inline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,
			VectorConstRef F,
			VectorRef G) const  {
		G.array() = F.array() * Z.array().tanh();
	}

	std::string name() const {
		return "LnCosh";
	}

	template<class Archive>
	void serialize(Archive& /*ar*/)
	{
	}
};

template<typename T>
class Tanh
{
public:
	using Scalar = T;
	using RealScalar = remove_complex_t<Scalar>;
	using Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;
	using VectorRef = Eigen::Ref<Vector>;
	using VectorConstRef = Eigen::Ref<const Vector>;

private:
	RealScalar constant_;

public:

	explicit Tanh(const RealScalar constant = 1.0) //constant*tanh(z/constant)
		: constant_{constant}
	{
	}

	// A = a*Tanh(Z/a)
	inline void operator()(VectorConstRef Z, VectorRef A) const  {
		A.array() = constant_ * (Z.array() / constant_).tanh();
	}

	// Apply the (derivative of activation function) matrix J to a vector F
	// A = a*Tanh(Z/a)
	// J = dA / dZ
	// G = J * F
	inline void ApplyJacobian(VectorConstRef /*Z*/, VectorConstRef A,
			VectorConstRef F,
			VectorRef G) const  {
		G.array() = F.array() * (1. - A.array() * A.array() / (constant_*constant_));
	}

	std::string name() const
	{
		return "Tanh";
	}

	template<class Archive>
	void serialize(Archive& ar)
	{
		ar(constant_);
	}
};

template<typename T>
class WeakTanh
{
public:
	using Scalar = T;
	using RealScalar = remove_complex_t<Scalar>;
	using Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;
	using VectorRef = Eigen::Ref<Vector>;
	using VectorConstRef = Eigen::Ref<const Vector>;

private:

public:

	explicit WeakTanh() //x - tanh(x)/2
	{
	}

	// A = a*Tanh(Z/a)
	inline void operator()(VectorConstRef Z, VectorRef A) const  {
		A.array() = Z.array();
		A.array() -= Z.array().tanh()/2.0;
	}

	// Apply the (derivative of activation function) matrix J to a vector F
	// A = Tanh(Z)
	// J = dA / dZ
	// G = J * F
	inline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,
			VectorConstRef F,
			VectorRef G) const  {
		Eigen::Array<T, Eigen::Dynamic, 1> tanh = Z.array().tanh();
		G.array() = F.array() * (1.0 +  tanh * tanh)/2.0;
	}

	std::string name() const
	{
		return "WeakTanh";
	}

	template<class Archive>
	void serialize(Archive& /*ar*/)
	{
	}
};

template<typename T>
class Sigmoid
{
	static_assert(!is_complex_type<T>::value, "Sigmoid now only supports real parameters");
public:
	using Scalar = T;
	using Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;
	using VectorRef = Eigen::Ref<Vector>;
	using VectorConstRef = Eigen::Ref<const Vector>;

	// A = Sigmoid(Z)
	inline void operator()(VectorConstRef Z, VectorRef A) const  {
		A.array() = Z.array().exp();
		A.array().inverse();
		A.array() += 1.;
		A.array().inverse();
	}

	// Apply the (derivative of activation function) matrix J to a vector F
	// A = Sigmoid(Z)
	// J = dA / dZ
	// G = J * F
	inline void ApplyJacobian(VectorConstRef /*Z*/, VectorConstRef A,
			VectorConstRef /*F*/,
			VectorRef G) const  {
		G.array() = (1. - A.array() ) * A.array();
	}

	std::string name() const
	{
		return "Sigmoid";
	}

	template<class Archive>
	void serialize(Archive& /*ar*/)
	{
	}
};

template<typename T, typename Enable = void>
class ReLU;

//for complex T
template<typename T>
class ReLU<T, typename std::enable_if<is_complex_type<T>::value>::type >
{
public:
	using Scalar = T;
	using RealScalar = remove_complex_t<Scalar>;
	using Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;
	using VectorRef = Eigen::Ref<Vector>;
	using VectorConstRef = Eigen::Ref<const Vector>;

	constexpr static RealScalar theta1_ = 3*M_PI/4;
	constexpr static RealScalar theta2_ = -M_PI/4;

	// A = ReLU(Z)
	inline void operator()(VectorConstRef Z, VectorRef A) const  {
		for (int i = 0; i < Z.size(); ++i) {
			A(i) =
				(std::arg(Z(i)) < theta1_) && (std::arg(Z(i)) > theta2_) ? Z(i) : 0.0;
		}
	}

	// Apply the (derivative of activation function) matrix J to a vector F
	// A = ReLU(Z)
	// J = dA / dZ
	// G = J * F = F
	inline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,
			VectorConstRef F,
			VectorRef G) const  {
		for (int i = 0; i < Z.size(); ++i) {
			G(i) =
				(std::arg(Z(i)) < theta1_) && (std::arg(Z(i)) > theta2_) ? F(i) : 0.0;
		}
	}

	std::string name() const
	{
		return "ReLU";
	}

	template<class Archive>
	void serialize(Archive& /*ar*/)
	{
	}
};
//For real T
template<typename T>
class ReLU<T, typename std::enable_if<!is_complex_type<T>::value>::type >
{
public:
	using Scalar = T;
	using Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;
	using VectorRef = Eigen::Ref<Vector>;
	using VectorConstRef = Eigen::Ref<const Vector>;

	// A = ReLU(Z)
	inline void operator()(VectorConstRef Z, VectorRef A) const  {
		for (int i = 0; i < Z.size(); ++i) {
			A(i) = std::max(Z(i), T{0.0});
		}
	}

	// Apply the (derivative of activation function) matrix J to a vector F
	// A = ReLU(Z)
	// J = dA / dZ
	// G = J * F = F
	inline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,
			VectorConstRef F,
			VectorRef G) const
	{
		for (int i = 0; i < Z.size(); ++i) {
			G(i) = Z(i)>0?F(i):T{0.0};
		}
	}

	std::string name() const
	{
		return "ReLU";
	}

	template<class Archive>
	void serialize(Archive& /*ar*/)
	{
	}
};

template<typename T, typename Enable = void>
class LeakyReLU;

//for complex T
template<typename T>
class LeakyReLU<T, typename std::enable_if<is_complex_type<T>::value>::type>
{
public:
	using Scalar = T;
	using RealScalar = remove_complex_t<Scalar>;
	using Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;
	using VectorRef = Eigen::Ref<Vector>;
	using VectorConstRef = Eigen::Ref<const Vector>;

	constexpr static RealScalar theta1_ = 3*M_PI/4;
	constexpr static RealScalar theta2_ = -M_PI/4;
	RealScalar negativeSlope_;

	LeakyReLU(const RealScalar negativeSlope = 0.1)
		: negativeSlope_{negativeSlope}
	{
	}

	// A = LeakyReLU(Z)
	inline void operator()(VectorConstRef Z, VectorRef A) const  {
		for (int i = 0; i < Z.size(); ++i) {
			A(i) =
				(std::arg(Z(i)) < theta1_) && (std::arg(Z(i)) > theta2_) ? Z(i) : negativeSlope_*Z(i);
		}
	}

	// Apply the (derivative of activation function) matrix J to a vector F
	// A = LeakyReLU(Z)
	// J = dA / dZ
	// G = J * F = F
	inline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,
			VectorConstRef F,
			VectorRef G) const
	{
		for (int i = 0; i < Z.size(); ++i) {
			G(i) =
				(std::arg(Z(i)) < theta1_) && (std::arg(Z(i)) > theta2_) ? F(i) : negativeSlope_*F(i);
		}
	}

	std::string name() const
	{
		return "LeakyReLU";
	}

	template<class Archive>
	void serialize(Archive& ar)
	{
		ar(negativeSlope_);
	}
};

//For real T
template<typename T>
class LeakyReLU<T, typename std::enable_if<!is_complex_type<T>::value>::type>
{
public:
	using Scalar = T;
	using Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;
	using VectorRef = Eigen::Ref<Vector>;
	using VectorConstRef = Eigen::Ref<const Vector>;

	Scalar negativeSlope_;

	LeakyReLU(const Scalar negativeSlope = 0.1)
		: negativeSlope_{negativeSlope}
	{
	}
	// A = LeakyReLU(Z)
	inline void operator()(VectorConstRef Z, VectorRef A) const  {
		for (int i = 0; i < Z.size(); ++i) {
			A(i) = Z(i)>0?Z(i):T{negativeSlope_*Z(i)};
		}
	}

	// Apply the (derivative of activation function) matrix J to a vector F
	// A = LeakyReLU(Z)
	// J = dA / dZ
	// G = J * F = F
	inline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,
			VectorConstRef F,
			VectorRef G) const
	{
		for (int i = 0; i < Z.size(); ++i) {
			G(i) = Z(i)>0?F(i):T{negativeSlope_*F(i)};
		}
	}

	std::string name() const
	{
		return "LeakyReLU";
	}
	template<class Archive>
	void serialize(Archive& ar)
	{
		ar(negativeSlope_);
	}
};

//For real T
template<typename T>
class HardTanh
{
public:
	static_assert(!is_complex_type<T>::value, "T must be a real type for HardTanh");
	using Scalar = T;
	using Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;
	using VectorRef = Eigen::Ref<Vector>;
	using VectorConstRef = Eigen::Ref<const Vector>;

	HardTanh()
	{
	}

	// A = hardtanh(Z)
	inline void operator()(VectorConstRef Z, VectorRef A) const
	{
		using std::abs;
		for (int i = 0; i < Z.size(); ++i)
		{
			A(i) = abs(Z(i))>1.0?copysign(1.0, Z(i)):Z(i);
		}
	}

	// Apply the (derivative of activation function) matrix J to a vector F
	// A = hardtanh(Z)
	// J = dA / dZ
	// G = J * F = F
	inline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,
			VectorConstRef F, VectorRef G) const
	{
		using std::abs;
		for (int i = 0; i < Z.size(); ++i) {
			G(i) = abs(Z(i))>1.0?0.0:F(i);
		}
	}

	std::string name() const
	{
		return "HardTanh";
	}

	template<class Archive>
	void serialize(Archive& /*ar*/)
	{
	}
};

template<typename T>
class SoftShrink
{
public:
	static_assert(!is_complex_type<T>::value, "T must be a real type for SoftShrink");
	using Scalar = T;
	using Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;
	using VectorRef = Eigen::Ref<Vector>;
	using VectorConstRef = Eigen::Ref<const Vector>;

	SoftShrink()
	{
	}

	// A = softshrink(Z)
	inline void operator()(VectorConstRef Z, VectorRef A) const
	{
		using std::abs;
		for (int i = 0; i < Z.size(); ++i)
		{
			A(i) = abs(Z(i))<1.0?0.0:(Z(i)-copysign(1.0,Z(i)));
		}
	}

	// Apply the (derivative of activation function) matrix J to a vector F
	// A = softshrink(Z)
	// J = dA / dZ
	// G = J * F = F
	inline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,
			VectorConstRef F, VectorRef G) const
	{
		using std::abs;
		for (int i = 0; i < Z.size(); ++i) {
			G(i) = abs(Z(i))<1.0?0.0:F(i);
		}
	}

	std::string name() const
	{
		return "SoftShrink";
	}

	template<class Archive>
	void serialize(Archive& /*ar*/)
	{
	}

};

template<typename T>
class LeakyHardTanh
{
public:
	static_assert(!is_complex_type<T>::value, "T must be a real type for LeakyHardTanh");
	using Scalar = T;
	using Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;
	using VectorRef = Eigen::Ref<Vector>;
	using VectorConstRef = Eigen::Ref<const Vector>;

	Scalar outsideSlope_;

	LeakyHardTanh(Scalar outsideSlope = 0.01)
		: outsideSlope_{outsideSlope}
	{
	}

	// A = leakyhardtanh(Z)
	inline void operator()(VectorConstRef Z, VectorRef A) const
	{
		using std::abs;
		for (int i = 0; i < Z.size(); ++i)
		{
			T val = abs(Z(i))>1.0?copysign(1.0, Z(i)):Z(i);
			val += abs(Z(i))<1.0?0.0:outsideSlope_*(Z(i)-copysign(1.0,Z(i)));
			A(i) = val;
		}
	}

	// Apply the (derivative of activation function) matrix J to a vector F
	// A = leakyhardtanh(Z)
	// J = dA / dZ
	// G = J * F = F
	inline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,
			VectorConstRef F, VectorRef G) const
	{
		using std::abs;
		for (int i = 0; i < Z.size(); ++i) {
			G(i) = abs(Z(i))>1.0?outsideSlope_*F(i):F(i);
		}
	}

	std::string name() const
	{
		return "LeakyHardTanh";
	}

	template<class Archive>
	void serialize(Archive& ar)
	{
		ar(outsideSlope_);
	}
};

template<typename T>
class SoftSign
{
public:
	static_assert(!is_complex_type<T>::value, "T must be a real type for SoftSign");
	using Scalar = T;
	using Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;
	using VectorRef = Eigen::Ref<Vector>;
	using VectorConstRef = Eigen::Ref<const Vector>;

	SoftSign()
	{
	}

	// A = softsign(Z)
	inline void operator()(VectorConstRef Z, VectorRef A) const
	{
		A.array() = Z.array()/(Z.array().abs()+1.0);
	}

	// Apply the (derivative of activation function) matrix J to a vector F
	// A = softsign(Z)
	// J = dA / dZ = I
	// G = J * F = F
	inline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,
			VectorConstRef F, VectorRef G) const
	{
		G.array() = (1.0+Z.array().abs()).square().inverse()*F.array();
	}

	std::string name() const
	{
		return "SoftSign";
	}

	template<class Archive>
	void serialize(Archive& /*ar*/)
	{
	}
};

template<typename T>
class Cos
{
private:
	T a_;
public:
	static_assert(!is_complex_type<T>::value, "T must be a real type for Cos");
	using Scalar = T;
	using Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;
	using VectorRef = Eigen::Ref<Vector>;
	using VectorConstRef = Eigen::Ref<const Vector>;

	Cos(T a = 1.0)
		: a_{a}
	{
	}

	// A = cos(Z)
	inline void operator()(VectorConstRef Z, VectorRef A) const
	{
		A.array() = a_*cos(Z.array()*M_PI/a_);
	}

	// Apply the (derivative of activation function) matrix J to a vector F
	// A = a*cos(\pi Z/a)
	// J = dA / dZ = \pi sin(\pi Z/ a)
	// G = J * F = F
	inline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,
			VectorConstRef F, VectorRef G) const
	{
		G.array() = -M_PI*sin(M_PI*Z.array()/a_)*F.array();
	}

	std::string name() const
	{
		return "Cos";
	}

	template<class Archive>
	void serialize(Archive& ar)
	{
		ar(a_);
	}
};
}//namsepace activation

}// namespace yannq

#endif

max_stars_repo_name: cecri/yannq

max_issues_repo_name: cecri/yannq

max_forks_repo_name: cecri/yannq


text:
#include "EdgeOperations2d.h"

#include <wmtk/TriMesh.h>
#include <wmtk/utils/VectorUtils.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <wmtk/ExecutionScheduler.hpp>

using namespace Edge2d;
using namespace wmtk;

auto renew = [](auto& m, auto op, auto& tris) {
    auto edges = m.new_edges_after(tris);
    auto optup = std::vector<std::pair<std::string, TriMesh::Tuple>>();
    for (auto& e : edges) optup.emplace_back(op, e);
    return optup;
};

auto edge_locker = [](auto& m, const auto& e, int task_id) -> bool {
    return m.try_set_edge_mutex_two_ring(e, task_id);
};

double EdgeOperations2d::compute_edge_cost_collapse_ar(const TriMesh::Tuple& t, double L) const
{
    double l = (vertex_attrs[t.vid(*this)].pos - vertex_attrs[t.switch_vertex(*this).vid(*this)].pos).norm();
    if (l < (4. / 5.) * L) return ((4. / 5.) * L - l);
    return -1;
}
double EdgeOperations2d::compute_edge_cost_split_ar(const TriMesh::Tuple& t, double L) const
{
    double l = (vertex_attrs[t.vid(*this)].pos - vertex_attrs[t.switch_vertex(*this).vid(*this)].pos).norm();
    if (l > (4. / 3.) * L) return (l - (4. / 3.) * L);
    return -1;
}

double EdgeOperations2d::compute_vertex_valence_ar(const TriMesh::Tuple& t) const
{
    std::vector<std::pair<TriMesh::Tuple, int>> valences(3);
    valences[0] = std::make_pair(t, get_one_ring_tris_for_vertex(t).size());
    auto t2 = t.switch_vertex(*this);
    valences[1] = std::make_pair(t2, get_one_ring_tris_for_vertex(t2).size());
    auto t3 = (t.switch_edge(*this)).switch_vertex(*this);
    valences[2] = std::make_pair(t3, get_one_ring_tris_for_vertex(t3).size());

    if ((t.switch_face(*this)).has_value()) {
        auto t4 = (((t.switch_face(*this)).value()).switch_edge(*this)).switch_vertex(*this);
        valences.emplace_back(t4, get_one_ring_tris_for_vertex(t4).size());
    }
    double cost_before_swap = 0.0;
    double cost_after_swap = 0.0;

    // check if it's internal vertex or bondary vertex
    // navigating starting one edge and getting back to the start

    for (int i = 0; i < valences.size(); i++) {
        TriMesh::Tuple vert = valences[i].first;
        int val = 6;
        auto one_ring_edges = get_one_ring_edges_for_vertex(vert);
        for (auto edge : one_ring_edges) {
            if (is_boundary_edge(edge)) {
                val = 4;
                break;
            }
        }
        cost_before_swap += (double)(valences[i].second - val) * (valences[i].second - val);
        cost_after_swap +=
            (i < 2) ? (double)(valences[i].second - 1 - val) * (valences[i].second - 1 - val)
                    : (double)(valences[i].second + 1 - val) * (valences[i].second + 1 - val);
    }
    return (cost_before_swap - cost_after_swap);
}

std::vector<double> EdgeOperations2d::average_len_valen()
{
    double average_len = 0.0;
    double average_valen = 0.0;
    auto edges = get_edges();
    auto verts = get_vertices();
    double maxlen = std::numeric_limits<double>::min();
    double maxval = std::numeric_limits<double>::min();
    double minlen = std::numeric_limits<double>::max();
    double minval = std::numeric_limits<double>::max();
    for (auto& loc : edges) {
        double currentlen =
            (vertex_attrs[loc.vid(*this)].pos - vertex_attrs[loc.switch_vertex(*this).vid(*this)].pos).norm();
        average_len += currentlen;
        if (maxlen < currentlen) maxlen = currentlen;
        if (minlen > currentlen) minlen = currentlen;
    }
    average_len /= edges.size();
    for (auto& loc : verts) {
        double currentval = get_one_ring_edges_for_vertex(loc).size();
        average_valen += currentval;
        if (maxval < currentval) maxval = currentval;
        if (minval > currentval) minval = currentval;
    }
    average_valen /= verts.size();
    int cnt = 0;
    std::vector<double> rtn{average_len, maxlen, minlen, average_valen, maxval, minval};
    return rtn;
}

std::vector<TriMesh::Tuple> Edge2d::EdgeOperations2d::new_edges_after_swap(
    const TriMesh::Tuple& t) const
{
    std::vector<TriMesh::Tuple> new_edges;
    std::vector<size_t> one_ring_fid;

    new_edges.push_back(t.switch_edge(*this));
    new_edges.push_back((t.switch_face(*this).value()).switch_edge(*this));
    new_edges.push_back((t.switch_vertex(*this)).switch_edge(*this));
    new_edges.push_back(((t.switch_vertex(*this)).switch_face(*this).value()).switch_edge(*this));
    return new_edges;
}

bool EdgeOperations2d::collapse_remeshing(double L)
{
    auto collect_all_ops = std::vector<std::pair<std::string, Tuple>>();
    for (auto& loc : get_edges()) collect_all_ops.emplace_back("edge_collapse", loc);

    auto setup_and_execute = [&](auto executor) {
        executor.renew_neighbor_tuples = renew;
        executor.priority = [&](auto& m, auto _, auto& e) {
            return -m.compute_edge_cost_collapse_ar(e, L);
        };
        executor.lock_vertices = edge_locker;

        executor.is_weight_up_to_date = [](auto& m, auto& ele) {
            auto& [val, op, e] = ele;
            if (val > 0) return false; // priority is negated.
            return true;
        };
        executor(*this, collect_all_ops);
    };
    if (NUM_THREADS > 0) {
        auto executor = wmtk::ExecutePass<EdgeOperations2d, ExecutionPolicy::kSeq>();
        setup_and_execute(executor);
    } else {
        auto executor = wmtk::ExecutePass<EdgeOperations2d, ExecutionPolicy::kPartition>();
        setup_and_execute(executor);
    }

    return true;
}
bool EdgeOperations2d::split_remeshing(double L)
{
    auto collect_all_ops = std::vector<std::pair<std::string, Tuple>>();
    for (auto& loc : get_edges()) collect_all_ops.emplace_back("edge_split", loc);

    auto setup_and_execute = [&](auto executor) {
        executor.num_threads = NUM_THREADS;

        executor.lock_vertices = edge_locker;

        executor.renew_neighbor_tuples = renew;
        executor.priority = [&](auto& m, auto _, auto& e) {
            return m.compute_edge_cost_split_ar(e, L);
        };
        executor.is_weight_up_to_date = [](auto& m, auto& ele) {
            auto& [val, op, e] = ele;
            if (val < 0) return false;
            return true;
        };
        executor(*this, collect_all_ops);
    };
    if (NUM_THREADS > 0) {
        auto executor = wmtk::ExecutePass<EdgeOperations2d, ExecutionPolicy::kSeq>();
        setup_and_execute(executor);
    } else {
        auto executor = wmtk::ExecutePass<EdgeOperations2d, ExecutionPolicy::kPartition>();
        setup_and_execute(executor);
    }

    return true;
}

bool EdgeOperations2d::swap_remeshing()
{
    auto collect_all_ops = std::vector<std::pair<std::string, Tuple>>();
    for (auto& loc : get_edges()) collect_all_ops.emplace_back("edge_swap", loc);

    auto setup_and_execute = [&](auto executor) {
        executor.renew_neighbor_tuples = renew;
        executor.priority = [](auto& m, auto op, const Tuple& e) {
            return m.compute_vertex_valence_ar(e);
        };
        executor.lock_vertices = edge_locker;
        executor.is_weight_up_to_date = [](auto& m, auto& ele) {
            auto& [val, _, e] = ele;
            auto val_energy = (m.compute_vertex_valence_ar(e));
            return (val_energy > 1e-5);
        };
        executor(*this, collect_all_ops);
    };
    if (NUM_THREADS > 0) {
        auto executor = wmtk::ExecutePass<EdgeOperations2d, ExecutionPolicy::kSeq>();
        setup_and_execute(executor);
    } else {
        auto executor = wmtk::ExecutePass<EdgeOperations2d, ExecutionPolicy::kPartition>();
        setup_and_execute(executor);
    }

    return true;
}
double area(EdgeOperations2d& m, std::array<TriMesh::Tuple, 3>& verts)
{
    return ((m.vertex_attrs[verts[0].vid(m)].pos - m.vertex_attrs[verts[2].vid(m)].pos)
                .cross(m.vertex_attrs[verts[1].vid(m)].pos - m.vertex_attrs[verts[2].vid(m)].pos))
               .norm() /
           2.0;
};

Eigen::Vector3d normal(EdgeOperations2d& m, std::array<TriMesh::Tuple, 3>& verts)
{
    return ((m.vertex_attrs[verts[0].vid(m)].pos - m.vertex_attrs[verts[2].vid(m)].pos)
                .cross(m.vertex_attrs[verts[1].vid(m)].pos - m.vertex_attrs[verts[2].vid(m)].pos))
        .normalized();
}

Eigen::Vector3d EdgeOperations2d::tangential_smooth(const Tuple& t)
{
    auto one_ring_tris = get_one_ring_tris_for_vertex(t);
    if (one_ring_tris.size() < 2) return vertex_attrs[t.vid(*this)].pos;
    Eigen::Vector3d after_smooth = smooth(t);
    // get normal and area of each face
    auto area = [](auto& m, auto& verts) {
        return ((m.vertex_attrs[verts[0].vid(m)].pos - m.vertex_attrs[verts[2].vid(m)].pos)
                    .cross(m.vertex_attrs[verts[1].vid(m)].pos - m.vertex_attrs[verts[2].vid(m)].pos))
                   .norm() /
               2.0;
    };
    auto normal = [](auto& m, auto& verts) {
        return ((m.vertex_attrs[verts[0].vid(m)].pos - m.vertex_attrs[verts[2].vid(m)].pos)
                    .cross(m.vertex_attrs[verts[1].vid(m)].pos - m.vertex_attrs[verts[2].vid(m)].pos))
            .normalized();
    };
    auto w0 = 0.0;
    Eigen::Vector3d n0(0.0, 0.0, 0.0);
    for (auto& e : one_ring_tris) {
        auto verts = oriented_tri_vertices(e);
        w0 += area(*this, verts);
        n0 += area(*this, verts) * normal(*this, verts);
    }
    n0 /= w0;
    after_smooth += n0 * n0.transpose() * (vertex_attrs[t.vid(*this)].pos - after_smooth);
    return after_smooth;
}

bool EdgeOperations2d::adaptive_remeshing(double L, int iterations, int sm)
{
    std::vector<double> avg_lens, max_lens, min_lens;
    std::vector<double> avg_valens, max_vals, min_vals;
    int cnt = 0;
    auto properties = average_len_valen();
    while ((properties[0] - L) * (properties[0] - L) > 1e-8 && cnt < iterations) {
        cnt++;
        avg_lens.push_back(properties[0]);
        avg_valens.push_back(properties[3]);
        max_lens.push_back(properties[1]);
        max_vals.push_back(properties[4]);
        min_lens.push_back(properties[2]);
        min_vals.push_back(properties[5]);

        // split
        split_remeshing(L);
        // collpase
        collapse_remeshing(L);

        // swap edges
        swap_remeshing();
        // smoothing
        auto vertices = get_vertices();
        if (sm == 0) {
            for (auto& loc : vertices) vertex_attrs[loc.vid(*this)].pos = smooth(loc);
        } else
            for (auto& loc : vertices) vertex_attrs[loc.vid(*this)].pos = tangential_smooth(loc);

        assert(check_mesh_connectivity_validity());
        consolidate_mesh();
        properties = average_len_valen();
    }
    wmtk::logger().info("avg edge len after each remesh is: ");
    wmtk::vector_print(avg_lens);
    wmtk::logger().info("max edge len after each remesh is: ");
    wmtk::vector_print(max_lens);
    wmtk::logger().info("min edge len after each remesh is: ");
    wmtk::vector_print(min_lens);

    wmtk::logger().info("avg valence after each remesh is: ");
    wmtk::vector_print(avg_valens);
    wmtk::logger().info("max valence after each remesh is: ");
    wmtk::vector_print(max_vals);
    wmtk::logger().info("min valence after each remesh is: ");
    wmtk::vector_print(min_vals);
    return true;
}

max_stars_repo_name: wildmeshing/wildmeshing-toolkit

max_issues_repo_name: wildmeshing/wildmeshing-toolkit

max_forks_repo_name: wildmeshing/wildmeshing-toolkit


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 _SDR_ATTRIBUTE_SDRALLFILLATTRIBUTESHELPER_HXX
#define _SDR_ATTRIBUTE_SDRALLFILLATTRIBUTESHELPER_HXX

#include "svx/svxdllapi.h"
#include <drawinglayer/attribute/fillgradientattribute.hxx>
#include <drawinglayer/attribute/sdrfillattribute.hxx>
#include <drawinglayer/primitive2d/baseprimitive2d.hxx>
#include <boost/shared_ptr.hpp>
#include <tools/color.hxx>
#include <svl/itemset.hxx>

//////////////////////////////////////////////////////////////////////////////

namespace drawinglayer
{
    namespace attribute
    {
        class SVX_DLLPUBLIC SdrAllFillAttributesHelper
        {
        private:
            basegfx::B2DRange                                                   maLastPaintRange;
            basegfx::B2DRange                                                   maLastDefineRange;
            boost::shared_ptr< drawinglayer::attribute::SdrFillAttribute >      maFillAttribute;
            boost::shared_ptr< drawinglayer::attribute::FillGradientAttribute > maFillGradientAttribute;
            drawinglayer::primitive2d::Primitive2DSequence                      maPrimitives;

            void createPrimitive2DSequence(
                const basegfx::B2DRange& rPaintRange,
                const basegfx::B2DRange& rDefineRange);

        protected:
        public:
            SdrAllFillAttributesHelper();
            SdrAllFillAttributesHelper(const Color& rColor);
            SdrAllFillAttributesHelper(const SfxItemSet& rSet);
            ~SdrAllFillAttributesHelper();

            bool isUsed() const;
            bool hasSdrFillAttribute() const { return maFillAttribute.get(); }
            bool hasFillGradientAttribute() const { return maFillGradientAttribute.get(); }
            bool isTransparent() const;

            const drawinglayer::attribute::SdrFillAttribute& getFillAttribute() const;
            const drawinglayer::attribute::FillGradientAttribute& getFillGradientAttribute() const;
            const drawinglayer::primitive2d::Primitive2DSequence& getPrimitive2DSequence(
                const basegfx::B2DRange& rPaintRange,
                const basegfx::B2DRange& rDefineRange) const;

            // get average fill color; tries to calculate a 'medium' color
            // which e.g. may be used as comparison to decide if other
            // colors are visible
            basegfx::BColor getAverageColor(const basegfx::BColor& rFallback) const;

            // return if a repaint of this content needs a complete repaint. This
            // is e.g. not needed for no fill or color fill (a partial repaint
            // will do the trick), but necessary for everything that is not top-left
            // oriented
            bool needCompleteRepaint() const;
        };
    } // end of namespace attribute
} // end of namespace drawinglayer

//////////////////////////////////////////////////////////////////////////////

namespace drawinglayer
{
    namespace attribute
    {
        typedef boost::shared_ptr< SdrAllFillAttributesHelper > SdrAllFillAttributesHelperPtr;
    } // end of namespace attribute
} // end of namespace drawinglayer

//////////////////////////////////////////////////////////////////////////////

#endif // _SDR_ATTRIBUTE_SDRALLFILLATTRIBUTESHELPER_HXX

// eof

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2014-2015, Oracle and/or its affiliates.

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

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

#ifndef BOOST_TEST_MODULE
#define BOOST_TEST_MODULE test_disjoint_coverage
#endif

// unit test to test disjoint for all geometry combinations

#include <iostream>

#include <boost/test/included/unit_test.hpp>

#include <boost/geometry/core/tag.hpp>
#include <boost/geometry/core/tags.hpp>

#include <boost/geometry/strategies/strategies.hpp>

#include <boost/geometry/io/wkt/wkt.hpp>
#include <boost/geometry/io/dsv/write.hpp>

#include <boost/geometry/geometries/geometries.hpp>

#include <boost/geometry/algorithms/disjoint.hpp>

#include <from_wkt.hpp>

#ifdef HAVE_TTMATH
#include <boost/geometry/extensions/contrib/ttmath_stub.hpp>
#endif

namespace bg = ::boost::geometry;

//============================================================================

struct test_disjoint
{
    template <typename Geometry1, typename Geometry2>
    static inline void apply(std::string const& case_id,
                             Geometry1 const& geometry1,
                             Geometry2 const& geometry2,
                             bool expected_result)
    {
        bool result = bg::disjoint(geometry1, geometry2);
        BOOST_CHECK_MESSAGE(result == expected_result,
            "case ID: " << case_id << ", G1: " << bg::wkt(geometry1)
            << ", G2: " << bg::wkt(geometry2) << " -> Expected: "
            << expected_result << ", detected: " << result);

        result = bg::disjoint(geometry2, geometry1);
        BOOST_CHECK_MESSAGE(result == expected_result,
            "case ID: " << case_id << ", G1: " << bg::wkt(geometry2)
            << ", G2: " << bg::wkt(geometry1) << " -> Expected: "
            << expected_result << ", detected: " << result);

#ifdef BOOST_GEOMETRY_TEST_DEBUG
        std::cout << "case ID: " << case_id << "; G1 - G2: ";
        std::cout << bg::wkt(geometry1) << " - ";
        std::cout << bg::wkt(geometry2) << std::endl;
        std::cout << std::boolalpha;
        std::cout << "expected/computed result: "
                  << expected_result << " / " << result << std::endl;
        std::cout << std::endl;
        std::cout << std::noboolalpha;
#endif
    }
};

//============================================================================

// pointlike-linear geometries
template <typename P>
inline void test_point_segment()
{
    typedef test_disjoint tester;
    typedef bg::model::segment<P> S;

    tester::apply("p-s-01",
                  from_wkt<P>("POINT(0 0)"),
                  from_wkt<S>("SEGMENT(0 0,2 0)"),
                  false);

    tester::apply("p-s-02",
                  from_wkt<P>("POINT(2 0)"),
                  from_wkt<S>("SEGMENT(0 0,2 0)"),
                  false);

    tester::apply("p-s-03",
                  from_wkt<P>("POINT(1 0)"),
                  from_wkt<S>("SEGMENT(0 0,2 0)"),
                  false);

    tester::apply("p-s-04",
                  from_wkt<P>("POINT(1 1)"),
                  from_wkt<S>("SEGMENT(0 0,2 0)"),
                  true);

    tester::apply("p-s-05",
                  from_wkt<P>("POINT(3 0)"),
                  from_wkt<S>("SEGMENT(0 0,2 0)"),
                  true);

    tester::apply("p-s-06",
                  from_wkt<P>("POINT(-1 0)"),
                  from_wkt<S>("SEGMENT(0 0,2 0)"),
                  true);

    // degenerate segment
    tester::apply("p-s-07",
                  from_wkt<P>("POINT(-1 0)"),
                  from_wkt<S>("SEGMENT(2 0,2 0)"),
                  true);

    // degenerate segment
    tester::apply("p-s-08",
                  from_wkt<P>("POINT(2 0)"),
                  from_wkt<S>("SEGMENT(2 0,2 0)"),
                  false);

    // degenerate segment
    tester::apply("p-s-09",
                  from_wkt<P>("POINT(3 0)"),
                  from_wkt<S>("SEGMENT(2 0,2 0)"),
                  true);

    // degenerate segment
    tester::apply("p-s-10",
                  from_wkt<P>("POINT(1 1)"),
                  from_wkt<S>("SEGMENT(2 0,2 0)"),
                  true);
}

template <typename P>
inline void test_point_linestring()
{
    typedef bg::model::linestring<P> L;

    typedef test_disjoint tester;

    tester::apply("p-l-01",
                  from_wkt<P>("POINT(0 0)"),
                  from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
                  false);

    tester::apply("p-l-02",
                  from_wkt<P>("POINT(1 1)"),
                  from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
                  false);

    tester::apply("p-l-03",
                  from_wkt<P>("POINT(3 3)"),
                  from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
                  false);

    tester::apply("p-l-04",
                  from_wkt<P>("POINT(1 0)"),
                  from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
                  true);

    tester::apply("p-l-05",
                  from_wkt<P>("POINT(5 5)"),
                  from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
                  true);

    tester::apply("p-l-06",
                  from_wkt<P>("POINT(5 5)"),
                  from_wkt<L>("LINESTRING(0 0,2 2)"),
                  true);
}

template <typename P>
inline void test_point_multilinestring()
{
    typedef bg::model::linestring<P> L;
    typedef bg::model::multi_linestring<L> ML;

    typedef test_disjoint tester;

    tester::apply("p-ml-01",
                  from_wkt<P>("POINT(0 1)"),
                  from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
                  true);

    tester::apply("p-ml-02",
                  from_wkt<P>("POINT(0 0)"),
                  from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
                  false);

    tester::apply("p-ml-03",
                  from_wkt<P>("POINT(1 1)"),
                  from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
                  false);

    tester::apply("p-ml-04",
                  from_wkt<P>("POINT(1 0)"),
                  from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
                  false);

    tester::apply("p-ml-05",
                  from_wkt<P>("POINT(0 0)"),
                  from_wkt<ML>("MULTILINESTRING((1 1,2 2,4 4),(3 0,4 0))"),
                  true);

    tester::apply("p-ml-06",
                  from_wkt<P>("POINT(0 0)"),
                  from_wkt<ML>("MULTILINESTRING((1 1,2 2,4 4),(0 0,4 0))"),
                  false);

    tester::apply("p-ml-07",
                  from_wkt<P>("POINT(0 0)"),
                  from_wkt<ML>("MULTILINESTRING((1 1,2 2,4 4),(-1 0,4 0))"),
                  false);
}

template <typename P>
inline void test_multipoint_segment()
{
    typedef test_disjoint tester;
    typedef bg::model::multi_point<P> MP;
    typedef bg::model::segment<P> S;

    tester::apply("mp-s-01",
                  from_wkt<MP>("MULTIPOINT(0 0,1 1)"),
                  from_wkt<S>("SEGMENT(0 0,2 0)"),
                  false);

    tester::apply("mp-s-02",
                  from_wkt<MP>("MULTIPOINT(1 0,1 1)"),
                  from_wkt<S>("SEGMENT(0 0,2 0)"),
                  false);

    tester::apply("mp-s-03",
                  from_wkt<MP>("MULTIPOINT(1 1,2 2)"),
                  from_wkt<S>("SEGMENT(0 0,2 0)"),
                  true);

    tester::apply("mp-s-04",
                  from_wkt<MP>("MULTIPOINT()"),
                  from_wkt<S>("SEGMENT(0 0,2 0)"),
                  true);

    tester::apply("mp-s-05",
                  from_wkt<MP>("MULTIPOINT(3 0,4 0)"),
                  from_wkt<S>("SEGMENT(0 0,2 0)"),
                  true);

    tester::apply("mp-s-06",
                  from_wkt<MP>("MULTIPOINT(1 0,4 0)"),
                  from_wkt<S>("SEGMENT(0 0,2 0)"),
                  false);

    // segments that degenerate to a point
    tester::apply("mp-s-07",
                  from_wkt<MP>("MULTIPOINT(1 1,2 2)"),
                  from_wkt<S>("SEGMENT(0 0,0 0)"),
                  true);

    tester::apply("mp-s-08",
                  from_wkt<MP>("MULTIPOINT(1 1,2 2)"),
                  from_wkt<S>("SEGMENT(1 1,1 1)"),
                  false);
}

template <typename P>
inline void test_multipoint_linestring()
{
    typedef bg::model::multi_point<P> MP;
    typedef bg::model::linestring<P> L;

    typedef test_disjoint tester;

    tester::apply("mp-l-01",
                  from_wkt<MP>("MULTIPOINT(0 0,1 0)"),
                  from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
                  false);

    tester::apply("mp-l-02",
                  from_wkt<MP>("MULTIPOINT(1 0,1 1)"),
                  from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
                  false);

    tester::apply("mp-l-03",
                  from_wkt<MP>("MULTIPOINT(1 0,3 3)"),
                  from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
                  false);

    tester::apply("mp-l-04",
                  from_wkt<MP>("MULTIPOINT(1 0,2 0)"),
                  from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
                  true);

    tester::apply("mp-l-05",
                  from_wkt<MP>("MULTIPOINT(-1 -1,2 0)"),
                  from_wkt<L>("LINESTRING(0 0,2 2,4 4)"),
                  true);

    tester::apply("mp-l-06",
                  from_wkt<MP>("MULTIPOINT(-1 -1,2 0)"),
                  from_wkt<L>("LINESTRING(1 0,3 0)"),
                  false);

    tester::apply("mp-l-07",
                  from_wkt<MP>("MULTIPOINT(-1 -1,2 0,-1 -1,2 0)"),
                  from_wkt<L>("LINESTRING(1 0,3 0)"),
                  false);

    tester::apply("mp-l-08",
                  from_wkt<MP>("MULTIPOINT(2 0)"),
                  from_wkt<L>("LINESTRING(1 0)"),
                  true);

    tester::apply("mp-l-09",
                  from_wkt<MP>("MULTIPOINT(3 0,0 0,3 0)"),
                  from_wkt<L>("LINESTRING(1 0,2 0)"),
                  true);
}

template <typename P>
inline void test_multipoint_multilinestring()
{
    typedef bg::model::multi_point<P> MP;
    typedef bg::model::linestring<P> L;
    typedef bg::model::multi_linestring<L> ML;

    typedef test_disjoint tester;

    tester::apply("mp-ml-01",
                  from_wkt<MP>("MULTIPOINT(0 1,0 2)"),
                  from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
                  true);

    tester::apply("mp-ml-02",
                  from_wkt<MP>("MULTIPOINT(0 0,1 0)"),
                  from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
                  false);

    tester::apply("mp-ml-03",
                  from_wkt<MP>("MULTIPOINT(0 1,1 1)"),
                  from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
                  false);

    tester::apply("mp-ml-04",
                  from_wkt<MP>("MULTIPOINT(0 1,1 0)"),
                  from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
                  false);

    tester::apply("mp-ml-05",
                  from_wkt<MP>("MULTIPOINT(0 0,10 0)"),
                  from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
                  false);

    tester::apply("mp-ml-06",
                  from_wkt<MP>("MULTIPOINT(-1 0,3 0)"),
                  from_wkt<ML>("MULTILINESTRING((0 0,2 2,4 4),(0 0,2 0,4 0))"),
                  false);
}

//============================================================================

template <typename CoordinateType>
inline void test_pointlike_linear()
{
    typedef bg::model::point<CoordinateType, 2, bg::cs::cartesian> point_type;

    test_point_linestring<point_type>();
    test_point_multilinestring<point_type>();
    test_point_segment<point_type>();

    test_multipoint_linestring<point_type>();
    test_multipoint_multilinestring<point_type>();
    test_multipoint_segment<point_type>();
}

//============================================================================

BOOST_AUTO_TEST_CASE( test_pointlike_linear_all )
{
    test_pointlike_linear<double>();
    test_pointlike_linear<int>();
#ifdef HAVE_TTMATH
    test_pointlike_linear<ttmath_big>();
#endif
}