<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

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

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

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

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE data_manager_test
#include <boost/test/unit_test.hpp>
#include <boost/optional.hpp>

#include "kraken/data_manager.h"
#include <atomic>

//mock of navitia::type::Data class
class Data{
    public:
        bool load(const std::string&,
                  const boost::optional<std::string>&) {
            return load_status;
        }
        mutable std::atomic<bool> is_connected_to_rabbitmq;
        static bool load_status;
        static bool destructor_called;

        Data(){is_connected_to_rabbitmq = false;}

        ~Data(){Data::destructor_called = true;}
};
bool Data::load_status = true;
bool Data::destructor_called = false;

struct fixture{
    fixture(){
        Data::load_status = true;
        Data::destructor_called = false;
    }
};

BOOST_FIXTURE_TEST_SUITE(s, fixture)

BOOST_AUTO_TEST_CASE(get_data){
    DataManager<Data> data_manager;
    auto data = data_manager.get_data();
    BOOST_REQUIRE(data);
    BOOST_CHECK_EQUAL(Data::destructor_called, false);
}

BOOST_AUTO_TEST_CASE(load_success){
    DataManager<Data> data_manager;
    auto first_data = data_manager.get_data();
    BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
    BOOST_CHECK(data_manager.load(""));
    auto second_data = data_manager.get_data();
    BOOST_CHECK_NE(first_data, second_data);
    BOOST_CHECK_EQUAL(Data::destructor_called, false);
}

BOOST_AUTO_TEST_CASE(load_fail){
    DataManager<Data> data_manager;
    auto first_data = data_manager.get_data();
    BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
    Data::load_status = false;
    BOOST_CHECK(! data_manager.load(""));
    Data::load_status = true;
    auto second_data = data_manager.get_data();
    BOOST_CHECK_EQUAL(first_data, second_data);
}

BOOST_AUTO_TEST_CASE(destructor_called){
    DataManager<Data> data_manager;
    {
        auto first_data = data_manager.get_data();
        BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
        BOOST_CHECK(data_manager.load(""));
        auto second_data = data_manager.get_data();
        BOOST_CHECK_NE(first_data, second_data);
        BOOST_CHECK_EQUAL(Data::destructor_called, false);
        first_data = boost::shared_ptr<Data>();
    }
    BOOST_CHECK_EQUAL(Data::destructor_called, true);
    BOOST_CHECK(data_manager.get_data());
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Kraken: fix init of Data mock<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

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

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

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

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE data_manager_test
#include <boost/test/unit_test.hpp>
#include <boost/optional.hpp>

#include "kraken/data_manager.h"
#include <atomic>

//mock of navitia::type::Data class
class Data{
    public:
        bool load(const std::string&,
                  const boost::optional<std::string>&) {
            return load_status;
        }
        mutable std::atomic<bool> is_connected_to_rabbitmq;
        static bool load_status;
        static bool destructor_called;
        size_t data_identifier;

        Data(size_t data_identifier=0):
            data_identifier(data_identifier)
        {is_connected_to_rabbitmq = false;}

        ~Data(){Data::destructor_called = true;}
};
bool Data::load_status = true;
bool Data::destructor_called = false;

struct fixture{
    fixture(){
        Data::load_status = true;
        Data::destructor_called = false;
    }
};

BOOST_FIXTURE_TEST_SUITE(s, fixture)

BOOST_AUTO_TEST_CASE(get_data){
    DataManager<Data> data_manager;
    auto data = data_manager.get_data();
    BOOST_REQUIRE(data);
    BOOST_CHECK_EQUAL(Data::destructor_called, false);
}

BOOST_AUTO_TEST_CASE(load_success){
    DataManager<Data> data_manager;
    auto first_data = data_manager.get_data();
    BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
    BOOST_CHECK(data_manager.load(""));
    auto second_data = data_manager.get_data();
    BOOST_CHECK_NE(first_data, second_data);
    BOOST_CHECK_EQUAL(Data::destructor_called, false);
}

BOOST_AUTO_TEST_CASE(load_fail){
    DataManager<Data> data_manager;
    auto first_data = data_manager.get_data();
    BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
    Data::load_status = false;
    BOOST_CHECK(! data_manager.load(""));
    Data::load_status = true;
    auto second_data = data_manager.get_data();
    BOOST_CHECK_EQUAL(first_data, second_data);
}

BOOST_AUTO_TEST_CASE(destructor_called){
    DataManager<Data> data_manager;
    {
        auto first_data = data_manager.get_data();
        BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
        BOOST_CHECK(data_manager.load(""));
        auto second_data = data_manager.get_data();
        BOOST_CHECK_NE(first_data, second_data);
        BOOST_CHECK_EQUAL(Data::destructor_called, false);
        first_data = boost::shared_ptr<Data>();
    }
    BOOST_CHECK_EQUAL(Data::destructor_called, true);
    BOOST_CHECK(data_manager.get_data());
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/* Copyright © 2001-2015, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

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

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

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

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#include "raptor.h"
#include "raptor_visitors.h"

#include <boost/range/algorithm/reverse.hpp>

namespace navitia { namespace routing {

namespace {

struct PathElt {
    explicit PathElt(const type::StopTime& b,
                     const DateTime b_dt,
                     const type::StopTime& e,
                     const DateTime e_dt,
                     const PathElt* p = nullptr):
        begin_st(b),
        begin_dt(b_dt),
        end_st(e),
        end_dt(e_dt),
        prev(p) {}
    PathElt(const PathElt&) = delete;
    PathElt& operator=(const PathElt&) = delete;
    const type::StopTime& begin_st;
    const DateTime begin_dt;
    const type::StopTime& end_st;
    const DateTime end_dt;
    const PathElt* prev;
};

struct Section {
    Section(const type::StopTime& in,
            const DateTime in_dt,
            const type::StopTime& out,
            const DateTime out_dt):
        get_in_st(&in), get_in_dt(in_dt), get_out_st(&out), get_out_dt(out_dt)
    {}
    const type::StopTime* get_in_st;
    DateTime get_in_dt;
    const type::StopTime* get_out_st;
    DateTime get_out_dt;
};

template<typename Visitor>
struct RaptorSolutionReader {
    RaptorSolutionReader(const RAPTOR& r,
                         const Visitor& vis,
                         const RAPTOR::vec_stop_point_duration& d,
                         const bool disruption,
                         const type::AccessibiliteParams& access):
        raptor(r), v(vis), dep(d), disruption_active(disruption), accessibilite_params(access)
    {}
    const RAPTOR& raptor;
    const Visitor& v;
    const RAPTOR::vec_stop_point_duration& dep;
    const bool disruption_active;
    const type::AccessibiliteParams& accessibilite_params;
    size_t nb_solutions = 0;

    void handle_solution(const PathElt& path) {
        ++nb_solutions;
        std::vector<Section> sections;
        for (const PathElt* elt = &path; elt != nullptr; elt = elt->prev) {
            if (v.clockwise()) {
                sections.emplace_back(elt->begin_st, elt->begin_dt, elt->end_st, elt->end_dt);
            } else {
                sections.emplace_back(elt->end_st, elt->end_dt, elt->begin_st, elt->begin_dt);
            }
        }
        if (v.clockwise()) { boost::reverse(sections); }

        for (const auto& s: sections) {
            std::cout << "("
                      << s.get_in_st->journey_pattern_point->journey_pattern->route->line->uri << ": "
                      << s.get_in_st->journey_pattern_point->stop_point->uri << "@"
                      << s.get_in_dt << ", "
                      << s.get_out_st->journey_pattern_point->stop_point->uri << "@"
                      << s.get_out_dt << ")";
        }
        std::cout << std::endl;
    }

    void transfer(const unsigned count,
                  const SpIdx sp_idx,
                  const DateTime begin_dt,
                  const PathElt* path) {
        const auto& cnx_list = v.clockwise() ?
            raptor.data.dataRaptor->connections.forward_connections :
            raptor.data.dataRaptor->connections.backward_connections;
        for (const auto& conn: cnx_list[sp_idx]) {
            const DateTime transfer_limit = raptor.labels[count].dt_pt(conn.sp_idx);
            const DateTime transfer_end = v.combine(begin_dt, conn.duration);
            if (v.comp(transfer_limit, transfer_end)) { continue; }

            // transfer is OK
            begin_pt(count, conn.sp_idx, transfer_end, path);
        }
    }

    template<typename Range>
    void end_pt(const unsigned count,
                const PathElt* path,
                const std::pair<const type::StopTime*, DateTime>& begin_st_dt,
                const uint16_t begin_zone,
                DateTime& cur_dt,
                const Range& st_range) {
        static const auto no_zone = std::numeric_limits<uint16_t>::max();

        for (const auto& end_st: st_range) {
            const auto current_time = end_st.section_end_time(
                v.clockwise(), DateTimeUtils::hour(cur_dt));
            DateTimeUtils::update(cur_dt, current_time, v.clockwise());

            // trying to end
            if (! end_st.valid_end(v.clockwise())) { continue; }
            if (begin_zone != no_zone && begin_zone == end_st.local_traffic_zone) { continue; }
            const SpIdx end_sp_idx = SpIdx(*end_st.journey_pattern_point->stop_point);
            if (! raptor.labels[count - 1].transfer_is_initialized(end_sp_idx)) { continue; }
            const DateTime end_limit = raptor.labels[count - 1].dt_transfer(end_sp_idx);
            if (v.comp(end_limit, cur_dt)) { continue; }

            // great, we can end
            const PathElt new_path(*begin_st_dt.first, begin_st_dt.second, end_st, cur_dt, path);
            if (count == 1) {
                // we've finished, and it's a valid end as it is initialized
                handle_solution(new_path);
            } else {
                transfer(count - 1, end_sp_idx, cur_dt, &new_path);
            }
        }
    }

    void begin_pt(const unsigned count,
                  const SpIdx begin_sp_idx,
                  const DateTime begin_dt,
                  const PathElt* path = nullptr) {
        const DateTime begin_limit = raptor.labels[count].dt_pt(begin_sp_idx);
        for (const auto jpp: raptor.data.dataRaptor->jpps_from_sp[begin_sp_idx]) {
            // trying to begin
            const auto begin_st_dt = raptor.next_st.next_stop_time(
                jpp.idx, begin_dt, v.clockwise(), disruption_active,
                accessibilite_params.vehicle_properties/*, jpp.has_freq*/);
            if (begin_st_dt.first == nullptr) { continue; }
            if (v.comp(begin_limit, begin_st_dt.second)) { continue; }

            // great, we can begin
            auto cur_dt = begin_st_dt.second;
            const auto begin_zone = begin_st_dt.first->local_traffic_zone;
            end_pt(count, path, begin_st_dt, begin_zone, cur_dt,
                   v.st_range(*begin_st_dt.first).advance_begin(1));

            // continuing in the stay in
            for (const auto* stay_in_vj = v.get_extension_vj(begin_st_dt.first->vehicle_journey);
                 stay_in_vj != nullptr;
                 stay_in_vj = v.get_extension_vj(stay_in_vj)) {
                end_pt(count, path, begin_st_dt, begin_zone, cur_dt,
                       v.stop_time_list(stay_in_vj));
            }
        }
    }
};
template<typename Visitor> RaptorSolutionReader<Visitor>
make_raptor_solution_reader(const RAPTOR& r,
                            const Visitor& v,
                            const RAPTOR::vec_stop_point_duration& d,
                            const bool disruption_active,
                            const type::AccessibiliteParams& accessibilite_params) {
    return RaptorSolutionReader<Visitor>(r, v, d, disruption_active, accessibilite_params);
}

