text:
#include "ros/ros.h"
#include <tf/tf.h>
#include <tf/transform_listener.h>
#include <math.h>
#include <sstream>
#include <string>
#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <tbb/atomic.h>
#include <signal.h>

#include "std_msgs/Int32.h"
#include "std_msgs/String.h"
#include "std_msgs/Bool.h"
#include "geometry_msgs/Twist.h"
#include <sensor_msgs/LaserScan.h>
#include "sepanta_msgs/arm.h"
#include "sepanta_msgs/omnidata.h"
#include "sepanta_msgs/head.h"
#include "sepanta_msgs/irsensor.h"
#include <dynamixel_msgs/MotorStateList.h>
#include <dynamixel_msgs/JointState.h>
#include <dynamixel_controllers/SetComplianceSlope.h>
#include <dynamixel_controllers/SetCompliancePunch.h>
#include <boost/thread.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <iostream>

#define FILTER_QUEU 10
//=============================================================

using std::string;
using std::exception;
using std::cout;
using std::cerr;
using std::endl;

using namespace std;
using namespace boost;

void Omnidrive(float vx, float vy, float w);

bool robot_init = false;
bool App_exit = false;
int control_mode = 0;
ros::Publisher chatter_pub[20];

float L = 50; //cm
int mobileplatform_motors_write[4] = {128, 128, 128, 128};
int mobileplatform_motors_read[4] = {128, 128, 128, 128};
tbb::atomic<int> keypad_status_raw;
tbb::atomic<int> keypad_status;
tbb::atomic<int> last_keypad_value;

float laser_IR[8];
int IR[5] = {0};
int EMS_STOP = 0;

ros::Publisher chatter_pub_motor[20];
tbb::atomic<int> Compass;

int key_pad_reset = 0;
int robot_max_speedx = 300;
int robot_max_speedy = 300;
int robot_max_speedw = 250;

//Status
int control_mode_old = 0;
int voltage_down = 0;
int voltage_up = 0;
bool green_light = false;
bool red_light = false;
bool btn_start = false;
bool btn_stop = false;

void chatterCallback_greenlight(const std_msgs::Bool::ConstPtr &msg)
{
    cout<<msg->data<<endl;
    green_light = msg->data;
}

void chatterCallback_redlight(const std_msgs::Bool::ConstPtr &msg)
{
    cout<<msg->data<<endl;
    red_light = msg->data;
}

float omnidrive_x = 0;
float omnidrive_y = 0;
float omnidrive_w = 0;

void chatterCallback_speech(const std_msgs::String::ConstPtr &msg)
{
   cout<<"Speech Get : "<<msg->data<<endl;

   std_msgs::String data;
   data.data = msg->data;
   //chatter_pub[0].publish(data);

}

