Parcourir la source

Add corsen library and tests

Eric Ramat il y a 10 ans
Parent
commit
79b8817211
43 fichiers modifiés avec 6393 ajouts et 283 suppressions
  1. 5 3
      src/apps/main.cpp
  2. 1 0
      src/tests/CMakeLists.txt
  3. 354 11
      src/tests/boost_graph/graph_manager.hpp
  4. 58 18
      src/tests/boost_graph/graph_partitioning.hpp
  5. 1 1
      src/tests/boost_graph/partitioning/CMakeLists.txt
  6. 0 22
      src/tests/boost_graph/partitioning/defs.hpp
  7. 456 162
      src/tests/boost_graph/partitioning/gggp.cpp
  8. 3 0
      src/tests/boost_graph/partitioning/gggp.hpp
  9. 77 0
      src/tests/boost_graph/partitioning/graph_build.cpp
  10. 1 0
      src/tests/boost_graph/partitioning/graph_build.hpp
  11. 125 43
      src/tests/boost_graph/partitioning/utils.cpp
  12. 10 2
      src/tests/boost_graph/partitioning/utils.hpp
  13. 278 21
      src/tests/boost_graph/tests.cpp
  14. 23 0
      src/tests/corsen/CMakeLists.txt
  15. 27 0
      src/tests/corsen/lib/CMakeLists.txt
  16. 149 0
      src/tests/corsen/lib/Constantes.h
  17. 112 0
      src/tests/corsen/lib/ContextData.h
  18. 234 0
      src/tests/corsen/lib/ContextFileReader.h
  19. 319 0
      src/tests/corsen/lib/Coordinates.h
  20. 193 0
      src/tests/corsen/lib/Corsen.cpp
  21. 157 0
      src/tests/corsen/lib/Corsen.hpp
  22. 126 0
      src/tests/corsen/lib/DrainFileStream.h
  23. 141 0
      src/tests/corsen/lib/ElevationFileStream.h
  24. 77 0
      src/tests/corsen/lib/Exception.h
  25. 209 0
      src/tests/corsen/lib/FileStream.h
  26. 173 0
      src/tests/corsen/lib/Functions.cpp
  27. 86 0
      src/tests/corsen/lib/Functions.h
  28. 230 0
      src/tests/corsen/lib/Graph.cpp
  29. 200 0
      src/tests/corsen/lib/Graph.hpp
  30. 282 0
      src/tests/corsen/lib/Layer.h
  31. 121 0
      src/tests/corsen/lib/LayersFileStream.h
  32. 141 0
      src/tests/corsen/lib/LayersTextFileStream.h
  33. 149 0
      src/tests/corsen/lib/Node.h
  34. 179 0
      src/tests/corsen/lib/Outlet.h
  35. 242 0
      src/tests/corsen/lib/OutletFileStream.h
  36. 87 0
      src/tests/corsen/lib/Parameters.h
  37. 255 0
      src/tests/corsen/lib/ParametersFileStream.h
  38. 123 0
      src/tests/corsen/lib/Singleton.h
  39. 114 0
      src/tests/corsen/lib/SlopeFileStream.h
  40. 98 0
      src/tests/corsen/lib/SoilFileStream.h
  41. 295 0
      src/tests/corsen/lib/Vertex.h
  42. 350 0
      src/tests/corsen/lib/XmlReader.h
  43. 132 0
      src/tests/corsen/tests.cpp

+ 5 - 3
src/apps/main.cpp

