<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2014 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
 *
 *****************************************************************************/

#include <mapnik/json/topojson_grammar.hpp>

namespace mapnik { namespace topojson {

namespace qi = boost::spirit::qi;
namespace phoenix = boost::phoenix;
namespace fusion = boost::fusion;

template <typename Iterator, typename ErrorHandler>
topojson_grammar<Iterator, ErrorHandler>::topojson_grammar()
    : topojson_grammar::base_type(topology, "topojson")
{
    qi::lit_type lit;
    qi::double_type double_;
    qi::int_type int_;
    qi::omit_type omit;
    qi::_val_type _val;
    qi::_1_type _1;
    qi::_2_type _2;
    qi::_3_type _3;
    qi::_4_type _4;
    qi::_r1_type _r1;
    using qi::fail;
    using qi::on_error;
    using phoenix::push_back;
    using phoenix::construct;
    // generic json types
    json_.value = json_.object | json_.array | json_.string_ | json_.number
        ;

    json_.pairs = json_.key_value % lit(',')
        ;

    json_.key_value = (json_.string_ >> lit(':') >> json_.value)
        ;

    json_.object = lit('{') >> *json_.pairs >> lit('}')
        ;

    json_.array = lit('[')
        >> json_.value >> *(lit(',') >> json_.value)
        >> lit(']')
        ;

    json_.number = json_.strict_double[_val = json_.double_converter(_1)]
        | json_.int__[_val = json_.integer_converter(_1)]
        | lit("true")[_val = true]
        | lit("false")[_val = false]
        | lit("null")[_val = construct<value_null>()]
        ;

    // topo json
    topology = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"Topology\"")
                        >> ( (lit(',') >> objects) ^ ( lit(',') >> arcs) ^ (lit(',') >> transform) ^ (lit(',') >> bbox))
                        >> lit('}')
        ;

    transform = lit("\"transform\"") >> lit(':') >> lit('{')
                                     >> lit("\"scale\"") >> lit(':')
                                     >> lit('[')
                                     >> double_ >> lit(',')
                                     >> double_ >> lit(']') >> lit(',')
                                     >> lit("\"translate\"") >> lit(':')
                                     >> lit('[') >> double_ >> lit(',') >> double_ >> lit(']')
                                     >> lit('}')
        ;

    bbox = lit("\"bbox\"") >> lit(':')
                           >> lit('[') >> double_ >> lit(',') >> double_
                           >> lit(',') >> double_ >> lit(',') >> double_
                           >> lit(']')
        ;

    objects = lit("\"objects\"")
        >> lit(':')
        >> lit('{')
        >> -((omit[json_.string_]
              >> lit(':')
              >>  (geometry_collection(_val) | geometry)) % lit(','))
        >> lit('}')
        ;

    geometry =
        point |
        linestring |
        polygon |
        multi_point |
        multi_linestring |
        multi_polygon |
        omit[json_.object]
        ;

    geometry_collection =  lit('{')
               >> lit("\"type\"") >> lit(':') >> lit("\"GeometryCollection\"") >> lit(',')
               >> lit("\"geometries\"") >> lit(':') >> lit('[') >> -(geometry[push_back(_r1, _1)] % lit(','))
               >> lit(']')
               >> lit('}')
        ;
    point = lit('{')
        >> lit("\"type\"") >> lit(':') >> lit("\"Point\"")
        >> ((lit(',') >> lit("\"coordinates\"") >> lit(':') >> coordinate)
            ^ (lit(',') >> properties) /*^ (lit(',') >> omit[id])*/)
        >> lit('}')
        ;

    multi_point = lit('{')
        >> lit("\"type\"") >> lit(':') >> lit("\"MultiPoint\"")
        >> ((lit(',') >> lit("\"coordinates\"") >> lit(':')
             >> lit('[') >> -(coordinate % lit(',')) >> lit(']'))
            ^ (lit(',') >> properties) ^ (lit(',') >> omit[id]))
        >> lit('}')
        ;

    linestring = lit('{')
        >> lit("\"type\"") >> lit(':') >> lit("\"LineString\"")
        >> ((lit(',') >> lit("\"arcs\"") >> lit(':') >> lit('[') >> int_ >> lit(']'))
            ^ (lit(',') >> properties) ^ (lit(',') >> omit[id]))
        >> lit('}')
        ;

    multi_linestring = lit('{')
        >> lit("\"type\"") >> lit(':') >> lit("\"MultiLineString\"")
        >> ((lit(',') >> lit("\"arcs\"") >> lit(':') >> lit('[')
             >> -((lit('[') >> int_ >> lit(']')) % lit(',')) >> lit(']'))
            ^ (lit(',') >> properties) ^ (lit(',') >> omit[id]))
        >> lit('}')
        ;

    polygon = lit('{')
        >> lit("\"type\"") >> lit(':') >> lit("\"Polygon\"")
        >> ((lit(',') >> lit("\"arcs\"") >> lit(':')
             >> lit('[') >> -(ring % lit(',')) >> lit(']'))
            ^ (lit(',') >> properties) ^ (lit(',') >> omit[id]))
        >> lit('}')
        ;

    multi_polygon = lit('{')
        >> lit("\"type\"") >> lit(':') >> lit("\"MultiPolygon\"")
        >> ((lit(',') >> lit("\"arcs\"") >> lit(':')
             >> lit('[')
             >> -((lit('[') >> -(ring % lit(',')) >> lit(']')) % lit(','))
             >> lit(']')) ^ (lit(',') >> properties) ^ (lit(',') >> omit[id]))
        >> lit('}')
        ;

    id = lit("\"id\"") >> lit(':') >> omit[json_.value]
        ;

    ring = lit('[') >> -(int_ % lit(',')) >> lit(']')
        ;

    properties = lit("\"properties\"")
        >> lit(':')
        >> (( lit('{') >> attributes >> lit('}')) | json_.object)
        ;

    attributes = (json_.string_ >> lit(':') >> attribute_value) % lit(',')
        ;

    attribute_value %= json_.number | json_.string_  ;

    arcs = lit("\"arcs\"") >> lit(':')
                           >> lit('[') >> -( arc % lit(',')) >> lit(']') ;

    arc = lit('[') >> -(coordinate % lit(',')) >> lit(']') ;

    coordinate = lit('[') >> double_ >> lit(',') >> double_ >> lit(']');

    topology.name("topology");
    transform.name("transform");
    objects.name("objects");
    arc.name("arc");
    arcs.name("arcs");
    json_.value.name("value");
    coordinate.name("coordinate");

    point.name("point");
    multi_point.name("multi_point");
    linestring.name("linestring");
    polygon.name("polygon");
    multi_polygon.name("multi_polygon");
    geometry_collection.name("geometry_collection");
    // error handler
    on_error<fail>(topology, error_handler(_1, _2, _3, _4));
}

}}
<commit_msg>topojson grammar - add optional bbox element which is omitted<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2014 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
 *
 *****************************************************************************/

#include <mapnik/json/topojson_grammar.hpp>

namespace mapnik { namespace topojson {

namespace qi = boost::spirit::qi;
namespace phoenix = boost::phoenix;
namespace fusion = boost::fusion;

template <typename Iterator, typename ErrorHandler>
topojson_grammar<Iterator, ErrorHandler>::topojson_grammar()
    : topojson_grammar::base_type(topology, "topojson")
{
    qi::lit_type lit;
    qi::double_type double_;
    qi::int_type int_;
    qi::omit_type omit;
    qi::_val_type _val;
    qi::_1_type _1;
    qi::_2_type _2;
    qi::_3_type _3;
    qi::_4_type _4;
    qi::_r1_type _r1;
    using qi::fail;
    using qi::on_error;
    using phoenix::push_back;
    using phoenix::construct;
    // generic json types
    json_.value = json_.object | json_.array | json_.string_ | json_.number
        ;

    json_.pairs = json_.key_value % lit(',')
        ;

    json_.key_value = (json_.string_ >> lit(':') >> json_.value)
        ;

    json_.object = lit('{') >> *json_.pairs >> lit('}')
        ;

    json_.array = lit('[')
        >> json_.value >> *(lit(',') >> json_.value)
        >> lit(']')
        ;

    json_.number = json_.strict_double[_val = json_.double_converter(_1)]
        | json_.int__[_val = json_.integer_converter(_1)]
        | lit("true")[_val = true]
        | lit("false")[_val = false]
        | lit("null")[_val = construct<value_null>()]
        ;

    // topo json
    topology = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"Topology\"")
                        >> ( (lit(',') >> objects) ^ ( lit(',') >> arcs) ^ (lit(',') >> transform) ^ (lit(',') >> bbox))
                        >> lit('}')
        ;

    transform = lit("\"transform\"") >> lit(':') >> lit('{')
                                     >> lit("\"scale\"") >> lit(':')
                                     >> lit('[')
                                     >> double_ >> lit(',')
                                     >> double_ >> lit(']') >> lit(',')
                                     >> lit("\"translate\"") >> lit(':')
                                     >> lit('[') >> double_ >> lit(',') >> double_ >> lit(']')
                                     >> lit('}')
        ;

    bbox = lit("\"bbox\"") >> lit(':')
                           >> lit('[') >> double_ >> lit(',') >> double_
                           >> lit(',') >> double_ >> lit(',') >> double_
                           >> lit(']')
        ;

    objects = lit("\"objects\"")
        >> lit(':')
        >> lit('{')
        >> -((omit[json_.string_]
              >> lit(':')
              >>  (geometry_collection(_val) | geometry)) % lit(','))
        >> lit('}')
        ;

    geometry =
        point |
        linestring |
        polygon |
        multi_point |
        multi_linestring |
        multi_polygon |
        omit[json_.object]
        ;

    geometry_collection =  lit('{')
               >> lit("\"type\"") >> lit(':') >> lit("\"GeometryCollection\"")
               >> -(lit(',') >> omit[bbox])
               >> lit(',') >> lit("\"geometries\"") >> lit(':') >> lit('[') >> -(geometry[push_back(_r1, _1)] % lit(','))
               >> lit(']')
               >> lit('}')
        ;
    point = lit('{')
        >> lit("\"type\"") >> lit(':') >> lit("\"Point\"")
        >> -(lit(',') >> omit[bbox])
        >> ((lit(',') >> lit("\"coordinates\"") >> lit(':') >> coordinate)
            ^ (lit(',') >> properties) /*^ (lit(',') >> omit[id])*/)
        >> lit('}')
        ;

    multi_point = lit('{')
        >> lit("\"type\"") >> lit(':') >> lit("\"MultiPoint\"")
        >> -(lit(',') >> omit[bbox])
        >> ((lit(',') >> lit("\"coordinates\"") >> lit(':')
             >> lit('[') >> -(coordinate % lit(',')) >> lit(']'))
            ^ (lit(',') >> properties) ^ (lit(',') >> omit[id]))
        >> lit('}')
        ;

