<commit_before>/*
    __ _____ _____ _____
 __|  |   __|     |   | |  JSON for Modern C++ (test suite)
|  |  |__   |  |  | | | |  version 3.7.3
|_____|_____|_____|_|___|  https://github.com/nlohmann/json

Licensed under the MIT License <http://opensource.org/licenses/MIT>.
SPDX-License-Identifier: MIT
Copyright (c) 2013-2019 Niels Lohmann <http://nlohmann.me>.

Permission is hereby  granted, free of charge, to any  person obtaining a copy
of this software and associated  documentation files (the "Software"), to deal
in the Software  without restriction, including without  limitation the rights
to  use, copy,  modify, merge,  publish, distribute,  sublicense, and/or  sell
copies  of  the Software,  and  to  permit persons  to  whom  the Software  is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE  IS PROVIDED "AS  IS", WITHOUT WARRANTY  OF ANY KIND,  EXPRESS OR
IMPLIED,  INCLUDING BUT  NOT  LIMITED TO  THE  WARRANTIES OF  MERCHANTABILITY,
FITNESS FOR  A PARTICULAR PURPOSE AND  NONINFRINGEMENT. IN NO EVENT  SHALL THE
AUTHORS  OR COPYRIGHT  HOLDERS  BE  LIABLE FOR  ANY  CLAIM,  DAMAGES OR  OTHER
LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE  OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "doctest_compatibility.h"

#include <nlohmann/json.hpp>
using nlohmann::json;

namespace
{
// helper function to check std::less<json::value_t>
// see https://en.cppreference.com/w/cpp/utility/functional/less
template <typename A, typename B, typename U = std::less<json::value_t>>
bool f(A a, B b, U u = U())
{
    return u(a, b);
}
}

TEST_CASE("lexicographical comparison operators")
{
    SECTION("types")
    {
        std::vector<json::value_t> j_types =
        {
            json::value_t::null,
            json::value_t::boolean,
            json::value_t::number_integer,
            json::value_t::number_unsigned,
            json::value_t::number_float,
            json::value_t::object,
            json::value_t::array,
            json::value_t::string,
            json::value_t::binary
        };

        SECTION("comparison: less")
        {
            std::vector<std::vector<bool>> expected =
            {
                {false, true, true, true, true, true, true, true, true},
                {false, false, true, true, true, true, true, true, true},
                {false, false, false, false, false, true, true, true, true},
                {false, false, false, false, false, true, true, true, true},
                {false, false, false, false, false, true, true, true, true},
                {false, false, false, false, false, false, true, true, true},
                {false, false, false, false, false, false, false, true, true},
                {false, false, false, false, false, false, false, false, true},
                {false, false, false, false, false, false, false, false, false}
            };

            for (size_t i = 0; i < j_types.size(); ++i)
            {
                for (size_t j = 0; j < j_types.size(); ++j)
                {
                    CAPTURE(i)
                    CAPTURE(j)
                    // check precomputed values
                    CHECK(operator<(j_types[i], j_types[j]) == expected[i][j]);
                    CHECK(f(j_types[i], j_types[j]) == expected[i][j]);
                }
            }
        }
    }

    SECTION("values")
    {
        json j_values =
        {
            nullptr, nullptr,
            -17, 42,
            8u, 13u,
            3.14159, 23.42,
            "foo", "bar",
            true, false,
            {1, 2, 3}, {"one", "two", "three"},
            {{"first", 1}, {"second", 2}}, {{"a", "A"}, {"b", {"B"}}},
            json::binary_array({1, 2, 3}), json::binary_array({1, 2, 4})
        };

        SECTION("comparison: equal")
        {
            std::vector<std::vector<bool>> expected =
            {
                {true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false},
                {true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false},
                {false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false},
                {false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false},
                {false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false},
                {false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false},
                {false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false},
                {false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false},
                {false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false},
                {false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false},
                {false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false},
                {false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false},
                {false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false},
                {false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false},
                {false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false},
                {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false},
                {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false},
                {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true}
            };

            for (size_t i = 0; i < j_values.size(); ++i)
            {
                for (size_t j = 0; j < j_values.size(); ++j)
                {
                    CAPTURE(i)
                    CAPTURE(j)
                    CAPTURE(j_values[i])
                    CAPTURE(j_values[j])
                    // check precomputed values
                    CHECK( (j_values[i] == j_values[j]) == expected[i][j] );
                }
            }

            // comparison with discarded elements
            json j_discarded(json::value_t::discarded);
            for (size_t i = 0; i < j_values.size(); ++i)
            {
                CHECK( (j_values[i] == j_discarded) == false);
                CHECK( (j_discarded == j_values[i]) == false);
                CHECK( (j_discarded == j_discarded) == false);
            }

            // compare with null pointer
            json j_null;
            CHECK(j_null == nullptr);
            CHECK(nullptr == j_null);
        }

        SECTION("comparison: not equal")
        {
            for (size_t i = 0; i < j_values.size(); ++i)
            {
                for (size_t j = 0; j < j_values.size(); ++j)
                {
                    CAPTURE(i)
                    CAPTURE(j)
                    // check definition
                    CHECK( (j_values[i] != j_values[j]) == not(j_values[i] == j_values[j]) );
                }
            }

            // compare with null pointer
            json j_null;
            CHECK( (j_null != nullptr) == false);
            CHECK( (nullptr != j_null) == false);
            CHECK( (j_null != nullptr) == not(j_null == nullptr));
            CHECK( (nullptr != j_null) == not(nullptr == j_null));
        }

        SECTION("comparison: less")
        {
            std::vector<std::vector<bool>> expected =
            {
                {false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true},
                {false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true},
                {false, false, false, true, true, true, true, true, true, true, false, false, true, true, true, true, true, true},
                {false, false, false, false, false, false, false, false, true, true, false, false, true, true, true, true, true, true},
                {false, false, false, true, false, true, false, true, true, true, false, false, true, true, true, true, true, true},
                {false, false, false, true, false, false, false, true, true, true, false, false, true, true, true, true, true, true},
                {false, false, false, true, true, true, false, true, true, true, false, false, true, true, true, true, true, true},
                {false, false, false, true, false, false, false, false, true, true, false, false, true, true, true, true, true, true},
                {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true},
                {false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, true, true},
                {false, false, true, true, true, true, true, true, true, true, false, false, true, true, true, true, true, true},
                {false, false, true, true, true, true, true, true, true, true, true, false, true, true, true, true, true, true},
                {false, false, false, false, false, false, false, false, true, true, false, false, false, true, false, false, true, true},
                {false, false, false, false, false, false, false, false, true, true, false, false, false, false, false, false, true, true},
                {false, false, false, false, false, false, false, false, true, true, false, false, true, true, false, false, true, true},
                {false, false, false, false, false, false, false, false, true, true, false, false, true, true, true, false, true, true},
                {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false},
                {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false}
            };

            for (size_t i = 0; i < j_values.size(); ++i)
            {
                for (size_t j = 0; j < j_values.size(); ++j)
                {
                    CAPTURE(i)
                    CAPTURE(j)
                    CAPTURE(j_values[i])
                    CAPTURE(j_values[j])
                    // check precomputed values
                    CHECK( (j_values[i] < j_values[j]) == expected[i][j] );
                }
            }

            // comparison with discarded elements
            json j_discarded(json::value_t::discarded);
            for (size_t i = 0; i < j_values.size(); ++i)
            {
                CAPTURE(i)
                CHECK( (j_values[i] < j_discarded) == false);
                CHECK( (j_discarded < j_values[i]) == false);
                CHECK( (j_discarded < j_discarded) == false);
            }
        }

        SECTION("comparison: less than or equal equal")
        {
            for (size_t i = 0; i < j_values.size(); ++i)
            {
                for (size_t j = 0; j < j_values.size(); ++j)
                {
                    CAPTURE(i)
                    CAPTURE(j)
                    // check definition
                    CHECK( (j_values[i] <= j_values[j]) == not(j_values[j] < j_values[i]) );
                }
            }
        }

        SECTION("comparison: greater than")
        {
            for (size_t i = 0; i < j_values.size(); ++i)
            {
                for (size_t j = 0; j < j_values.size(); ++j)
                {
                    CAPTURE(i)
                    CAPTURE(j)
                    // check definition
                    CHECK( (j_values[i] > j_values[j]) == (j_values[j] < j_values[i]) );
                }
            }
        }

        SECTION("comparison: greater than or equal")
        {
            for (size_t i = 0; i < j_values.size(); ++i)
            {
                for (size_t j = 0; j < j_values.size(); ++j)
                {
                    CAPTURE(i)
                    CAPTURE(j)
                    // check definition
                    CHECK( (j_values[i] >= j_values[j]) == not(j_values[i] < j_values[j]) );
                }
            }
        }
    }
}
<commit_msg>:white_check_mark: fix test cases<commit_after>/*
    __ _____ _____ _____
 __|  |   __|     |   | |  JSON for Modern C++ (test suite)
|  |  |__   |  |  | | | |  version 3.7.3
|_____|_____|_____|_|___|  https://github.com/nlohmann/json

Licensed under the MIT License <http://opensource.org/licenses/MIT>.
SPDX-License-Identifier: MIT
Copyright (c) 2013-2019 Niels Lohmann <http://nlohmann.me>.

Permission is hereby  granted, free of charge, to any  person obtaining a copy
of this software and associated  documentation files (the "Software"), to deal
in the Software  without restriction, including without  limitation the rights
to  use, copy,  modify, merge,  publish, distribute,  sublicense, and/or  sell
copies  of  the Software,  and  to  permit persons  to  whom  the Software  is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE  IS PROVIDED "AS  IS", WITHOUT WARRANTY  OF ANY KIND,  EXPRESS OR
IMPLIED,  INCLUDING BUT  NOT  LIMITED TO  THE  WARRANTIES OF  MERCHANTABILITY,
FITNESS FOR  A PARTICULAR PURPOSE AND  NONINFRINGEMENT. IN NO EVENT  SHALL THE
AUTHORS  OR COPYRIGHT  HOLDERS  BE  LIABLE FOR  ANY  CLAIM,  DAMAGES OR  OTHER
LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE  OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "doctest_compatibility.h"

#include <nlohmann/json.hpp>
using nlohmann::json;

namespace
{
// helper function to check std::less<json::value_t>
// see https://en.cppreference.com/w/cpp/utility/functional/less
template <typename A, typename B, typename U = std::less<json::value_t>>
bool f(A a, B b, U u = U())
{
    return u(a, b);
}
}

TEST_CASE("lexicographical comparison operators")
{
    SECTION("types")
    {
        std::vector<json::value_t> j_types =
        {
            json::value_t::null,
            json::value_t::boolean,
            json::value_t::number_integer,
            json::value_t::number_unsigned,
            json::value_t::number_float,
            json::value_t::object,
            json::value_t::array,
            json::value_t::string,
            json::value_t::binary
        };

        SECTION("comparison: less")
        {
            std::vector<std::vector<bool>> expected =
            {
                {false, true, true, true, true, true, true, true, true},
                {false, false, true, true, true, true, true, true, true},
                {false, false, false, false, false, true, true, true, true},
                {false, false, false, false, false, true, true, true, true},
                {false, false, false, false, false, true, true, true, true},
                {false, false, false, false, false, false, true, true, true},
                {false, false, false, false, false, false, false, true, true},
                {false, false, false, false, false, false, false, false, true},
                {false, false, false, false, false, false, false, false, false}
            };

            for (size_t i = 0; i < j_types.size(); ++i)
            {
                for (size_t j = 0; j < j_types.size(); ++j)
                {
                    CAPTURE(i)
                    CAPTURE(j)
                    // check precomputed values
                    CHECK(operator<(j_types[i], j_types[j]) == expected[i][j]);
                    CHECK(f(j_types[i], j_types[j]) == expected[i][j]);
                }
            }
        }
    }

    SECTION("values")
    {
        json j_values =
        {
            nullptr, nullptr,
            -17, 42,
            8u, 13u,
            3.14159, 23.42,
            "foo", "bar",
            true, false,
            {1, 2, 3}, {"one", "two", "three"},
            {{"first", 1}, {"second", 2}}, {{"a", "A"}, {"b", {"B"}}},
            json::binary_array({1, 2, 3}), json::binary_array({1, 2, 4})
        };

        SECTION("comparison: equal")
        {
            std::vector<std::vector<bool>> expected =
            {
                {true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false},
                {true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false},
                {false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false},
                {false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false},
                {false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false},
                {false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false},
                {false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false},
                {false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false},
                {false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false},
                {false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false},
                {false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false},
                {false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false},
                {false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false},
                {false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false},
                {false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false},
                {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false},
                {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false},
                {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true}
            };

            for (size_t i = 0; i < j_values.size(); ++i)
            {
                for (size_t j = 0; j < j_values.size(); ++j)
                {
                    CAPTURE(i)
                    CAPTURE(j)
                    CAPTURE(j_values[i])
                    CAPTURE(j_values[j])
                    // check precomputed values
                    CHECK( (j_values[i] == j_values[j]) == expected[i][j] );
                }
            }

            // comparison with discarded elements
            json j_discarded(json::value_t::discarded);
            for (size_t i = 0; i < j_values.size(); ++i)
            {
                CHECK( (j_values[i] == j_discarded) == false);
                CHECK( (j_discarded == j_values[i]) == false);
                CHECK( (j_discarded == j_discarded) == false);
            }

            // compare with null pointer
            json j_null;
            CHECK(j_null == nullptr);
            CHECK(nullptr == j_null);
        }

        SECTION("comparison: not equal")
        {
            for (size_t i = 0; i < j_values.size(); ++i)
            {
                for (size_t j = 0; j < j_values.size(); ++j)
                {
                    CAPTURE(i)
                    CAPTURE(j)
                    // check definition
                    CHECK( (j_values[i] != j_values[j]) == not(j_values[i] == j_values[j]) );
                }
            }

            // compare with null pointer
            json j_null;
            CHECK( (j_null != nullptr) == false);
            CHECK( (nullptr != j_null) == false);
            CHECK( (j_null != nullptr) == not(j_null == nullptr));
            CHECK( (nullptr != j_null) == not(nullptr == j_null));
        }

        SECTION("comparison: less")
        {
            std::vector<std::vector<bool>> expected =
            {
                {false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true},
                {false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true},
                {false, false, false, true, true, true, true, true, true, true, false, false, true, true, true, true, true, true},
                {false, false, false, false, false, false, false, false, true, true, false, false, true, true, true, true, true, true},
                {false, false, false, true, false, true, false, true, true, true, false, false, true, true, true, true, true, true},
                {false, false, false, true, false, false, false, true, true, true, false, false, true, true, true, true, true, true},
                {false, false, false, true, true, true, false, true, true, true, false, false, true, true, true, true, true, true},
                {false, false, false, true, false, false, false, false, true, true, false, false, true, true, true, true, true, true},
                {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true},
                {false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, true, true},
                {false, false, true, true, true, true, true, true, true, true, false, false, true, true, true, true, true, true},
                {false, false, true, true, true, true, true, true, true, true, true, false, true, true, true, true, true, true},
                {false, false, false, false, false, false, false, false, true, true, false, false, false, true, false, false, true, true},
                {false, false, false, false, false, false, false, false, true, true, false, false, false, false, false, false, true, true},
                {false, false, false, false, false, false, false, false, true, true, false, false, true, true, false, false, true, true},
                {false, false, false, false, false, false, false, false, true, true, false, false, true, true, true, false, true, true},
                {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true},
                {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false}
            };

            for (size_t i = 0; i < j_values.size(); ++i)
            {
                for (size_t j = 0; j < j_values.size(); ++j)
                {
                    CAPTURE(i)
                    CAPTURE(j)
                    CAPTURE(j_values[i])
                    CAPTURE(j_values[j])
                    // check precomputed values
                    CHECK( (j_values[i] < j_values[j]) == expected[i][j] );
                }
            }

            // comparison with discarded elements
            json j_discarded(json::value_t::discarded);
            for (size_t i = 0; i < j_values.size(); ++i)
            {
                CAPTURE(i)
                CHECK( (j_values[i] < j_discarded) == false);
                CHECK( (j_discarded < j_values[i]) == false);
                CHECK( (j_discarded < j_discarded) == false);
            }
        }

        SECTION("comparison: less than or equal equal")
        {
            for (size_t i = 0; i < j_values.size(); ++i)
            {
                for (size_t j = 0; j < j_values.size(); ++j)
                {
                    CAPTURE(i)
                    CAPTURE(j)
                    // check definition
                    CHECK( (j_values[i] <= j_values[j]) == not(j_values[j] < j_values[i]) );
                }
            }
        }

        SECTION("comparison: greater than")
        {
            for (size_t i = 0; i < j_values.size(); ++i)
            {
                for (size_t j = 0; j < j_values.size(); ++j)
                {
                    CAPTURE(i)
                    CAPTURE(j)
                    // check definition
                    CHECK( (j_values[i] > j_values[j]) == (j_values[j] < j_values[i]) );
                }
            }
        }

        SECTION("comparison: greater than or equal")
        {
            for (size_t i = 0; i < j_values.size(); ++i)
            {
                for (size_t j = 0; j < j_values.size(); ++j)
                {
                    CAPTURE(i)
                    CAPTURE(j)
                    // check definition
                    CHECK( (j_values[i] >= j_values[j]) == not(j_values[i] < j_values[j]) );
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>#define BOOST_TEST_MODULE TestDischargeCurve
#define BOOST_TEST_MAIN
#include <cap/energy_storage_device.h>
#include <cap/utils.h>
#include <boost/format.hpp>
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>

namespace cap {

void print_headers(std::string const & discharge_mode, std::ostream & os)
{
    os<<"# discharge curve (discharge_mode="<<discharge_mode<<")\n";
    os<<boost::format( "# %22s  %22s  %22s  \n")
        % "time t [second]"
        % "current I [ampere]"
        % "voltage U [volt]"
        ;
}

void report(double const time, std::shared_ptr<EnergyStorageDevice const> dev, std::ostream & os)
{
    double current;
    dev->get_current(current);
    double voltage;
    dev->get_voltage(voltage);
    os<<boost::format("  %22.15e  %22.15e  %22.15e  \n")
        % time
        % current
        % voltage
        ;
}

std::function<void(double const, double const, std::shared_ptr<cap::EnergyStorageDevice>)>
get_discharge_evolve_one_time_step(std::string const & discharge_mode, std::shared_ptr<boost::property_tree::ptree const> database)
{
    if (discharge_mode.compare("constant_current") == 0) {
        double const discharge_current = database->get<double>("discharge_current");
        return [discharge_current](double const, double const time_step, std::shared_ptr<cap::EnergyStorageDevice> dev)
            { dev->evolve_one_time_step_constant_current(time_step, -discharge_current); };
    } else if (discharge_mode.compare("constant_power") == 0) {
        double const discharge_power = database->get<double>("discharge_power");
        return [discharge_power](double const, double const time_step, std::shared_ptr<cap::EnergyStorageDevice> dev)
            { dev->evolve_one_time_step_constant_power(time_step, -discharge_power); };
    } else if (discharge_mode.compare("constant_load") == 0) {
        double const discharge_load = database->get<double>("discharge_load");
        return [discharge_load](double const, double const time_step, std::shared_ptr<cap::EnergyStorageDevice> dev)
            { dev->evolve_one_time_step_constant_load(time_step, discharge_load); };
    } else {
        throw std::runtime_error("invalid discharge mode "+discharge_mode);
    }
}

std::function<bool(double const, std::shared_ptr<cap::EnergyStorageDevice>)>
get_discharge_end_criterion(std::string const & discharge_stop_at, std::shared_ptr<boost::property_tree::ptree const> database)
{
    if (discharge_stop_at.compare("voltage_less_than") == 0) {
        double const discharge_voltage_limit = database->get<double>("discharge_voltage_limit");
        return [discharge_voltage_limit](double const, std::shared_ptr<cap::EnergyStorageDevice> dev)
            { double voltage; dev->get_voltage(voltage); return (voltage <= discharge_voltage_limit); };
    } else if (discharge_stop_at.compare("time_greater_than") == 0) {
        double const discharge_duration = database->get<double>("discharge_duration");
        return [discharge_duration](double const time, std::shared_ptr<cap::EnergyStorageDevice>)
            { return (time >= discharge_duration); };
    } else {
        throw std::runtime_error("invalid test stop at "+discharge_stop_at);
    }
}

void discharge_curve(std::shared_ptr<cap::EnergyStorageDevice> dev, std::shared_ptr<boost::property_tree::ptree const> database, std::ostream & os = std::cout)
{
    std::string const discharge_mode    = database->get<std::string>("discharge_mode"   );
    auto evolve_one_time_step = get_discharge_evolve_one_time_step(discharge_mode, database);
    std::string const discharge_stop_at = database->get<std::string>("discharge_stop_at");
    auto end_criterion = get_discharge_end_criterion(discharge_stop_at, database);

    double const max_discharge_time = database->get<double>("max_discharge_time");
    double const time_step          = database->get<double>("time_step"         );
    double const initial_voltage    = database->get<double>("initial_voltage"   );
    dev->reset_voltage(initial_voltage);

    double time = 0.0;
    print_headers(discharge_mode, os);
    report(time, dev, os);
    while (time < max_discharge_time)
    {
        evolve_one_time_step(time, time_step, dev);
        time += time_step;
        report(time, dev, os);
        if (end_criterion(time, dev))
            break;
    }
}

} // end namespace cap

BOOST_AUTO_TEST_CASE( test_discharge_curve )
{
    // parse input file
    std::shared_ptr<boost::property_tree::ptree> input_database =
        std::make_shared<boost::property_tree::ptree>();
    read_xml("input_discharge_curve", *input_database);

    // build an energy storage system
    std::shared_ptr<boost::property_tree::ptree> device_database =
        std::make_shared<boost::property_tree::ptree>(input_database->get_child("device"));
    std::shared_ptr<cap::EnergyStorageDevice> device =
        cap::buildEnergyStorageDevice(std::make_shared<cap::Parameters>(device_database));

    // measure discharge curve
    std::fstream fout;
    fout.open("discharge_curve_data", std::fstream::out);

    std::shared_ptr<boost::property_tree::ptree> discharge_curve_database =
        std::make_shared<boost::property_tree::ptree>(input_database->get_child("discharge_curve"));
    cap::discharge_curve(device, discharge_curve_database, fout);

    fout.close();
}
<commit_msg>remove spaces in headers for charge curve<commit_after>#define BOOST_TEST_MODULE TestDischargeCurve
#define BOOST_TEST_MAIN
#include <cap/energy_storage_device.h>
#include <cap/utils.h>
#include <boost/format.hpp>
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>

namespace cap {

void print_headers(std::string const & discharge_mode, std::ostream & os)
{
    os<<"# discharge curve (discharge_mode="<<discharge_mode<<")\n";
    os<<boost::format( "# %22s  %22s  %22s  \n")
        % "time_t_[second]"
        % "current_I_[ampere]"
        % "voltage_U_[volt]"
        ;
}

void report(double const time, std::shared_ptr<EnergyStorageDevice const> dev, std::ostream & os)
{
    double current;
    dev->get_current(current);
    double voltage;
    dev->get_voltage(voltage);
    os<<boost::format("  %22.15e  %22.15e  %22.15e  \n")
        % time
        % current
        % voltage
        ;
}

std::function<void(double const, double const, std::shared_ptr<cap::EnergyStorageDevice>)>
get_discharge_evolve_one_time_step(std::string const & discharge_mode, std::shared_ptr<boost::property_tree::ptree const> database)
{
    if (discharge_mode.compare("constant_current") == 0) {
        double const discharge_current = database->get<double>("discharge_current");
        return [discharge_current](double const, double const time_step, std::shared_ptr<cap::EnergyStorageDevice> dev)
            { dev->evolve_one_time_step_constant_current(time_step, -discharge_current); };
    } else if (discharge_mode.compare("constant_power") == 0) {
        double const discharge_power = database->get<double>("discharge_power");
        return [discharge_power](double const, double const time_step, std::shared_ptr<cap::EnergyStorageDevice> dev)
            { dev->evolve_one_time_step_constant_power(time_step, -discharge_power); };
    } else if (discharge_mode.compare("constant_load") == 0) {
        double const discharge_load = database->get<double>("discharge_load");
        return [discharge_load](double const, double const time_step, std::shared_ptr<cap::EnergyStorageDevice> dev)
            { dev->evolve_one_time_step_constant_load(time_step, discharge_load); };
    } else {
        throw std::runtime_error("invalid discharge mode "+discharge_mode);
    }
}

std::function<bool(double const, std::shared_ptr<cap::EnergyStorageDevice>)>
get_discharge_end_criterion(std::string const & discharge_stop_at, std::shared_ptr<boost::property_tree::ptree const> database)
{
    if (discharge_stop_at.compare("voltage_less_than") == 0) {
        double const discharge_voltage_limit = database->get<double>("discharge_voltage_limit");
        return [discharge_voltage_limit](double const, std::shared_ptr<cap::EnergyStorageDevice> dev)
            { double voltage; dev->get_voltage(voltage); return (voltage <= discharge_voltage_limit); };
    } else if (discharge_stop_at.compare("time_greater_than") == 0) {
        double const discharge_duration = database->get<double>("discharge_duration");
        return [discharge_duration](double const time, std::shared_ptr<cap::EnergyStorageDevice>)
            { return (time >= discharge_duration); };
    } else {
        throw std::runtime_error("invalid test stop at "+discharge_stop_at);
    }
}

void discharge_curve(std::shared_ptr<cap::EnergyStorageDevice> dev, std::shared_ptr<boost::property_tree::ptree const> database, std::ostream & os = std::cout)
{
    std::string const discharge_mode    = database->get<std::string>("discharge_mode"   );
    auto evolve_one_time_step = get_discharge_evolve_one_time_step(discharge_mode, database);
    std::string const discharge_stop_at = database->get<std::string>("discharge_stop_at");
    auto end_criterion = get_discharge_end_criterion(discharge_stop_at, database);

    double const max_discharge_time = database->get<double>("max_discharge_time");
    double const time_step          = database->get<double>("time_step"         );
    double const initial_voltage    = database->get<double>("initial_voltage"   );
    dev->reset_voltage(initial_voltage);

    double time = 0.0;
    print_headers(discharge_mode, os);
    report(time, dev, os);
    while (time < max_discharge_time)
    {
        evolve_one_time_step(time, time_step, dev);
        time += time_step;
        report(time, dev, os);
        if (end_criterion(time, dev))
            break;
    }
}

} // end namespace cap

BOOST_AUTO_TEST_CASE( test_discharge_curve )
{
    // parse input file
    std::shared_ptr<boost::property_tree::ptree> input_database =
        std::make_shared<boost::property_tree::ptree>();
    read_xml("input_discharge_curve", *input_database);

    // build an energy storage system
    std::shared_ptr<boost::property_tree::ptree> device_database =
        std::make_shared<boost::property_tree::ptree>(input_database->get_child("device"));
    std::shared_ptr<cap::EnergyStorageDevice> device =
        cap::buildEnergyStorageDevice(std::make_shared<cap::Parameters>(device_database));

    // measure discharge curve
    std::fstream fout;
    fout.open("discharge_curve_data", std::fstream::out);

    std::shared_ptr<boost::property_tree::ptree> discharge_curve_database =
        std::make_shared<boost::property_tree::ptree>(input_database->get_child("discharge_curve"));
    cap::discharge_curve(device, discharge_curve_database, fout);

    fout.close();
}
<|endoftext|>


<commit_before>#include <boost/uuid/uuid_generators.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp> /** to string conversion when using < C++11 */