template<typename Visitor>
size_t read_solutions(const RAPTOR& raptor,
                    const Visitor& v,
                    const RAPTOR::vec_stop_point_duration& dep,
                    const RAPTOR::vec_stop_point_duration& arr,
                    const bool disruption_active,
                    const type::AccessibiliteParams& accessibilite_params)
{
    auto reader = make_raptor_solution_reader(raptor, v, dep, disruption_active, accessibilite_params);
    std::cout << "begin reader" << std::endl;
    for (unsigned count = 1; count <= raptor.count; ++count) {
        auto& working_labels = raptor.labels[count];
        for (const auto& a: arr) {
            if (working_labels.pt_is_initialized(a.first)) {
                std::cout << "from " << raptor.get_sp(a.first)->uri << std::endl;
                reader.begin_pt(count, a.first, working_labels.dt_pt(a.first));
            }
        }
    }
    std::cout << "end reader" << std::endl;
    return reader.nb_solutions;
}

} // anonymous namespace

size_t read_solutions(const RAPTOR& raptor,
                      const bool clockwise,
                      const RAPTOR::vec_stop_point_duration& dep,
                      const RAPTOR::vec_stop_point_duration& arr,
                      const bool disruption_active,
                      const type::AccessibiliteParams& accessibilite_params)
{
    if (clockwise) {
        return read_solutions(raptor, raptor_reverse_visitor(), dep, arr,
                              disruption_active, accessibilite_params);
    } else {
        return read_solutions(raptor, raptor_visitor(), dep, arr,
                              disruption_active, accessibilite_params);
    }
}

}} // namespace navitia::routing
<commit_msg>raptor: add Journey object in the reader<commit_after>/* Copyright © 2001-2015, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

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

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

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

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#include "raptor.h"
#include "raptor_visitors.h"

#include <boost/range/algorithm/reverse.hpp>

namespace navitia { namespace routing {

namespace {

struct PathElt {
    explicit PathElt(const type::StopTime& b,
                     const DateTime b_dt,
                     const type::StopTime& e,
                     const DateTime e_dt,
                     const PathElt* p = nullptr):
        begin_st(b),
        begin_dt(b_dt),
        end_st(e),
        end_dt(e_dt),
        prev(p) {}
    PathElt(const PathElt&) = delete;
    PathElt& operator=(const PathElt&) = delete;
    const type::StopTime& begin_st;
    const DateTime begin_dt;
    const type::StopTime& end_st;
    const DateTime end_dt;
    const PathElt* prev;
};

struct Journey {
    Journey(const PathElt& path, const bool c): clockwise(c) {
        for (const PathElt* elt = &path; elt != nullptr; elt = elt->prev) {
            if (clockwise) {
                sections.emplace_back(elt->begin_st, elt->begin_dt, elt->end_st, elt->end_dt);
            } else {
                sections.emplace_back(elt->end_st, elt->end_dt, elt->begin_st, elt->begin_dt);
            }
        }
        if (clockwise) { boost::reverse(sections); }
    }

    struct Section {
        Section(const type::StopTime& in,
                const DateTime in_dt,
                const type::StopTime& out,
                const DateTime out_dt):
            get_in_st(&in), get_in_dt(in_dt), get_out_st(&out), get_out_dt(out_dt)
            {}
        const type::StopTime* get_in_st;
        DateTime get_in_dt;
        const type::StopTime* get_out_st;
        DateTime get_out_dt;
    };
    std::vector<Section> sections;
    bool clockwise;
};

template<typename Visitor>
struct RaptorSolutionReader {
    RaptorSolutionReader(const RAPTOR& r,
                         const Visitor& vis,
                         const RAPTOR::vec_stop_point_duration& d,
                         const bool disruption,
                         const type::AccessibiliteParams& access):
        raptor(r), v(vis), dep(d), disruption_active(disruption), accessibilite_params(access)
    {}
    const RAPTOR& raptor;
    const Visitor& v;
    const RAPTOR::vec_stop_point_duration& dep;
    const bool disruption_active;
    const type::AccessibiliteParams& accessibilite_params;
    size_t nb_solutions = 0;

    void handle_solution(const PathElt& path) {
        ++nb_solutions;
        Journey journey(path, v.clockwise());

        for (const auto& s: journey.sections) {
            std::cout << "("
                      << s.get_in_st->journey_pattern_point->journey_pattern->route->line->uri << ": "
                      << s.get_in_st->journey_pattern_point->stop_point->uri << "@"
                      << s.get_in_dt << ", "
                      << s.get_out_st->journey_pattern_point->stop_point->uri << "@"
                      << s.get_out_dt << ")";
        }
        std::cout << std::endl;
    }

    void transfer(const unsigned count,
                  const SpIdx sp_idx,
                  const DateTime begin_dt,
                  const PathElt* path) {
        const auto& cnx_list = v.clockwise() ?
            raptor.data.dataRaptor->connections.forward_connections :
            raptor.data.dataRaptor->connections.backward_connections;
        for (const auto& conn: cnx_list[sp_idx]) {
            const DateTime transfer_limit = raptor.labels[count].dt_pt(conn.sp_idx);
            const DateTime transfer_end = v.combine(begin_dt, conn.duration);
            if (v.comp(transfer_limit, transfer_end)) { continue; }

            // transfer is OK
            begin_pt(count, conn.sp_idx, transfer_end, path);
        }
    }

    template<typename Range>
    void end_pt(const unsigned count,
                const PathElt* path,
                const std::pair<const type::StopTime*, DateTime>& begin_st_dt,
                const uint16_t begin_zone,
                DateTime& cur_dt,
                const Range& st_range) {
        static const auto no_zone = std::numeric_limits<uint16_t>::max();

        for (const auto& end_st: st_range) {
            const auto current_time = end_st.section_end_time(
                v.clockwise(), DateTimeUtils::hour(cur_dt));
            DateTimeUtils::update(cur_dt, current_time, v.clockwise());

            // trying to end
            if (! end_st.valid_end(v.clockwise())) { continue; }
            if (begin_zone != no_zone && begin_zone == end_st.local_traffic_zone) { continue; }
            const SpIdx end_sp_idx = SpIdx(*end_st.journey_pattern_point->stop_point);
            if (! raptor.labels[count - 1].transfer_is_initialized(end_sp_idx)) { continue; }
            const DateTime end_limit = raptor.labels[count - 1].dt_transfer(end_sp_idx);
            if (v.comp(end_limit, cur_dt)) { continue; }

            // great, we can end
            const PathElt new_path(*begin_st_dt.first, begin_st_dt.second, end_st, cur_dt, path);
            if (count == 1) {
                // we've finished, and it's a valid end as it is initialized
                handle_solution(new_path);
            } else {
                transfer(count - 1, end_sp_idx, cur_dt, &new_path);
            }
        }
    }

    void begin_pt(const unsigned count,
                  const SpIdx begin_sp_idx,
                  const DateTime begin_dt,
                  const PathElt* path = nullptr) {
        const DateTime begin_limit = raptor.labels[count].dt_pt(begin_sp_idx);
        for (const auto jpp: raptor.data.dataRaptor->jpps_from_sp[begin_sp_idx]) {
            // trying to begin
            const auto begin_st_dt = raptor.next_st.next_stop_time(
                jpp.idx, begin_dt, v.clockwise(), disruption_active,
                accessibilite_params.vehicle_properties/*, jpp.has_freq*/);
            if (begin_st_dt.first == nullptr) { continue; }
            if (v.comp(begin_limit, begin_st_dt.second)) { continue; }

            // great, we can begin
            auto cur_dt = begin_st_dt.second;
            const auto begin_zone = begin_st_dt.first->local_traffic_zone;
            end_pt(count, path, begin_st_dt, begin_zone, cur_dt,
                   v.st_range(*begin_st_dt.first).advance_begin(1));

            // continuing in the stay in
            for (const auto* stay_in_vj = v.get_extension_vj(begin_st_dt.first->vehicle_journey);
                 stay_in_vj != nullptr;
                 stay_in_vj = v.get_extension_vj(stay_in_vj)) {
                end_pt(count, path, begin_st_dt, begin_zone, cur_dt,
                       v.stop_time_list(stay_in_vj));
            }
        }
    }
};
template<typename Visitor> RaptorSolutionReader<Visitor>
make_raptor_solution_reader(const RAPTOR& r,
                            const Visitor& v,
                            const RAPTOR::vec_stop_point_duration& d,
                            const bool disruption_active,
                            const type::AccessibiliteParams& accessibilite_params) {
    return RaptorSolutionReader<Visitor>(r, v, d, disruption_active, accessibilite_params);
}

template<typename Visitor>
size_t read_solutions(const RAPTOR& raptor,
                    const Visitor& v,
                    const RAPTOR::vec_stop_point_duration& dep,
                    const RAPTOR::vec_stop_point_duration& arr,
                    const bool disruption_active,
                    const type::AccessibiliteParams& accessibilite_params)
{
    auto reader = make_raptor_solution_reader(raptor, v, dep, disruption_active, accessibilite_params);
    std::cout << "begin reader" << std::endl;
    for (unsigned count = 1; count <= raptor.count; ++count) {
        auto& working_labels = raptor.labels[count];
        for (const auto& a: arr) {
            if (working_labels.pt_is_initialized(a.first)) {
                std::cout << "from " << raptor.get_sp(a.first)->uri << std::endl;
                reader.begin_pt(count, a.first, working_labels.dt_pt(a.first));
            }
        }
    }
    std::cout << "end reader" << std::endl;
    return reader.nb_solutions;
}

} // anonymous namespace