    linestring = lit('{')
        >> lit("\"type\"") >> lit(':') >> lit("\"LineString\"")
        >> ((lit(',') >> lit("\"arcs\"") >> lit(':') >> lit('[') >> int_ >> lit(']'))
            ^ (lit(',') >> properties) ^ (lit(',') >> omit[id]))
        >> lit('}')
        ;

    multi_linestring = lit('{')
        >> lit("\"type\"") >> lit(':') >> lit("\"MultiLineString\"")
        >> -(lit(',') >> omit[bbox])
        >> ((lit(',') >> lit("\"arcs\"") >> lit(':') >> lit('[')
             >> -((lit('[') >> int_ >> lit(']')) % lit(',')) >> lit(']'))
            ^ (lit(',') >> properties) ^ (lit(',') >> omit[id]))
        >> lit('}')
        ;

    polygon = lit('{')
        >> lit("\"type\"") >> lit(':') >> lit("\"Polygon\"")
        >> -(lit(',') >> omit[bbox])
        >> ((lit(',') >> lit("\"arcs\"") >> lit(':')
             >> lit('[') >> -(ring % lit(',')) >> lit(']'))
            ^ (lit(',') >> properties) ^ (lit(',') >> omit[id]))
        >> lit('}')
        ;

    multi_polygon = lit('{')
        >> lit("\"type\"") >> lit(':') >> lit("\"MultiPolygon\"")
        >> -(lit(',') >> omit[bbox])
        >> ((lit(',') >> lit("\"arcs\"") >> lit(':')
             >> lit('[')
             >> -((lit('[') >> -(ring % lit(',')) >> lit(']')) % lit(','))
             >> lit(']')) ^ (lit(',') >> properties) ^ (lit(',') >> omit[id]))
        >> lit('}')
        ;

    id = lit("\"id\"") >> lit(':') >> omit[json_.value]
        ;

    ring = lit('[') >> -(int_ % lit(',')) >> lit(']')
        ;

    properties = lit("\"properties\"")
        >> lit(':')
        >> (( lit('{') >> attributes >> lit('}')) | json_.object)
        ;

    attributes = (json_.string_ >> lit(':') >> attribute_value) % lit(',')
        ;

    attribute_value %= json_.number | json_.string_  ;

    arcs = lit("\"arcs\"") >> lit(':')
                           >> lit('[') >> -( arc % lit(',')) >> lit(']') ;

    arc = lit('[') >> -(coordinate % lit(',')) >> lit(']') ;

    coordinate = lit('[') >> double_ >> lit(',') >> double_ >> lit(']');

    topology.name("topology");
    transform.name("transform");
    objects.name("objects");
    arc.name("arc");
    arcs.name("arcs");
    json_.value.name("value");
    coordinate.name("coordinate");

    point.name("point");
    multi_point.name("multi_point");
    linestring.name("linestring");
    polygon.name("polygon");
    multi_polygon.name("multi_polygon");
    geometry_collection.name("geometry_collection");
    // error handler
    on_error<fail>(topology, error_handler(_1, _2, _3, _4));
}

}}
<|endoftext|>


<commit_before>#pragma once

#include <cstddef>
#include <boost/iterator/counting_iterator.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/iterator/iterator_facade.hpp>

#include "andres/graph/grid-graph.hxx"

#include "nifty/tools/runtime_check.hxx"
#include "nifty/graph/undirected_graph_base.hxx"
#include "nifty/graph/detail/adjacency.hxx"
#include "nifty/graph/graph_tags.hxx"
#include "nifty/parallel/threadpool.hxx"
#include "nifty/array/arithmetic_array.hxx"

namespace nifty{
namespace graph{

namespace detail_graph{

    template<std::size_t DIM, bool SIMPLE_NH>
    class UndirectedGridGraphIter{
    public:
        typedef andres::graph::GridGraph<DIM> AGridGraph;
        typedef typename AGridGraph::AdjacencyIterator AGridGraphAdjacencyIter;
        typedef UndirectedAdjacency<int64_t,int64_t,int64_t,int64_t> NodeAdjacency;

        struct UnaryFunction{
            typedef NodeAdjacency value_type;
            template<class ADJ>
            NodeAdjacency operator()(const ADJ & adjacency)const{
                return NodeAdjacency(adjacency.vertex(), adjacency.vertex());
            }
        };

        typedef boost::transform_iterator<
            UnaryFunction,
            typename AGridGraph::AdjacencyIterator,
            NodeAdjacency,
            NodeAdjacency
        > OldAdjacencyIter;

        class AdjacencyIter
        : public boost::iterator_facade<
            AdjacencyIter,
            NodeAdjacency,
            std::random_access_iterator_tag,
            const NodeAdjacency &
        >
        {
        public:
            AdjacencyIter(const AGridGraphAdjacencyIter & iter)
            :   iter_(iter),
                adjacency_(){
            }
            bool equal(const AdjacencyIter & other)const{
                return iter_ == other.iter_;
            }
            void increment(){
                ++iter_;
            }
            void dencrement(){
                --iter_;
            }
            void advance(const std::size_t n){
                iter_+=n;
            }
            std::ptrdiff_t distance_to(const AdjacencyIter & other)const{
                return std::distance(iter_, other.iter_);
            }
            const NodeAdjacency & dereference()const{
                adjacency_ = NodeAdjacency(iter_->vertex(), iter_->edge());
                return adjacency_;
            }
        private:
            mutable AGridGraphAdjacencyIter iter_;
            mutable NodeAdjacency adjacency_;
        };

        class NodeIter : public boost::counting_iterator<int64_t>{
            using boost::counting_iterator<int64_t>::counting_iterator;
            using boost::counting_iterator<int64_t>::operator=;
        };