#include <envire_core/TransformTreeTypes.hpp>
#include <envire_core/TransformTree.hpp>
#include <envire_core/Item.hpp>
#include <envire_core/GraphViz.hpp>
#include <envire_core/FrameEventDispatcher.hpp>
#include <envire_core/FrameRootAddedEvent.hpp>

using namespace envire::core;

BOOST_AUTO_TEST_CASE(add_root_Frame_test)
{
  TransformTree tree;
  Frame root("Root");
  BOOST_CHECK(tree.num_vertices() == 0);
  BOOST_CHECK(tree.num_edges() == 0);
  vertex_descriptor v = tree.addRootFrame(root);
  const Frame& frame2 = tree.getFrame(v);
  BOOST_CHECK(root.uuid == frame2.uuid);
  BOOST_CHECK(tree.num_vertices() == 1);
  BOOST_CHECK(tree.num_edges() == 0);
}

class Dispatcher : public FrameEventDispatcher {
public:
    boost::optional<FrameAddedEvent> frameAddedEvent;
    boost::optional<FrameRootAddedEvent> frameRootAddedEvent;
    int callCount = 0;

    virtual void frameAdded(const FrameAddedEvent& e)
    {
      ++callCount;
      frameAddedEvent = e;
    }
    virtual void frameRootAdded(const FrameRootAddedEvent& e)
    {
      ++callCount;
      frameRootAddedEvent = e;
    }
};