size_t read_solutions(const RAPTOR& raptor,
                      const bool clockwise,
                      const RAPTOR::vec_stop_point_duration& dep,
                      const RAPTOR::vec_stop_point_duration& arr,
                      const bool disruption_active,
                      const type::AccessibiliteParams& accessibilite_params)
{
    if (clockwise) {
        return read_solutions(raptor, raptor_reverse_visitor(), dep, arr,
                              disruption_active, accessibilite_params);
    } else {
        return read_solutions(raptor, raptor_visitor(), dep, arr,
                              disruption_active, accessibilite_params);
    }
}

}} // namespace navitia::routing
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <sstream>
#include <ios>
#include <rang.hpp>

#include "Tools/Exception/exception.hpp"

#include "Terminal_BFER.hpp"

using namespace aff3ct;
using namespace aff3ct::tools;

template <typename B, typename R>
Terminal_BFER<B,R>
::Terminal_BFER(const module::Monitor_BFER<B,R> &monitor, bool display_mutinfo)
: Terminal       (                                ),
  monitor        (monitor                         ),
  t_snr          (std::chrono::steady_clock::now()),
  real_time_state(0                               ),
  display_mutinfo(display_mutinfo                 )
{
}

template <typename B, typename R>
void Terminal_BFER<B,R>
::set_noise(const Noise<float>& noise)
{
	if (this->n != nullptr)
		delete this->n;

	this->n = noise.clone();
}

template <typename B, typename R>
void Terminal_BFER<B,R>
::set_noise(const Noise<double>& n)
{
	if (this->n != nullptr)
		delete this->n;

	this->n = tools::cast<float>(n);
}

template <typename B, typename R>
void Terminal_BFER<B,R>
::legend(std::ostream &stream)
{
	this->cols_groups.resize(2);

	auto& bfer_title       = this->cols_groups[0].first;
	auto& bfer_cols        = this->cols_groups[0].second;
	auto& throughput_title = this->cols_groups[1].first;
	auto& throughput_cols  = this->cols_groups[1].second;

	bfer_title = std::make_pair("Bit Error Rate (BER) and Frame Error Rate (FER)", "");

	switch (this->n->get_type())
	{
		case Noise_type::SIGMA :
			bfer_title.second = "depending on the Signal Noise Ratio (SNR)";
			bfer_cols.push_back(std::make_pair("Es/N0", "(dB)"));
			bfer_cols.push_back(std::make_pair("Eb/N0", "(dB)"));
		break;
		case Noise_type::ROP :
			bfer_title.second = "depending on the Received Optical Power (ROP)";
			bfer_cols.push_back(std::make_pair("ROP", "(dB)"));
		break;
		case Noise_type::EP :
			bfer_title.second = "depending on the Erasure Probability (EP)";
			bfer_cols.push_back(std::make_pair("EP", ""));
		break;
	}

	if (display_mutinfo)
	{
		bfer_title.first = "MutInfo (MI), " + bfer_title.first;
		bfer_cols.push_back(std::make_pair("MI", ""));
	}

	bfer_cols.push_back(std::make_pair("FRA", ""));
	bfer_cols.push_back(std::make_pair("BE",  ""));
	bfer_cols.push_back(std::make_pair("FE",  ""));
	bfer_cols.push_back(std::make_pair("BER", ""));
	bfer_cols.push_back(std::make_pair("FER", ""));

	throughput_title = std::make_pair("Global throughput", "and elapsed time");
	throughput_cols.push_back(std::make_pair("SIM_THR", "(Mb/s)"));
	throughput_cols.push_back(std::make_pair("ET/RT", "(hhmmss)"));

	// stream << "# " << "---------------------------------------------------------------------||---------------------" << std::endl;
	// stream << "# " << "      Bit Error Rate (BER) and Frame Error Rate (FER) depending      ||  Global throughput  " << std::endl;
	// stream << "# " << "                   on the Erasure Probability (EP)                   ||  and elapsed time   " << std::endl;
	// stream << "# " << "---------------------------------------------------------------------||---------------------" << std::endl;
	// stream << "# " << "---------|-----------|-----------|-----------|-----------|-----------||----------|----------" << std::endl;
	// stream << "# " << "      EP |       FRA |        BE |        FE |       BER |       FER ||  SIM_THR |    ET/RT " << std::endl;
	// stream << "# " << "         |           |           |           |           |           ||   (Mb/s) | (hhmmss) " << std::endl;
	// stream << "# " << "---------|-----------|-----------|-----------|-----------|-----------||----------|----------" << std::endl;

	Terminal::legend(stream); // print effectively the legend
}

template <typename B, typename R>
void Terminal_BFER<B,R>
::_report(std::ostream &stream)
{
	using namespace std::chrono;
	using namespace std;

	auto ber = monitor.get_ber();
	auto fer = monitor.get_fer();
	auto fra = monitor.get_n_analyzed_fra();
	auto be  = monitor.get_n_be();
	auto fe  = monitor.get_n_fe();
	auto MI  = monitor.get_MI  ();

	auto simu_time = (float)duration_cast<nanoseconds>(steady_clock::now() - t_snr).count() * 0.000000001f;
	auto simu_cthr = ((float)monitor.get_K() * (float)monitor.get_n_analyzed_fra()) / simu_time ; // = bps
	simu_cthr /= 1000.f; // = kbps
	simu_cthr /= 1000.f; // = mbps

	if (module::Monitor::is_interrupt()) stream << "\r";

	stream << data_tag;

	const auto report_style = rang::style::bold;

	switch (this->n->get_type())
	{
		case Noise_type::SIGMA :
		{
			auto sig = dynamic_cast<const tools::Sigma<>*>(this->n);
			stream << setprecision(2) << fixed << setw(column_width - 1) << sig->get_esn0() << report_style
			       << spaced_scol_separator << rang::style::reset;
			stream << setprecision(2) << fixed << setw(column_width - 1) << sig->get_ebn0() << report_style
			       << spaced_scol_separator << rang::style::reset;
			break;
		}
		case Noise_type::ROP :
		{
			stream << setprecision(2) << fixed << setw(column_width - 1) << this->n->get_noise() << report_style
			       << spaced_scol_separator << rang::style::reset;
			break;
		}
		case Noise_type::EP :
		{
			stream << setprecision(4) << fixed << setw(column_width - 1) << this->n->get_noise() << report_style
			       << spaced_scol_separator << rang::style::reset;
			break;
		}
	}

	stringstream str_ber, str_fer, str_MI;
	str_ber << setprecision(2) << scientific << setw(column_width-1) << ber;
	str_fer << setprecision(2) << scientific << setw(column_width-1) << fer;
	str_MI  << setprecision(2) << scientific << setw(column_width-1) << MI;

	const unsigned long long l = 99999999;  // limit 0

	if (display_mutinfo)
	stream <<                                                                                str_MI.str() << report_style << spaced_scol_separator << rang::style::reset;
	stream << setprecision((fra > l) ? 2 : 0) << ((fra > l) ? scientific : fixed) << setw(column_width-1) << ((fra > l) ? (float)fra : fra) << report_style << spaced_scol_separator << rang::style::reset;
	stream << setprecision(( be > l) ? 2 : 0) << ((be  > l) ? scientific : fixed) << setw(column_width-1) << (( be > l) ? (float) be :  be) << report_style << spaced_scol_separator << rang::style::reset;
	stream << setprecision(( fe > l) ? 2 : 0) << ((fe  > l) ? scientific : fixed) << setw(column_width-1) << (( fe > l) ? (float) fe :  fe) << report_style << spaced_scol_separator << rang::style::reset;
	stream <<                                                                                str_ber.str() << report_style << spaced_scol_separator << rang::style::reset;
	stream <<                                                                                str_fer.str() << report_style << spaced_dcol_separator << rang::style::reset;
	stream << setprecision(                2) <<                           fixed  << setw(column_width-1) <<                      simu_cthr;
}

template <typename B, typename R>
void Terminal_BFER<B,R>
::temp_report(std::ostream &stream)
{
	using namespace std::chrono;

	std::ios::fmtflags f(stream.flags());

	_report(stream);

	auto et = duration_cast<milliseconds>(steady_clock::now() - t_snr).count() / 1000.f;
	auto tr = et * ((float)monitor.get_fe_limit() / (float)monitor.get_n_fe()) - et;
	auto tr_format = get_time_format((monitor.get_n_fe() == 0) ? 0 : tr);

	stream << rang::style::bold << spaced_scol_separator << rang::style::reset << std::setprecision(0) << std::fixed
	       << std::setw(column_width-1) << tr_format;

	stream << " ";
	switch (real_time_state)
	{
		case 0: stream << rang::style::bold << rang::fg::green << "*" << rang::style::reset; break;
		case 1: stream << rang::style::bold << rang::fg::green << "*" << rang::style::reset; break;
		case 2: stream << rang::style::bold << rang::fg::green << " " << rang::style::reset; break;
		case 3: stream << rang::style::bold << rang::fg::green << " " << rang::style::reset; break;
		default: break;
	}
	real_time_state = (real_time_state + (unsigned short)1) % (unsigned short)4;
	stream << "\r";

	stream.flush();
	stream.flags(f);
}

template <typename B, typename R>
void Terminal_BFER<B,R>
::final_report(std::ostream &stream)
{
	using namespace std::chrono;

	std::ios::fmtflags f(stream.flags());

	Terminal::final_report(stream);

	this->_report(stream);

	auto et = duration_cast<milliseconds>(steady_clock::now() - t_snr).count() / 1000.f;
	auto et_format = get_time_format(et);

	stream << rang::style::bold << spaced_scol_separator << rang::style::reset << std::setprecision(0) << std::fixed
	       << std::setw(column_width-1) << et_format;

	stream << (module::Monitor::is_interrupt() ? " x" : "  ") << std::endl;

	t_snr = std::chrono::steady_clock::now();

	stream.flags(f);
}

// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::tools::Terminal_BFER<B_8, Q_8>;
template class aff3ct::tools::Terminal_BFER<B_16,Q_16>;
template class aff3ct::tools::Terminal_BFER<B_32,Q_32>;
template class aff3ct::tools::Terminal_BFER<B_64,Q_64>;
#else
template class aff3ct::tools::Terminal_BFER<B,Q>;
#endif
// ==================================================================================== explicit template instantiation
<commit_msg>Init n to nullptr in constructor<commit_after>#include <iostream>
#include <iomanip>
#include <sstream>
#include <ios>
#include <rang.hpp>

#include "Tools/Exception/exception.hpp"