        class EdgeIter : public boost::counting_iterator<int64_t>{
            using boost::counting_iterator<int64_t>::counting_iterator;
            using boost::counting_iterator<int64_t>::operator=;
        };
    };

};

template<std::size_t DIM, bool SIMPLE_NH>
class UndirectedGridGraph;

template<std::size_t DIM>
class UndirectedGridGraph<DIM,true> : public
    UndirectedGraphBase<
        UndirectedGridGraph<DIM, true>,
        typename detail_graph::UndirectedGridGraphIter<DIM,true>::NodeIter,
        typename detail_graph::UndirectedGridGraphIter<DIM,true>::EdgeIter,
        typename detail_graph::UndirectedGridGraphIter<DIM,true>::AdjacencyIter
    >
{
private:
    typedef andres::graph::GridGraph<DIM> AndresGridGraphType;
    typedef typename AndresGridGraphType::VertexCoordinate AndresVertexCoordinate;
public:
    typedef nifty::array::StaticArray<int64_t, DIM> ShapeType;
    typedef nifty::array::StaticArray<int64_t, DIM> CoordinateType;

    typedef typename detail_graph::UndirectedGridGraphIter<DIM,true>::NodeIter      NodeIter;
    typedef typename detail_graph::UndirectedGridGraphIter<DIM,true>::EdgeIter      EdgeIter;
    typedef typename detail_graph::UndirectedGridGraphIter<DIM,true>::AdjacencyIter AdjacencyIter;

    typedef ContiguousTag EdgeIdTag;
    typedef ContiguousTag NodeIdTag;

    typedef SortedTag EdgeIdOrderTag;
    typedef SortedTag NodeIdOrderTag;

    UndirectedGridGraph()
    : gridGraph_(){
    }

    template<class T>
    UndirectedGridGraph(const nifty::array::StaticArray<T, DIM> & shape)
    : gridGraph_(){

        AndresVertexCoordinate ashape;
        std::copy(shape.rbegin(), shape.rend(), ashape.begin());
        gridGraph_.assign(ashape);

    }

    template<class T>
    void assign(const nifty::array::StaticArray<T, DIM> & shape){

        AndresVertexCoordinate ashape;
        std::copy(shape.rbegin(), shape.rend(), ashape.begin());
        gridGraph_.assign(ashape);

    }

    //void assign(const uint64_t numberOfNodes = 0, const uint64_t reserveNumberOfEdges = 0);

    // MUST IMPL INTERFACE
    int64_t u(const int64_t e)const{
        return gridGraph_.vertexOfEdge(e,0);
    }
    int64_t v(const int64_t e)const{
        return gridGraph_.vertexOfEdge(e,1);
    }

    int64_t findEdge(const int64_t u, const int64_t v)const{
        const auto r = gridGraph_.findEdge(u,v);
        if(r.first)
            return r.second;
        else
            return -1;
    }
    int64_t nodeIdUpperBound() const{
         return numberOfNodes() == 0 ? 0 : numberOfNodes()-1;
    }
    int64_t edgeIdUpperBound() const{
        return numberOfEdges() == 0 ? 0 : numberOfEdges()-1;
    }

    uint64_t numberOfEdges() const{
        return gridGraph_.numberOfEdges();
    }
    uint64_t numberOfNodes() const{
        return gridGraph_.numberOfVertices();
    }

    NodeIter nodesBegin()const{
        return NodeIter(0);
    }
    NodeIter nodesEnd()const{
        return NodeIter(this->numberOfNodes());
    }
    EdgeIter edgesBegin()const{
        return EdgeIter(0);
    }
    EdgeIter edgesEnd()const{
        return EdgeIter(this->numberOfEdges());
    }

    AdjacencyIter adjacencyBegin(const int64_t node)const{
        return AdjacencyIter(gridGraph_.adjacenciesFromVertexBegin(node));
    }
    AdjacencyIter adjacencyEnd(const int64_t node)const{
        return AdjacencyIter(gridGraph_.adjacenciesFromVertexEnd(node));
    }
    AdjacencyIter adjacencyOutBegin(const int64_t node)const{
        return AdjacencyIter(gridGraph_.adjacenciesFromVertexBegin(node));
    }
     AdjacencyIter adjacencyOutEnd(const int64_t node)const{
        return AdjacencyIter(gridGraph_.adjacenciesFromVertexEnd(node));
    }

    // optional (with default impl in base)
    //std::pair<int64_t,int64_t> uv(const int64_t e)const;

    template<class F>
    void forEachEdge(F && f)const{
        for(uint64_t edge=0; edge< numberOfEdges(); ++edge){
            f(edge);
        }
    }

    template<class F>
    void forEachNode(F && f)const{
        for(uint64_t node=0; node< numberOfNodes(); ++node){
            f(node);
        }
    }

    // serialization de-serialization

    uint64_t serializationSize() const{
        return DIM + 1;
    }

    template<class ITER>
    void serialize(ITER iter) const{
        for(auto d=0; d<DIM; ++d){
            *iter = gridGraph_.shape(d);
            ++iter;
        }
        // simple nh?
        *iter = true;
        ++iter;
    }

    template<class ITER>
    void deserialize(ITER iter);

    /**
     * @brief convert an image with DIM dimension to an edge map
     * @details convert an image with DIM dimension to an edge map
     * by applying a binary functor to the values of a node map at
     * the endpoints of an edge.
     *
     * @param       image the  input image
     * @param       binaryFunctor a binary functor
     * @param[out]  the result edge map
     *
     * @return [description]
     */
    template<class IMAGE, class BINARY_FUNCTOR, class EDGE_MAP>
    void imageToEdgeMap(
        const IMAGE & image,
        BINARY_FUNCTOR binaryFunctor,
        EDGE_MAP & edgeMap
    )const{
        for(const auto edge : this->edges()){
            const auto uv = this->uv(edge);
            CoordinateType cU,cV;
            nodeToCoordinate(uv.first,  cU);
            nodeToCoordinate(uv.second, cV);
            const auto uVal = image(cU.asStdArray());
            const auto vVal = image(cU.asStdArray());
            edgeMap[edge] = binaryFunctor(uVal, vVal);
        }
    }

    // FIXME this can probably be done more effiicently
    /**
     * @brief convert an affinity map with DIM+1 dimension to an edge map
     * @details convert an affinity map with DIM+1 dimension to an edge map
     * by assining the affinity values to corresponding affinity values
     *
     * @param       image the input affinities
     * @param[out]  the result edge map
     *
     * @return [description]
     */
    template<class AFFINITIES, class EDGE_MAP>
    void affinitiesToEdgeMap(
        const AFFINITIES & affinities,
        EDGE_MAP & edgeMap
    )const{
        NIFTY_CHECK_OP(affinities.shape(0), ==, DIM, "wrong number of affinity channels")
        for(auto d=1; d<DIM+1; ++d){
            NIFTY_CHECK_OP(shape(d-1), ==, affinities.shape(d), "wrong shape")
        }

        typedef nifty::array::StaticArray<int64_t, DIM+1> AffinityCoordType;

        CoordinateType cU,cV;
        for(const auto edge : this->edges()){

            const auto uv = this->uv(edge);
            nodeToCoordinate(uv.first,  cU);
            nodeToCoordinate(uv.second, cV);

            // find the correct affinity edge
            AffinityCoordType affCoord;
            for(size_t d = 0; d < DIM; ++d) {
                auto diff = cU[d] - cV[d];
                if(diff == 0) {
                    affCoord[d + 1] = cU[d];
                }
                else {
                    // TODO max for different direction convention
                    affCoord[d + 1] = std::min(cU[d], cV[d]);
                    affCoord[0] = d;
                }
            }

            edgeMap[edge] = affinities(affCoord.asStdArray());
        }
    }

    template<class AFFINITIES, class EDGE_MAP, class ITER>
    void longRangeAffinitiesToLiftedEdges(
        const AFFINITIES & affinities,
        EDGE_MAP & edgeMap,
        ITER rangesBegin, // iterator to the ranges of the affinities
        ITER axesBegin    // iterator to the axes of the affinities
    ) const {
        typedef nifty::array::StaticArray<int64_t, DIM+1> AffinityCoordType;
        for(auto d=1; d<DIM+1; ++d){
            NIFTY_CHECK_OP(shape(d-1), ==, affinities.shape(d), "wrong shape")
        }
        size_t affLen = affinities.shape(0);
        std::vector<int> ranges(rangesBegin, rangesBegin + affLen);
        std::vector<int> axes(axesBegin, axesBegin + affLen);

        AffinityCoordType affCoord;
        CoordinateType cU, cV;
        size_t axis, range;

        // iterate over the affinties
        for(size_t edgeId = 0; edgeId < affinities.size(); ++edgeId) {
            affinities.indexToCoordinates(edgeId, affCoord.begin());
            axis  = axes[affCoord[0]];
            range = ranges[affCoord[0]];

            //
            for(size_t d = 0; d < DIM; ++d) {
                cU[d] = affCoord[d+1];
                if(d == axis) {
                    cV[d] = affCoord[d+1] + range;
                    // range check
                    if(cV[d] >= shape(d) || cV[d] < 0) {
                        continue;
                    }
                } else {
                    cV[d] = affCoord[d+1];
                }
                auto u = coordianteToNode(cU);
                auto v = coordianteToNode(cV);
                edgeMap.emplace(std::make_pair(std::min(u,v), std::max(u,v)), affinities(affCoord.asStdArray()));
            }
        }
    }

    /**
     * @brief convert an image with DIM dimension to an edge map
     * @details convert an image with DIM dimension to an edge map
     * by taking the values of the image at the
     * interpixel coordinates.
     * The shape of the image must be 2*shape-1
     *
     *
     * @param       image the  input image
     * @param       binaryFunctor a binary functor
     * @param[out]  the result edge map
     *
     * @return [description]
     */
    template<class IMAGE, class EDGE_MAP>
    void imageToInterpixelEdgeMap(
        const IMAGE & image,
        EDGE_MAP & edgeMap
    )const{

        for(auto d=0; d<DIM; ++d){
            NIFTY_CHECK_OP(shape(d)*2-1, ==, image.shape(d),
                "wrong shape foer image to interpixel edge map")
        }

        for(const auto edge : this->edges()){
            const auto uv = this->uv(edge);
            CoordinateType cU,cV;
            nodeToCoordinate(uv.first,  cU);
            nodeToCoordinate(uv.second, cV);
            const auto uVal = image(cU.asStdArray());
            cU += cV;
            edgeMap[edge] = image(cU.asStdArray());
        }
    }

    uint64_t shape(const std::size_t d)const{
        return gridGraph_.shape(DIM-1-d);
    }

    // COORDINATE RELATED
    CoordinateType nodeToCoordinate(const uint64_t node)const{
        CoordinateType ret;
        nodeToCoordinate(node, ret);
        return ret;
    }

    template<class NODE_COORDINATE>
    void nodeToCoordinate(
        const uint64_t node,
        NODE_COORDINATE & coordinate
    )const{
        AndresVertexCoordinate aCoordinate;
        gridGraph_.vertex(node, aCoordinate);
        for(auto d=0; d<DIM; ++d){
            coordinate[d] = aCoordinate[DIM-1-d];
        }
    }

    template<class NODE_COORDINATE>
    uint64_t coordianteToNode(const NODE_COORDINATE & coordinate)const{
        AndresVertexCoordinate aCoordinate;
        for(auto d=0; d<DIM; ++d){
            aCoordinate[DIM-1-d] = coordinate[d];
        }
        return gridGraph_.vertex(aCoordinate);
    }

private:
    andres::graph::GridGraph<DIM> gridGraph_;

};

} // namespace nifty::graph
} // namespace nifty
<commit_msg>Fix lifted affinities in grid rag<commit_after>#pragma once

#include <cstddef>
#include <boost/iterator/counting_iterator.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/iterator/iterator_facade.hpp>

#include "andres/graph/grid-graph.hxx"

#include "nifty/tools/runtime_check.hxx"
#include "nifty/graph/undirected_graph_base.hxx"
#include "nifty/graph/detail/adjacency.hxx"
#include "nifty/graph/graph_tags.hxx"
#include "nifty/parallel/threadpool.hxx"
#include "nifty/array/arithmetic_array.hxx"

namespace nifty{
namespace graph{

namespace detail_graph{

    template<std::size_t DIM, bool SIMPLE_NH>
    class UndirectedGridGraphIter{
    public:
        typedef andres::graph::GridGraph<DIM> AGridGraph;
        typedef typename AGridGraph::AdjacencyIterator AGridGraphAdjacencyIter;
        typedef UndirectedAdjacency<int64_t,int64_t,int64_t,int64_t> NodeAdjacency;

        struct UnaryFunction{
            typedef NodeAdjacency value_type;
            template<class ADJ>
            NodeAdjacency operator()(const ADJ & adjacency)const{
                return NodeAdjacency(adjacency.vertex(), adjacency.vertex());
            }
        };

        typedef boost::transform_iterator<
            UnaryFunction,
            typename AGridGraph::AdjacencyIterator,
            NodeAdjacency,
            NodeAdjacency
        > OldAdjacencyIter;

        class AdjacencyIter
        : public boost::iterator_facade<
            AdjacencyIter,
            NodeAdjacency,
            std::random_access_iterator_tag,
            const NodeAdjacency &
        >
        {
        public:
            AdjacencyIter(const AGridGraphAdjacencyIter & iter)
            :   iter_(iter),
                adjacency_(){
            }
            bool equal(const AdjacencyIter & other)const{
                return iter_ == other.iter_;
            }
            void increment(){
                ++iter_;
            }
            void dencrement(){
                --iter_;
            }
            void advance(const std::size_t n){
                iter_+=n;
            }
            std::ptrdiff_t distance_to(const AdjacencyIter & other)const{
                return std::distance(iter_, other.iter_);
            }
            const NodeAdjacency & dereference()const{
                adjacency_ = NodeAdjacency(iter_->vertex(), iter_->edge());
                return adjacency_;
            }
        private:
            mutable AGridGraphAdjacencyIter iter_;
            mutable NodeAdjacency adjacency_;
        };

        class NodeIter : public boost::counting_iterator<int64_t>{
            using boost::counting_iterator<int64_t>::counting_iterator;
            using boost::counting_iterator<int64_t>::operator=;
        };