BOOST_AUTO_TEST_CASE(root_frame_event_test)
{
    Dispatcher d;
    TransformTree tree;
    tree.subscribe(&d);
    Frame root("Root");
    vertex_descriptor v = tree.addRootFrame(root);
    BOOST_CHECK(d.frameRootAddedEvent.is_initialized());//i.e. the event handler was called
    BOOST_CHECK(d.callCount == 1);
    BOOST_CHECK(d.frameRootAddedEvent->addedVertex == v);
}

BOOST_AUTO_TEST_CASE(frame_add_event_test)
{
    Dispatcher d;
    TransformTree tree;
    tree.subscribe(&d);
    Frame root("Root");
    vertex_descriptor rootVertex = tree.addRootFrame(root);

    Frame child("child");
    Frame childchild("childchild");

    Transform tf;
    tf.transform.translation.x() = 42;

    BOOST_CHECK(!d.frameAddedEvent.is_initialized());
    BOOST_CHECK(d.callCount == 1);
    vertex_descriptor childVertex = tree.addFrame(child, rootVertex, tf);
    BOOST_CHECK(d.frameAddedEvent.is_initialized());
    BOOST_CHECK(d.callCount == 2);
    BOOST_CHECK(d.frameAddedEvent->parent == rootVertex);
    BOOST_CHECK(d.frameAddedEvent->addedVertex == childVertex);
    BOOST_CHECK(d.frameAddedEvent->transform.transform.translation.x() == 42);

    d.frameAddedEvent.reset();
    BOOST_CHECK(!d.frameAddedEvent.is_initialized());
    Transform tf2;
    tf2.transform.translation.x() = 84;
    vertex_descriptor childChildVertex = tree.addFrame(childchild, childVertex, tf2);
    BOOST_CHECK(d.frameAddedEvent.is_initialized());
    BOOST_CHECK(d.callCount == 3);
    BOOST_CHECK(d.frameAddedEvent->parent == childVertex);
    BOOST_CHECK(d.frameAddedEvent->addedVertex == childChildVertex);
    BOOST_CHECK(d.frameAddedEvent->transform.transform.translation.x() == 84);
}