#include "Terminal_BFER.hpp"

using namespace aff3ct;
using namespace aff3ct::tools;

template <typename B, typename R>
Terminal_BFER<B,R>
::Terminal_BFER(const module::Monitor_BFER<B,R> &monitor, bool display_mutinfo)
: Terminal       (                                ),
  monitor        (monitor                         ),
  t_snr          (std::chrono::steady_clock::now()),
  real_time_state(0                               ),
  display_mutinfo(display_mutinfo                 ),
  n              (nullptr                         )
{
}

template <typename B, typename R>
void Terminal_BFER<B,R>
::set_noise(const Noise<float>& noise)
{
	if (this->n != nullptr)
		delete this->n;

	this->n = noise.clone();
}

template <typename B, typename R>
void Terminal_BFER<B,R>
::set_noise(const Noise<double>& n)
{
	if (this->n != nullptr)
		delete this->n;

	this->n = tools::cast<float>(n);
}

template <typename B, typename R>
void Terminal_BFER<B,R>
::legend(std::ostream &stream)
{
	this->cols_groups.resize(2);

	auto& bfer_title       = this->cols_groups[0].first;
	auto& bfer_cols        = this->cols_groups[0].second;
	auto& throughput_title = this->cols_groups[1].first;
	auto& throughput_cols  = this->cols_groups[1].second;

	bfer_title = std::make_pair("Bit Error Rate (BER) and Frame Error Rate (FER)", "");

	switch (this->n->get_type())
	{
		case Noise_type::SIGMA :
			bfer_title.second = "depending on the Signal Noise Ratio (SNR)";
			bfer_cols.push_back(std::make_pair("Es/N0", "(dB)"));
			bfer_cols.push_back(std::make_pair("Eb/N0", "(dB)"));
		break;
		case Noise_type::ROP :
			bfer_title.second = "depending on the Received Optical Power (ROP)";
			bfer_cols.push_back(std::make_pair("ROP", "(dB)"));
		break;
		case Noise_type::EP :
			bfer_title.second = "depending on the Erasure Probability (EP)";
			bfer_cols.push_back(std::make_pair("EP", ""));
		break;
	}

	if (display_mutinfo)
	{
		bfer_title.first = "MutInfo (MI), " + bfer_title.first;
		bfer_cols.push_back(std::make_pair("MI", ""));
	}

	bfer_cols.push_back(std::make_pair("FRA", ""));
	bfer_cols.push_back(std::make_pair("BE",  ""));
	bfer_cols.push_back(std::make_pair("FE",  ""));
	bfer_cols.push_back(std::make_pair("BER", ""));
	bfer_cols.push_back(std::make_pair("FER", ""));

	throughput_title = std::make_pair("Global throughput", "and elapsed time");
	throughput_cols.push_back(std::make_pair("SIM_THR", "(Mb/s)"));
	throughput_cols.push_back(std::make_pair("ET/RT", "(hhmmss)"));

	// stream << "# " << "---------------------------------------------------------------------||---------------------" << std::endl;
	// stream << "# " << "      Bit Error Rate (BER) and Frame Error Rate (FER) depending      ||  Global throughput  " << std::endl;
	// stream << "# " << "                   on the Erasure Probability (EP)                   ||  and elapsed time   " << std::endl;
	// stream << "# " << "---------------------------------------------------------------------||---------------------" << std::endl;
	// stream << "# " << "---------|-----------|-----------|-----------|-----------|-----------||----------|----------" << std::endl;
	// stream << "# " << "      EP |       FRA |        BE |        FE |       BER |       FER ||  SIM_THR |    ET/RT " << std::endl;
	// stream << "# " << "         |           |           |           |           |           ||   (Mb/s) | (hhmmss) " << std::endl;
	// stream << "# " << "---------|-----------|-----------|-----------|-----------|-----------||----------|----------" << std::endl;

	Terminal::legend(stream); // print effectively the legend
}

template <typename B, typename R>
void Terminal_BFER<B,R>
::_report(std::ostream &stream)
{
	using namespace std::chrono;
	using namespace std;

	auto ber = monitor.get_ber();
	auto fer = monitor.get_fer();
	auto fra = monitor.get_n_analyzed_fra();
	auto be  = monitor.get_n_be();
	auto fe  = monitor.get_n_fe();
	auto MI  = monitor.get_MI  ();

	auto simu_time = (float)duration_cast<nanoseconds>(steady_clock::now() - t_snr).count() * 0.000000001f;
	auto simu_cthr = ((float)monitor.get_K() * (float)monitor.get_n_analyzed_fra()) / simu_time ; // = bps
	simu_cthr /= 1000.f; // = kbps
	simu_cthr /= 1000.f; // = mbps

	if (module::Monitor::is_interrupt()) stream << "\r";

	stream << data_tag;

	const auto report_style = rang::style::bold;

	switch (this->n->get_type())
	{
		case Noise_type::SIGMA :
		{
			auto sig = dynamic_cast<const tools::Sigma<>*>(this->n);
			stream << setprecision(2) << fixed << setw(column_width - 1) << sig->get_esn0() << report_style
			       << spaced_scol_separator << rang::style::reset;
			stream << setprecision(2) << fixed << setw(column_width - 1) << sig->get_ebn0() << report_style
			       << spaced_scol_separator << rang::style::reset;
			break;
		}
		case Noise_type::ROP :
		{
			stream << setprecision(2) << fixed << setw(column_width - 1) << this->n->get_noise() << report_style
			       << spaced_scol_separator << rang::style::reset;
			break;
		}
		case Noise_type::EP :
		{
			stream << setprecision(4) << fixed << setw(column_width - 1) << this->n->get_noise() << report_style
			       << spaced_scol_separator << rang::style::reset;
			break;
		}
	}

	stringstream str_ber, str_fer, str_MI;
	str_ber << setprecision(2) << scientific << setw(column_width-1) << ber;
	str_fer << setprecision(2) << scientific << setw(column_width-1) << fer;
	str_MI  << setprecision(2) << scientific << setw(column_width-1) << MI;

	const unsigned long long l = 99999999;  // limit 0

	if (display_mutinfo)
	stream <<                                                                                str_MI.str() << report_style << spaced_scol_separator << rang::style::reset;
	stream << setprecision((fra > l) ? 2 : 0) << ((fra > l) ? scientific : fixed) << setw(column_width-1) << ((fra > l) ? (float)fra : fra) << report_style << spaced_scol_separator << rang::style::reset;
	stream << setprecision(( be > l) ? 2 : 0) << ((be  > l) ? scientific : fixed) << setw(column_width-1) << (( be > l) ? (float) be :  be) << report_style << spaced_scol_separator << rang::style::reset;
	stream << setprecision(( fe > l) ? 2 : 0) << ((fe  > l) ? scientific : fixed) << setw(column_width-1) << (( fe > l) ? (float) fe :  fe) << report_style << spaced_scol_separator << rang::style::reset;
	stream <<                                                                                str_ber.str() << report_style << spaced_scol_separator << rang::style::reset;
	stream <<                                                                                str_fer.str() << report_style << spaced_dcol_separator << rang::style::reset;
	stream << setprecision(                2) <<                           fixed  << setw(column_width-1) <<                      simu_cthr;
}

template <typename B, typename R>
void Terminal_BFER<B,R>
::temp_report(std::ostream &stream)
{
	using namespace std::chrono;

	std::ios::fmtflags f(stream.flags());

	_report(stream);

	auto et = duration_cast<milliseconds>(steady_clock::now() - t_snr).count() / 1000.f;
	auto tr = et * ((float)monitor.get_fe_limit() / (float)monitor.get_n_fe()) - et;
	auto tr_format = get_time_format((monitor.get_n_fe() == 0) ? 0 : tr);

	stream << rang::style::bold << spaced_scol_separator << rang::style::reset << std::setprecision(0) << std::fixed
	       << std::setw(column_width-1) << tr_format;

	stream << " ";
	switch (real_time_state)
	{
		case 0: stream << rang::style::bold << rang::fg::green << "*" << rang::style::reset; break;
		case 1: stream << rang::style::bold << rang::fg::green << "*" << rang::style::reset; break;
		case 2: stream << rang::style::bold << rang::fg::green << " " << rang::style::reset; break;
		case 3: stream << rang::style::bold << rang::fg::green << " " << rang::style::reset; break;
		default: break;
	}
	real_time_state = (real_time_state + (unsigned short)1) % (unsigned short)4;
	stream << "\r";

	stream.flush();
	stream.flags(f);
}

template <typename B, typename R>
void Terminal_BFER<B,R>
::final_report(std::ostream &stream)
{
	using namespace std::chrono;

	std::ios::fmtflags f(stream.flags());

	Terminal::final_report(stream);

	this->_report(stream);

	auto et = duration_cast<milliseconds>(steady_clock::now() - t_snr).count() / 1000.f;
	auto et_format = get_time_format(et);

	stream << rang::style::bold << spaced_scol_separator << rang::style::reset << std::setprecision(0) << std::fixed
	       << std::setw(column_width-1) << et_format;

	stream << (module::Monitor::is_interrupt() ? " x" : "  ") << std::endl;

	t_snr = std::chrono::steady_clock::now();

	stream.flags(f);
}

// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::tools::Terminal_BFER<B_8, Q_8>;
template class aff3ct::tools::Terminal_BFER<B_16,Q_16>;
template class aff3ct::tools::Terminal_BFER<B_32,Q_32>;
template class aff3ct::tools::Terminal_BFER<B_64,Q_64>;
#else
template class aff3ct::tools::Terminal_BFER<B,Q>;
#endif
// ==================================================================================== explicit template instantiation
<|endoftext|>


<commit_before>inline
opt_feat::opt_feat(const std::string in_path,
		   const std::string in_actionNames,
		   const int in_col,
		   const int in_row,
		   const int in_scale_factor,
		   const int in_shift,
		   const int in_scene, //only for kth
		   const int in_dim
)
:path(in_path), actionNames(in_actionNames), col(in_col), row(in_row), scale_factor(in_scale_factor), shift(in_shift), total_scene(in_scene), dim(in_dim)
{

  actions.load( actionNames );
  //dim = 14;
  //dim = 12; //Action Recognition from Video Using feature Covariance Matrices
}