@@ -118,6 +118,8 @@ void run_hierarchic_with_vector()
 
 int main()
 {
+    boost::timer::cpu_timer t;
+
     srand(108364);
 
     run_flat_with_heap < 10 >();
@@ -144,18 +146,18 @@ int main()
     run_flat_with_vector < 100 >();
     run_flat_with_vector < 200 >();
 
-    double t2 = t.elapsed();
+    double t2 = t.elapsed().user;
 
     std::cout << "run_hierarchic_with_heap ..." << std::endl;
     run_hierarchic_with_heap();
 
-    double t3 = t.elapsed();
+    double t3 = t.elapsed().user;
 
     std::cout << "... OK -> " << (t3 - t2) << std::endl;
     std::cout << "run_hierarchic_with_vector ..." << std::endl;
     run_hierarchic_with_vector();
 
-    double t4 = t.elapsed();
+    double t4 = t.elapsed().user;
 
     std::cout << "... OK -> "  << (t4 - t3) << std::endl;
 

+ 1 - 0
src/tests/CMakeLists.txt

@@ -10,6 +10,7 @@ LINK_DIRECTORIES(
   ${LIBXML_LIBRARY_DIR})
 
 ADD_SUBDIRECTORY(boost_graph)
+ADD_SUBDIRECTORY(corsen)
 ADD_SUBDIRECTORY(dtss)
 ADD_SUBDIRECTORY(mixed)
 ADD_SUBDIRECTORY(multithreading)

+ 354 - 11
src/tests/boost_graph/graph_manager.hpp

@@ -34,7 +34,10 @@
 #include <kernel/pdevs/GraphManager.hpp>
 #include <kernel/pdevs/Simulator.hpp>
 
+#include <kernel/pdevs/multithreading/Coordinator.hpp>
+
 #include <tests/boost_graph/models.hpp>
+#include <tests/boost_graph/graph_partitioning.hpp>
 
 namespace paradevs { namespace tests { namespace boost_graph {
 
@@ -258,6 +261,71 @@ public:
     { }
 };
 
+template < class SchedulerHandle >
+class ParallelBuiltFlatGraphManager :
+        public FlatGraphManager < SchedulerHandle, GraphParameters >
+{
+public:
+    ParallelBuiltFlatGraphManager(
+        common::Coordinator < common::DoubleTime,
+                              SchedulerHandle >* coordinator,
+        const GraphParameters& parameters) :
+        FlatGraphManager < SchedulerHandle, GraphParameters >(
+            coordinator, parameters)
+    {
+        ParallelBuiltFlatGraphManager < SchedulerHandle >::build_flat_graph(
+            parameters._graph, parameters._input_edges);
+        // input
+        for (Edges::const_iterator it = parameters._input_edges.begin();
+             it != parameters._input_edges.end(); ++it) {
+            std::ostringstream ss_in;
+
+            ss_in << "in_" << it->first;
+            if (not coordinator->exist_in_port(ss_in.str())) {
+                coordinator->add_in_port(ss_in.str());
+            }
+            ParallelBuiltFlatGraphManager < SchedulerHandle>::add_link(
+                coordinator, ss_in.str(),
+                ParallelBuiltFlatGraphManager <
+                    SchedulerHandle >::_normal_simulators[it->second], "in");
+        }
+        // output
+        for (Edges::const_iterator it = parameters._output_edges.begin();
+             it != parameters._output_edges.end(); ++it) {
+            std::ostringstream ss_out;
+
+            ss_out << "out_" << it->first;
+            if (not coordinator->exist_out_port(ss_out.str())) {
+                coordinator->add_out_port(ss_out.str());
+            }
+            if (not ParallelBuiltFlatGraphManager < SchedulerHandle>::exist_link(
+                ParallelBuiltFlatGraphManager <
+                    SchedulerHandle >::_normal_simulators[it->first], "out",
+                coordinator, ss_out.str())) {
+                ParallelBuiltFlatGraphManager < SchedulerHandle>::add_link(
+                    ParallelBuiltFlatGraphManager <
+                        SchedulerHandle >::_normal_simulators[it->first], "out",
+                    coordinator, ss_out.str());
+            }
+        }
+    }
+
+    void init()
+    { }
+
+    void start(common::DoubleTime::type /* t */)
+    { }
+
+    void transition(
+        const common::Models < common::DoubleTime,
+                               SchedulerHandle >& /* receivers */,
+        common::DoubleTime::type /* t */)
+    { }
+
+    virtual ~ParallelBuiltFlatGraphManager()
+    { }
+};
+
 template < class SchedulerHandle, class GraphBuilder >
 class InBuildFlatGraphManager :
         public FlatGraphManager < SchedulerHandle,
@@ -287,22 +355,40 @@ public:
     { }
 };
 
+struct PartitioningParameters
+{
+    int         cluster_number;
+    std::string partitioning_method_name;
+    int         contraction_coef;
+    bool        contraction_coef_flag;
+
+    PartitioningParameters(int cn,
+                           const std::string& pmn,
+                           int cc, bool ccf) :
+        cluster_number(cn), partitioning_method_name(pmn),
+        contraction_coef(cc), contraction_coef_flag(ccf)
+    { }
+};
+
 template < class SchedulerHandle, class GraphBuilder >
-class HierarchicalGraphManager :
+class HeapHierarchicalGraphManager :
         public paradevs::pdevs::GraphManager < common::DoubleTime,
                                                SchedulerHandle,
-                                               paradevs::common::NoParameters >
+                                               PartitioningParameters >
 {
 public:
-    HierarchicalGraphManager(
+    HeapHierarchicalGraphManager(
         common::Coordinator < common::DoubleTime,
                               SchedulerHandle >* coordinator,
-        const paradevs::common::NoParameters& parameters) :
+        const PartitioningParameters& parameters) :
         paradevs::pdevs::GraphManager < common::DoubleTime, SchedulerHandle,
-                                        paradevs::common::NoParameters >(
+                                        PartitioningParameters >(
                                             coordinator, parameters)
     {
-        GraphBuilder   graph_builder;
+        GraphBuilder graph_builder(parameters.cluster_number,
+                                   parameters.partitioning_method_name,
+                                   parameters.contraction_coef,
+                                   parameters.contraction_coef_flag);
         OrientedGraphs graphs;
         InputEdgeList  input_edges;
         OutputEdgeList output_edges;
@@ -311,6 +397,25 @@ public:
         graph_builder.build(graphs, input_edges, output_edges,
                             parent_connections);
 
+        // for (unsigned int i = 0; i < graphs.size(); ++i) {
+        //     std::cout << "graph[" << i << "]:" << std::endl;
+        //     const OrientedGraph& og = graphs[i];
+        //     OrientedGraph::vertex_iterator it_og, end_og;
+        //     tie(it_og, end_og) = vertices(og);
+        //     for (; it_og != end_og; ++it_og) {
+        //         OrientedGraph::adjacency_iterator neighbour_it, neighbour_end;
+
+        //         std::cout << og[*it_og]._index << " is connected with ";
+        //         tie(neighbour_it, neighbour_end) = adjacent_vertices(*it_og,
+        //                                                              og);
+        //         for (; neighbour_it != neighbour_end; ++neighbour_it)
+        //             std::cout << og[*neighbour_it]._index << " ";
+        //         std::cout << " and weight = " << og[*it_og]._weight
+        //                   << std::endl;
+        //     }
+        //     std::cout << "===" << std::endl;
+        // }
+
         // build coordinators (graphs)
         for (unsigned int i = 0; i < graphs.size(); ++i) {
             Coordinator* coordinator = 0;
@@ -322,8 +427,9 @@ public:
                                 GraphParameters(graphs[i], input_edges[i],
                                                 output_edges[i]));
             _coordinators.push_back(coordinator);
-            HierarchicalGraphManager < SchedulerHandle,
-                                       GraphBuilder >::add_child(coordinator);
+            HeapHierarchicalGraphManager < SchedulerHandle,
+                                           GraphBuilder >::add_child(
+                                               coordinator);
 
         }
 
@@ -337,13 +443,13 @@ public:
             ss_out << "out_" << connection.first.second;
             ss_in << "in_" << connection.first.second;
 
-            if (not HierarchicalGraphManager <
+            if (not HeapHierarchicalGraphManager <
                     SchedulerHandle, GraphBuilder >::exist_link(
                         _coordinators[connection.first.first - 1],
                         ss_out.str(),
                         _coordinators[connection.second.first - 1],
                         ss_in.str())) {
-                HierarchicalGraphManager <
+                HeapHierarchicalGraphManager <
                     SchedulerHandle, GraphBuilder >::add_link(
                         _coordinators[connection.first.first - 1],
                         ss_out.str(),
@@ -353,7 +459,7 @@ public:
         }
     }
 
-    virtual ~HierarchicalGraphManager()
+    virtual ~HeapHierarchicalGraphManager()
     {
         for (typename Coordinators::const_iterator it = _coordinators.begin();
              it != _coordinators.end(); ++it) {
@@ -374,6 +480,243 @@ private:
     Coordinators _coordinators;
 };
 
+template < class SchedulerHandle, class GraphBuilder >
+class VectorHierarchicalGraphManager :
+        public paradevs::pdevs::GraphManager < common::DoubleTime,
+                                               SchedulerHandle,
+                                               PartitioningParameters >
+{
+public:
+    VectorHierarchicalGraphManager(
+        common::Coordinator < common::DoubleTime,
+                              SchedulerHandle >* coordinator,
+        const PartitioningParameters& parameters) :
+        paradevs::pdevs::GraphManager < common::DoubleTime, SchedulerHandle,
+                                        PartitioningParameters >(
+                                            coordinator, parameters)
+    {
+        GraphBuilder   graph_builder(parameters.cluster_number,
+                                     parameters.partitioning_method_name,
+                                     parameters.contraction_coef,
+                                     parameters.contraction_coef_flag);
+        OrientedGraphs graphs;
+        InputEdgeList  input_edges;
+        OutputEdgeList output_edges;
+        Connections    parent_connections;
+
+        graph_builder.build(graphs, input_edges, output_edges,
+                            parent_connections);
+
+        // build coordinators (graphs)
+        for (unsigned int i = 0; i < graphs.size(); ++i) {
+            Coordinator* coordinator = 0;
+            std::ostringstream ss;
+
+            ss << "S" << (i + 1);
+            coordinator =
+                new Coordinator(ss.str(), paradevs::common::NoParameters(),
+                                GraphParameters(graphs[i], input_edges[i],
+                                                output_edges[i]));
+            _coordinators.push_back(coordinator);
+            VectorHierarchicalGraphManager < SchedulerHandle,
+                                             GraphBuilder >::add_child(
+                                                 coordinator);
+
+        }
+
+        // builds internal connections (edges)
+        for (Connections::const_iterator it = parent_connections.begin();
+             it != parent_connections.end(); ++it) {
+            const Connection& connection = *it;
+            std::ostringstream ss_out;
+            std::ostringstream ss_in;
+
+            ss_out << "out_" << connection.first.second;
+            ss_in << "in_" << connection.first.second;
+
+            if (not VectorHierarchicalGraphManager <
+                    SchedulerHandle, GraphBuilder >::exist_link(
+                        _coordinators[connection.first.first - 1],
+                        ss_out.str(),
+                        _coordinators[connection.second.first - 1],
+                        ss_in.str())) {
+                VectorHierarchicalGraphManager <
+                    SchedulerHandle, GraphBuilder >::add_link(
+                        _coordinators[connection.first.first - 1],
+                        ss_out.str(),
+                        _coordinators[connection.second.first - 1],
+                        ss_in.str());
+            }
+        }
+    }
+
+    virtual ~VectorHierarchicalGraphManager()
+    {
+        for (typename Coordinators::const_iterator it = _coordinators.begin();
+             it != _coordinators.end(); ++it) {
+            delete *it;
+        }
+    }
+
+private:
+    typedef paradevs::pdevs::Coordinator <
+    common::DoubleTime,
+    paradevs::common::scheduler::VectorScheduler <
+        paradevs::common::DoubleTime >,
+    paradevs::common::scheduler::NoSchedulerHandle,
+    BuiltFlatGraphManager < paradevs::common::scheduler::NoSchedulerHandle >,
+    common::NoParameters,
+    GraphParameters > Coordinator;
+    typedef std::vector < Coordinator* > Coordinators;
+
+    Coordinators _coordinators;
+};
+
+template < class SchedulerHandle, class GraphBuilder >
+class ParallelHeapHierarchicalGraphManager :
+        public paradevs::pdevs::GraphManager < common::DoubleTime,
+                                               SchedulerHandle,
+                                               PartitioningParameters >
+{
+public:
+    ParallelHeapHierarchicalGraphManager(
+        common::Coordinator < common::DoubleTime,
+                              SchedulerHandle >* coordinator,
+        const PartitioningParameters& parameters) :
+        paradevs::pdevs::GraphManager < common::DoubleTime, SchedulerHandle,
+                                        PartitioningParameters >(
+                                            coordinator, parameters)
+    {
+        GraphBuilder   graph_builder(parameters.cluster_number,
+                                     parameters.partitioning_method_name,
+                                     parameters.contraction_coef,
+                                     parameters.contraction_coef_flag);
+        OrientedGraphs graphs;
+        InputEdgeList  input_edges;
+        OutputEdgeList output_edges;
+        Connections    parent_connections;
+
+        graph_builder.build(graphs, input_edges, output_edges,
+                            parent_connections);
+
+        // build coordinators (graphs)
+        for (unsigned int i = 0; i < graphs.size(); ++i) {
+            ParallelCoordinator* coordinator = 0;
+            std::ostringstream ss;
+
+            ss << "S" << (i + 1);
+            coordinator =
+                new ParallelCoordinator(ss.str(),
+                                        paradevs::common::NoParameters(),
+                                        GraphParameters(graphs[i],
+                                                        input_edges[i],
+                                                        output_edges[i]));
+            _coordinators.push_back(coordinator);
+            ParallelHeapHierarchicalGraphManager < SchedulerHandle,
+                                                   GraphBuilder >::add_child(
+                                                       coordinator);
+
+        }
+
+        // builds internal connections (edges)
+        for (Connections::const_iterator it = parent_connections.begin();
+             it != parent_connections.end(); ++it) {
+            const Connection& connection = *it;
+            std::ostringstream ss_out;
+            std::ostringstream ss_in;
+
+            ss_out << "out_" << connection.first.second;
+            ss_in << "in_" << connection.first.second;
+
+            if (not ParallelHeapHierarchicalGraphManager <
+                    SchedulerHandle, GraphBuilder >::exist_link(
+                        _coordinators[connection.first.first - 1],
+                        ss_out.str(),
+                        _coordinators[connection.second.first - 1],
+                        ss_in.str())) {
+                ParallelHeapHierarchicalGraphManager <
+                    SchedulerHandle, GraphBuilder >::add_link(
+                        _coordinators[connection.first.first - 1],
+                        ss_out.str(),
+                        _coordinators[connection.second.first - 1],
+                        ss_in.str());
+            }
+        }
+    }
+
+    virtual ~ParallelHeapHierarchicalGraphManager()
+    {
+        for (typename Coordinators::const_iterator it = _coordinators.begin();
+             it != _coordinators.end(); ++it) {
+            delete *it;
+        }
+    }
+
+    void init()
+    {
+        for (typename Coordinators::const_iterator it = _coordinators.begin();
+             it != _coordinators.end(); ++it) {
+            (*it)->set_sender(
+                dynamic_cast < paradevs::pdevs::multithreading::Coordinator <
+                    common::DoubleTime,
+                    SchedulerType,
+                    SchedulerHandle,
+                    ParallelHeapHierarchicalGraphManager <
+                        SchedulerHandle,
+                        PartitioningGraphBuilder >,
+                    paradevs::common::NoParameters,
+                    PartitioningParameters >*
+                >(ParallelHeapHierarchicalGraphManager < SchedulerHandle,
+                                                         GraphBuilder >::
+                  get_coordinator())->get_sender());
+        }
+    }
+
+    void start(common::DoubleTime::type t)
+    {
+        for (typename Coordinators::const_iterator it = _coordinators.begin();
+             it != _coordinators.end(); ++it) {
+            (*it)->get_sender().send(
+                paradevs::pdevs::multithreading::start_message <
+                    paradevs::common::DoubleTime >(t));
+        }
+    }
+
+    void transition(const common::Models < common::DoubleTime,
+                    SchedulerHandle >& receivers,
+                    paradevs::common::DoubleTime::type t)
+    {
+        typename Coordinators::const_iterator it = _coordinators.begin();
+        bool found = false;
+
+        while (not found) {
+            if (std::find(receivers.begin(), receivers.end(),
+                          *it) != receivers.end()) {
+                (*it)->get_sender().send(
+                    paradevs::pdevs::multithreading::transition_message <
+                        paradevs::common::DoubleTime >(t));
+                found = true;
+            } else {
+                ++it;
+            }
+        }
+    }
+
+private:
+    typedef paradevs::pdevs::multithreading::Coordinator <
+    common::DoubleTime,
+    SchedulerType,
+    SchedulerHandle,
+    ParallelBuiltFlatGraphManager
+    < SchedulerHandle >,
+    common::NoParameters,
+    GraphParameters > ParallelCoordinator;
+
+    typedef std::vector < ParallelCoordinator* > Coordinators;
+
+    Coordinators _coordinators;
+};
+
 } } } // namespace paradevs tests boost_graph
 
 #endif

+ 58 - 18
src/tests/boost_graph/graph_partitioning.hpp

@@ -31,12 +31,16 @@
 #include <tests/boost_graph/partitioning/graph_build.hpp>
 #include <tests/boost_graph/partitioning/gggp.hpp>
 
+#include <boost/graph/copy.hpp>
+
 namespace paradevs { namespace tests { namespace boost_graph {
 
 class PartitioningGraphBuilder
 {
 public:
-    PartitioningGraphBuilder()
+    PartitioningGraphBuilder(int cn, std::string pmn, int cc, bool ccf) :
+        cluster_number(cn), partitioning_method_name(pmn),
+        contraction_coef(cc), contraction_coef_flag(ccf)
     { }
 
     void build(OrientedGraphs& graphs,
@@ -48,30 +52,66 @@ public:
     	//srand(7266);
 
         UnorientedGraph* g = new UnorientedGraph();
-        OrientedGraph* go = new OrientedGraph();
-        UnorientedGraph* graph_origin = new UnorientedGraph();
-        OrientedGraph* gop = new OrientedGraph();
-
-        build_graph(*g, *go);
-        build_graph(*graph_origin, *gop);
-
-        delete gop;
+        OrientedGraph go;
+        UnorientedGraph graph_origin;
+
+        // internal examples
+        // {
+        //     build_graph(*g, go);
+        //     boost::copy_graph(*g, graph_origin);
+        // }
+
+        // corsen examples
+        {
+            build_corsen_graph(go);
+            make_unoriented_graph(go, *g);
+            boost::copy_graph(*g, graph_origin);
+        }
 
-        int nbr_parties = 12;
         Edges edge_partie;
         Connections connections;
 
-        output_edges = OutputEdgeList(nbr_parties);
+        output_edges = OutputEdgeList(cluster_number);
+
+        if (contraction_coef_flag) {
+            graphs = Multiniveau(num_vertices(*g) / contraction_coef,
+                                 g, &graph_origin, &go,
+                                 cluster_number, "HEM",
+                                 partitioning_method_name,
+                                 "cut_norm", "norm", edge_partie ,
+                                 output_edges, input_edges,
+                                 parent_connections);
+        } else {
+            graphs = Multiniveau(contraction_coef, g, &graph_origin, &go,
+                                 cluster_number, "HEM",
+                                 partitioning_method_name,
+                                 "cut_norm", "norm", edge_partie ,
+                                 output_edges, input_edges,
+                                 parent_connections);
+        }
+    }
+
+private:
+    int cluster_number;
+    std::string partitioning_method_name;
+    int contraction_coef;
+    bool contraction_coef_flag;
+};
 
-        graphs = Multiniveau(num_vertices(*g)/2, g, graph_origin, go, nbr_parties,"rand", "gggp_pond",
-                             "cut_norm", "norm", edge_partie ,
-                             output_edges, input_edges,
-                             parent_connections);
-        //std::cout<<"Sorti ! "<<std::endl;
+class CorsenFlatGraphBuilder
+{
+public:
+    CorsenFlatGraphBuilder()
+    { }
 
-        delete graph_origin;
-        delete go;
+    void build(OrientedGraphs& graphs, InputEdgeList& /* input_edges */,
+               OutputEdgeList& /* output_edges */,
+               Connections& /* parent_connections */)
+    {
+        OrientedGraph graph;
 
+        build_corsen_graph(graph);
+        graphs.push_back(graph);
     }
 };
 

+ 1 - 1
src/tests/boost_graph/partitioning/CMakeLists.txt

@@ -15,7 +15,7 @@ SET(PARTITIONING_CPP utils.cpp gggp.cpp graph_build.cpp)
 
 ADD_LIBRARY(partitioning SHARED ${PARTITIONING_HPP};${PARTITIONING_CPP})
 
-TARGET_LINK_LIBRARIES(partitioning
+TARGET_LINK_LIBRARIES(partitioning corsen
   ${Boost_LIBRARIES}
   ${GLIBMM_LIBRARIES}
   ${LIBXML_LIBRARIES}

+ 0 - 22
src/tests/boost_graph/partitioning/defs.hpp

@@ -27,32 +27,10 @@
 #ifndef TESTS_BOOST_GRAPH_PARTITIONING_DEFS_H
 #define TESTS_BOOST_GRAPH_PARTITIONING_DEFS_H 1
 
-// #include <stdlib.h>
-// #include <stdio.h>
-// #include <iostream>
-// #include <iomanip>
-// #include <fstream>
 #include <list>
 #include <vector>
-// #include <map>
-// #include <exception>
-// #include <ctime>       /* clock_t, clock, CLOCKS_PER_SEC */
-// #include <cmath>
-// #include <algorithm>
 
-// #include <boost/graph/topological_sort.hpp>
 #include <boost/graph/adjacency_list.hpp>
-// #include <boost/graph/adjacency_matrix.hpp>
-// #include <boost/graph/graph_utility.hpp>
-// #include <boost/version.hpp>
-// #include <boost/graph/graph_traits.hpp>
-// #include <boost/graph/graph_concepts.hpp>
-// #include <boost/concept/assert.hpp>
-// #include <boost/graph/adjacency_iterator.hpp>
-// #include <boost/limits.hpp>
-// #include <boost/graph/breadth_first_search.hpp>
-// #include <boost/graph/graphviz.hpp>
-// #include <boost/graph/undirected_graph.hpp>
 
 #include <tests/boost_graph/graph_defs.hpp>
 

+ 456 - 162
src/tests/boost_graph/partitioning/gggp.cpp

@@ -37,6 +37,214 @@ extern UnorientedGraph::adjacency_iterator neighbourIt, neighbourEnd;
 extern OrientedGraph::vertex_iterator vertexIto, vertexEndo;
 extern OrientedGraph::adjacency_iterator neighbourIto, neighbourEndo;
 
+void ggp(UnorientedGraph *g, Entiers *sommetsSource,
+               Entiers *sommetsDestination, EntiersEntiers &Partition)
+{
+    //std::cout<<""<<std::endl;
+    int val;
+    Entiers sommets_adj;
+    if(sommetsSource->size()==1){
+        val=0;
+        //std::cout<<"Entré dans le debug ! "<<std::endl;
+        Entiers tailles;
+        for(uint i=0;i<Partition.size();i++){
+            tailles.push_back(Partition.at(i)->size());
+        }
+        uint tmp=*max_element(tailles.begin(),tailles.end());
+        for(uint i=0; i<Partition.size();i++){
+            if(Partition.at(i)->size()==tmp)
+            {
+                ggp(g,Partition[i],sommetsDestination,Partition);
+                return;
+            }
+        }
+    }
+    else
+        val=rand_fini(0,sommetsSource->size()-1);//Tirage aléatoire de l'indice du premier sommet entre 0 et taille du tableau -1
+        //std::cout<<"val : "<<sommetsSource->at(val)<<std::endl;
+    double poids_max=0;
+    for(uint i=0;i<sommetsSource->size();i++){
+        poids_max+=(*g)[sommetsSource->at(i)]._weight;
+    }
+    poids_max/=2.;
+
+    double poids=(*g)[sommetsSource->at(val)]._weight;
+    sommetsDestination->push_back(sommetsSource->at(val));
+    sommetsSource->erase(sommetsSource->begin() + val);
+    int cpt = 0;
+
+   // std::cout<<"taille sommetsSource avant le while : "<<sommetsSource->size()<<std::endl;
+    while(poids<poids_max && sommetsSource->size()>1)
+    {
+        //std::cout<<"taille sommetsSource dans le while "<<sommetsSource->size()<<std::endl;
+        if(cpt<sommetsDestination->size() )
+            adjacence_ggp(sommetsDestination->at(cpt),sommets_adj,g);
+        else{
+            val=rand_fini(0,sommetsSource->size()-1);
+            sommetsDestination->push_back(sommetsSource->at(val));
+            sommetsSource->erase(sommetsSource->begin() + val);
+            adjacence_ggp(sommetsDestination->at(cpt),sommets_adj,g);
+        }
+        /*std::cout<<"adj :"<<std::endl;
+        for(uint a = 0; a<sommets_adj.size(); a++){
+            std::cout<<sommets_adj.at(a)<<std::endl;
+        }*/
+        if(sommets_adj.size()==0)
+        {
+            //std::cout<<"Je suis sorti car pas de voisin !!!! "<<std::endl;
+            for (uint i=0; i<sommetsSource->size();i++)
+            {
+                for (uint j=0; j<sommetsDestination->size();j++)
+                {
+                    remove_edge(sommetsSource->at(i),sommetsDestination->at(j),*g);
+                }
+            }
+            sort(sommetsDestination->begin(), sommetsDestination->end());
+            return;
+        }
+        else{
+            for(uint i =0; i<sommets_adj.size(); i++){
+                if(In_tab(*sommetsDestination,sommets_adj.at(i))!=1 && sommetsSource->size()!=1){
+                    sommetsDestination->push_back(sommets_adj.at(i));
+                    poids+=(*g)[sommets_adj.at(i)]._weight;
+                    suprim_val(*sommetsSource, sommets_adj[i]);
+                }
+                if(poids>poids_max || sommetsSource->size()==1)
+                    break;
+            }
+
+            /*std::cout<<"Sommets_source :"<<std::endl;
+            for(uint i =0; i<sommetsSource->size();i++){
+                std::cout<<sommetsSource->at(i)<<",";
+            }
+            std::cout<<std::endl;
+            std::cout<<"Sommets_destination :"<<std::endl;
+            for(uint i =0; i<sommetsDestination->size();i++){
+                std::cout<<sommetsDestination->at(i)<<",";
+            }
+            std::cout<<std::endl;*/
+
+            if(poids>poids_max  || sommetsSource->size()==1){
+                for (uint i=0; i<sommetsSource->size();i++)
+                {
+                    for (uint j=0; j<sommetsDestination->size();j++)
+                    {
+                        remove_edge(sommetsSource->at(i),sommetsDestination->at(j),*g);
+                    }
+                }
+                sort(sommetsDestination->begin(), sommetsDestination->end());
+                return;
+            }
+
+            sommets_adj.clear();
+            cpt++;
+        }
+
+    }
+
+    for (uint i=0; i<sommetsSource->size();i++)
+    {
+        for (uint j=0; j<sommetsDestination->size();j++)
+        {
+            remove_edge(sommetsSource->at(i),sommetsDestination->at(j),*g);
+        }
+    }
+    sort(sommetsDestination->begin(), sommetsDestination->end());
+}
+
+void Iter_2l(EntiersEntiers &part, int nbr_parties, UnorientedGraph *g,
+             const std::string &nom)
+{
+    if (nom =="gggp"){
+
+        for(int i = 0; i<floor(log(nbr_parties)/log(2)); i++)
+        {
+            for(int j = 0; j< pow(2,i);j++)
+            {
+                Entiers *Q = new Entiers();
+                gggp(g,part[j],Q,part);
+                part.push_back(Q);
+            }
+        }
+    }
+
+    else if (nom =="ggp"){
+ for(int i = 0; i<floor(log(nbr_parties)/log(2)); i++)
+        {
+            //std::cout<<"Et un tours de plus !!!! "<<std::endl;
+            for(int j = 0; j< pow(2,i);j++)
+            {
+                Entiers *Q = new Entiers();
+                ggp(g,part[j],Q,part);
+                part.push_back(Q);
+            }
+
+        }
+    }
+
+    else {
+        //std::cout<<"je jsuis dans gggp_pond"<<std::endl;
+
+        for(int i = 0; i<floor(log(nbr_parties)/log(2)); i++)
+        {
+            //std::cout<<"Et un tours de plus !!!! "<<std::endl;
+            for(int j = 0; j< pow(2,i);j++)
+            {
+                Entiers *Q = new Entiers();
+                gggp_pond(g,part.at(j),Q,part);
+                //std::clog<<"sortie du gggp_pond"<<std::endl;
+                part.push_back(Q);
+            }
+            //std::cout<<"\n"<<std::endl;
+
+        }
+    }
+}
+
+void bissectionRec(UnorientedGraph *g, EntiersEntiers &Partition,
+                   int nbr_parties, const std::string &nom)
+{
+    if((nbr_parties&(nbr_parties-1))==0)
+    {
+        //std::cout<<"C'est de la forme 2l : "<<nbr_parties<<std::endl;
+        Iter_2l(Partition,nbr_parties,g,nom);
+    }
+    else
+    {
+        int puissance_2=0;
+
+        Entiers tailles;
+
+        while(pow(2,puissance_2)<nbr_parties)
+            puissance_2++;
+
+        Iter_2l(Partition,pow(2,puissance_2-1),g,nom);
+
+        for(unsigned int i = 0; i< Partition.size() -1 ; i++)
+        {
+            for(EntiersEntiers::iterator it1 = Partition.begin() + i ; it1!=Partition.end(); it1++)
+            {
+                if((*it1)->size() > Partition.at(i)->size())
+                    Partition.at(i)->swap(**it1);
+            }
+        }
+
+        for(int j = 0; j<nbr_parties-pow(2,puissance_2-1);j++)
+        {
+            Entiers *Q = new Entiers();
+            if(nom=="gggp")
+                gggp(g,Partition.at(j),Q,Partition);
+            else if (nom == "ggp")
+                ggp(g,Partition.at(j),Q,Partition);
+            else
+                gggp_pond(g,Partition.at(j),Q,Partition);
+            Partition.push_back(Q);
+        }
+    }
+}
+
+
+
 void gggp(UnorientedGraph *g, Entiers *sommetsSource,
           Entiers *sommetsDestination, EntiersEntiers &Partition)
 {
@@ -132,7 +340,6 @@ void gggp_pond(UnorientedGraph *g, Entiers *sommetsSource,
     Entiers sommets_adj;
     if(sommetsSource->size()==1){
         val=0;
-        //std::cout<<"Entré dans le debug ! "<<std::endl;
         Entiers tailles;
         for(uint i=0;i<Partition.size();i++){
             tailles.push_back(Partition.at(i)->size());
@@ -142,13 +349,12 @@ void gggp_pond(UnorientedGraph *g, Entiers *sommetsSource,
             if(Partition.at(i)->size()==tmp)
             {
                 gggp_pond(g,Partition[i],sommetsDestination,Partition);
-            	return;
+                return;
             }
         }
     }
     else
-        val=rand_fini(0,sommetsSource->size()-1);//Tirage aléatoire de l'indice du premier sommet entre 0 et taille du tableau -1
-    	//std::cout<<"val : "<<sommetsSource->at(val)<<std::endl;
+        val=rand_fini(0,sommetsSource->size()-1);
     double poids_max=0;
     for(uint i=0;i<sommetsSource->size();i++){
         poids_max+=(*g)[sommetsSource->at(i)]._weight;
@@ -156,18 +362,15 @@ void gggp_pond(UnorientedGraph *g, Entiers *sommetsSource,
     poids_max/=2.;
     double poids=(*g)[sommetsSource->at(val)]._weight;
     std::vector<float> sommets_cut;
-
+    float cut = Degree(*g,sommetsSource->at(val));
     sommetsDestination->push_back(sommetsSource->at(val));
     sommetsSource->erase(sommetsSource->begin() + val);
 
-   // std::cout<<"taille sommetsSource avant le while : "<<sommetsSource->size()<<std::endl;
     while(poids<poids_max && sommetsSource->size()>1)
     {
-    	//std::cout<<"taille sommetsSource dans le while "<<sommetsSource->size()<<std::endl;
         Liste_Voisin(*sommetsDestination,sommets_adj,*g);
         if(sommets_adj.size()==0)
         {
-            //std::cout<<"Je suis sorti car pas de voisin !!!! "<<std::endl;
             for (uint i=0; i<sommetsSource->size();i++)
             {
                 for (uint j=0; j<sommetsDestination->size();j++)
@@ -181,23 +384,13 @@ void gggp_pond(UnorientedGraph *g, Entiers *sommetsSource,
         else{
             sort(sommets_adj.begin(), sommets_adj.end());
 
-            /*std::cout<<"adj :"<<std::endl;
-            for(uint a = 0; a<sommets_adj.size(); a++){
-            	std::cout<<sommets_adj.at(a)<<std::endl;
-            }
-            std::cout<<std::endl;*/
-
             for(uint i=0;i<sommets_adj.size();i++)
             {
-                sommets_cut.push_back(Cout_coupe_pond(*sommetsDestination,sommets_adj[i],*g));
-            }
-            /*std::cout<<"cut :"<<std::endl;
-            for(uint a = 0; a<sommets_cut.size(); a++){
-            	std::cout<<sommets_cut.at(a)<<std::endl;
+                sommets_cut.push_back(modif_Cout_coupe(*sommetsDestination,sommets_adj.at(i),cut,g));
             }
-            std::cout<<std::endl;*/
+
+            cut = *min_element(sommets_cut.begin(),sommets_cut.end());
             sommetsDestination->push_back(sommets_adj[recherche_val2(sommets_cut,*min_element(sommets_cut.begin(),sommets_cut.end()))]);
-            //std::cout<<"Sommet deplacé : "<<sommets_adj[recherche_val2(sommets_cut,*min_element(sommets_cut.begin(),sommets_cut.end()))]<<std::endl;
             poids+=(*g)[sommets_adj[recherche_val2(sommets_cut,*min_element(sommets_cut.begin(),sommets_cut.end()))]]._weight;
             suprim_val(*sommetsSource, sommets_adj[recherche_val2(sommets_cut,*min_element(sommets_cut.begin(),sommets_cut.end()))]);
             suprim_val(sommets_adj, sommets_adj[recherche_val2(sommets_cut,*min_element(sommets_cut.begin(),sommets_cut.end()))]);
@@ -205,16 +398,6 @@ void gggp_pond(UnorientedGraph *g, Entiers *sommetsSource,
             sommets_cut.clear();
 
         }
-
-        /*for(uint i =0; i<sommetsSource->size();i++){
-        	std::cout<<sommetsSource->at(i)<<",";
-        }
-        std::cout<<std::endl;
-        for(uint i =0; i<sommetsDestination->size();i++){
-        	std::cout<<sommetsDestination->at(i)<<",";
-        }
-        std::cout<<std::endl;*/
-
     }
 
     for (uint i=0; i<sommetsSource->size();i++)
@@ -226,91 +409,196 @@ void gggp_pond(UnorientedGraph *g, Entiers *sommetsSource,
     }
     sort(sommetsDestination->begin(), sommetsDestination->end());
 
-    //std::cout<<"fin du gggp_pond"<<std::endl;
-}
-
-void Iter_2l(EntiersEntiers &part, int nbr_parties, UnorientedGraph *g,
-             const std::string &nom)
-{
-    if (nom!="gggp_pond"){
-        //std::cout<<"je jsuis dans gggp"<<std::endl;
-
-        for(int i = 0; i<floor(log(nbr_parties)/log(2)); i++)
-        {
-            //std::cout<<"Et un tours de plus !!!! "<<std::endl;
-            for(int j = 0; j< pow(2,i);j++)
-            {
-                Entiers *Q = new Entiers();
-                gggp(g,part[j],Q,part);
-                part.push_back(Q);
-            }
-
-        }
-    } else {
-        //std::cout<<"je jsuis dans gggp_pond"<<std::endl;
-
-        for(int i = 0; i<floor(log(nbr_parties)/log(2)); i++)
-        {
-            //std::cout<<"Et un tours de plus !!!! "<<std::endl;
-            for(int j = 0; j< pow(2,i);j++)
-            {
-                Entiers *Q = new Entiers();
-                gggp_pond(g,part.at(j),Q,part);
-                //std::clog<<"sortie du gggp_pond"<<std::endl;
-                part.push_back(Q);
-            }
-            //std::cout<<"\n"<<std::endl;
-
-        }
-    }
 }
 
-void bissectionRec(UnorientedGraph *g, EntiersEntiers &Partition,
-                   int nbr_parties, const std::string &nom)
-{
-    if((nbr_parties&(nbr_parties-1))==0)
-    {
-        //std::cout<<"C'est de la forme 2l : "<<nbr_parties<<std::endl;
-        Iter_2l(Partition,nbr_parties,g,nom);
-    }
-    else
-    {
-        int puissance_2=0;
-
-        Entiers tailles;
-
-        while(pow(2,puissance_2)<nbr_parties)
-            puissance_2++;
-
-        Iter_2l(Partition,pow(2,puissance_2-1),g,nom);
-
-        for(unsigned int i = 0; i< Partition.size() -1 ; i++)
-        {
-            for(EntiersEntiers::iterator it1 = Partition.begin() + i ; it1!=Partition.end(); it1++)
-            {
-                if((*it1)->size() > Partition.at(i)->size())
-                    Partition.at(i)->swap(**it1);
-            }
-        }
-
-        for(int j = 0; j<nbr_parties-pow(2,puissance_2-1);j++)
-        {
-            Entiers *Q = new Entiers();
-            if(nom!="gggp_pond")
-                gggp(g,Partition.at(j),Q,Partition);
-            else
-                gggp_pond(g,Partition.at(j),Q,Partition);
-            Partition.push_back(Q);
-        }
-    }
-    std::cout<<"Partition avant affinage "<<std::endl;
-    for(uint i = 0 ; i<Partition.size(); i++){
-    	for(uint j = 0 ; j<Partition.at(i)->size(); j++){
-    		std::cout<<Partition.at(i)->at(j)<<" ";
-    	}
-    	std::cout<<"\n"<<std::endl;
-    }
-}
+// void gggp_pond(UnorientedGraph *g, Entiers *sommetsSource,
+//                Entiers *sommetsDestination, EntiersEntiers &Partition)
+// {
+//     int val;
+//     Entiers sommets_adj;
+//     if(sommetsSource->size()==1){
+//         val=0;
+//         //std::cout<<"Entré dans le debug ! "<<std::endl;
+//         Entiers tailles;
+//         for(uint i=0;i<Partition.size();i++){
+//             tailles.push_back(Partition.at(i)->size());
+//         }
+//         uint tmp=*max_element(tailles.begin(),tailles.end());
+//         for(uint i=0; i<Partition.size();i++){
+//             if(Partition.at(i)->size()==tmp)
+//             {
+//                 gggp_pond(g,Partition[i],sommetsDestination,Partition);
+//             	return;
+//             }
+//         }
+//     }
+//     else
+//         val=rand_fini(0,sommetsSource->size()-1);//Tirage aléatoire de l'indice du premier sommet entre 0 et taille du tableau -1
+//     	//std::cout<<"val : "<<sommetsSource->at(val)<<std::endl;
+//     double poids_max=0;
+//     for(uint i=0;i<sommetsSource->size();i++){
+//         poids_max+=(*g)[sommetsSource->at(i)]._weight;
+//     }
+//     poids_max/=2.;
+//     double poids=(*g)[sommetsSource->at(val)]._weight;
+//     std::vector<float> sommets_cut;
+//     float  cut = Degree(*g,sommetsSource->at(val));
+
+//     sommetsDestination->push_back(sommetsSource->at(val));
+//     sommetsSource->erase(sommetsSource->begin() + val);
+
+//    // std::cout<<"taille sommetsSource avant le while : "<<sommetsSource->size()<<std::endl;
+//     while(poids<poids_max && sommetsSource->size()>1)
+//     {
+//     	//std::cout<<"taille sommetsSource dans le while "<<sommetsSource->size()<<std::endl;
+//         Liste_Voisin(*sommetsDestination,sommets_adj,*g);
+//         if(sommets_adj.size()==0)
+//         {
+//             //std::cout<<"Je suis sorti car pas de voisin !!!! "<<std::endl;
+//             for (uint i=0; i<sommetsSource->size();i++)
+//             {
+//                 for (uint j=0; j<sommetsDestination->size();j++)
+//                 {
+//                     remove_edge(sommetsSource->at(i),sommetsDestination->at(j),*g);
+//                 }
+//             }
+//             sort(sommetsDestination->begin(), sommetsDestination->end());
+//             return;
+//         }
+//         else{
+//             sort(sommets_adj.begin(), sommets_adj.end());
+
+//             /*std::cout<<"adj :"<<std::endl;
+//             for(uint a = 0; a<sommets_adj.size(); a++){
+//             	std::cout<<sommets_adj.at(a)<<std::endl;
+//             }
+//             std::cout<<std::endl;*/
+
+//             for(uint i=0;i<sommets_adj.size();i++)
+//             {
+//                 sommets_cut.push_back(modif_Cout_coupe(*sommetsDestination, sommets_adj.at(i), cut, g));
+//                 // sommets_cut.push_back(Cout_coupe_pond(*sommetsDestination,sommets_adj[i],*g));
+//             }
+//             /*std::cout<<"cut :"<<std::endl;
+//             for(uint a = 0; a<sommets_cut.size(); a++){
+//             	std::cout<<sommets_cut.at(a)<<std::endl;
+//             }
+//             std::cout<<std::endl;*/
+//             sommetsDestination->push_back(sommets_adj[recherche_val2(sommets_cut,*min_element(sommets_cut.begin(),sommets_cut.end()))]);
+//             //std::cout<<"Sommet deplacé : "<<sommets_adj[recherche_val2(sommets_cut,*min_element(sommets_cut.begin(),sommets_cut.end()))]<<std::endl;
+//             poids+=(*g)[sommets_adj[recherche_val2(sommets_cut,*min_element(sommets_cut.begin(),sommets_cut.end()))]]._weight;
+//             suprim_val(*sommetsSource, sommets_adj[recherche_val2(sommets_cut,*min_element(sommets_cut.begin(),sommets_cut.end()))]);
+//             suprim_val(sommets_adj, sommets_adj[recherche_val2(sommets_cut,*min_element(sommets_cut.begin(),sommets_cut.end()))]);
+
+//             sommets_cut.clear();
+
+//         }
+
+//         /*for(uint i =0; i<sommetsSource->size();i++){
+//         	std::cout<<sommetsSource->at(i)<<",";
+//         }
+//         std::cout<<std::endl;
+//         for(uint i =0; i<sommetsDestination->size();i++){
+//         	std::cout<<sommetsDestination->at(i)<<",";
+//         }
+//         std::cout<<std::endl;*/
+
+//     }
+
+//     for (uint i=0; i<sommetsSource->size();i++)
+//     {
+//         for (uint j=0; j<sommetsDestination->size();j++)
+//         {
+//             remove_edge(sommetsSource->at(i),sommetsDestination->at(j),*g);
+//         }
+//     }
+//     sort(sommetsDestination->begin(), sommetsDestination->end());
+
+//     //std::cout<<"fin du gggp_pond"<<std::endl;
+// }
+
+// void Iter_2l(EntiersEntiers &part, int nbr_parties, UnorientedGraph *g,
+//              const std::string &nom)
+// {
+//     if (nom!="gggp_pond"){
+//         //std::cout<<"je jsuis dans gggp"<<std::endl;
+
+//         for(int i = 0; i<floor(log(nbr_parties)/log(2)); i++)
+//         {
+//             //std::cout<<"Et un tours de plus !!!! "<<std::endl;
+//             for(int j = 0; j< pow(2,i);j++)
+//             {
+//                 Entiers *Q = new Entiers();
+//                 gggp(g,part[j],Q,part);
+//                 part.push_back(Q);
+//             }
+
+//         }
+//     } else {
+//         //std::cout<<"je jsuis dans gggp_pond"<<std::endl;
+
+//         for(int i = 0; i<floor(log(nbr_parties)/log(2)); i++)
+//         {
+//             //std::cout<<"Et un tours de plus !!!! "<<std::endl;
+//             for(int j = 0; j< pow(2,i);j++)
+//             {
+//                 Entiers *Q = new Entiers();
+//                 gggp_pond(g,part.at(j),Q,part);
+//                 //std::clog<<"sortie du gggp_pond"<<std::endl;
+//                 part.push_back(Q);
+//             }
+//             //std::cout<<"\n"<<std::endl;
+
+//         }
+//     }
+// }
+
+// void bissectionRec(UnorientedGraph *g, EntiersEntiers &Partition,
+//                    int nbr_parties, const std::string &nom)
+// {
+//     if((nbr_parties&(nbr_parties-1))==0)
+//     {
+//         //std::cout<<"C'est de la forme 2l : "<<nbr_parties<<std::endl;
+//         Iter_2l(Partition,nbr_parties,g,nom);
+//     }
+//     else
+//     {
+//         int puissance_2=0;
+
+//         Entiers tailles;
+
+//         while(pow(2,puissance_2)<nbr_parties)
+//             puissance_2++;
+
+//         Iter_2l(Partition,pow(2,puissance_2-1),g,nom);
+
+//         for(unsigned int i = 0; i< Partition.size() -1 ; i++)
+//         {
+//             for(EntiersEntiers::iterator it1 = Partition.begin() + i ; it1!=Partition.end(); it1++)
+//             {
+//                 if((*it1)->size() > Partition.at(i)->size())
+//                     Partition.at(i)->swap(**it1);
+//             }
+//         }
+
+//         for(int j = 0; j<nbr_parties-pow(2,puissance_2-1);j++)
+//         {
+//             Entiers *Q = new Entiers();
+//             if(nom!="gggp_pond")
+//                 gggp(g,Partition.at(j),Q,Partition);
+//             else
+//                 gggp_pond(g,Partition.at(j),Q,Partition);
+//             Partition.push_back(Q);
+//         }
+//     }
+//     // std::cout<<"Partition avant affinage "<<std::endl;
+//     // for(uint i = 0 ; i<Partition.size(); i++){
+//     // 	for(uint j = 0 ; j<Partition.at(i)->size(); j++){
+//     // 		std::cout<<Partition.at(i)->at(j)<<" ";
+//     // 	}
+//     // 	std::cout<<"\n"<<std::endl;
+//     // }
+// }
 
 /**
  * Fonction réalisant un partitionnement pseudo aléatoire suivant un voisinage.
@@ -382,7 +670,7 @@ void Pseudo_random_partitioning(UnorientedGraph *g, EntiersEntiers &Partition,
             tie(neighbourIt, neighbourEnd) = adjacent_vertices(part->at(j),*g);
             for (; neighbourIt != neighbourEnd; ++neighbourIt){
                 if(In_tab(*Partition.at(0),*neighbourIt)==1){
-                    std::cout<<"le voisin déplacé est : "<<*neighbourIt<<std::endl;
+                    // std::cout<<"le voisin déplacé est : "<<*neighbourIt<<std::endl;
                     part->push_back(*neighbourIt);
                     cpt_sommets++;
                     suprim_val(*Partition.at(0),*neighbourIt);
@@ -473,6 +761,10 @@ OrientedGraphs Multiniveau(uint niveau_contraction,
     int val_cpt = num_vertices(*g);
     bool stop = false;
 
+    if (niveau_contraction == val_cpt) {
+        stop = true;
+    }
+
     while(stop != true)
     {
     	if(contraction == "HEM")
@@ -480,28 +772,28 @@ OrientedGraphs Multiniveau(uint niveau_contraction,
     	else
     		stop = contraction_Random_Maching(baseg.at(cpt),baseg,liste_corr,niveau_contraction,val_cpt);
         cpt++;
-        std::cout<<"passage"<<std::endl;
+        // std::cout<<"passage"<<std::endl;
     }
 
-    std::cout<<"Graphe contracté : "<<std::endl;
-    for (uint i = 0; i< baseg.size(); i++) {
-        tie(vertexIt, vertexEnd) = vertices(*baseg[i]);
-        for (; vertexIt != vertexEnd; ++vertexIt) {
-            std::cout << (*baseg[i])[*vertexIt]._index
-                      << " est connecté avec ";
-            tie(neighbourIt, neighbourEnd) = adjacent_vertices(*vertexIt,
-            		*baseg[i]);
-            for (; neighbourIt != neighbourEnd; ++neighbourIt)
-                std::cout << (*baseg[i])[*neighbourIt]._index << " ";
-            std::cout << " et son poids est de "
-                      << (*baseg[i])[*vertexIt]._weight<<std::endl;
-        }
-        std::cout << std::endl;
-    }
+    // std::cout<<"Graphe contracté : "<<std::endl;
+    // for (uint i = 0; i< baseg.size(); i++) {
+    //     tie(vertexIt, vertexEnd) = vertices(*baseg[i]);
+    //     for (; vertexIt != vertexEnd; ++vertexIt) {
+    //         std::cout << (*baseg[i])[*vertexIt]._index
+    //                   << " est connecté avec ";
+    //         tie(neighbourIt, neighbourEnd) = adjacent_vertices(*vertexIt,
+    //         		*baseg[i]);
+    //         for (; neighbourIt != neighbourEnd; ++neighbourIt)
+    //             std::cout << (*baseg[i])[*neighbourIt]._index << " ";
+    //         std::cout << " et son poids est de "
+    //                   << (*baseg[i])[*vertexIt]._weight<<std::endl;
+    //     }
+    //     std::cout << std::endl;
+    // }
     UnorientedGraph *gtmp = new UnorientedGraph();
     *gtmp = *baseg.at(baseg.size() - 1);
-    std::cout<<"Partitionnement "<<std::endl;
-    if(type_methode == "gggp_pond" || type_methode == "gggp"){
+    // std::cout<<"Partitionnement "<<std::endl;
+    if(type_methode == "gggp_pond" || type_methode == "gggp" || type_methode == "ggp"){
 		for(uint i = 0;i < num_vertices(*baseg.at(baseg.size() - 1)); i++)
 		{
 			part->push_back(i);
@@ -509,7 +801,8 @@ OrientedGraphs Multiniveau(uint niveau_contraction,
 		Partition.push_back(part);
 		bissectionRec(baseg.at(baseg.size()-1),Partition,nbr_parties,type_methode);
 		double cut_norm = Cut_cluster(Partition,*gtmp,"norm");
-		std::cout<<"Cout de coupe normalisé initial : "<<cut_norm<<std::endl;
+		// std::cout<<"Cout de coupe normalisé initial : "<<cut_norm<<std::
+                    // endl;
 		int cpt_part = 0;
 		while (cpt_part!=3){
 			EntiersEntiers new_Partition;
@@ -521,10 +814,10 @@ OrientedGraphs Multiniveau(uint niveau_contraction,
 			new_Partition.push_back(new_part);
 			bissectionRec(baseg.at(baseg.size()-1),new_Partition,nbr_parties,type_methode);
 			double new_cut_norm = Cut_cluster(new_Partition,*gtmp,"norm");
-			std::cout<<"Nouveau cout de coupe normalisé : "<<new_cut_norm<<std::endl;
+			// std::cout<<"Nouveau cout de coupe normalisé : "<<new_cut_norm<<std::endl;
 
 			if(new_cut_norm<cut_norm){
-				std::cout<<"Changement !!!"<<std::endl;
+				// std::cout<<"Changement !!!"<<std::endl;
 				for(EntiersEntiers::iterator it = Partition.begin(); it != Partition.end(); it++)
 				{
 					delete *it;
@@ -542,13 +835,13 @@ OrientedGraphs Multiniveau(uint niveau_contraction,
 			}
 			cpt_part++;
 		}
-		std::cout<<std::endl;
-		std::cout<<"Cout de coupe normalisé conservé : "<<cut_norm<<std::endl;
+		// std::cout<<std::endl;
+		// std::cout<<"Cout de coupe normalisé conservé : "<<cut_norm<<std::endl;
 		delete gtmp;
     }
     else
     	Partition = Random_partitioning(baseg.at(baseg.size()-1),nbr_parties);
-    std::cout<<std::endl;
+    // std::cout<<std::endl;
 
     ListEntiersEntiers::iterator lit(liste_corr.end());
     bool proj;
@@ -564,13 +857,13 @@ OrientedGraphs Multiniveau(uint niveau_contraction,
 
     for(uint y =0; y<taille_list;y++){
     	if(proj != true){
-    		std::cout<<"Projection "<<std::endl;
+    		// std::cout<<"Projection "<<std::endl;
     		projection(Partition,lit);
-    		std::cout<<std::endl;
+    		// std::cout<<std::endl;
     		double cut = Cut_cluster(Partition,*baseg.at(baseg.size()-2-y),type_cut);
-    		std::cout<<"Cout de coupe avant affinage : "<<cut<<std::endl;
-    		std::cout<<std::endl;
-    		std::cout<<"Affinage "<<std::endl;
+    		// std::cout<<"Cout de coupe avant affinage : "<<cut<<std::endl;
+    		// std::cout<<std::endl;
+    		// std::cout<<"Affinage "<<std::endl;
     		if(choix_affinage=="charge")
     			Affinage_equilibrage_charge(baseg.at(baseg.size()-2-y),Partition);
     		else
@@ -579,22 +872,23 @@ OrientedGraphs Multiniveau(uint niveau_contraction,
     		lit--;
     	}
     	else{
-    		std::cout<<"Pas de projection "<<std::endl;
-    		std::cout<<std::endl;
+    		// std::cout<<"Pas de projection "<<std::endl;
+    		// std::cout<<std::endl;
 
     		if(nbr_parties != num_vertices(*g)){
-    			std::cout<<"Affinage "<<std::endl;
+    			// std::cout<<"Affinage "<<std::endl;
         		double cut = Cut_cluster(Partition,*graph_origin,type_cut);
-        		std::cout<<"Cout de coupe avant affinage : "<<cut<<std::endl;
+        		// std::cout<<"Cout de coupe avant affinage : "<<cut<<std::
+                            // endl;
     			if(choix_affinage=="charge")
     				Affinage_equilibrage_charge(graph_origin,Partition);
     			else{
     				Affinage_recherche_locale(graph_origin,Partition,cut,type_cut);
-    				std::cout<<"Cout de coupe après affinage : "<<cut<<std::endl;
+    				// std::cout<<"Cout de coupe après affinage : "<<cut<<std::endl;
     			}
     		}
-    		else
-    			std::cout<<"Pas d'affinage "<<std::endl;
+    		// else
+    			// std::cout<<"Pas d'affinage "<<std::endl;
     	}
 
     }
@@ -602,19 +896,19 @@ OrientedGraphs Multiniveau(uint niveau_contraction,
     OrientedGraphs Graphes = Graph_Partition(Partition, go, g, outputedgeslist,
                                              inputedgelist, connections);
 
-    std::cout<<std::endl;
-    std::cout<<"Résultat de la partition "<<std::endl;
-    for(uint k=0; k<Partition.size(); k++)
-    {
-    	for(uint j=0; j<Partition.at(k)->size(); j++)
-    	{
-    		std::cout<<Partition.at(k)->at(j)<<" ";
-    	}
-    	std::cout<<"\n"<<std::endl;
-    }
+    // std::cout<<std::endl;
+    // std::cout<<"Résultat de la partition "<<std::endl;
+    // for(uint k=0; k<Partition.size(); k++)
+    // {
+    // 	for(uint j=0; j<Partition.at(k)->size(); j++)
+    // 	{
+    // 		std::cout<<Partition.at(k)->at(j)<<" ";
+    // 	}
+    // 	std::cout<<"\n"<<std::endl;
+    // }
 
 	double cut = Cut_cluster(Partition,*graph_origin,"cut");
-	std::cout<<"Cout de coupe engendré par le partitionnement: "<<cut<<std::endl;
+	// std::cout<<"Cout de coupe engendré par le partitionnement: "<<cut<<std::endl;
 
 
     for(EntiersEntiers::iterator it = Partition.begin(); it != Partition.end(); it++)

+ 3 - 0
src/tests/boost_graph/partitioning/gggp.hpp

@@ -31,6 +31,9 @@
 
 namespace paradevs { namespace tests { namespace boost_graph {
 
+void ggp(UnorientedGraph *g, Entiers *sommetsSource,
+         Entiers *sommetsDestination, EntiersEntiers &Partition);
+
 void gggp(UnorientedGraph *g, Entiers *sommetsSource,
           Entiers *sommetsDestination, EntiersEntiers &Partition);
 

+ 77 - 0
src/tests/boost_graph/partitioning/graph_build.cpp

@@ -26,6 +26,8 @@
 
 #include <tests/boost_graph/partitioning/graph_build.hpp>
 
+#include <tests/corsen/lib/Corsen.hpp>
+
 namespace paradevs { namespace tests { namespace boost_graph {
 
 void build_graph(UnorientedGraph& ug, OrientedGraph& og)
@@ -354,4 +356,79 @@ void build_graph(UnorientedGraph& ug, OrientedGraph& og)
 
 }
 
+void modify_file_paths(std::string& absolutePath,
+                       std::vector < std::string* >& files)
+{
+    for (std::vector < std::string* >::iterator it = files.begin();
+         it != files.end(); it++) {
+        (*it)->insert(0, absolutePath);
+    }
+}
+
+void build_corsen_graph(OrientedGraph& graph)
+{
+    std::string absolutePath(
+        "/home/eric/vle/vle-labs/paradevs/src/tests/corsen/data_s/");
+    std::string modeFile(".mode");
+    std::string parametersFile("par.txt");
+    std::string elevationFile("alt");
+    std::string outletFile("arbre");
+    std::string layersFile("couche");
+    std::string contextFile("contexte_yar_scenario.xml");
+    std::string slopeFile("pav");
+    std::vector < std::string* > files;
+    Corsen c;
+
+    files.push_back(&parametersFile);
+    files.push_back(&modeFile);
+    files.push_back(&elevationFile);
+    files.push_back(&outletFile);
+    files.push_back(&slopeFile);
+    files.push_back(&contextFile);
+    files.push_back(&layersFile);
+    modify_file_paths(absolutePath, files);
+
+    c.read(files, absolutePath);
+    c.buildGraph();
+
+    const DirectedGraph& g = c.getGraph().graph();
+    std::vector < vertex_t > og_vertex_list;
+    std::vector < vertex_t > dg_vertex_list;
+    std::vector < int > dg_in_vertex_list;
+    DirectedGraph::vertex_iterator it_dg, end_dg;
+
+    tie(it_dg, end_dg) = vertices(g);
+    for (uint i = 0; it_dg != end_dg; ++it_dg, ++i) {
+        og_vertex_list.push_back(add_vertex(graph));
+        dg_vertex_list.push_back(*it_dg);
+        dg_in_vertex_list.push_back(0);
+    }
+
+    tie(it_dg, end_dg) = vertices(g);
+    for (uint i = 0; it_dg != end_dg; ++it_dg, ++i) {
+        DirectedGraph::adjacency_iterator neighbour_it, neighbour_end;
+
+        tie(neighbour_it, neighbour_end) = adjacent_vertices(*it_dg, g);
+        for (; neighbour_it != neighbour_end; ++neighbour_it) {
+            uint index = 0;
+
+            while (dg_vertex_list[index] != *neighbour_it) {
+                ++index;
+            }
+            ++dg_in_vertex_list[index];
+            boost::add_edge(og_vertex_list[i], og_vertex_list[index],
+                            EdgeProperties(1.), graph);
+        }
+    }
+
+    tie(it_dg, end_dg) = vertices(g);
+    for (uint i = 0; it_dg != end_dg; ++it_dg, ++i) {
+        if (dg_in_vertex_list[i] == 0) {
+            graph[og_vertex_list[i]] = VertexProperties(i, 1., TOP_PIXEL);
+        } else {
+            graph[og_vertex_list[i]] = VertexProperties(i, 1., NORMAL_PIXEL);
+        }
+    }
+}
+
 } } } // namespace paradevs tests boost_graph

+ 1 - 0
src/tests/boost_graph/partitioning/graph_build.hpp

@@ -32,6 +32,7 @@
 namespace paradevs { namespace tests { namespace boost_graph {
 
 void build_graph(UnorientedGraph& g, OrientedGraph& graph);
+void build_corsen_graph(OrientedGraph& graph);
 
 } } } // namespace paradevs tests boost_graph
 

+ 125 - 43
src/tests/boost_graph/partitioning/utils.cpp

@@ -228,10 +228,10 @@ void Affinage_equilibrage_charge(UnorientedGraph *g, EntiersEntiers &Partition)
 
     std::clog << "Poids initial des parties : " << std::endl;
 
-    for (uint i = 0; i < poids_parties.size(); i++){
-        std::cout << poids_parties.at(i) << " ";
-    }
-    std::cout << "\n" << std::endl;
+    // for (uint i = 0; i < poids_parties.size(); i++){
+    //     std::cout << poids_parties.at(i) << " ";
+    // }
+    // std::cout << "\n" << std::endl;
 
     /*
      * Le critère d'amélioration consiste à faire tendre vers 0 la somme
@@ -251,7 +251,7 @@ void Affinage_equilibrage_charge(UnorientedGraph *g, EntiersEntiers &Partition)
     // on conserve le poids maximum
     double p_max = *max_element(poids_parties.begin(), poids_parties.end());
 
-    std::cout << "Valeurs du criètre de départ : " << critere << std::endl;
+    // std::cout << "Valeurs du criètre de départ : " << critere << std::endl;
 
     // création d'un second critère légérement plsu faible que le premier
     double best_critere = critere - 1e-7;
@@ -358,13 +358,14 @@ void Affinage_equilibrage_charge(UnorientedGraph *g, EntiersEntiers &Partition)
                         suprim_val(*Partition.at(community.at(val)),vertex);
                         Partition.at(cpt)->push_back(vertex);
                         std::sort(Partition.at(cpt)->begin(), Partition.at(cpt)->end());
-                        std::cout<<" C'EST MORT RETOUR EN ARRIERE ! "<<std::endl;
+                        // std::cout<<" C'EST MORT RETOUR EN ARRIERE ! "<<std::endl
+                            ;
                     }
                     else
                     {
                         poids_parties = new_poids_parties;
                         decision = true;
-                        std::cout<<" Modification reussi ! "<<std::endl;
+                        // std::cout<<" Modification reussi ! "<<std::endl;
                     }
                 }
             }
@@ -390,16 +391,16 @@ void Affinage_equilibrage_charge(UnorientedGraph *g, EntiersEntiers &Partition)
             nbr_passage = 0;
         }
 
-        std::clog<<"Poids des parties modifié : "<<std::endl;
-        for(uint i = 0; i<poids_parties.size(); i++){
-            std::cout<<poids_parties.at(i)<<" ";
-        }
-        std::cout<<"\n"<<std::endl;
+        // std::clog<<"Poids des parties modifié : "<<std::endl;
+        // for(uint i = 0; i<poids_parties.size(); i++){
+        //     std::cout<<poids_parties.at(i)<<" ";
+        // }
+        // std::cout<<"\n"<<std::endl;
         p_max = *max_element(poids_parties.begin(),poids_parties.end());
-        std::cout<<"Valeurs du criètre : "<<critere<<std::endl;
-        std::cout<<"Valeurs du best_criètre : "<<best_critere<<std::endl;
-        std::cout<<"Nombre de passage : "<<nbr_passage<<std::endl;
-        std::cout<<"\n"<<std::endl;
+        // std::cout<<"Valeurs du criètre : "<<critere<<std::endl;
+        // std::cout<<"Valeurs du best_criètre : "<<best_critere<<std::endl;
+        // std::cout<<"Nombre de passage : "<<nbr_passage<<std::endl;
+        // std::cout<<"\n"<<std::endl;
 
     }
 }
@@ -465,7 +466,7 @@ void Affinage_recherche_locale(UnorientedGraph *g, EntiersEntiers &Partition, do
                 double cut_min = *min_element(tmp_cut.begin(),tmp_cut.end());
                 //std::cout<<"cout de coupe minimum de la liste : "<<cut_min<<std::endl;
                 if(cut_min<cut){
-                    std::clog<<"Changement ! "<<std::endl;
+                    // std::clog<<"Changement ! "<<std::endl;
                     int tmp = recherche_val_double(tmp_cut,cut_min);
                     cut=cut_min;
                     Partition.at(community.at(tmp))->push_back(vertex);
@@ -767,7 +768,7 @@ bool contraction_HEM(UnorientedGraph *g, Base_Graph &baseg, ListEntiersEntiers &
 				Random_list_vertices[i]=-1;
 				Random_list_vertices[recherche_val(Random_list_vertices,best_vertexs)]=-1;
 				val_cpt--;
-				std::cout<<val_cpt<<std::endl;
+				// std::cout<<val_cpt<<std::endl;
 			}
 			else{
 				/*
@@ -809,7 +810,7 @@ bool contraction_HEM(UnorientedGraph *g, Base_Graph &baseg, ListEntiersEntiers &
 	}
 
 	std::sort(sommets_a_detruire.begin(), sommets_a_detruire.end()); // Trie dans l'ordre croissant des "sommets à détruire"
-	std::cout<<"\n"<<std::endl;
+	// std::cout<<"\n"<<std::endl;
 	/*
 	 * Suppression des sommets de la liste "sommets à détruire". Cette suppression est
 	 * effectuée dans l'ordre décroissant afin à maintenir à jour la renumérotation
@@ -820,25 +821,25 @@ bool contraction_HEM(UnorientedGraph *g, Base_Graph &baseg, ListEntiersEntiers &
 		remove_vertex(sommets_a_detruire[j],*gtmp);
 	}
 
-	std::clog<<"Affichage avant tri "<<std::endl;
-	for(uint k = 0;k<tableau_de_correspondance->size();k++){
-		for(uint v = 0; v<tableau_de_correspondance->at(k)->size();v++){
-			std::cout<<tableau_de_correspondance->at(k)->at(v)<<" ";
-		}
-		std::cout<<"\n"<<std::endl;
-	}
+	// std::clog<<"Affichage avant tri "<<std::endl;
+	// for(uint k = 0;k<tableau_de_correspondance->size();k++){
+	// 	for(uint v = 0; v<tableau_de_correspondance->at(k)->size();v++){
+	// 		std::cout<<tableau_de_correspondance->at(k)->at(v)<<" ";
+	// 	}
+	// 	std::cout<<"\n"<<std::endl;
+	// }
 	std::sort(tableau_de_correspondance->begin(),tableau_de_correspondance->end(),myobject); // Trie dans l'ordre croissant des couples de sommets de la liste de correspondance
 
-	std::clog<<"Tableau de correspondance "<<std::endl;
-	for(uint k = 0;k<tableau_de_correspondance->size();k++){
-		for(uint v = 0; v<tableau_de_correspondance->at(k)->size();v++){
-			std::cout<<tableau_de_correspondance->at(k)->at(v)<<" ";
-		}
-		std::cout<<"\n"<<std::endl;
-	}
+	// std::clog<<"Tableau de correspondance "<<std::endl;
+	// for(uint k = 0;k<tableau_de_correspondance->size();k++){
+	// 	for(uint v = 0; v<tableau_de_correspondance->at(k)->size();v++){
+	// 		std::cout<<tableau_de_correspondance->at(k)->at(v)<<" ";
+	// 	}
+	// 	std::cout<<"\n"<<std::endl;
+	// }
 
 	liste_corr.push_back(tableau_de_correspondance);
-	std::cout<<"\n"<<std::endl;
+	// std::cout<<"\n"<<std::endl;
 	baseg.push_back(gtmp); // Ajout du graphe modifié à la "base des graphe"
 
 	if(val_cpt == val_reduc)
@@ -952,7 +953,7 @@ bool contraction_Random_Maching(UnorientedGraph *g, Base_Graph &baseg, ListEntie
 				Random_list_vertices[i]=-1;
 				Random_list_vertices[recherche_val(Random_list_vertices,best_vertexs)]=-1;
 				val_cpt--;
-				std::cout<<val_cpt<<std::endl;
+				// std::cout<<val_cpt<<std::endl;
 			}
 			else{
 				/*
@@ -998,16 +999,16 @@ bool contraction_Random_Maching(UnorientedGraph *g, Base_Graph &baseg, ListEntie
 	}*/
 	std::sort(tableau_de_correspondance->begin(),tableau_de_correspondance->end(),myobject); // Trie dans l'ordre croissant des couples de sommets de la liste de correspondance
 
-	std::clog<<"Tableau de correspondance "<<std::endl;
-	for(uint k = 0;k<tableau_de_correspondance->size();k++){
-		for(uint v = 0; v<tableau_de_correspondance->at(k)->size();v++){
-			std::cout<<tableau_de_correspondance->at(k)->at(v)<<" ";
-		}
-		std::cout<<"\n"<<std::endl;
-	}
+	// std::clog<<"Tableau de correspondance "<<std::endl;
+	// for(uint k = 0;k<tableau_de_correspondance->size();k++){
+	// 	for(uint v = 0; v<tableau_de_correspondance->at(k)->size();v++){
+	// 		std::cout<<tableau_de_correspondance->at(k)->at(v)<<" ";
+	// 	}
+	// 	std::cout<<"\n"<<std::endl;
+	// }
 
 	liste_corr.push_back(tableau_de_correspondance);
-	std::cout<<"\n"<<std::endl;
+	// std::cout<<"\n"<<std::endl;
 	baseg.push_back(gtmp); // Ajout du graphe modifié à la "base des graphe"
 
 
@@ -1503,4 +1504,85 @@ OrientedGraphs Graph_Partition(const EntiersEntiers& Partition,
 	return Neight;
 }*/
 
+void make_unoriented_graph(const OrientedGraph& og, UnorientedGraph& ug)
+{
+    std::vector < vertex_t > ug_vertex_list;
+    std::vector < vertex_t > og_vertex_list;
+
+    for (uint i = 0; i < num_vertices(og); ++i) {
+        ug_vertex_list.push_back(add_vertex(ug));
+    }
+
+    OrientedGraph::vertex_iterator it_og, end_og;
+    UnorientedGraph::vertex_iterator it_ug, end_ug;
+
+    tie(it_og, end_og) = vertices(og);
+    tie(it_ug, end_ug) = vertices(ug);
+    for (; it_og != end_og; ++it_og, ++it_ug) {
+        ug[*it_ug] = og[*it_og];
+        og_vertex_list.push_back(*it_og);
+    }
+
+    OrientedGraph::edge_iterator ite_og, ende_og;
+
+    tie(ite_og, ende_og) = edges(og);
+    for (; ite_og != ende_og; ++ite_og) {
+        boost::add_edge(source(*ite_og, og), target(*ite_og, og),
+                        og[*ite_og], ug);
+    }
+
+    // std::cout << "Oriented graph: " << std::endl;
+    // tie(it_og, end_og) = vertices(og);
+    // for (; it_og != end_og; ++it_og) {
+    //     OrientedGraph::adjacency_iterator neighbour_it, neighbour_end;
+
+    //     std::cout << og[*it_og]._index << " is connected with ";
+    //     tie(neighbour_it, neighbour_end) = adjacent_vertices(*it_og, og);
+    //     for (; neighbour_it != neighbour_end; ++neighbour_it)
+    //         std::cout << og[*neighbour_it]._index << " ";
+    //     std::cout << " and weight = " << og[*it_og]._weight << std::endl;
+    // }
+    // std::cout << std::endl;
+
+    // std::cout << "Unoriented graph: " << std::endl;
+    // tie(it_ug, end_ug) = vertices(ug);
+    // for (; it_ug != end_ug; ++it_ug) {
+    //     UnorientedGraph::adjacency_iterator neighbour_it, neighbour_end;
+
+    //     std::cout << ug[*it_ug]._index << " is connected with ";
+    //     tie(neighbour_it, neighbour_end) = adjacent_vertices(*it_ug, ug);
+    //     for (; neighbour_it != neighbour_end; ++neighbour_it)
+    //         std::cout << ug[*neighbour_it]._index << " ";
+    //     std::cout << " and weight = " << ug[*it_ug]._weight << std::endl;
+    // }
+    // std::cout << std::endl;
+}
+
+void adjacence_ggp(int vertex, Entiers &sommets_adj, UnorientedGraph *g)
+{
+    tie(neighbourIt, neighbourEnd) = adjacent_vertices(vertex, *g);
+    for (; neighbourIt != neighbourEnd; ++neighbourIt)
+    {
+        sommets_adj.push_back(*neighbourIt);
+    }
+
+}
+
+float modif_Cout_coupe(const Entiers &P, int val, float cut, UnorientedGraph *g)
+{
+    //std::cout<<"Cout de coupe initiale : "<<cut<<std::endl;
+    //std::cout<<"degré du sommet tiré : "<<Degree(*g,val)<<std::endl;
+    double cpt=0;
+    float new_cut;
+    tie(neighbourIt, neighbourEnd) = adjacent_vertices(val, *g);
+    for (; neighbourIt != neighbourEnd; neighbourIt++){
+        if(In_tab(P,*neighbourIt)==1){
+            cpt++;
+        }
+    }
+    new_cut = cut + (Degree(*g,val) - (2 * cpt));
+    return new_cut;
+}
+
+
 } } } // namespace paradevs tests boost_graph

+ 10 - 2
src/tests/boost_graph/partitioning/utils.hpp

@@ -74,9 +74,11 @@ void Affinage_recherche_locale(UnorientedGraph *g, EntiersEntiers &Partition,
 void projection(EntiersEntiers &Partition,ListEntiersEntiers::iterator lit);
 
 bool contraction_HEM(UnorientedGraph *g, Base_Graph &baseg,
-                     ListEntiersEntiers &liste_corr, int val_reduc, int &val_cpt);
+                     ListEntiersEntiers &liste_corr, int val_reduc,
+                     int &val_cpt);
 bool contraction_Random_Maching(UnorientedGraph *g, Base_Graph &baseg,
-								ListEntiersEntiers &liste_corr, int val_reduc, int &val_cpt);
+                                ListEntiersEntiers &liste_corr, int val_reduc,
+                                int &val_cpt);
 
 Entiers Liste_adjacence(UnorientedGraph &g, int vertexs,
                         const Entiers &random_vertices);
@@ -101,6 +103,12 @@ int In_community_dichotomie(const EntiersEntiers &part, int val);
 double Degree(UnorientedGraph &g , int node);
 double Cluster_Degree(UnorientedGraph &g , const Entiers &cluster);
 
+void make_unoriented_graph(const OrientedGraph& og, UnorientedGraph& uog);
+
+void adjacence_ggp(int vertex, Entiers &sommets_adj, UnorientedGraph *g);
+
+float modif_Cout_coupe(const Entiers &P, int val, float cut, UnorientedGraph *g);
+
 } } } // namespace paradevs tests boost_graph
 
 #endif

+ 278 - 21
src/tests/boost_graph/tests.cpp

@@ -38,7 +38,8 @@ using namespace paradevs::common::scheduler;
 using namespace paradevs::pdevs;
 using namespace paradevs::tests::boost_graph;
 
-void flat_test()
+template < class GraphBuilder >
+void flat_heap_test(double duration)
 {
     RootCoordinator <
         DoubleTime,
@@ -48,33 +49,81 @@ void flat_test()
             SchedulerHandle,
             InBuildFlatGraphManager <
                 SchedulerHandle,
-                FlatGraphBuilder >,
+                GraphBuilder >,
             paradevs::common::NoParameters,
             paradevs::common::NoParameters >
-    > rc(0, 100000, "root", NoParameters(), NoParameters());
+    > rc(0, duration, "root", NoParameters(), NoParameters());
 
     rc.run();
 }
 
-void hierarchical_test()
+template < class GraphBuilder >
+void flat_vector_test(double duration)
 {
     RootCoordinator <
         DoubleTime,
         paradevs::pdevs::Coordinator <
+            DoubleTime,
+            paradevs::common::scheduler::VectorScheduler <
+                paradevs::common::DoubleTime >,
+            paradevs::common::scheduler::NoSchedulerHandle,
+            InBuildFlatGraphManager <
+                paradevs::common::scheduler::NoSchedulerHandle,
+                GraphBuilder >,
+            paradevs::common::NoParameters,
+            paradevs::common::NoParameters >
+    > rc(0, duration, "root", NoParameters(), NoParameters());
+
+    rc.run();
+}
+
+void hierarchical_test()
+{
+    // RootCoordinator <
+    //     DoubleTime,
+    //     paradevs::pdevs::Coordinator <
+    //         DoubleTime,
+    //         SchedulerType,
+    //         SchedulerHandle,
+    //         HierarchicalGraphManager <
+    //             SchedulerHandle,
+    //             HierarchicalGraphBuilder >,
+    //         paradevs::common::NoParameters,
+    //         paradevs::common::NoParameters >
+    //     > rc(0, 100, "root", NoParameters(), NoParameters());
+
+    // rc.run();
+}
+
+void parallel_partitionning_heap_test(double duration,
+                                      int cluster_number,
+                                      std::string partitioning_method_name,
+                                      int contraction_coef,
+                                      bool contraction_coef_flag)
+{
+    RootCoordinator <
+        DoubleTime,
+        paradevs::pdevs::multithreading::Coordinator <
             DoubleTime,
             SchedulerType,
             SchedulerHandle,
-            HierarchicalGraphManager <
+            ParallelHeapHierarchicalGraphManager <
                 SchedulerHandle,
-                HierarchicalGraphBuilder >,
+                PartitioningGraphBuilder >,
             paradevs::common::NoParameters,
-            paradevs::common::NoParameters >
-        > rc(0, 100, "root", NoParameters(), NoParameters());
+            PartitioningParameters >
+        > rc(0, duration, "root", NoParameters(),
+             PartitioningParameters(cluster_number, partitioning_method_name,
+                                    contraction_coef, contraction_coef_flag));
 
     rc.run();
 }
 
-void partitionning_test()
+void partitionning_heap_test(double duration,
+                             int cluster_number,
+                             std::string partitioning_method_name,
+                             int contraction_coef,
+                             bool contraction_coef_flag)
 {
     RootCoordinator <
         DoubleTime,
@@ -82,36 +131,244 @@ void partitionning_test()
             DoubleTime,
             SchedulerType,
             SchedulerHandle,
-            HierarchicalGraphManager <
+            HeapHierarchicalGraphManager <
                 SchedulerHandle,
                 PartitioningGraphBuilder >,
             paradevs::common::NoParameters,
-            paradevs::common::NoParameters >
-        > rc(0, 100000, "root", NoParameters(), NoParameters());
+            PartitioningParameters >
+        > rc(0, duration, "root", NoParameters(),
+             PartitioningParameters(cluster_number, partitioning_method_name,
+                                    contraction_coef, contraction_coef_flag));
 
-    std::cout << rc.to_string() << std::endl;
+    rc.run();
+}
+
+void partitionning_vector_test(double duration,
+                               int cluster_number,
+                               std::string partitioning_method_name,
+                               int contraction_coef,
+                               bool contraction_coef_flag)
+{
+    RootCoordinator <
+        DoubleTime,
+        paradevs::pdevs::Coordinator <
+            DoubleTime,
+            paradevs::common::scheduler::VectorScheduler <
+                paradevs::common::DoubleTime >,
+            paradevs::common::scheduler::NoSchedulerHandle,
+            VectorHierarchicalGraphManager <
+                paradevs::common::scheduler::NoSchedulerHandle,
+                PartitioningGraphBuilder >,
+            paradevs::common::NoParameters,
+            PartitioningParameters >
+        > rc(0, duration, "root", NoParameters(),
+             PartitioningParameters(cluster_number, partitioning_method_name,
+                                    contraction_coef, contraction_coef_flag));
 
     rc.run();
 }
 
-int main()
+void test(double duration, std::string partitioning_method_name,
+          unsigned int min, unsigned int max, unsigned int step,
+          bool vector, bool heap,
+          int contraction_coef,
+          bool contraction_coef_flag)
 {
     boost::timer t;
 
-    std::cout << "flat graph ..." << std::endl;
-    flat_test();
+    std::cout << "==== " << partitioning_method_name << " with ";
+    if (contraction_coef_flag) {
+        std::cout << "/";
+    }
+    std::cout << contraction_coef << " ===" << std::endl;
+    std::cout << "n";
+    if (heap) {
+        std::cout << "\t heap";
+    }
+    if (vector) {
+        std::cout << "\t vector";
+    }
+    std::cout << std::endl;
+
+    if (contraction_coef_flag) {
+        for (unsigned int n = min; n <= max; n += step) {
+            std::cout << n << "\t";
+            if (heap) {
+                double t1 = t.elapsed();
+
+                for (unsigned int i = 0; i < 20; ++i) {
+                    partitionning_heap_test(duration, n,
+                                            partitioning_method_name,
+                                            contraction_coef,
+                                            contraction_coef_flag);
+                }
+
+                double t2 = t.elapsed();
+
+                std::cout << (t2 - t1) / 20 << "\t";
+            }
+            if (vector) {
+                double t1 = t.elapsed();
+
+                for (unsigned int i = 0; i < 20; ++i) {
+                    partitionning_vector_test(duration, n,
+                                              partitioning_method_name,
+                                              contraction_coef,
+                                              contraction_coef_flag);
+                }
+
+                double t2 = t.elapsed();
+
+                std::cout << (t2 - t1) / 20 << std::endl;
+            } else {
+                std::cout << std::endl;
+            }
+
+        }
+    } else {
+        std::cout << contraction_coef << "\t";
+        if (heap) {
+            double t1 = t.elapsed();
+
+            for (unsigned int i = 0; i < 20; ++i) {
+                partitionning_heap_test(duration, contraction_coef,
+                                        partitioning_method_name,
+                                        contraction_coef,
+                                        contraction_coef_flag);
+            }
+
+            double t2 = t.elapsed();
+
+            std::cout << (t2 - t1) / 20 << "\t";
+        }
+        if (vector) {
+            double t1 = t.elapsed();
+
+            for (unsigned int i = 0; i < 20; ++i) {
+                partitionning_vector_test(duration, contraction_coef,
+                                          partitioning_method_name,
+                                          contraction_coef,
+                                          contraction_coef_flag);
+                }
+
+            double t2 = t.elapsed();
+
+            std::cout << (t2 - t1) / 20 << std::endl;
+        } else {
+            std::cout << std::endl;
+        }
+    }
+}
+
+void test_flat_38()
+{
+    boost::timer t;
+
+    std::cout << "== 38 nodes == " << std::endl;
+    std::cout << "flat graph with heap = ";
+    for (unsigned int i = 0; i < 20; ++i) {
+        flat_heap_test< FlatGraphBuilder >(10000);
+    }
 
     double t2 = t.elapsed();
 
-    std::cout << "... OK -> " << t2 << std::endl;
+    std::cout << t2 / 20 << std::endl;
 
-    //hierarchical_test();
+    std::cout << "flat graph with vector = ";
+    for (unsigned int i = 0; i < 20; ++i) {
+        flat_vector_test< FlatGraphBuilder >(10000);
+    }
 
-    std::cout << "partitioning graph ..." << std::endl;
-    partitionning_test();
+    double t3 = t.elapsed();
+
+    std::cout << (t3 - t2) / 20 << std::endl;
+}
+
+void test_partiotining_38()
+{
+    for (int i = 1; i <= 2; ++i) {
+        test(10000, "ggp", 2, 16, 2, true, true, i, true);
+        test(10000, "gggp_pond", 2, 16, 2, true, true, i, true);
+        test(10000, "random", 2, 16, 2, true, true, i, true);
+    }
+
+    for (int i = 2; i <= 8; i += 2) {
+        test(10000, "gggp_pond", 0, 0, 0, true, true, i, false);
+    }
+}
+
+void test_flat_corsen()
+{
+    boost::timer t;
+
+    std::cout << "== CORSEN == " << std::endl;
+    std::cout << "flat graph with heap = ";
+    for (unsigned int i = 0; i < 20; ++i) {
+        flat_heap_test< CorsenFlatGraphBuilder >(10);
+    }
+
+    double t2 = t.elapsed();
+
+    std::cout << t2 / 20 << std::endl;
+
+    std::cout << "flat graph with vector = ";
+    for (unsigned int i = 0; i < 20; ++i) {
+        flat_vector_test< CorsenFlatGraphBuilder >(10);
+    }
 
     double t3 = t.elapsed();
 
-    std::cout << "... OK -> " << (t3 - t2) << std::endl;
+    std::cout << (t3 - t2) / 20 << std::endl;
+}
+
+const double corsen_duration = 10;
+
+void test_partitioning_corsen()
+{
+    test(corsen_duration, "gggp_pond", 2, 32, 2, false, true, 10, true);
+    test(corsen_duration, "gggp_pond", 2, 32, 2, false, true, 20, true);
+    test(corsen_duration, "gggp_pond", 2, 32, 2, false, true, 40, true);
+    test(corsen_duration, "gggp_pond", 2, 32, 2, false, true, 80, true);
+    test(corsen_duration, "gggp_pond", 2, 22, 2, false, true, 200, true);
+
+    test(corsen_duration, "gggp_pond", 2, 32, 2, false, true, 30, false);
+    test(corsen_duration, "gggp_pond", 2, 32, 2, false, true, 40, false);
+    test(corsen_duration, "gggp_pond", 2, 32, 2, false, true, 50, false);
+    test(corsen_duration, "gggp_pond", 2, 32, 2, false, true, 60, false);
+    test(corsen_duration, "gggp_pond", 2, 32, 2, false, true, 70, false);
+    test(corsen_duration, "gggp_pond", 2, 32, 2, false, true, 80, false);
+    test(corsen_duration, "gggp_pond", 2, 32, 2, false, true, 90, false);
+    test(corsen_duration, "gggp_pond", 2, 32, 2, false, true, 100, false);
+
+    test(corsen_duration, "ggp", 2, 32, 2, false, true, 10, true);
+    test(corsen_duration, "ggp", 2, 32, 2, false, true, 20, true);
+    test(corsen_duration, "ggp", 2, 32, 2, false, true, 40, true);
+    test(corsen_duration, "ggp", 2, 32, 2, false, true, 80, true);
+    test(corsen_duration, "ggp", 2, 22, 2, false, true, 200, true);
+
+    test(corsen_duration, "ggp", 2, 32, 2, false, true, 30, false);
+    test(corsen_duration, "ggp", 2, 32, 2, false, true, 40, false);
+    test(corsen_duration, "ggp", 2, 32, 2, false, true, 50, false);
+    test(corsen_duration, "ggp", 2, 32, 2, false, true, 60, false);
+    test(corsen_duration, "ggp", 2, 32, 2, false, true, 70, false);
+    test(corsen_duration, "ggp", 2, 32, 2, false, true, 80, false);
+    test(corsen_duration, "ggp", 2, 32, 2, false, true, 90, false);
+    test(corsen_duration, "ggp", 2, 32, 2, false, true, 100, false);
+
+    test(corsen_duration, "random", 2, 32, 2, false, true, 10, true);
+    test(corsen_duration, "random", 2, 32, 2, false, true, 20, true);
+    test(corsen_duration, "random", 2, 32, 2, false, true, 40, true);
+    test(corsen_duration, "random", 2, 32, 2, false, true, 80, true);
+    test(corsen_duration, "random", 2, 22, 2, false, true, 200, true);
+}
+
+int main()
+{
+    // test_flat_38();
+    // test_partiotining_38();
+
+    test_flat_corsen();
+    test_partitioning_corsen();
+
     return 0;
 }

+ 23 - 0
src/tests/corsen/CMakeLists.txt

@@ -0,0 +1,23 @@
+INCLUDE_DIRECTORIES(
+  ${PARADEVS_BINARY_DIR}/src
+  ${PARADEVS_SOURCE_DIR}/src
+  ${Boost_INCLUDE_DIRS}
+  ${GLIBMM_INCLUDE_DIRS}
+  ${LIBXML_INCLUDE_DIRS})
+
+LINK_DIRECTORIES(
+  ${GLIBMM_LIBRARY_DIRS}
+  ${LIBXML_LIBRARY_DIR})
+
+# corsen tests
+ADD_EXECUTABLE(corsen-tests ${COMMON_HPP} ${COMMON_SCHEDULER_HPP} ${PDEVS_HPP}
+  tests.cpp)
+SET_TARGET_PROPERTIES(corsen-tests PROPERTIES ${PARADEVS_APP_PROPERTIES})
+
+TARGET_LINK_LIBRARIES(corsen-tests corsen
+  ${Boost_LIBRARIES}
+  ${GLIBMM_LIBRARIES}
+  ${LIBXML_LIBRARIES}
+  ${GTHREAD_LIBRARIES})
+
+ADD_SUBDIRECTORY(lib)

+ 27 - 0
src/tests/corsen/lib/CMakeLists.txt

@@ -0,0 +1,27 @@
+INCLUDE_DIRECTORIES(
+  ${PARADEVS_BINARY_DIR}/src
+  ${PARADEVS_SOURCE_DIR}/src
+  ${PARADEVS_SOURCE_DIR}/src/tests/corsen/lib
+  ${Boost_INCLUDE_DIRS}
+  ${GLIBMM_INCLUDE_DIRS}
+  ${LIBXML_INCLUDE_DIRS})
+
+LINK_DIRECTORIES(
+  ${GLIBMM_LIBRARY_DIRS}
+  ${LIBXML_LIBRARY_DIR})
+
+SET(CORSEN_HPP Constantes.h Coordinates.h ElevationFileStream.h Functions.h
+  LayersFileStream.h OutletFileStream.h Parameters.h SoilFileStream.h
+  ContextData.h Corsen.hpp Exception.h Graph.hpp LayersTextFileStream.h Outlet.h
+  Singleton.h Vertex.h ContextFileReader.h DrainFileStream.h FileStream.h
+  Layer.h Node.h ParametersFileStream.h SlopeFileStream.h XmlReader.h)
+
+SET(CORSEN_CPP Corsen.cpp Functions.cpp Graph.cpp)
+
+ADD_LIBRARY(corsen SHARED ${CORSEN_HPP};${CORSEN_CPP})
+
+TARGET_LINK_LIBRARIES(corsen
+  ${Boost_LIBRARIES}
+  ${GLIBMM_LIBRARIES}
+  ${LIBXML_LIBRARIES}
+  ${GTHREAD_LIBRARIES})

+ 149 - 0
src/tests/corsen/lib/Constantes.h

@@ -0,0 +1,149 @@
+/**
+ *
+ * \file Constantes.h
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 30 mai 2013
+ * \brief regroupe toutes les constantes du programme.
+ */
+
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef CONSTANTES_H_
+#define CONSTANTES_H_
+
+//#define DEBUG
+#define SUJET 0
+#define OBJET 1
+#define VRAI 1
+#define FAUX 0
+#define LIG_KEY 1
+#define COL_KEY 2
+#define ALTITUDE 1
+#define COULEUR 2
+#define BASSIN 3
+#define DRAIN 4
+#define MNT 5
+#define NODE 6
+#define DERIVE 7
+#define IMAGE 8
+#define LAYER 9
+#define RESEAU 10
+#define EXUTOIRE 11
+#define HAIE 12
+#define EXTREMITE 13
+#define ZHANG 14
+#define NETW625 15
+#define MASK 16
+#define DRAIN_INI 17
+#define MUR 18
+
+#define RIEN -1
+#define ASCII 99
+#define NODATA -9999
+
+#define ALT 0
+#define SBV 1
+#define DBV 2
+#define LOD 3
+#define LON 3
+#define SML 4
+#define LZD 4
+#define CVX 4
+#define PEN 5
+#define BEV 6
+#define PAV 7
+#define MRT 8
+#define CFL 9
+#define DLT 9
+#define EXP 10
+#define DAR 10
+#define APL 10
+#define COV 11
+#define PRM 11
+#define DAS 11
+#define LOV 11
+#define DVV 11
+#define CNT 12
+#define IMA 12
+#define RAY 15
+#define MCX 15
+#define	BASE 0
+#define	ZOOM 1
+#define	INFO 2
+#define	AFFI 3
+#define	SELE 4
+#define	MAJ 5
+#define	SUPP 6
+#define	PROM1 7
+#define	PROM2 8
+#define	COUPE 9
+#define RACCORD 10
+#define MAJSBV 11
+#define MAJMDD 12
+#define MAJMUR 13
+
+#define NORD 1
+#define NORDOUEST 2
+#define OUEST 3
+#define SUDOUEST 4
+#define SUD 5
+#define SUDEST 6
+#define EST 7
+#define NORDEST 8
+#define PLATEAU 9
+#define EXUTOIRE_BORD 10
+#define EXUTOIRE_MER 11
+#define TROU 12
+
+#define ARCINFO 0
+#define DESCARTES 1
+#define MAPINFO  2
+#define ARCVIEW 3
+
+
+#define LONGUEUR_LABEL_MAX 60
+#define LONGUEUR_LIGNE_INDEX_VAR_MAX 129
+#define NB_COUCHE_MAX 32
+#define POUR_FREQUENCE 99
+#define POUR_COUCHE 2
+
+#define MAP 0
+/* si 1: Affichage des elements de mise au point */
+
+#define NB_DERIVES_MAX 50
+#define RESEAU_HYDRO 1
+#define CONTOUR_BASSIN 2
+#define CONTOUR_IMAGE_BINAIRE 3
+#define EXUTOIRES 4
+#define AUTRES 5
+#define NOMBRE_DE_CLASSE 1000
+#define DEFAULT_COLORS 16
+#define NB_FORMAT 5
+#define NB_COULEURS_DYNAMIC 90
+#define RAPPORT_SURFACE 10000
+#define TROU_TOLERE 1
+#define FACT 1000
+#define EPSALT 0.00001
+#define chemin_appli
+#define LONGMAILLE 50.
+#define ALTMER 0.1
+
+#endif /* CONSTANTES_H_ */

+ 112 - 0
src/tests/corsen/lib/ContextData.h

@@ -0,0 +1,112 @@
+/*!
+ * \file ContextData.h
+ * \brief Stocke les données du fichier context.
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ */
+
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef CONTEXTDATA_H_
+#define CONTEXTDATA_H_
+
+#include <string>
+#include "Singleton.h"
+
+/*! \class ContextData
+ *
+ * \brief regroupe les données du fichier context.
+ *
+ */
+
+class ContextData : public Singleton<ContextData>
+{
+	friend class Singleton<ContextData>;
+
+public :
+
+	/**
+	 * \struct mesh_chrono_t
+	 * \brief structure pour gestion des sorties.
+	 */
+	struct mesh_chrono_t
+	{
+		int line;       /*!< numéro de ligne */
+		int column;       /*!< numéro de colonne */
+		FILE * ptf;  /*!< pointeur vers fichier sorties */
+
+		mesh_chrono_t() : line(0), column(0), ptf(NULL) {}
+	};
+
+
+	typedef int day_t ;
+
+	/**
+	 * \struct date_t
+	 * \brief structure pour représentation des dates.
+	 */
+	struct date_t
+	{
+		unsigned day; /*!< numéro jour */
+		unsigned month; /*!< numéro mois */
+		unsigned year; /*!< numéro année */
+
+		date_t():day(0), month(0),year(0) {}
+	};
+
+	std::string _pathToData; /*!< chemin vers le répertoire contenant les fichiers de données */
+	int _soilNumber; /*!< numéro de la couche sur laquelle on travaille */
+	char * _absolutePath; /*!< chemin absolu vers le répertoire principal d'un projet TNT */
+	double _defaultNetworkSlope; /*!< pente par défaut du réseau */
+	std::string _soilFileName; /*!< nom du fichier de couches */
+	double _pptionAccess; /*!< prop_acces_eau */
+	mesh_chrono_t _outletsCoordinates[15]; /*!< Coordonnées exutoire */
+	day_t _numberDays; /*!< Durée en jours de la simulation */
+	date_t _simulationStartDate; /*!< Date du premier jour */
+
+private :
+
+	/*!
+	 *  \brief Constructeur
+	 *
+	 *  Constructeur de la classe ContextData.
+	 *
+	 *  Initialise les attributs.
+	 *
+	 */
+
+	ContextData()
+{
+		_soilNumber = 0;
+		_absolutePath = NULL;
+		_defaultNetworkSlope = 0.;
+		_pptionAccess = 0.;
+		_numberDays = 0;
+}
+	/*!
+	 *  \brief Destructeur
+	 *
+	 *  Destructeur de la classe ContextData
+	 */
+
+	~ContextData(){}
+};
+
+#endif /* CONTEXTDATA_H_ */

+ 234 - 0
src/tests/corsen/lib/ContextFileReader.h

@@ -0,0 +1,234 @@
+/*!
+ * \file ContextFileReader.h
+ * \brief Lecteur de fichier de type context.
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef CONTEXTFILEREADER_H_
+#define CONTEXTFILEREADER_H_
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <iostream>
+#include "ContextData.h"
+#include "XmlReader.h"
+#include "Functions.h"
+
+#define LINSIZE 1024
+
+/*! \class ContextFileReader
+ * \brief représente le lecteur de fichier de type context.
+ *
+ */
+
+class ContextFileReader
+{
+public :
+
+	/*!
+	 *  \brief Lecture.
+	 *
+	 *  Lit le fichier des paramètres d'entrées.
+	 *
+	 *  \param docname : le nom du du document à lire et analyser.
+	 *  \param numberDays : Durée en jours de la simulation.
+	 *  \param simulationStartDate : Date du premier jour.
+	 *  \param outletsCoordinates : Coordonnées exutoires.
+	 *  \return EXIT_SUCCESS - Fin normal de la méthode.
+	 */
+
+
+	static int read(const char * docname,  ContextData::day_t & numberDays, ContextData::date_t & simulationStartDate, ContextData::mesh_chrono_t outletsCoordinates[])
+	{
+		xmlDocPtr doc_context = XmlReader::parseDoc(docname);
+
+		/* Coordonnées exutoire */
+
+		getOutletCoordinates(doc_context, outletsCoordinates);
+
+		/* Durée en jours de la simulation */
+
+		numberDays = XmlReader::getIntParamValue(doc_context,"duree_simulation");
+
+		ContextData * ctxtD = ContextData::getInstance();
+
+		/* Date du premier jour */
+		simulationStartDate = getDate(((char *)XmlReader::getStringParamValue(doc_context,"debut-simulation")));
+
+		ctxtD->_soilNumber = XmlReader::getIntParamValue(doc_context,"nb_sols");
+
+		ctxtD->_soilFileName = (char*)XmlReader::getStringParamValue(doc_context,"file_sol_loc");
+
+		ctxtD->_defaultNetworkSlope = XmlReader::getFloatParamValue(doc_context,"defaut_pente_reseau");
+
+		ctxtD->_pptionAccess = XmlReader::getFloatParamValue(doc_context,"prop_acces_eau");
+
+		xmlFreeDoc(doc_context);
+		xmlCleanupParser();
+		xmlMemoryDump();
+
+		return EXIT_SUCCESS;
+	}
+
+	/*!
+	 *  \brief Obtenir date.
+	 *
+	 *  Transforme une représentation chaînée d'une date en une structure date.
+	 *
+	 *  \param dateStr : représentation chaînée d'une date au format jj/mm/aaaa.
+	 *  \return structure date avec un attribut pour le jour, le mois et l'année.
+	 */
+
+private :
+
+	static ContextData::date_t getDate(char dateStr[11])
+	{
+		ContextData::date_t date;
+		char c1,c2;
+
+		if(sscanf(dateStr,"%2d%c%2d%c%4d", &date.day,&c1,&date.month,&c2,&date.year)!=5)
+			printf("\n Erreur dans la lecture de date sur la chaine %s",dateStr);
+
+		return date;
+	}
+
+	/*!
+	 *  \brief Obtenir coordonnées exutoire.
+	 *
+	 *  Récupère les coordonnées de l'exutoire dans le document XML.
+	 *
+	 *  \param doc_context : document dans lequel se trouve l'information.
+	 *  \param outletsCoordinates : structure dans laquelle les données trouvées seront sauvegardées.
+	 *  \return void.
+	 */
+
+	static void getOutletCoordinates(xmlDocPtr doc_context, ContextData::mesh_chrono_t outletsCoordinates[])
+	{
+		xmlNodePtr cur_node = NULL;
+		xmlChar *value_x;
+		xmlChar *value_y;
+
+		cur_node = XmlReader::findNodeWithTagAndAttrName(doc_context, "mesh", "exutoire");
+		if (cur_node!=NULL)
+		{
+			value_x = xmlGetProp(cur_node,(const xmlChar*)"x-value");
+			value_y = xmlGetProp(cur_node,(const xmlChar*)"y-value");
+			outletsCoordinates[0].line= atoi((const char*) value_x );
+			outletsCoordinates[0].column= atoi((const char*) value_y );
+			xmlFree(value_x);
+			xmlFree(value_y);
+		}
+		else
+		{
+			std::cerr <<"Error  : Outlet coordinate not defined\n";
+			exit(0);
+		}
+	}
+};
+
+#endif /* CONTEXTFILEREADER_H_ */
+
+
+
+
+
+
+
+
+
+
+
+/*---------------------------------------------------------------------------*/
+/*  lecture_fichier_contexte :                                               */
+/* Entree : nomfich                                               			 */
+/*          fichier renfermant les parametres d'entrees                 	 */
+/*---------------------------------------------------------------------------*/
+/*void lecture_fichier_contexte (char *nomfich, jour_t & nbjours, struct_date_t & date_deb_simu, struct_maille_chrono_t TabMailles [])
+{
+    FILE *fpnomfich = NULL;
+    char tbuf[LINSIZE];
+    int afmsg;
+
+ *tbuf = 0;
+
+    if( !nomfich) {
+        printf("\nVeuillez taper le nom du fichier contexte, puis appuyez sur ENTREE [CR/LF]");
+        printf("\n ou appuyez sur ENTREE pour entrer les valeurs a partir du 'clavier'\n");
+
+        putchar('?');
+
+        fgets(tbuf, LINSIZE, stdin);  Demande le nom du fichier contexte
+        putchar('\n');
+        Util::ignorelf(tbuf);
+         Si le nom du fichier contexte est donne
+        if( tbuf[0]) {
+            int i = -1;  determine sa longueur et
+            while( tbuf[++i]) {}
+
+            if((nomfich = (char *)malloc(i+1)) == NULL)
+                Util::traiterreur(tbuf);
+            else     --  copie-le dans la variable nomfich --
+            {
+                i = -1;
+                while ((nomfich[++i] = tbuf[i]))
+                {
+
+                }
+
+            }
+        }
+    }
+
+     Si le nom de fichier contexte n'est pas donne
+       ou si on a pas pu l'ouvrir,
+       On lit les valeurs initiales au clavier [entree standard]
+
+    afmsg = (nomfich == NULL) ? 1 : 0;
+
+    if( ! afmsg) {
+         Essaie d'ouvrir le fichier, en cas d'impossiblite dis pourquoi
+        if( !(fpnomfich = fopen (nomfich,"r"))) {
+        	Util::traiterreur(nomfich);
+            afmsg = 1;
+        }
+    }
+
+     Les param d'entree doivent etre donnes dans un fichier
+     et ne peuvent plus etre lus au clavier
+    if( !fpnomfich) {
+        fpnomfich = stdin;
+        printf("VOUS DEVEZ DONNER LE NOM DU FICHIER DES PARAMETRES D'ENTREE !!");
+        exit(0);
+    }
+
+    //exutoire = NULL;
+
+    appel de la fonction qui va lire le fichier des parametres d'entree
+
+    read_context_file(nomfich, nbjours, date_deb_simu, TabMailles);
+
+
+    fclose(fpnomfich);
+}*/
+
+

+ 319 - 0
src/tests/corsen/lib/Coordinates.h

@@ -0,0 +1,319 @@
+/*!
+ * \file Coordinates.h
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 3 juin 2013
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef COORDINATES_H_
+#define COORDINATES_H_
+
+#include <iostream>
+#include <sstream>
+#include <fstream>
+#include "Parameters.h"
+
+/*! \class Coordinates
+ * \brief représente les coordonnées en 2D d'un point du bassin versant.
+ */
+
+class Coordinates
+{
+private :
+	short _line; /*!< numéro de ligne */
+	short _column; /*!< numéro de colonne */
+
+public :
+	static int _columnsNumber; /*!< nombre de colonnes */
+	/*!
+	 *  \brief Constructeur
+	 *
+	 *  Constructeur par défaut de la classe Coordinates.
+	 *  Initialise les attributs à 0.
+	 *
+	 *  \return void.
+	 */
+
+	Coordinates(): _line(0), _column(0) {};
+
+	/*!
+	 *  \brief Constructeur
+	 *
+	 *  Constructeur avec paramètres de la classe Coordinates.
+	 *
+	 *  \param line : numéro de la ligne.
+	 *  \param column : : numéro de la colonne.
+	 *  \return void.
+	 */
+
+	Coordinates(short line, short column) : _line(line),_column(column) {}
+
+	/*!
+	 *  \brief Constructeur
+	 *
+	 *  Constructeur par copie de la classe Coordinates.
+	 *
+	 *  \param c : Instance de la classe Coordonnées à copier.
+	 *  \return void.
+	 */
+
+	Coordinates(const Coordinates &c): _line(c.getLine()), _column(c.getColumn()){}
+
+	/*!
+	 *  \brief Constructeur
+	 *
+	 *  Constructeur avec paramètres de la classe Coordinates.
+	 *
+	 *  \param nodeCoordinates : Coordonnées de base indispensable pour le calcul de la coordonnée voisine.
+	 *  \param identifiantVoisin : détermine la position du voisin par rapport à la coordonnées de base.
+	 *  \return void.
+	 */
+
+	Coordinates(const Coordinates & nodeCoordinates, char identifiantVoisin)
+	{
+		switch (identifiantVoisin)
+		{
+		case '1' :
+			_line = nodeCoordinates.getLine() - 1 ;
+			_column = nodeCoordinates.getColumn() ;
+			break ;
+		case '2' :
+			_line = nodeCoordinates.getLine() - 1 ;
+			_column = nodeCoordinates.getColumn() + 1 ;
+			break ;
+
+		case '3':
+			_line = nodeCoordinates.getLine() ;
+			_column = nodeCoordinates.getColumn() + 1 ;
+			break ;
+
+		case '4' :
+			_line = nodeCoordinates.getLine() + 1 ;
+			_column = nodeCoordinates.getColumn() + 1 ;
+			break ;
+
+		case '5' :
+			_line = nodeCoordinates.getLine() + 1 ;
+			_column = nodeCoordinates.getColumn() ;
+			break ;
+
+		case '6' :
+			_line = nodeCoordinates.getLine() + 1 ;
+			_column = nodeCoordinates.getColumn() - 1 ;
+			break ;
+
+		case '7' :
+			_line = nodeCoordinates.getLine() ;
+			_column = nodeCoordinates.getColumn() - 1 ;
+			break ;
+
+		case '8' :
+			_line = nodeCoordinates.getLine() - 1 ;
+			_column = nodeCoordinates.getColumn() - 1 ;
+			break ;
+		}
+	}
+
+
+	void operator = (const Coordinates& c)
+	{
+		_line = c.getLine();
+		_column = c.getColumn();
+	}
+
+	/*!
+	 *  \brief Destructeur
+	 *
+	 *  Destructeur de la classe Coordinates
+	 */
+
+	virtual ~Coordinates()
+	{
+
+	}
+
+	short getColumn() const
+	{
+		return _column;
+	}
+
+	void setColumn(short colonne)
+	{
+		this->_column = colonne;
+	}
+
+	short getLine() const
+	{
+		return _line;
+	}
+
+	void setLine(int ligne)
+	{
+		this->_line = ligne;
+	}
+
+	/*!
+	 * \brief Transformer en chaîne.
+	 *
+	 * Représentation chaînée de l'objet
+	 *
+	 * \param void
+	 * \return string
+	 */
+
+	const std::string toString() const
+	{
+		std::stringstream ss;
+		ss<<"Ligne "<<_line<<" Colonne "<<_column<<" ";
+		return ss.str();
+	}
+
+	/*!
+	 * \brief clé.
+	 *
+	 * Génère un identifiant unique (sans doublons) en fonction du numéro de la ligne et de la colonne et du nombre de colonnes.
+	 *
+	 * \param void
+	 * \return identifiant de la coordonnées.
+	 *
+	 */
+	int key() const
+	{ return (_line * _columnsNumber + _column); }
+
+	virtual bool operator==(const Coordinates& coordinates) const
+					{ return key() == coordinates.key(); }
+
+	virtual bool operator!=(const Coordinates& coordinates) const
+					{return key() != coordinates.key();}
+
+	virtual bool operator<(const Coordinates& coordinates) const
+	{ return key() < coordinates.key(); }
+
+	/*!
+	 * \brief est valide ?
+	 *
+	 * Vérifie que la coordonnées correspond bien à un point du bassin versant.
+	 * \param p : paramètres du programme et du bassin versant.
+	 * \return true si elle est située dans le bassin versant, false sinon.
+	 *
+	 */
+
+	bool isValid (Parameters * p)
+	{
+		return (_line>=0 && _line <p->_linesNumber && _column>=0 && _column < p->_columnsNumber) ;
+	}
+
+	/*!
+	 * \brief est sur la même ligne ?
+	 *
+	 * Vérifie que si les lignes sont identiques.
+	 * \param line : numéro de la ligne.
+	 * \return true si elles sont identiques, false sinon.
+	 *
+	 */
+
+	bool isSameLine(short line) const
+	{
+		return (_line == line);
+	}
+
+	/*!
+	 * \brief est sur la même colonne ?
+	 *
+	 * Vérifie que si les colonnes sont identiques.
+	 * \param column : numéro de la colonne.
+	 * \return true si elles sont identiques, false sinon.
+	 *
+	 */
+	bool isSameColumn(short column) const
+	{
+		return (_column == column);
+	}
+
+	/*!
+	 * \brief est sur la même ligne ?
+	 *
+	 * Vérifie que si les lignes sont identiques.
+	 * \param c : Coordonnées à tester.
+	 * \return true si elles sont identiques, false sinon.
+	 *
+	 */
+
+	bool isSameLine(const Coordinates & c) const
+	{
+		return (_line == c.getLine());
+	}
+
+	/*!
+	 * \brief est sur la même colonne ?
+	 *
+	 * Vérifie que si les colonnes sont identiques.
+	 * \param c : Coordonnées à tester.
+	 * \return true si elles sont identiques, false sinon.
+	 *
+	 */
+
+	bool isSameColumn(const Coordinates & c) const
+	{
+		return (_column == c.getColumn());
+	}
+
+	/*!
+	 * \brief est sur le contour ?
+	 *
+	 * Vérifie si la coordonnées se situe sur le contour du bassin versant.
+	 * \param p : paramètres du programme et du bassin versant.
+	 * \return true si elle est située sur le contour du bassin versant, false sinon.
+	 *
+	 */
+	bool isOnShore(const Parameters * p) const
+	{
+		if (_line == 0)
+			return true;
+		else if( _column == 0)
+			return true;
+		else if(_line == p->_linesNumber - 1)
+			return true;
+		else if (_column == p->_columnsNumber - 1)
+			return true;
+		else
+			return false;
+	}
+
+	/*!
+	 * \brief Envoyer vers fichier binaire
+	 *
+	 * Écrit l'objet dans un fichier binaire.
+	 * \param file : fichier ou écrire les données.
+	 * \return void.
+	 *
+	 */
+
+
+	void toBinaryFile(std::ofstream & file)
+	{
+		file.write(reinterpret_cast<char *>(&_line),sizeof(short));
+		file.write(reinterpret_cast<char *>(&_column),sizeof(short));
+	}
+
+};
+
+#endif /* COORDINATES_H_ */

+ 193 - 0
src/tests/corsen/lib/Corsen.cpp

@@ -0,0 +1,193 @@
+/*!
+ * \file Corsen.cpp
+ * \brief Charge les différents fichiers en mémoire et lance la
+ * génération du graphe.
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ */
+
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "Corsen.hpp"
+
+int Coordinates::_columnsNumber = 0;
+
+Corsen::Corsen() : _graph()
+{
+    _pfs = NULL;
+    _efs = NULL;
+    _ofs = NULL;
+    _gfs = NULL;
+    _lfs = NULL;
+    _sfs = NULL;
+    _dfs = NULL;
+    _elevationMatrixBv = NULL;
+    _outlet = NULL;
+    _soilMatrix = NULL;
+    _gradientMatrix = NULL;
+    _elevationMatrix = NULL;
+    _outlets = NULL;
+    _param = NULL;
+    _layers = NULL;
+}
+
+void Corsen::read(std::vector < std::string* > & files,
+                  std::string& absolutePath) throw (FileNotFound, ReadError,
+                                                    InvalidFileFormat,
+                                                    std::invalid_argument)
+{
+    std::stringstream ss;
+
+    _pfs = new ParametersFileStream(*files.at(0), *files.at(1));
+    _efs = new ElevationFileStream(*files.at(2));
+    _ofs = new OutletFileStream(*files.at(3));
+    _gfs = new SlopeFileStream(*files.at(4));
+    _dfs = new DrainFileStream<corsenContainers::vecS, float>(*files.at(4));
+
+    ContextData * ctxtD = ContextData::getInstance();
+
+    ContextFileReader::read((*files.at(5)).c_str(), ctxtD->_numberDays,
+                            ctxtD->_simulationStartDate,
+                            ctxtD->_outletsCoordinates);
+    _sfs = new SoilFileStream(absolutePath + ctxtD->_soilFileName);
+
+    _layers = new std::vector<Layer>();
+    _layers->push_back(Layer(std::string("Reseau Hydrographique"), 0, 0,
+                             RESEAU_HYDRO, false));
+
+    _param = _pfs->read();
+    Coordinates::_columnsNumber = _param->_columnsNumber;
+
+    _soilMatrix = _sfs->read();
+    _gradientMatrix = _gfs->read();
+    _elevationMatrix = _efs->read();
+    _outlets = _ofs->read();
+
+    int layerNumber = Layer::find(*_layers, RESEAU_HYDRO);
+
+    if(layerNumber == -1)
+        throw std::invalid_argument(
+            "Impossible de trouver l'élément dans le tableau de couches");
+
+    ss << *files.at(6) << layerNumber;
+    _lfs = new LayersFileStream(ss.str(), _param);
+    _layers->at(layerNumber).setData(_lfs->read());
+}
+
+void Corsen::buildGraph()
+{
+    Coordinates c(ContextData::getInstance()->_outletsCoordinates[0].line, ContextData::getInstance()->_outletsCoordinates[0].column);
+    for(std::list<Outlet *>::const_iterator it = _outlets->begin(); it!=_outlets->end();it++)
+    {
+        if((*it)->getCoord() == c)
+        {
+            _outlet = *it;
+            _outlet->setBrother(NULL);
+            break;
+        }
+        _outlet = (*it)->searchChildNode(c);
+        if (_outlet != NULL)
+        {
+            _outlet->setBrother(NULL);
+            break;
+        }
+    }
+
+    _layers->at(Layer::find(*_layers, RESEAU_HYDRO)).matbiton(_outlet->getCoord(), _param);
+
+    _efs->write(*_elevationMatrix, std::string(".sav"));
+    std::stack<Node *> stack;
+
+    stack.push(_outlet);
+    _elevationMatrixBv = new std::vector<float>(_elevationMatrix->size());
+
+    while (not stack.empty())
+    {
+        Node * s = stack.top();
+        unsigned int index = s->getCoord().getLine() * _param->_columnsNumber + s->getCoord().getColumn();
+
+        _elevationMatrixBv->at(index) = _elevationMatrix->at(index);
+        stack.pop();
+        if (s->getBrother())
+            stack.push(s->getBrother());
+        if (s->getChild())
+            stack.push(s->getChild());
+    }
+
+    _graph.build(_elevationMatrixBv, _param);
+}
+
+void Corsen::display()
+{
+    std::cout<<"Les paramètres du programme sont :"<<_param->toString()<<std::endl;
+    std::cout<<"Liste d'adjacence :"<<std::endl;
+    _graph.display();
+#ifdef DEBUG
+    std::cout<<"Tableau de couches :"<<std::endl;
+    for(std::vector<Layer>::const_iterator it = _layers->begin(); it!=_layers->end(); it++)
+        it->display(_param);
+#endif
+
+}
+
+Corsen::~Corsen()
+{
+    if(_outlets !=NULL)
+    {
+        for(std::list<Outlet *>::iterator it = _outlets->begin(); it!=_outlets->end(); it++)
+        {
+            delete (*it);
+            *it = NULL;
+        }
+    }
+
+    if(_soilMatrix != NULL)
+        delete _soilMatrix;
+    if(_gradientMatrix !=NULL)
+        delete _gradientMatrix;
+    if(_param !=NULL)
+        delete _param;
+    if(_outlets !=NULL)
+        delete _outlets;
+    if(_elevationMatrix !=NULL)
+        delete _elevationMatrix;
+    if(_pfs != NULL)
+        delete _pfs;
+    if(_efs != NULL)
+        delete _efs;
+    if(_ofs != NULL)
+        delete _ofs;
+    if(_gfs != NULL)
+        delete _gfs;
+    if(_sfs != NULL)
+        delete _sfs;
+    if(_lfs != NULL)
+        delete _lfs;
+    if(_layers != NULL)
+        delete _layers;
+    if(_elevationMatrixBv != NULL)
+        delete _elevationMatrixBv;
+    if(_dfs != NULL)
+        delete _dfs;
+    ContextData::kill();
+#ifdef DEBUG
+    std::cout<<"destruction achevée \n";
+#endif
+}

+ 157 - 0
src/tests/corsen/lib/Corsen.hpp

@@ -0,0 +1,157 @@
+/*!
+ * \file Corsen.h
+ * \brief Charge les différents fichiers en mémoire et lance la génération du graphe.
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+#ifndef CORSEN_H_
+#define CORSEN_H_
+#define BOOST_TEST_DYN_LINK
+
+#include <fstream>
+#include <sstream>
+#include <cstdio>
+#include <stack>
+#include <boost/foreach.hpp>
+#include "ElevationFileStream.h"
+#include "ParametersFileStream.h"
+#include "LayersFileStream.h"
+#include "OutletFileStream.h"
+#include "SlopeFileStream.h"
+#include "SoilFileStream.h"
+#include "DrainFileStream.h"
+#include "LayersTextFileStream.h"
+#include "ContextFileReader.h"
+#include "ContextData.h"
+#include "Constantes.h"
+#include "Functions.h"
+#include "Graph.hpp"
+
+/*! \class Corsen
+ * \brief est la classe centrale de la bibliothèque.
+ *
+ *  La classe gère la lecture, l'ecriture des différents fichiers de données
+ *  pour un bassin versant. Elle génère le boost graph correspondant aux
+ *  données.
+ */
+
+class Corsen
+{
+public:
+  /*!
+   *  \brief Constructeur
+   *
+   *  Constructeur de la classe Corsen.
+   */
+  Corsen();
+
+  /*!
+   *  \brief Lecture
+   *
+   *  Lecture des fichiers de données du bassin versant.
+   *
+   *  \param files : liste des fichiers à lire.
+   *  \param absolutePath : emplacement des fichiers à lire.
+   */
+  void read(std::vector<std::string* >& files,
+	    std::string& absolutePath) throw (FileNotFound, ReadError,
+					      InvalidFileFormat,
+					      std::invalid_argument);
+
+  /*!
+   *  \brief Construire graphe
+   *
+   *	génère le boostGraph
+   */
+  void buildGraph();
+
+  /*!
+   *  \brief Affichage
+   *
+   *  Affiche le contenu des attributs.
+   */
+  void display();
+
+  const std::vector<float> * getElevationMatrix() const
+  {
+    return _elevationMatrix;
+  }
+
+  const Graph& getGraph() const {
+    return _graph;
+  }
+
+  const std::vector<Layer> * getLayers() const {
+    return _layers;
+  }
+
+  const std::list<Outlet*> * getOutlets() const {
+    return _outlets;
+  }
+
+  const Parameters * getParam() const {
+    return _param;
+  }
+
+  const Node * getExutoire() const {
+    return _outlet;
+  }
+
+  const std::vector<float> * getGradientMatrix() const {
+    return _gradientMatrix;
+  }
+
+  const std::vector<float> * getSoilMatrix() const {
+    return _soilMatrix;
+  }
+
+  const std::vector<float> * getElevationMatrixBv() const {
+    return _elevationMatrixBv;
+  }
+
+  /*!
+   *  \brief Destructeur
+   *
+   *  Destructeur de la classe Corsen
+   */
+  virtual ~Corsen();
+
+private:
+
+	Graph _graph;
+	ParametersFileStream * _pfs; /*!< Flux fichier paramètres */
+	ElevationFileStream * _efs; /*!< Flux fichier des données d'altitudes */
+	OutletFileStream * _ofs; /*!< Flux fichier des arbres de drainage */
+	SlopeFileStream * _gfs; /*!< Flux fichier des pentes */
+	SoilFileStream * _sfs;
+	LayersFileStream * _lfs; /*!< Flux fichier des couches*/
+	DrainFileStream<corsenContainers::vecS, float> * _dfs;
+	std::vector<float> * _gradientMatrix ;/*!< données pentes */
+	std::vector<float> * _soilMatrix;
+	std::vector<float> * _elevationMatrix;/*!< données altitudes */
+	std::list<Outlet *> * _outlets;/*!< liste des exutoires */
+	std::vector<Layer> *  _layers; /*!< liste des couches */
+	Parameters * _param; /*!< paramètres du programme */
+	Node * _outlet; /*!< noeud exutoire */
+	std::vector<float> * _elevationMatrixBv;
+};
+
+#endif /* CORSEN_H_ */

+ 126 - 0
src/tests/corsen/lib/DrainFileStream.h

@@ -0,0 +1,126 @@
+/*!
+ * \file DrainFileStream.h
+ * \brief Flux binaire sur fichier contenant toutes les données de l'arborescence de MntSurf.
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 13 juin 2013
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef DRAINFILESTREAM_H_
+#define DRAINFILESTREAM_H_
+
+#include "FileStream.h"
+#include "Coordinates.h"
+#include <typeinfo>
+#include <vector>
+
+/*! \class DrainFileStream
+ *
+ * \brief gère un flux binaire en lecture et écriture sur le fichier de drain.
+ */
+
+
+template <class X, class Y, class T = FileStream<X,Y> >
+class DrainFileStream : public T
+{
+public :
+	DrainFileStream(std::string & filePath) : T(filePath)
+	{
+
+
+	}
+	~DrainFileStream() {}
+
+	typename T::returnType * read() const throw (FileNotFound, ReadError, InvalidFileFormat, std::bad_alloc)
+	{
+		std::ifstream drainFile(T::_filePath.c_str(),std::ios::binary);
+
+		if(not drainFile)
+			throw FileNotFound("Exception opening file\n: "+ T:: _filePath);
+
+		if(T::_format.compare("") == 0)
+			return readStandardFormat(drainFile);
+
+		throw InvalidFileFormat("Exception Unknown file format "+T::_filePath+"\n");
+
+	}
+
+	void write(const typename T::returnType & object, const std::string & extension) const
+	{
+	/*	std::string filePath(_filePath);
+		filePath.append(extension);
+		std::ofstream drainFile(filePath.c_str(), std::ios::trunc);
+
+		if(not drainFile)
+			throw FileNotFound("Exception opening file "+ filePath +"\n");
+
+		if(_format.compare("") == 0)
+			return writeStandardFormat(drainFile, object);
+
+		throw InvalidFileFormat("Exception Unknown file format "+ filePath +"\n");
+*/
+	}
+
+private :
+
+	typename T::returnType * readStandardFormat(std::ifstream & file) const throw(ReadError, std::bad_alloc)
+	{
+		try
+		{
+			typename T::returnType * tmpVec = new  typename T::returnType();
+			Y tmp;
+			do
+			{
+				file.read(reinterpret_cast<char *>(&tmp), sizeof(Y));
+				if(not file.eof() and not file.bad())
+					tmpVec->push_back(tmp);
+
+			}
+			while(file.good());
+			if(file.bad() or not file.eof())
+			{
+				file.close();
+				throw ReadError("Exception Reading data"+ T::_filePath);
+			}
+			file.close();
+			return tmpVec;
+		}
+		catch(std::bad_alloc & e)
+		{
+			throw;
+		}
+	}
+
+
+	void writeStandardFormat(std::ofstream & file, const typename T::returnType & object) const
+	{
+		Y tmp;
+		for(int i  = 0; i < object.size() ; i++)
+		{
+			tmp = object.at(i);
+			file.write(reinterpret_cast<char *>(&tmp), sizeof(Y));
+		}
+		file.close();
+	}
+};
+
+
+#endif /* DRAINFILESTREAM_H_ */

+ 141 - 0
src/tests/corsen/lib/ElevationFileStream.h

@@ -0,0 +1,141 @@
+/*!
+ * \file ElevationFileStream.h
+ * \brief Flux sur le fichier d'altitudes.
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 11 juin 2013
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef ELEVATIONFILESTREAM_H_
+#define ELEVATIONFILESTREAM_H_
+
+#include "FileStream.h"
+
+/*! \class ElevationFileStream
+ *
+ * \brief gère un flux en lecture et écriture  sur le fichier d'altitudes.
+ */
+
+class ElevationFileStream: public FileStream<corsenContainers::vecS,float>
+{
+public :
+	ElevationFileStream(const std::string & filePath) : FileStream<corsenContainers::vecS,float>(filePath) {}
+	virtual ~ElevationFileStream(){}
+
+	returnType * read() const throw (FileNotFound, ReadError, InvalidFileFormat, std::bad_alloc)
+	{
+		std::ifstream altFile(_filePath.c_str(),std::ios::binary);
+		if(not altFile)
+			throw FileNotFound("Exception opening file\n "+_filePath);
+
+		if(_format.compare("") == 0)
+			return readStandardFormat(altFile);
+
+		throw InvalidFileFormat("Exception Unknown file format "+_filePath+"\n");
+	}
+
+	returnType * read(const std::string & extension) const throw (FileNotFound, ReadError, InvalidFileFormat, std::bad_alloc)
+	{
+		std::string filePath(_filePath);
+		filePath.append(extension);
+
+		std::ifstream altFile(filePath.c_str(),std::ios::binary);
+		if(not altFile)
+			throw FileNotFound("Exception opening file "+filePath+"\n");
+
+		if(extension.compare(".sav") == 0)
+			return readStandardFormat(altFile);
+
+		throw InvalidFileFormat("Exception Unknown file format "+filePath+"\n");
+	}
+
+
+	void write(const returnType & object, const std::string & extension) const throw (FileNotFound, InvalidFileFormat)
+	{
+		std::string filePath(_filePath);
+		filePath.append(extension);
+		std::ofstream altFile(filePath.c_str(), std::ios::trunc);
+
+		if(not altFile)
+			throw FileNotFound("Exception opening file "+ filePath +"\n");
+
+		if(_format.compare("") == 0)
+			return writeStandardFormat(altFile, object);
+
+		throw InvalidFileFormat("Exception Unknown file format "+ filePath +"\n");
+	}
+
+private :
+	returnType * readStandardFormat(std::ifstream & file) const throw (ReadError, std::bad_alloc)
+	{
+		// get length of file:
+		file.seekg (0, file.end);
+		int length = file.tellg();
+		file.seekg (0, file.beg);
+
+		try
+		{
+			returnType * tmpVec = new returnType();
+			/* double tailleeffective = static_cast<double>(length) / static_cast<double>(sizeof(float)); */
+#ifdef DEBUG
+			std::cout<<"------ ElevationFileStream --------- \n";
+			std::cout<<"Taille en octets : "<<length <<"\nTaille du type de retour : "<<sizeof(float)<<"\nTaille du vec d'élévation : "<<length/sizeof(returnType)
+										<<"\nTaille effective : "<< tailleeffective <<std::endl;
+			std::cout<<"------ ElevationFileStream --------- \n";
+#endif
+			float tmp;
+			do
+			{
+				file.read(reinterpret_cast<char *>(&tmp), sizeof(float));
+				if(not file.eof() and not file.bad())
+					tmpVec->push_back(tmp);
+
+			}
+			while(file.good());
+			if(file.bad() or not file.eof())
+			{
+				file.close();
+				throw ReadError("Exception Reading data"+ _filePath);
+			}
+			file.close();
+			return tmpVec;
+		}
+		catch(std::bad_alloc & e)
+		{
+			throw;
+		}
+
+	}
+
+	void writeStandardFormat(std::ofstream & file, const returnType & object) const throw (std::exception)
+	{
+		float tmp;
+		for(returnType::const_iterator it = object.begin(); it!= object.end() ; ++it)
+		{
+			tmp = *it;
+			file.write(reinterpret_cast<char *>(&tmp), sizeof(float));
+		}
+		file.close();
+	}
+};
+
+
+#endif /* ELEVATIONFILESTREAM_H_ */

+ 77 - 0
src/tests/corsen/lib/Exception.h

@@ -0,0 +1,77 @@
+/*!
+ * \file Exception.h
+ * \brief Exceptions du programme Corsen.
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 4 juin 2013
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef EXCEPTION_H_
+#define EXCEPTION_H_
+
+#include <iostream>
+#include <string>
+#include <stdexcept>
+
+/*! \class FileNotFound
+ * \brief Exception - Fichier non trouvé.
+ *
+ *   Déclenché par le programme pour vous signifier que le fichier recherché n'a pas été trouvé.
+ */
+
+class FileNotFound : public std::runtime_error
+{
+public:
+	FileNotFound(const std::string& argv = std::string()) :
+        std::runtime_error(argv)
+    { }
+};
+
+/*! \class ReadError
+ * \brief Exception - Erreur de lecture.
+ *
+ * Déclenché par le programme pour vous signifier qu'une erreur de lecture dans un fichier a été rencontrée.
+ */
+
+class ReadError : public std::runtime_error
+{
+public :
+	ReadError(const std::string& argv = std::string()):
+		std::runtime_error(argv)
+	{ }
+};
+
+/*! \class InvalidFileFormat
+ * \brief Exception - Format de fichier invalide.
+ *
+ * Déclenché par le programme pour vous signifier que le format du fichier ne peut pas être interprété par les méthodes de la bibliothèque.
+ */
+
+class InvalidFileFormat : public std::runtime_error
+{
+public :
+	InvalidFileFormat(const std::string& argv = std::string()):
+		std::runtime_error(argv)
+	{ }
+};
+
+
+#endif /* EXCEPTION_H_ */

+ 209 - 0
src/tests/corsen/lib/FileStream.h

@@ -0,0 +1,209 @@
+/*!
+ * \file FileStream.h
+ * \brief modèle de flux sur fichiers applicable à n'importe quelle classe.
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 11 juin 2013
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef FILESTREAM_H_
+#define FILESTREAM_H_
+#include <iostream>
+#include <fstream>
+#include <vector>
+#include <boost/algorithm/string.hpp>
+#include "Exception.h"
+#include "Constantes.h"
+
+
+namespace corsenContainers
+{
+struct vecS{};
+struct listS{};
+struct CType {};
+template <class Selector, class ValueType>
+struct container_gen { };
+
+template <class ValueType>
+struct container_gen<vecS, ValueType> {
+	typedef std::vector<ValueType> type;
+};
+template <class ValueType>
+struct container_gen<CType, ValueType> {
+	typedef ValueType type;
+};
+template <class ValueType>
+struct container_gen<listS, ValueType> {
+	typedef std::list<ValueType> type;
+};
+}
+
+template<class container, class valuetype>
+
+/*! \class FileStream
+ *
+ * \brief est une classe abstraite, elle sert de modèle aux différents lecteurs de fichiers.
+ *
+ *  La classe gère la lecture et l'ecriture au format standard.
+ */
+
+class FileStream
+{
+protected :
+	std::string _filePath; /*!< chemin du fichier*/
+	std::string _format; /*!< format du fichier*/
+public :
+
+	/*!
+	 *  \brief Constructeur
+	 *
+	 *  Constructeur de la classe FileReader, analyse le chemin du fichier afin de déterminer son format.
+	 *
+	 *  \param filePath : chemin du fichier.
+	 *  \return void
+	 */
+
+	FileStream(const std::string & filePath)
+{
+		_filePath = filePath;
+		_format = findFormat(filePath);
+}
+	typedef typename corsenContainers::container_gen<container,valuetype>::type returnType;
+
+	/*!
+	 *  \brief Lecture
+	 *
+	 *  Analyse le format du fichier et lance la méthode de lecture adaptée.
+	 *
+	 *  \return un objet contenant les informations lues.
+	 */
+	virtual returnType * read() const = 0;
+
+	/*!
+	 *  \brief écriture
+	 *
+	 *  Analyse le format du fichier et lance la méthode d'écriture adaptée.
+	 *
+	 *   \param object : objet contenant les informations à écrire
+	 *   \param extension : format du fichier pour la sauvegarde
+	 *   \return void
+	 */
+
+	virtual void write(const returnType & object, const std::string & extension) const = 0;
+
+	/*!
+	 *  \brief Destructeur
+	 *
+	 *  Destructeur de la classe FileStream
+	 */
+	virtual ~FileStream(){}
+
+	const std::string& getFilePath() const
+	{
+		return _filePath;
+	}
+
+	void setFilePath(const std::string& filePath)
+	{
+		_filePath = filePath;
+		_format = findFormat(filePath);
+	}
+
+protected :
+
+	const std::string findFormat(const std::string & filePath) const
+	{
+		std::string format("");
+
+		std::vector<std::string>Vec;
+		std::string reversefilePath(filePath.rbegin(), filePath.rend());
+		boost::split(Vec,reversefilePath,boost::is_any_of("\\/"));
+		if(Vec.size() !=0)
+		{
+			std::string filePathEnd(Vec.at(0).rbegin(),Vec.at(0).rend());
+			Vec.clear();
+			boost::split(Vec, filePathEnd, boost::is_any_of("."));
+			if(isHiddenFile(filePathEnd))
+			{
+				for(unsigned int i = 2; i<Vec.size();i++)
+					format+="."+Vec.at(i);
+			}
+			else
+			{
+				for(unsigned int i = 1; i<Vec.size();i++)
+					format+="."+Vec.at(i);
+			}
+		}
+		else
+		{
+			boost::split(Vec, _filePath, boost::is_any_of("."));
+			if(isHiddenFile(_filePath))
+			{
+				for(unsigned int i = 2; i<Vec.size();i++)
+					format+="."+Vec.at(i);
+			}
+			else
+			{
+				for(unsigned int i = 1; i<Vec.size();i++)
+					format+="."+Vec.at(i);
+			}
+		}
+
+		return format;
+	}
+
+	bool isHiddenFile(const std::string & filePath) const
+	{
+		if(filePath.substr(0,1).compare(".") == 0)
+			return true;
+
+		return false;
+	}
+
+private:
+
+
+	/*!
+	 *  \brief Lecture au format standard
+	 *
+	 *  Lecture des données du fichier selon un formatage particulier .
+	 *
+	 * \param file fichier dans lequel lire les données.
+	 *  \return l'objet contenant les informations lues.
+	 */
+
+	virtual returnType * readStandardFormat(std::ifstream & file) const = 0;
+	/*!
+	 *  \brief écriture au format standard
+	 *
+	 *  Écriture des données dans le fichier selon un formatage particulier.
+	 *
+	 *  \param file fichier dans lequel écrire les données.
+	 *  \param object l'objet contenant les informations à écrire.
+	 *  \return void
+	 */
+
+	virtual void writeStandardFormat(std::ofstream & file, const returnType & object) const = 0;
+
+};
+
+
+#endif /* FILESTREAM_H_ */

+ 173 - 0
src/tests/corsen/lib/Functions.cpp

@@ -0,0 +1,173 @@
+/*!
+ * \file Functions.cpp
+ * \brief
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <ctype.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include "Functions.h"
+
+#define COMMENTC     '#'
+
+char * programName;
+char * workingDirectory;
+
+void Functions::fatalError(const char* s, int erreurcode)
+{
+     fprintf( stderr,"Erreur fatale: %s > arret de %s\n", s?s:"", programName);
+
+     /*  avant de retourner  dans le repertoire d'ou TNT est appele */
+     if (workingDirectory)
+          chdir(workingDirectory);
+     exit(erreurcode);
+}
+
+
+//void Functions::handleError(const char* s)
+//{
+//     switch(errno) {
+//     case 0:  /* il n'y a pas d'erreur,   */
+//          fprintf(stderr,"%s: CECI NE DEVRAIT PAS ARRIVER il n'y a pas d'erreur!!\n",s?s:"");
+//          break;
+//
+//     case EPERM:  /*non super" utilisateur */
+//          fprintf( stderr,"%s: acces refuse: il faut etre Super Utilisateur pour ce faire!\n",s?s:"");
+//          break;
+//
+//     case 	ENOENT:		/* No such file or directory	*/
+//          fprintf( stderr," %s: Fichier/Repertoire inexistant\n", s?s:"");
+//          break;
+//
+//     case 	ENOMEM:		/* No enough memory 	*/
+//          fatalError("pas assez de memoire", errno);
+//          break;
+//
+//     case 	ENXIO:	/* No such device or address */
+//          fprintf( stderr,"%s: adresse/peripherique inexistant\n", s?s:"");
+//          break;
+//
+//     case 	EAGAIN : /* Resource temporarily unavailable*/
+//          fprintf( stderr,"%s: ressources momentanement indisponibles\n",s?s:"");
+//          break;
+//
+//     case 	EACCES : /* Permission denied	*/
+//          fprintf( stderr,"%s: acces refuse, vos droits sont limites\n", s?s:"");
+//          break;
+//
+//     case 	EEXIST :  /* File exists	*/
+//          fprintf( stderr,"%s : fichier/repertoire deja existant\n",s?s:"");
+//          break;
+//
+//     case 	ENODEV : /* No such device	*/
+//          fprintf( stderr,"%s: peripherique inexistant\n", s?s:"");
+//          break;
+//
+//     case 	ENOTDIR: /* Not a directory	*/
+//          fprintf( stderr,"%s: n'est pas un repertoire\n", s?s:"");
+//          break;
+//
+//     case 	EISDIR : /* Is a directory	*/
+//          fprintf( stderr,"%s: est un repertoire\n", s?s:"");
+//          break;
+//
+//     case 	EINVAL : /* Invalid argument	*/
+//          fprintf( stderr,"%s : valeur de l'argument passe  inacceptable\n",s?s:"");
+//          break;
+//
+//     case 	ENOTTY : /* Inappropriate ioctl for device */
+//          fprintf( stderr,"%s : fonction inadaptee pour ce peripherique\n",s?s:"");
+//          break;
+//
+//     case 	EFBIG  : /* File too large	*/
+//          fprintf( stderr,"%s : fichier trop grand\n",s?s:"");
+//          break;
+//
+//     case 	ENOSPC : /* No space left on device	*/
+//          fprintf( stderr,"%s: plus de place disponible sur le peripherique\n",s?s:"");
+//          break;
+//
+//     case 	EROFS  : /* Read only file system	*/
+//          fprintf( stderr,"%s : systeme de fichier monte en mode lecture seule\n",s?s:"");
+//          break;
+//
+//     case 	EDOM   : /* Math arg out of domain of func*/
+//          fprintf(stderr,"%s: argument hors du domaine de definition fonc. math\n",s?s:"");
+//          break;
+//
+//     case 	ERANGE : /* Math result not representable*/
+//          fprintf( stderr,"%s : resultat non significatif\n",s?s:"");
+//          break;
+//
+//     case 	EOVERFLOW : /* vue too large to be stored in data type */
+//          fprintf( stderr,"%s : Resultat hors gabarit, trop grand\n",s?s:"");
+//          break;
+//
+//     default :
+//          fprintf( stderr,"Une erreur non geree par %s est survenue. errno = %d\n",programName, errno);
+//          break;
+//     }
+//}
+//
+//void Functions::ignorelf( char *s)
+//{
+//     char *p = s-1;
+//
+//     while(*++p && (*p != '\r' && *p != '\n')) {}
+//     *p ='\0';
+//}
+
+//bool Functions::isComment(char *s)
+//{
+//     char *p = s;
+//
+//     ignorelf(s);   /* ignore le caractere fin-de-ligne LF ou CR*/
+//     /* ignore les espaces d'en-tete */
+//     while(*p and isspace(*p)) {
+//          ++p;
+//     }
+//
+//     return *p == COMMENTC or *p == '\0';
+//}
+
+//FILE* Functions::openFile(const char* nom, const char* mode)
+//{
+//     FILE * fp;
+//
+//     if ((fp = fopen (nom,mode)) == NULL) {
+//          handleError(nom);
+//          fatalError(nom, errno);
+//     }
+//     return(fp);
+//}
+
+//bool is_reseau(int lig, int col)
+//{
+//     return getmatbit(Mcouche[numero_couche_riviere], lig, col);
+//}
+
+
+
+

+ 86 - 0
src/tests/corsen/lib/Functions.h

@@ -0,0 +1,86 @@
+/*!
+ * \file Functions.h
+ * \brief
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef FUNCTIONS_H_
+#define FUNCTIONS_H_
+
+#include <stdio.h>
+#include "Parameters.h"
+#include "Coordinates.h"
+
+class Functions {
+
+public :
+
+
+	/*!
+	 *  \brief Retourner un bit d'un entier.
+	 *
+	 * \param n : Entier ou chercher le bit .
+	 * \param b : Nombre de décalage binaire à effectuer.
+	 * \return la valeur du bit b du nombre n.
+	 */
+
+	static int getvalbit (int n, unsigned b)
+	{
+		return ((n>>b) & 1) ;
+	}
+
+	/*!
+	 *  \brief Affecte la valeur 1 au bit b du nombre pointé par n.
+	 *
+	 * \param n : Entier à modifier .
+	 * \param b : Nombre de décalage binaire à effectuer.
+	 * \return void.
+	 */
+
+	static void valbiton (int * n, unsigned b)
+	{
+		*n |= 1<<b ;
+	}
+
+	/*!
+	 *  \brief Affecte la valeur 0 au bit b du nombre pointé par n.
+	 *
+	 * \param n : Entier à modifier .
+	 * \param b : Nombre de décalage binaire à effectuer.
+	 * \return void.
+	 */
+
+	static void valbitoff (int *n, unsigned b)
+	{
+		*n &= ~(1<<b) ;
+	}
+
+	static void fatalError(const char* s, int erreurcode);
+	//static void ignorelf(char *s);
+	//static bool isComment(char *s);
+	//static bool isNetwork(int lig, int col);
+	//static FILE* openFile(const char *nom, const char *mode);
+	//static void handleError(const char* s);
+
+};
+
+#endif /* FUNCTIONS_H_ */

+ 230 - 0
src/tests/corsen/lib/Graph.cpp

@@ -0,0 +1,230 @@
+/**
+ *
+ * \file Graph.cpp
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 30 mai 2013
+ * \brief Générateur du graphe représentant un bassin versant.
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "Graph.hpp"
+
+Graph::Graph(): _isolatedVertices(0), _param(NULL)
+{ }
+
+void Graph::build(std::vector<float> * elevationMatrix, Parameters * p)
+{
+    _param = p;
+
+    int counter = 0;
+    for (int i = 0 ; i < p->_linesNumber; i++) {
+        for (int j = 0 ; j < p->_columnsNumber ; j++) {
+            if (elevationMatrix->at(i*p->_columnsNumber+j) > ALTMER) {
+                _vertices[i * p->_columnsNumber + j] =
+                    Vertex(i * p->_columnsNumber + j,
+                           Coordinates(i, j),
+                           elevationMatrix->at(i * p->_columnsNumber + j));
+                counter++;
+            }
+        }
+    }
+
+    std::vector < Vertex* > tmpVertices;
+
+    for(std::map < int, Vertex >::iterator it = _vertices.begin();
+        it!=_vertices.end(); it++) {
+        for (int i = it->second.getCoord().getLine() - 1 ;
+             i <= it->second.getCoord().getLine() +1 ; i++) {
+            for (int j = it->second.getCoord().getColumn() - 1 ;
+                 j <= it->second.getCoord().getColumn()  + 1 ; j++) {
+                if (Coordinates(i,j).isValid(p) &&
+                    (not it->second.getCoord().isSameLine(i) ||
+                     not it->second.getCoord().isSameColumn(j))) {
+                    tmpVertices.push_back(
+                        &_vertices[i * p->_columnsNumber + j]);
+                }
+            }
+        }
+        it->second.setNeighbours(tmpVertices);
+        tmpVertices.clear();
+    }
+    buildMesh();
+    buildTablelandsMeshes() ;
+}
+
+void Graph::display()
+{
+    //const char* name = "ABCDEF";
+    int tablelandsCounter = 0;
+
+    //std::cout << "vertex set: ";
+    //boost::print_vertices(_gno, name);
+    //std::cout << std::endl;
+    //
+    //std::cout << "edge set: ";
+    //boost::print_edges(_gno, name);
+    //std::cout << std::endl;
+    //
+    //std::cout << "incident edges: " << std::endl;
+    //boost::print_graph(_gno, name);
+    //std::cout << std::endl;
+
+    for (std::map < int, Vertex >::iterator it = _vertices.begin();
+         it != _vertices.end(); it++) {
+        if (it->second.getMp() == 'v')
+            tablelandsCounter++ ;
+    }
+
+    DirectedGraph::vertex_iterator beginV, endV;
+    DirectedGraph::adjacency_iterator beginA, endA;
+
+    std::cout << "edge set: \n";
+    boost::tie(beginV, endV) = boost::vertices(_go);
+    for(; beginV!=endV; beginV++)
+    {
+        std::cout<<*beginV<<" -> ";
+        boost::tie(beginA,endA) = boost::adjacent_vertices(*beginV,_go);
+        for(; beginA!=endA; beginA++)
+        {
+            std::cout<<*beginA<<" ";
+        }
+        std::cout<<"\n";
+    }
+
+    std::cout<<"vertices number : "<<boost::num_vertices(_go)<<"\n";
+    std::cout<<"edges number : "<<boost::num_edges(_go)<<"\n";
+    std::cout<<"meshes number of tableland type :"<<tablelandsCounter<<std::endl;
+}
+
+void Graph::buildMesh()
+{
+    std::vector<Vertex *>tmpNeighbours;
+
+    for(std::map<int,Vertex>::iterator it = _vertices.begin(); it!=_vertices.end();it++)
+    {
+        if(it->second.getElevation() > ALTMER)
+        {
+            if(it->second.sigma(Vertex::elevation) <= EPSALT && not it->second.getCoord().isOnShore(_param) && not it->second.isOnSeaside())
+                it->second.setMp('p');
+            else
+            {
+                createVertex(it->second);
+                tmpNeighbours = it->second.getNeighbours();
+                for(std::vector<Vertex *>::iterator itNeighbours = tmpNeighbours.begin(); itNeighbours != tmpNeighbours.end(); itNeighbours++)
+                {
+                    if ((*itNeighbours)->getElevation() > ALTMER && ((it->second.getElevation() - (*itNeighbours)->getElevation()) > EPSALT))
+                    {
+                        createVertex(**itNeighbours);
+                        createEdge((*itNeighbours), it->second,  (*itNeighbours)->tanBxL(&it->second, Vertex::elevation) / it->second.sigma(Vertex::elevation)) ;
+                    }
+                }
+            }
+        }
+    }
+}
+
+void Graph::buildTablelandsMeshes()
+{
+    int nbi;
+
+    for(std::map<int, Vertex>::iterator it = _vertices.begin(); it!=_vertices.end(); it++)
+    {
+        if (it->second.getMp() == 'p')
+        {
+            it->second.setMp('v');
+            nbi = 0;
+            searchOutlet (it->second, nbi) ;
+            // if ( nbi == 0)
+                // std::cerr<<"\n"<<_isolatedVertices++ <<" Impossible de sortir du plateau "<<it->second.toString()<<"\t"<<" and "<< nbi <<"issue(s)."<<std::endl;
+
+            computeGeodesic() ;
+            addTablelandsEdges() ;
+            for(std::vector<Vertex *>::iterator it = _tablelandVertices.begin(); it!=_tablelandVertices.end(); it++)
+                (**it).setDerive(-999999.0);
+            _tablelandVertices.clear();
+        }
+    }
+}
+
+void Graph::searchOutlet(Vertex & m, int nbi)
+{
+    std::vector<Vertex *>tmpNeighbours = m.getNeighbours();
+
+    for(std::vector<Vertex *>::iterator itNeighbours = tmpNeighbours.begin(); itNeighbours != tmpNeighbours.end(); itNeighbours++)
+    {
+        if (fabs((**itNeighbours).getElevation() - m.getElevation()) < 0.0001)
+        {
+            if ((**itNeighbours).getMp() == 'p')
+            {
+                (**itNeighbours).setMp('v');
+                searchOutlet(**itNeighbours, nbi) ;
+            }
+            else if ((**itNeighbours).getMp() == 'n')
+            {
+                (**itNeighbours).setDerive(1.);
+                nbi++;
+                (**itNeighbours).setMp('i');
+                _tablelandVertices.push_back((*itNeighbours));
+            }
+        }
+    }
+}
+
+void Graph::computeGeodesic()
+{
+    std::vector<Vertex *>tmpNeighbours;
+    int i = 0;
+    while(_tablelandVertices.begin() + i != _tablelandVertices.end())
+    {
+        tmpNeighbours = _tablelandVertices.at(i)->getNeighbours();
+
+        for(std::vector<Vertex *>::iterator itNeighbours = tmpNeighbours.begin(); itNeighbours != tmpNeighbours.end(); itNeighbours++)
+        {
+            if ((**itNeighbours).getMp() == 'v')
+            {
+                (**itNeighbours).setDerive(_tablelandVertices.at(i)->getDerive() + 1.);
+                (**itNeighbours).setMp('g');
+                _tablelandVertices.push_back(*itNeighbours);
+            }
+        }
+        i++;
+    }
+}
+
+void Graph::addTablelandsEdges()
+{
+    std::vector<Vertex *>tmpNeighbours;
+
+    for (std::vector<Vertex *>::iterator it = _tablelandVertices.begin(); it!=_tablelandVertices.end(); ++it)
+    {
+        createVertex(**it);
+        tmpNeighbours = (**it).getNeighbours();
+
+        for(std::vector<Vertex *>::iterator itNeighbours = tmpNeighbours.begin(); itNeighbours != tmpNeighbours.end(); itNeighbours++)
+        {
+            if ((**itNeighbours).getDerive() > ALTMER && (**itNeighbours).getDerive() < (**it).getDerive())
+            {
+                createVertex(**itNeighbours);
+                createEdge((*itNeighbours), **it,  (*itNeighbours)->tanBxL(*it, Vertex::derive) / (*it)->sigma(Vertex::derive)) ;
+            }
+        }
+    }
+}

+ 200 - 0
src/tests/corsen/lib/Graph.hpp

@@ -0,0 +1,200 @@
+/**
+ *
+ * \file Graph.hpp
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 30 mai 2013
+ * \brief Générateur du graphe représentant un bassin versant.
+ */
+
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef GRAPH_HPP_
+#define GRAPH_HPP_ 1
+
+#include <iostream>
+#include <fstream>
+#include <stack>
+#include <utility>
+#include <unistd.h>
+#include <cstdio>
+#include <iterator>
+#include <list>
+#include <vector>
+#include <map>
+#include <string>
+#include <algorithm>
+#include <boost/array.hpp>
+#include <boost/format.hpp>
+#include "boost/graph/topological_sort.hpp"
+#include <boost/graph/adjacency_list.hpp>
+#include <boost/graph/graph_utility.hpp>
+#include <boost/version.hpp>
+#include <boost/graph/graph_traits.hpp>
+#include <boost/graph/graph_concepts.hpp>
+#include <boost/concept/assert.hpp>
+#include <boost/graph/adjacency_iterator.hpp>
+#include <boost/config.hpp>
+#include <boost/limits.hpp>
+#include "Constantes.h"
+#include "Vertex.h"
+#include "Exception.h"
+#include "Parameters.h"
+
+/*! \class Graph
+ * \brief représente un bassin versant sous forme de graphe.
+ *
+ *  La classe détermine le maillage du bassin versant. Pour effectuer
+ *  cela, la classe crée un objet de type boost::graph et le complète
+ *  en y ajoutant des sommets et des arcs.
+ */
+
+class Graph
+{
+public:
+
+    /*!
+     *  \brief Constructeur
+     *
+     *  initialisation de certains attributs.
+     */
+    Graph();
+
+    virtual ~Graph()
+    { }
+
+    /*!
+     *  \brief Construction du graphe.
+     *
+     *  Méthode qui crée les sommets et génère le boost::graph en fonction des
+     *  données contenues dans ceux-ci.
+     *
+     *  \param elevationMatrix : données d'altitudes du bassin versant
+     *  \param p : paramètres du programme.
+     */
+    void build(std::vector<float> * elevationMatrix, Parameters * p);
+
+    const DirectedGraph& graph() const
+    { return _go; }
+
+    /*!
+     * \brief Afficher
+     *
+     *  Affiche les sommets, les arêtes et les arêtes incidentes.
+     */
+    void display();
+
+private:
+
+    /*!
+     * \brief Créer arc.
+     *
+     * Crée un nouvel arc entre deux sommets, il sera ajouté au
+     * vecteur d'arcs du boost Graph.
+     * \param Source : arc sortant
+     * \param Dest : arc entrant
+     * \param pourcent : ratio entre le poids du sommet et la somme
+     * des poids de ses sommets voisins.
+     */
+    void createEdge(Vertex * src , Vertex & dst, float pourcent)
+    {
+        boost::add_edge(src->getBoostGraphIdentifier(),
+                        dst.getBoostGraphIdentifier(),
+                        EdgeProperties(0., 0., pourcent),_go);
+    }
+
+    /*!
+     * \brief Créer sommet.
+     *
+     * Crée un nouveau sommet si inexistant, il sera ajouté au vecteur
+     * de sommets du boost Graph.
+     *
+     */
+    void createVertex(Vertex & m)
+    {
+        if (m.getBoostGraphIdentifier() == 4294967295)
+            m.setBoostGraphIdentifier(
+                boost::add_vertex(VertexProperties(
+                                      (boost::format("p_%1%") %
+                                       (m.getIdentifier())).str(),
+                                      m.getIdentifier(),
+                                      m.getCoord()),_go));
+    }
+
+    /*!
+     * \brief Construire maillage.
+     *
+     * 	Classement des sommets du bassin versant selon leur dénivellation.
+     * 	Ajout d'arcs au graphe selon plusieurs critères :
+     * 	 - La positionnement des sommets.
+     * 	 - La dénivellation entre les sommets.
+     */
+    void buildMesh();
+
+    /*!
+     * \brief Construire maillages plateaux
+     *
+     * Ajout d'arcs au graphe selon plusieurs critères :
+     *  - Le positionnement des sommets.
+     * 	- L'absence ou la faible dénivellation entre les sommets.
+     */
+    void buildTablelandsMeshes();
+
+    /*!
+     * \brief Rechercher exutoire
+     *
+     * Ajout dans la liste les sommets dits 'exutoire' du plateau étudié.
+     *
+     */
+    void searchOutlet(Vertex & m, int nbi);
+
+    /*!
+     * \brief Calculer géodésique.
+     *
+     *  Calcule le chemin le plus court, ou l'un des plus courts
+     *  chemins s'il en existe plusieurs, entre deux sommets du bassin versant.
+     */
+
+    void computeGeodesic();
+
+    /*!
+     * \brief Ajouter des arcs au maillage plateau.
+     *
+     * Ajout d'arcs au graphe reliant les sommets entre eux selon
+     * plusieurs critères :
+     *  - Leur positionnement.
+     * 	- L'absence ou la faible dénivellation entre eux.
+     */
+
+    void addTablelandsEdges();
+
+    DirectedGraph            _go; /*!< Graphe Orienté */
+    std::map < int, Vertex > _vertices; /*!< Sommets du bassin versant */
+    std::vector < Vertex* >  _tablelandVertices; /*!< Ensemble de
+                                                  * sommets du bassin
+                                                  * versant qui une
+                                                  * fois reliés forme
+                                                  * un maillage 'plateau' */
+    int                      _isolatedVertices; /*!< Nombre de sommets sans
+                                                 * exutoire du bassin versant */
+    const Parameters*        _param; /*!< Paramètres du programme */
+};
+
+#endif /* GRAPHE_HPP_ */

+ 282 - 0
src/tests/corsen/lib/Layer.h

@@ -0,0 +1,282 @@
+/**
+ *
+ * \file Layer.h
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 3 juin 2013
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef LAYER_H_
+#define LAYER_H_
+
+#include <iostream>
+#include <fstream>
+#include <boost/lexical_cast.hpp>
+#include <boost/algorithm/string.hpp>
+#include <boost/tokenizer.hpp>
+#include "Constantes.h"
+#include "Exception.h"
+#include "Functions.h"
+
+class Layer
+{
+private :
+
+	std::string _label ;
+	int _color ;
+	int _active ;
+	int _type ;
+	bool _modified ;
+	unsigned char * _data; /*!< données sur couches */
+
+public :
+	Layer():_label(""),_color(0),_active(0),_type(0),_modified(0), _data(NULL){}
+	Layer(std::string label, int color,int active,int type, bool modified)
+	{
+		_label = label;
+		_color = color;
+		_active = active;
+		_type = type;
+		_modified = modified;
+		_data = NULL;
+	}
+
+	Layer(std::string & label, int color,int active,int type, bool modified)
+	{
+		_label = label;
+		_color = color;
+		_active = active;
+		_type = type;
+		_modified = modified;
+		_data = NULL;
+	}
+	Layer(const Layer & c)
+	{
+		_label = c.getLabel();
+		_color = c.getColor();
+		_active = c.getActive();
+		_type = c.getType();
+		_modified = c.isModified();
+		_data = c.getData();
+	}
+	/*!
+	 *
+	 * \brief Constructeur
+	 *
+	 * Constructeur avec paramètres de la classe Layer, remplit les attributs de la classe avec les données de 'ligne'.
+	 *
+	 * \param ligne : chaîne de caractères contenant des informations pour la classe
+	 * \return void
+	 */
+
+	Layer(const std::string & line)
+	{
+		_data = NULL ;
+
+		using boost::lexical_cast ;
+		using boost::bad_lexical_cast ;
+
+		boost::char_separator<char> sep("\"");
+		boost::tokenizer <boost::char_separator<char> >tokens(line,sep);
+
+		boost::tokenizer<boost::char_separator<char> >::iterator it = tokens.begin();
+		_label = *it;
+		++it;
+
+		try
+		{
+			_color = lexical_cast<int>(*it);
+			_active =  lexical_cast<int>(*it);
+			_type = lexical_cast<int>(*it);
+		}
+
+		catch(const bad_lexical_cast & e)
+		{
+			std::cerr<<e.what();
+		}
+
+		_modified = false ;
+	}
+
+	bool operator==(const Layer& layer) const
+							{ return (_type == layer.getType() and (_type == CONTOUR_BASSIN or _type == RESEAU_HYDRO or _type == EXUTOIRES));}
+
+	void toTextFile(std::ofstream & file) const
+	{
+		file<<"\""<<_label<<"\""<<" "<<_color<<" "<<_active<<" "<<_type<<"\n";
+	}
+
+	~Layer()
+	{
+		if(_data !=NULL)
+			delete [] _data;
+	}
+
+	int getActive() const
+	{
+		return _active;
+	}
+
+	int getColor() const
+	{
+		return _color;
+	}
+
+	const std::string& getLabel() const
+	{
+		return _label;
+	}
+
+	bool isModified() const
+	{
+		return _modified;
+	}
+
+	int getType() const
+	{
+		return _type;
+	}
+
+	void setLabel(const std::string& label) {
+		_label = label;
+	}
+
+	void setColor(int couleur) {
+#ifdef IHM
+		_color = couleur;
+#endif
+	}
+
+	void setActive(int active)
+	{
+		_active = active;
+	}
+
+	void setType(int type)
+	{
+		_type = type;
+	}
+
+	static void fill(std::vector<Layer> & layers)
+	{
+		layers.push_back(Layer(std::string("Reseau Hydrographique"), 0,0,RESEAU_HYDRO,false));
+		layers.push_back(Layer(std::string("Contour des Bassins Versants"), 0,0,CONTOUR_BASSIN,false));
+		layers.push_back(Layer(std::string(""), 0,0,CONTOUR_IMAGE_BINAIRE,false));
+		layers.push_back(Layer(std::string("Exutoires du Reseau Hydro"), 0,0,EXUTOIRES,false));
+	}
+
+	static int find(std::vector<Layer> & layers, int type)
+	{
+		for(unsigned short int  i = 0; i < layers.size(); i++)
+		{
+			if(layers.at(i).getType() == type && (type == CONTOUR_BASSIN || type == RESEAU_HYDRO || type == EXUTOIRES))
+				return i;
+		}
+
+		return -1 ;
+	}
+
+	const std::string toString() const
+	{
+		std::stringstream ss;
+		ss <<"label "<<_label <<" couleur "<<_color<<" active "<<_active<<" type"<<_type;
+		return ss.str();
+	}
+
+	void display(Parameters * p) const
+	{
+		std::cout<<toString()<<std::endl;
+
+		std::cout<<"Données Couches "<<std::endl;
+
+		for(int i = 0; i< p->_linesNumber; i++)
+		{
+			for(int j = 0; j< p->_columnsNumber; j++)
+			{
+				std::cout<<isNetwork(Coordinates(p->_linesNumber - 1 - i , j),p )<<std::endl;
+			}
+			std::cout<<"\n";
+		}
+	}
+
+	unsigned char* getData() const
+	{
+		return _data;
+	}
+
+	void setData(unsigned char* data)
+	{
+		_data = data;
+	}
+
+	/*!
+	 *  \brief Retourner le bit de coordonnées i, j d'une matrice
+	 *
+	 * \param m : matrice des couches.
+	 * \param c : Coordonnées 2D afin de se situer dans la matrice.
+	 * \param p : Paramètres du bassin versant.
+	 * \return la valeur du bit correspondant au pixel i, j dans la matrice m.
+	 */
+
+	bool getmatbit (const Coordinates & c, const Parameters * p) const
+	{
+		return (((*( _data + (c.getLine() *p->_charColumnsNumber+(c.getColumn()>>3))))>>(c.getColumn()&7)) & 1);
+	}
+
+	/*!
+	 *  \brief Affecte la valeur 1 au bit correspondant au pixel i, j dans la matrice m.
+	 *
+	 * \param m : Matrice des couches.
+	 * \param c : Coordonnées 2D afin de se situer dans la matrice.
+	 * \param p : Paramètres du bassin versant.
+	 * \return void.
+	 */
+
+	void matbiton (const Coordinates & c, const Parameters * p)
+	{
+		*(_data + (c.getLine() * p->_charColumnsNumber +(c.getColumn()>>3))) |= 1<<(c.getColumn()&7);
+	}
+
+
+	/*!
+	 *  \brief Affecte la valeur 0 au bit correspondant au pixel i, j dans la matrice m.
+	 *
+	 * \param m : Matrice des couches.
+	 * \param c : Coordonnées 2D afin de se situer dans la matrice.
+	 * \param p : Paramètres du bassin versant.
+	 * \return void.
+	 */
+
+	void matbitoff (Coordinates &c, const Parameters * p)
+	{
+		*(_data + (c.getLine() * p->_charColumnsNumber + (c.getColumn()>>3))) &= ~(1<<(c.getColumn()&7)) ;
+	}
+
+
+	bool isNetwork(const Coordinates & c, const Parameters * p) const
+	{
+		return getmatbit(c, p);
+	}
+};
+
+
+
+#endif /* LAYER_H_ */

+ 121 - 0
src/tests/corsen/lib/LayersFileStream.h

@@ -0,0 +1,121 @@
+/*!
+ * \file LayersFileStream.h
+ * \brief Flux binaire sur le fichier de couches.
+ * \author The VLE Development Team
+ *  See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 3 juin 2013
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef LAYERSFILESTREAM_H_
+#define LAYERSFILESTREAM_H_
+
+#include <sstream>
+#include "FileStream.h"
+#include "Parameters.h"
+
+/*! \class LayersFileStream
+ *
+ * \brief gère un flux en lecture et écriture sur le fichier de couches.
+ *
+ */
+
+class LayersFileStream : public FileStream<corsenContainers::CType,unsigned char>
+{
+private :
+	Parameters * _param;
+
+
+public :
+	LayersFileStream(const std::string & filePath, Parameters * param) : FileStream<corsenContainers::CType,unsigned char>(filePath)
+	{
+		_param = param;
+
+	}
+
+	returnType * read() const throw (FileNotFound, ReadError, InvalidFileFormat, std::bad_alloc)
+	{
+
+		std::ifstream layersFile(_filePath.c_str() ,std::ios::binary);
+		if(!layersFile)
+			throw FileNotFound("Exception opening File : "+_filePath);
+
+		if(_format.compare("") == 0 )
+			return readStandardFormat(layersFile);
+
+		throw InvalidFileFormat("Exception Unknown file format "+ _filePath +"\n");
+	}
+
+	void write(const returnType & /* object */,
+		   const std::string & /* extension */) const
+	{
+
+	}
+
+	virtual ~LayersFileStream()
+	{
+
+	}
+
+
+private :
+	returnType * readStandardFormat(std::ifstream & file) const throw (ReadError, std::bad_alloc)
+	{
+		unsigned char * c;
+		try
+		{
+			c = new unsigned char[_param->_linesNumber * _param->_charColumnsNumber + 1];
+		}
+		catch(std::bad_alloc & e)
+		{
+			throw;
+		}
+		int i =0;
+		do
+		{
+			file.read(reinterpret_cast<char *>(&c[i]),sizeof(unsigned char));
+			i++;
+		}
+		while(i != (_param->_linesNumber * _param->_charColumnsNumber));
+
+		if(file.bad() /*or not file.eof()*/)
+		{
+			std::stringstream ss;
+			ss << file.gcount();
+			file.close();
+			throw ReadError("Exception Reading data only "+ss.str()+" could be read "+_filePath);
+		}
+#ifdef DEBUG
+		std::cout << "LayersFileStream : all characters read successfully.\n";
+#endif
+		file.close();
+		c[_param->_linesNumber * _param->_charColumnsNumber] = '\0';
+		return c;
+	}
+
+	void writeStandardFormat(std::ofstream & /* file */,
+				 const returnType & /* object */) const
+	{
+
+	}
+};
+
+
+#endif /* LAYERSFILESTREAM_H_ */

+ 141 - 0
src/tests/corsen/lib/LayersTextFileStream.h

@@ -0,0 +1,141 @@
+/**
+ * \file LayersTextFileStream.h
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 3 juin 2013
+ * \brief Flux texte sur fichier de couches.
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef LAYERSTEXTFILESTREAM_H_
+#define LAYERSTEXTFILESTREAM_H_
+
+#include <iostream>
+#include <vector>
+#include <list>
+#include <cstdlib>
+#include <cstdio>
+#include <stdbool.h>
+#include <string>
+#include <sstream>
+#include "FileStream.h"
+#include "Layer.h"
+#include "Constantes.h"
+
+/*! \class LayersTextFileStream
+ *
+ * \brief gère un flux texte en lecture et écriture sur le fichier de couches.
+ */
+
+class LayersTextFileStream : public FileStream<corsenContainers::vecS,Layer>
+{
+
+public :
+	LayersTextFileStream(std::string & filePath)  : FileStream<corsenContainers::vecS,Layer>(filePath) {}
+	virtual ~LayersTextFileStream() {}
+
+public :
+
+	/*!
+	 * \brief Lecture
+	 *
+	 * Ouvre le fichier de couches et lance la méthode de lecture adaptée.
+	 * \param void
+	 * \return l'objet contenant les données lues.
+	 */
+
+	returnType * read() const throw (FileNotFound, InvalidFileFormat)
+	{
+		std::ifstream file(_filePath.c_str(),std::ios::in);
+
+		if(not file)
+			throw FileNotFound("Exception opening file\n "+_filePath);
+
+		if(_format.compare("") == 0)
+			return readStandardFormat(file);
+
+		throw InvalidFileFormat("Exception Unknown file format "+_filePath+"\n");
+	}
+
+	/*!
+	 * \brief Écriture
+	 *  Ouvre le fichier de couches et lance la méthode d'écriture adaptée.
+	 *  \param object : objet contenant les informations à écrire
+	 *  \param extension : format du fichier pour la sauvegarde
+	 *  \return void
+	 */
+
+	void write(const returnType & object, const std::string & extension) const throw (FileNotFound, InvalidFileFormat)
+	{
+		std::string filePath(_filePath);
+		filePath.append(extension);
+		std::ofstream file(filePath.c_str() ,std::ios::app);
+
+		if(not file)
+			throw ("Exception opening file\n "+ filePath);
+
+		if(_format.compare("") == 0)
+			return writeStandardFormat(file, object);
+
+		throw InvalidFileFormat("Exception Unknown file format "+ filePath + "\n");
+	}
+
+private:
+
+	/*!
+	 * \brief Lecture au format standard
+	 *
+	 * Lit dans le fichier '_filePath' le label et la couleur des couches de segments raster.
+	 * \param file fichier dans lequel lire les données.
+	 * \return l'objet contenant les données lues.
+	 */
+
+	returnType * readStandardFormat(std::ifstream & file) const
+	{
+		std::string line;
+		std::vector<Layer> * layers = new std::vector<Layer>();
+
+		while(std::getline(file,line))
+			layers->push_back(Layer(line));
+
+		file.close();
+
+		return layers;
+	}
+
+	/*!
+	 * \brief Écriture au format standard
+	 *
+	 * Écrit dans le fichier '_filePath' le label et la la couleur des couches de segments raster.
+	 * \param file fichier dans lequel écrire les données.
+	 * \param object l'objet contenant les informations à écrire.
+	 * \return void
+	 */
+
+	void writeStandardFormat(std::ofstream & file, const returnType & object) const
+	{
+		for (std::vector<Layer>::const_iterator it = object.begin(); it!= object.end(); it++)
+			it->toTextFile(file);
+	}
+
+};
+
+
+#endif /* LAYERSTEXTFILESTREAM_H_ */

+ 149 - 0
src/tests/corsen/lib/Node.h

@@ -0,0 +1,149 @@
+/*!
+ * \file Node.h
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 3 juin 2013
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef NODE_H_
+#define NODE_H_
+
+#include "Coordinates.h"
+#include <list>
+class Node
+{
+protected :
+	Coordinates _coord;
+	Node * _father;
+	Node * _child;
+	Node * _brother;
+
+public :
+
+	Node(): _coord()
+{
+		_father = NULL;
+		_child = NULL;
+		_brother = NULL;
+}
+
+	Node(const Node & n)
+	{
+		_coord = n.getCoord();
+		_father = n.getFather();
+		_child = n.getChild();
+		_brother = n.getBrother();
+	}
+
+	Node(const Coordinates & c, Node * father) :_coord(c)
+	{
+		_father = father;
+		_child = NULL;
+		_brother = NULL;
+	}
+
+	virtual ~Node(){}
+
+	void setPere(Node * pere)
+	{
+		_father = pere;
+	}
+
+	void setCoord(const Coordinates& coord)
+	{
+		_coord = coord;
+	}
+
+	const Coordinates& getCoord() const
+	{
+		return _coord;
+	}
+
+	Node * getChild() const
+	{
+		return _child;
+	}
+
+	Node * getBrother() const
+	{
+		return _brother;
+	}
+
+	Node * getFather() const
+	{
+		return _father;
+	}
+
+	void setChild(Node *  child)
+	{
+		_child = child;
+	}
+
+	void setBrother(Node *  brother)
+	{
+		_brother = brother;
+	}
+
+	const std::string toString() const
+	{
+		std::stringstream ss;
+
+		ss <<"coordonnes du noeud : "<<_coord.toString()<<"\n";
+
+		if(_child !=NULL)
+			ss<<"coordonnes du fils : "<<_child->getCoord().toString()<<"\n";
+
+		if(_brother !=NULL)
+			ss<<"coordonnes du frere : "<<_brother->getCoord().toString()<<"\n";
+
+		return ss.str();
+	}
+
+	char getNeighbourId(const Node * n) const
+	{
+		char c ='X';
+		short diffi = _coord.getLine() - n->getCoord().getLine() ;
+		short diffj = _coord.getColumn() - n->getCoord().getColumn();
+
+		if (diffi == 1 && diffj == 0)
+			c ='1';
+		else if (diffi == 1 && diffj == -1)
+			c = '2' ;
+		else if(diffi == 0 && diffj == -1)
+			c = '3' ;
+		else if (diffi == -1 && diffj == -1)
+			c = '4' ;
+		else if (diffi == -1 && diffj == 0)
+			c = '5' ;
+		else if (diffi == -1 && diffj == 1)
+			c = '6' ;
+		else if (diffi == 0 && diffj == 1)
+			c = '7' ;
+		else if (diffi == 1 && diffj == 1)
+			c = '8' ;
+
+		return c;
+	}
+
+
+};
+
+#endif /* NODE_H_ */

+ 179 - 0
src/tests/corsen/lib/Outlet.h

@@ -0,0 +1,179 @@
+/*!
+ * \file Outlet.h
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 3 juin 2013
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef OUTLET_H_
+#define OUTLET_H_
+
+#include "Node.h"
+#include <vector>
+#include <map>
+
+
+class Outlet : public Node
+{
+
+public :
+	short getFlag() const {
+		return _flag;
+	}
+
+	short getMx() const {
+		return _mx;
+	}
+
+	short getGmx() const {
+		return _Mx;
+	}
+
+	short getMy() const {
+		return _my;
+	}
+
+	short getGmy() const {
+		return _My;
+	}
+
+	int getNumber() const {
+		return _number;
+	}
+
+	short getOrder() const {
+		return _order;
+	}
+
+	void setFlag(short flag)
+	{
+		_flag = flag;
+	}
+
+	void setMx(short mx)
+	{
+		_mx = mx;
+	}
+
+	void setGMx(short mx)
+	{
+		_Mx = mx;
+	}
+
+	void setMy(short my)
+	{
+		_my = my;
+	}
+
+	void setGMy(short my)
+	{
+		_My = my;
+	}
+
+	void setNumber(int number)
+	{
+		_number = number;
+	}
+
+	void setOrder(short order)
+	{
+		_order = order;
+	}
+
+	Outlet() : Node()
+	{
+		_flag = 0;
+		_order = 0;
+		_mx = 0;
+		_my = 0;
+		_Mx = 0;
+		_My = 0;
+		_number = 0;
+	}
+
+	Outlet(const Outlet & o) : Node(o.getCoord(), o.getFather())
+	{
+		_father = o.getFather();
+		_brother = o.getBrother();
+		_child = o.getChild();
+		_flag = o.getFlag();
+		_number = o.getNumber() ;
+		_order = o.getOrder();
+		_mx = o.getMx();
+		_my = o.getMy();
+		_Mx = o.getGmx();
+		_My = o.getGmy();
+
+	}
+
+	Outlet(const Coordinates & c, short flag, int outletsNumber) : Node(c, NULL)
+	{
+		_child = NULL;
+		_brother = NULL;
+		_flag = flag;
+		_number = outletsNumber ;
+		_order = 0;
+		_mx = 0;
+		_my = 0;
+		_Mx = 0;
+		_My = 0;
+
+	}
+	~Outlet()
+	{
+		for(std::map<Coordinates, Node *>::iterator it = _childrenNodes.begin(); it!=_childrenNodes.end();it++)
+			delete it->second;
+	}
+
+	void setNodes(const std::map<Coordinates, Node*>& nodes)
+	{
+		this->_childrenNodes = nodes;
+	}
+
+	const std::string toString() const
+	{
+		std::stringstream ss;
+		ss<<"Outlet : "<<_coord.toString()<<"flag "<<_flag<<" numero "<<_number<<std::endl;
+
+		ss <<"All nodes : \n";
+		for(std::map<Coordinates, Node *>::const_iterator it = _childrenNodes.begin(); it!=_childrenNodes.end();it++)
+			ss << it->second->toString()<<"\n:";
+
+		return ss.str();
+	}
+
+	 Node * searchChildNode(const Coordinates & coord) const
+	{
+		if(_childrenNodes.count(coord))
+			return _childrenNodes.find(coord)->second;
+
+		return NULL;
+	}
+
+private :
+	std::map<Coordinates, Node *>_childrenNodes;
+	short _flag;
+	short _order;
+	short _mx, _my, _Mx, _My ;
+	int _number ;
+};
+
+#endif /* OUTLET_H_ */

+ 242 - 0
src/tests/corsen/lib/OutletFileStream.h

@@ -0,0 +1,242 @@
+/*!
+ * \file OutletFileStream.h
+ * \brief Flux binaire sur fichier contenant toutes les données de l'arborescence de MntSurf.
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 13 juin 2013
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef OUTLETFILESTREAM_H_
+#define OUTLETFILESTREAM_H_
+
+#include "FileStream.h"
+#include "Outlet.h"
+#include "Coordinates.h"
+#include <list>
+
+/*! \class OutletFileStream
+ *
+ * \brief gère un flux binaire en lecture et écriture sur le fichier contenant l'arborescence de MntSurf.
+ */
+
+class OutletFileStream : public FileStream<corsenContainers::listS,Outlet *>
+{
+public :
+	enum returnTypeTree {recursiveOff, recursiveOn , eof};
+	OutletFileStream(std::string & filePath) : FileStream<corsenContainers::listS,Outlet *>(filePath) { }
+	~OutletFileStream() {}
+
+	returnType * read() const throw (FileNotFound, ReadError, InvalidFileFormat, std::bad_alloc)
+	{
+		std::ifstream outletFile(_filePath.c_str(),std::ios::binary);
+
+		if(not outletFile)
+			throw FileNotFound("Exception opening file\n: "+ _filePath);
+
+		if(_format.compare("") == 0)
+			return readStandardFormat(outletFile);
+
+		throw InvalidFileFormat("Exception Unknown file format "+_filePath+"\n");
+
+	}
+
+	void write(const returnType & object, const std::string & extension) const
+	{
+		std::string filePath(_filePath);
+		filePath.append(extension);
+		std::ofstream altFile(filePath.c_str(), std::ios::trunc);
+
+		if(not altFile)
+			throw FileNotFound("Exception opening file "+ filePath +"\n");
+
+		if(_format.compare("") == 0)
+			return writeStandardFormat(altFile, object);
+
+		throw InvalidFileFormat("Exception Unknown file format "+ filePath +"\n");
+
+	}
+
+private :
+
+	void fillMap(Node * n, std::map<Coordinates, Node *> & tmpNodes) const
+	{
+		if (n != NULL)
+		{
+			tmpNodes[n->getCoord()] = n;
+			fillMap(n->getChild(),tmpNodes);
+			fillMap(n->getBrother(),tmpNodes);
+		}
+	}
+
+
+	returnType * readStandardFormat(std::ifstream & file) const throw(ReadError, std::bad_alloc)
+	{
+		try
+		{
+			std::list<Outlet *> * tmp = new std::list<Outlet *>();
+			std::map<Coordinates, Node *> tmpNodes;
+			Outlet * olt = NULL;
+			short ligne, colonne;
+			int outletsNum = 100000 ;
+
+			do
+			{
+				outletsNum -= 1 ;
+				file.read(reinterpret_cast<char *>(&ligne), sizeof(short));
+				file.read(reinterpret_cast<char *>(&colonne), sizeof(short));
+				olt = new Outlet(Coordinates(ligne,colonne),0,outletsNum);
+
+				if (readTree(file, olt, NULL) == eof)
+				{
+					delete olt;
+					break;
+				}
+
+				fillMap(olt->getChild(), tmpNodes);
+				olt->setNodes(tmpNodes);
+				tmpNodes.clear();
+				(*tmp).push_front(olt);
+			}
+			while(file.good());
+			if(file.bad() or not file.eof())
+			{
+				file.close();
+				throw ReadError("Exception reading file "+ _filePath);
+			}
+
+			file.close();
+			return tmp;
+		}
+		catch(std::bad_alloc & e)
+		{
+			throw;
+		}
+
+	}
+
+	/*!
+	 *  \brief Lecture arbre
+	 *
+	 *  - Lit le fichier arbre.
+	 *  - Stocke dans une liste les exutoires de réseau de drainage,
+	 *  chaque exutoire contient la racine d'un arbre binaire.
+	 *
+	 *  \param file : fichier ou est stocké l'arborescence du réseau de drainage.
+	 *  \param n : Noeud fils
+	 *  \param p : Noeud père
+	 *  \return recursiveoff : arrêt du parcours de l'arbre ou de la branche.
+	 *  		recursiveon  : continuer parcours des branches de l'arbre.
+	 *  		eof : fin du fichier atteinte.
+	 */
+
+
+	returnTypeTree readTree(std::ifstream & file, Node * n, Node * p) const
+	{
+		char c;
+
+		file.read(reinterpret_cast<char *>(&c),sizeof(char));
+
+		if(file.eof())
+			return eof;
+
+		switch (c)
+		{
+		case '(' :
+
+			file.read(reinterpret_cast<char *>(&c),sizeof(char));
+
+			if (c == ')')
+				return recursiveOff ;
+
+			n->setChild(new Node(Coordinates(n->getCoord(), c), n));
+
+			if (readTree(file, (n->getChild()), n) == recursiveOn)
+				return (readTree(file, n, p));
+
+			break ;
+
+		case ')' :
+			n->setBrother(NULL);
+			if (p->getFather() !=NULL)
+				return recursiveOn ;
+			else
+				return recursiveOff ;
+
+		default :
+			n->setBrother(new Node(Coordinates(p->getCoord(),c), p));
+			return (readTree(file, n->getBrother(), p)) ;
+		}
+
+		return recursiveOn;
+	}
+
+
+	void writeStandardFormat(std::ofstream & file, const returnType & object) const
+	{
+
+#ifdef DEBUG
+		std::cout<<"Sauvegarde de l'arbre.\n";
+#endif
+		if (object.size() == 0)
+			return ;
+
+		for (returnType::const_reverse_iterator it = object.rbegin(); it!=object.rend() ; it++)
+		{
+			Coordinates outletCoordinates((*it)->getCoord());
+			outletCoordinates.toBinaryFile(file);
+
+			file.put('(');
+
+			if ((*it)->getChild() != NULL)
+				writeTree(file, *it, (*it)->getChild()) ;
+			else
+				file.put(')') ;
+		}
+
+		file.close();
+	}
+
+	void writeTree(std::ofstream & file, const Node * father, const Node * child) const
+	{
+		if(child != NULL)
+		{
+			file.put(father->getNeighbourId(child));
+
+			if (child->getChild() !=NULL)
+			{
+				file.put('(') ;
+				writeTree(file, child, child->getChild()) ;
+			}
+
+			if (child->getBrother() != NULL)
+				writeTree(file, father, child->getBrother());
+			else
+				file.put(')');
+		}
+
+	}
+
+};
+
+
+
+
+#endif /* OUTLETFILESTREAM_H_ */

+ 87 - 0
src/tests/corsen/lib/Parameters.h

@@ -0,0 +1,87 @@
+/*!
+ * \file Parameters.h
+ * \brief paramètres du programme et du bassin versant.
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 12 juin 2013
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef PARAMETERS_H_
+#define PARAMETERS_H_
+
+#include <iostream>
+#include <sstream>
+
+/*! \class Parameters
+ *
+ * \brief Regroupe les paramètres du programme et du bassin versant.
+ *
+ */
+
+class Parameters
+{
+public :
+	int _gap;
+	bool _meshMode;
+	int _riverLevel;
+	int _displaySea;
+	int _nodesPerLine;
+	int _nodesPerColumn;
+	int _linesNumber;
+	int _columnsNumber;
+	float _meshSize;
+	float _horizontalMeshStep;
+	float _verticalMeshStep;
+	float _meshArea;
+	float _colorColumnsNumber;
+	int _charColumnsNumber;
+	float lx0;
+	float ly0;
+	float lx1;
+	float ly1;
+	float lx2;
+	float ly2;
+	float lx3;
+	float ly3;
+	bool _lambertCadre;
+
+	/*!
+	 * \brief Transformer en chaîne.
+	 *
+	 * Représentation chaînée de l'objet.
+	 *
+	 * \param void
+	 * \return string
+	 */
+
+	const std::string toString() const
+	{
+		std::stringstream s;
+
+		s << "\n - trou " <<((_gap == 0 ) ? "non" : "oui")<<"\n - modeMaille "<<((_meshMode == false ) ? "non" : "oui")<<"\n - afficherMer "<<((_displaySea == 0 ) ? "non" : "oui") <<"\n - nbNoeudLig "<<_nodesPerLine<<"\n - nbNoeudCol "<<_nodesPerColumn
+				<<"\n - nbLig "<<_linesNumber<<"\n - nbCol "<<_columnsNumber<<"\n - tailleMaille "<<_meshSize<<"\n - pasMailleX "<<_horizontalMeshStep<<"\n - pasMailleY "<<_verticalMeshStep<<"\n - aireMaille "<<_meshArea<<
+				"\n - colorColumnsNumber "<<_colorColumnsNumber<<"\n - nbColCar "<<_charColumnsNumber<<"\n - lx0 "<<lx0<<"\n - ly0 "<<ly0<<"\n - lx1 "<<lx1<<"\n - ly1 "<<ly1<<"\n - lx2 "<<lx2<<"\n - ly2 "<<ly2<<"\n - lx3 "<<lx3<<"\n - ly3 "<<ly3<<"\n - cadreLambert "<<((_lambertCadre == false ) ? "non" : "oui");
+		return s.str();
+	}
+};
+
+
+#endif /* PARAMETERS_H_ */

+ 255 - 0
src/tests/corsen/lib/ParametersFileStream.h

@@ -0,0 +1,255 @@
+/*!
+ * \file ParametersFileStream.h
+ * \brief Flux texte sur le fichier de paramètres du programme et du bassin versant.
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 12 juin 2013
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef PARAMETERSFILESTREAM_H_
+#define PARAMETERSFILESTREAM_H_
+
+#include "FileStream.h"
+#include "Parameters.h"
+#include <boost/lexical_cast.hpp>
+#include <boost/shared_ptr.hpp>
+
+/*! \class ParametersFileStream
+ *
+ * \brief gère un flux texte en lecture et écriture sur le fichier de paramètres.
+ */
+
+class ParametersFileStream : public FileStream<corsenContainers::CType, Parameters>
+{
+public:
+	std::string _modeFilePath;
+	std::string _modeFileFormat;
+
+	ParametersFileStream(std::string & parametersFilePath, std::string & modeFilePath) : FileStream<corsenContainers::CType, Parameters>(parametersFilePath)
+	{
+		_modeFilePath = modeFilePath;
+		_modeFileFormat = findFormat(modeFilePath);
+	}
+
+	virtual ~ParametersFileStream(){}
+
+	returnType * read() const throw (FileNotFound, InvalidFileFormat)
+	{
+		std::ifstream parFile(_filePath.c_str(),std::ios::in);
+		std::ifstream modeFile(_modeFilePath.c_str(),std::ios::in);
+		Parameters * p = NULL;
+
+		if(not parFile)
+			throw FileNotFound("Exception opening file : "+ _filePath);
+
+		if(not modeFile)
+			throw FileNotFound("Exception opening file : "+ _modeFilePath);
+
+		if(_format.compare(".txt") == 0)
+			p = readStandardFormat(parFile);
+		else if(_format.compare(".def") == 0)
+			p = readDefaultValues(parFile);
+		else
+			throw InvalidFileFormat("Exception Unknown file format "+_format+"\n");
+
+		if(_modeFileFormat.compare("") == 0)
+			readStandardModeFormat(modeFile, p);
+		else
+		{
+			if(p != NULL)
+				delete p;
+
+			throw InvalidFileFormat("Exception Unknown file format "+_modeFileFormat+"\n");
+		}
+
+		return p;
+	}
+
+
+	void write(const returnType & object, const std::string & /* extension */) const throw (FileNotFound, InvalidFileFormat)
+	{
+		std::ofstream parFile(_filePath.c_str(), std::ios::trunc) ;
+
+		if(not parFile)
+			throw FileNotFound("Exception opening file: "+ _filePath);
+
+		if(_format.compare(".txt") == 0)
+			return writeStandardFormat(parFile, object);
+
+		throw InvalidFileFormat("Exception Unknown file format "+_filePath+"\n");
+	}
+
+private :
+
+	void readStandardModeFormat(std::ifstream & file, Parameters * p) const throw (FileNotFound, boost::bad_lexical_cast)
+	{
+		using boost::lexical_cast;
+		std::string line;
+		std::vector<std::string> parameters;
+
+		std::getline(file, line);
+		boost::split(parameters,line,boost::is_any_of(" "));
+		p->_meshMode = lexical_cast<bool>(parameters.at(0));
+		p->_gap = lexical_cast<int>(parameters.at(1));
+
+		file.close();
+	}
+
+	returnType * readDefaultValues(std::ifstream & file) const throw (ReadError)
+	{
+		Parameters * param = new Parameters();
+		file.read(reinterpret_cast<char *>(&(param->_riverLevel)), sizeof(int));
+		file.read(reinterpret_cast<char *>(&(param->_displaySea)), sizeof(int));
+		if(file.bad() or not file.eof())
+		{
+			file.close();
+			throw ReadError("Exception reading file "+ _filePath);
+		}
+#ifdef DEBUG
+		std::cout<<"Seuil de rivière: "<<param->_riverLevel<<" ha"<<std::endl;
+		std::cout<<"Afficher la  mer: "<<param->_displaySea<<std::endl
+#endif
+		file.close();
+		return param;
+}
+
+	returnType * readStandardFormat(std::ifstream & file) const
+	{
+		using boost::lexical_cast;
+		using boost::bad_lexical_cast ;
+		Parameters * param = new Parameters();
+		std::string line;
+		std::vector<std::string> parameters;
+
+		std::getline(file,line);
+		boost::split(parameters, line, boost::is_any_of(" "));
+		try
+		{
+			param->_nodesPerLine = lexical_cast<int>(parameters.at(0));
+			param->_nodesPerColumn = lexical_cast <int>(parameters.at(1));
+
+			if(param->_meshMode)
+			{
+				param->_linesNumber = param->_nodesPerLine;
+				param->_columnsNumber = param->_nodesPerColumn;
+			}
+			else
+			{
+				param->_linesNumber = param->_nodesPerLine - 1 ;
+				param->_columnsNumber = param->_nodesPerColumn - 1 ;
+			}
+#ifdef DEBUG
+			std::cout<<"Matrice Altitude : "<<param->_linesNumber<<" lignes et "<<param->_columnsNumber<<" colonnes \n"<<"mnt "<<param->_nodesPerLine<<" X "<<param->_nodesPerColumn<<std::endl;
+#endif
+		}
+		catch (const bad_lexical_cast & e)
+		{
+			std::cerr<<e.what();
+		}
+		if(parameters.size() >= 3)
+		{
+			param->_horizontalMeshStep = lexical_cast<double>(parameters.at(2));
+
+			if (parameters.size() >=4 )
+			{
+				param->_verticalMeshStep = lexical_cast<double>(parameters.at(3));
+				param->_lambertCadre = false ;
+
+				if (parameters.size() == 12)
+				{
+					param->_lambertCadre = true ;
+					param->lx0 = lexical_cast<double>(parameters.at(4));
+					param->ly0 = lexical_cast<double>(parameters.at(5));
+					param->lx1 = lexical_cast<double>(parameters.at(6));
+					param->ly1 = lexical_cast<double>(parameters.at(7));
+					param->lx2 = lexical_cast<double>(parameters.at(8));
+					param->ly2 = lexical_cast<double>(parameters.at(9));
+					param->lx3 = lexical_cast<double>(parameters.at(10));
+					param->ly3 = lexical_cast<double>(parameters.at(11));
+				}
+
+			}
+			else
+				param->_verticalMeshStep = param->_horizontalMeshStep;
+
+			param->_meshSize = param->_horizontalMeshStep  ;
+
+		}
+		else
+		{
+			param->_horizontalMeshStep =  50. ;
+			param->_verticalMeshStep = 50.;
+			param->_meshSize = 50.;
+		}
+
+		param->_meshArea = param->_horizontalMeshStep * param->_verticalMeshStep ;
+		param->_colorColumnsNumber = (( param->_columnsNumber / 32 ) + 1 ) * 32 ;
+		param->_charColumnsNumber = (int) ceil ( (double) param->_columnsNumber / 8. ) ;
+
+#ifdef DEBUG
+		std::cout<<"Pas de la maille en x : "<<param->_horizontalMeshStep<<" mètres \n" ;
+		std::cout<<"Pas de la maille en y : "<<param->_verticalMeshStep<<" mètres \n\n";
+		std::cout<<param->_colorColumnsNumber<<" colonnes couleur\n\n";
+		std::cout<<param->_charColumnsNumber<<" colonnes caractère (codage binaire)\n\n";
+#endif
+		if(not param->_lambertCadre)
+		{
+			param->lx0 = 0. ;
+			param->ly0 = 0. ;
+			param->lx1 = 0. ;
+			param->ly1 = param->_verticalMeshStep * param->_nodesPerColumn / 1000. ;
+			param->lx2 = param->_verticalMeshStep * param->_nodesPerLine / 1000. ;
+			param->ly2 = 0. ;
+			param->lx3 = param->_verticalMeshStep * param->_nodesPerLine / 1000. ;
+			param->ly3 = param->_verticalMeshStep * param->_nodesPerColumn / 1000. ;
+			param->_lambertCadre = true ;
+		}
+
+		file.close();
+		return param;
+	}
+
+	void writeStandardFormat(std::ofstream & file, const returnType & object) const throw (FileNotFound)
+	{
+		std::ofstream modeFile(_modeFilePath, std::ios::trunc);
+		if(not modeFile)
+			throw FileNotFound("Exception opening file: "+ _modeFilePath);
+
+		modeFile<<object._meshMode<<" "<<object._gap;;
+		modeFile.close();
+
+		file<<object._linesNumber<<" ";
+		file<<object._columnsNumber<<" ";
+		file<<object._horizontalMeshStep<<" ";
+		file<<object._verticalMeshStep<<" ";
+		file<<object.lx0<<" ";
+		file<<object.ly0<<" ";
+		file<<object.lx1<<" ";
+		file<<object.ly1<<" ";
+		file<<object.lx2<<" ";
+		file<<object._charColumnsNumber<<" ";
+		file<<object.lx3<<" ";
+		file<<object.ly3<<"\n";
+		file.close();
+	}
+};
+
+#endif /* PARAMETERSFILESTREAM_H_ */

+ 123 - 0
src/tests/corsen/lib/Singleton.h

@@ -0,0 +1,123 @@
+/*!
+ * \file Singleton.h
+ * \brief modèle de singleton applicable à n'importe quelle classe.
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 6 juin 2013
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef SINGLETON_H_
+#define SINGLETON_H_
+
+#include <iostream>
+#include "Constantes.h"
+
+/*! \class Singleton
+ *
+ * \brief est un design pattern dont l'objet est de restreindre l'instanciation d'une classe à un seul objet.
+ */
+
+template <typename T>
+class Singleton
+{
+protected:
+
+	/*!
+	 *  \brief Constructeur
+	 *
+	 *  Constructeur de la classe Singleton.
+	 *  \param void
+	 *  \return void
+	 *
+	 */
+
+	Singleton () { }
+
+	/*!
+	 *  \brief Destructeur
+	 *
+	 *  Destructeur de la classe Singleton.
+	 */
+
+	~Singleton ()
+	{
+#ifdef DEBUG
+		std::cout << "destroying singleton." << std::endl;
+#endif
+	}
+
+public:
+
+	/*!
+	 *  \brief Retourner instance.
+	 *
+	 *  Méthode qui crée l'unique instance de la classe si elle n'existe pas encore puis la retourne.
+	 *
+	 * \param void
+	 * \return Singleton
+	 */
+
+	static T * getInstance ()
+	{
+		if (NULL == _instance)
+		{
+#ifdef DEBUG
+			std::cout << "creating singleton." << std::endl;
+#endif
+			_instance = new T;
+		}
+		else
+		{
+#ifdef DEBUG
+			std::cout << "singleton already created!" << std::endl;
+#endif
+		}
+
+		return (static_cast<T*> (_instance));
+	}
+
+	/*!
+	 *  \brief Supprimer instance.
+	 *
+	 *  Méthode qui supprime l'unique instance de la classe si elle existe.
+	 *
+	 * \param void
+	 * \return void
+	 */
+
+	static void kill ()
+	{
+		if (_instance != NULL)
+		{
+			delete _instance;
+			_instance = NULL;
+		}
+	}
+
+private:
+	static T *_instance; /*!< Unique instance */
+};
+
+template <typename T>
+T *Singleton<T>::_instance = NULL;
+
+
+#endif /* SINGLETON_H_ */

+ 114 - 0
src/tests/corsen/lib/SlopeFileStream.h

@@ -0,0 +1,114 @@
+/*!
+ * \file SlopeFileStream.h
+ * \brief Flux binaire sur fichier de pentes.
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 20 juin 2013
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef SLOPEFILESTREAM_H_
+#define SLOPEFILESTREAM_H_
+
+// read a file and save it into memory
+
+#include <sstream>
+#include "FileStream.h"
+
+
+/*! \class SlopeFileStream
+ * \brief gère un flux binaire en lecture et écriture sur le fichier de pentes.
+ *
+ */
+
+class SlopeFileStream: public FileStream<corsenContainers::vecS,float>
+{
+public :
+	SlopeFileStream(const std::string & filePath) : FileStream<corsenContainers::vecS,float>(filePath) {}
+	virtual ~SlopeFileStream(){}
+
+	returnType * read() const throw (FileNotFound, ReadError, InvalidFileFormat, std::bad_alloc)
+	{
+		std::ifstream gradientFile(_filePath.c_str(),std::ios::binary);
+		if(not gradientFile)
+			throw FileNotFound("Exception opening file\n "+_filePath);
+
+		if(_format.compare("") == 0)
+			return readStandardFormat(gradientFile);
+
+		throw InvalidFileFormat("Exception Unknown file format "+_filePath+"\n");
+	}
+
+	void write(const returnType & /* object */, const std::string & /* extension */) const
+	{
+
+	}
+
+	returnType * readStandardFormat(std::ifstream & file) const throw (ReadError, std::bad_alloc)
+	{
+		int i = 0;
+		float tmp;
+		try
+		{
+			returnType *  gradientVec = new returnType();
+
+			do
+			{
+				file.read(reinterpret_cast<char *>(&tmp), sizeof(float));
+				if(file.eof())
+				{
+					file.close();
+#ifdef DEBUG
+					std::cout<<"SlopeFileStream : all characters read successfully.\n";
+#endif
+					break;
+				}
+				else if(file.bad())
+				{
+					file.close();
+					std::stringstream ss;
+					ss << i * sizeof(float);
+					throw ReadError("Exception Reading file, only " + ss.str() + " bytes could be read");
+				}
+				else
+				{
+					gradientVec->push_back(tmp);
+					i++;
+				}
+			}
+			while(file.good());
+
+			return gradientVec;
+		}
+		catch(std::bad_alloc & e)
+		{
+			throw;
+		}
+	}
+
+	void writeStandardFormat(std::ofstream & /* file */,
+				 const returnType & /* object */) const
+	{
+	}
+
+};
+
+
+#endif /* SLOPEFILESTREAM_H_ */

+ 98 - 0
src/tests/corsen/lib/SoilFileStream.h

@@ -0,0 +1,98 @@
+/*!
+ * \file SoilFileStream.h
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ * \date 12 juin 2013
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef SOILFILESTREAM_H_
+#define SOILFILESTREAM_H_
+
+#include "FileStream.h"
+#include <sstream>
+
+class SoilFileStream : public FileStream<corsenContainers::vecS,float>
+{
+public :
+
+	SoilFileStream(const std::string & filePath) : FileStream<corsenContainers::vecS,float>(filePath) {}
+	virtual ~SoilFileStream(){}
+
+	returnType * read() const throw (FileNotFound, ReadError, InvalidFileFormat)
+	{
+		std::ifstream gradientFile(_filePath.c_str(),std::ios::binary);
+		if(not gradientFile)
+			throw FileNotFound("Exception opening file\n "+_filePath);
+
+		if(_format.compare("") == 0)
+			return readStandardFormat(gradientFile);
+
+		throw InvalidFileFormat("Exception Unknown file format "+_filePath+"\n");
+	}
+
+
+	void write(const returnType & /* object */, const std::string & /* extension */) const
+	{
+
+	}
+
+private :
+	returnType * readStandardFormat(std::ifstream & file) const throw (ReadError)
+	{
+			int i = 0;
+			int tmp;
+			returnType * soilVec = new returnType();
+			do
+			{
+				file.read(reinterpret_cast<char *>(&tmp), sizeof(float));
+				if(file.eof())
+				{
+					file.close();
+#ifdef DEBUG
+					std::cout << "SoilFileStream : all characters read successfully. \n";
+#endif
+					break;
+				}
+				else if(file.bad())
+				{
+					file.close();
+					std::stringstream ss;
+					ss << i * sizeof(float);
+					throw ReadError("Exception Reading file, only " + ss.str() + " bytes could be read");
+				}
+				else
+				{
+					soilVec->push_back(tmp) ;
+					i++;
+				}
+			}
+			while(file.good());
+
+			return soilVec;
+	}
+
+	void writeStandardFormat(std::ofstream & /* file */, const returnType & /* object */) const
+	{
+	}
+
+};
+
+#endif

+ 295 - 0
src/tests/corsen/lib/Vertex.h

@@ -0,0 +1,295 @@
+/*!
+ * \file Vertex.h
+ * \brief les types de données nécessaires aux sommets.
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef VERTEX_H_
+#define VERTEX_H_
+
+#include <sstream>
+#include <boost/graph/adjacency_list.hpp>
+#include <boost/graph/graph_utility.hpp>
+#include <boost/graph/graph_traits.hpp>
+#include "Parameters.h"
+#include "Coordinates.h"
+#include "Constantes.h"
+
+
+/**
+ * \struct VertexProperties
+ * \brief structure représentant un sommet dans le boost::Graph.
+ */
+struct VertexProperties
+{
+	std::string name; /*!< nom du sommet*/
+	int identifier; /*!< identifiant du sommet*/
+	Coordinates c; /*!< Coordonnées du sommet*/
+	VertexProperties() : name(""), identifier(0), c() {} /*!< Constructeur par defaut*/
+	VertexProperties(std::string const& n, int i, const Coordinates & coord) : name(n), identifier(i), c(coord)  {} /*!< Constructeur avec paramètres*/
+};
+
+/**
+ * \struct EdgeProperties
+ * \brief structure représentant un arc dans le boost::Graph.
+ */
+struct EdgeProperties
+{
+	double weight;
+	double distance;
+	float pourcent;
+	EdgeProperties() : weight(0.), distance(0.), pourcent(0.) {}
+	EdgeProperties(double w, double d, float p) : weight(w), distance(d), pourcent(p) {}
+};
+
+
+typedef boost::adjacency_list< boost::vecS, boost::vecS, boost::directedS, VertexProperties, EdgeProperties > DirectedGraph; /*!< Liste d'adjacence */
+
+//Some typedefs for simplicity
+typedef boost::graph_traits<DirectedGraph>::vertex_descriptor vertex_t; /*!< Simplification descripteur de sommet de la liste d'adjacence accessible via la classe de traits graph_traits */
+typedef boost::graph_traits<DirectedGraph>::edge_descriptor edge_t; /*!< Simplification descripteur d'un arc de la liste d'adjacence accessible via la classe de traits graph_traits */
+
+
+/*! \class Vertex
+ * \brief représente un point du bassin versant.
+ */
+
+class Vertex
+{
+private :
+	vertex_t _boostGraphIdentifier; /*!< identifiant boostGraph liant une instance de cette classe à un sommet du boostGraph */
+	char _mp; /*!< Type */
+	int _identifier; /*!< Identifiant*/
+	Coordinates _coordinates; /*!< Coordonnées en 2D */
+	float _elevation /*!< Altitude */;
+	std::vector<Vertex *>_neighbours; /*!< liste voisins */
+	float _derive; /*!< derive */
+
+public :
+
+	enum dataType {elevation, derive};
+
+	/*!
+	 *  \brief Constructeur par défaut
+	 *
+	 *  Constructeur de la classe Vertex
+	 *
+	 */
+
+	Vertex() :_coordinates()
+	{
+		_mp = 'n';
+		_identifier = 0;
+		_elevation = 0.;
+		_derive = 0.;
+		_boostGraphIdentifier = 4294967295;
+	}
+
+	/*!
+	 *  \brief Constructeur
+	 *
+	 *  Constructeur avec paramètres de la classe Vertex
+	 *
+	 * \param id : identifiant
+	 * \param c : Coordonnées
+	 * \param elevation : altitude
+	 */
+
+	Vertex(int id, const Coordinates & c, float elevation)
+	{
+		_derive = -999999.0;
+		_boostGraphIdentifier = 4294967295;
+		_mp = 'n';
+		_identifier = id;
+		_coordinates = c;
+		this->_elevation = elevation;
+	}
+
+	/*!
+	 *  \brief Constructeur
+	 *
+	 *  Constructeur par recopie de la classe Vertex
+	 *
+	 * \param v : sommet à copier.
+	 */
+
+	Vertex(const Vertex & v)
+	{
+		_mp = v.getMp();
+		_identifier = v.getIdentifier();
+		_coordinates = v.getCoord();
+		_elevation = v.getElevation();
+		_boostGraphIdentifier = v.getBoostGraphIdentifier();
+		_derive = v.getDerive();
+		_neighbours = v.getNeighbours();
+	}
+
+	virtual ~Vertex(){}
+
+	const std::vector<Vertex*> & getNeighbours() const
+			{
+		return _neighbours;
+			}
+
+	void setNeighbours(const std::vector<Vertex*> & neighbours)
+	{
+		this->_neighbours = neighbours;
+	}
+
+	const Coordinates& getCoord() const
+	{
+		return _coordinates;
+	}
+
+
+	/*!
+	 * \brief Transformer en chaîne.
+	 *
+	 * Représentation chaînée de l'objet
+	 *
+	 * \param void
+	 * \return string
+	 */
+
+
+	const std::string toString() const
+	{
+		std::stringstream s;
+		s <<"mp :"<<_mp <<" coordonnées : "<<_coordinates.toString()<<" altitude : "<<_elevation<<" identifiant : "<<_identifier<<" sommet : "<<_boostGraphIdentifier<<" derive : "<<_derive;
+		return s.str();
+	}
+
+
+	float getElevation() const
+	{
+		return _elevation;
+	}
+
+	vertex_t getBoostGraphIdentifier() const
+	{
+		return _boostGraphIdentifier;
+	}
+
+	void setBoostGraphIdentifier(vertex_t vertex)
+	{
+		this->_boostGraphIdentifier = vertex;
+	}
+
+	int getIdentifier() const {
+		return _identifier;
+	}
+
+	void setDerive(float derive) {
+		this->_derive = derive;
+	}
+
+	float getDerive() const
+	{
+		return _derive;
+	}
+
+	/*!
+	 *  \brief sigma
+	 *  \param dt : précise l'attribut avec lequel effectuer le calcul.
+	 *  \return la somme des poids des sommets voisins du sommet
+	 */
+
+	float sigma(dataType dt) const
+	{
+		float somme = 0. ;
+
+		if(dt == elevation)
+		{
+			for(std::vector<Vertex *>::const_iterator itVoisins = _neighbours.begin();itVoisins!=_neighbours.end();itVoisins++)
+			{
+				if ((**itVoisins).getElevation() > ALTMER)
+					somme += (*itVoisins)->tanBxL(getInstance(), elevation) ;
+			}
+		}
+		else
+		{
+			for(std::vector<Vertex *>::const_iterator itVoisins = _neighbours.begin();itVoisins!=_neighbours.end();itVoisins++)
+			{
+				if ((**itVoisins).getDerive() > ALTMER)
+					somme += (*itVoisins)->tanBxL(getInstance(), derive);
+			}
+		}
+		return somme ;
+	}
+
+	/*!
+	 * \brief teste la position de la maille.
+	 * \return true si la maille testée se situe sur le bord_de_mer, faux sinon
+	 */
+
+	bool isOnSeaside()
+	{
+		for (std::vector<Vertex *>::const_iterator it = _neighbours.begin(); it !=_neighbours.end(); it++)
+		{
+			if ((*it)->getElevation() <= ALTMER)
+				return true;
+		}
+		return false;
+	}
+
+	/*!
+	 * \brief tanBxL
+	 * \param v : le sommet avec laquelle effectuer le calcul.
+	 * \param dt : précise l'attribut avec lequel effectuer le calcul.
+	 * \return le poids du sommet dans la diffusion de la surface contributive vers la maille v.
+	 */
+
+	float tanBxL(const Vertex * v, dataType dt ) const
+	{
+		float delta;
+
+		if(dt == elevation)
+			delta = v->getElevation() -_elevation;
+		else
+			delta = v->getDerive() -_derive;
+
+		if (delta > 0.)
+			return ((_coordinates.isSameLine(v->getCoord()) || _coordinates.isSameColumn(v->getCoord())) ? delta*0.5 : delta*0.354) ;
+		else
+			return 0. ;
+	}
+
+	char getMp() const
+	{
+		return _mp;
+	}
+
+	void setMp(char mp)
+	{
+		this->_mp = mp;
+	}
+
+	const Vertex * getInstance() const
+	{
+		return this;
+	}
+
+
+};
+
+
+#endif /* VERTEX_H_ */

+ 350 - 0
src/tests/corsen/lib/XmlReader.h

@@ -0,0 +1,350 @@
+/*!
+ * \file XmlReader.h
+ * \brief Lecteur XML de base
+ * \author The VLE Development Team
+ * See the AUTHORS or Authors.txt file
+ * \version 2.0
+ */
+/*
+ * Copyright (C) 2012-2013 ULCO http://www.univ-littoral.fr
+ * Copyright (C) 2012-2013 INRA http://www.inra.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef XMLREADER_H_
+#define XMLREADER_H_
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <libxml/xmlmemory.h>
+#include <libxml/parser.h>
+#include <string>
+#include <sstream>
+
+/*! \class XmlReader
+ *
+ * \brief permet d'analyser un fichier XML
+ *
+ */
+
+
+class XmlReader
+{
+public :
+
+	static xmlNodePtr findNodeWithTagAttributAndAttrValue(xmlDocPtr doc, const char* tagName, const char* attributeName, const char* attributeValue)
+	{
+		xmlNodePtr cur = NULL;
+		//xmlChar *name;
+		std::string name;
+
+		cur = xmlDocGetRootElement(doc);
+
+		if (cur == NULL) {
+			fprintf(stderr,"Empty document\n");
+			xmlFreeDoc(doc);
+			exit(EXIT_FAILURE);
+		}
+
+		cur = cur->xmlChildrenNode;
+		while (cur != NULL) {
+			if ((!xmlStrcmp(cur->name, (const xmlChar *)tagName))) {
+				if (getAttributeAndTest(cur,attributeName,attributeValue)) {
+					break;
+				}
+			}
+			cur = cur->next;
+		}
+
+		if (cur==NULL) {
+			fprintf(stderr,"\n Tag name %s with attribute %s=%s is not defined\n ",tagName, attributeName,attributeValue);
+			exit(EXIT_FAILURE);
+		}
+		return cur;
+
+	}
+
+	/*!
+	 *  \brief trouver un noeud
+	 *
+	 *  Méthode qui permet de trouver un noeud avec le nom d'une balise  et le nom d'un attribut.
+	 *
+	 *  \param doc : le document dans lequel chercher.
+	 *  \param tagName : le nom de la balise .
+	 *  \param attributeName : le nom de l'attribut.
+	 *  \return un pointeur sur le noeud.
+	 */
+
+	static xmlNodePtr findNodeWithTagAndAttrName(xmlDocPtr doc, const char* tagName, const char* attributeName)
+	{
+		xmlNodePtr cur =NULL;
+		cur = findNode(doc,tagName,attributeName);
+
+		if (cur==NULL) {
+			fprintf(stderr,"\n Tag name %s with attribute %s is not defined\n ",tagName, attributeName);
+			//exit(EXIT_FAILURE);
+		}
+		return cur;
+
+	}
+	/*!
+	 *  \brief trouver valeur d'un attribut à partir du document.
+	 *
+	 *  Méthode qui permet de trouver la valeur d'un attribut avec le nom d'un attribut.
+	 *
+	 *  \param paramName : nom de l'attribut. On considère qu'il n'y a pas de doublons.
+	 *  \param doc : le document dans lequel chercher.
+	 *  \return la valeur de l'attribut sous forme de chaîne de caractères, NULL sinon
+	 */
+
+	static xmlChar* getStringParamValue(xmlDocPtr doc, const char* paramName)
+	{
+		xmlChar *value;
+
+		value = getParamValue(doc,paramName);
+		if (value==NULL) {
+			fprintf(stderr,"Value of parameter %s is not defined",paramName);
+			exit(EXIT_FAILURE);
+		} else {
+			return value;
+		}
+	}
+
+
+	/*!
+	 *  \brief trouver valeur d'un attribut à partir d'un noeud du document.
+	 *
+	 *  Méthode qui permet de trouver la valeur d'un attribut avec le nom d'un attribut.
+	 *
+	 *
+	 *  \param paramName : nom de l'attribut. On considère qu'il n'y a pas de doublons.
+	 *  \param node : le noeud dans lequel chercher.
+	 *  \return la valeur de l'attribut sous forme de chaîne de caractères, NULL sinon
+	 */
+
+
+	static xmlChar* getStringParamValueFromNode(xmlNodePtr node, const char* paramName)
+	{
+		xmlChar *value;
+
+		value = getParamValueFromNode(node,paramName);
+		if (value==NULL) {
+			fprintf(stderr,"Value of parameter %s is not defined",paramName);
+			exit(EXIT_FAILURE);
+		} else {
+			return value;
+		}
+
+	}
+
+	/*!
+	 *  \brief trouver valeur d'un attribut à partir du document.
+	 *
+	 *  Méthode qui permet de trouver la valeur d'un attribut avec le nom d'un attribut.
+	 *
+	 *
+	 *  \param paramName : nom de l'attribut. On considère qu'il n'y a pas de doublons.
+	 *  \param doc : le document dans lequel chercher.
+	 *  \return la valeur de l'attribut sous forme de réel, NULL sinon
+	 */
+
+	static float getFloatParamValue(xmlDocPtr doc, const char* paramName)
+	{
+		xmlChar *value;
+		float valueFloat;
+		value = getParamValue(doc,paramName);
+		if (value==NULL) {
+			fprintf(stderr,"Value of parameter %s is not defined",paramName);
+			exit(EXIT_FAILURE);
+		} else {
+			std::istringstream stringValue((char *) value);
+			stringValue>>valueFloat;
+			return valueFloat;
+		}
+
+	}
+
+	/*!
+	 *  \brief trouver valeur d'un attribut à partir d'un noeud du document.
+	 *
+	 *  Méthode qui permet de trouver la valeur d'un attribut avec le nom d'un attribut.
+	 *
+	 *
+	 *  \param paramName : nom de l'attribut. On considère qu'il n'y a pas de doublons.
+	 *  \param node : le noeud dans lequel chercher.
+	 *  \return la valeur de l'attribut sous la forme d'un réel, NULL sinon
+	 */
+
+
+	static float getFloatParamValueFromNode(xmlNodePtr node, const char* paramName)
+	{
+		xmlChar *value;
+		float valueFloat;
+
+		value = getParamValueFromNode(node,paramName);
+		if (value==NULL) {
+			fprintf(stderr,"Value of parameter %s is not defined",paramName);
+			exit(EXIT_FAILURE);
+		} else {
+			std::istringstream stringValue((char *) value);
+			stringValue>>valueFloat;
+			return valueFloat;
+		}
+
+	}
+
+	/*!
+	 *  \brief trouver valeur d'un attribut à partir du document.
+	 *
+	 *  Méthode qui permet de trouver la valeur d'un attribut avec le nom d'un attribut.
+	 *
+	 *
+	 *  \param paramName : nom de l'attribut. On considère qu'il n'y a pas de doublons.
+	 *  \param doc : le document dans lequel chercher.
+	 *  \return la valeur de l'attribut sous la forme d'un entier, NULL sinon
+	 */
+
+	static int getIntParamValue(xmlDocPtr doc, const char* paramName)
+	{
+		xmlChar *value;
+		int intValue;
+
+		value = getParamValue(doc,paramName);
+		if (value==NULL) {
+			//fprintf(stderr,"Value of parameter %s is not defined\n",paramName);
+			return 0;
+		} else {
+			std::istringstream stringValue((char *) value);
+			stringValue>>intValue;
+			return intValue;
+		}
+
+	}
+
+	static xmlChar *getParamValue(xmlDocPtr doc, const char* paramName)
+	{
+		xmlNodePtr cur;
+
+		cur = xmlDocGetRootElement(doc);
+
+		if (cur == NULL) {
+			fprintf(stderr,"Empty document\n");
+			xmlFreeDoc(doc);
+			exit(EXIT_FAILURE);
+		}
+
+		if (xmlStrcmp(cur->name, (const xmlChar *) "context")) {
+			fprintf(stderr,"Document of the wrong type, root node != context");
+			xmlFreeDoc(doc);
+			exit(EXIT_FAILURE);
+		}
+		return getParamValueFromNode(cur,paramName);
+
+
+	}
+
+	static xmlDocPtr parseDoc(const char *docname)
+	{
+		xmlDocPtr xmlDoc = xmlParseFile(docname);
+
+		/* Lecture et analyse du document XML contenu dans docname */
+		if (xmlDoc == NULL) {
+			fprintf(stderr,"Document %s not parsed successfully. \n",docname);
+			exit(EXIT_FAILURE);
+		}
+		return xmlDoc;
+	}
+
+	static std::string getAttribute(xmlNodePtr cur, const char* attr)
+	{
+		const xmlChar* attrName = (const xmlChar *)attr;
+		xmlChar* prop = xmlGetProp(cur, attrName);
+		std::string s((const char*)prop);
+		xmlFree(prop);
+		return s;
+
+	}
+
+	static bool getAttributeAndTest(xmlNodePtr cur, const char* attr, const char* attrValue)
+	{
+		bool isGoodAttr = false;
+		const xmlChar* attrName = (const xmlChar *)attr;
+		xmlChar* prop = xmlGetProp(cur, attrName);
+
+		if (prop != NULL) {
+			std::string s((const char*)prop);
+
+			if (s.compare(attrValue)==0) {
+				isGoodAttr = true;
+			}
+			xmlFree(prop);
+		}
+		return isGoodAttr;
+
+	}
+
+private :
+
+	static xmlNodePtr findNode(xmlDocPtr doc, const char* tagName, const char* attributeName)
+	{
+		xmlNodePtr cur = NULL;
+
+		cur = xmlDocGetRootElement(doc);
+
+		if (cur == NULL) {
+			fprintf(stderr,"Empty document\n");
+			xmlFreeDoc(doc);
+			exit(EXIT_FAILURE);
+		}
+
+		cur = cur->xmlChildrenNode;
+		while (cur != NULL) {
+			if ((!xmlStrcmp(cur->name, (const xmlChar *)tagName))) {
+				//name = (xmlChar *)xmlGetProp(cur, ( const xmlChar* )"name");
+				if (getAttributeAndTest(cur,"name",attributeName)) {
+					break;
+				}
+			}
+			cur = cur->next;
+		}
+
+		if (cur==NULL) {
+			fprintf(stderr,"\n Tag name %s with attribute %s is not defined\n ",tagName, attributeName);
+			//exit(EXIT_FAILURE);
+		}
+
+		return cur;
+	}
+
+
+	static xmlChar *getParamValueFromNode(xmlNodePtr cur, const char* paramName)
+	{
+		cur = cur->xmlChildrenNode;
+		while (cur != NULL) {
+			if ((!xmlStrcmp(cur->name, (const xmlChar *)"param"))) {
+				if (getAttributeAndTest(cur, "name", paramName)) {
+					//printf("%s \n",getAttribute(cur,"value").c_str());
+					return (xmlChar *)(getAttribute(cur,"value").c_str());
+				}
+			}
+			cur = cur->next;
+		}
+		return NULL;
+	}
+};
+
+#endif /* XMLREADER_H_ */

+ 132 - 0
src/tests/corsen/tests.cpp

@@ -0,0 +1,132 @@
+/**
+ * @file tests/corsen/tests.cpp
+ * @author The PARADEVS Development Team
+ * See the AUTHORS or Authors.txt file
+ */
+
+/*
+ * PARADEVS - the multimodeling and simulation environment
+ * This file is a part of the PARADEVS environment
+ *
+ * Copyright (C) 2013 ULCO http://www.univ-litoral.fr
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <boost/timer.hpp>
+
+#include <common/RootCoordinator.hpp>
+
+#include "lib/Corsen.hpp"
+
+// #include <tests/boost_graph/models.hpp>
+// #include <tests/boost_graph/graph_builder.hpp>
+// #include <tests/boost_graph/graph_manager.hpp>
+// #include <tests/boost_graph/graph_partitioning.hpp>
+
+// using namespace paradevs::common;
+// using namespace paradevs::common::scheduler;
+// using namespace paradevs::pdevs;
+// using namespace paradevs::tests::boost_graph;
+
+/**
+ * \fn void modifyFilesPath(string & absolutePath, vector<string *> & files)
+ * \brief Modifie le chemin par défaut des fichiers.
+ * \param absolutePath : chemin absolu ou sont stockés les fichiers
+ * \param files : tableau contenant les chemins vers les fichiers .
+ */
+
+void modifyFilesPath(std::string& absolutePath,
+                     std::vector < std::string* >& files)
+{
+    for (std::vector < std::string* >::iterator it = files.begin();
+        it != files.end(); it++) {
+        (*it)->insert(0, absolutePath);
+    }
+}
+
+int main(int argc, char** argv)
+{
+    bool defaultFilePath = true;
+    std::string absolutePath("");
+    std::string modeFile(".mode"), parametersFile("par.txt"),
+        elevationFile("alt"), outletFile("arbre"), layersFile("couche"),
+        contextFile("contexte_agro_prairie.xml") ,slopeFile("pav");
+    std::vector<std::string *> files;
+
+    files.push_back(&parametersFile);
+    files.push_back(&modeFile);
+    files.push_back(&elevationFile);
+    files.push_back(&outletFile);
+    files.push_back(&slopeFile);
+    files.push_back(&contextFile);
+    files.push_back(&layersFile);
+
+    /* Lecture des paramètres en ligne de commande */
+    if(argc > 1) {
+        int i = 1;
+        char* option;
+
+        while (i < argc) {
+            option = argv[i++];
+            if (strcmp(option,"-h") == 0) {
+                std::cerr << "Utilisation : " << argv[0]
+                          << "[-h] [-a absolute path]" << std::endl;
+                std::cerr << " -a : chemin absolu" << std::endl;
+                std::cerr << " -c : nom du fichier xml" << std::endl;
+                std::cerr << " -h : cette aide" << std::endl;
+                exit(0);
+            } else if (strcmp(option, "-a") == 0) {
+                if (i == argc) {
+                    std::cerr << "il manque le chemin absolu" << std::endl;
+                    exit(0);
+                }
+                defaultFilePath = false;
+                absolutePath.append(argv[i++]);
+                if(absolutePath.c_str()[absolutePath.size()- 1] != '/') {
+                    absolutePath+="/";
+                }
+                modifyFilesPath(absolutePath,files);
+            } else if  (strcmp(option,"-c")==0) {
+                if (i == argc) {
+                    std::cerr << "il manque le nom du fichier xml" << std::endl;
+                    exit(0);
+                }
+                contextFile.clear();
+                //contextFile.append("data/");
+                contextFile.append(argv[i++]);
+                std::vector<std::string *>context;
+                context.push_back(&contextFile);
+                modifyFilesPath(absolutePath,context);
+            } else {
+                std::cerr << "Option non reconnue essayez -h" << std::endl;
+                exit(0);
+            }
+        }
+    }
+
+    try {
+        if(defaultFilePath) {
+            std::string defaultFilePathStr("data/");
+            modifyFilesPath(defaultFilePathStr,files);
+        }
+        Corsen c;
+        c.read(files, absolutePath);
+        c.buildGraph();
+        // c.display();
+    } catch(std::exception & e) {
+        std::cout<<e.what()<<std::endl;
+    }
+    return 0;
+}