BOOST_AUTO_TEST_CASE(add_and_remove_vertex_test)
{
    unsigned int max_vertices = 100;

    BOOST_TEST_MESSAGE("ADD VERTEX TEST...");
    envire::core::TransformTree tree;

    register unsigned int i = 0;
    for (i = 0; i<max_vertices; ++i)
    {
        envire::core::Frame frame("frame_"+boost::lexical_cast<std::string>(i));
        tree.add_vertex(frame);
    }

    BOOST_CHECK(tree.num_vertices() == i);
    BOOST_TEST_MESSAGE("DONE\n");

    BOOST_TEST_MESSAGE("REMOVE VERTEX TEST...");
    envire::core::vertex_iterator vi, vi_end, next;
    boost::tie(vi, vi_end) = tree.vertices();
    for (next = vi; vi != vi_end; vi = next)
    {
        ++next;
        tree.remove_vertex(*vi);
    }

    BOOST_CHECK(tree.num_vertices() == 0);
    BOOST_TEST_MESSAGE("DONE\n");
}

BOOST_AUTO_TEST_CASE(add_and_remove_edge_test)
{

    unsigned int max_vertices = 100;

    BOOST_TEST_MESSAGE("ADD EDGES TEST...");
    envire::core::TransformTree tree;

    register unsigned int i = 0;
    for (i = 0; i<max_vertices; ++i)
    {
        envire::core::Frame frame("frame_"+boost::lexical_cast<std::string>(i));
        envire::core::vertex_descriptor v1 = tree.add_vertex(frame);
    }

    /** get root node **/
    envire::core::vertex_descriptor root = tree.vertex(0);
    for (envire::core::vertices_size_type iv = 1; iv < tree.num_vertices(); ++iv)
    {
        envire::core::edge_descriptor edge; bool b;
        envire::core::vertex_descriptor node_to = tree.vertex(iv);
        try
        {
            boost::tie(edge, b) = tree.add_edge(root, node_to);
            BOOST_CHECK(b == true);
        }catch (std::logic_error e)
        {
            std::cerr<<e.what();
        }
    }

    BOOST_CHECK(tree.num_edges() == tree.num_vertices() - 1);
    BOOST_TEST_MESSAGE("DONE\n");

    BOOST_TEST_MESSAGE("REMOVE EDGES TEST...");
    envire::core::edge_iterator ei, ei_end, next;
    boost::tie(ei, ei_end) = tree.edges();
    for (next = ei; ei != ei_end; ei = next)
    {
        ++next;
        tree.remove_edge(*ei);
    }

    BOOST_CHECK(tree.num_edges() == 0);
    BOOST_TEST_MESSAGE("DONE\n");
}

BOOST_AUTO_TEST_CASE(add_an_item)
{
    // Instantiate a tree and vertex
    using namespace envire::core;
    TransformTree tree;
    Frame frame("Example frame");
    vertex_descriptor v1 = tree.add_vertex(frame);
    // Add an item to the frame of the vertex
    boost::intrusive_ptr<Item<std::string>> item(new Item<std::string>());
    item->setData("Contents of the Item");
    boost::intrusive_ptr<ItemBase> itemB(item);

    // Include the item in the vector of the frame (with a vector)
    unsigned int vectorSize = 1;
    std::vector< boost::intrusive_ptr<ItemBase>> itemPVector(vectorSize);
    itemPVector[0] = itemB;
    frame.items = itemPVector;
    // Visualize results
    envire::core::GraphViz gviz;
    gviz.write(tree, "graphviz_boost_test_add_an_item.dot");
}

class Vector: public envire::core::Item<Eigen::Vector3d>
{
};

BOOST_AUTO_TEST_CASE(property_and_grahviz_test)
{

    unsigned int max_vertices = 100;

    envire::core::TransformTree tree;
    unsigned int vector_size = 100;
    unsigned int magic_number = 42;

    /** Create a list of items **/
    std::vector< boost::intrusive_ptr<envire::core::ItemBase> > items_vector(vector_size);
    boost::intrusive_ptr<Vector> my_vector(new Vector());
    my_vector->setData(magic_number * Eigen::Vector3d::Ones());

    for (std::vector<boost::intrusive_ptr<envire::core::ItemBase> >::iterator it = items_vector.begin() ; it != items_vector.end(); ++it)
    {
        /** Pointer to the same object **/
        *it = my_vector;
    }

    for (unsigned int i = 0; i<max_vertices; ++i)
    {
        envire::core::Frame frame("frame_"+boost::lexical_cast<std::string>(i));
        frame.items = items_vector;
        envire::core::vertex_descriptor v1 = tree.add_vertex(frame);
    }

    BOOST_TEST_MESSAGE("FRAME PROPERTY TEST...");
    for (unsigned int i = 0; i < max_vertices; ++i)
    {
        envire::core::Frame frame = tree.getFrame(tree.vertex(i));
        BOOST_CHECK(frame.name == "frame_"+boost::lexical_cast<std::string>(i));
        BOOST_CHECK(frame.items.size() == vector_size);
        for (std::vector< boost::intrusive_ptr<envire::core::ItemBase> >::const_iterator it = frame.items.begin();
                it != frame.items.end(); ++it)
        {
            BOOST_CHECK(*it == my_vector);
            Vector* pvector = dynamic_cast< Vector* >(it->get());
            BOOST_CHECK(pvector->getData() == magic_number * Eigen::Vector3d::Ones());
        }
    }
    BOOST_TEST_MESSAGE("DONE\n");

    /** get root node and create edges **/
    base::Time now = base::Time::now();
    envire::core::vertex_descriptor root = tree.vertex(0);
    for (envire::core::vertices_size_type iv = 1; iv < tree.num_vertices(); ++iv)
    {
        envire::core::edge_descriptor edge; bool b;
        envire::core::Transform tf_prop(now);
        base::TransformWithCovariance tf(Eigen::AngleAxisd::Identity(), static_cast<base::Position>(my_vector->getData()));
        tf_prop.setTransform(tf);
        envire::core::vertex_descriptor node_to = tree.vertex(iv);
        boost::tie(edge, b) = tree.add_edge(root, node_to, tf_prop);
        BOOST_CHECK(b == true);
    }

    BOOST_TEST_MESSAGE("TRANSFORM PROPERTY TEST...");
    envire::core::edge_iterator it, end;
    for(boost::tie(it, end) = tree.edges(); it != end; ++it)
    {

        const Transform& transform = tree.getTransform(it);
        BOOST_CHECK(transform.time == now);
        BOOST_CHECK(transform.transform.translation == my_vector->getData());
    }
    BOOST_TEST_MESSAGE("DONE\n");

    BOOST_TEST_MESSAGE("GRAPHVIZ TEST...");
    envire::core::GraphViz gviz;

    gviz.write(tree, "graphviz_boost_test_transform_tree.dot");

    //tree.clear();
    BOOST_TEST_MESSAGE("DONE\n");
}

<commit_msg>test_transform_tree: cleanup. Removed some unused variables and the register keyword.<commit_after>#include <boost/uuid/uuid_generators.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp> /** to string conversion when using < C++11 */

#include <envire_core/TransformTreeTypes.hpp>
#include <envire_core/TransformTree.hpp>
#include <envire_core/Item.hpp>
#include <envire_core/GraphViz.hpp>
#include <envire_core/FrameEventDispatcher.hpp>
#include <envire_core/FrameRootAddedEvent.hpp>

using namespace envire::core;

BOOST_AUTO_TEST_CASE(add_root_Frame_test)
{
  TransformTree tree;
  Frame root("Root");
  BOOST_CHECK(tree.num_vertices() == 0);
  BOOST_CHECK(tree.num_edges() == 0);
  vertex_descriptor v = tree.addRootFrame(root);
  const Frame& frame2 = tree.getFrame(v);
  BOOST_CHECK(root.uuid == frame2.uuid);
  BOOST_CHECK(tree.num_vertices() == 1);
  BOOST_CHECK(tree.num_edges() == 0);
}

class Dispatcher : public FrameEventDispatcher {
public:
    boost::optional<FrameAddedEvent> frameAddedEvent;
    boost::optional<FrameRootAddedEvent> frameRootAddedEvent;
    int callCount = 0;

    virtual void frameAdded(const FrameAddedEvent& e)
    {
      ++callCount;
      frameAddedEvent = e;
    }
    virtual void frameRootAdded(const FrameRootAddedEvent& e)
    {
      ++callCount;
      frameRootAddedEvent = e;
    }
};

BOOST_AUTO_TEST_CASE(root_frame_event_test)
{
    Dispatcher d;
    TransformTree tree;
    tree.subscribe(&d);
    Frame root("Root");
    vertex_descriptor v = tree.addRootFrame(root);
    BOOST_CHECK(d.frameRootAddedEvent.is_initialized());//i.e. the event handler was called
    BOOST_CHECK(d.callCount == 1);
    BOOST_CHECK(d.frameRootAddedEvent->addedVertex == v);
}

BOOST_AUTO_TEST_CASE(frame_add_event_test)
{
    Dispatcher d;
    TransformTree tree;
    tree.subscribe(&d);
    Frame root("Root");
    vertex_descriptor rootVertex = tree.addRootFrame(root);

    Frame child("child");
    Frame childchild("childchild");

    Transform tf;
    tf.transform.translation.x() = 42;

    BOOST_CHECK(!d.frameAddedEvent.is_initialized());
    BOOST_CHECK(d.callCount == 1);
    vertex_descriptor childVertex = tree.addFrame(child, rootVertex, tf);
    BOOST_CHECK(d.frameAddedEvent.is_initialized());
    BOOST_CHECK(d.callCount == 2);
    BOOST_CHECK(d.frameAddedEvent->parent == rootVertex);
    BOOST_CHECK(d.frameAddedEvent->addedVertex == childVertex);
    BOOST_CHECK(d.frameAddedEvent->transform.transform.translation.x() == 42);

    d.frameAddedEvent.reset();
    BOOST_CHECK(!d.frameAddedEvent.is_initialized());
    Transform tf2;
    tf2.transform.translation.x() = 84;
    vertex_descriptor childChildVertex = tree.addFrame(childchild, childVertex, tf2);
    BOOST_CHECK(d.frameAddedEvent.is_initialized());
    BOOST_CHECK(d.callCount == 3);
    BOOST_CHECK(d.frameAddedEvent->parent == childVertex);
    BOOST_CHECK(d.frameAddedEvent->addedVertex == childChildVertex);
    BOOST_CHECK(d.frameAddedEvent->transform.transform.translation.x() == 84);
}