inline
void
opt_feat::features_all_videos( field<string> all_people )
{
  int n_actions = actions.n_rows;
  int n_peo =  all_people.n_rows;
  //all_people.print("people");

  field <std::string> load_save_names (n_peo*n_actions,3);
  int sc = total_scene; //Solo estoy usando 1
  int k =0;

  for (int pe = 0; pe< n_peo; ++pe)
  {
    for (int act=0; act<n_actions; ++act)
    {
      std::stringstream ss_video_name;
      ss_video_name << path << actions (act) << "/" << all_people (pe) << "_" << actions (act) << "_d" << sc << "_uncomp.avi";

      std::stringstream save_folder;
      std::stringstream save_feat_video_i;
      std::stringstream save_labels_video_i;

      save_folder << "./kth-features_dim" << dim <<  "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
      save_feat_video_i   << save_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";
      save_labels_video_i << save_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

      load_save_names(k,0) = ss_video_name.str();
      load_save_names(k,1) = save_feat_video_i.str();
      load_save_names(k,2) = save_labels_video_i.str();
      k++;

    }
  }

  //int nProcessors=omp_get_max_threads();
  //std::cout<<nProcessors<<std::endl;
  //std::cout<< omp_get_num_threads()<<std::endl;

  wall_clock timer;
  timer.tic();
  omp_set_num_threads(10); //Use only 10 processors

  #pragma omp parallel for
  for (int i = 0; i<load_save_names.n_rows; ++i)
  {

    std::string one_video = load_save_names(i,0);
    int tid=omp_get_thread_num();

    #pragma omp critical
    cout<< "Processor " << tid <<" doing "<< one_video << endl;

    Struct_feat_lab my_Struct_feat_lab;

    feature_video( one_video, my_Struct_feat_lab );
    mat mat_features_video_i;
    vec lab_video_i;

    if (my_Struct_feat_lab.features_video_i.size()>0)
    {
      mat_features_video_i.zeros( dim,my_Struct_feat_lab.features_video_i.size() );
      lab_video_i.zeros( my_Struct_feat_lab.features_video_i.size() );
      for (uword i = 0; i < my_Struct_feat_lab.features_video_i.size(); ++i)
      {
	mat_features_video_i.col(i) = my_Struct_feat_lab.features_video_i.at(i)/norm(my_Struct_feat_lab.features_video_i.at(i),2);
	lab_video_i(i) = my_Struct_feat_lab.labels_video_i.at(i);
      }
    }
    else
    {
      mat_features_video_i.zeros(dim,0);
    }

    std::string save_feat_video_i   = load_save_names(i,1);
    std::string save_labels_video_i = load_save_names(i,2);

    mat_features_video_i.save( save_feat_video_i, hdf5_binary );
    lab_video_i.save( save_labels_video_i, hdf5_binary );
  }

  double n = timer.toc();
  cout << "number of seconds NO parallel : " << n << endl;

}

// //****************** Feature Extraction**************************************
// //***************************************************************************

inline
void
opt_feat::feature_video( std::string one_video, Struct_feat_lab &my_Struct_feat_lab )
{

  my_Struct_feat_lab.features_video_i.clear();
  my_Struct_feat_lab.labels_video_i.clear();

  int new_row = row;
  int new_col = col;

  cv::VideoCapture capVideo(one_video);
  int n_frames = capVideo.get(CV_CAP_PROP_FRAME_COUNT);

  if( !capVideo.isOpened() )
  {
    cout << "Video couldn't be opened" << endl;
    return;
  }

  cv::Mat prevgray, gray, flow, cflow, frame, prevflow;
  cv::Mat ixMat, iyMat, ixxMat, iyyMat;
  cv::Mat flow_xy[2], mag, ang;

  string text;

  for(int fr=0; fr<n_frames; fr++){

    //cout << fr << " " ;

    bool bSuccess = capVideo.read(frame); // read a new frame from video

    if (!bSuccess) //if not success, break loop
    {
      cout << "Cannot read the frame from video file" << endl;
      break;
    }

    if (scale_factor!=1)
    {
      new_row = row*scale_factor;
      new_col = col*scale_factor;
      cv::resize( frame, frame, cv::Size(new_row, new_col) );
    }

    cv::cvtColor(frame, gray, CV_BGR2GRAY);

    if( prevgray.data )
    {
      //cout << t << " " ;
      cv::calcOpticalFlowFarneback(prevgray,
				   gray,
				   flow,
				   0.5, //pyr_scale
				   3,   //levels
				   9,   //winsize
				   1,   //iterations
				   5,   //poly_n
				   1.1, //poly_sigma
				   0);  //flags

      //optical flow
      cv::split(flow, flow_xy);
      cv::cartToPolar(flow_xy[0], flow_xy[1], mag, ang, true);

      cv::Sobel(gray, ixMat, CV_32F, 1, 0, 1);
      cv::Sobel(gray, iyMat, CV_32F, 0, 1, 1);
      cv::Sobel(gray, ixxMat, CV_32F, 2, 0, 1);
      cv::Sobel(gray, iyyMat, CV_32F, 0, 2, 1);

      float  ux = 0, uy = 0, vx = 0,  vy = 0;
      float u, v;

      if( prevflow.data )
      {
	//cout << new_col << " " << new_row << endl;

	for (int x = 0 ; x < new_col ; ++x ){
	  for (int y = 0 ; y < new_row ; ++y ) {

	    vec features_one_pixel(dim);
	    u = flow.at<cv::Vec2f>(y, x)[0];
	    v = flow.at<cv::Vec2f>(y, x)[1];

	    //cout << "x= " << x << " - y= " << y << endl;
	    // x grad
	    //cout << " x y grad" << endl;
	    float ix = ixMat.at<float>(y, x);
	    //cout << " y grad" << endl;
	    float iy = iyMat.at<float>(y, x);

	    // grad direction &  grad magnitude. (Edges)
	    //cout << "grad direction &  grad magnitude" << endl;
	    float gd = std::atan2(std::abs(iy), std::abs(ix));
	    float gm = std::sqrt(ix * ix + iy * iy);

	    // x second grad
	    //cout << "x y  second grad " << endl;
	    float ixx = ixxMat.at<float>(y, x);
	    // y second grad
	    float iyy = iyyMat.at<float>(y, x);

	    //du/dt
	    float ut = u - prevflow.at<cv::Vec2f>(y, x)[0];
	    // dv/dt
	    float vt = v - prevflow.at<cv::Vec2f>(y, x)[1];

	    if (x>0 && y>0 )
	    {
	      ux = u - flow.at<cv::Vec2f>(y, x - 1)[0];
	      uy = u - flow.at<cv::Vec2f>(y - 1, x)[0];
	      vx = v - flow.at<cv::Vec2f>(y, x - 1)[1];
	      vy = v - flow.at<cv::Vec2f>(y - 1, x)[1];
	    }

	    float Div = (ux + vy);
	    float Vor = (vx - uy);
	    //Adding more features
	    mat G (2,2);
	    mat S;
	    float gd_opflow = ang.at<float>(y,x);
	    float mg_opflow = mag.at<float>(y,x);
	    //Gradient Tensor
	    G   << ux << uy << endr
	    << vx << vy << endr;

	    //Rate of Stein Tensor
	    S = 0.5*(G + G.t());

	    float tr_G = trace(G);
	    float tr_G2 = trace( square(G) );
	    float tr_S = trace(S);
	    float tr_S2 = trace(square(S));

	    //Tensor Invariants  of the optical flow
	    float Gten = 0.5*( tr_G*tr_G - tr_G2 );
	    float Sten = 0.5*( tr_S*tr_S - tr_S2 );

	    if (dim ==12)
	    {
	      features_one_pixel  << x       << y       << fr   << gm  << u    << v
	      << abs(ut) << abs(vt) << Div  << Vor << Gten << Sten;
	    }

	    if (dim ==14)
	    {

	      features_one_pixel  << x << y << abs(ix) << abs(iy) << abs(ixx)
	      << abs(iyy) << gm << gd <<  u << v << abs(ut)
	      << abs(vt) << (ux + vy)  << (vx - uy);
	    }

	    if (!is_finite( features_one_pixel ) )
	    {
	      cout << "It's not FINITE... continue???" << endl;
	      getchar();
	    }
	    // Plotting Moving pixels
	    //cout << " " << gm;

	    double is_zero = accu(abs(features_one_pixel));

	    if (gm>40 && is_finite( features_one_pixel ) && is_zero!=0 ) // Empirically set to 40
	    {

	      frame.at<cv::Vec3b>(y,x)[0] = 0;
	      frame.at<cv::Vec3b>(y,x)[1] = 0;
	      frame.at<cv::Vec3b>(y,x)[2] = 255;
	      my_Struct_feat_lab.features_video_i.push_back(features_one_pixel);
	      my_Struct_feat_lab.labels_video_i.push_back( fr );
	    }
	  }
	}
      }

      if(cv::waitKey(30)>=0)
	break;

    }

    std::swap(prevgray, gray);
    std::swap(prevflow, flow);

    //cv::imshow("color", frame);
    //cv::waitKey(1);

  }

}<commit_msg>Without # of threads<commit_after>inline
opt_feat::opt_feat(const std::string in_path,
		   const std::string in_actionNames,
		   const int in_col,
		   const int in_row,
		   const int in_scale_factor,
		   const int in_shift,
		   const int in_scene, //only for kth
		   const int in_dim
)
:path(in_path), actionNames(in_actionNames), col(in_col), row(in_row), scale_factor(in_scale_factor), shift(in_shift), total_scene(in_scene), dim(in_dim)
{

  actions.load( actionNames );
  //dim = 14;
  //dim = 12; //Action Recognition from Video Using feature Covariance Matrices
}