        class EdgeIter : public boost::counting_iterator<int64_t>{
            using boost::counting_iterator<int64_t>::counting_iterator;
            using boost::counting_iterator<int64_t>::operator=;
        };
    };

};

template<std::size_t DIM, bool SIMPLE_NH>
class UndirectedGridGraph;

template<std::size_t DIM>
class UndirectedGridGraph<DIM,true> : public
    UndirectedGraphBase<
        UndirectedGridGraph<DIM, true>,
        typename detail_graph::UndirectedGridGraphIter<DIM,true>::NodeIter,
        typename detail_graph::UndirectedGridGraphIter<DIM,true>::EdgeIter,
        typename detail_graph::UndirectedGridGraphIter<DIM,true>::AdjacencyIter
    >
{
private:
    typedef andres::graph::GridGraph<DIM> AndresGridGraphType;
    typedef typename AndresGridGraphType::VertexCoordinate AndresVertexCoordinate;
public:
    typedef nifty::array::StaticArray<int64_t, DIM> ShapeType;
    typedef nifty::array::StaticArray<int64_t, DIM> CoordinateType;

    typedef typename detail_graph::UndirectedGridGraphIter<DIM,true>::NodeIter      NodeIter;
    typedef typename detail_graph::UndirectedGridGraphIter<DIM,true>::EdgeIter      EdgeIter;
    typedef typename detail_graph::UndirectedGridGraphIter<DIM,true>::AdjacencyIter AdjacencyIter;

    typedef ContiguousTag EdgeIdTag;
    typedef ContiguousTag NodeIdTag;

    typedef SortedTag EdgeIdOrderTag;
    typedef SortedTag NodeIdOrderTag;

    UndirectedGridGraph()
    : gridGraph_(){
    }

    template<class T>
    UndirectedGridGraph(const nifty::array::StaticArray<T, DIM> & shape)
    : gridGraph_(){

        AndresVertexCoordinate ashape;
        std::copy(shape.rbegin(), shape.rend(), ashape.begin());
        gridGraph_.assign(ashape);

    }

    template<class T>
    void assign(const nifty::array::StaticArray<T, DIM> & shape){

        AndresVertexCoordinate ashape;
        std::copy(shape.rbegin(), shape.rend(), ashape.begin());
        gridGraph_.assign(ashape);

    }

    //void assign(const uint64_t numberOfNodes = 0, const uint64_t reserveNumberOfEdges = 0);

    // MUST IMPL INTERFACE
    int64_t u(const int64_t e)const{
        return gridGraph_.vertexOfEdge(e,0);
    }
    int64_t v(const int64_t e)const{
        return gridGraph_.vertexOfEdge(e,1);
    }

    int64_t findEdge(const int64_t u, const int64_t v)const{
        const auto r = gridGraph_.findEdge(u,v);
        if(r.first)
            return r.second;
        else
            return -1;
    }
    int64_t nodeIdUpperBound() const{
         return numberOfNodes() == 0 ? 0 : numberOfNodes()-1;
    }
    int64_t edgeIdUpperBound() const{
        return numberOfEdges() == 0 ? 0 : numberOfEdges()-1;
    }

    uint64_t numberOfEdges() const{
        return gridGraph_.numberOfEdges();
    }
    uint64_t numberOfNodes() const{
        return gridGraph_.numberOfVertices();
    }

    NodeIter nodesBegin()const{
        return NodeIter(0);
    }
    NodeIter nodesEnd()const{
        return NodeIter(this->numberOfNodes());
    }
    EdgeIter edgesBegin()const{
        return EdgeIter(0);
    }
    EdgeIter edgesEnd()const{
        return EdgeIter(this->numberOfEdges());
    }

    AdjacencyIter adjacencyBegin(const int64_t node)const{
        return AdjacencyIter(gridGraph_.adjacenciesFromVertexBegin(node));
    }
    AdjacencyIter adjacencyEnd(const int64_t node)const{
        return AdjacencyIter(gridGraph_.adjacenciesFromVertexEnd(node));
    }
    AdjacencyIter adjacencyOutBegin(const int64_t node)const{
        return AdjacencyIter(gridGraph_.adjacenciesFromVertexBegin(node));
    }
     AdjacencyIter adjacencyOutEnd(const int64_t node)const{
        return AdjacencyIter(gridGraph_.adjacenciesFromVertexEnd(node));
    }

    // optional (with default impl in base)
    //std::pair<int64_t,int64_t> uv(const int64_t e)const;

    template<class F>
    void forEachEdge(F && f)const{
        for(uint64_t edge=0; edge< numberOfEdges(); ++edge){
            f(edge);
        }
    }

    template<class F>
    void forEachNode(F && f)const{
        for(uint64_t node=0; node< numberOfNodes(); ++node){
            f(node);
        }
    }

    // serialization de-serialization

    uint64_t serializationSize() const{
        return DIM + 1;
    }

    template<class ITER>
    void serialize(ITER iter) const{
        for(auto d=0; d<DIM; ++d){
            *iter = gridGraph_.shape(d);
            ++iter;
        }
        // simple nh?
        *iter = true;
        ++iter;
    }

    template<class ITER>
    void deserialize(ITER iter);

    /**
     * @brief convert an image with DIM dimension to an edge map
     * @details convert an image with DIM dimension to an edge map
     * by applying a binary functor to the values of a node map at
     * the endpoints of an edge.
     *
     * @param       image the  input image
     * @param       binaryFunctor a binary functor
     * @param[out]  the result edge map
     *
     * @return [description]
     */
    template<class IMAGE, class BINARY_FUNCTOR, class EDGE_MAP>
    void imageToEdgeMap(
        const IMAGE & image,
        BINARY_FUNCTOR binaryFunctor,
        EDGE_MAP & edgeMap
    )const{
        for(const auto edge : this->edges()){
            const auto uv = this->uv(edge);
            CoordinateType cU,cV;
            nodeToCoordinate(uv.first,  cU);
            nodeToCoordinate(uv.second, cV);
            const auto uVal = image(cU.asStdArray());
            const auto vVal = image(cU.asStdArray());
            edgeMap[edge] = binaryFunctor(uVal, vVal);
        }
    }

    // FIXME this can probably be done more effiicently
    /**
     * @brief convert an affinity map with DIM+1 dimension to an edge map
     * @details convert an affinity map with DIM+1 dimension to an edge map
     * by assining the affinity values to corresponding affinity values
     *
     * @param       image the input affinities
     * @param[out]  the result edge map
     *
     * @return [description]
     */
    template<class AFFINITIES, class EDGE_MAP>
    void affinitiesToEdgeMap(
        const AFFINITIES & affinities,
        EDGE_MAP & edgeMap
    )const{
        NIFTY_CHECK_OP(affinities.shape(0), ==, DIM, "wrong number of affinity channels")
        for(auto d=1; d<DIM+1; ++d){
            NIFTY_CHECK_OP(shape(d-1), ==, affinities.shape(d), "wrong shape")
        }

        typedef nifty::array::StaticArray<int64_t, DIM+1> AffinityCoordType;

        CoordinateType cU,cV;
        for(const auto edge : this->edges()){

            const auto uv = this->uv(edge);
            nodeToCoordinate(uv.first,  cU);
            nodeToCoordinate(uv.second, cV);

            // find the correct affinity edge
            AffinityCoordType affCoord;
            for(size_t d = 0; d < DIM; ++d) {
                auto diff = cU[d] - cV[d];
                if(diff == 0) {
                    affCoord[d + 1] = cU[d];
                }
                else {
                    // TODO max for different direction convention
                    affCoord[d + 1] = std::min(cU[d], cV[d]);
                    affCoord[0] = d;
                }
            }

            edgeMap[edge] = affinities(affCoord.asStdArray());
        }
    }

    template<class AFFINITIES, class EDGE_MAP, class ITER>
    void longRangeAffinitiesToLiftedEdges(
        const AFFINITIES & affinities,
        EDGE_MAP & edgeMap,
        ITER rangesBegin, // iterator to the ranges of the affinities
        ITER axesBegin    // iterator to the axes of the affinities
    ) const {
        typedef nifty::array::StaticArray<int64_t, DIM+1> AffinityCoordType;
        for(auto d=1; d<DIM+1; ++d){
            NIFTY_CHECK_OP(shape(d-1), ==, affinities.shape(d), "wrong shape")
        }
        size_t affLen = affinities.shape(0);
        std::vector<int> ranges(rangesBegin, rangesBegin + affLen);
        std::vector<int> axes(axesBegin, axesBegin + affLen);

        AffinityCoordType affCoord;
        CoordinateType cU, cV;
        size_t axis, range;

        // iterate over the affinties
        for(size_t edgeId = 0; edgeId < affinities.size(); ++edgeId) {
            affinities.indexToCoordinates(edgeId, affCoord.begin());
            axis  = axes[affCoord[0]];
            range = ranges[affCoord[0]];

            for(size_t d = 0; d < DIM; ++d) {
                cU[d] = affCoord[d+1];
                cV[d] = affCoord[d+1];
            }
            cV[axis] += range;
            // range check
            if(cV[axis] >= shape(axis) || cV[axis] < 0) {
                continue;
            }
            auto u = coordianteToNode(cU);
            auto v = coordianteToNode(cV);
            edgeMap.emplace(
                std::make_pair(std::min(u,v), std::max(u,v)),
                affinities(affCoord.asStdArray())
            );
        }
    }

    /**
     * @brief convert an image with DIM dimension to an edge map
     * @details convert an image with DIM dimension to an edge map
     * by taking the values of the image at the
     * interpixel coordinates.
     * The shape of the image must be 2*shape-1
     *
     *
     * @param       image the  input image
     * @param       binaryFunctor a binary functor
     * @param[out]  the result edge map
     *
     * @return [description]
     */
    template<class IMAGE, class EDGE_MAP>
    void imageToInterpixelEdgeMap(
        const IMAGE & image,
        EDGE_MAP & edgeMap
    )const{

        for(auto d=0; d<DIM; ++d){
            NIFTY_CHECK_OP(shape(d)*2-1, ==, image.shape(d),
                "wrong shape foer image to interpixel edge map")
        }

        for(const auto edge : this->edges()){
            const auto uv = this->uv(edge);
            CoordinateType cU,cV;
            nodeToCoordinate(uv.first,  cU);
            nodeToCoordinate(uv.second, cV);
            const auto uVal = image(cU.asStdArray());
            cU += cV;
            edgeMap[edge] = image(cU.asStdArray());
        }
    }

    uint64_t shape(const std::size_t d)const{
        return gridGraph_.shape(DIM-1-d);
    }

    // COORDINATE RELATED
    CoordinateType nodeToCoordinate(const uint64_t node)const{
        CoordinateType ret;
        nodeToCoordinate(node, ret);
        return ret;
    }

    template<class NODE_COORDINATE>
    void nodeToCoordinate(
        const uint64_t node,
        NODE_COORDINATE & coordinate
    )const{
        AndresVertexCoordinate aCoordinate;
        gridGraph_.vertex(node, aCoordinate);
        for(auto d=0; d<DIM; ++d){
            coordinate[d] = aCoordinate[DIM-1-d];
        }
    }

    template<class NODE_COORDINATE>
    uint64_t coordianteToNode(const NODE_COORDINATE & coordinate)const{
        AndresVertexCoordinate aCoordinate;
        for(auto d=0; d<DIM; ++d){
            aCoordinate[DIM-1-d] = coordinate[d];
        }
        return gridGraph_.vertex(aCoordinate);
    }

private:
    andres::graph::GridGraph<DIM> gridGraph_;

};

} // namespace nifty::graph
} // namespace nifty
<|endoftext|>


<commit_before>// Copyright (c) 2017 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#ifndef TAOCPP_PEGTL_INCLUDE_CONTRIB_REP_ONE_MIN_MAX_HPP
#define TAOCPP_PEGTL_INCLUDE_CONTRIB_REP_ONE_MIN_MAX_HPP

#include <algorithm>

#include "../config.hpp"

#include "../analysis/counted.hpp"

#include "../internal/bump_help.hpp"
#include "../internal/skip_control.hpp"