BOOST_AUTO_TEST_CASE(add_and_remove_vertex_test)
{
    unsigned int max_vertices = 100;

    BOOST_TEST_MESSAGE("ADD VERTEX TEST...");
    envire::core::TransformTree tree;

    unsigned int i = 0;
    for (i = 0; i<max_vertices; ++i)
    {
        envire::core::Frame frame("frame_"+boost::lexical_cast<std::string>(i));
        tree.add_vertex(frame);
    }

    BOOST_CHECK(tree.num_vertices() == i);
    BOOST_TEST_MESSAGE("DONE\n");

    BOOST_TEST_MESSAGE("REMOVE VERTEX TEST...");
    envire::core::vertex_iterator vi, vi_end, next;
    boost::tie(vi, vi_end) = tree.vertices();
    for (next = vi; vi != vi_end; vi = next)
    {
        ++next;
        tree.remove_vertex(*vi);
    }

    BOOST_CHECK(tree.num_vertices() == 0);
    BOOST_TEST_MESSAGE("DONE\n");
}

BOOST_AUTO_TEST_CASE(add_and_remove_edge_test)
{

    unsigned int max_vertices = 100;

    BOOST_TEST_MESSAGE("ADD EDGES TEST...");
    envire::core::TransformTree tree;

    unsigned int i = 0;
    for (i = 0; i<max_vertices; ++i)
    {
        envire::core::Frame frame("frame_"+boost::lexical_cast<std::string>(i));
        tree.add_vertex(frame);
    }

    /** get root node **/
    envire::core::vertex_descriptor root = tree.vertex(0);
    for (envire::core::vertices_size_type iv = 1; iv < tree.num_vertices(); ++iv)
    {
        envire::core::edge_descriptor edge; bool b;
        envire::core::vertex_descriptor node_to = tree.vertex(iv);
        try
        {
            boost::tie(edge, b) = tree.add_edge(root, node_to);
            BOOST_CHECK(b == true);
        }catch (std::logic_error e)
        {
            std::cerr<<e.what();
        }
    }

    BOOST_CHECK(tree.num_edges() == tree.num_vertices() - 1);
    BOOST_TEST_MESSAGE("DONE\n");

    BOOST_TEST_MESSAGE("REMOVE EDGES TEST...");
    envire::core::edge_iterator ei, ei_end, next;
    boost::tie(ei, ei_end) = tree.edges();
    for (next = ei; ei != ei_end; ei = next)
    {
        ++next;
        tree.remove_edge(*ei);
    }

    BOOST_CHECK(tree.num_edges() == 0);
    BOOST_TEST_MESSAGE("DONE\n");
}

BOOST_AUTO_TEST_CASE(add_an_item)
{
    // Instantiate a tree and vertex
    using namespace envire::core;
    TransformTree tree;
    Frame frame("Example frame");
    tree.add_vertex(frame);
    // Add an item to the frame of the vertex
    boost::intrusive_ptr<Item<std::string>> item(new Item<std::string>());
    item->setData("Contents of the Item");
    boost::intrusive_ptr<ItemBase> itemB(item);

    // Include the item in the vector of the frame (with a vector)
    unsigned int vectorSize = 1;
    std::vector< boost::intrusive_ptr<ItemBase>> itemPVector(vectorSize);
    itemPVector[0] = itemB;
    frame.items = itemPVector;
    // Visualize results
    envire::core::GraphViz gviz;
    gviz.write(tree, "graphviz_boost_test_add_an_item.dot");
}

class Vector: public envire::core::Item<Eigen::Vector3d>
{
};

BOOST_AUTO_TEST_CASE(property_and_grahviz_test)
{

    unsigned int max_vertices = 100;

    envire::core::TransformTree tree;
    unsigned int vector_size = 100;
    unsigned int magic_number = 42;

    /** Create a list of items **/
    std::vector< boost::intrusive_ptr<envire::core::ItemBase> > items_vector(vector_size);
    boost::intrusive_ptr<Vector> my_vector(new Vector());
    my_vector->setData(magic_number * Eigen::Vector3d::Ones());

    for (std::vector<boost::intrusive_ptr<envire::core::ItemBase> >::iterator it = items_vector.begin() ; it != items_vector.end(); ++it)
    {
        /** Pointer to the same object **/
        *it = my_vector;
    }

    for (unsigned int i = 0; i<max_vertices; ++i)
    {
        envire::core::Frame frame("frame_"+boost::lexical_cast<std::string>(i));
        frame.items = items_vector;
        tree.add_vertex(frame);
    }

    BOOST_TEST_MESSAGE("FRAME PROPERTY TEST...");
    for (unsigned int i = 0; i < max_vertices; ++i)
    {
        envire::core::Frame frame = tree.getFrame(tree.vertex(i));
        BOOST_CHECK(frame.name == "frame_"+boost::lexical_cast<std::string>(i));
        BOOST_CHECK(frame.items.size() == vector_size);
        for (std::vector< boost::intrusive_ptr<envire::core::ItemBase> >::const_iterator it = frame.items.begin();
                it != frame.items.end(); ++it)
        {
            BOOST_CHECK(*it == my_vector);
            Vector* pvector = dynamic_cast< Vector* >(it->get());
            BOOST_CHECK(pvector->getData() == magic_number * Eigen::Vector3d::Ones());
        }
    }
    BOOST_TEST_MESSAGE("DONE\n");

    /** get root node and create edges **/
    base::Time now = base::Time::now();
    envire::core::vertex_descriptor root = tree.vertex(0);
    for (envire::core::vertices_size_type iv = 1; iv < tree.num_vertices(); ++iv)
    {
        envire::core::edge_descriptor edge; bool b;
        envire::core::Transform tf_prop(now);
        base::TransformWithCovariance tf(Eigen::AngleAxisd::Identity(), static_cast<base::Position>(my_vector->getData()));
        tf_prop.setTransform(tf);
        envire::core::vertex_descriptor node_to = tree.vertex(iv);
        boost::tie(edge, b) = tree.add_edge(root, node_to, tf_prop);
        BOOST_CHECK(b == true);
    }

    BOOST_TEST_MESSAGE("TRANSFORM PROPERTY TEST...");
    envire::core::edge_iterator it, end;
    for(boost::tie(it, end) = tree.edges(); it != end; ++it)
    {

        const Transform& transform = tree.getTransform(it);
        BOOST_CHECK(transform.time == now);
        BOOST_CHECK(transform.transform.translation == my_vector->getData());
    }
    BOOST_TEST_MESSAGE("DONE\n");

    BOOST_TEST_MESSAGE("GRAPHVIZ TEST...");
    envire::core::GraphViz gviz;

    gviz.write(tree, "graphviz_boost_test_transform_tree.dot");

    //tree.clear();
    BOOST_TEST_MESSAGE("DONE\n");
}

<|endoftext|>


<commit_before>#include "ffmpegdecoder.h"
#include "makeguard.h"
#include "interlockedadd.h"

extern "C"
{
#include "libavutil/imgutils.h"
}

#include <boost/log/trivial.hpp>
#include <tuple>

namespace {

bool frameToImage(
    VideoFrame& videoFrameData,
    AVFramePtr& m_videoFrame,
    SwsContext*& m_imageCovertContext,
    AVPixelFormat m_pixelFormat)
{
    if (m_videoFrame->format == m_pixelFormat
        || m_videoFrame->format == AV_PIX_FMT_DXVA2_VLD)
    {
        std::swap(m_videoFrame, videoFrameData.m_image);
    }
    else
    {
        const int width = m_videoFrame->width;
        const int height = m_videoFrame->height;

        videoFrameData.realloc(m_pixelFormat, width, height);

        // Prepare image conversion
        m_imageCovertContext =
            sws_getCachedContext(m_imageCovertContext, m_videoFrame->width, m_videoFrame->height,
            static_cast<AVPixelFormat>(m_videoFrame->format), width, height, m_pixelFormat,
            0, nullptr, nullptr, nullptr);

        assert(m_imageCovertContext != nullptr);

        if (m_imageCovertContext == nullptr)
        {
            return false;
        }

        // Doing conversion
        if (sws_scale(m_imageCovertContext, m_videoFrame->data, m_videoFrame->linesize, 0,
            m_videoFrame->height, videoFrameData.m_image->data, videoFrameData.m_image->linesize) <= 0)
        {
            assert(false && "sws_scale failed");
            BOOST_LOG_TRIVIAL(error) << "sws_scale failed";
            return false;
        }

        videoFrameData.m_image->sample_aspect_ratio = m_videoFrame->sample_aspect_ratio;
    }

    return true;
}

auto GetAsyncConversionFunction(AVFramePtr input,
    std::promise<VideoFrame *> &videoFramePromise,
    boost::shared_ptr<IFrameDecoder::ImageConversionFunc> imageConversionFunc,
    AVPixelFormat pixelFormat)
{
    return [input = std::move(input),
        outputFut = videoFramePromise.get_future(),
        imageConversionFunc = std::move(imageConversionFunc),
        pixelFormat]() mutable
    {
        try {
            const int stride = (input->width + 1) & ~1;

            std::vector<uint8_t> img(stride * (input->height + (input->height + 1) / 2));

            const auto data = img.data();

            if (input->format == AV_PIX_FMT_NV12)
            {
                av_image_copy_plane(data, stride, input->data[0], input->linesize[0], input->width, input->height);
                av_image_copy_plane(data + stride * input->height, stride, input->data[1], input->linesize[1], input->width, input->height / 2);
            }
            else
            {
                auto img_convert_ctx = sws_getContext(
                    input->width,
                    input->height,
                    (AVPixelFormat)input->format,
                    input->width,
                    input->height,
                    AV_PIX_FMT_NV12,
                    SWS_FAST_BILINEAR, NULL, NULL, NULL);

                uint8_t* const dst[] = { data, data + stride * input->height };
                const int dstStride[] = { stride, stride };

                sws_scale(img_convert_ctx, input->data, input->linesize, 0, input->height,
                    dst, dstStride);

                sws_freeContext(img_convert_ctx);
            }

            std::vector<uint8_t> outputImg;

            int outputHeight{};
            int outputWidth{};

            (*imageConversionFunc)(data, stride, input->width, input->height, outputImg, outputWidth, outputHeight);

            const int outputStride = outputWidth;

            auto output = outputFut.get();
            if (!output)
                return false;

            output->realloc(pixelFormat, outputWidth, outputHeight);

            auto img_convert_ctx = sws_getContext(
                outputWidth,
                outputHeight,
                AV_PIX_FMT_NV12,
                outputWidth,
                outputHeight,
                pixelFormat,
                SWS_FAST_BILINEAR, NULL, NULL, NULL);

            const auto outputData = outputImg.data();

            uint8_t* const src[] = { outputData, outputData + outputStride * outputHeight };
            const int srcStride[] = { outputStride, outputStride };

            sws_scale(img_convert_ctx,
                src, srcStride,
                0, outputHeight,
                output->m_image->data,
                output->m_image->linesize);

            sws_freeContext(img_convert_ctx);
        }
        catch (const std::exception& ex) {
            CHANNEL_LOG(ffmpeg_sync) << "Exception in async converter: " << typeid(ex).name() << ": " << ex.what();
            return false;
        }

        return true;
    };
}

} // namespace