inline
void
opt_feat::features_all_videos( field<string> all_people )
{
  int n_actions = actions.n_rows;
  int n_peo =  all_people.n_rows;
  //all_people.print("people");

  field <std::string> load_save_names (n_peo*n_actions,3);
  int sc = total_scene; //Solo estoy usando 1
  int k =0;

  for (int pe = 0; pe< n_peo; ++pe)
  {
    for (int act=0; act<n_actions; ++act)
    {
      std::stringstream ss_video_name;
      ss_video_name << path << actions (act) << "/" << all_people (pe) << "_" << actions (act) << "_d" << sc << "_uncomp.avi";

      std::stringstream save_folder;
      std::stringstream save_feat_video_i;
      std::stringstream save_labels_video_i;

      save_folder << "./kth-features_dim" << dim <<  "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
      save_feat_video_i   << save_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";
      save_labels_video_i << save_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

      load_save_names(k,0) = ss_video_name.str();
      load_save_names(k,1) = save_feat_video_i.str();
      load_save_names(k,2) = save_labels_video_i.str();
      k++;

    }
  }

  //int nProcessors=omp_get_max_threads();
  //std::cout<<nProcessors<<std::endl;
  //std::cout<< omp_get_num_threads()<<std::endl;

  wall_clock timer;
  timer.tic();
  //omp_set_num_threads(10); //Use only 10 processors

  #pragma omp parallel for
  for (int i = 0; i<load_save_names.n_rows; ++i)
  {

    std::string one_video = load_save_names(i,0);
    int tid=omp_get_thread_num();

    #pragma omp critical
    cout<< "Processor " << tid <<" doing "<< one_video << endl;

    Struct_feat_lab my_Struct_feat_lab;

    feature_video( one_video, my_Struct_feat_lab );
    mat mat_features_video_i;
    vec lab_video_i;

    if (my_Struct_feat_lab.features_video_i.size()>0)
    {
      mat_features_video_i.zeros( dim,my_Struct_feat_lab.features_video_i.size() );
      lab_video_i.zeros( my_Struct_feat_lab.features_video_i.size() );
      for (uword i = 0; i < my_Struct_feat_lab.features_video_i.size(); ++i)
      {
	mat_features_video_i.col(i) = my_Struct_feat_lab.features_video_i.at(i)/norm(my_Struct_feat_lab.features_video_i.at(i),2);
	lab_video_i(i) = my_Struct_feat_lab.labels_video_i.at(i);
      }
    }
    else
    {
      mat_features_video_i.zeros(dim,0);
    }

    std::string save_feat_video_i   = load_save_names(i,1);
    std::string save_labels_video_i = load_save_names(i,2);

    mat_features_video_i.save( save_feat_video_i, hdf5_binary );
    lab_video_i.save( save_labels_video_i, hdf5_binary );
  }

  double n = timer.toc();
  cout << "number of seconds NO parallel : " << n << endl;

}

// //****************** Feature Extraction**************************************
// //***************************************************************************

inline
void
opt_feat::feature_video( std::string one_video, Struct_feat_lab &my_Struct_feat_lab )
{

  my_Struct_feat_lab.features_video_i.clear();
  my_Struct_feat_lab.labels_video_i.clear();

  int new_row = row;
  int new_col = col;

  cv::VideoCapture capVideo(one_video);
  int n_frames = capVideo.get(CV_CAP_PROP_FRAME_COUNT);

  if( !capVideo.isOpened() )
  {
    cout << "Video couldn't be opened" << endl;
    return;
  }

  cv::Mat prevgray, gray, flow, cflow, frame, prevflow;
  cv::Mat ixMat, iyMat, ixxMat, iyyMat;
  cv::Mat flow_xy[2], mag, ang;

  string text;

  for(int fr=0; fr<n_frames; fr++){

    //cout << fr << " " ;

    bool bSuccess = capVideo.read(frame); // read a new frame from video

    if (!bSuccess) //if not success, break loop
    {
      cout << "Cannot read the frame from video file" << endl;
      break;
    }

    if (scale_factor!=1)
    {
      new_row = row*scale_factor;
      new_col = col*scale_factor;
      cv::resize( frame, frame, cv::Size(new_row, new_col) );
    }

    cv::cvtColor(frame, gray, CV_BGR2GRAY);

    if( prevgray.data )
    {
      //cout << t << " " ;
      cv::calcOpticalFlowFarneback(prevgray,
				   gray,
				   flow,
				   0.5, //pyr_scale
				   3,   //levels
				   9,   //winsize
				   1,   //iterations
				   5,   //poly_n
				   1.1, //poly_sigma
				   0);  //flags

      //optical flow
      cv::split(flow, flow_xy);
      cv::cartToPolar(flow_xy[0], flow_xy[1], mag, ang, true);

      cv::Sobel(gray, ixMat, CV_32F, 1, 0, 1);
      cv::Sobel(gray, iyMat, CV_32F, 0, 1, 1);
      cv::Sobel(gray, ixxMat, CV_32F, 2, 0, 1);
      cv::Sobel(gray, iyyMat, CV_32F, 0, 2, 1);

      float  ux = 0, uy = 0, vx = 0,  vy = 0;
      float u, v;

      if( prevflow.data )
      {
	//cout << new_col << " " << new_row << endl;

	for (int x = 0 ; x < new_col ; ++x ){
	  for (int y = 0 ; y < new_row ; ++y ) {

	    vec features_one_pixel(dim);
	    u = flow.at<cv::Vec2f>(y, x)[0];
	    v = flow.at<cv::Vec2f>(y, x)[1];

	    //cout << "x= " << x << " - y= " << y << endl;
	    // x grad
	    //cout << " x y grad" << endl;
	    float ix = ixMat.at<float>(y, x);
	    //cout << " y grad" << endl;
	    float iy = iyMat.at<float>(y, x);

	    // grad direction &  grad magnitude. (Edges)
	    //cout << "grad direction &  grad magnitude" << endl;
	    float gd = std::atan2(std::abs(iy), std::abs(ix));
	    float gm = std::sqrt(ix * ix + iy * iy);

	    // x second grad
	    //cout << "x y  second grad " << endl;
	    float ixx = ixxMat.at<float>(y, x);
	    // y second grad
	    float iyy = iyyMat.at<float>(y, x);

	    //du/dt
	    float ut = u - prevflow.at<cv::Vec2f>(y, x)[0];
	    // dv/dt
	    float vt = v - prevflow.at<cv::Vec2f>(y, x)[1];

	    if (x>0 && y>0 )
	    {
	      ux = u - flow.at<cv::Vec2f>(y, x - 1)[0];
	      uy = u - flow.at<cv::Vec2f>(y - 1, x)[0];
	      vx = v - flow.at<cv::Vec2f>(y, x - 1)[1];
	      vy = v - flow.at<cv::Vec2f>(y - 1, x)[1];
	    }

	    float Div = (ux + vy);
	    float Vor = (vx - uy);
	    //Adding more features
	    mat G (2,2);
	    mat S;
	    float gd_opflow = ang.at<float>(y,x);
	    float mg_opflow = mag.at<float>(y,x);
	    //Gradient Tensor
	    G   << ux << uy << endr
	    << vx << vy << endr;

	    //Rate of Stein Tensor
	    S = 0.5*(G + G.t());

	    float tr_G = trace(G);
	    float tr_G2 = trace( square(G) );
	    float tr_S = trace(S);
	    float tr_S2 = trace(square(S));

	    //Tensor Invariants  of the optical flow
	    float Gten = 0.5*( tr_G*tr_G - tr_G2 );
	    float Sten = 0.5*( tr_S*tr_S - tr_S2 );

	    if (dim ==12)
	    {
	      features_one_pixel  << x       << y       << fr   << gm  << u    << v
	      << abs(ut) << abs(vt) << Div  << Vor << Gten << Sten;
	    }

	    if (dim ==14)
	    {

	      features_one_pixel  << x << y << abs(ix) << abs(iy) << abs(ixx)
	      << abs(iyy) << gm << gd <<  u << v << abs(ut)
	      << abs(vt) << (ux + vy)  << (vx - uy);
	    }

	    if (!is_finite( features_one_pixel ) )
	    {
	      cout << "It's not FINITE... continue???" << endl;
	      getchar();
	    }
	    // Plotting Moving pixels
	    //cout << " " << gm;

	    double is_zero = accu(abs(features_one_pixel));

	    if (gm>40 && is_finite( features_one_pixel ) && is_zero!=0 ) // Empirically set to 40
	    {

	      frame.at<cv::Vec3b>(y,x)[0] = 0;
	      frame.at<cv::Vec3b>(y,x)[1] = 0;
	      frame.at<cv::Vec3b>(y,x)[2] = 255;
	      my_Struct_feat_lab.features_video_i.push_back(features_one_pixel);
	      my_Struct_feat_lab.labels_video_i.push_back( fr );
	    }
	  }
	}
      }

      if(cv::waitKey(30)>=0)
	break;

    }

    std::swap(prevgray, gray);
    std::swap(prevflow, flow);

    //cv::imshow("color", frame);
    //cv::waitKey(1);

  }

}<|endoftext|>


<commit_before>#include "Board.h"
#include "Pawn.h"
#include "Rook.h"
#include "Knight.h"
#include "Bishop.h"
#include "Queen.h"
#include "King.h"

namespace Chess {
	Board::Board() {
		for (int x = 0; x < 8; x++) {
			for (int y = 0; y < 8; y++) {
				pieces[x][y] = nullptr;
			}
		}

		// Black pawns
		for (int x = 0; x < 8; x++) {
			pieces[x][6] = new Pawn(Position(x, 6), false);
		}

		// White pawns
		for (int x = 0; x < 8; x++) {
			pieces[x][1] = new Pawn(Position(x, 1), true);
		}

		// Rooks
		pieces[0][7] = new Rook(Position(0, 7), false);
		pieces[7][7] = new Rook(Position(7, 7), false);
		pieces[0][0] = new Rook(Position(0, 0), true);
		pieces[7][0] = new Rook(Position(7, 0), true);

		// Knights
		pieces[1][7] = new Knight(Position(1, 7), false);
		pieces[6][7] = new Knight(Position(6, 7), false);
		pieces[1][0] = new Knight(Position(1, 0), true);
		pieces[6][0] = new Knight(Position(6, 0), true);

		// Bishops
		pieces[2][7] = new Bishop(Position(2, 7), false);
		pieces[5][7] = new Bishop(Position(5, 7), false);
		pieces[2][0] = new Bishop(Position(2, 0), true);
		pieces[5][0] = new Bishop(Position(5, 0), true);

		// Queens
		pieces[3][7] = new Queen(Position(3, 7), false);
		pieces[3][0] = new Queen(Position(3, 0), true);

		// Kings
		blackKing = new King(Position(4, 7), false);
		pieces[4][7] = blackKing;
		whiteKing = new King(Position(4, 0), true);
		pieces[4][0] = whiteKing;
	}

	Board::~Board() {
		for (int x = 0; x < 8; x++) {
			for (int y = 0; y < 8; y++) {
				if (pieces[x][y] != nullptr)
					delete pieces[x][y];
			}
		}
	}

	Piece* Board::getPiece(const Position& position) const {
		return pieces[position.x][position.y];
	}