namespace tao
{
   namespace TAOCPP_PEGTL_NAMESPACE
   {
      namespace internal
      {
         template< unsigned Min, unsigned Max, char C >
         struct rep_one_min_max
         {
            using analyze_t = analysis::counted< analysis::rule_type::ANY, Min >;

            static_assert( Min <= Max, "invalid rep_one_min_max rule (maximum number of repetitions smaller than minimum)" );

            template< typename Input >
            static bool match( Input& in )
            {
               const auto size = in.size( Max + 1 );
               if( size < Min ) {
                  return false;
               }
               std::size_t i = 0;
               while( ( i < size ) && ( in.peek_char( i ) == C ) ) {
                  ++i;
               }
               if( ( Min <= i ) && ( i <= Max ) ) {
                  bump_help< result_on_found::SUCCESS, Input, char, C >( in, i );
                  return true;
               }
               return false;
            }
         };

         template< unsigned Min, unsigned Max, char C >
         struct skip_control< rep_one_min_max< Min, Max, C > > : std::true_type
         {
         };

      }  // namespace internal

      inline namespace ascii
      {
         template< unsigned Min, unsigned Max, char C >
         struct rep_one_min_max : internal::rep_one_min_max< Min, Max, C >
         {
         };
         struct ellipsis : internal::rep_one_min_max< 3, 3, '.' >
         {
         };

      }  // namespace ascii

   }  // namespace TAOCPP_PEGTL_NAMESPACE

}  // namespace tao

#endif
<commit_msg>Style<commit_after>// Copyright (c) 2017 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#ifndef TAOCPP_PEGTL_INCLUDE_CONTRIB_REP_ONE_MIN_MAX_HPP
#define TAOCPP_PEGTL_INCLUDE_CONTRIB_REP_ONE_MIN_MAX_HPP

#include <algorithm>

#include "../config.hpp"

#include "../analysis/counted.hpp"

#include "../internal/bump_help.hpp"
#include "../internal/skip_control.hpp"

namespace tao
{
   namespace TAOCPP_PEGTL_NAMESPACE
   {
      namespace internal
      {
         template< unsigned Min, unsigned Max, char C >
         struct rep_one_min_max
         {
            using analyze_t = analysis::counted< analysis::rule_type::ANY, Min >;

            static_assert( Min <= Max, "invalid rep_one_min_max rule (maximum number of repetitions smaller than minimum)" );

            template< typename Input >
            static bool match( Input& in )
            {
               const auto size = in.size( Max + 1 );
               if( size < Min ) {
                  return false;
               }
               std::size_t i = 0;
               while( ( i < size ) && ( in.peek_char( i ) == C ) ) {
                  ++i;
               }
               if( ( Min <= i ) && ( i <= Max ) ) {
                  bump_help< result_on_found::SUCCESS, Input, char, C >( in, i );
                  return true;
               }
               return false;
            }
         };

         template< unsigned Min, unsigned Max, char C >
         struct skip_control< rep_one_min_max< Min, Max, C > > : std::true_type
         {
         };

      }  // namespace internal

      inline namespace ascii
      {
         template< unsigned Min, unsigned Max, char C >
         struct rep_one_min_max : internal::rep_one_min_max< Min, Max, C >
         {
         };

         struct ellipsis : internal::rep_one_min_max< 3, 3, '.' >
         {
         };

      }  // namespace ascii

   }  // namespace TAOCPP_PEGTL_NAMESPACE

}  // namespace tao

#endif
<|endoftext|>


<commit_before>//! \file **************************************************************
//! \brief Source Gestion des action/raccourcis
//!
//! - Compilateur : GCC,MinGW
//!
//! \author Antoine Maleyrie
//! \version 1.13
//! \date 20.03.2013
//!
//! ********************************************************************

/*
*	Copyright © 2013 - Antoine Maleyrie.
*/

#include "actionManager.hpp"

//TEST
#include <iostream>

// *********************************************************************
// Class ActionManager
// *********************************************************************

ActionManager::ActionManager() : _shortcut(this)
{
}

ActionManager::~ActionManager()
{
	removeAll();
}

bool ActionManager::add(ShortcutKey const &shortcut, Action* act)
{
	//Ajout à la liste des actions.
	if(!ManagerBase<ShortcutKey, Action>::add(shortcut, act))
		return false;

	//Et on l'ajouter à la liste des raccourcis.
	int id = _shortcut.creat(shortcut);
	Bind(EVT_SHORTCUT, &ActionManager::OnShortcut, this, id);

	return true;
}

bool ActionManager::remove(ShortcutKey const& shortcut)
{
	if(ManagerBase<ShortcutKey, Action>::remove(shortcut))
	{
		//Suppression du accourcie.
		_shortcut.remove(shortcut);
		return true;
	}

	return false;
}

void ActionManager::removeAll()
{
	//Désinstalle les raccourcis.
		_shortcut.removeAll();

	//Suppression des actions.
	ManagerBase<ShortcutKey, Action>::removeAll();
}

void ActionManager::load(wxFileConfig& fileConfig)
{
	wxString stringShortcut;
	long lIndex;

	//Avent de charger quoi que se soi on supprime tout les raccourcis/actions
	removeAll();

	//On positionne le path
	fileConfig.SetPath("/ActionManager");

	//On récupère le premier raccourci
	if(!fileConfig.GetFirstGroup(stringShortcut, lIndex))
	{
		//On positionne le path a la racine.
		fileConfig.SetPath("/");
		return;
	}

	do
	{
		//On positionne le path
		fileConfig.SetPath(stringShortcut);

		//Récupérer le type de l'action.
		wxString actTypeName;
		fileConfig.Read("ActTypeName", &actTypeName);

		//Création d'une action a parte de son nom.
		Action* tmpAct = Action::newAction(actTypeName);
		//Chargement des préférence de l'action à partir du fichier de configuration.
		tmpAct->load(fileConfig);
		//Ajout de l'action.
		add(ShortcutKey::stringToShortcutKey(stringShortcut), tmpAct);

		//On positionne le path
		fileConfig.SetPath("../");

	}//Puis tous les autres
	while(fileConfig.GetNextGroup(stringShortcut, lIndex));

	//On positionne le path a la racine.
	fileConfig.SetPath("/");
}

void ActionManager::save(wxFileConfig& fileConfig)const
{
	for(auto &it: _data)
	{
		//Obtenir la version string du raccourci.
		wxString stringShortcut = ShortcutKey::shortcutKeyToString(it.first);
		//Crée un groupe pour ce raccourci.
		fileConfig.SetPath("/ActionManager/"+stringShortcut);

		//Sauvegarde de l'action
		it.second->save(fileConfig);
	}
}

void ActionManager::enableShortcuts(bool val)
{
	_shortcut.enable(val);
}

void ActionManager::OnShortcut(ShortcutEvent& event)
{
	_data[event.getShortcutKey()]->execute();
}

// *********************************************************************
// Class EditActionManager
// *********************************************************************

EditActionManager::EditActionManager()
{
}

EditActionManager::~EditActionManager()
{
}

void EditActionManager::init()
{
	auto act = ActionManager::getInstance()->getData();

	//Copie de tout les actions.
	for(auto it : act)
		add(it.first, Action::newAction(it.second));
}

void EditActionManager::apply()
{
	ActionManager* actionManager = ActionManager::getInstance();

	//On supprime tout
	actionManager->removeAll();

	//Et on remplie en copient tout les actions.
	for(auto it : _data)
		actionManager->add(it.first, Action::newAction(it.second));
}

std::vector<ShortcutKey> EditActionManager::getShortcutUsedList(wxString const& listName)
{
	std::vector<ShortcutKey> shortcuts;

	//Parcoure de tout les raccourcis/actions
	for(auto it: _data)
	{
		if(it.second->getListNameUsed() == listName)
			shortcuts.push_back(it.first);
	}

	return shortcuts;
}
<commit_msg>fix bug do not charging action if no know<commit_after>//! \file **************************************************************
//! \brief Source Gestion des action/raccourcis
//!
//! - Compilateur : GCC,MinGW
//!
//! \author Antoine Maleyrie
//! \version 1.13
//! \date 20.03.2013
//!
//! ********************************************************************

/*
*	Copyright © 2013 - Antoine Maleyrie.
*/

#include "actionManager.hpp"

//TEST
#include <iostream>

// *********************************************************************
// Class ActionManager
// *********************************************************************

ActionManager::ActionManager() : _shortcut(this)
{
}

ActionManager::~ActionManager()
{
	removeAll();
}

bool ActionManager::add(ShortcutKey const &shortcut, Action* act)
{
	//Ajout à la liste des actions.
	if(!ManagerBase<ShortcutKey, Action>::add(shortcut, act))
		return false;

	//Et on l'ajouter à la liste des raccourcis.
	int id = _shortcut.creat(shortcut);
	Bind(EVT_SHORTCUT, &ActionManager::OnShortcut, this, id);

	return true;
}

bool ActionManager::remove(ShortcutKey const& shortcut)
{
	if(ManagerBase<ShortcutKey, Action>::remove(shortcut))
	{
		//Suppression du accourcie.
		_shortcut.remove(shortcut);
		return true;
	}

	return false;
}

void ActionManager::removeAll()
{
	//Désinstalle les raccourcis.
		_shortcut.removeAll();

	//Suppression des actions.
	ManagerBase<ShortcutKey, Action>::removeAll();
}

void ActionManager::load(wxFileConfig& fileConfig)
{
	wxString stringShortcut;
	long lIndex;

	//Avent de charger quoi que se soi on supprime tout les raccourcis/actions
	removeAll();

	//On positionne le path
	fileConfig.SetPath("/ActionManager");

	//On récupère le premier raccourci
	if(!fileConfig.GetFirstGroup(stringShortcut, lIndex))
	{
		//On positionne le path a la racine.
		fileConfig.SetPath("/");
		return;
	}

	do
	{
		//On positionne le path
		fileConfig.SetPath(stringShortcut);

		//Récupérer le type de l'action.
		wxString actTypeName;
		fileConfig.Read("ActTypeName", &actTypeName);

		//Création d'une action a parte de son nom.
		Action* tmpAct = Action::newAction(actTypeName);

		//Si la création de l'action a réussie, alor on l'ajoute.
		if(tmpAct)
		{
			//Chargement des préférence de l'action à partir du fichier de configuration.
			tmpAct->load(fileConfig);
			//Ajout de l'action.
			add(ShortcutKey::stringToShortcutKey(stringShortcut), tmpAct);
		}

		//On positionne le path
		fileConfig.SetPath("../");

	}//Puis tous les autres
	while(fileConfig.GetNextGroup(stringShortcut, lIndex));

	//On positionne le path a la racine.
	fileConfig.SetPath("/");
}