struct FFmpegDecoder::VideoParseContext
{
    bool initialized = false;
    int numSkipped = 0;
};

void FFmpegDecoder::videoParseRunnable()
{
    CHANNEL_LOG(ffmpeg_threads) << "Video thread started";
    m_videoStartClock = VIDEO_START_CLOCK_NOT_INITIALIZED;
    double videoClock = 0; // pts of last decoded frame / predicted pts of next decoded frame

    VideoParseContext context{};

    for (;;)
    {
        if (m_isPaused && !m_isVideoSeekingWhilePaused)
        {
            boost::unique_lock<boost::mutex> locker(m_isPausedMutex);
            while (m_isPaused && !m_isVideoSeekingWhilePaused)
            {
                m_isPausedCV.wait(locker);
            }
        }

        for (;;)
        {
            AVPacket packet;
            if (!m_videoPacketsQueue.pop(packet,
                [this] { return m_isPaused && !m_isVideoSeekingWhilePaused; }))
            {
                break;
            }

            auto packetGuard = MakeGuard(&packet, av_packet_unref);

            if (!handleVideoPacket(packet, videoClock, context)
                || m_isPaused && !m_isVideoSeekingWhilePaused)
            {
                break;
            }
        }
    }
}

bool FFmpegDecoder::handleVideoPacket(
    const AVPacket& packet,
    double& videoClock,
    VideoParseContext& context)
{
    const int ret = avcodec_send_packet(m_videoCodecContext, &packet);
    if (ret < 0) {
        return false;
    }

    AVFramePtr videoFrame(av_frame_alloc());
    while (avcodec_receive_frame(m_videoCodecContext, videoFrame.get()) == 0)
    {
		const int64_t duration_stamp = videoFrame->best_effort_timestamp;

        // compute the exact PTS for the picture if it is omitted in the stream
        // pts1 is the dts of the pkt / pts of the frame
        if (duration_stamp != AV_NOPTS_VALUE)
        {
            videoClock = duration_stamp * av_q2d(m_videoStream->time_base);
        }
        const double pts = videoClock;

        // update video clock for next frame
        // for MPEG2, the frame can be repeated, so we update the clock accordingly
        const double frameDelay = av_q2d(m_videoCodecContext->time_base) *
            (1. + videoFrame->repeat_pict * 0.5);
        videoClock += frameDelay;

        if (!handleVideoFrame(videoFrame, pts, context)) {
            break;
        }
    }

    return true;
}

bool FFmpegDecoder::handleVideoFrame(
    AVFramePtr& videoFrame,
    double pts,
    VideoParseContext& context)
{
    enum { MAX_SKIPPED_TILL_REDRAW = 5 };
    enum { SKIP_LOOP_FILTER_THRESHOLD = 50 };
    const double MAX_DELAY = 0.2;

    const int64_t duration_stamp = videoFrame->best_effort_timestamp;

    boost::posix_time::time_duration td(boost::posix_time::pos_infin);
    bool inNextFrame = false;
    const bool haveVideoPackets = !m_videoPacketsQueue.empty();

    {
        boost::lock_guard<boost::mutex> locker(m_isPausedMutex);

        const bool isPaused = m_isPaused;
        inNextFrame = isPaused && m_isVideoSeekingWhilePaused;
        if (!context.initialized || inNextFrame)
        {
            const auto val = (isPaused ? m_pauseTimer : GetHiResTime()) - pts;
            m_videoStartClock = val;
            CHANNEL_LOG(ffmpeg_sync) << "isPaused = " << isPaused << " m_videoStartClock = " << val;
        }

        // Skipping frames
        if (context.initialized && !inNextFrame && haveVideoPackets)
        {
            const double curTime = GetHiResTime();
            if (m_videoStartClock + pts <= curTime)
            {
                if (m_videoStartClock + pts < curTime - MAX_DELAY)
                {
                    InterlockedAdd(m_videoStartClock, MAX_DELAY);
                }

                ++context.numSkipped;
                if (context.numSkipped == SKIP_LOOP_FILTER_THRESHOLD)
                {
                    if (m_videoCodecContext->skip_loop_filter != AVDISCARD_ALL)
                    {
                        // https://trac.kodi.tv/ticket/4943
                        CHANNEL_LOG(ffmpeg_sync) << "skip_loop_filter = AVDISCARD_ALL";
                        m_videoCodecContext->skip_loop_filter = AVDISCARD_ALL;
                    }
                }
                if ((context.numSkipped % MAX_SKIPPED_TILL_REDRAW) != 0)
                {
                    CHANNEL_LOG(ffmpeg_sync) << "Hard skip frame";

                    // pause
                    return !(isPaused && !m_isVideoSeekingWhilePaused);
                }
            }
            else
            {
                const auto speed = getSpeedRational();
                context.numSkipped = 0;
                td = boost::posix_time::milliseconds(
                    int((m_videoStartClock + pts - curTime) * 1000.  * speed.denominator / speed.numerator) + 1);
            }
        }
    }

    context.initialized = true;

    boost::shared_ptr<ImageConversionFunc> imageConversionFunc = m_imageConversionFunc;
    const bool useAsyncConversion = imageConversionFunc != nullptr && (*imageConversionFunc);

    handleDirect3dData(videoFrame.get(), useAsyncConversion);

    std::future<bool> convert;
    std::promise<VideoFrame*> videoFramePromise;

    auto promGuard = MakeGuard(&videoFramePromise, [](auto promise) { promise->set_value(nullptr); });

    if (useAsyncConversion)
    {
        AVFramePtr input(av_frame_alloc());

        std::swap(input, videoFrame);

        auto asyncConversion = GetAsyncConversionFunction(std::move(input),
            videoFramePromise,
            std::move(imageConversionFunc),
            m_pixelFormat);

        convert = std::async(std::launch::async, std::move(asyncConversion));
    }

    {
        boost::unique_lock<boost::mutex> locker(m_videoFramesMutex);

        if (!m_videoFramesCV.timed_wait(locker, td, [this]
        {
            return m_isPaused && !m_isVideoSeekingWhilePaused ||
                m_videoFramesQueue.canPush();
        }))
        {
            CHANNEL_LOG(ffmpeg_sync) << "Frame wait abandoned";
            return true;
        }
    }

    {
        boost::lock_guard<boost::mutex> locker(m_isPausedMutex);
        if (m_isPaused && !m_isVideoSeekingWhilePaused)
        {
            return false;
        }

        m_isVideoSeekingWhilePaused = false;
    }

    if (inNextFrame)
    {
        m_isPausedCV.notify_all();
    }

    VideoFrame& current_frame = m_videoFramesQueue.back();

    if (!useAsyncConversion && !frameToImage(current_frame, videoFrame, m_imageCovertContext, m_pixelFormat))
    {
        return true;
    }

    current_frame.m_pts = pts;
    current_frame.m_duration = duration_stamp;

    if (useAsyncConversion)
    {
        promGuard.release();
        videoFramePromise.set_value(&current_frame);
        current_frame.m_convert = std::move(convert);
    }

    {
        boost::lock_guard<boost::mutex> locker(m_videoFramesMutex);
        m_videoFramesQueue.pushBack();
    }
    m_videoFramesCV.notify_all();

    return true;
}
<commit_msg>simplified<commit_after>#include "ffmpegdecoder.h"
#include "makeguard.h"
#include "interlockedadd.h"

extern "C"
{
#include "libavutil/imgutils.h"
}

#include <boost/log/trivial.hpp>
#include <tuple>

namespace {

bool frameToImage(
    VideoFrame& videoFrameData,
    AVFramePtr& m_videoFrame,
    SwsContext*& m_imageCovertContext,
    AVPixelFormat m_pixelFormat)
{
    if (m_videoFrame->format == m_pixelFormat
        || m_videoFrame->format == AV_PIX_FMT_DXVA2_VLD)
    {
        std::swap(m_videoFrame, videoFrameData.m_image);
    }
    else
    {
        const int width = m_videoFrame->width;
        const int height = m_videoFrame->height;

        videoFrameData.realloc(m_pixelFormat, width, height);

        // Prepare image conversion
        m_imageCovertContext =
            sws_getCachedContext(m_imageCovertContext, m_videoFrame->width, m_videoFrame->height,
            static_cast<AVPixelFormat>(m_videoFrame->format), width, height, m_pixelFormat,
            0, nullptr, nullptr, nullptr);

        assert(m_imageCovertContext != nullptr);

        if (m_imageCovertContext == nullptr)
        {
            return false;
        }

        // Doing conversion
        if (sws_scale(m_imageCovertContext, m_videoFrame->data, m_videoFrame->linesize, 0,
            m_videoFrame->height, videoFrameData.m_image->data, videoFrameData.m_image->linesize) <= 0)
        {
            assert(false && "sws_scale failed");
            BOOST_LOG_TRIVIAL(error) << "sws_scale failed";
            return false;
        }

        videoFrameData.m_image->sample_aspect_ratio = m_videoFrame->sample_aspect_ratio;
    }

    return true;
}

auto GetAsyncConversionFunction(AVFramePtr input,
    std::promise<VideoFrame *> &videoFramePromise,
    boost::shared_ptr<IFrameDecoder::ImageConversionFunc> imageConversionFunc,
    AVPixelFormat pixelFormat)
{
    return [input = std::move(input),
        outputFut = videoFramePromise.get_future(),
        imageConversionFunc = std::move(imageConversionFunc),
        pixelFormat]() mutable
    {
        try {
            const int stride = (input->width + 1) & ~1;

            std::vector<uint8_t> img(stride * (input->height + (input->height + 1) / 2));

            const auto data = img.data();

            if (input->format == AV_PIX_FMT_NV12)
            {
                av_image_copy_plane(data, stride, input->data[0], input->linesize[0], input->width, input->height);
                av_image_copy_plane(data + stride * input->height, stride, input->data[1], input->linesize[1], input->width, input->height / 2);
            }
            else
            {
                auto img_convert_ctx = sws_getContext(
                    input->width,
                    input->height,
                    (AVPixelFormat)input->format,
                    input->width,
                    input->height,
                    AV_PIX_FMT_NV12,
                    SWS_FAST_BILINEAR, NULL, NULL, NULL);

                uint8_t* const dst[] = { data, data + stride * input->height };
                const int dstStride[] = { stride, stride };

                sws_scale(img_convert_ctx, input->data, input->linesize, 0, input->height,
                    dst, dstStride);

                sws_freeContext(img_convert_ctx);
            }

            std::vector<uint8_t> outputImg;

            int outputHeight{};
            int outputWidth{};

            (*imageConversionFunc)(data, stride, input->width, input->height, outputImg, outputWidth, outputHeight);

            const int outputStride = outputWidth;

            auto output = outputFut.get();
            if (!output)
                return false;

            output->realloc(pixelFormat, outputWidth, outputHeight);

            auto img_convert_ctx = sws_getContext(
                outputWidth,
                outputHeight,
                AV_PIX_FMT_NV12,
                outputWidth,
                outputHeight,
                pixelFormat,
                SWS_FAST_BILINEAR, NULL, NULL, NULL);

            const auto outputData = outputImg.data();

            uint8_t* const src[] = { outputData, outputData + outputStride * outputHeight };
            const int srcStride[] = { outputStride, outputStride };

            sws_scale(img_convert_ctx,
                src, srcStride,
                0, outputHeight,
                output->m_image->data,
                output->m_image->linesize);

            sws_freeContext(img_convert_ctx);
        }
        catch (const std::exception& ex) {
            CHANNEL_LOG(ffmpeg_sync) << "Exception in async converter: " << typeid(ex).name() << ": " << ex.what();
            return false;
        }

        return true;
    };
}

} // namespace