	bool Board::move(const Position& oldPosition, const Position& newPosition) {
		Piece* piece = getPiece(oldPosition);

		if (piece != nullptr) {
			// Check if the piece is of the right color.
			if (piece->isWhite() == (turn % 2 == 0)) {
				state = GameState::WHITEPLAYS;
				// Check if the move is legal.
				if (piece->isLegal(*this, newPosition)) {
					pieces[oldPosition.x][oldPosition.y] = nullptr;

					// Delete captured piece.
					if (pieces[newPosition.x][newPosition.y] != nullptr)
						delete pieces[newPosition.x][newPosition.y];

					// TODO: En passant.

					pieces[newPosition.x][newPosition.y] = piece;
					piece->move(newPosition);

					// TODO: Castling, promotion, pawn double move.

					turn++;
					return true;
				}
			}
			else
				state = GameState::BLACKPLAYS;
		}

		return false;
	}
}<commit_msg>Undid state transition<commit_after>#include "Board.h"
#include "Pawn.h"
#include "Rook.h"
#include "Knight.h"
#include "Bishop.h"
#include "Queen.h"
#include "King.h"

namespace Chess {
	Board::Board() {
		for (int x = 0; x < 8; x++) {
			for (int y = 0; y < 8; y++) {
				pieces[x][y] = nullptr;
			}
		}

		// Black pawns
		for (int x = 0; x < 8; x++) {
			pieces[x][6] = new Pawn(Position(x, 6), false);
		}

		// White pawns
		for (int x = 0; x < 8; x++) {
			pieces[x][1] = new Pawn(Position(x, 1), true);
		}

		// Rooks
		pieces[0][7] = new Rook(Position(0, 7), false);
		pieces[7][7] = new Rook(Position(7, 7), false);
		pieces[0][0] = new Rook(Position(0, 0), true);
		pieces[7][0] = new Rook(Position(7, 0), true);

		// Knights
		pieces[1][7] = new Knight(Position(1, 7), false);
		pieces[6][7] = new Knight(Position(6, 7), false);
		pieces[1][0] = new Knight(Position(1, 0), true);
		pieces[6][0] = new Knight(Position(6, 0), true);

		// Bishops
		pieces[2][7] = new Bishop(Position(2, 7), false);
		pieces[5][7] = new Bishop(Position(5, 7), false);
		pieces[2][0] = new Bishop(Position(2, 0), true);
		pieces[5][0] = new Bishop(Position(5, 0), true);

		// Queens
		pieces[3][7] = new Queen(Position(3, 7), false);
		pieces[3][0] = new Queen(Position(3, 0), true);

		// Kings
		blackKing = new King(Position(4, 7), false);
		pieces[4][7] = blackKing;
		whiteKing = new King(Position(4, 0), true);
		pieces[4][0] = whiteKing;
	}

	Board::~Board() {
		for (int x = 0; x < 8; x++) {
			for (int y = 0; y < 8; y++) {
				if (pieces[x][y] != nullptr)
					delete pieces[x][y];
			}
		}
	}

	Piece* Board::getPiece(const Position& position) const {
		return pieces[position.x][position.y];
	}

	bool Board::move(const Position& oldPosition, const Position& newPosition) {
		Piece* piece = getPiece(oldPosition);

		if (piece != nullptr) {
			// Check if the piece is of the right color.
			if (piece->isWhite() == (turn % 2 == 0)) {
				// Check if the move is legal.
				if (piece->isLegal(*this, newPosition)) {
					pieces[oldPosition.x][oldPosition.y] = nullptr;

					// Delete captured piece.
					if (pieces[newPosition.x][newPosition.y] != nullptr)
						delete pieces[newPosition.x][newPosition.y];

					// TODO: En passant.

					pieces[newPosition.x][newPosition.y] = piece;
					piece->move(newPosition);

					// TODO: Castling, promotion, pawn double move.

					turn++;
					return true;
				}
			}
		}

		return false;
	}
}<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/
#include <mitkImageStatisticsContainer.h>

#include <algorithm>

namespace mitk
{
    ImageStatisticsContainer::ImageStatisticsContainer()
    {
      this->Reset();
    }

    //The order is derived from the old (<2018) image statistics plugin.
    const ImageStatisticsContainer::StatisticsObject::StatisticNameVector ImageStatisticsContainer::StatisticsObject::m_DefaultNames = {
      ImageStatisticsConstants::MEAN(),
      ImageStatisticsConstants::MEDIAN(),
      ImageStatisticsConstants::STANDARDDEVIATION(),
      ImageStatisticsConstants::RMS(),
      ImageStatisticsConstants::MAXIMUM(),
      ImageStatisticsConstants::MAXIMUMPOSITION(),
      ImageStatisticsConstants::MINIMUM(),
      ImageStatisticsConstants::MINIMUMPOSITION(),
      ImageStatisticsConstants::NUMBEROFVOXELS(),
      ImageStatisticsConstants::VOLUME(),
      ImageStatisticsConstants::SKEWNESS(),
      ImageStatisticsConstants::KURTOSIS(),
      ImageStatisticsConstants::UNIFORMITY(),
      ImageStatisticsConstants::ENTROPY(),
      ImageStatisticsConstants::MPP(),
      ImageStatisticsConstants::UPP() };

    ImageStatisticsContainer::StatisticsObject::StatisticsObject() {
      Reset();
    }

    void ImageStatisticsContainer::StatisticsObject::AddStatistic(const std::string& key, StatisticsVariantType value)
    {
      m_Statistics.emplace(key, value);

      if (std::find(std::cbegin(m_DefaultNames), std::cend(m_DefaultNames), key)==std::cend(m_DefaultNames))
      {
        if (std::find(std::cbegin(m_CustomNames), std::cend(m_CustomNames), key) == std::cend(m_CustomNames))
        {
          m_CustomNames.emplace_back(key);
        }
      }
    }

    const ImageStatisticsContainer::StatisticsObject::StatisticNameVector& ImageStatisticsContainer::StatisticsObject::GetDefaultStatisticNames()
    {
      return m_DefaultNames;
    };

    const ImageStatisticsContainer::StatisticsObject::StatisticNameVector& ImageStatisticsContainer::StatisticsObject::GetCustomStatisticNames() const
    {
      return m_CustomNames;
    }

    ImageStatisticsContainer::StatisticsObject::StatisticNameVector ImageStatisticsContainer::StatisticsObject::GetAllStatisticNames() const
    {
      StatisticNameVector names = GetDefaultStatisticNames();
      names.insert(std::end(names),std::cbegin(m_CustomNames), std::cend(m_CustomNames));

      return std::move(names);
    }

    bool ImageStatisticsContainer::StatisticsObject::HasStatistic(const std::string& name) const
    {
      return m_Statistics.find(name)!=std::cend(m_Statistics);
    }

    ImageStatisticsContainer::StatisticsVariantType ImageStatisticsContainer::StatisticsObject::GetValueNonConverted(const std::string& name) const
    {
      if (HasStatistic(name)) {
        return m_Statistics.find(name)->second;
      }
      else {
        mitkThrow() << "invalid statistic key, could not find";
      }
    }

    void ImageStatisticsContainer::StatisticsObject::Reset()
    {
      m_Statistics.clear();
      m_CustomNames.clear();
    }

    bool ImageStatisticsContainer::TimeStepExists(TimeStepType timeStep) const {
      return m_TimeStepMap.find(timeStep) != m_TimeStepMap.end();
    }

    const ImageStatisticsContainer::StatisticsObject& ImageStatisticsContainer::GetStatisticsForTimeStep(TimeStepType timeStep) const {
      auto it = m_TimeStepMap.find(timeStep);
      if (it != m_TimeStepMap.end()) {
        return it->second;
      }
      mitkThrow() << "StatisticsObject for timeStep " << timeStep << " not found!";
    }

    void ImageStatisticsContainer::SetStatisticsForTimeStep(TimeStepType timeStep, StatisticsObject statistics) {
      if (timeStep < this->GetTimeSteps()) {
        m_TimeStepMap.emplace(timeStep, statistics);
        this->Modified();
      }
      else {
        mitkThrow() << "Given timeStep " << timeStep << " out of timeStep geometry bounds. TimeSteps in geometry: " << this->GetTimeSteps();
      }
    }

    void ImageStatisticsContainer::PrintSelf(std::ostream &os, itk::Indent indent) const
    {
      Superclass::PrintSelf(os, indent);
      for (unsigned int i = 0; i < this->GetTimeSteps(); i++) {
        auto statisticsValues = GetStatisticsForTimeStep(i);
        os << std::endl << indent << "Statistics instance for timeStep " << i << ":";
        auto statisticKeys = statisticsValues.GetAllStatisticNames();
        os << std::endl << indent << "Number of entries: " << statisticKeys.size();
        for (const auto& aKey : statisticKeys) {
          os << std::endl << indent.GetNextIndent() << aKey << ": " << statisticsValues.GetValueNonConverted(aKey);
        }
      }
    }

    unsigned int ImageStatisticsContainer::GetNumberOfTimeSteps()const {
      return this->GetTimeSteps();
    }

    void ImageStatisticsContainer::Reset()
    {
      for (auto iter = m_TimeStepMap.begin(); iter != m_TimeStepMap.end(); iter++) {
        iter->second.Reset();
      }
    }

    itk::LightObject::Pointer ImageStatisticsContainer::InternalClone() const
    {
      itk::LightObject::Pointer ioPtr = Superclass::InternalClone();
      Self::Pointer rval = dynamic_cast<Self*>(ioPtr.GetPointer());
      if (rval.IsNull())
      {
        itkExceptionMacro(<< "downcast to type "
          << "StatisticsContainer"
          << " failed.");
      }

      rval->SetTimeStepMap(m_TimeStepMap);
      rval->SetTimeGeometry(this->GetTimeGeometry()->Clone());

      return ioPtr;
    }

    void ImageStatisticsContainer::SetTimeStepMap(TimeStepMapType map) {
      m_TimeStepMap = map;
    }

    ImageStatisticsContainer::StatisticsObject::StatisticNameVector
      GetAllStatisticNames(const ImageStatisticsContainer* container)
    {
      ImageStatisticsContainer::StatisticsObject::StatisticNameVector names = ImageStatisticsContainer::StatisticsObject::GetDefaultStatisticNames();

      if (container)
      {
        std::set<std::string> customKeys;

        for (unsigned int i = 0; i < container->GetTimeSteps(); i++) {
          auto statisticKeys = container->GetStatisticsForTimeStep(i).GetCustomStatisticNames();
          customKeys.insert(std::cbegin(statisticKeys), std::cend(statisticKeys));
        }

        names.insert(std::end(names), std::begin(customKeys), std::end(customKeys));
      }

      return std::move(names);
    };