void ActionManager::save(wxFileConfig& fileConfig)const
{
	for(auto &it: _data)
	{
		//Obtenir la version string du raccourci.
		wxString stringShortcut = ShortcutKey::shortcutKeyToString(it.first);
		//Crée un groupe pour ce raccourci.
		fileConfig.SetPath("/ActionManager/"+stringShortcut);

		//Sauvegarde de l'action
		it.second->save(fileConfig);
	}
}

void ActionManager::enableShortcuts(bool val)
{
	_shortcut.enable(val);
}

void ActionManager::OnShortcut(ShortcutEvent& event)
{
	_data[event.getShortcutKey()]->execute();
}

// *********************************************************************
// Class EditActionManager
// *********************************************************************

EditActionManager::EditActionManager()
{
}

EditActionManager::~EditActionManager()
{
}

void EditActionManager::init()
{
	auto act = ActionManager::getInstance()->getData();

	//Copie de tout les actions.
	for(auto it : act)
		add(it.first, Action::newAction(it.second));
}

void EditActionManager::apply()
{
	ActionManager* actionManager = ActionManager::getInstance();

	//On supprime tout
	actionManager->removeAll();

	//Et on remplie en copient tout les actions.
	for(auto it : _data)
		actionManager->add(it.first, Action::newAction(it.second));
}

std::vector<ShortcutKey> EditActionManager::getShortcutUsedList(wxString const& listName)
{
	std::vector<ShortcutKey> shortcuts;

	//Parcoure de tout les raccourcis/actions
	for(auto it: _data)
	{
		if(it.second->getListNameUsed() == listName)
			shortcuts.push_back(it.first);
	}

	return shortcuts;
}
<|endoftext|>


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

#include <znc/FileUtils.h>
#include <znc/Client.h>
#include <znc/Chan.h>
#include <znc/Modules.h>

class CBacklogMod : public CModule {
public:
	MODCONSTRUCTOR(CBacklogMod) {}
		/*
		AddHelpCommand();
		AddCommand("LogPath",		static_cast<CModCommand::ModCmdFunc>(&CBacklogMod::SetLogPath),
			"<path>");
		AddCommand("Get",			static_cast<CModCommand::ModCmdFunc>(&CBacklogMod::SetLogPath),
	}
	*/

	virtual bool OnLoad(const CString& sArgs, CString& sMessage);
	virtual ~CBacklogMod();
	virtual void OnModCommand(const CString& sCommand);
	virtual void SetLogPath(const CString& Path);

private:
	CString			LogPath;
};

bool CBacklogMod::OnLoad(const CString& sArgs, CString& sMessage) {
	LogPath = sArgs;
	PutModule("I'm being loaded with the arguments: [" + sArgs + "]");

	if(LogPath.empty()) {
		LogPath = GetNV("LogPath");
		if(LogPath.empty()) {
			// TODO: guess logpath

		}
	} else {
		SetNV("LogPath", LogPath);
	}
	return true;
}

CBacklogMod::~CBacklogMod() {
	PutModule("I'm being unloaded!");
}

void CBacklogMod::OnModCommand(const CString& sCommand) {
	if (sCommand.Token(0).CaseCmp("help") == 0) {
		// TODO: help text, look how AddHelpCommand() does it in other ZNC code
		PutModule("Help");
		return;
	}
	else if (sCommand.Token(0).CaseCmp("logpath") == 0) {
		CString Args = sCommand.Token(1, true);
		SetNV("LogPath", Args);
		PutModule("LogPath set to: " + Args);
		return;
	}

	CString User;
	CString Network;
	CString Channel;

	CFile LogFile(sCommand);
	CString Line;

	if (LogFile.Open()) {
		while (LogFile.ReadLine(Line)) {
			PutModule(Line);
		}
	} else {
		PutModule("Could not open log file [" + sCommand + "]: " + strerror(errno));
	}

	LogFile.Close();
}

void CBacklogMod::SetLogPath(const CString& Path) {
	SetNV("LogPath", LogPath);
}

template<> void TModInfo<CBacklogMod>(CModInfo& Info) {
	Info.AddType(CModInfo::NetworkModule);
	Info.AddType(CModInfo::GlobalModule);
	Info.SetWikiPage("backlog");
	Info.SetArgsHelpText("Takes as optional argument (and if given, sets) the log path, use keywords: $USER, $NETWORK and $WINDOW");
	Info.SetHasArgs(true);
}

NETWORKMODULEDEFS(CBacklogMod, "Module for getting the last X lines of a channels log.")
<commit_msg>tell user when setting logpath<commit_after>/*
 * Copyright (C) 2004-2013 ZNC, see the NOTICE file for details.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <znc/FileUtils.h>
#include <znc/Client.h>
#include <znc/Chan.h>
#include <znc/Modules.h>

class CBacklogMod : public CModule {
public:
	MODCONSTRUCTOR(CBacklogMod) {}
		/*
		AddHelpCommand();
		AddCommand("LogPath",		static_cast<CModCommand::ModCmdFunc>(&CBacklogMod::SetLogPath),
			"<path>");
		AddCommand("Get",			static_cast<CModCommand::ModCmdFunc>(&CBacklogMod::SetLogPath),
	}
	*/

	virtual bool OnLoad(const CString& sArgs, CString& sMessage);
	virtual ~CBacklogMod();
	virtual void OnModCommand(const CString& sCommand);

private:
	CString			LogPath;
};

bool CBacklogMod::OnLoad(const CString& sArgs, CString& sMessage) {
	LogPath = sArgs;
	PutModule("I'm being loaded with the arguments: [" + sArgs + "]");

	if(LogPath.empty()) {
		LogPath = GetNV("LogPath");
		if(LogPath.empty()) {
			// TODO: guess logpath

		}
	} else {
		SetNV("LogPath", LogPath);
		PutModule("LogPath set to: " + LogPath);
	}
	return true;
}

CBacklogMod::~CBacklogMod() {
	PutModule("I'm being unloaded!");
}

void CBacklogMod::OnModCommand(const CString& sCommand) {
	if (sCommand.Token(0).CaseCmp("help") == 0) {
		// TODO: help text, look how AddHelpCommand() does it in other ZNC code
		PutModule("Help");
		return;
	}
	else if (sCommand.Token(0).CaseCmp("logpath") == 0) {
		LogPath = sCommand.Token(1, true);
		SetNV("LogPath", LogPath);
		PutModule("LogPath set to: " + LogPath);
		return;
	}

	CString User;
	CString Network;
	CString Channel;

	CFile LogFile(sCommand);
	CString Line;

	if (LogFile.Open()) {
		while (LogFile.ReadLine(Line)) {
			PutModule(Line);
		}
	} else {
		PutModule("Could not open log file [" + sCommand + "]: " + strerror(errno));
	}

	LogFile.Close();
}

template<> void TModInfo<CBacklogMod>(CModInfo& Info) {
	Info.AddType(CModInfo::NetworkModule);
	Info.AddType(CModInfo::GlobalModule);
	Info.SetWikiPage("backlog");
	Info.SetArgsHelpText("Takes as optional argument (and if given, sets) the log path, use keywords: $USER, $NETWORK and $WINDOW");
	Info.SetHasArgs(true);
}

NETWORKMODULEDEFS(CBacklogMod, "Module for getting the last X lines of a channels log.")
<|endoftext|>


<commit_before>#include <iostream>
#include <boost/smart_ptr.hpp>

using namespace std;

int main(){
    boost::shared_ptr<int> p(new int);
    *p = 10;
    cout << *p << endl;
    cout << "Count of p is " << p.use_count() << endl;
    int* int_ptr = new int;
    boost::shared_ptr<int> p2(p);
    *int_ptr = 20;
    cout << *p2 << endl;
    cout << "Count of p is " << p2.use_count() << endl;
    return 0;
}
<commit_msg> Update 03_shared_ptr_example.cpp<commit_after>#include <iostream>
#include <boost/smart_ptr.hpp>
#include <boost/make_shared.hpp>
#include <vector>

using namespace std;

int main(){
    boost::shared_ptr<int> p(new int);
    *p = 10;
    cout << *p << endl;
    cout << "Count of p is " << p.use_count() << endl;
    int* int_ptr = new int;
    boost::shared_ptr<int> p2(p);
    *int_ptr = 20;
    cout << *p2 << endl;
    cout << "Count of p is " << p2.use_count() << endl;

    auto sp = boost::make_shared<string>("make_shared");
    auto spv= boost::make_shared<vector<int> >(10,2);
    for(auto i = spv->begin(); i != spv->end(); ++i)
        cout << *i << endl;
    return 0;
}
<|endoftext|>


<commit_before>// This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org/>

#include "GeometricShapes.h"

#include <cmath>

#include "SupportLibrary.h"

Cylinder::Cylinder()
{
  diameter_ = -999999;
  length_ = -999999;
}

Cylinder::~Cylinder()
{}

double Cylinder::AreaCrossSection()
{
  return (pi / 4) * pow(diameter_, 2);
}

bool Cylinder::Validate(bool is_included_warnings,
                        std::list<std::string>* messages_error) const
{
  bool is_valid = true;

  // validate diameter
  if (diameter_ <= 0
      || ((100 < diameter_) && (is_included_warnings == true))) {

    is_valid = false;
    if (messages_error != nullptr) {
      messages_error->push_back("CYLINDER - Invalid diameter");
    }
  }

  // validate length
  if (length_ <= 0
    || ((120 < length_) && (is_included_warnings == true))) {

    is_valid = false;
    if (messages_error != nullptr) {
      messages_error->push_back("CYLINDER - Invalid length");
    }
  }

  return is_valid;
}

double Cylinder::Volume()
{
  return AreaCrossSection() * length_;
}

double Cylinder::diameter()
{
  return diameter_;
}

double Cylinder::length()
{
  return length_;
}

void Cylinder::set_diameter(const double& diameter)
{
  diameter_ = diameter;
}

void Cylinder::set_length(const double& length)
{
  length_ = length;
}
<commit_msg>Updated code formatting<commit_after>// This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org/>

#include "GeometricShapes.h"

#include <cmath>

#include "SupportLibrary.h"

Cylinder::Cylinder()
{
  diameter_ = -999999;
  length_ = -999999;
}

Cylinder::~Cylinder()
{}

double Cylinder::AreaCrossSection()
{
  return (pi / 4) * pow(diameter_, 2);
}

bool Cylinder::Validate(bool is_included_warnings,
                        std::list<std::string>* messages_error) const
{
  bool is_valid = true;

  // validate diameter
  if (diameter_ <= 0
      || ((100 < diameter_) && (is_included_warnings == true))) {

    is_valid = false;
    if (messages_error != nullptr) {
      messages_error->push_back("CYLINDER - Invalid diameter");
    }
  }

  // validate length
  if (length_ <= 0
      || ((120 < length_) && (is_included_warnings == true))) {

    is_valid = false;
    if (messages_error != nullptr) {
      messages_error->push_back("CYLINDER - Invalid length");
    }
  }

  return is_valid;
}