struct FFmpegDecoder::VideoParseContext
{
    bool initialized = false;
    int numSkipped = 0;
};

void FFmpegDecoder::videoParseRunnable()
{
    CHANNEL_LOG(ffmpeg_threads) << "Video thread started";
    m_videoStartClock = VIDEO_START_CLOCK_NOT_INITIALIZED;
    double videoClock = 0; // pts of last decoded frame / predicted pts of next decoded frame

    VideoParseContext context{};

    for (;;)
    {
        AVPacket packet;
        if (!m_videoPacketsQueue.pop(packet))
        {
            break;
        }

        auto packetGuard = MakeGuard(&packet, av_packet_unref);

        handleVideoPacket(packet, videoClock, context);
    }
}

bool FFmpegDecoder::handleVideoPacket(
    const AVPacket& packet,
    double& videoClock,
    VideoParseContext& context)
{
    const int ret = avcodec_send_packet(m_videoCodecContext, &packet);
    if (ret < 0) {
        return false;
    }

    AVFramePtr videoFrame(av_frame_alloc());
    while (avcodec_receive_frame(m_videoCodecContext, videoFrame.get()) == 0)
    {
		const int64_t duration_stamp = videoFrame->best_effort_timestamp;

        // compute the exact PTS for the picture if it is omitted in the stream
        // pts1 is the dts of the pkt / pts of the frame
        if (duration_stamp != AV_NOPTS_VALUE)
        {
            videoClock = duration_stamp * av_q2d(m_videoStream->time_base);
        }
        const double pts = videoClock;

        // update video clock for next frame
        // for MPEG2, the frame can be repeated, so we update the clock accordingly
        const double frameDelay = av_q2d(m_videoCodecContext->time_base) *
            (1. + videoFrame->repeat_pict * 0.5);
        videoClock += frameDelay;

        if (!handleVideoFrame(videoFrame, pts, context)) {
            break;
        }
    }

    return true;
}

bool FFmpegDecoder::handleVideoFrame(
    AVFramePtr& videoFrame,
    double pts,
    VideoParseContext& context)
{
    enum { MAX_SKIPPED_TILL_REDRAW = 5 };
    enum { SKIP_LOOP_FILTER_THRESHOLD = 50 };
    const double MAX_DELAY = 0.2;

    const int64_t duration_stamp = videoFrame->best_effort_timestamp;

    boost::posix_time::time_duration td(boost::posix_time::pos_infin);
    bool inNextFrame = false;

    {
        boost::unique_lock<boost::mutex> locker(m_isPausedMutex);
        while (m_isPaused && !m_isVideoSeekingWhilePaused)
        {
            m_isPausedCV.wait(locker);
        }

        const bool isPaused = m_isPaused;
        inNextFrame = isPaused && m_isVideoSeekingWhilePaused;
        if (!context.initialized || inNextFrame)
        {
            const auto val = (isPaused ? m_pauseTimer : GetHiResTime()) - pts;
            m_videoStartClock = val;
            CHANNEL_LOG(ffmpeg_sync) << "isPaused = " << isPaused << " m_videoStartClock = " << val;
        }

        // Skipping frames
        if (context.initialized && !inNextFrame && !m_videoPacketsQueue.empty())
        {
            const double curTime = GetHiResTime();
            if (m_videoStartClock + pts <= curTime)
            {
                if (m_videoStartClock + pts < curTime - MAX_DELAY)
                {
                    InterlockedAdd(m_videoStartClock, MAX_DELAY);
                }

                ++context.numSkipped;
                if (context.numSkipped == SKIP_LOOP_FILTER_THRESHOLD)
                {
                    if (m_videoCodecContext->skip_loop_filter != AVDISCARD_ALL)
                    {
                        // https://trac.kodi.tv/ticket/4943
                        CHANNEL_LOG(ffmpeg_sync) << "skip_loop_filter = AVDISCARD_ALL";
                        m_videoCodecContext->skip_loop_filter = AVDISCARD_ALL;
                    }
                }
                if ((context.numSkipped % MAX_SKIPPED_TILL_REDRAW) != 0)
                {
                    CHANNEL_LOG(ffmpeg_sync) << "Hard skip frame";

                    // pause
                    return !(isPaused && !m_isVideoSeekingWhilePaused);
                }
            }
            else
            {
                const auto speed = getSpeedRational();
                context.numSkipped = 0;
                td = boost::posix_time::milliseconds(
                    int((m_videoStartClock + pts - curTime) * 1000.  * speed.denominator / speed.numerator) + 1);
            }
        }
    }

    context.initialized = true;

    boost::shared_ptr<ImageConversionFunc> imageConversionFunc = m_imageConversionFunc;
    const bool useAsyncConversion = imageConversionFunc != nullptr && (*imageConversionFunc);

    handleDirect3dData(videoFrame.get(), useAsyncConversion);

    std::future<bool> convert;
    std::promise<VideoFrame*> videoFramePromise;

    auto promGuard = MakeGuard(&videoFramePromise, [](auto promise) { promise->set_value(nullptr); });

    if (useAsyncConversion)
    {
        AVFramePtr input(av_frame_alloc());

        std::swap(input, videoFrame);

        auto asyncConversion = GetAsyncConversionFunction(std::move(input),
            videoFramePromise,
            std::move(imageConversionFunc),
            m_pixelFormat);

        convert = std::async(std::launch::async, std::move(asyncConversion));
    }

    {
        boost::unique_lock<boost::mutex> locker(m_videoFramesMutex);

        if (!m_videoFramesCV.timed_wait(locker, td, [this]
        {
            return m_isPaused && !m_isVideoSeekingWhilePaused ||
                m_videoFramesQueue.canPush();
        }))
        {
            CHANNEL_LOG(ffmpeg_sync) << "Frame wait abandoned";
            return true;
        }
    }

    {
        boost::lock_guard<boost::mutex> locker(m_isPausedMutex);
        if (m_isPaused && !m_isVideoSeekingWhilePaused)
        {
            return false;
        }

        m_isVideoSeekingWhilePaused = false;
    }

    if (inNextFrame)
    {
        m_isPausedCV.notify_all();
    }

    VideoFrame& current_frame = m_videoFramesQueue.back();

    if (!useAsyncConversion && !frameToImage(current_frame, videoFrame, m_imageCovertContext, m_pixelFormat))
    {
        return true;
    }

    current_frame.m_pts = pts;
    current_frame.m_duration = duration_stamp;

    if (useAsyncConversion)
    {
        promGuard.release();
        videoFramePromise.set_value(&current_frame);
        current_frame.m_convert = std::move(convert);
    }

    {
        boost::lock_guard<boost::mutex> locker(m_videoFramesMutex);
        m_videoFramesQueue.pushBack();
    }
    m_videoFramesCV.notify_all();

    return true;
}
<|endoftext|>


<commit_before>/**
 * \ file LMSFilter.cpp
 */

#include <array>
#include <fstream>

#include <ATK/Adaptive/LMSFilter.h>

#include <ATK/Core/InPointerFilter.h>
#include <ATK/Core/OutPointerFilter.h>

#include <ATK/Tools/SumFilter.h>

#include <Eigen/Core>

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>

#include <boost/math/constants/constants.hpp>

#define PROCESSSIZE (1200)

BOOST_AUTO_TEST_CASE(LMSFilter_size_negative_test)
{
  ATK::LMSFilter<float> filter(100);
  BOOST_CHECK_THROW(filter.set_size(0), std::out_of_range);
}

BOOST_AUTO_TEST_CASE(LMSFilter_size_set_test)
{
  ATK::LMSFilter<float> filter(100);
  filter.set_size(10);
  BOOST_CHECK_EQUAL(filter.get_size(), 10);
}

BOOST_AUTO_TEST_CASE(LMSFilter_memory_negative_test)
{
  ATK::LMSFilter<float> filter(100);
  BOOST_CHECK_THROW(filter.set_memory(0), std::out_of_range);
}

BOOST_AUTO_TEST_CASE(LMSFilter_memory_test)
{
  ATK::LMSFilter<float> filter(100);
  filter.set_memory(0.5);
  BOOST_CHECK_EQUAL(filter.get_memory(), 0.5);
}

BOOST_AUTO_TEST_CASE( LMSFilter_memory_positive1_test )
{
  ATK::LMSFilter<float> filter(100);
  BOOST_CHECK_THROW(filter.set_memory(1), std::out_of_range);
}