    ImageStatisticsContainer::StatisticsObject::StatisticNameVector
      GetAllStatisticNames(std::vector<ImageStatisticsContainer::ConstPointer> containers)
    {
      ImageStatisticsContainer::StatisticsObject::StatisticNameVector names = ImageStatisticsContainer::StatisticsObject::GetDefaultStatisticNames();

      std::set<std::string> customKeys;

      for (auto container : containers)
      {
        for (unsigned int i = 0; i < container->GetTimeSteps(); i++) {
          auto statisticKeys = container->GetStatisticsForTimeStep(i).GetCustomStatisticNames();
          customKeys.insert(std::cbegin(statisticKeys), std::cend(statisticKeys));
        }
      }

      names.insert(std::end(names), std::begin(customKeys), std::end(customKeys));

      return std::move(names);
    };

}
<commit_msg>resolved T25834 compiler automatically optimizes return value in C++11<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/
#include <mitkImageStatisticsContainer.h>

#include <algorithm>

namespace mitk
{
    ImageStatisticsContainer::ImageStatisticsContainer()
    {
      this->Reset();
    }

    //The order is derived from the old (<2018) image statistics plugin.
    const ImageStatisticsContainer::StatisticsObject::StatisticNameVector ImageStatisticsContainer::StatisticsObject::m_DefaultNames = {
      ImageStatisticsConstants::MEAN(),
      ImageStatisticsConstants::MEDIAN(),
      ImageStatisticsConstants::STANDARDDEVIATION(),
      ImageStatisticsConstants::RMS(),
      ImageStatisticsConstants::MAXIMUM(),
      ImageStatisticsConstants::MAXIMUMPOSITION(),
      ImageStatisticsConstants::MINIMUM(),
      ImageStatisticsConstants::MINIMUMPOSITION(),
      ImageStatisticsConstants::NUMBEROFVOXELS(),
      ImageStatisticsConstants::VOLUME(),
      ImageStatisticsConstants::SKEWNESS(),
      ImageStatisticsConstants::KURTOSIS(),
      ImageStatisticsConstants::UNIFORMITY(),
      ImageStatisticsConstants::ENTROPY(),
      ImageStatisticsConstants::MPP(),
      ImageStatisticsConstants::UPP() };

    ImageStatisticsContainer::StatisticsObject::StatisticsObject() {
      Reset();
    }

    void ImageStatisticsContainer::StatisticsObject::AddStatistic(const std::string& key, StatisticsVariantType value)
    {
      m_Statistics.emplace(key, value);

      if (std::find(std::cbegin(m_DefaultNames), std::cend(m_DefaultNames), key)==std::cend(m_DefaultNames))
      {
        if (std::find(std::cbegin(m_CustomNames), std::cend(m_CustomNames), key) == std::cend(m_CustomNames))
        {
          m_CustomNames.emplace_back(key);
        }
      }
    }

    const ImageStatisticsContainer::StatisticsObject::StatisticNameVector& ImageStatisticsContainer::StatisticsObject::GetDefaultStatisticNames()
    {
      return m_DefaultNames;
    };

    const ImageStatisticsContainer::StatisticsObject::StatisticNameVector& ImageStatisticsContainer::StatisticsObject::GetCustomStatisticNames() const
    {
      return m_CustomNames;
    }

    ImageStatisticsContainer::StatisticsObject::StatisticNameVector ImageStatisticsContainer::StatisticsObject::GetAllStatisticNames() const
    {
      StatisticNameVector names = GetDefaultStatisticNames();
      names.insert(std::end(names),std::cbegin(m_CustomNames), std::cend(m_CustomNames));

      return names;
    }

    bool ImageStatisticsContainer::StatisticsObject::HasStatistic(const std::string& name) const
    {
      return m_Statistics.find(name)!=std::cend(m_Statistics);
    }

    ImageStatisticsContainer::StatisticsVariantType ImageStatisticsContainer::StatisticsObject::GetValueNonConverted(const std::string& name) const
    {
      if (HasStatistic(name)) {
        return m_Statistics.find(name)->second;
      }
      else {
        mitkThrow() << "invalid statistic key, could not find";
      }
    }

    void ImageStatisticsContainer::StatisticsObject::Reset()
    {
      m_Statistics.clear();
      m_CustomNames.clear();
    }

    bool ImageStatisticsContainer::TimeStepExists(TimeStepType timeStep) const {
      return m_TimeStepMap.find(timeStep) != m_TimeStepMap.end();
    }

    const ImageStatisticsContainer::StatisticsObject& ImageStatisticsContainer::GetStatisticsForTimeStep(TimeStepType timeStep) const {
      auto it = m_TimeStepMap.find(timeStep);
      if (it != m_TimeStepMap.end()) {
        return it->second;
      }
      mitkThrow() << "StatisticsObject for timeStep " << timeStep << " not found!";
    }

    void ImageStatisticsContainer::SetStatisticsForTimeStep(TimeStepType timeStep, StatisticsObject statistics) {
      if (timeStep < this->GetTimeSteps()) {
        m_TimeStepMap.emplace(timeStep, statistics);
        this->Modified();
      }
      else {
        mitkThrow() << "Given timeStep " << timeStep << " out of timeStep geometry bounds. TimeSteps in geometry: " << this->GetTimeSteps();
      }
    }

    void ImageStatisticsContainer::PrintSelf(std::ostream &os, itk::Indent indent) const
    {
      Superclass::PrintSelf(os, indent);
      for (unsigned int i = 0; i < this->GetTimeSteps(); i++) {
        auto statisticsValues = GetStatisticsForTimeStep(i);
        os << std::endl << indent << "Statistics instance for timeStep " << i << ":";
        auto statisticKeys = statisticsValues.GetAllStatisticNames();
        os << std::endl << indent << "Number of entries: " << statisticKeys.size();
        for (const auto& aKey : statisticKeys) {
          os << std::endl << indent.GetNextIndent() << aKey << ": " << statisticsValues.GetValueNonConverted(aKey);
        }
      }
    }

    unsigned int ImageStatisticsContainer::GetNumberOfTimeSteps()const {
      return this->GetTimeSteps();
    }

    void ImageStatisticsContainer::Reset()
    {
      for (auto iter = m_TimeStepMap.begin(); iter != m_TimeStepMap.end(); iter++) {
        iter->second.Reset();
      }
    }

    itk::LightObject::Pointer ImageStatisticsContainer::InternalClone() const
    {
      itk::LightObject::Pointer ioPtr = Superclass::InternalClone();
      Self::Pointer rval = dynamic_cast<Self*>(ioPtr.GetPointer());
      if (rval.IsNull())
      {
        itkExceptionMacro(<< "downcast to type "
          << "StatisticsContainer"
          << " failed.");
      }

      rval->SetTimeStepMap(m_TimeStepMap);
      rval->SetTimeGeometry(this->GetTimeGeometry()->Clone());

      return ioPtr;
    }

    void ImageStatisticsContainer::SetTimeStepMap(TimeStepMapType map) {
      m_TimeStepMap = map;
    }

    ImageStatisticsContainer::StatisticsObject::StatisticNameVector
      GetAllStatisticNames(const ImageStatisticsContainer* container)
    {
      ImageStatisticsContainer::StatisticsObject::StatisticNameVector names = ImageStatisticsContainer::StatisticsObject::GetDefaultStatisticNames();

      if (container)
      {
        std::set<std::string> customKeys;

        for (unsigned int i = 0; i < container->GetTimeSteps(); i++) {
          auto statisticKeys = container->GetStatisticsForTimeStep(i).GetCustomStatisticNames();
          customKeys.insert(std::cbegin(statisticKeys), std::cend(statisticKeys));
        }

        names.insert(std::end(names), std::begin(customKeys), std::end(customKeys));
      }

      return names;
    };

    ImageStatisticsContainer::StatisticsObject::StatisticNameVector
      GetAllStatisticNames(std::vector<ImageStatisticsContainer::ConstPointer> containers)
    {
      ImageStatisticsContainer::StatisticsObject::StatisticNameVector names = ImageStatisticsContainer::StatisticsObject::GetDefaultStatisticNames();

      std::set<std::string> customKeys;

      for (auto container : containers)
      {
        for (unsigned int i = 0; i < container->GetTimeSteps(); i++) {
          auto statisticKeys = container->GetStatisticsForTimeStep(i).GetCustomStatisticNames();
          customKeys.insert(std::cbegin(statisticKeys), std::cend(statisticKeys));
        }
      }

      names.insert(std::end(names), std::begin(customKeys), std::end(customKeys));

      return names;
    };

}
<|endoftext|>


<commit_before>#ifndef BONEFISH_SERIALIZATION_MSGPACK_SERIALIZER_HPP
#define BONEFISH_SERIALIZATION_MSGPACK_SERIALIZER_HPP

#include <bonefish/serialization/wamp_serializer.hpp>
#include <bonefish/serialization/wamp_serializer_type.hpp>

#include <cstddef>

namespace bonefish {

class wamp_message;

class msgpack_serializer : public wamp_serializer
{
public:
    msgpack_serializer();
    virtual ~msgpack_serializer() override;

    virtual wamp_serializer_type get_type() const override;
    virtual wamp_message* deserialize(const char* buffer, size_t length) const override;
    virtual size_t serialize(const wamp_message* message, char* buffer, size_t length) const override;
};

inline msgpack_serializer::msgpack_serializer()
{
}

inline msgpack_serializer::~msgpack_serializer()
{
}

inline wamp_serializer_type msgpack_serializer::get_type() const
{
    return wamp_serializer_type::MSGPACK;
}

} // namespace bonefish

#endif // BONEFISH_SERIALIZATION_SERIALIZER_HPP
<commit_msg>Fix header include guard comment.<commit_after>#ifndef BONEFISH_SERIALIZATION_MSGPACK_SERIALIZER_HPP
#define BONEFISH_SERIALIZATION_MSGPACK_SERIALIZER_HPP

#include <bonefish/serialization/wamp_serializer.hpp>
#include <bonefish/serialization/wamp_serializer_type.hpp>

#include <cstddef>

namespace bonefish {

class wamp_message;

class msgpack_serializer : public wamp_serializer
{
public:
    msgpack_serializer();
    virtual ~msgpack_serializer() override;

    virtual wamp_serializer_type get_type() const override;
    virtual wamp_message* deserialize(const char* buffer, size_t length) const override;
    virtual size_t serialize(const wamp_message* message, char* buffer, size_t length) const override;
};

inline msgpack_serializer::msgpack_serializer()
{
}

inline msgpack_serializer::~msgpack_serializer()
{
}

inline wamp_serializer_type msgpack_serializer::get_type() const
{
    return wamp_serializer_type::MSGPACK;
}

} // namespace bonefish

#endif // BONEFISH_SERIALIZATION_MSGPACK_SERIALIZER_HPP
<|endoftext|>