double Cylinder::Volume()
{
  return AreaCrossSection() * length_;
}

double Cylinder::diameter()
{
  return diameter_;
}

double Cylinder::length()
{
  return length_;
}

void Cylinder::set_diameter(const double& diameter)
{
  diameter_ = diameter;
}

void Cylinder::set_length(const double& length)
{
  length_ = length;
}
<|endoftext|>


<commit_before>//Implementation of a Forest Fire Simulation

#include <cassert>
#include <random>
#include "forest.hpp"
#include "tclap/ValueArg.h"

WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(ForestEvent)

std::vector<std::shared_ptr<warped::Event> > Forest::initializeLP() {

    // Register random number generator
    //this->registerRNG<std::default_random_engine>(this->rng_);

    std::default_random_engine rng;

    uniform_int_distribution<int> LPS(0, this->width * this->height);

    std::vector<std::shared_ptr<warped::Event> > events;

    events.emplace_back(new ForestEvent {lp_name(LPS(rng), IGNITION, 1});

    return events;
}

inline std::string Forest::lp_name(const unsigned int lp_index){

    return std::string("Forest_") + std::to_string(lp_index);
}

std::vector<std::shared_ptr<warped::Event> > Forest::receiveEvent(const warped::Event& event) {

    std::vector<std::shared_ptr<warped::Event> > response_events;
    auto received_event = static_cast<const ForestEvent&>(event);

    switch (received_event.type_) {

        case RADIATION: {
            this->state_.heat_content_=this->state_.heat_content_ + recieved_event.heat_content;
            // if there is enough heat and the vegtation is unburnt Schedule ignition
            if(this->state_.heat_content_ >= this->ignition_threshold && this->state_burn_status == UNBURNT){
            unsigned int ignition_time = recieved_event.ts+1;
            response_events.emplace_back(new ForestEvent {this->name_, IGNITION, ignition_time });
            }
            break;
        }

        case RADIATION_TIMER: {
            unsigned int radiation_heat=this->state_.heat_content_ /100 * 5
            this->state_.heat_content_ /100 * 95;
            // Schedule Radiation events for each of the eight surrounding LPs
            /*begin for loop*/
            unsigned int radiation_time = received_event.ts_ + 1;
            response_events.emplace_back(new ForestEvent { this->name_, RADIATION,
                                                                            radiation_time });
            /*end for loop*/
            if(this->state_.heat_content_ <= this->burnout_threshold){
            this->state_.burn_status_ = BURNOUT
            }
            else{
            unsigned int radiation_timer = recieved_event.ts + 5;
            response_events.emplace_back(new ForestEvent {this->name_, RADIATION_TIMER, radiation_timer });
            }
            break;
        }
        case IGNITION: {
            this->state_.burn_status_=GROWTH;
            // Schedule Peak Event
            unsigned int peak_time = received_event.ts + ((this->peak_threshold-this->ignition_threshold)/this->heat_rate);
            response_events.emplace_back(new ForestEvent {this->name_, PEAK, peak_time });
            break;
        }
        case PEAK: {
            this->state_.burn_status_=DECAY;
            this->state_.heat_content_=this->state_.heat_content_ + (this->peak_threshold - this->ignition_threshold);
            // Schedule first Radiation Timer
            unsigned int radiation_timer = recieved_event.ts + 5;
            response_events.emplace_back(new ForestEvent {this->name_, RADIATION_TIMER, radiation_timer });
            break;
        }
    }
    return response_events;
}

std::queue<int> ignition_threshold_vector;
std::queue<int> peak_threshold_vector;
unsigned int width,height;

unsigned char *read_bmp( std::string img_name, unsigned int heat_rate,
                         unsigned int radiation_percent, unsigned int burnout_threshold){

    FILE *fp = fopen(img_name.c_str(), "rb");
    if(!fp) throw "Argument Exception";

    // Read the 54-byte header
    unsigned char info[54];
    fread(info, sizeof(unsigned char), 54, fp);

    // Extract image height and width from header
    width  = *(unsigned int *)&info[18];
    height = *(unsigned int *)&info[22];

    std::cout << "Width  : " << width    << std::endl;
    std::cout << "Height : " << height   << std::endl;

    unsigned int row_padded = (width*3 + 3) & (~3);
    unsigned char *data = new unsigned char[row_padded];

    for( unsigned int i = 0; i < height; i++ ) {
        fread(data, sizeof(unsigned char), row_padded, fp);
        for(unsigned int j = 0; j < width*3; j += 3) {
            //std::cout   << "B: "<< (int)data[j]
            //            << " G: " << (int)data[j+1]
            //            << " R: " << (int)data[j+2]
            //            << std::endl;
            unsigned int index_num = i*j;
            //Placeholder equations for threshold calculation
            unsigned int ignition_threshold = (int)data[j] + (int)data[j+1] + (int)data[j+2];
            unsigned int peak_threshold = ((int)data[j] + (int)data[j+1] + (int)data[j+2]) * 2;

            std::string name = Forest::lp_name(index_num)
            lps.emplace_back(name, width, height,ignition_threshold, heat_rate,
                             peak_threshold, burnout_threshold, index_num);

        }
   }
   fclose(fp);
   return data;
}

int main(int argc, char *argv[],){

    std::string config_filename = "map_hawaii.bmp";
    unsigned int heat_rate = 100;
    unsigned int radiation_percent = 5;
    unsigned int burnout_threshold = 50;

    TCLAP::ValueArg<std::string> config_arg("m", "map",
                        "Forest model vegetation config", false, config_filename, "string");
    TCLAP::ValueArg<unsigned int> heat_rate_arg("h", "heat-rate", "Speed of growth of the fire",
                                                                false, heat_rate, "unsigned int");
    TCLAP::ValueArg<unsigned int> radition_percent_arg("r", "radiation-percent",
            "Percent of Heat released every timstamp", false, radiation_percent, "unsigned int");
    TCLAP::ValueArg<unsigned int> burnout_threshold_arg("b", "burnout-threshold",
                                    "Amount of heat needed for a cell to burn out", false,
                                                            burnout_threshold, "unsigned int");
    std::vector<TCLAP::Arg*> args = {&config_arg, &heat_rate_arg,
                                     &radiation_percent_arg, &burnout_threshold_arg};

    config_filename = config_arg.getValue();
    heat_rate = heat_rate_arg.getValue();
    radiation_percent = radiation_percent_arg.getValue();
    burnout_threshold = burnout_threshold.getValue();

    warped::Simulation forest_sim {"Forest Simulation", argc, argv, args};

    std::vector<Forest> lps;

    (void) read_bmp(config_filename, heat_rate, radiation_percent, burnout_threshold);

    std::vector<warped::LogicalProcess*> lp_pointers;
    for (auto& lp : lps) {
        lp_pointers.push_back(&lp);
    }

    forest_sim.simulate(lp_pointers);

    return 0;

}
<commit_msg>Created compute spread skeleton function<commit_after>//Implementation of a Forest Fire Simulation

#include <cassert>
#include <random>
#include "forest.hpp"
#include "tclap/ValueArg.h"

WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(ForestEvent)

std::vector<std::shared_ptr<warped::Event> > Forest::initializeLP() {

    std::vector<std::shared_ptr<warped::Event> > events;

    for (unsigned int i = 0; i < this->index_; i++){ //For all of the cells in the forest
        if(this->state.heat_content_ >= this->ignition_threshold){ //If heat content > ignition threshold
            events.emplace_back(new ForestEvent {this->name_, IGNITION,ts_} // Then start an ignition event
        }
    }
    return events;
}

inline std::string Forest::lp_name(const unsigned int lp_index){

    return std::string("Forest_") + std::to_string(lp_index);
}

std::vector<std::shared_ptr<warped::Event> > Forest::receiveEvent(const warped::Event& event) {

    std::vector<std::shared_ptr<warped::Event> > response_events;
    auto received_event = static_cast<const ForestEvent&>(event);

    switch (received_event.type_) {

        case RADIATION: {
            this->state_.heat_content_=this->state_.heat_content_ + recieved_event.heat_content;
            // if there is enough heat and the vegtation is unburnt Schedule ignition
            if(this->state_.heat_content_ >= this->ignition_threshold &&
                                                            this->state_burn_status == UNBURNT){
            unsigned int ignition_time = recieved_event.ts+1;
            response_events.emplace_back(new ForestEvent {this->name_, IGNITION, ignition_time });
            }
            break;
        }

        case RADIATION_TIMER: {
            unsigned int radiation_heat=this->state_.heat_content_ /100 * 5
            this->state_.heat_content_ /100 * 95;
            // Schedule Radiation events for each of the eight surrounding LPs
            /*begin for loop*/
            unsigned int radiation_time = received_event.ts_ + 1;
            response_events.emplace_back(new ForestEvent { this->name_, RADIATION,
                                                                            radiation_time });
            /*end for loop*/
            if(this->state_.heat_content_ <= this->burnout_threshold){
            this->state_.burn_status_ = BURNOUT
            }
            else{
            unsigned int radiation_timer = recieved_event.ts + 5;
            response_events.emplace_back(new ForestEvent {this->name_, RADIATION_TIMER,
                                                                           radiation_timer });
            }
            break;
        }
        case IGNITION: {
            this->state_.burn_status_=GROWTH;
            // Schedule Peak Event
            unsigned int peak_time = received_event.ts + ((this->peak_threshold-this->ignition_threshold)/this->heat_rate);
            response_events.emplace_back(new ForestEvent {this->name_, PEAK, peak_time });
            break;
        }
        case PEAK: {
            this->state_.burn_status_=DECAY;
            this->state_.heat_content_=this->state_.heat_content_ + (this->peak_threshold - this->ignition_threshold);
            // Schedule first Radiation Timer
            unsigned int radiation_timer = recieved_event.ts + 5;
            response_events.emplace_back(new ForestEvent {this->name_, RADIATION_TIMER,
                                                                          radiation_timer });
            break;
        }
    }
    return response_events;
}

unsigned char *read_bmp( std::string img_name, unsigned int heat_rate,
                            unsigned int radiation_percent, unsigned int burnout_threshold
                                        unsigned int burn_start_x, unsigned int burn_start_y){

    FILE *fp = fopen(img_name.c_str(), "rb");
    if(!fp) throw "Argument Exception";

    // Read the 54-byte header
    unsigned char info[54];
    fread(info, sizeof(unsigned char), 54, fp);

    // Extract image height and width from header
    width  = *(unsigned int *)&info[18];
    height = *(unsigned int *)&info[22];

    std::cout << "Width  : " << width    << std::endl;
    std::cout << "Height : " << height   << std::endl;

    unsigned int row_padded = (width*3 + 3) & (~3);
    unsigned char *data = new unsigned char[row_padded];

    for( unsigned int i = 0; i < height; i++ ) {
        fread(data, sizeof(unsigned char), row_padded, fp);
        for(unsigned int j = 0; j < width*3; j += 3) {
            //std::cout   << "B: "<< (int)data[j]
            //            << " G: " << (int)data[j+1]
            //            << " R: " << (int)data[j+2]
            //            << std::endl;
            unsigned int index_num = i*j;
            //Placeholder equations for threshold calculation
            unsigned int ignition_threshold = (int)data[j] + (int)data[j+1] + (int)data[j+2];
            unsigned int peak_threshold = ((int)data[j] + (int)data[j+1] + (int)data[j+2]) * 2;

            std::string name = Forest::lp_name(index_num)
            lps.emplace_back(name, width, height,ignition_threshold, heat_rate,
                                     peak_threshold, burnout_threshold, index_num);

            /* If the LP being created is the start of the fire then give it intial heat content */
            if(i == burn_start_x && j == burn_start_y){
                this->state.heat_content_ = 400
            }
        }
   }
   fclose(fp);
   return data;
}

std::string Forest::compute_spread(direction_t direction) {

    unsigned int new_x = 0, new_y = 0;
    unsigned int current_y = index_ / size_x_;
    unsigned int current_x = index_ % size_x_;

    switch (direction) {

       case NORTH: {
           new_x = current_x;
           new_y = (current_y + 1) % size_y_;
       } break;

       case NORTH_EAST: {
           new_x = (current_x + 1) % size_x_;
           new_y = (current_y + 1) % size_y_;
       } break;

       case EAST: {
           new_x = (current_x + 1) % size_x_;
           new_y = current_y;
       } break;

       case SOUTH_EAST: {
           new_x = (current_x + 1) % size_x_;
           new_y = (current_y + size_y_ - 1) % size_y_;
       } break;

       case SOUTH: {
           new_x = current_x;
           new_y = (current_y + size_y_ - 1) % size_y_;
       } break;

       case SOUTH_WEST: {
           new_x = (current_x + size_x_ - 1) % size_x_;
           new_y = (current_y + size_y_ - 1) % size_y_;
       } break;

       case WEST: {
           new_x = (current_x + size_x_ - 1) % size_x_;
           new_y = current_y;
       } break;

       case NORTH_WEST: {
           new_x = (current_x + size_x_ - 1) % size_x_;
           new_y = (current_y + 1) % size_y_;
       } break;

       default: {
           std::cerr << "Invalid move direction " << direction << std::endl;
           assert(0);
       }
       }

       return lp_name(new_x + new_y * size_x_);
}

int main(int argc, char *argv[],){

    std::string config_filename = "map_hawaii.bmp";
    unsigned int heat_rate = 100;
    unsigned int radiation_percent = 5;
    unsigned int burnout_threshold = 50;
    unsigned int burn_start_x = 500;
    unsigned int burn_start_y = 501;

    TCLAP::ValueArg<std::string> config_arg("m", "map", "Forest model vegetation config",
                                                                false, config_filename, "string");
    TCLAP::ValueArg<unsigned int> heat_rate_arg("h", "heat-rate", "Speed of growth of the fire",
                                                                false, heat_rate, "unsigned int");
    TCLAP::ValueArg<unsigned int> radition_percent_arg("r", "radiation-percent",
             "Percent of Heat released every timstamp", false, radiation_percent, "unsigned int");
    TCLAP::ValueArg<unsigned int> burnout_threshold_arg("b", "burnout-threshold",
                                    "Amount of heat needed for a cell to burn out", false,
                                                               burnout_threshold, "unsigned int");
    TCLAP::ValueArg<unsigned int> burn_start_x_arg("x", "burn-start-x",
                                                     "x coordinate of the start of fire", false,
                                                                    burn_start_x, "unsigned int");
    TCLAP::ValueArg<unsigned int> burn_start_y_arg("y", "burn-start-y",
                                                     "y coordinate of the start of fire", false,
                                                                    burn_start_y, "unsigned int");

    std::vector<TCLAP::Arg*> args = {&config_arg, &heat_rate_arg,
                                        &radiation_percent_arg, &burnout_threshold_arg,
                                                    &burn_start_x_arg, &burn_start_y_arg};

    config_filename = config_arg.getValue();
    heat_rate = heat_rate_arg.getValue();
    radiation_percent = radiation_percent_arg.getValue();
    burnout_threshold = burnout_threshold.getValue();
    burn_start_x = burn_start_x.getValue();
    burn_start_y = burn_start_y.getValue();

    warped::Simulation forest_sim {"Forest Simulation", argc, argv, args};

    std::vector<Forest> lps;

    (void) read_bmp(config_filename, heat_rate, radiation_percent, burnout_threshold,
                                                                burn_start_x, burn_start_y);

    std::vector<warped::LogicalProcess*> lp_pointers;
    for (auto& lp : lps) {
        lp_pointers.push_back(&lp);
    }

    forest_sim.simulate(lp_pointers);

    return 0;

}
<|endoftext|>


<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
    commands/refreshx509certscommand.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2008 Klarälvdalens Datakonsult AB

    Kleopatra is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Kleopatra is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <config-kleopatra.h>

#include "refreshx509certscommand.h"

#include <KLocale>
#include <KMessageBox>

using namespace Kleo;
using namespace Kleo::Commands;

RefreshX509CertsCommand::RefreshX509CertsCommand( KeyListController * c )
    : GnuPGProcessCommand( c )
{

}

RefreshX509CertsCommand::RefreshX509CertsCommand( QAbstractItemView * v, KeyListController * c )
    : GnuPGProcessCommand( v, c )
{

}

RefreshX509CertsCommand::~RefreshX509CertsCommand() {}

bool RefreshX509CertsCommand::preStartHook( QWidget * parent ) const {
    return KMessageBox::warningContinueCancel( parent,
                                               i18n("Refreshing X.509 certificates implies downloading CRLs for all certificates, "
                                                    "even if they might otherwise still be valid. "
                                                    "This can put a severe strain on your own as well as other people's network "
                                                    "connection, and can take up to an hour or more to complete, depending on "
                                                    "your network connection, and the number of certificates to check. "
                                                    "Are you sure you want to continue?"),
                                               i18n("X.509 Certitifcate Refresh"),
                                               KStandardGuiItem::cont(), KStandardGuiItem::cancel(),
                                               QLatin1String( "warn-refresh-x509-expensive" ) )
        == KMessageBox::Continue;
}

QStringList RefreshX509CertsCommand::arguments() const {
    return QStringList() << "gpgsm" << "-k" << "--with-validation" << "--force-crl-refresh" << "--enable-crl-checks";
}

QString RefreshX509CertsCommand::errorCaption() const {
    return i18n( "X.509 Certificate Refresh Error" );
}

QString RefreshX509CertsCommand::successCaption() const {
    return i18n( "X.509 Certificate Refresh Finished" );
}

QString RefreshX509CertsCommand::crashExitMessage( const QStringList & args ) const {
    return i18n( "The GpgSM process that tried to refresh X.509 certificates "
                 "ended prematurely because of an unexpected error. "
                 "Please check the output of %1 for details.", args.join( " " ) ) ;
}

QString RefreshX509CertsCommand::errorExitMessage( const QStringList & args ) const {
    return i18n( "An error occurred while trying to refresh X.509 certificates. "
                 "The output from %1 was:\n%2", args[0], errorString() );
}

QString RefreshX509CertsCommand::successMessage( const QStringList & ) const {
    return i18n( "X.509 certificates refreshed successfully." );
}

#include "moc_refreshx509certscommand.cpp"
<commit_msg>Use gpgSmPath() instead of "gpgsm"<commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
    commands/refreshx509certscommand.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2008 Klarälvdalens Datakonsult AB

    Kleopatra is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Kleopatra is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <config-kleopatra.h>

#include "refreshx509certscommand.h"

#include <utils/gnupg-helper.h>

#include <KLocale>
#include <KMessageBox>

using namespace Kleo;
using namespace Kleo::Commands;

RefreshX509CertsCommand::RefreshX509CertsCommand( KeyListController * c )
    : GnuPGProcessCommand( c )
{

}

RefreshX509CertsCommand::RefreshX509CertsCommand( QAbstractItemView * v, KeyListController * c )
    : GnuPGProcessCommand( v, c )
{

}

RefreshX509CertsCommand::~RefreshX509CertsCommand() {}

bool RefreshX509CertsCommand::preStartHook( QWidget * parent ) const {
    return KMessageBox::warningContinueCancel( parent,
                                               i18n("Refreshing X.509 certificates implies downloading CRLs for all certificates, "
                                                    "even if they might otherwise still be valid. "
                                                    "This can put a severe strain on your own as well as other people's network "
                                                    "connection, and can take up to an hour or more to complete, depending on "
                                                    "your network connection, and the number of certificates to check. "
                                                    "Are you sure you want to continue?"),
                                               i18n("X.509 Certitifcate Refresh"),
                                               KStandardGuiItem::cont(), KStandardGuiItem::cancel(),
                                               QLatin1String( "warn-refresh-x509-expensive" ) )
        == KMessageBox::Continue;
}

QStringList RefreshX509CertsCommand::arguments() const {
    return QStringList() << gpgSmPath() << "-k" << "--with-validation" << "--force-crl-refresh" << "--enable-crl-checks";
}

QString RefreshX509CertsCommand::errorCaption() const {
    return i18n( "X.509 Certificate Refresh Error" );
}

QString RefreshX509CertsCommand::successCaption() const {
    return i18n( "X.509 Certificate Refresh Finished" );
}

QString RefreshX509CertsCommand::crashExitMessage( const QStringList & args ) const {
    return i18n( "The GpgSM process that tried to refresh X.509 certificates "
                 "ended prematurely because of an unexpected error. "
                 "Please check the output of %1 for details.", args.join( " " ) ) ;
}

QString RefreshX509CertsCommand::errorExitMessage( const QStringList & args ) const {
    return i18n( "An error occurred while trying to refresh X.509 certificates. "
                 "The output from %1 was:\n%2", args[0], errorString() );
}

QString RefreshX509CertsCommand::successMessage( const QStringList & ) const {
    return i18n( "X.509 certificates refreshed successfully." );
}

#include "moc_refreshx509certscommand.cpp"
<|endoftext|>


<commit_before><commit_msg>do not make default suffix lower case<commit_after><|endoftext|>


<commit_before><commit_msg>remove whitespace<commit_after><|endoftext|>