int main(int argc, char **argv)
{
    ros::init(argc, argv, "speechrecognition");

    ros::NodeHandle node_handles[50];
   ros::Subscriber sub_handles[15];
    //===========================================================================================

    sub_handles[0] = node_handles[0].subscribe("/speechRec/cmd_spch", 10, chatterCallback_speech);
    chatter_pub[0] = node_handles[1].advertise<std_msgs::String>("/texttospeech/message", 10);

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

    ros::Rate loop_rate(20);

    while (ros::ok() && App_exit == false)
    {

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

    App_exit = true;

    return 0;
}


text:
/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

 * -------------------------------------------------------------------------- */

/**
 * @file DecisionTreeFactor.cpp
 * @brief discrete factor
 * @date Feb 14, 2011
 * @author Duy-Nguyen Ta
 * @author Frank Dellaert
 */

#include <gtsam/discrete/DecisionTreeFactor.h>
#include <gtsam/discrete/DiscreteConditional.h>
#include <gtsam/base/FastSet.h>

#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>

using namespace std;

namespace gtsam {

  /* ******************************************************************************** */
  DecisionTreeFactor::DecisionTreeFactor() {
  }

  /* ******************************************************************************** */
  DecisionTreeFactor::DecisionTreeFactor(const DiscreteKeys& keys,
      const ADT& potentials) :
      DiscreteFactor(keys.indices()), Potentials(keys, potentials) {
  }

  /* *************************************************************************/
  DecisionTreeFactor::DecisionTreeFactor(const DiscreteConditional& c) :
      DiscreteFactor(c.keys()), Potentials(c) {
  }

  /* ************************************************************************* */
  bool DecisionTreeFactor::equals(const This& other, double tol) const {
    return IndexFactor::equals(other, tol) && Potentials::equals(other, tol);
  }

  /* ************************************************************************* */
  void DecisionTreeFactor::print(const string& s,
      const IndexFormatter& formatter) const {
    cout << s;
    IndexFactor::print("IndexFactor:",formatter);
    Potentials::print("Potentials:",formatter);
  }

  /* ************************************************************************* */
  DecisionTreeFactor DecisionTreeFactor::apply //
  (const DecisionTreeFactor& f, ADT::Binary op) const {
    map<Index,size_t> cs; // new cardinalities
    // make unique key-cardinality map
    BOOST_FOREACH(Index j, keys()) cs[j] = cardinality(j);
    BOOST_FOREACH(Index j, f.keys()) cs[j] = f.cardinality(j);
    // Convert map into keys
    DiscreteKeys keys;
    BOOST_FOREACH(const DiscreteKey& key, cs)
      keys.push_back(key);
    // apply operand
    ADT result = ADT::apply(f, op);
    // Make a new factor
    return DecisionTreeFactor(keys, result);
  }

  /* ************************************************************************* */
  DecisionTreeFactor::shared_ptr DecisionTreeFactor::combine //
  (size_t nrFrontals, ADT::Binary op) const {

    if (nrFrontals > size()) throw invalid_argument(
        (boost::format(
            "DecisionTreeFactor::combine: invalid number of frontal keys %d, nr.keys=%d")
            % nrFrontals % size()).str());

    // sum over nrFrontals keys
    size_t i;
    ADT result(*this);
    for (i = 0; i < nrFrontals; i++) {
      Index j = keys()[i];
      result = result.combine(j, cardinality(j), op);
    }

    // create new factor, note we start keys after nrFrontals
    DiscreteKeys dkeys;
    for (; i < keys().size(); i++) {
      Index j = keys()[i];
      dkeys.push_back(DiscreteKey(j,cardinality(j)));
    }
    return boost::make_shared<DecisionTreeFactor>(dkeys, result);
  }

/* ************************************************************************* */
} // namespace gtsam

ext: cpp

max_stars_repo_name: malcolmreynolds/GTSAM

max_issues_repo_name: malcolmreynolds/GTSAM

max_forks_repo_name: malcolmreynolds/GTSAM


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

#include <boost/hana/detail/assert.hpp>
#include <boost/hana/detail/constexpr.hpp>
#include <boost/hana/functional.hpp>
using namespace boost::hana;

int main() {
    //! [main]
    BOOST_HANA_CONSTEXPR_LAMBDA auto plus = [](auto x, auto y) {
        return x + y;
    };

    BOOST_HANA_CONSTEXPR_LAMBDA auto increment = partial(plus, 1);

    BOOST_HANA_CONSTEXPR_ASSERT(increment(2) == 3);
    //! [main]
}

max_stars_repo_name: rbock/hana

max_issues_repo_name: rbock/hana

max_forks_repo_name: rbock/hana


text:
// Copyright (c) 2016 Klemens D. Morgenstern
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_PROCESS_DETAIL_POSIX_ASYNC_PIPE_HPP_
#define BOOST_PROCESS_DETAIL_POSIX_ASYNC_PIPE_HPP_

#include <boost/process/detail/posix/basic_pipe.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <system_error>
#include <string>

namespace boost { namespace process { namespace detail { namespace posix {

class async_pipe
{
    ::boost::asio::posix::stream_descriptor _source;
    ::boost::asio::posix::stream_descriptor _sink  ;
public:
    typedef int native_handle_type;
    typedef ::boost::asio::posix::stream_descriptor handle_type;

    inline async_pipe(boost::asio::io_service & ios) : async_pipe(ios, ios) {}

    inline async_pipe(boost::asio::io_service & ios_source,
                      boost::asio::io_service & ios_sink) : _source(ios_source), _sink(ios_sink)
    {
        int fds[2];
        if (::pipe(fds) == -1)
            boost::process::detail::throw_last_error("pipe(2) failed");

        _source.assign(fds[0]);
        _sink  .assign(fds[1]);
    };
    inline async_pipe(boost::asio::io_service & ios, const std::string & name)
        : async_pipe(ios, ios, name) {}

    inline async_pipe(boost::asio::io_service & ios_source,
                      boost::asio::io_service & io_sink, const std::string & name);
    inline async_pipe(const async_pipe& lhs);
    async_pipe(async_pipe&& lhs)  : _source(std::move(lhs._source)), _sink(std::move(lhs._sink))
    {
        lhs._source.assign (-1);
        lhs._sink  .assign (-1);
    }

    template<class CharT, class Traits = std::char_traits<CharT>>
    explicit async_pipe(::boost::asio::io_service & ios_source,
                        ::boost::asio::io_service & ios_sink,
                         const basic_pipe<CharT, Traits> & p)
            : _source(ios_source, p.native_source()), _sink(ios_sink, p.native_sink())
    {
    }

    template<class CharT, class Traits = std::char_traits<CharT>>
    explicit async_pipe(boost::asio::io_service & ios, const basic_pipe<CharT, Traits> & p)
            : async_pipe(ios, ios, p)
    {
    }

    template<class CharT, class Traits = std::char_traits<CharT>>
    inline async_pipe& operator=(const basic_pipe<CharT, Traits>& p);
    inline async_pipe& operator=(const async_pipe& rhs);

    inline async_pipe& operator=(async_pipe&& lhs);

    ~async_pipe()
    {
        if (_sink .native()  != -1)
            ::close(_sink.native());
        if (_source.native() != -1)
            ::close(_source.native());
    }

    template<class CharT, class Traits = std::char_traits<CharT>>
    inline explicit operator basic_pipe<CharT, Traits>() const;

    void cancel()
    {
        if (_sink.is_open())
            _sink.cancel();
        if (_source.is_open())
            _source.cancel();
    }

    void close()
    {
        if (_sink.is_open())
            _sink.close();
        if (_source.is_open())
            _source.close();
    }
    void close(boost::system::error_code & ec)
    {
        if (_sink.is_open())
            _sink.close(ec);
        if (_source.is_open())
            _source.close(ec);
    }

    bool is_open() const
    {
        return  _sink.is_open() || _source.is_open();
    }
    void async_close()
    {
        if (_sink.is_open())
            _sink.get_io_service().  post([this]{_sink.close();});
        if (_source.is_open())
            _source.get_io_service().post([this]{_source.close();});
    }

    template<typename MutableBufferSequence>
    std::size_t read_some(const MutableBufferSequence & buffers)
    {
        return _source.read_some(buffers);
    }
    template<typename MutableBufferSequence>
    std::size_t write_some(const MutableBufferSequence & buffers)
    {
        return _sink.write_some(buffers);
    }

    native_handle_type native_source() const {return const_cast<boost::asio::posix::stream_descriptor&>(_source).native();}
    native_handle_type native_sink  () const {return const_cast<boost::asio::posix::stream_descriptor&>(_sink  ).native();}

    template<typename MutableBufferSequence,
             typename ReadHandler>
    BOOST_ASIO_INITFN_RESULT_TYPE(
          ReadHandler, void(boost::system::error_code, std::size_t))
      async_read_some(
        const MutableBufferSequence & buffers,
              ReadHandler &&handler)
    {
        _source.async_read_some(buffers, std::forward<ReadHandler>(handler));
    }

    template<typename ConstBufferSequence,
             typename WriteHandler>
    BOOST_ASIO_INITFN_RESULT_TYPE(
              WriteHandler, void(boost::system::error_code, std::size_t))
      async_write_some(
        const ConstBufferSequence & buffers,
        WriteHandler&& handler)
    {
        _sink.async_write_some(buffers, std::forward<WriteHandler>(handler));
    }

    const handle_type & sink  () const & {return _sink;}
    const handle_type & source() const & {return _source;}

    handle_type && sink()  &&  { return std::move(_sink); }
    handle_type && source()&&  { return std::move(_source); }

    handle_type source(::boost::asio::io_service& ios) &&
    {
        ::boost::asio::posix::stream_descriptor stolen(ios, _source.release());
        return stolen;
    }
    handle_type sink  (::boost::asio::io_service& ios) &&
    {
        ::boost::asio::posix::stream_descriptor stolen(ios, _sink.release());
        return stolen;
    }

    handle_type source(::boost::asio::io_service& ios) const &
    {
        auto source_in = const_cast<::boost::asio::posix::stream_descriptor &>(_source).native();
        return ::boost::asio::posix::stream_descriptor(ios, ::dup(source_in));
    }
    handle_type sink  (::boost::asio::io_service& ios) const &
    {
        auto sink_in = const_cast<::boost::asio::posix::stream_descriptor &>(_sink).native();
        return ::boost::asio::posix::stream_descriptor(ios, ::dup(sink_in));
    }
};

async_pipe::async_pipe(boost::asio::io_service & ios_source,
                       boost::asio::io_service & ios_sink,
                       const std::string & name) : _source(ios_source), _sink(ios_sink)
{
    auto fifo = mkfifo(name.c_str(), 0666 );

    if (fifo != 0)
        boost::process::detail::throw_last_error("mkfifo() failed");

    int  read_fd = open(name.c_str(), O_RDWR);

    if (read_fd == -1)
        boost::process::detail::throw_last_error();

    int write_fd = dup(read_fd);

    if (write_fd == -1)
        boost::process::detail::throw_last_error();

    _source.assign(read_fd);
    _sink  .assign(write_fd);
}

async_pipe::async_pipe(const async_pipe & p) :
        _source(const_cast<async_pipe&>(p)._source.get_io_service()),
        _sink(  const_cast<async_pipe&>(p)._sink.get_io_service())
{

    //cannot get the handle from a const object.
    auto source_in = const_cast<::boost::asio::posix::stream_descriptor &>(_source).native();
    auto sink_in   = const_cast<::boost::asio::posix::stream_descriptor &>(_sink).native();
    if (source_in == -1)
        _source.assign(-1);
    else
    {
        _source.assign(::dup(source_in));
        if (_source.native()== -1)
            ::boost::process::detail::throw_last_error("dup()");
    }

    if (sink_in   == -1)
        _sink.assign(-1);
    else
    {
        _sink.assign(::dup(sink_in));
        if (_sink.native() == -1)
            ::boost::process::detail::throw_last_error("dup()");
    }
}

async_pipe& async_pipe::operator=(const async_pipe & p)
{
    int source;
    int sink;

    //cannot get the handle from a const object.
    auto source_in = const_cast<::boost::asio::posix::stream_descriptor &>(_source).native();
    auto sink_in   = const_cast<::boost::asio::posix::stream_descriptor &>(_sink).native();
    if (source_in == -1)
        source = -1;
    else
    {
        source = ::dup(source_in);
        if (source == -1)
            ::boost::process::detail::throw_last_error("dup()");
    }

    if (sink_in   == -1)
        sink = -1;
    else
    {
        sink  = ::dup(sink_in);
        if (sink == -1)
            ::boost::process::detail::throw_last_error("dup()");
    }
    _source.assign(source);
    _sink.  assign(sink);

    return *this;
}

async_pipe& async_pipe::operator=(async_pipe && lhs)
{
    if (_source.native_handle() == -1)
         ::close(_source.native());

    if (_sink.native_handle()   == -1)
        ::close(_sink.native());

    _source.assign(lhs._source.native_handle());
    _sink  .assign(lhs._sink  .native_handle());
    lhs._source.assign(-1);
    lhs._sink  .assign(-1);
    return *this;
}

template<class CharT, class Traits>
async_pipe::operator basic_pipe<CharT, Traits>() const
{
    int source;
    int sink;

    //cannot get the handle from a const object.
    auto source_in = const_cast<::boost::asio::posix::stream_descriptor &>(_source).native();
    auto sink_in   = const_cast<::boost::asio::posix::stream_descriptor &>(_sink).native();

    if (source_in == -1)
        source = -1;
    else
    {
        source = ::dup(source_in);
        if (source == -1)
            ::boost::process::detail::throw_last_error("dup()");
    }

    if (sink_in   == -1)
        sink = -1;
    else
    {
        sink = ::dup(sink_in);
        if (sink == -1)
            ::boost::process::detail::throw_last_error("dup()");
    }

    return basic_pipe<CharT, Traits>{source, sink};
}

inline bool operator==(const async_pipe & lhs, const async_pipe & rhs)
{
    return compare_handles(lhs.native_source(), rhs.native_source()) &&
           compare_handles(lhs.native_sink(),   rhs.native_sink());
}

inline bool operator!=(const async_pipe & lhs, const async_pipe & rhs)
{
    return !compare_handles(lhs.native_source(), rhs.native_source()) ||
           !compare_handles(lhs.native_sink(),   rhs.native_sink());
}

template<class Char, class Traits>
inline bool operator==(const async_pipe & lhs, const basic_pipe<Char, Traits> & rhs)
{
    return compare_handles(lhs.native_source(), rhs.native_source()) &&
           compare_handles(lhs.native_sink(),   rhs.native_sink());
}

template<class Char, class Traits>
inline bool operator!=(const async_pipe & lhs, const basic_pipe<Char, Traits> & rhs)
{
    return !compare_handles(lhs.native_source(), rhs.native_source()) ||
           !compare_handles(lhs.native_sink(),   rhs.native_sink());
}

template<class Char, class Traits>
inline bool operator==(const basic_pipe<Char, Traits> & lhs, const async_pipe & rhs)
{
    return compare_handles(lhs.native_source(), rhs.native_source()) &&
           compare_handles(lhs.native_sink(),   rhs.native_sink());
}

template<class Char, class Traits>
inline bool operator!=(const basic_pipe<Char, Traits> & lhs, const async_pipe & rhs)
{
    return !compare_handles(lhs.native_source(), rhs.native_source()) ||
           !compare_handles(lhs.native_sink(),   rhs.native_sink());
}

}}}}

#endif /* INCLUDE_BOOST_PIPE_DETAIL_WINDOWS_ASYNC_PIPE_HPP_ */

ext: hpp


text:
#include <X4ConverterTools/xmf/XmfDataBufferDesc.h>

#include <iostream>
#include <boost/format.hpp>
#include <boost/numeric/conversion/cast.hpp>
using namespace Assimp;
using namespace boost;
using boost::numeric_cast;
namespace xmf {
    XmfDataBufferDesc::XmfDataBufferDesc(StreamReaderLE &reader) {
        reader >> Type;
        reader >> UsageIndex;
        reader >> DataOffset;
        reader >> Compressed;
        for (uint8_t &b : _pad0) {
            reader >> b;
        }
        reader >> Format;
        reader >> CompressedDataSize;
        reader >> NumItemsPerSection;
        reader >> ItemSize;
        reader >> NumSections;
        for (uint8_t &b : _pad1) {
            reader >> b;
        }
        reader >> NumVertexElements;
        for (XmfVertexElement &e : VertexElements) {
            e = XmfVertexElement(reader);
        }
        //TODO make this validation code?
//    for (byte &b : _pad0) {
//        if (b != 0) {
//            throw std::runtime_error("Non-zero pad byte in _pad0");
//        }
//    }
//
//    for (byte &b : _pad1) {
//        if (b != 0) {
//            std::cout << (int) b << std::endl;
//            throw std::runtime_error("Non-zero pad byte in _pad1");
//        }
//    }
        NormalizeVertexDeclaration();
        validate();
    }

    bool XmfDataBufferDesc::IsCompressed() const {
        return Compressed != 0;
    }

    bool XmfDataBufferDesc::IsVertexBuffer() const {
        return !IsIndexBuffer();
    }

    bool XmfDataBufferDesc::IsIndexBuffer() const {
        return Type == 30;
    }

    void XmfDataBufferDesc::NormalizeVertexDeclaration() {
        if (!IsVertexBuffer() || NumVertexElements > 0)
            return;

        NumVertexElements = 1;
        VertexElements[0].Type = Format;
        switch (Type) {
            case 0:
            case 1:
                VertexElements[0].Usage = D3DDECLUSAGE_POSITION;
                break;

            case 2:
            case 3:
                VertexElements[0].Usage = D3DDECLUSAGE_NORMAL;
                break;

            case 4:
                VertexElements[0].Usage = D3DDECLUSAGE_TANGENT;
                break;

            case 5:
                VertexElements[0].Usage = D3DDECLUSAGE_BINORMAL;
                break;

            case 8:
                VertexElements[0].Usage = D3DDECLUSAGE_COLOR;
                break;

            case 20:
                VertexElements[0].Usage = D3DDECLUSAGE_PSIZE;
                break;

            default:
                VertexElements[0].Usage = D3DDECLUSAGE_TEXCOORD;
                break;
        }
        VertexElements[0].UsageIndex = numeric_cast<uint8_t>(UsageIndex);

        Type = 0;
        UsageIndex = 0;
        Format = 32;
    }

    void XmfDataBufferDesc::DenormalizeVertexDeclaration() {
        if (!IsVertexBuffer() || NumVertexElements != 1)
            return;

        Format = VertexElements[0].Type;
        switch (VertexElements[0].Usage) {
            case D3DDECLUSAGE_POSITION:
                Type = 0;
                break;

            case D3DDECLUSAGE_NORMAL:
                Type = 2;
                break;

            case D3DDECLUSAGE_TANGENT:
                Type = 4;
                break;

            case D3DDECLUSAGE_BINORMAL:
                Type = 5;
                break;

            case D3DDECLUSAGE_COLOR:
                Type = 8;
                break;

            case D3DDECLUSAGE_PSIZE:
                Type = 20;
                break;

            default:
                Type = 31;
                break;
        }
        UsageIndex = VertexElements[0].UsageIndex;
        NumVertexElements = 0;
    }

    int XmfDataBufferDesc::GetVertexDeclarationSize() {
        int size = 0;
        for (int i = 0; i < NumVertexElements; ++i) {
            size += util::DXUtil::GetVertexElementTypeSize((D3DDECLTYPE) VertexElements[i].Type);
        }
        return size;
    }

    D3DFORMAT XmfDataBufferDesc::GetIndexFormat() {
        if (!IsIndexBuffer()) {
            throw std::runtime_error("The data buffer is not an index buffer");
        }
        return Format == 30 ? D3DFMT_INDEX16 : D3DFMT_INDEX32;
    }

    void XmfDataBufferDesc::Write(Assimp::StreamWriterLE &writer) {
        writer << Type;
        writer << UsageIndex;
        writer << DataOffset;
        writer << Compressed;
        for (uint8_t &b : _pad0) {
            writer << b;
        }

        writer << Format;
        writer << CompressedDataSize;
        writer << NumItemsPerSection;
        writer << ItemSize;
        writer << NumSections;
        for (uint8_t &b : _pad1) {
            writer << b;
        }
        writer << NumVertexElements;
        for (XmfVertexElement &e : VertexElements) {
            e.Write(writer);
        }
    }

    std::string XmfDataBufferDesc::validate() {
        std::string ret = "DataBufferDesc:\n";
        bool valid = true;

        ret.append(str(format("\tType: %1%\n") % Type));
        ret.append(str(format("\tUsageIndex: %1%\n") % UsageIndex));
        ret.append(str(format("\tDataOffset: %1%\n") % DataOffset));
        ret.append(str(format("\tCompressed: %1%\n") % Compressed));
        //TODO ret.append(str(format("(w*): %1%\n")%Pad));
        ret.append(str(format("\tFormat: %1%\n") % Format));
        ret.append(str(format("\tCompressedDataSize: %1%\n") % CompressedDataSize));
        ret.append(str(format("\tNumItemsPerSection: %1%\n") % NumItemsPerSection));
        ret.append(str(format("\tItemSize: %1%\n") % ItemSize));
        ret.append(str(format("\tNumSections: %1%\n") % NumSections));
        // TODO more padding
        ret.append(str(format("\tNumVertexElements: %1%\n") % NumVertexElements));
        // TODO Vertex elements
        if (NumSections != 1) {
            ret.append("\tERROR: Unexpected number of sections (must be 1)");
            valid = false;
        }
        if (IsVertexBuffer() && ItemSize != GetVertexDeclarationSize()) {
            ret.append("\tERROR: Item size for vertex buffer is incorrect");
            valid = false;
        } else if (IsIndexBuffer()) {
            D3DFORMAT format = GetIndexFormat();
            if ((format == D3DFMT_INDEX16 && ItemSize != sizeof(uint16_t)) ||
                (format == D3DFMT_INDEX32 && ItemSize != sizeof(uint32_t))) {
                ret.append("\tERROR: Item size for index buffer is incorrect");
                valid = false;
            }
        }
        if (!valid) {
            throw std::runtime_error(ret);
        }
        return ret;
    }
}


text:
#pragma once

#include <boost/mpl/if.hpp>
#include <boost/multiprecision/mpfr.hpp>
#include <boost/type_traits.hpp>
#include <complex>

namespace boltzmann {

/*
 *  @brief returns T1 if it is a complex type, otherwise returns type of T2
 *
 */
template <typename T1, typename T2>
struct numeric_super_type
{
  typedef typename boost::mpl::eval_if_c<boost::is_complex<T1>::value, /* is a complex type */
                                         boost::mpl::identity<T1>,
                                         boost::mpl::if_c<boost::is_complex<T2>::value,
                                                          T2, /* is a complex type */
                                                          T2  /* a numeric type */
                                                          > >::type type;
};

// ----------------------------------------------------------------------
// MULTIPRECISION, boost::mpfr

template <typename T>
struct is_mpfr
{
  static const bool value = false;
};

/**
 *   specialization for boost mpfr floating type
 */
template <unsigned N, boost::multiprecision::expression_template_option ET>
struct is_mpfr<boost::multiprecision::number<boost::multiprecision::mpfr_float_backend<N>, ET> >
{
  static const bool value = true;
};

/**
 *   specialization for boost mpfr floating type: const reference
 */
template <unsigned N, boost::multiprecision::expression_template_option ET>
struct is_mpfr<
    const boost::multiprecision::number<boost::multiprecision::mpfr_float_backend<N>, ET>&>
{
  static const bool value = true;
};

/**
 *   specialization for boost mpfr floating type: reference
 */
template <unsigned N, boost::multiprecision::expression_template_option ET>
struct is_mpfr<boost::multiprecision::number<boost::multiprecision::mpfr_float_backend<N>, ET>&>
{
  static const bool value = true;
};

}  // end namespace boltzmann


text:
#define CF_USE_TIMER 1
#include "main.h"
#include "arap_material.h"
#include "hcheck.h"
#include "neohookean_material.h"
#include "tet_elastic_body.h"
#include "typedefs.h"
#include "utils.h"

#include <mkl.h>
#include <Eigen/PardisoSupport>

#include <cstdio>
#include <memory>

using namespace baseline;

bool baseline::g_hessian_proj = true;
double baseline::g_hessian_diag_reg = 0;
using SparseMat = materials::ElasticBody<3, double>::SparseMat;

namespace {

//! change g_hessian_proj in the scope of this class and restore to old value
class ChangeHeissianProj : public cf::NonCopyable {
    const bool m_old;

public:
    explicit ChangeHeissianProj(bool v) : m_old{g_hessian_proj} {
        g_hessian_proj = v;
    }
    ~ChangeHeissianProj() { g_hessian_proj = m_old; }
};

// compute stiffness matrix K for current configuration
void get_stiffmat_and_force(
        const materials::TetMesh<double>&
                tet_mesh,  // the tet mesh with rest configuration
        const materials::TetElasticBody<double>& tet_def_body,
        const CoordMat& vertices,  // the vertices coordinates in current
                                   // configuration (size 3 * N)
        const CoordMat* f_ext,     // static external force
        const std::vector<bool>& index_mask,  // the index mask, which obtained
                                              // from set_boundary_conditions
        SparseMat* K,                         // output: the stiffness matrix
        Eigen::VectorXd& force_elastic  // output: the elastic force in current
                                        // configuration
) {
    const size_t rows = tet_mesh.vertex().rows();
    const size_t cols = tet_mesh.vertex().cols();
    const size_t total_dim = rows * cols;

    SparseMat K_full;

    if (K) {
        K_full = tet_def_body.compute_stiffness_matrix(vertices);

        if (g_hessian_diag_reg) {
            SparseMat regularizer(K_full.rows(), K_full.cols());
            regularizer.setIdentity();

            // add a regularization term on the diagonal
            K_full += regularizer * g_hessian_diag_reg;
        }
    }

    Eigen::Matrix3Xd force_elastic_full = tet_def_body.compute_force(vertices);
    if (f_ext) {
        force_elastic_full += *f_ext;
    }

    // trim K_full and force_elastic_full with vertex_mask
    std::unique_ptr<int[]> index_mapping(new int[total_dim]);
    int dofs = 0;
    for (size_t i = 0; i < total_dim; i++) {
        index_mapping[i] = dofs;
        if (index_mask[i]) {
            dofs++;
        }
    }

    if (K) {
        std::vector<Eigen::Triplet<double>> triplet_list;
        triplet_list.reserve(K_full.nonZeros());
        for (int k = 0; k < K_full.outerSize(); k++) {
            for (SparseMat::InnerIterator it(K_full, k); it; ++it) {
                if (index_mask[it.row()] && index_mask[it.col()]) {
                    triplet_list.push_back(Eigen::Triplet<double>(
                            index_mapping[it.row()], index_mapping[it.col()],
                            it.value()));
                }
            }
        }
        K->resize(dofs, dofs);
        K->setZero();
        K->makeCompressed();
        K->setFromTriplets(triplet_list.begin(), triplet_list.end());
    }

    force_elastic = Eigen::VectorXd::Zero(dofs);
    for (size_t i = 0; i < total_dim; i++) {
        if (index_mask[i])
            force_elastic[index_mapping[i]] = force_elastic_full(i % 3, i / 3);
    }
}

std::unique_ptr<materials::Material<3, double>> make_material(
        const MaterialDesc& desc) {
    std::unique_ptr<materials::Material<3, double>> ret;
    switch (desc.energy) {
        case MaterialDesc::NEOHOOKEAN_C:
            ret.reset(new materials::CompressibleNeohookeanMaterial<3, double>(
                    desc.young, desc.poisson));
            break;
        case MaterialDesc::NEOHOOKEAN_I:
            ret.reset(
                    new materials::IncompressibleNeohookeanMaterial<3, double>(
                            desc.young, desc.poisson));
            break;
        case MaterialDesc::ARAP:
            ret.reset(new materials::ARAPElasticityMaterial<3, double>(
                    desc.young, desc.poisson));
            break;
        default:
            cf_assert(0, "bad material");
    }
    return ret;
}

void check_hessian() {
    static bool enable = getenv("FEA_CHECK");
    if (!enable) {
        return;
    }
    static bool done = false;
    if (!done) {
        ChangeHeissianProj disable_proj{false};
        materials::CompressibleNeohookeanMaterial<3, double> m0(1.2, 0.45);
        materials::check_hessian("neohookean_c", m0);
        materials::IncompressibleNeohookeanMaterial<3, double> m1(1.2, 0.45);
        materials::check_hessian("neohookean_i", m1);
        materials::ARAPElasticityMaterial<3, double> m2(1.2, 0.45);
        materials::check_hessian("arap", m2);
        done = true;
    }
}

class SparseSolver {
    bool m_self_adj;
    Eigen::PardisoLLT<SparseMat, Eigen::Upper> m_solver_llt;
    Eigen::PardisoLU<SparseMat> m_solver_lu;

public:
    explicit SparseSolver(bool self_adj) : m_self_adj{self_adj} {}

    void set_self_adj(bool self_adj) { m_self_adj = self_adj; }

    Eigen::VectorXd solve(const SparseMat& A, const Eigen::VectorXd& b) {
        Eigen::VectorXd r;
        Eigen::ComputationInfo info;
        if (m_self_adj) {
            r = m_solver_llt.compute(A).solve(b);
            info = m_solver_llt.info();
        } else {
            r = m_solver_lu.compute(A).solve(b);
            info = m_solver_lu.info();
        }
        if (info) {
            std::string info_message;
            if (info == 1) {
                info_message = "NumericalIssue";
            } else if (info == 2) {
                info_message = "NoConvergence";
            } else if (info == 3) {
                info_message = "InvalidInput";
            } else {
                info_message = "UnknownError";
            }
            throw std::runtime_error{std::move(info_message)};
        }
        return r;
    }
};

//! compute A'A with MKL builtin
void compute_aTa(SparseMat& dst, SparseMat& A) {
    cf_assert(A.isCompressed() && A.IsRowMajor);
    sparse_matrix_t A_mkl, ATA_mkl;
    {
        int* rows_start = A.outerIndexPtr();
        int* rows_end = A.outerIndexPtr() + 1;
        int* col_indx = A.innerIndexPtr();
        auto err = mkl_sparse_d_create_csr(&A_mkl, SPARSE_INDEX_BASE_ZERO,
                                           A.rows(), A.cols(), rows_start,
                                           rows_end, col_indx, A.valuePtr());
        cf_assert(err == SPARSE_STATUS_SUCCESS);
    }

    CF_DEFER(std::bind(mkl_sparse_destroy, A_mkl));

    auto status = mkl_sparse_syrk(SPARSE_OPERATION_TRANSPOSE, A_mkl, &ATA_mkl);
    cf_assert(status == SPARSE_STATUS_SUCCESS,
              "failed to compute A'A: status=%d", static_cast<int>(status));
    CF_DEFER(std::bind(mkl_sparse_destroy, ATA_mkl));

    sparse_index_base_t ATA_idx;
    MKL_INT r, c, *ATA_ia0, *ATA_ia1, *ATA_ja;
    double* ATA_a;
    status = mkl_sparse_d_export_csr(ATA_mkl, &ATA_idx, &r, &c, &ATA_ia0,
                                     &ATA_ia1, &ATA_ja, &ATA_a);
    cf_assert(status == SPARSE_STATUS_SUCCESS,
              "failed to export A'A: status=%d", static_cast<int>(status));
    cf_assert(r == c && r == A.rows());
    cf_assert(ATA_idx == SPARSE_INDEX_BASE_ZERO);
    cf_assert(ATA_ia1 == ATA_ia0 + 1);
    dst.makeCompressed();
    dst = Eigen::Map<const Eigen::SparseMatrix<double, Eigen::RowMajor>>{
            r, c, ATA_ia0[r], ATA_ia0, ATA_ja, ATA_a};
    cf_assert(dst.isCompressed());
}

double rms(const Eigen::VectorXd& v) {
    return std::sqrt(v.squaredNorm() / v.size());
}

}  // anonymous namespace

baseline::Stat baseline::solve_energy_min(
        const IndexMat& elements, const CoordMat& vtx_init,
        const CoordMat& vtx_dst, const CoordMat* f_ext, const MaskMat& bnd_mask,
        const MaterialDesc& material_desc, double gtol_refine,
        const IterCallback& iter_callback) {
    check_hessian();
    auto material = make_material(material_desc);
    materials::TetMesh<double> tet_mesh{vtx_init, elements};
    materials::TetElasticBody<double> tet_def_body(*material, {}, {}, tet_mesh);

    CoordMat vertices = vtx_dst;
    SparseMat hessian;
    Eigen::VectorXd grad;
    std::vector<bool> index_mask(bnd_mask.cols() * 3);
    for (int i = 0; i < bnd_mask.cols(); ++i) {
        for (int j = 0; j < 3; ++j) {
            index_mask[i * 3 + j] = !bnd_mask(j, i);
        }
    }

    Stat stat;
    cf::Timer timer;
    timer.start();

    constexpr double gtol = 1e-6, xtol = 1e-6, ls_c1 = 0.2;
    SparseSolver solver{g_hessian_proj};

    auto get_energy = [&tet_def_body, f_ext, &vtx_init](const CoordMat& vtx) {
        auto e = tet_def_body.compute_energy(vtx);
        if (f_ext) {
            Eigen::Map<const Eigen::VectorXd> v0_flat{vtx_init.data(),
                                                      vtx_init.size()},
                    v1_flat{vtx.data(), vtx.size()},
                    f_flat{f_ext->data(), f_ext->size()};
            e += (v0_flat - v1_flat).dot(f_flat);
        }
        return e;
    };

    Eigen::Matrix<double, 3, Eigen::Dynamic> new_vertices;
    for (;;) {
        get_stiffmat_and_force(tet_mesh, tet_def_body, vertices, f_ext,
                               index_mask, &hessian, grad);
        // this is actually the negative grad since it is the force
        ++stat.nr_iter;
        cf::Timer timer_newton;
        timer_newton.start();
        Eigen::VectorXd u = solver.solve(hessian, grad);

        double step = 1, energy = get_energy(vertices),
               c1_g_p = -ls_c1 * u.dot(grad), new_energy,
               dx_base = u.norm() / (new_vertices.norm() + 1);
        if (g_hessian_proj) {
            cf_assert(c1_g_p < 0);
        } else {
            if (c1_g_p >= 0) {
                c1_g_p = 0;
            }
        }
        int linear_search_cnt = 0;
        for (;; ++linear_search_cnt) {
            new_vertices = vertices;

            // get the final positions and shove them in u
            int cnt = 0;
            for (int i = 0; i < vertices.cols(); i++) {
                for (int j = 0; j < 3; j++) {
                    if (index_mask[i * 3 + j]) {
                        new_vertices(j, i) += u(cnt++) * step;
                    }
                }
            }

            new_energy = get_energy(new_vertices);
            if (new_energy < energy + step * c1_g_p) {
                break;
            }
            step /= 2;
            if (dx_base * step < xtol) {
                new_vertices = vertices;
                break;
            }
        }

        timer_newton.stop();
        stat.tot_newton_time += timer_newton.time();

        double grad_rms = rms(grad),
               df = (energy - new_energy) / (new_energy + 1),
               dx = dx_base * step;

        vertices = new_vertices;

        printf("\riter=%d grms=%g df=%g dx=%g step=%g f=%g cnt=%d  ",
               stat.nr_iter, grad_rms, df, dx, step, energy, linear_search_cnt);
        fflush(stdout);
        if (iter_callback && !iter_callback(vertices)) {
            break;
        }
        if (grad_rms < gtol || dx < xtol) {
            stat.df = df;
            stat.dx = dx;
            stat.grad_rms = grad_rms;
            stat.energy = energy;
            break;
        }
    }
    printf("\n");
    auto postprocess = [&]() {
        timer.stop();
        stat.tot_time = timer.time();
        stat.vtx = vertices;
    };

    if (stat.grad_rms <= gtol_refine) {
        postprocess();
        return stat;
    }

    printf("run refinement: grad_rms=%g gtol_refine=%g\n", stat.grad_rms,
           gtol_refine);

    ChangeHeissianProj disable_proj{false};
    solver.set_self_adj(false);
    get_stiffmat_and_force(tet_mesh, tet_def_body, vertices, f_ext, index_mask,
                           &hessian, grad);
    for (;;) {
        ++stat.nr_iter;
        ++stat.nr_iter_refine;
        cf::Timer timer_newton;
        timer_newton.start();
        Eigen::VectorXd u = solver.solve(hessian, grad);
        {
            int cnt = 0;
            for (int i = 0; i < vertices.cols(); i++) {
                for (int j = 0; j < 3; j++) {
                    if (index_mask[i * 3 + j]) {
                        vertices(j, i) += u(cnt++);
                    }
                }
            }
        }
        timer_newton.stop();
        stat.tot_newton_time += timer_newton.time();

        get_stiffmat_and_force(tet_mesh, tet_def_body, vertices, f_ext,
                               index_mask, &hessian, grad);

        double grad_rms = rms(grad);
        printf("\riter=%d grms=%g ", stat.nr_iter, grad_rms);
        fflush(stdout);
        if (iter_callback && !iter_callback(vertices)) {
            break;
        }
        if (grad_rms < gtol_refine || stat.nr_iter_refine >= 20) {
            stat.grad_rms_refine = grad_rms;
            break;
        }
    }
    printf("\n");
    postprocess();
    return stat;
}

baseline::Stat baseline::solve_force_equ_levmar(
        const IndexMat& elements, const CoordMat& vtx_init,
        const CoordMat& f_ext, const MaskMat& bnd_mask,
        const MaterialDesc& material_desc, double gtol,
        const IterCallback& iter_callback) {
    check_hessian();
    cf_assert(!g_hessian_proj);
    auto material = make_material(material_desc);
    materials::TetMesh<double> tet_mesh{vtx_init, elements};
    materials::TetElasticBody<double> tet_def_body(*material, {}, {}, tet_mesh);

    CoordMat vertices = vtx_init, new_vertices;
    SparseMat jacobian, damped;
    Eigen::VectorXd force, new_force, eqn_rhs;
    std::vector<bool> index_mask(bnd_mask.cols() * 3);
    for (int i = 0; i < bnd_mask.cols(); ++i) {
        for (int j = 0; j < 3; ++j) {
            index_mask[i * 3 + j] = !bnd_mask(j, i);
        }
    }

    Stat stat;
    cf::Timer timer;

    auto postprocess = [&]() {
        timer.stop();
        printf("\n");
        stat.tot_time = timer.time();
        stat.vtx = vertices;
    };

    timer.start();

    constexpr int max_iters = 1000;
    constexpr double damp_coeff_k = 10,
                     damp_coeff_min = std::numeric_limits<double>::epsilon();
    SparseSolver solver{true};
    double damp_coeff = 1e-4;
    Eigen::VectorXd delta, diag;
    for (;;) {
        ++stat.nr_iter;
        get_stiffmat_and_force(tet_mesh, tet_def_body, vertices, &f_ext,
                               index_mask, &jacobian, force);

        cf::Timer timer_newton;
        timer_newton.start();
        double energy = rms(force), new_energy;
        compute_aTa(damped, jacobian);
        eqn_rhs = jacobian.transpose() * force;
        diag = damped.diagonal();

        int search_cnt = 0;
        for (; ++search_cnt;) {
            damped.diagonal() = diag * (1 + damp_coeff);
            delta = solver.solve(damped, eqn_rhs);

            new_vertices = vertices;
            {
                // get the final positions and shove them in u
                int cnt = 0;
                for (int i = 0; i < vertices.cols(); i++) {
                    for (int j = 0; j < 3; j++) {
                        if (index_mask[i * 3 + j]) {
                            new_vertices(j, i) += delta(cnt++);
                        }
                    }
                }
            }

            timer_newton.stop();
            try {
                get_stiffmat_and_force(tet_mesh, tet_def_body, new_vertices,
                                       &f_ext, index_mask, nullptr, new_force);
                new_energy = rms(new_force);
            } catch (materials::NumericalError&) {
                new_energy = energy * 1.1;
            }
            timer_newton.start();
            if (new_energy < energy) {
                damp_coeff =
                        std::max(damp_coeff / damp_coeff_k, damp_coeff_min);
                break;
            } else {
                damp_coeff *= damp_coeff_k;
            }

            if (search_cnt >= 50) {
                // no progress can be made ...
                stat.grad_rms = energy;
                stat.dx = -1;
                postprocess();
                return stat;
            }
        }

        timer_newton.stop();
        stat.tot_newton_time += timer_newton.time();

        auto dx = delta.norm() / (new_vertices.norm() + 1);
        printf("\riter=%d grms=%g dg=%g dx=%g lambda=%g/%.1g cnt=%d  ",
               stat.nr_iter, new_energy, energy - new_energy, dx, damp_coeff,
               damp_coeff_min, search_cnt);
        fflush(stdout);

        vertices = new_vertices;
        energy = new_energy;

        if (iter_callback && !iter_callback(vertices)) {
            break;
        }
        if (energy < gtol || stat.nr_iter >= max_iters) {
            stat.dx = dx;
            stat.grad_rms = energy;
            break;
        }
    }
    postprocess();
    return stat;
}

max_stars_repo_name: jia-kai/SANM

max_issues_repo_name: jia-kai/SANM

max_forks_repo_name: jia-kai/SANM


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

#ifndef MAPNIK_IMAGE_COMPOSITING_HPP
#define MAPNIK_IMAGE_COMPOSITING_HPP

#include <mapnik/config.hpp>
#include <mapnik/image.hpp>

#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/optional.hpp>
#pragma GCC diagnostic pop

// stl
#include <string>

namespace mapnik
{

// Compositing modes
// http://www.w3.org/TR/2009/WD-SVGCompositing-20090430/

enum composite_mode_e
{
    clear = 0,
    src,
    dst,
    src_over,
    dst_over,
    src_in,
    dst_in,
    src_out,
    dst_out,
    src_atop,
    dst_atop,
    _xor,
    plus,
    minus,
    multiply,
    screen,
    overlay,
    darken,
    lighten,
    color_dodge,
    color_burn,
    hard_light,
    soft_light,
    difference,
    exclusion,
    contrast,
    invert,
    invert_rgb,
    grain_merge,
    grain_extract,
    hue,
    saturation,
    _color,
    _value,
    linear_dodge,
    linear_burn,
    divide
};

MAPNIK_DECL boost::optional<composite_mode_e> comp_op_from_string(std::string const& name);
MAPNIK_DECL boost::optional<std::string> comp_op_to_string(composite_mode_e comp_op);

template <typename T>
MAPNIK_DECL void composite(T & dst, T const& src,
                           composite_mode_e mode,
                           float opacity=1,
                           int dx=0,
                           int dy=0);

}
#endif // MAPNIK_IMAGE_COMPOSITING_HPP


text:
#pragma once

#include <polyfem/Types.hpp>

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

namespace polyfem {

	// Show some stats about the matrix M: det, singular values, condition number, etc
	void show_matrix_stats(const Eigen::MatrixXd &M);

	template<typename T>
	T determinant(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, 0, 3, 3> &mat)
	{
		assert(mat.rows() == mat.cols());

		if(mat.rows() == 1)
			return mat(0);
		else if(mat.rows() == 2)
			return mat(0, 0) * mat(1, 1) - mat(0, 1) * mat(1, 0);
		else if(mat.rows() == 3)
			return mat(0,0)*(mat(1,1)*mat(2,2)-mat(1,2)*mat(2,1))-mat(0,1)*(mat(1,0)*mat(2,2)-mat(1,2)*mat(2,0))+mat(0,2)*(mat(1,0)*mat(2,1)-mat(1,1)*mat(2,0));

		assert(false);
		return T(0);
	}

    template<typename T>
	void read_matrix(const std::string &path, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &mat);

	Eigen::Vector4d compute_specturm(const StiffnessMatrix &mat);

} // namespace polyfem

max_stars_repo_name: ldXiao/polyfem

max_issues_repo_name: ldXiao/polyfem

max_forks_repo_name: ldXiao/polyfem


text:
#ifndef PYTHONIC_TYPES_STR_HPP
#define PYTHONIC_TYPES_STR_HPP

#include "pythonic/types/slice.hpp"
#include "pythonic/types/long.hpp"
#include "pythonic/types/tuple.hpp"

#include "pythonic/utils/shared_ref.hpp"
#include "pythonic/utils/proxy.hpp"
#include "pythonic/utils/int_.hpp"

#include <boost/format.hpp>
#include <cassert>
#include <string>
#include <cstring>
#include <sstream>
#include <stdexcept>

namespace pythonic {

    namespace types {

        class str;

        struct const_sliced_str_iterator : std::iterator< std::random_access_iterator_tag, char, ptrdiff_t, char*, char >
        {
            const char * data;
            long step;
            const_sliced_str_iterator(char const *data, long step) : data(data), step(step) {
            }
            const_sliced_str_iterator operator++() { data +=step; return *this; }
            bool operator<(const_sliced_str_iterator const& other) const { return (step>0)?(data < other.data):(data > other.data); }
            bool operator==(const_sliced_str_iterator const& other) const { return data == other.data; }
            bool operator!=(const_sliced_str_iterator const& other) const { return data != other.data; }
            char operator*() const { return *data; }
            const_sliced_str_iterator operator-(long n) const { const_sliced_str_iterator other(*this); other.data -= step * n; return other; }
            long operator-(const_sliced_str_iterator const & other) const { return (data - other.data)/step; }
        };

        template<class S=slice>
        class sliced_str {
            typedef std::string container_type;
            utils::shared_ref<container_type> data;

            typename S::normalized_type slicing;

            public:
            //  types
            typedef container_type::reference reference;
            typedef container_type::const_reference const_reference;
            typedef const_sliced_str_iterator iterator;
            typedef const_sliced_str_iterator const_iterator;
            typedef container_type::size_type size_type;
            typedef container_type::difference_type difference_type;
            typedef container_type::value_type value_type;
            typedef container_type::allocator_type allocator_type;
            typedef container_type::pointer pointer;
            typedef container_type::const_pointer const_pointer;

            // constructor
            sliced_str(): data(utils::no_memory()) {}
            sliced_str(sliced_str const & s): data(s.data), slicing(s.slicing) {}

            sliced_str(sliced_str const & s, typename S::normalized_type const& sl): data(s.data), slicing(s.slicing * sl) {}
            sliced_str(types::str const & other, typename S::normalized_type const & s);

            // const getter
            container_type const & get_data() const { return *data; }
            typename S::normalized_type const & get_slice() const { return slicing; }

            // assignment
            sliced_str& operator=(str const & );
            sliced_str& operator=(sliced_str const & );
            str operator+(sliced_str const & );

            // iterators
            const_iterator begin() const { return const_iterator(data->c_str() + slicing.lower, slicing.step); }
            const_iterator end() const { return const_iterator(data->c_str() + slicing.upper, slicing.step); }

            // size
            size_type size() const { return slicing.size(); }

            // accessor
            char const & operator[](long i) const { return (*data)[slicing.get(i)];}
            char & operator[](long i) { return (*data)[slicing.get(i)];}
            sliced_str<slice> operator[](slice const& s) const { return sliced_str<slice>(*this, s.normalize(size())); }
            sliced_str<contiguous_slice> operator[](contiguous_slice const& s) const { return sliced_str<contiguous_slice>(*this, s.normalize(size())); }

            // conversion
            operator long();
            explicit operator bool() const {return size() > 0;}
            bool operator!() const { return not bool();}

            size_t find(str const &s, size_t pos = 0) const;
            bool contains(str const& v) const { return find(v) != std::string::npos; }

            // io
            friend  std::ostream& operator<<(std::ostream& os, types::sliced_str<S> const & v) {
                for(auto b = v.begin(); b != v.end(); ++b)
                    os << *b;
                return os;
            }
        };

        class str {
            template<class S> friend class sliced_str;
            typedef std::string container_type;
            utils::shared_ref<container_type> data;

            public:

            static const size_t npos = std::string::npos;

            typedef str value_type; // in Python, a string contains... strings
            typedef container_type::iterator iterator;
            typedef container_type::reverse_iterator reverse_iterator;
            typedef container_type::const_reverse_iterator const_reverse_iterator;

            str() : data() {}
            str(std::string const & s) : data(s) {}
            str(std::string && s) : data(std::move(s)) {}
            str(const char*s) : data(s) {}
            str(const char*s, size_t n) : data(s,n) {}
            str(char c) : data(1,c) {}
            template<class S>
            str(sliced_str<S> const & other) : data(other.begin(), other.end()) {}
            template<class T>
                str(T const& begin, T const& end) : data(begin, end) {}

            explicit operator char() const {
                assert(size() == 1);
                return (*data)[0];
            }

            operator long int() const { // Allows implicit conversion without loosing bool conversion
                char *endptr;
                auto dat = data->data();
                long res = strtol(dat, &endptr,10);
                if(endptr == dat) {
                    std::ostringstream err;
                    err << "invalid literal for long() with base 10:"
                        "'" << c_str() << '\'';
                    throw std::runtime_error(err.str());
                }
                return res;
            }

            operator pythran_long_t() const {
#ifdef USE_GMP
                return pythran_long_t(*data);
#else
                char *endptr;
                auto dat = data->data();
                pythran_long_t res = strtoll(dat, &endptr,10);
                if(endptr == dat) {
                    std::ostringstream err;
                    err << "invalid literal for long() with base 10:"
                        "'" << c_str() << '\'';
                    throw std::runtime_error(err.str());
                }
                return res;
#endif
            }

            explicit operator double() const {
                char *endptr;
                auto dat = data->data();
                double res = strtod(dat, &endptr);
                if(endptr == dat) {
                    std::ostringstream err;
                    err << "invalid literal for double():"
                        << "'" << c_str() << "'";
                    throw std::runtime_error(err.str());
                }
                return res;
            }
            template<class S>
            str& operator=(sliced_str<S> const & other) {
                if(other.get_data() == *data ) {
                    auto it = std::copy(other.begin(), other.end(), begin());
                    resize(it - this->begin());
                }
                else {
                    *this=other.get_data();
                }
                return *this;
            }

            types::str& operator+=(types::str const& s) {
                *data += *s.data;
                return *this;
            }

            container_type const & get_data() const { return *data; }

            size_t size() const { return data->size(); }
            auto begin() const -> decltype(data->begin()) { return data->begin(); }
            auto begin() -> decltype(data->begin()) { return data->begin(); }
            auto rbegin() const -> decltype(data->rbegin()) { return data->rbegin(); }
            auto rbegin() -> decltype(data->rbegin()) { return data->rbegin(); }
            auto end() const -> decltype(data->end()) { return data->end(); }
            auto end() -> decltype(data->end()) { return data->end(); }
            auto rend() const -> decltype(data->rend()) { return data->rend(); }
            auto rend() -> decltype(data->rend()) { return data->rend(); }
            auto c_str() const -> decltype(data->c_str()) { return data->c_str(); }
            auto resize(long n) -> decltype(data->resize(n)) { return data->resize(n); }
            long find(str const &s, size_t pos = 0) const {
                const char * res =  strstr(c_str() + pos, s.c_str());
                return res ? res - c_str() : -1;
            }
            bool contains(str const& v) const { return find(v) != -1; }
            long find_first_of(str const &s, size_t pos = 0) const { return data-> find_first_of(*s.data, pos); }
            long find_first_of(const char* s, size_t pos = 0) const { return data-> find_first_of(s, pos); }
            long find_first_not_of(str const &s, size_t pos = 0) const { return data->find_first_not_of(*s.data, pos); }
            long find_last_not_of(str const &s, size_t pos = npos) const { return data-> find_last_not_of(*s.data, pos); }
            str substr(size_t pos = 0, size_t len = npos) const { return data->substr(pos, len); }
            bool empty() const { return data->empty(); }
            int compare(size_t pos, size_t len, str const & str) const { return data->compare(pos, len, *str.data); }
            void reserve(size_t n) { data->reserve(n); }
            str& replace(size_t pos,  size_t len,  str const & str) { data->replace(pos, len, *str.data); return *this; }

            template<class S>
            str& operator+=(sliced_str<S> const & other) {
                resize(size() + other.get_data().size());
                std::copy(other.begin(), other.end(), begin());
                return *this;
            }
            bool operator==(str const& other) const { return *data == *other.data; }
            bool operator!=(str const& other) const { return *data != *other.data; }
            bool operator<=(str const& other) const { return *data <= *other.data; }
            bool operator<(str const& other) const { return *data < *other.data; }
            bool operator>=(str const& other) const { return *data >= *other.data; }
            bool operator>(str const& other) const { return *data > *other.data; }
            template<class S>
            bool operator==(sliced_str<S> const & other) const {
                if(size() != other.size())
                    return false;
                for(size_t i=other.get_slice().lower, j=0L;
                        j<size();
                        i= i + other.get_slice().step, j++)
                    if(other.get_data()[i] != (*this)[j])
                        return false;
                return true;
            }
            sliced_str<slice> operator()( slice const &s) const {
                return operator[](s);
            }
            sliced_str<contiguous_slice> operator()( contiguous_slice const &s) const {
                return operator[](s);
            }

            char operator[]( long i) const {
                if(i<0) i+= size();
                return (*data)[i];
            }

            char& operator[]( long i) {
                if(i<0) i+= size();
                return (*data)[i];
            }
            sliced_str<slice> operator[]( slice const &s ) const {
                return sliced_str<slice>(*this, s.normalize(size()));
            }
            sliced_str<contiguous_slice> operator[]( contiguous_slice const &s ) const {
                return sliced_str<contiguous_slice>(*this, s.normalize(size()));
            }
#ifdef USE_GMP
            char operator[](pythran_long_t const &m) const { return (*this)[m.get_si()];}
            char & operator[](pythran_long_t const& m) { return (*this)[m.get_si()];}
#endif

            explicit operator bool() const{
                return not data->empty();
            }
            template<class A>
                types::str operator%(A const & a) const {
                    const boost::format fmter(*data);
                    return (boost::format(fmter) % a ).str();
                }
            template<class ...A>
                types::str operator%(std::tuple<A...> const & a) const {
                    boost::format fmter(*data);
                    (fmt(fmter, a, utils::int_<sizeof...(A)>() ));
                    return fmter.str();
                }
            template<size_t N, class T>
                types::str operator%(types::array<T, N> const & a) const {
                    boost::format fmter(*data);
                    (fmt(fmter, a, utils::int_<N>() ));
                    return fmter.str();
                }

            long count(types::str const & sub) const {
                long counter = 0;
                for(long z = find(sub);           // begin by looking for sub
                    z != -1;                      // as long as we don't reach the end
                    z = find(sub, z + sub.size()))  // look for another one
                {
                    ++counter;
                }
                return counter;
            }

            private:
            template<class Tuple, size_t I>
                void fmt(boost::format & f, Tuple const & a, utils::int_<I>) const {
                    fmt(f % std::get<std::tuple_size<Tuple>::value-I>(a), a, utils::int_<I-1>());
                }
            template<class Tuple>
                void fmt(boost::format & f, Tuple const & a, utils::int_<1>) const {
                    f % std::get<std::tuple_size<Tuple>::value-1>(a);
                }

        };

        template<class S>
        str sliced_str<S>::operator+(sliced_str<S> const & s) {
            str out(*data);
            std::copy(s.begin(), s.end(), std::copy(begin(), end(), out.begin()));
            return out;
        }
        template<class S>
        size_t sliced_str<S>::find(str const &s, size_t pos) const {
          return str(*this).find(s); // quite inefficient
        }

        str operator+(str const& self, str const& other) {
            return str(self.get_data() + other.get_data());
        }
        template<size_t N>
        str operator+(str const& self, char const (&other)[N]) {
          std::string s;
          s.reserve(self.size() + N);
          s += self.get_data();
          s += other;
          return {std::move(s)};
        }
        template<size_t N>
        str operator+(char const (&self)[N], str const& other) {
          std::string s;
          s.reserve(other.size() + N);
          s += self;
          s += other.get_data();
          return {std::move(s)};
        }

        bool operator==(char c, str const& s) {
            return s.size() == 1 and s[0] == c;
        }
        bool operator==(str const& s, char c) {
            return s.size() == 1 and s[0] == c;
        }
        bool operator!=(char c, str const& s) {
            return s.size() != 1 or s[0] != c;
        }
        bool operator!=(str const& s, char c) {
            return s.size() != 1 or s[0] != c;
        }
        std::ostream& operator<<(std::ostream& os, str const & s) {
            return os << s.c_str();
        }

    }

}

namespace pythonic {

namespace operator_ {

    template<size_t N, class Arg>
    auto mod(const char (&fmt) [N], Arg&& arg) -> decltype(pythonic::types::str(fmt)%std::forward<Arg>(arg)) {
      return pythonic::types::str(fmt)%std::forward<Arg>(arg);
    }
}

}

pythonic::types::str operator*(pythonic::types::str const & s, long n) {
    if(n<0)
        return pythonic::types::str();
    pythonic::types::str other;
    other.resize(s.size()*n);
    auto where = other.begin();
    for(long i=0;i<n; i++, where+=s.size())
        std::copy(s.begin(), s.end(), where);
    return other;
}

pythonic::types::str operator*(long t, pythonic::types::str const & s) {
    return s*t;
}

template<class S>
pythonic::types::sliced_str<S>& pythonic::types::sliced_str<S>::operator=(pythonic::types::sliced_str<S> const & s) {
    slicing=s.slicing;
    data=s.data;
    return *this;
}

template<class S>
pythonic::types::sliced_str<S>& pythonic::types::sliced_str<S>::operator=(pythonic::types::str const & s) {
    if( slicing.step == 1) {
        data->erase(slicing.lower, slicing.upper);
        data->insert(slicing.lower, s.get_data());
    }
    else {
        assert("not implemented yet");
    }
    return *this;
}

template<class S>
pythonic::types::sliced_str<S>::sliced_str(pythonic::types::str const& other, typename S::normalized_type const & s) : data(other.data), slicing(s){}

template<class S>
pythonic::types::sliced_str<S>::operator long() {
    long out;
    std::istringstream iss(pythonic::types::str(*this).get_data());
    iss >> out;
    return out;
}

namespace std {
    template <> struct hash<pythonic::types::str>
    {
        size_t operator()(const pythonic::types::str & x) const
        {
            return hash<std::string>()(x.get_data());
        }
    };
}

namespace pythonic {
    namespace types {
        std::size_t hash_value(str  const &x) {
            return std::hash<str>()(x);
        }
    }
}

/* std::get overload */
namespace std {
    template <size_t I>
        typename pythonic::types::str get( pythonic::types::str const &t) { return pythonic::types::str(t[I]); }

    template <size_t I>
        class tuple_element<I, pythonic::types::str > {
            public:
                typedef typename pythonic::types::str type;
        };
    template <size_t I, class S>
        class tuple_element<I, pythonic::types::sliced_str<S> > {
            public:
            typedef typename pythonic::types::str type;
        };
}
#ifdef ENABLE_PYTHON_MODULE

#include "pythonic/python/register_once.hpp"

namespace pythonic {
    template<>
        struct python_to_pythran< types::str >{
            python_to_pythran(){
                static bool registered =false;
                if(not registered) {
                    registered=true;
                    boost::python::converter::registry::insert(&convertible,&construct,boost::python::type_id<types::str>());
                }
            }
            static void* convertible(PyObject* obj_ptr){
                if( !PyString_Check(obj_ptr) ) return 0;
                return obj_ptr;
            }
            static void construct(PyObject* obj_ptr, boost::python::converter::rvalue_from_python_stage1_data* data){
                void* storage=((boost::python::converter::rvalue_from_python_storage<types::str >*)(data))->storage.bytes;
                char* s=PyString_AS_STRING(obj_ptr);
                new (storage) types::str(s, PyString_GET_SIZE(obj_ptr));
                data->convertible=storage;
            }
        };
    struct custom_pythran_string_to_str{
        static PyObject* convert(const types::str& v){
            return PyString_FromStringAndSize(v.c_str(), v.size());
        }
    };

    template<>
        struct pythran_to_python< types::str > {
            pythran_to_python() {
                register_once< types::str, custom_pythran_string_to_str >();
            }
        };

    struct custom_pythran_sliced_str_to_str {
        static PyObject* convert(const types::sliced_str<types::contiguous_slice>& v){
            return custom_pythran_string_to_str().convert(v);
        }
        static PyObject* convert(const types::sliced_str<types::slice>& v){
            return custom_pythran_string_to_str().convert(v);
        }
    };

    template<class S>
    struct pythran_to_python< types::sliced_str<S> > {
        pythran_to_python() {
            register_once< types::sliced_str<S>, custom_pythran_sliced_str_to_str >();
        }
    };

}
/* type inference stuff  {*/
#include "pythonic/types/combined.hpp"

template <>
struct __combined<char const *, pythonic::types::str> {
    typedef pythonic::types::str type;
};
template <>
struct __combined<pythonic::types::str, char const *> {
    typedef pythonic::types::str type;
};

/* } */

#endif

#endif

max_stars_repo_name: Pikalchemist/Pythran

max_issues_repo_name: Pikalchemist/Pythran

max_forks_repo_name: Pikalchemist/Pythran


text:
//
// A demo program of reordering using Rabbit Order.
//
// Author: ARAI Junya <arai.junya@lab.ntt.co.jp> <araijn@gmail.com>
//

#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/algorithm/count.hpp>

#include "../rabbit_order.hpp"
#include "edge_list.hpp"
#include <utils/yche_serialization.h>

using rabbit_order::vint;
typedef std::vector<std::vector<std::pair<vint, float> > > adjacency_list;

string g_path_dir;

vint count_unused_id(const vint n, const std::vector<edge_list::edge> &edges) {
    std::vector<char> appears(n);
    for (size_t i = 0; i < edges.size(); ++i) {
        appears[std::get<0>(edges[i])] = true;
        appears[std::get<1>(edges[i])] = true;
    }
    return static_cast<vint>(boost::count(appears, false));
}

vint count_unused_id_unweighted(const vint n, const std::vector<edge_list::aux::unweighted_edge> &edges) {
    std::vector<char> appears(n);
    for (size_t i = 0; i < edges.size(); ++i) {
        appears[std::get<0>(edges[i])] = true;
        appears[std::get<1>(edges[i])] = true;
    }
    return static_cast<vint>(boost::count(appears, false));
}

template<typename RandomAccessRange>
adjacency_list make_adj_list(const vint n, const RandomAccessRange &es) {
    using std::get;

    // Symmetrize the edge list and remove self-loops simultaneously
    std::vector<edge_list::aux::edge> ss(boost::size(es) * 2);
#pragma omp parallel for
    for (size_t i = 0; i < boost::size(es); ++i) {
        auto &e = es[i];
        if (get<0>(e) != get<1>(e)) {
            ss[i * 2] = std::make_tuple(get<0>(e), get<1>(e), 1.0f);
            ss[i * 2 + 1] = std::make_tuple(get<1>(e), get<0>(e), 1.0f);
        } else {
            // Insert zero-weight edges instead of loops; they are ignored in making
            // an adjacency list
            ss[i * 2] = std::make_tuple(0, 0, 0.0f);
            ss[i * 2 + 1] = std::make_tuple(0, 0, 0.0f);
        }
    }

    // Sort the edges
    __gnu_parallel::sort(ss.begin(), ss.end());

    // Convert to an adjacency list
    adjacency_list adj(n);
#pragma omp parallel
    {
        // Advance iterators to a boundary of a source vertex
        const auto adv = [](auto it, const auto first, const auto last) {
            while (first != it && it != last && get<0>(*(it - 1)) == get<0>(*it))
                ++it;
            return it;
        };

        // Compute an iterator range assigned to this thread
        const int p = omp_get_max_threads();
        const size_t t = static_cast<size_t>(omp_get_thread_num());
        const size_t ifirst = ss.size() / p * (t) + std::min(t, ss.size() % p);
        const size_t ilast = ss.size() / p * (t + 1) + std::min(t + 1, ss.size() % p);
        auto it = adv(ss.begin() + ifirst, ss.begin(), ss.end());
        const auto last = adv(ss.begin() + ilast, ss.begin(), ss.end());

        // Reduce edges and store them in std::vector
        while (it != last) {
            const vint s = get<0>(*it);

            // Obtain an upper bound of degree and reserve memory
            const auto maxdeg =
                    std::find_if(it, last, [s](auto &x) { return get<0>(x) != s; }) - it;
            adj[s].reserve(maxdeg);

            while (it != last && get<0>(*it) == s) {
                const vint t = get<1>(*it);
                float w = 0.0;
                while (it != last && get<0>(*it) == s && get<1>(*it) == t)
                    w += get<2>(*it++);
                if (w > 0.0)
                    adj[s].push_back({t, w});
            }

            // The actual degree can be smaller than the upper bound
            adj[s].shrink_to_fit();
        }
    }

    return adj;
}

adjacency_list read_graph(const std::string &graphpath) {
//    const auto edges = edge_list::read(graphpath);
    FILE *pFile = fopen(graphpath.c_str(), "r");
    YcheSerializer serializer;
    vector<tuple<vint, vint >> edges;
    serializer.read_array(pFile, edges);
    fclose(pFile);

    // The number of vertices = max vertex ID + 1 (assuming IDs start from zero)
    const auto n =
            boost::accumulate(edges, static_cast<vint>(0), [](vint s, auto &e) {
                return std::max(s, std::max(std::get<0>(e), std::get<1>(e)) + 1);
            });

    if (const size_t c = count_unused_id_unweighted(n, edges)) {
        std::cerr << "WARNING: " << c << "/" << n << " vertex IDs are unused"
                  << " (zero-degree vertices or noncontiguous IDs?)\n";
    }

    return make_adj_list(n, edges);
}

template<typename InputIt>
typename std::iterator_traits<InputIt>::difference_type
count_uniq(const InputIt f, const InputIt l) {
    std::vector<typename std::iterator_traits<InputIt>::value_type> ys(f, l);
    return boost::size(boost::unique(boost::sort(ys)));
}

double compute_modularity(const adjacency_list &adj, const vint *const coms) {
    const vint n = static_cast<vint>(adj.size());
    const auto ncom = count_uniq(coms, coms + n);
    double m2 = 0.0;  // total weight of the (bidirectional) edges

    std::unordered_map<vint, double[2]> degs(ncom);  // ID -> {all, loop}
    degs.reserve(ncom);

#pragma omp parallel reduction(+:m2)
    {
        std::unordered_map<vint, double[2]> mydegs(ncom);
        mydegs.reserve(ncom);

#pragma omp for
        for (vint v = 0; v < n; ++v) {
            const vint c = coms[v];
            auto *const d = &mydegs[c];
            for (const auto e : adj[v]) {
                m2 += e.second;
                (*d)[0] += e.second;
                if (coms[e.first] == c) (*d)[1] += e.second;
            }
        }

#pragma omp critical
        {
            for (auto &kv : mydegs) {
                auto *const d = &degs[kv.first];
                (*d)[0] += kv.second[0];
                (*d)[1] += kv.second[1];
            }
        }
    }
    assert(static_cast<intmax_t>(degs.size()) == ncom);

    double q = 0.0;
    for (auto &kv : degs) {
        const double all = kv.second[0];
        const double loop = kv.second[1];
        q += loop / m2 - (all / m2) * (all / m2);
    }

    return q;
}

void detect_community(adjacency_list adj) {
    auto _adj = adj;  // copy `adj` because it is used for computing modularity

    std::cerr << "Detecting communities...\n";
    const double tstart = rabbit_order::now_sec();
    //--------------------------------------------
    auto g = rabbit_order::aggregate(std::move(_adj));
    const auto c = std::make_unique<vint[]>(g.n());
#pragma omp parallel for
    for (vint v = 0; v < g.n(); ++v)
        c[v] = rabbit_order::trace_com(v, &g);
    //--------------------------------------------
    std::cerr << "Runtime for community detection [sec]: "
              << rabbit_order::now_sec() - tstart << std::endl;

    // Print the result
    std::copy(&c[0], &c[g.n()], std::ostream_iterator<vint>(std::cout, "\n"));

    std::cerr << "Computing modularity of the result...\n";
    const double q = compute_modularity(adj, c.get());
    std::cerr << "Modularity: " << q << std::endl;
}

void reorder(adjacency_list adj) {
    std::cerr << "Generating a permutation...\n";
    const double tstart = rabbit_order::now_sec();
    //--------------------------------------------
    const auto g = rabbit_order::aggregate(std::move(adj));
    const auto p = rabbit_order::compute_perm(g);
    //--------------------------------------------
    std::cerr << "Runtime for permutation generation [sec]: "
              << rabbit_order::now_sec() - tstart << std::endl;

    // Print the result
    std::copy(&p[0], &p[g.n()], std::ostream_iterator<vint>(std::cout, "\n"));

    // save the binary dictionary to file here
    // output using ycheserializer
    string my_path = g_path_dir + "/" + "rabbit_order.dict";
    cout << my_path << endl;
    FILE *pFile = fopen(my_path.c_str(), "wb");
    YcheSerializer serializer;
    serializer.write_array(pFile, p.get(), g.n());

    // flush and close the file handle
    fflush(pFile);
    fclose(pFile);
}

int main(int argc, char *argv[]) {
    using boost::adaptors::transformed;

    // Parse command-line arguments
    if (argc != 2 && (argc != 3 || std::string("-c") != argv[1])) {
        std::cerr << "Usage: reorder [-c] GRAPH_FILE\n"
                  << "  -c    Print community IDs instead of a new ordering\n";
        exit(EXIT_FAILURE);
    }
    const std::string graphpath = argc == 3 ? argv[2] : argv[1];

    string tmp = graphpath;
    auto upper_bound = tmp.find_last_of('/');
    g_path_dir = tmp.substr(0, upper_bound);

    const bool commode = argc == 3;

    std::cerr << "Number of threads: " << omp_get_max_threads() << std::endl;

    std::cerr << "Reading an edge-list file: " << graphpath << std::endl;
    auto adj = read_graph(graphpath);
    const auto m =
            boost::accumulate(adj | transformed([](auto &es) { return es.size(); }),
                              static_cast<size_t>(0));
    std::cerr << "Number of vertices: " << adj.size() << std::endl;
    std::cerr << "Number of edges: " << m << std::endl;

    if (commode)
        detect_community(std::move(adj));
    else
        reorder(std::move(adj));

    return EXIT_SUCCESS;
}

ext: cc

max_stars_repo_name: HackerFoo/GraphReorderAndConverter

max_issues_repo_name: HackerFoo/GraphReorderAndConverter

max_forks_repo_name: HackerFoo/GraphReorderAndConverter


text:
/*************** <auto-copyright.rb BEGIN do not edit this line> **************
 *
 * Copyright 2012-2013 by Ames Laboratory
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 *************** <auto-copyright.rb END do not edit this line> ***************/

// --- LEAF Includes --- //
#include <leaf/wrapper/rusle2/RomeWrapper.h>

// --- ROME Includes --- //
#include <cstdlib> //This must be included before api-rome.h
#if __RUSLE2_version <= 2000004
#define AFX_API_IMPORT
#endif //__RUSLE2_version
#include <api-rome.h>

// --- Boost Includes --- //
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>

// --- STL Includes --- //
#include <iostream>
#include <sstream>

namespace leaf
{
namespace wrapper
{
namespace rusle2
{

////////////////////////////////////////////////////////////////////////////////
RomeWrapper::RomeWrapper()
    :
    m_rtApp( NULL ),
    m_rtEngine( NULL ),
    m_rtDatabase( NULL ),
    m_rtFiles( NULL ),
    m_pProfile( NULL ),
    m_pContour( NULL ),
    m_pClimate( NULL ),
    m_pSoil( NULL ),
    m_pStripBarrier( NULL ),
    m_pManagement( NULL ),
    m_sciVer( 0 ),
    m_sciVerStr( "" )
{
    ;
}
////////////////////////////////////////////////////////////////////////////////
RomeWrapper::~RomeWrapper()
{
    ;
}
////////////////////////////////////////////////////////////////////////////////
void RomeWrapper::Exit()
{
    m_pProfile = NULL;
    m_pContour = NULL;
    m_pClimate = NULL;
    m_pSoil = NULL;
    m_pStripBarrier = NULL;
    m_pManagement = NULL;

    CloseAllFiles();

    //Shutdown connection to RomeDLL
    RT_BOOL success = RomeExit( m_rtApp );
    if( !success )
    {
        OutputErrorInfo();
    }

    m_rtFiles = NULL;
    m_rtDatabase = NULL;
    m_rtEngine = NULL;
    m_rtApp = NULL;
}
////////////////////////////////////////////////////////////////////////////////
RomeWrapper& RomeWrapper::Instance(
    bool const& erase )
{
    static RomeWrapper* sRomeWrapper = new RomeWrapper();
    if( erase )
    {
        sRomeWrapper->Exit();
        delete sRomeWrapper;
        sRomeWrapper = NULL;
    }

    return *sRomeWrapper;
}
////////////////////////////////////////////////////////////////////////////////
void RomeWrapper::Init(
    std::string const& dirRoot,
    std::string const& dbPath )
{
    std::stringstream arguments;
    arguments << "RomeDLL "
              << "\"/DirRoot=" << dirRoot << "\" "
              << "\"/Path:Session=" << dirRoot << "\" "
              << "\"/Path:Users=" << dirRoot << "\" "
              << "\"/UnitSystem=US\"";

    //Create connection to the Rome DLL
    m_rtApp = RomeInit( arguments.str().c_str() );
    if( !m_rtApp )
    {
        OutputErrorInfo();
    }

    //Turn off Autorun
    m_rtEngine = RomeGetEngine( m_rtApp );
    if( !m_rtEngine )
    {
        OutputErrorInfo();
    }
    RomeEngineSetAutorun( m_rtEngine, RX_FALSE );

    //Get a pointer to the Rome database
    m_rtDatabase = RomeGetDatabase( m_rtApp );
    if( !m_rtDatabase )
    {
        OutputErrorInfo();
    }

    //"http"
    //"internal"
    //"sqlite2"
    //"file"
    //"msaccess"
    //std::string dbPath = "file://" + boost::filesystem::current_path().string();
    RT_BOOL success = RomeDatabaseOpen( m_rtDatabase, dbPath.c_str() );
    if( !success )
    {
        OutputErrorInfo();
    }

    //Get a pointer to the Rome file system
    m_rtFiles = RomeGetFiles( m_rtApp );
    if( !m_rtFiles )
    {
        OutputErrorInfo();
    }

    Reset();

    //Get science version
    m_sciVer = RomeGetScienceVersion( m_rtApp );
    m_sciVerStr = boost::lexical_cast< std::string >( m_sciVer );
}
////////////////////////////////////////////////////////////////////////////////
RT_FileObj* RomeWrapper::AddFile(
    ObjectType const& objType,
    std::string const& fullName )
{
    RT_FileObj* fileObj = RomeFilesAdd(
        m_rtFiles, NAME( objType ).c_str(), fullName.c_str() );
    if( !fileObj )
    {
        OutputErrorInfo();
    }

    return fileObj;
}
////////////////////////////////////////////////////////////////////////////////
bool RomeWrapper::CloseFile(
    RT_FileObj* fileObj )
{
    RT_BOOL retVal = RomeFileClose( fileObj );

    //return RX_TRUE    ( 1) if the file was closed/reloaded
    //       RX_FALSE   ( 0) on failure
    //       RX_FAILURE (-1) on error
    switch( retVal )
    {
        case 1:
            return true;
        case 0:
            return false;
        default:
        {
            OutputErrorInfo();
            return false;
        }
    }
}
////////////////////////////////////////////////////////////////////////////////
void RomeWrapper::CloseAllFiles(
    unsigned int const& nFlags )
{
    //RX_CLOSEALL_SAVE : Allow saving modified [and temp] files
      //If this flag isn't set, flag #RX_CLOSEALL_CANCEL will have no effect
    //RX_CLOSEALL_CANCEL : Allow canceling this operation
      //The [Cancel] button won't be shown unless this flag is set
      //Note: This only works in applications which handle dialog notifications
    //RX_CLOSEALL_TEMP : Close temporary files
      //Normally temporary files remain open until the app closes
    //RX_CLOSEALL_USED : Close files still being used
    //RX_CLOSEALL_NOCLOSE : Close internal #OBJT_NOCLOSE files
      //This is normally only done on app shutdown
    //RX_CLOSEALL_NOMODIFIED : Don't close modified files
    //RX_CLOSEALL_NOUPDATE : Don't allow engine to finish before closing files
    //RX_CLOSEALL_NOUNUSED : Don't close unused top-level files
      //This is independent of #RX_CLOSEALL_NOUSED
    RomeFilesCloseAll( m_rtFiles, nFlags );
}
////////////////////////////////////////////////////////////////////////////////
bool RomeWrapper::DeleteFile(
    RT_FileObj* fileObj )
{
    RT_BOOL retVal = RomeFileDelete( fileObj );

    //return RX_TRUE    ( 1) if the file was closed/reloaded
    //       RX_FALSE   ( 0) on failure
    //       RX_FAILURE (-1) on error
    switch( retVal )
    {
        case 1:
            return true;
        case 0:
            return false;
        default:
        {
            OutputErrorInfo();
            return false;
        }
    }
}
////////////////////////////////////////////////////////////////////////////////
bool RomeWrapper::FinishUpdates()
{
    RT_BOOL retVal = RomeEngineFinishUpdates( m_rtEngine );

    //return RX_TRUE    ( 1) on success
    //       RX_FALSE   ( 0) on failure
    //       RX_FAILURE (-1) on error
    switch( retVal )
    {
        case 1:
            return true;
        case 0:
        default:
        {
            OutputErrorInfo();
            return false;
        }
    }
}
////////////////////////////////////////////////////////////////////////////////
std::string RomeWrapper::GetFullname(
    RT_FileObj* fileObj )
{
    RT_CSTR attrVal = RomeFileGetFullname( fileObj );
    if( !attrVal )
    {
        OutputErrorInfo();
    }

    return attrVal;
}
////////////////////////////////////////////////////////////////////////////////
std::string RomeWrapper::GetAttrVal(
    RT_FileObj* fileObj,
    std::string const& attrName,
    unsigned int const& index )
{
    RT_CSTR attrVal = RomeFileGetAttrValue( fileObj, attrName.c_str(), index );
    if( !attrVal )
    {
        OutputErrorInfo();
    }

    return attrVal;
}
////////////////////////////////////////////////////////////////////////////////
short int RomeWrapper::GetAttrSize(
    RT_FileObj* fileObj,
    std::string const& attrName )
{
    RT_SHORT attrSize = RomeFileGetAttrSize( fileObj, attrName.c_str() );
    if( attrSize == -1 )
    {
        OutputErrorInfo();
    }

    return attrSize;
}
////////////////////////////////////////////////////////////////////////////////
unsigned int const& RomeWrapper::GetSciVer() const
{
    return m_sciVer;
}
////////////////////////////////////////////////////////////////////////////////
std::string const& RomeWrapper::GetSciVerStr() const
{
    return m_sciVerStr;
}
////////////////////////////////////////////////////////////////////////////////
RT_FileObj*& RomeWrapper::OBJECT(
    ObjectType const& objType )
{
    switch( objType )
    {
        case OBJTYP_SLOPE:
        {
            return m_pProfile;
        }
        case OBJTYP_CONTOUR:
        {
            return m_pContour;
        }
        case OBJTYP_CLIMATE:
        {
            return m_pClimate;
        }
        case OBJTYP_SOIL:
        {
            return m_pSoil;
        }
        case OBJTYP_STRIPBARRIER:
        {
            return m_pStripBarrier;
        }
        case OBJTYP_MANAGEMENT:
        {
            return m_pManagement;
        }
        default:
            return m_pProfile;
    }
}
////////////////////////////////////////////////////////////////////////////////
RT_FileObj* RomeWrapper::OpenFile(
    std::string const& filePath,
    unsigned int const& nFlags )
{
    //File open mode flags used by RomeFilesOpen()
    //RX_FILESOPEN_USE_OPEN : Use an existing open copy
    //RX_FILESOPEN_NO_CREATE : Don't create if not found in the database
    //RX_FILESOPEN_TEMP : Create a temporary file
    //RX_FILESOPEN_NO_DEFAULT : Don't open user default if not found -- use model
    //RX_FILESOPEN_SHOW_VIEW : Open a view for the file (not used by all fns)
    //RX_FILESOPEN_NO_KNOWN : Don't use map of known bad files
    //RX_FILESOPEN_SAVE_EDITED : Save an edited file before reopening (if flag #RX_FILESOPEN_USE_OPEN not set)
    //RX_FILESOPEN_CLONE : Return a clone of the file asked for
    //RX_FILESOPEN_USERRENAME : Allow user renaming the opened file
    //RX_FILESOPEN_PRIVATE : Open as private file (don't allow save, excludes flag #RX_FILESOPEN_TEMP)
    //RX_FILESOPEN_LOG_HIST : Log this action to the history log (commands.xml)
    //RX_FILESOPEN_CMD_USER : Caused by a user action (for logging purposes)
    //RX_FILESOPEN_FORMAT_CFF : Data is in CFF format (for some fns only)
    //RX_FILESOPEN_FORMAT_XML : Data is in XML format (for some fns only)
    //RX_FILESOPEN_NO_REGISTER : Don't add the filename to the map of open files
    //RX_FILESOPEN_NO_LOAD : Don't load a file from the database
    //RX_FILESOPEN_INTERNAL : RX_FILESOPEN_PRIVATE
    RT_FileObj* rtFileObj =
        RomeFilesOpen( m_rtFiles, filePath.c_str(), nFlags );
    if( !rtFileObj ) OutputErrorInfo();

    return rtFileObj;
}
////////////////////////////////////////////////////////////////////////////////
void RomeWrapper::Reset()
{
    m_pProfile = NULL;
    m_pContour = NULL;
    m_pClimate = NULL;
    m_pSoil = NULL;
    m_pStripBarrier = NULL;
    m_pManagement = NULL;

    CloseAllFiles();

#if __RUSLE2_version >= 2002005
    //RX_FILESOPEN_INTERNAL is important to allow modification of attributes
    m_pProfile = OpenFile( TBL( OBJTYP_SLOPE ) +
        "\\" + "#ENTRY_DEFAULT", RX_FILESOPEN_INTERNAL );
#else
    m_pProfile = OpenFile( TBL( OBJTYP_SLOPE ) +
        "\\" + "#ENTRY_DEFAULT" );
    GetAttrVal( m_pProfile, PTR( OBJTYP_CONTOUR ) );
    GetAttrVal( m_pProfile, PTR( OBJTYP_CLIMATE ) );
    GetAttrVal( m_pProfile, PTR( OBJTYP_SOIL ) );
    GetAttrVal( m_pProfile, PTR( OBJTYP_STRIPBARRIER ) );
    GetAttrVal( m_pProfile, PTR( OBJTYP_MANAGEMENT ) );
#endif //__RUSLE2_version
}
////////////////////////////////////////////////////////////////////////////////
bool RomeWrapper::Run()
{
    //Force calculation of outputs whose inputs have changed
    //NOTE: This is necessary because we have set Autorun to FALSE above
    //NOTE: This call does not cause unnecessary calculation of outputs
    //      that are already current
    RT_BOOL retVal = RomeEngineRun( m_rtEngine );

    //return RX_TRUE    ( 1) on success
    //       RX_FALSE   ( 0) on failure
    //       RX_FAILURE (-1) on error
    switch( retVal )
    {
        case 1:
            return true;
        case 0:
        default:
        {
            OutputErrorInfo();
            return false;
        }
    }
}
////////////////////////////////////////////////////////////////////////////////
bool RomeWrapper::SaveFile(
    RT_FileObj* fileObj,
    std::string const& filePath )
{
    RT_BOOL retVal = RomeFileSaveAs( fileObj, filePath.c_str() );

    //return RX_TRUE    ( 1) on success
    //       RX_FALSE   ( 0) on failure
    //       RX_FAILURE (-1) on error
    switch( retVal )
    {
        case 1:
            return true;
        case 0:
        default:
        {
            OutputErrorInfo();
            return false;
        }
    }
}
////////////////////////////////////////////////////////////////////////////////
bool RomeWrapper::SetAttrVal(
    RT_FileObj* fileObj,
    std::string const& attrName,
    std::string const& attrVal,
    unsigned int const& index )
{
    RT_SHORT retVal = RomeFileSetAttrValue(
        fileObj, attrName.c_str(), attrVal.c_str(), index );

    //return RX_TRUE    ( 1) if the value changed
    //       RX_FALSE   ( 0) if unchanged
    //       RX_FAILURE (-1) on error
    switch( retVal )
    {
        case 1:
        case 0:
            return true;
        default:
        {
            OutputErrorInfo();
            return false;
        }
    }
}
////////////////////////////////////////////////////////////////////////////////
bool RomeWrapper::SetAttrSize(
    RT_FileObj* fileObj,
    std::string const& attrName,
    short int const& attrVal )
{
    RT_SHORT retVal = RomeFileSetAttrSize( fileObj, attrName.c_str(), attrVal );

    //return RX_TRUE    ( 1) if the value changed
    //       RX_FALSE   ( 0) if unchanged
    //       RX_FAILURE (-1) on error
    switch( retVal )
    {
        case 1:
        case 0:
            return true;
        default:
        {
            OutputErrorInfo();
            return false;
        }
    }
}
////////////////////////////////////////////////////////////////////////////////
void RomeWrapper::OutputErrorInfo()
{
    //Check for Rome error info
    //This will work even if pRome is NULL
    RT_CSTR pszRomeError = RomeGetLastError( m_rtApp );
    if( !pszRomeError ) return;
    throw std::runtime_error( pszRomeError );
}
////////////////////////////////////////////////////////////////////////////////

} //end rusle2
} //end wrapper
} //end leaf

ext: cxx

max_stars_repo_name: IdahoLabCuttingBoard/LEAF

max_issues_repo_name: IdahoLabCuttingBoard/LEAF

max_forks_repo_name: IdahoLabCuttingBoard/LEAF