BOOST_AUTO_TEST_CASE( LMSFilter_memory_99_test )
{
  std::array<double, PROCESSSIZE> data;
  {
    std::ifstream input(ATK_SOURCE_TREE "/tests/data/input_lms.dat", std::ios::binary);
    input.read(reinterpret_cast<char*>(data.data()), PROCESSSIZE * sizeof(double));
  }

  ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
  generator.set_output_sampling_rate(48000);

  ATK::LMSFilter<double> filter(100);
  filter.set_input_sampling_rate(48000);
  filter.set_output_sampling_rate(48000);
  filter.set_memory(.999);
  filter.set_mu(.01);

  filter.set_input_port(0, &generator, 0);
  filter.set_input_port(1, &generator, 0);

  filter.process(PROCESSSIZE);

  std::array<double, PROCESSSIZE> outdata;
  {
    std::ifstream input(ATK_SOURCE_TREE "/tests/data/output_lms.dat", std::ios::binary);
    input.read(reinterpret_cast<char*>(outdata.data()), PROCESSSIZE * sizeof(double));
  }

  for (unsigned int i = 0; i < PROCESSSIZE; ++i)
  {
    BOOST_CHECK_CLOSE(outdata[i], filter.get_output_array(0)[i], 0.0001);
  }
}
<commit_msg>Adding mu tests<commit_after>/**
 * \ file LMSFilter.cpp
 */

#include <array>
#include <fstream>

#include <ATK/Adaptive/LMSFilter.h>

#include <ATK/Core/InPointerFilter.h>
#include <ATK/Core/OutPointerFilter.h>

#include <ATK/Tools/SumFilter.h>

#include <Eigen/Core>

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>

#include <boost/math/constants/constants.hpp>

#define PROCESSSIZE (1200)

BOOST_AUTO_TEST_CASE(LMSFilter_size_negative_test)
{
  ATK::LMSFilter<float> filter(100);
  BOOST_CHECK_THROW(filter.set_size(0), std::out_of_range);
}

BOOST_AUTO_TEST_CASE(LMSFilter_size_set_test)
{
  ATK::LMSFilter<float> filter(100);
  filter.set_size(10);
  BOOST_CHECK_EQUAL(filter.get_size(), 10);
}

BOOST_AUTO_TEST_CASE(LMSFilter_memory_negative_test)
{
  ATK::LMSFilter<float> filter(100);
  BOOST_CHECK_THROW(filter.set_memory(0), std::out_of_range);
}

BOOST_AUTO_TEST_CASE(LMSFilter_memory_test)
{
  ATK::LMSFilter<float> filter(100);
  filter.set_memory(0.5);
  BOOST_CHECK_EQUAL(filter.get_memory(), 0.5);
}

BOOST_AUTO_TEST_CASE( LMSFilter_memory_positive1_test )
{
  ATK::LMSFilter<float> filter(100);
  BOOST_CHECK_THROW(filter.set_memory(1), std::out_of_range);
}

BOOST_AUTO_TEST_CASE(LMSFilter_mu_negative_test)
{
  ATK::LMSFilter<float> filter(100);
  BOOST_CHECK_THROW(filter.set_mu(0), std::out_of_range);
}

BOOST_AUTO_TEST_CASE(LMSFilter_mu_test)
{
  ATK::LMSFilter<float> filter(100);
  filter.set_mu(0.5);
  BOOST_CHECK_EQUAL(filter.get_mu(), 0.5);
}

BOOST_AUTO_TEST_CASE( LMSFilter_mu_positive1_test )
{
  ATK::LMSFilter<float> filter(100);
  BOOST_CHECK_THROW(filter.set_mu(1), std::out_of_range);
}

BOOST_AUTO_TEST_CASE( LMSFilter_memory_99_test )
{
  std::array<double, PROCESSSIZE> data;
  {
    std::ifstream input(ATK_SOURCE_TREE "/tests/data/input_lms.dat", std::ios::binary);
    input.read(reinterpret_cast<char*>(data.data()), PROCESSSIZE * sizeof(double));
  }

  ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
  generator.set_output_sampling_rate(48000);

  ATK::LMSFilter<double> filter(100);
  filter.set_input_sampling_rate(48000);
  filter.set_output_sampling_rate(48000);
  filter.set_memory(.999);
  filter.set_mu(.01);

  filter.set_input_port(0, &generator, 0);
  filter.set_input_port(1, &generator, 0);

  filter.process(PROCESSSIZE);

  std::array<double, PROCESSSIZE> outdata;
  {
    std::ifstream input(ATK_SOURCE_TREE "/tests/data/output_lms.dat", std::ios::binary);
    input.read(reinterpret_cast<char*>(outdata.data()), PROCESSSIZE * sizeof(double));
  }

  for (unsigned int i = 0; i < PROCESSSIZE; ++i)
  {
    BOOST_CHECK_CLOSE(outdata[i], filter.get_output_array(0)[i], 0.0001);
  }
}
<|endoftext|>


<commit_before>//===-- ARMWinCOFFObjectWriter.cpp - ARM Windows COFF Object Writer -- C++ -==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "MCTargetDesc/ARMFixupKinds.h"
#include "llvm/MC/MCFixup.h"
#include "llvm/MC/MCValue.h"
#include "llvm/MC/MCWinCOFFObjectWriter.h"
#include "llvm/Support/COFF.h"
#include "llvm/Support/Debug.h"

using namespace llvm;

namespace {
class ARMWinCOFFObjectWriter : public MCWinCOFFObjectTargetWriter {
public:
  ARMWinCOFFObjectWriter(bool Is64Bit)
    : MCWinCOFFObjectTargetWriter(COFF::IMAGE_FILE_MACHINE_ARMNT) {
    assert(!Is64Bit && "AArch64 support not yet implemented");
  }
  virtual ~ARMWinCOFFObjectWriter() = default;

  unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup,
                        bool IsCrossSection) const override;
};

unsigned ARMWinCOFFObjectWriter::getRelocType(const MCValue &Target,
                                              const MCFixup &Fixup,
                                              bool IsCrossSection) const {
  assert(getMachine() == COFF::IMAGE_FILE_MACHINE_ARMNT &&
         "AArch64 support not yet implemented");

  MCSymbolRefExpr::VariantKind Modifier =
    Target.isAbsolute() ? MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();

  switch (static_cast<unsigned>(Fixup.getKind())) {
  default: llvm_unreachable("unsupported relocation type");
  case FK_Data_4:
    switch (Modifier) {
    case MCSymbolRefExpr::VK_COFF_IMGREL32:
      return COFF::IMAGE_REL_ARM_ADDR32NB;
    case MCSymbolRefExpr::VK_SECREL:
      return COFF::IMAGE_REL_ARM_SECREL;
    default:
      return COFF::IMAGE_REL_ARM_ADDR32;
    }
  case ARM::fixup_t2_condbranch:
    return COFF::IMAGE_REL_ARM_BRANCH20T;
  case ARM::fixup_t2_uncondbranch:
    return COFF::IMAGE_REL_ARM_BRANCH24T;
  case ARM::fixup_arm_thumb_bl:
  case ARM::fixup_arm_thumb_blx:
    return COFF::IMAGE_REL_ARM_BLX23T;
  case ARM::fixup_t2_movw_lo16:
    return COFF::IMAGE_REL_ARM_MOV32T;
  case ARM::fixup_t2_movt_hi16:
    llvm_unreachable("High-word for pair-wise relocations are contiguously "
                     "addressed as an IMAGE_REL_ARM_MOV32T relocation");
  }
}
}

namespace llvm {
MCObjectWriter *createARMWinCOFFObjectWriter(raw_ostream &OS, bool Is64Bit) {
  MCWinCOFFObjectTargetWriter *MOTW = new ARMWinCOFFObjectWriter(Is64Bit);
  return createWinCOFFObjectWriter(MOTW, OS);
}
}

<commit_msg>ARM: MSVC does not support = default<commit_after>//===-- ARMWinCOFFObjectWriter.cpp - ARM Windows COFF Object Writer -- C++ -==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "MCTargetDesc/ARMFixupKinds.h"
#include "llvm/MC/MCFixup.h"
#include "llvm/MC/MCValue.h"
#include "llvm/MC/MCWinCOFFObjectWriter.h"
#include "llvm/Support/COFF.h"
#include "llvm/Support/Debug.h"

using namespace llvm;

namespace {
class ARMWinCOFFObjectWriter : public MCWinCOFFObjectTargetWriter {
public:
  ARMWinCOFFObjectWriter(bool Is64Bit)
    : MCWinCOFFObjectTargetWriter(COFF::IMAGE_FILE_MACHINE_ARMNT) {
    assert(!Is64Bit && "AArch64 support not yet implemented");
  }
  virtual ~ARMWinCOFFObjectWriter() { }

  unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup,
                        bool IsCrossSection) const override;
};

unsigned ARMWinCOFFObjectWriter::getRelocType(const MCValue &Target,
                                              const MCFixup &Fixup,
                                              bool IsCrossSection) const {
  assert(getMachine() == COFF::IMAGE_FILE_MACHINE_ARMNT &&
         "AArch64 support not yet implemented");

  MCSymbolRefExpr::VariantKind Modifier =
    Target.isAbsolute() ? MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();

  switch (static_cast<unsigned>(Fixup.getKind())) {
  default: llvm_unreachable("unsupported relocation type");
  case FK_Data_4:
    switch (Modifier) {
    case MCSymbolRefExpr::VK_COFF_IMGREL32:
      return COFF::IMAGE_REL_ARM_ADDR32NB;
    case MCSymbolRefExpr::VK_SECREL:
      return COFF::IMAGE_REL_ARM_SECREL;
    default:
      return COFF::IMAGE_REL_ARM_ADDR32;
    }
  case ARM::fixup_t2_condbranch:
    return COFF::IMAGE_REL_ARM_BRANCH20T;
  case ARM::fixup_t2_uncondbranch:
    return COFF::IMAGE_REL_ARM_BRANCH24T;
  case ARM::fixup_arm_thumb_bl:
  case ARM::fixup_arm_thumb_blx:
    return COFF::IMAGE_REL_ARM_BLX23T;
  case ARM::fixup_t2_movw_lo16:
    return COFF::IMAGE_REL_ARM_MOV32T;
  case ARM::fixup_t2_movt_hi16:
    llvm_unreachable("High-word for pair-wise relocations are contiguously "
                     "addressed as an IMAGE_REL_ARM_MOV32T relocation");
  }
}
}

namespace llvm {
MCObjectWriter *createARMWinCOFFObjectWriter(raw_ostream &OS, bool Is64Bit) {
  MCWinCOFFObjectTargetWriter *MOTW = new ARMWinCOFFObjectWriter(Is64Bit);
  return createWinCOFFObjectWriter(MOTW, OS);
}
}

<|endoftext|>