<commit_before>/**
 * Copyright 2019-2020 Advanced Micro Devices, Inc. All rights reserved.
 *
 * 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.
 */

#pragma once

#include <cstddef>
#include <functional>
#include <string>
#include <tuple>
#include <vector>

#include <Tensile/Debug.hpp>
#include <Tensile/Distance.hpp>
#include <Tensile/Properties.hpp>
#include <Tensile/Utils.hpp>

namespace Tensile
{
    /**
 * \ingroup Tensile
 * \defgroup PropertyMatching Property Matching
 *
 * @brief Distance-based matching of Property values to a table.
 *
 * Generic algorithm for comparing an object to a table of predefined
 * values based on Property objects and a Distance function. Used for
 * MatchingLibrary.
 */

    /**
 * \ingroup PropertyMatching
 */
    namespace Matching
    {
        template <typename Key, typename Value>
        struct MatchingTableEntry
        {
            Key    key;
            Value  value;
            double speed;
        };

        template <typename Object, typename Value, typename ReturnValue>
        struct MatchingTable
        {
            using Properties = std::vector<std::shared_ptr<Property<Object>>>;
            using Transform  = std::function<ReturnValue(Value)>;

            MatchingTable() = default;
            MatchingTable(Properties const& properties)
                : properties(properties)
            {
            }

            virtual ~MatchingTable() = default;

            virtual std::tuple<ReturnValue, double> findBestMatch(Object const& object,
                                                                  Transform transform) const = 0;

            virtual ReturnValue findBestEvaluationSolution(Object const&   object,
                                                           Hardware const& hardware,
                                                           Transform       transform) const = 0;

            virtual std::vector<Value> matchesInOrder(Object const& object) const = 0;

            virtual std::string description() const = 0;

            virtual std::string distanceType() const = 0;

            Properties properties;
        };

        /**
 * This exists to provide an abstraction around the different syntax of creating
 * a vector of a size given at runtime vs. creating an array with a fixed size.
 */
        template <typename Key>
        struct KeyFactory
        {
        };

        template <typename T>
        struct KeyFactory<std::vector<T>>
        {
            static std::vector<T> MakeKey(size_t size)
            {
                return std::vector<T>(size);
            }
        };

        template <typename T, size_t N>
        struct KeyFactory<std::array<T, N>>
        {
            static std::array<T, N> MakeKey(size_t size)
            {
                return std::array<T, N>();
            }
        };

        template <typename Key,
                  typename Object,
                  typename Value,
                  typename ReturnValue,
                  typename Distance>
        class DistanceMatchingTable : public MatchingTable<Object, Value, ReturnValue>
        {
        public:
            using Base       = MatchingTable<Object, Value, ReturnValue>;
            using Entry      = MatchingTableEntry<Key, Value>;
            using Transform  = typename Base::Transform;
            using Properties = typename Base::Properties;

            DistanceMatchingTable(ReturnValue nullValue = ReturnValue())
                : nullValue(nullValue)
            {
            }

            DistanceMatchingTable(Properties const& properties,
                                  ReturnValue       nullValue = ReturnValue())
                : Base(properties)
                , nullValue(nullValue)
            {
            }

            DistanceMatchingTable(Distance const&   distance,
                                  Properties const& properties,
                                  ReturnValue       nullValue = ReturnValue())
                : Base(properties)
                , nullValue(nullValue)
                , distance(distance)
            {
            }

            virtual std::string distanceType() const override
            {
                return Distance::Type();
            }

            std::tuple<ReturnValue, double> findBestKeyMatch(Key const& key,
                                                             Transform  transform) const
            {
                const bool debug = Debug::Instance().printPropertyEvaluation();
                const bool naive = Debug::Instance().naivePropertySearch();

                if(naive)
                {
                    if(debug)
                        return findBestKeyMatch_NaiveSearch<true>(key, transform);
                    else
                        return findBestKeyMatch_NaiveSearch<false>(key, transform);
                }
                else
                {
                    if(debug)
                        return findBestKeyMatch_BinSearch<true>(key, transform);
                    else
                        return findBestKeyMatch_BinSearch<false>(key, transform);
                }
            }

            template <bool T_Debug>
            std::tuple<ReturnValue, double> findBestKeyMatch_BinSearch(Key const& key,
                                                                       Transform  transform) const
            {
                if(this->table.empty())
                    return std::make_tuple(this->nullValue, std::numeric_limits<double>::max());

                auto comp = [](Entry const& e, Key const& key) { return e.key < key; };

                auto origIter = std::lower_bound(table.begin(), table.end(), key, comp);

                if(T_Debug)
                {
                    std::cout << "Key: ";
                    streamJoin(std::cout, key, ", ");
                    std::cout << std::endl;

                    std::cout << "Starting point: ";
                    streamJoin(std::cout, origIter->key, ", ");
                    std::cout << std::endl;

                    std::cout << "Rightward search..." << std::endl;
                }

                double bestDistance = std::numeric_limits<double>::max();
                auto   bestMatch    = this->nullValue;
                double bestSpeed    = 0.0;

                ptrdiff_t count = 0;

                for(auto iter = origIter; iter != table.end(); iter++)
                {
                    if(bestMatch && !distance.improvementPossible(key, iter->key, 0, bestDistance))
                    {
                        if(T_Debug)
                        {
                            streamJoin(std::cout, iter->key, ", ");
                            std::cout << ": Stopping rightward search early." << std::endl;
                        }

                        break;
                    }

                    count++;

                    auto myDistance = distance(key, iter->key);
                    bool thisMatch  = false;

                    if(myDistance < bestDistance
                       || (myDistance == bestDistance && iter->speed > bestSpeed))
                    {
                        auto myMatch = transform(iter->value);

                        if(myMatch)
                        {
                            bestDistance = myDistance;
                            bestMatch    = myMatch;
                            bestSpeed    = iter->speed;
                            thisMatch    = true;
                        }
                    }

                    if(T_Debug)
                    {
                        if(myDistance <= bestDistance)
                            std::cout << std::endl;

                        std::cout << "speed: " << iter->speed << " | ";
                        streamJoin(std::cout, iter->key, ", ");
                        std::cout << ": " << myDistance;

                        if(myDistance < bestDistance)
                            std::cout << " < ";
                        else if(myDistance > bestDistance)
                            std::cout << " > ";
                        else
                            std::cout << " == ";

                        std::cout << bestDistance;

                        if(myDistance < bestDistance)
                        {
                            if(thisMatch)
                                std::cout << " <-- Best so far";
                            else
                                std::cout << " <-- Best distance, but no matching solution";
                        }

                        std::cout << std::endl;
                    }
                }

                auto iter = table.rbegin();

                if(origIter != table.end())
                    iter = std::make_reverse_iterator(origIter);

                if(T_Debug)
                    std::cout << "Leftward search..." << std::endl;

                for(; iter != table.rend(); iter++)
                {
                    if(bestMatch && !distance.improvementPossible(key, iter->key, 0, bestDistance))
                    {
                        if(T_Debug)
                        {
                            streamJoin(std::cout, iter->key, ", ");
                            std::cout << ": Stopping leftward search early." << std::endl;
                        }

                        break;
                    }

                    count++;

                    auto myDistance = distance(key, iter->key);
                    bool thisMatch  = false;

                    if(myDistance < bestDistance
                       || (myDistance == bestDistance && iter->speed > bestSpeed))
                    {
                        auto myMatch = transform(iter->value);

                        if(myMatch)
                        {
                            bestDistance = myDistance;
                            bestMatch    = myMatch;
                            bestSpeed    = iter->speed;
                            thisMatch    = true;
                        }
                    }

                    if(T_Debug)
                    {
                        if(myDistance <= bestDistance)
                            std::cout << std::endl;

                        streamJoin(std::cout, iter->key, ", ");
                        std::cout << ": " << myDistance;

                        if(myDistance < bestDistance)
                            std::cout << " < ";
                        else if(myDistance > bestDistance)
                            std::cout << " > ";
                        else
                            std::cout << " == ";

                        std::cout << bestDistance;

                        if(myDistance < bestDistance)
                        {
                            if(thisMatch)
                                std::cout << " <-- Best so far";
                            else
                                std::cout << " <-- Best distance, but no matching solution";
                        }

                        std::cout << std::endl;
                    }
                }

                if((T_Debug || Debug::Instance().printLookupEfficiency()) && table.size() > 0)
                {
                    double considered = count;
                    considered /= table.size();
                    considered *= 100;
                    std::cout << "Considered " << considered << "% of entries." << std::endl;
                }

                return std::make_tuple(bestMatch, bestDistance);
            }

            template <bool T_Debug>
            std::tuple<ReturnValue, double> findBestKeyMatch_NaiveSearch(Key const& key,
                                                                         Transform  transform) const
            {
                double bestDistance = std::numeric_limits<double>::max();

                auto iter = this->table.begin();
                if(iter == this->table.end())
                    return std::make_tuple(this->nullValue, bestDistance);

                ReturnValue bestMatch = transform(iter->value);

                if(bestMatch)
                    bestDistance = distance(key, iter->key);

                if(T_Debug)
                {
                    std::cout << "Key: ";
                    streamJoin(std::cout, key, ", ");
                    std::cout << std::endl;

                    streamJoin(std::cout, iter->key, ", ");

                    std::cout << ": " << bestDistance << " <-- First" << std::endl;
                }

                iter++;

                while(iter != this->table.end())
                {
                    auto myDistance = distance(key, iter->key);
                    bool thisMatch  = false;

                    if(myDistance < bestDistance)
                    {
                        auto myMatch = transform(iter->value);

                        if(myMatch)
                        {
                            bestDistance = myDistance;
                            bestMatch    = myMatch;
                            thisMatch    = true;
                        }
                    }

                    if(T_Debug)
                    {
                        streamJoin(std::cout, iter->key, ", ");
                        std::cout << ": " << myDistance;
                        if(myDistance < bestDistance)
                        {
                            std::cout << " <-- Best so far";

                            if(thisMatch)
                                std::cout << " (has a matching solution)";
                            else
                                std::cout << " (no match)";
                        }

                        std::cout << std::endl;
                    }

                    iter++;
                }

                return std::make_tuple(bestMatch, bestDistance);
            }

            std::vector<Value> keyMatchesInOrder(Key const& key) const
            {
                std::vector<std::pair<double, size_t>> indices(this->table.size());

                for(size_t i = 0; i < this->table.size(); i++)
                    indices[i] = std::make_pair(distance(key, this->table[i].key), i);

                std::sort(indices.begin(), indices.end());

                std::vector<Value> result;
                result.reserve(this->table.size());

                for(auto const& entry : indices)
                    result.push_back(this->table[entry.second].value);

                return result;
            }

            Key keyForProblem(Object const& object) const
            {
                bool debug = Debug::Instance().printPropertyEvaluation();

                Key myKey = KeyFactory<Key>::MakeKey(this->properties.size());

                for(int i = 0; i < this->properties.size(); i++)
                    myKey[i] = (*this->properties[i])(object);

                if(debug)
                {
                    std::cout << "Object key: ";
                    streamJoin(std::cout, myKey, ", ");
                    std::cout << std::endl;
                }

                return myKey;
            }

            virtual std::tuple<ReturnValue, double>
                findBestMatch(Object const& object, Transform transform) const override
            {
                return findBestKeyMatch(keyForProblem(object), transform);
            }

            virtual std::vector<Value> matchesInOrder(Object const& object) const override
            {
                return keyMatchesInOrder(keyForProblem(object));
            }

            virtual ReturnValue findBestEvaluationSolution(Object const&   object,
                                                           Hardware const& hardware,
                                                           Transform       transform) const override
            {
                double bestDistance = std::numeric_limits<double>::max();

                auto iter = this->table.begin();
                if(iter == this->table.end())
                    return this->nullValue;

                ReturnValue theMatch = transform(iter->value);

                ReturnValue bestMatch = theMatch;
                if(theMatch != nullptr)
                {
                    size_t model_M          = iter->key[0];
                    size_t model_N          = iter->key[1];
                    size_t model_K          = 1;
                    size_t model_NumBatches = 1;

                    if(iter->key.size() > 3)
                    {
                        model_K          = iter->key[3];
                        model_NumBatches = iter->key[2];
                    }
                    else
                    {
                        model_K = iter->key[2];
                    }
                    bestDistance = theMatch->computeTAMScore(object,
                                                             hardware,
                                                             (double)model_M,
                                                             (double)model_N,
                                                             (double)model_K,
                                                             (double)model_NumBatches);
                }

                iter++;

                while(iter != this->table.end())
                {
                    auto nextMatch = transform(iter->value);

                    if(nextMatch != nullptr)
                    {
                        size_t model_M          = iter->key[0];
                        size_t model_N          = iter->key[1];
                        size_t model_K          = 1;
                        size_t model_NumBatches = 1;

                        if(iter->key.size() > 3)
                        {
                            model_K          = iter->key[3];
                            model_NumBatches = iter->key[2];
                        }
                        else
                        {
                            model_K = iter->key[2];
                        }
                        double nextDistance = theMatch->computeTAMScore(object,
                                                                        hardware,
                                                                        (double)model_M,
                                                                        (double)model_N,
                                                                        (double)model_K,
                                                                        (double)model_NumBatches);

                        if(nextDistance < bestDistance)
                        {
                            bestMatch    = nextMatch;
                            bestDistance = nextDistance;
                        }
                    }

                    ++iter;
                }

                return bestMatch;
            }

            virtual std::string description() const override
            {
                std::string rv = concatenate(
                    "Table: Properties: ", this->properties, ", ", table.size(), " rows, ");

                rv += concatenate("Distance: ", Distance::Type());

                return rv;
            }

            std::vector<Entry> table;
            Distance           distance;

        protected:
            ReturnValue nullValue;
        };
    } // namespace Matching
} // namespace Tensile
<commit_msg>Print solution index selected after search (#1394)<commit_after>/**
 * Copyright 2019-2020 Advanced Micro Devices, Inc. All rights reserved.
 *
 * 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.
 */

#pragma once

#include <cstddef>
#include <functional>
#include <string>
#include <tuple>
#include <vector>

#include <Tensile/Debug.hpp>
#include <Tensile/Distance.hpp>
#include <Tensile/Properties.hpp>
#include <Tensile/Utils.hpp>

namespace Tensile
{
    /**
 * \ingroup Tensile
 * \defgroup PropertyMatching Property Matching
 *
 * @brief Distance-based matching of Property values to a table.
 *
 * Generic algorithm for comparing an object to a table of predefined
 * values based on Property objects and a Distance function. Used for
 * MatchingLibrary.
 */

    /**
 * \ingroup PropertyMatching
 */
    namespace Matching
    {
        template <typename Key, typename Value>
        struct MatchingTableEntry
        {
            Key    key;
            Value  value;
            double speed;
        };

        template <typename Object, typename Value, typename ReturnValue>
        struct MatchingTable
        {
            using Properties = std::vector<std::shared_ptr<Property<Object>>>;
            using Transform  = std::function<ReturnValue(Value)>;

            MatchingTable() = default;
            MatchingTable(Properties const& properties)
                : properties(properties)
            {
            }

            virtual ~MatchingTable() = default;

            virtual std::tuple<ReturnValue, double> findBestMatch(Object const& object,
                                                                  Transform transform) const = 0;

            virtual ReturnValue findBestEvaluationSolution(Object const&   object,
                                                           Hardware const& hardware,
                                                           Transform       transform) const = 0;

            virtual std::vector<Value> matchesInOrder(Object const& object) const = 0;

            virtual std::string description() const = 0;

            virtual std::string distanceType() const = 0;

            Properties properties;
        };

        /**
 * This exists to provide an abstraction around the different syntax of creating
 * a vector of a size given at runtime vs. creating an array with a fixed size.
 */
        template <typename Key>
        struct KeyFactory
        {
        };

        template <typename T>
        struct KeyFactory<std::vector<T>>
        {
            static std::vector<T> MakeKey(size_t size)
            {
                return std::vector<T>(size);
            }
        };

        template <typename T, size_t N>
        struct KeyFactory<std::array<T, N>>
        {
            static std::array<T, N> MakeKey(size_t size)
            {
                return std::array<T, N>();
            }
        };

        template <typename Key,
                  typename Object,
                  typename Value,
                  typename ReturnValue,
                  typename Distance>
        class DistanceMatchingTable : public MatchingTable<Object, Value, ReturnValue>
        {
        public:
            using Base       = MatchingTable<Object, Value, ReturnValue>;
            using Entry      = MatchingTableEntry<Key, Value>;
            using Transform  = typename Base::Transform;
            using Properties = typename Base::Properties;

            DistanceMatchingTable(ReturnValue nullValue = ReturnValue())
                : nullValue(nullValue)
            {
            }

            DistanceMatchingTable(Properties const& properties,
                                  ReturnValue       nullValue = ReturnValue())
                : Base(properties)
                , nullValue(nullValue)
            {
            }

            DistanceMatchingTable(Distance const&   distance,
                                  Properties const& properties,
                                  ReturnValue       nullValue = ReturnValue())
                : Base(properties)
                , nullValue(nullValue)
                , distance(distance)
            {
            }

            virtual std::string distanceType() const override
            {
                return Distance::Type();
            }

            std::tuple<ReturnValue, double> findBestKeyMatch(Key const& key,
                                                             Transform  transform) const
            {
                const bool debug = Debug::Instance().printPropertyEvaluation();
                const bool naive = Debug::Instance().naivePropertySearch();

                if(naive)
                {
                    if(debug)
                        return findBestKeyMatch_NaiveSearch<true>(key, transform);
                    else
                        return findBestKeyMatch_NaiveSearch<false>(key, transform);
                }
                else
                {
                    if(debug)
                        return findBestKeyMatch_BinSearch<true>(key, transform);
                    else
                        return findBestKeyMatch_BinSearch<false>(key, transform);
                }
            }

            template <bool T_Debug>
            std::tuple<ReturnValue, double> findBestKeyMatch_BinSearch(Key const& key,
                                                                       Transform  transform) const
            {
                if(this->table.empty())
                    return std::make_tuple(this->nullValue, std::numeric_limits<double>::max());

                auto comp = [](Entry const& e, Key const& key) { return e.key < key; };

                auto origIter = std::lower_bound(table.begin(), table.end(), key, comp);

                if(T_Debug)
                {
                    std::cout << "Key: ";
                    streamJoin(std::cout, key, ", ");
                    std::cout << std::endl;

                    std::cout << "Starting point: ";
                    streamJoin(std::cout, origIter->key, ", ");
                    std::cout << std::endl;

                    std::cout << "Rightward search..." << std::endl;
                }

                double bestDistance = std::numeric_limits<double>::max();
                auto   bestMatch    = this->nullValue;
                double bestSpeed    = 0.0;

                ptrdiff_t count = 0;

                for(auto iter = origIter; iter != table.end(); iter++)
                {
                    if(bestMatch && !distance.improvementPossible(key, iter->key, 0, bestDistance))
                    {
                        if(T_Debug)
                        {
                            streamJoin(std::cout, iter->key, ", ");
                            std::cout << ": Stopping rightward search early." << std::endl;
                        }

                        break;
                    }

                    count++;

                    auto myDistance = distance(key, iter->key);
                    bool thisMatch  = false;

                    if(myDistance < bestDistance
                       || (myDistance == bestDistance && iter->speed > bestSpeed))
                    {
                        auto myMatch = transform(iter->value);

                        if(myMatch)
                        {
                            bestDistance = myDistance;
                            bestMatch    = myMatch;
                            bestSpeed    = iter->speed;
                            thisMatch    = true;
                        }
                    }

                    if(T_Debug)
                    {
                        if(myDistance <= bestDistance)
                            std::cout << std::endl;

                        std::cout << "speed: " << iter->speed << " | ";
                        streamJoin(std::cout, iter->key, ", ");
                        std::cout << ": " << myDistance;

                        if(myDistance < bestDistance)
                            std::cout << " < ";
                        else if(myDistance > bestDistance)
                            std::cout << " > ";
                        else
                            std::cout << " == ";

                        std::cout << bestDistance;

                        if(myDistance < bestDistance)
                        {
                            if(thisMatch)
                                std::cout << " <-- Best so far";
                            else
                                std::cout << " <-- Best distance, but no matching solution";
                        }

                        std::cout << std::endl;
                    }
                }

                auto iter = table.rbegin();

                if(origIter != table.end())
                    iter = std::make_reverse_iterator(origIter);

                if(T_Debug)
                    std::cout << "Leftward search..." << std::endl;

                for(; iter != table.rend(); iter++)
                {
                    if(bestMatch && !distance.improvementPossible(key, iter->key, 0, bestDistance))
                    {
                        if(T_Debug)
                        {
                            streamJoin(std::cout, iter->key, ", ");
                            std::cout << ": Stopping leftward search early." << std::endl;
                        }

                        break;
                    }

                    count++;

                    auto myDistance = distance(key, iter->key);
                    bool thisMatch  = false;

                    if(myDistance < bestDistance
                       || (myDistance == bestDistance && iter->speed > bestSpeed))
                    {
                        auto myMatch = transform(iter->value);

                        if(myMatch)
                        {
                            bestDistance = myDistance;
                            bestMatch    = myMatch;
                            bestSpeed    = iter->speed;
                            thisMatch    = true;
                        }
                    }

                    if(T_Debug)
                    {
                        if(myDistance <= bestDistance)
                            std::cout << std::endl;

                        streamJoin(std::cout, iter->key, ", ");
                        std::cout << ": " << myDistance;

                        if(myDistance < bestDistance)
                            std::cout << " < ";
                        else if(myDistance > bestDistance)
                            std::cout << " > ";
                        else
                            std::cout << " == ";

                        std::cout << bestDistance;

                        if(myDistance < bestDistance)
                        {
                            if(thisMatch)
                                std::cout << " <-- Best so far";
                            else
                                std::cout << " <-- Best distance, but no matching solution";
                        }

                        std::cout << std::endl;
                    }
                }

                if((T_Debug || Debug::Instance().printLookupEfficiency()) && table.size() > 0)
                {
                    double considered = count;
                    considered /= table.size();
                    considered *= 100;
                    std::cout << "Considered " << considered << "% of entries." << std::endl;
                }

                if(T_Debug && bestMatch)
                    std::cout << "Solution index selected: " << bestMatch->index << std::endl;

                return std::make_tuple(bestMatch, bestDistance);
            }

            template <bool T_Debug>
            std::tuple<ReturnValue, double> findBestKeyMatch_NaiveSearch(Key const& key,
                                                                         Transform  transform) const
            {
                double bestDistance = std::numeric_limits<double>::max();

                auto iter = this->table.begin();
                if(iter == this->table.end())
                    return std::make_tuple(this->nullValue, bestDistance);

                ReturnValue bestMatch = transform(iter->value);

                if(bestMatch)
                    bestDistance = distance(key, iter->key);

                if(T_Debug)
                {
                    std::cout << "Key: ";
                    streamJoin(std::cout, key, ", ");
                    std::cout << std::endl;

                    streamJoin(std::cout, iter->key, ", ");

                    std::cout << ": " << bestDistance << " <-- First" << std::endl;
                }

                iter++;

                while(iter != this->table.end())
                {
                    auto myDistance = distance(key, iter->key);
                    bool thisMatch  = false;

                    if(myDistance < bestDistance)
                    {
                        auto myMatch = transform(iter->value);

                        if(myMatch)
                        {
                            bestDistance = myDistance;
                            bestMatch    = myMatch;
                            thisMatch    = true;
                        }
                    }

                    if(T_Debug)
                    {
                        streamJoin(std::cout, iter->key, ", ");
                        std::cout << ": " << myDistance;
                        if(myDistance < bestDistance)
                        {
                            std::cout << " <-- Best so far";

                            if(thisMatch)
                                std::cout << " (has a matching solution)";
                            else
                                std::cout << " (no match)";
                        }

                        std::cout << std::endl;
                    }

                    iter++;
                }

                if(T_Debug && bestMatch)
                    std::cout << "Solution index selected: " << bestMatch->index << std::endl;

                return std::make_tuple(bestMatch, bestDistance);
            }

            std::vector<Value> keyMatchesInOrder(Key const& key) const
            {
                std::vector<std::pair<double, size_t>> indices(this->table.size());

                for(size_t i = 0; i < this->table.size(); i++)
                    indices[i] = std::make_pair(distance(key, this->table[i].key), i);

                std::sort(indices.begin(), indices.end());

                std::vector<Value> result;
                result.reserve(this->table.size());

                for(auto const& entry : indices)
                    result.push_back(this->table[entry.second].value);

                return result;
            }

            Key keyForProblem(Object const& object) const
            {
                bool debug = Debug::Instance().printPropertyEvaluation();

                Key myKey = KeyFactory<Key>::MakeKey(this->properties.size());

                for(int i = 0; i < this->properties.size(); i++)
                    myKey[i] = (*this->properties[i])(object);

                if(debug)
                {
                    std::cout << "Object key: ";
                    streamJoin(std::cout, myKey, ", ");
                    std::cout << std::endl;
                }

                return myKey;
            }

            virtual std::tuple<ReturnValue, double>
                findBestMatch(Object const& object, Transform transform) const override
            {
                return findBestKeyMatch(keyForProblem(object), transform);
            }

            virtual std::vector<Value> matchesInOrder(Object const& object) const override
            {
                return keyMatchesInOrder(keyForProblem(object));
            }

            virtual ReturnValue findBestEvaluationSolution(Object const&   object,
                                                           Hardware const& hardware,
                                                           Transform       transform) const override
            {
                double bestDistance = std::numeric_limits<double>::max();

                auto iter = this->table.begin();
                if(iter == this->table.end())
                    return this->nullValue;

                ReturnValue theMatch = transform(iter->value);

                ReturnValue bestMatch = theMatch;
                if(theMatch != nullptr)
                {
                    size_t model_M          = iter->key[0];
                    size_t model_N          = iter->key[1];
                    size_t model_K          = 1;
                    size_t model_NumBatches = 1;

                    if(iter->key.size() > 3)
                    {
                        model_K          = iter->key[3];
                        model_NumBatches = iter->key[2];
                    }
                    else
                    {
                        model_K = iter->key[2];
                    }
                    bestDistance = theMatch->computeTAMScore(object,
                                                             hardware,
                                                             (double)model_M,
                                                             (double)model_N,
                                                             (double)model_K,
                                                             (double)model_NumBatches);
                }

                iter++;

                while(iter != this->table.end())
                {
                    auto nextMatch = transform(iter->value);

                    if(nextMatch != nullptr)
                    {
                        size_t model_M          = iter->key[0];
                        size_t model_N          = iter->key[1];
                        size_t model_K          = 1;
                        size_t model_NumBatches = 1;

                        if(iter->key.size() > 3)
                        {
                            model_K          = iter->key[3];
                            model_NumBatches = iter->key[2];
                        }
                        else
                        {
                            model_K = iter->key[2];
                        }
                        double nextDistance = theMatch->computeTAMScore(object,
                                                                        hardware,
                                                                        (double)model_M,
                                                                        (double)model_N,
                                                                        (double)model_K,
                                                                        (double)model_NumBatches);

                        if(nextDistance < bestDistance)
                        {
                            bestMatch    = nextMatch;
                            bestDistance = nextDistance;
                        }
                    }

                    ++iter;
                }

                return bestMatch;
            }

            virtual std::string description() const override
            {
                std::string rv = concatenate(
                    "Table: Properties: ", this->properties, ", ", table.size(), " rows, ");

                rv += concatenate("Distance: ", Distance::Type());

                return rv;
            }

            std::vector<Entry> table;
            Distance           distance;

        protected:
            ReturnValue nullValue;
        };
    } // namespace Matching
} // namespace Tensile
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkSupervisedClassifierTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2001 Insight Consortium
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * The name of the Insight Consortium, nor the names of any consortium members,
   nor of any contributors, may be used to endorse or promote products derived
   from this software without specific prior written permission.

  * Modified source versions must be plainly marked as such, and must not be
    misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
// Insight classes
#include "itkImage.h"
#include "itkVector.h"
#include "vnl/vnl_matrix_fixed.h"
#include "itkImageRegionIterator.h"
#include "itkGaussianSupervisedClassifier.h"

//Data definitons
#define   IMGWIDTH            2
#define   IMGHEIGHT           2
#define   NFRAMES             4
#define   NUMBANDS            2
#define   NDIMENSION          3
#define   NUM_CLASSES         3
#define   MAX_NUM_ITER       50

// class to support progress feeback
template<class TClassifier>
class ShowProgressObject
{
public:
  ShowProgressObject(TClassifier * o)
    {m_Process = o;}
  void ShowProgress()
    {std::cout << "Progress " << m_Process->GetProgress() << std::endl;}
  TClassifier::Pointer m_Process;
};

int main()
{

  //------------------------------------------------------
  //Create a simple test image with width, height, and
  //depth 4 vectors each with each vector having data for
  //2 bands.
  //------------------------------------------------------
  typedef itk::Image<itk::Vector<double,NUMBANDS>,NDIMENSION> VecImageType;

  VecImageType::Pointer vecImage = VecImageType::New();

  VecImageType::SizeType vecImgSize = {{ IMGWIDTH , IMGHEIGHT, NFRAMES }};

  VecImageType::IndexType index = VecImageType::IndexType::ZeroIndex;
  VecImageType::RegionType region;

  region.SetSize( vecImgSize );
  region.SetIndex( index );

  vecImage->SetLargestPossibleRegion( region );
  vecImage->SetBufferedRegion( region );
  vecImage->Allocate();

  // setup the iterators
  typedef VecImageType::PixelType VecPixelType;

  enum { VecImageDimension = VecImageType::ImageDimension };
  typedef
    itk::ImageRegionIterator< VecImageType > VecIterator;

  VecIterator outIt( vecImage, vecImage->GetBufferedRegion() );

  //--------------------------------------------------------------------------
  //Manually create and store each vector
  //--------------------------------------------------------------------------

  //Slice 1
  //Vector no. 1
  VecPixelType vec;
  vec = 21,19; outIt.Set( vec ); ++outIt;
  //Vector no. 2
  vec = 20,20; outIt.Set( vec ); ++outIt;
  //Vector no. 3
  vec = 8,11; outIt.Set( vec ); ++outIt;
  //Vector no. 4
  vec = 10,12; outIt.Set( vec ); ++outIt;
  //Slice 2
  //Vector no. 1
  vec = 22,21; outIt.Set( vec ); ++outIt;
  //Vector no. 2
  vec = 21,22; outIt.Set( vec ); ++outIt;
  //Vector no. 3
  vec = 11,12; outIt.Set( vec ); ++outIt;
  //Vector no. 4
  vec = 9,10; outIt.Set( vec ); ++outIt;

  //Slice 3
  //Vector no. 1
  vec = 19,20; outIt.Set( vec ); ++outIt;
  //Vector no. 2
  vec = 19,21; outIt.Set( vec ); ++outIt;
  //Vector no. 3
  vec = 11,11; outIt.Set( vec ); ++outIt;
  //Vector no. 4
  vec = 11,10; outIt.Set( vec ); ++outIt;

  //Slice 4
  //Vector no. 1
  vec = 18,18; outIt.Set( vec ); ++outIt;
  //Vector no. 2
  vec = 18,20; outIt.Set( vec ); ++outIt;
  //Vector no. 3
  vec = 12,10; outIt.Set( vec ); ++outIt;
  //Vector no. 4
  vec = 14,13; outIt.Set( vec ); ++outIt;

  //---------------------------------------------------------------
  //Generate the training data
  //---------------------------------------------------------------
  typedef itk::Image<unsigned short,NDIMENSION> ClassImageType;
  ClassImageType::Pointer classImage  = ClassImageType::New();

  ClassImageType::SizeType classImgSize = {{ IMGWIDTH , IMGHEIGHT, NFRAMES }};

  ClassImageType::IndexType classindex = ClassImageType::IndexType::ZeroIndex;
  ClassImageType::RegionType classregion;

  classregion.SetSize( classImgSize );
  classregion.SetIndex( classindex );

  classImage->SetLargestPossibleRegion( classregion );
  classImage->SetBufferedRegion( classregion );
  classImage->Allocate();

  // setup the iterators
  typedef ClassImageType::PixelType ClassImagePixelType;

  typedef
    itk::ImageRegionIterator<ClassImageType> ClassImageIterator;

  ClassImageIterator
	  classoutIt( classImage, classImage->GetBufferedRegion() );

  ClassImagePixelType outputPixel;
  //--------------------------------------------------------------------------
  //Manually create and store each vector
  //--------------------------------------------------------------------------
  //Slice 1
  //Pixel no. 1
  outputPixel = 2;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 2
  outputPixel = 2;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 3
  outputPixel = 1;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 4
  outputPixel = 1;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Slice 2
  //Pixel no. 1
  outputPixel = 0;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 2
  outputPixel = 0;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 3
  outputPixel = 0;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 4
  outputPixel = 0;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Slice 3
  //Pixel no. 1
  outputPixel = 2;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 2
  outputPixel = 2;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 3
  outputPixel = 1;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 4
  outputPixel = 1;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Slice 4
  //Pixel no. 1
  outputPixel = 0;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 2
  outputPixel = 0;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 3
  outputPixel = 0;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 4
  outputPixel = 0;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //----------------------------------------------------------------------
  // Test code for the supervised classifier algorithm
  //----------------------------------------------------------------------

  //---------------------------------------------------------------------
  // Multiband data is now available in the right format
  //---------------------------------------------------------------------
  typedef itk::GaussianSupervisedClassifier<VecImageType,ClassImageType>
	  GaussianSupervisedClassifierType;
  GaussianSupervisedClassifierType::Pointer
	  applyClassifier = GaussianSupervisedClassifierType::New();

  typedef ShowProgressObject<GaussianSupervisedClassifierType>
    ProgressType;

  ProgressType progressWatch(applyClassifier);
  itk::SimpleMemberCommand<ProgressType>::Pointer command;
  command = itk::SimpleMemberCommand<ProgressType>::New();
  command->SetCallbackFunction(&progressWatch,
                               &ProgressType::ShowProgress);
  applyClassifier->AddObserver(itk::Command::ProgressEvent, command);

  // Set the Classifier parameters
  applyClassifier->SetNumberOfClasses(NUM_CLASSES);
  applyClassifier->SetInputImage(vecImage);
  applyClassifier->SetTrainingImage(classImage);

  //Run the gaussian classifier algorithm
  applyClassifier->ClassifyImage();

  ClassImageType::Pointer outClassImage =
	  applyClassifier->GetClassifiedImage();

  //Print the gaussian classified image
  ClassImageIterator labeloutIt( outClassImage,
                                 outClassImage->GetBufferedRegion() );

  int i=0;
  while(!labeloutIt.IsAtEnd())
    {
    //Print the classified index
    int classIndex = (int) labeloutIt.Get();
    std::cout << " Pixel No" << i << " Value " << classIndex << std::endl;
    ++i;
    ++labeloutIt;
    }//end while

  //Verify if the results were as per expectation
  labeloutIt.GoToBegin();
  bool passTest = true;

  //Loop through the data set
  while(!labeloutIt.IsAtEnd())
    {
    int classIndex = (int) labeloutIt.Get();
    if (classIndex != 2)
    {
      passTest = false;
      break;
    }
    ++labeloutIt;

    classIndex = (int) labeloutIt.Get();
    if (classIndex != 2)
    {
      passTest = false;
      break;
    }
    ++labeloutIt;

    classIndex = (int) labeloutIt.Get();
    if (classIndex != 1)
    {
      passTest = false;
      break;
    }
    ++labeloutIt;

    classIndex = (int) labeloutIt.Get();
    if (classIndex != 1)
    {
      passTest = false;
      break;
    }
    ++labeloutIt;

  }//end while

  if( passTest == true )
    {
    std::cout<< "Supervised Classifier Test Passed" << std::endl;
    }
  else
    {
    std::cout<< "Supervised Classifier Test failed" << std::endl;
    }

  return 0;
}
<commit_msg><commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkSupervisedClassifierTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2001 Insight Consortium
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * The name of the Insight Consortium, nor the names of any consortium members,
   nor of any contributors, may be used to endorse or promote products derived
   from this software without specific prior written permission.

  * Modified source versions must be plainly marked as such, and must not be
    misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
// Insight classes
#include "itkImage.h"
#include "itkVector.h"
#include "vnl/vnl_matrix_fixed.h"
#include "itkImageRegionIterator.h"
#include "itkGaussianSupervisedClassifier.h"

//Data definitons
#define   IMGWIDTH            2
#define   IMGHEIGHT           2
#define   NFRAMES             4
#define   NUMBANDS            2
#define   NDIMENSION          3
#define   NUM_CLASSES         3
#define   MAX_NUM_ITER       50

// class to support progress feeback
template<class TClassifier>
class ShowProgressObject
{
public:
  ShowProgressObject(TClassifier * o)
    {m_Process = o;}
  void ShowProgress()
    {std::cout << "Progress " << m_Process->GetProgress() << std::endl;}
  typename TClassifier::Pointer m_Process;
};

int main()
{

  //------------------------------------------------------
  //Create a simple test image with width, height, and
  //depth 4 vectors each with each vector having data for
  //2 bands.
  //------------------------------------------------------
  typedef itk::Image<itk::Vector<double,NUMBANDS>,NDIMENSION> VecImageType;

  VecImageType::Pointer vecImage = VecImageType::New();

  VecImageType::SizeType vecImgSize = {{ IMGWIDTH , IMGHEIGHT, NFRAMES }};

  VecImageType::IndexType index = VecImageType::IndexType::ZeroIndex;
  VecImageType::RegionType region;

  region.SetSize( vecImgSize );
  region.SetIndex( index );

  vecImage->SetLargestPossibleRegion( region );
  vecImage->SetBufferedRegion( region );
  vecImage->Allocate();

  // setup the iterators
  typedef VecImageType::PixelType VecPixelType;

  enum { VecImageDimension = VecImageType::ImageDimension };
  typedef
    itk::ImageRegionIterator< VecImageType > VecIterator;

  VecIterator outIt( vecImage, vecImage->GetBufferedRegion() );

  //--------------------------------------------------------------------------
  //Manually create and store each vector
  //--------------------------------------------------------------------------

  //Slice 1
  //Vector no. 1
  VecPixelType vec;
  vec = 21,19; outIt.Set( vec ); ++outIt;
  //Vector no. 2
  vec = 20,20; outIt.Set( vec ); ++outIt;
  //Vector no. 3
  vec = 8,11; outIt.Set( vec ); ++outIt;
  //Vector no. 4
  vec = 10,12; outIt.Set( vec ); ++outIt;
  //Slice 2
  //Vector no. 1
  vec = 22,21; outIt.Set( vec ); ++outIt;
  //Vector no. 2
  vec = 21,22; outIt.Set( vec ); ++outIt;
  //Vector no. 3
  vec = 11,12; outIt.Set( vec ); ++outIt;
  //Vector no. 4
  vec = 9,10; outIt.Set( vec ); ++outIt;

  //Slice 3
  //Vector no. 1
  vec = 19,20; outIt.Set( vec ); ++outIt;
  //Vector no. 2
  vec = 19,21; outIt.Set( vec ); ++outIt;
  //Vector no. 3
  vec = 11,11; outIt.Set( vec ); ++outIt;
  //Vector no. 4
  vec = 11,10; outIt.Set( vec ); ++outIt;

  //Slice 4
  //Vector no. 1
  vec = 18,18; outIt.Set( vec ); ++outIt;
  //Vector no. 2
  vec = 18,20; outIt.Set( vec ); ++outIt;
  //Vector no. 3
  vec = 12,10; outIt.Set( vec ); ++outIt;
  //Vector no. 4
  vec = 14,13; outIt.Set( vec ); ++outIt;

  //---------------------------------------------------------------
  //Generate the training data
  //---------------------------------------------------------------
  typedef itk::Image<unsigned short,NDIMENSION> ClassImageType;
  ClassImageType::Pointer classImage  = ClassImageType::New();

  ClassImageType::SizeType classImgSize = {{ IMGWIDTH , IMGHEIGHT, NFRAMES }};

  ClassImageType::IndexType classindex = ClassImageType::IndexType::ZeroIndex;
  ClassImageType::RegionType classregion;

  classregion.SetSize( classImgSize );
  classregion.SetIndex( classindex );

  classImage->SetLargestPossibleRegion( classregion );
  classImage->SetBufferedRegion( classregion );
  classImage->Allocate();

  // setup the iterators
  typedef ClassImageType::PixelType ClassImagePixelType;

  typedef
    itk::ImageRegionIterator<ClassImageType> ClassImageIterator;

  ClassImageIterator
	  classoutIt( classImage, classImage->GetBufferedRegion() );

  ClassImagePixelType outputPixel;
  //--------------------------------------------------------------------------
  //Manually create and store each vector
  //--------------------------------------------------------------------------
  //Slice 1
  //Pixel no. 1
  outputPixel = 2;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 2
  outputPixel = 2;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 3
  outputPixel = 1;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 4
  outputPixel = 1;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Slice 2
  //Pixel no. 1
  outputPixel = 0;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 2
  outputPixel = 0;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 3
  outputPixel = 0;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 4
  outputPixel = 0;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Slice 3
  //Pixel no. 1
  outputPixel = 2;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 2
  outputPixel = 2;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 3
  outputPixel = 1;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 4
  outputPixel = 1;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Slice 4
  //Pixel no. 1
  outputPixel = 0;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 2
  outputPixel = 0;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 3
  outputPixel = 0;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //Pixel no. 4
  outputPixel = 0;
  classoutIt.Set( outputPixel );
  ++classoutIt;

  //----------------------------------------------------------------------
  // Test code for the supervised classifier algorithm
  //----------------------------------------------------------------------

  //---------------------------------------------------------------------
  // Multiband data is now available in the right format
  //---------------------------------------------------------------------
  typedef itk::GaussianSupervisedClassifier<VecImageType,ClassImageType>
	  GaussianSupervisedClassifierType;
  GaussianSupervisedClassifierType::Pointer
	  applyClassifier = GaussianSupervisedClassifierType::New();

  typedef ShowProgressObject<GaussianSupervisedClassifierType>
    ProgressType;

  ProgressType progressWatch(applyClassifier);
  itk::SimpleMemberCommand<ProgressType>::Pointer command;
  command = itk::SimpleMemberCommand<ProgressType>::New();
  command->SetCallbackFunction(&progressWatch,
                               &ProgressType::ShowProgress);
  applyClassifier->AddObserver(itk::Command::ProgressEvent, command);

  // Set the Classifier parameters
  applyClassifier->SetNumberOfClasses(NUM_CLASSES);
  applyClassifier->SetInputImage(vecImage);
  applyClassifier->SetTrainingImage(classImage);

  //Run the gaussian classifier algorithm
  applyClassifier->ClassifyImage();

  ClassImageType::Pointer outClassImage =
	  applyClassifier->GetClassifiedImage();

  //Print the gaussian classified image
  ClassImageIterator labeloutIt( outClassImage,
                                 outClassImage->GetBufferedRegion() );

  int i=0;
  while(!labeloutIt.IsAtEnd())
    {
    //Print the classified index
    int classIndex = (int) labeloutIt.Get();
    std::cout << " Pixel No" << i << " Value " << classIndex << std::endl;
    ++i;
    ++labeloutIt;
    }//end while

  //Verify if the results were as per expectation
  labeloutIt.GoToBegin();
  bool passTest = true;

  //Loop through the data set
  while(!labeloutIt.IsAtEnd())
    {
    int classIndex = (int) labeloutIt.Get();
    if (classIndex != 2)
    {
      passTest = false;
      break;
    }
    ++labeloutIt;

    classIndex = (int) labeloutIt.Get();
    if (classIndex != 2)
    {
      passTest = false;
      break;
    }
    ++labeloutIt;

    classIndex = (int) labeloutIt.Get();
    if (classIndex != 1)
    {
      passTest = false;
      break;
    }
    ++labeloutIt;

    classIndex = (int) labeloutIt.Get();
    if (classIndex != 1)
    {
      passTest = false;
      break;
    }
    ++labeloutIt;

  }//end while

  if( passTest == true )
    {
    std::cout<< "Supervised Classifier Test Passed" << std::endl;
    }
  else
    {
    std::cout<< "Supervised Classifier Test failed" << std::endl;
    }

  return 0;
}
<|endoftext|>


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

#include "open_spiel/algorithms/is_mcts.h"

#include <random>

#include "open_spiel/abseil-cpp/absl/random/distributions.h"
#include "open_spiel/algorithms/mcts.h"
#include "open_spiel/spiel.h"
#include "open_spiel/spiel_bots.h"
#include "open_spiel/spiel_utils.h"

namespace open_spiel {
namespace {

constexpr const int kSeed = 93879211;

void PlayGame(const Game &game, algorithms::ISMCTSBot *bot, std::mt19937 *rng) {
  std::unique_ptr<State> state = game.NewInitialState();
  while (!state->IsTerminal()) {
    std::cout << "State:" << std::endl;
    std::cout << state->ToString() << std::endl;

    Action chosen_action = kInvalidAction;
    if (state->IsChanceNode()) {
      chosen_action =
          SampleAction(state->ChanceOutcomes(), absl::Uniform(*rng, 0.0, 1.0))
              .first;
    } else {
      chosen_action = bot->Step(*state);
    }

    std::cout << "Chosen action: " << state->ActionToString(chosen_action)
              << std::endl;
    state->ApplyAction(chosen_action);
  }

  std::cout << "Terminal state:" << std::endl;
  std::cout << state->ToString() << std::endl;
  std::cout << "Returns: " << absl::StrJoin(state->Returns(), " ") << std::endl;
}

void ISMCTSTest_PlayGame(const std::string &game_name) {
  std::shared_ptr<const Game> game = LoadGame(game_name);
  auto evaluator =
      std::make_shared<algorithms::RandomRolloutEvaluator>(1, kSeed);

  for (algorithms::ISMCTSFinalPolicyType type:
      {algorithms::ISMCTSFinalPolicyType::kNormalizedVisitCount,
       algorithms::ISMCTSFinalPolicyType::kMaxVisitCount,
       algorithms::ISMCTSFinalPolicyType::kMaxValue}) {
    auto bot1 = std::make_unique<algorithms::ISMCTSBot>(
        kSeed, evaluator, 5.0, 1000, algorithms::kUnlimitedNumWorldSamples,
        type, false, false);

    std::mt19937 rng(kSeed);

    std::cout << "Testing " << game_name << ", bot 1" << std::endl;
    PlayGame(*game, bot1.get(), &rng);

    auto bot2 = std::make_unique<algorithms::ISMCTSBot>(
        kSeed, evaluator, 5.0, 1000, 10, type, false, false);
    std::cout << "Testing " << game_name << ", bot 2" << std::endl;
    PlayGame(*game, bot2.get(), &rng);
  }
}

void ISMCTS_BasicPlayGameTest_Kuhn() {
  ISMCTSTest_PlayGame("kuhn_poker");
  ISMCTSTest_PlayGame("kuhn_poker(players=3)");
}

void ISMCTS_BasicPlayGameTest_Leduc() {
  ISMCTSTest_PlayGame("leduc_poker");
  ISMCTSTest_PlayGame("leduc_poker(players=3)");
}

void ISMCTS_LeducObservationTest() {
  std::mt19937 rng(kSeed);
  std::shared_ptr<const Game> game = LoadGame("leduc_poker");
  auto evaluator =
      std::make_shared<algorithms::RandomRolloutEvaluator>(1, kSeed);
  auto bot = std::make_unique<algorithms::ISMCTSBot>(
      kSeed, evaluator, 10.0, 1000, algorithms::kUnlimitedNumWorldSamples,
      algorithms::ISMCTSFinalPolicyType::kNormalizedVisitCount, true, true);
  PlayGame(*game, bot.get(), &rng);
}

}  // namespace
}  // namespace open_spiel

int main(int argc, char **argv) {
  open_spiel::ISMCTS_BasicPlayGameTest_Kuhn();
  open_spiel::ISMCTS_BasicPlayGameTest_Leduc();
  open_spiel::ISMCTS_LeducObservationTest();
}<commit_msg>reversed accidental whitespace changes in is_mcts_test.cc<commit_after>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "open_spiel/algorithms/is_mcts.h"

#include <random>

#include "open_spiel/abseil-cpp/absl/random/distributions.h"
#include "open_spiel/algorithms/mcts.h"
#include "open_spiel/spiel.h"
#include "open_spiel/spiel_bots.h"
#include "open_spiel/spiel_utils.h"

namespace open_spiel {
namespace {

constexpr const int kSeed = 93879211;

void PlayGame(const Game& game, algorithms::ISMCTSBot* bot, std::mt19937* rng) {
  std::unique_ptr<State> state = game.NewInitialState();
  while (!state->IsTerminal()) {
    std::cout << "State:" << std::endl;
    std::cout << state->ToString() << std::endl;

    Action chosen_action = kInvalidAction;
    if (state->IsChanceNode()) {
      chosen_action =
          SampleAction(state->ChanceOutcomes(), absl::Uniform(*rng, 0.0, 1.0))
              .first;
    } else {
      chosen_action = bot->Step(*state);
    }

    std::cout << "Chosen action: " << state->ActionToString(chosen_action)
              << std::endl;
    state->ApplyAction(chosen_action);
  }

  std::cout << "Terminal state:" << std::endl;
  std::cout << state->ToString() << std::endl;
  std::cout << "Returns: " << absl::StrJoin(state->Returns(), " ") << std::endl;
}

void ISMCTSTest_PlayGame(const std::string& game_name) {
  std::shared_ptr<const Game> game = LoadGame(game_name);
  auto evaluator =
      std::make_shared<algorithms::RandomRolloutEvaluator>(1, kSeed);

  for (algorithms::ISMCTSFinalPolicyType type:
       {algorithms::ISMCTSFinalPolicyType::kNormalizedVisitCount,
        algorithms::ISMCTSFinalPolicyType::kMaxVisitCount,
        algorithms::ISMCTSFinalPolicyType::kMaxValue}) {
    auto bot1 = std::make_unique<algorithms::ISMCTSBot>(
        kSeed, evaluator, 5.0, 1000, algorithms::kUnlimitedNumWorldSamples,
        type, false, false);

    std::mt19937 rng(kSeed);

    std::cout << "Testing " << game_name << ", bot 1" << std::endl;
    PlayGame(*game, bot1.get(), &rng);

    auto bot2 = std::make_unique<algorithms::ISMCTSBot>(
        kSeed, evaluator, 5.0, 1000, 10, type, false, false);
    std::cout << "Testing " << game_name << ", bot 2" << std::endl;
    PlayGame(*game, bot2.get(), &rng);
  }
}

void ISMCTS_BasicPlayGameTest_Kuhn() {
  ISMCTSTest_PlayGame("kuhn_poker");
  ISMCTSTest_PlayGame("kuhn_poker(players=3)");
}

void ISMCTS_BasicPlayGameTest_Leduc() {
  ISMCTSTest_PlayGame("leduc_poker");
  ISMCTSTest_PlayGame("leduc_poker(players=3)");
}

void ISMCTS_LeducObservationTest() {
  std::mt19937 rng(kSeed);
  std::shared_ptr<const Game> game = LoadGame("leduc_poker");
  auto evaluator =
      std::make_shared<algorithms::RandomRolloutEvaluator>(1, kSeed);
  auto bot = std::make_unique<algorithms::ISMCTSBot>(
      kSeed, evaluator, 10.0, 1000, algorithms::kUnlimitedNumWorldSamples,
      algorithms::ISMCTSFinalPolicyType::kNormalizedVisitCount, true, true);
  PlayGame(*game, bot.get(), &rng);
}

}  // namespace
}  // namespace open_spiel

int main(int argc, char** argv) {
  open_spiel::ISMCTS_BasicPlayGameTest_Kuhn();
  open_spiel::ISMCTS_BasicPlayGameTest_Leduc();
  open_spiel::ISMCTS_LeducObservationTest();
}<|endoftext|>


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

 Program:   BlueBerry Platform
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) German Cancer Research Center, Division of Medical and
 Biological Informatics. All rights reserved.
 See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/

#include "berryQtWorkbenchAdvisor.h"
#include "berryQtAssistantUtil.h"
#include "../internal/berryQtGlobalEventFilter.h"
#include "../berryQtPreferences.h"

#include <berryPlatform.h>
#include <berryIPreferencesService.h>
#include <berryIQtStyleManager.h>

#include <QApplication>
#include <QString>

#include <Poco/File.h>
#include <Poco/FileStream.h>

#include <vector>

namespace berry
{

void QtWorkbenchAdvisor::Initialize(IWorkbenchConfigurer::Pointer configurer)
{
  WorkbenchAdvisor::Initialize(configurer);

  IPreferencesService::Pointer prefService = Platform::GetServiceRegistry().GetServiceById<IPreferencesService>(
      IPreferencesService::ID);
  IPreferences::Pointer prefs = prefService->GetSystemPreferences()->Node(QtPreferences::QT_STYLES_NODE);
  QString styleName = QString::fromStdString(prefs->Get(QtPreferences::QT_STYLE_NAME, ""));

  IQtStyleManager::Pointer styleManager = Platform::GetServiceRegistry().GetServiceById<IQtStyleManager>(IQtStyleManager::ID);
  styleManager->SetStyle(styleName);

  QObject* eventFilter = new QtGlobalEventFilter(qApp);
  qApp->installEventFilter(eventFilter);
}

bool QtWorkbenchAdvisor::PreShutdown()
{
  berry::QtAssistantUtil::CloseAssistant();
  return true;
}

}
<commit_msg>FIX (#2302): set encoding for c-strings used with QString and QObject::tr() calls to UTF-8<commit_after>/*=========================================================================

 Program:   BlueBerry Platform
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) German Cancer Research Center, Division of Medical and
 Biological Informatics. All rights reserved.
 See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/

#include "berryQtWorkbenchAdvisor.h"
#include "berryQtAssistantUtil.h"
#include "../internal/berryQtGlobalEventFilter.h"
#include "../berryQtPreferences.h"

#include <berryPlatform.h>
#include <berryIPreferencesService.h>
#include <berryIQtStyleManager.h>

#include <QApplication>
#include <QString>
#include <QTextCodec>

#include <Poco/File.h>
#include <Poco/FileStream.h>

#include <vector>

namespace berry
{

void QtWorkbenchAdvisor::Initialize(IWorkbenchConfigurer::Pointer configurer)
{
  WorkbenchAdvisor::Initialize(configurer);

  IPreferencesService::Pointer prefService = Platform::GetServiceRegistry().GetServiceById<IPreferencesService>(
      IPreferencesService::ID);
  IPreferences::Pointer prefs = prefService->GetSystemPreferences()->Node(QtPreferences::QT_STYLES_NODE);
  QString styleName = QString::fromStdString(prefs->Get(QtPreferences::QT_STYLE_NAME, ""));

  IQtStyleManager::Pointer styleManager = Platform::GetServiceRegistry().GetServiceById<IQtStyleManager>(IQtStyleManager::ID);
  styleManager->SetStyle(styleName);

  QObject* eventFilter = new QtGlobalEventFilter(qApp);
  qApp->installEventFilter(eventFilter);

  // character strings should be interpredted as UTF-8 encoded strings
  // e.g. plugin.xml files are UTF-8 encoded
  QTextCodec* utf8Codec = QTextCodec::codecForName("UTF-8");
  QTextCodec::setCodecForCStrings(utf8Codec);
  QTextCodec::setCodecForTr(utf8Codec);
}

bool QtWorkbenchAdvisor::PreShutdown()
{
  berry::QtAssistantUtil::CloseAssistant();
  return true;
}

}
<|endoftext|>


<commit_before>#include "Core\Context.h"
#include "Core\Engine.h"
#include "Core\Logger.h"
#include "GameFramework\World.h"
#include "GameFramework\Entity.h"
#include "Component\CameraComponent.h"
#include "Component\MeshRenderComponent.h"
#include "Component\LightComponent.h"
#include "Resource\ResourceManager.h"
#include "Resource\Model.h"
#include "Resource\ModelLoader.h"
#include "Resource\Material.h"
#include "Resource\Texture2D.h"
#include "Math\Vector3.h"
#include "MT\ThreadPool.h"
#include "RotateComponent.h"

using namespace Mile;

int main( )
{
   auto context = new Context( );
   auto engine = new Engine( context );

   if ( !engine->Init( ) )
   {
      return 1;
   }

   auto world = context->GetSubSystem<World>( );
   auto resMng = context->GetSubSystem<ResourceManager>( );

   //Entity* camera = world->CreateEntity( TEXT( "Camera" ) );
   //CameraComponent* camComponent = camera->AddComponent<CameraComponent>( );
   //Transform* camTransform = camera->GetTransform( );
   //camComponent->SetNearPlane(1.0f);
   //camComponent->SetFarPlane(1000.0f);
   //camComponent->SetFov(60.0f);
   //camTransform->SetPosition(Vector3(0.0f, 0.0f, -5.0f));

   //Entity* mainLight = world->CreateEntity(TEXT("Upper Light"));
   //LightComponent* mainLightComponent = mainLight->AddComponent<LightComponent>();
   //Transform* mainLightTransform = mainLight->GetTransform();
   //mainLightComponent->SetLightType(ELightType::Point);
   //mainLightComponent->SetRadiance(Vector3(200.0f, 200.0f, 200.0f));
   //mainLightTransform->SetPosition(Vector3(0.0f, 0.0f, -5.0f));

   //Model* damagedHelmetModel = resMng->Load<Model>(TEXT("Contents/Models/DamagedHelmet/DamagedHelmet.gltf"));
   //Entity* damagedHelmet = Model::Instantiate(damagedHelmetModel, world, TEXT("DamagedHelmet"));
   //Entity* damagedHelmetMesh = damagedHelmet->GetChildren()[0];
   //RotateComponent* damagedHelmetRotation = damagedHelmet->AddComponent<RotateComponent>();
   //MeshRenderComponent* helmetRenderComponent = damagedHelmetMesh->GetComponent<MeshRenderComponent>();
   //Material* damagedHelmetMaterial = helmetRenderComponent->GetMaterial();
   //damagedHelmetMaterial->Save();

   //Model* lanternModel = resMng->Load<Model>(TEXT("Contents/Models/Lantern/Lantern.gltf"));
   //Entity* lantern = Model::Instantiate(lanternModel, world, TEXT("Lantern"));
   //Entity* lanternMesh = lantern->GetChildren()[0];
   //RotateComponent* lanternRotateComponent = lantern->AddComponent<RotateComponent>();
   //MeshRenderComponent* lanternRenderComponent = lanternMesh->GetComponent<MeshRenderComponent>();
   //Material* lanternMaterial = lanternRenderComponent->GetMaterial();
   //lanternMaterial->Save();

   //Transform* lanternTransform = lantern->GetTransform();
   //lanternTransform->SetScale(Vector3(0.1f, 0.1f, 0.1f));
   //lanternTransform->SetPosition(Vector3(-2.5f, -0.9f, 0.0f));

   //Model* metalRoughSpheresModel = resMng->Load<Model>(TEXT("Contents/Models/MetalRoughSpheres/MetalRoughSpheres.gltf"));
   //Entity* spheresEntity = Model::Instantiate(metalRoughSpheresModel, world, TEXT("Spheres"));
   //Entity* spheresMesh = spheresEntity->GetChildren()[0];
   //MeshRenderComponent* spheresRenderComponent = spheresMesh->GetComponent<MeshRenderComponent>();
   //Material* spheresMaterial = spheresRenderComponent->GetMaterial();
   //spheresMaterial->Save();

   //Transform* spheresTransform = spheresEntity->GetTransform();
   ////spheresTransform->SetScale(Vector3(0.1f, 0.1f, 0.1f));
   //spheresTransform->SetPosition(Vector3(0.0f, 0.0f, 4.0f));

   int execute = engine->Execute( );
   world->Save();
   SafeDelete( context );
   return execute;
}<commit_msg>Update Entry.cpp<commit_after>#include "Core\Context.h"
#include "Core\Engine.h"
#include "Core\Logger.h"
#include "GameFramework\World.h"
#include "GameFramework\Entity.h"
#include "Component\CameraComponent.h"
#include "Component\MeshRenderComponent.h"
#include "Component\LightComponent.h"
#include "Resource\ResourceManager.h"
#include "Resource\Model.h"
#include "Resource\ModelLoader.h"
#include "Resource\Material.h"
#include "Resource\Texture2D.h"
#include "Math\Vector3.h"
#include "MT\ThreadPool.h"
#include "RotateComponent.h"

using namespace Mile;

int main( )
{
   auto context = new Context( );
   auto engine = new Engine( context );

   if ( !engine->Init( ) )
   {
      return 1;
   }

   auto world = context->GetSubSystem<World>( );
   auto resMng = context->GetSubSystem<ResourceManager>( );

   Entity* camera = world->CreateEntity( TEXT( "Camera" ) );
   CameraComponent* camComponent = camera->AddComponent<CameraComponent>( );
   Transform* camTransform = camera->GetTransform( );
   camComponent->SetNearPlane(1.0f);
   camComponent->SetFarPlane(1000.0f);
   camComponent->SetFov(60.0f);
   camTransform->SetPosition(Vector3(0.0f, 0.0f, -5.0f));

   Entity* mainLight = world->CreateEntity(TEXT("Upper Light"));
   LightComponent* mainLightComponent = mainLight->AddComponent<LightComponent>();
   Transform* mainLightTransform = mainLight->GetTransform();
   mainLightComponent->SetLightType(ELightType::Point);
   mainLightComponent->SetRadiance(Vector3(200.0f, 200.0f, 200.0f));
   mainLightTransform->SetPosition(Vector3(0.0f, 0.0f, -5.0f));

   Model* damagedHelmetModel = resMng->Load<Model>(TEXT("Contents/Models/DamagedHelmet/DamagedHelmet.gltf"));
   Entity* damagedHelmet = Model::Instantiate(damagedHelmetModel, world, TEXT("DamagedHelmet"));
   Entity* damagedHelmetMesh = damagedHelmet->GetChildren()[0];
   RotateComponent* damagedHelmetRotation = damagedHelmet->AddComponent<RotateComponent>();
   MeshRenderComponent* helmetRenderComponent = damagedHelmetMesh->GetComponent<MeshRenderComponent>();
   Material* damagedHelmetMaterial = helmetRenderComponent->GetMaterial();
   damagedHelmetMaterial->Save();

   Model* lanternModel = resMng->Load<Model>(TEXT("Contents/Models/Lantern/Lantern.gltf"));
   Entity* lantern = Model::Instantiate(lanternModel, world, TEXT("Lantern"));
   Entity* lanternMesh = lantern->GetChildren()[0];
   RotateComponent* lanternRotateComponent = lantern->AddComponent<RotateComponent>();
   MeshRenderComponent* lanternRenderComponent = lanternMesh->GetComponent<MeshRenderComponent>();
   Material* lanternMaterial = lanternRenderComponent->GetMaterial();
   lanternMaterial->Save();

   Transform* lanternTransform = lantern->GetTransform();
   lanternTransform->SetScale(Vector3(0.1f, 0.1f, 0.1f));
   lanternTransform->SetPosition(Vector3(-2.5f, -0.9f, 0.0f));

   Model* metalRoughSpheresModel = resMng->Load<Model>(TEXT("Contents/Models/MetalRoughSpheres/MetalRoughSpheres.gltf"));
   Entity* spheresEntity = Model::Instantiate(metalRoughSpheresModel, world, TEXT("Spheres"));
   Entity* spheresMesh = spheresEntity->GetChildren()[0];
   MeshRenderComponent* spheresRenderComponent = spheresMesh->GetComponent<MeshRenderComponent>();
   Material* spheresMaterial = spheresRenderComponent->GetMaterial();
   spheresMaterial->Save();

   Transform* spheresTransform = spheresEntity->GetTransform();
   //spheresTransform->SetScale(Vector3(0.1f, 0.1f, 0.1f));
   spheresTransform->SetPosition(Vector3(0.0f, 0.0f, 4.0f));

   int execute = engine->Execute( );
   //world->Save();
   SafeDelete( context );
   return execute;
}<|endoftext|>


<commit_before>// $Id$

AliAnalysisTaskSE *AddTaskEMCALTender(
  const char *perstr   = "LHC11h",
  Bool_t distBC         = kTRUE,
  Bool_t recalibClus    = kTRUE,
  Bool_t recalcClusPos  = kTRUE,
  Bool_t nonLinearCorr  = kTRUE,
  Bool_t remExotic      = kTRUE,
  Bool_t fidRegion      = kFALSE,
  Bool_t calibEnergy    = kTRUE,
  Bool_t calibTime      = kTRUE,
  Bool_t remBC          = kTRUE,
  UInt_t nonLinFunct    = AliEMCALRecoUtils::kBeamTestCorrected,
  Bool_t reclusterize   = kFALSE,
  Float_t seedthresh    = 0.1, // 100 MeV
  Float_t cellthresh    = 0.05, // 50 MeV
  UInt_t clusterizer    = AliEMCALRecParam::kClusterizerNxN,
  Bool_t trackMatch     = kFALSE,
  Bool_t updateCellOnly = kFALSE,
  Float_t timeMin       = -1,   // minimum time of physical signal in a cell/digit
  Float_t timeMax       = 1e6,  // maximum time of physical signal in a cell/digit
  Float_t timeCut       = 1e6,  // maximum time difference between the digits inside EMC cluster
  const char *pass      = 0)
{
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskEMCALTender", "No analysis manager to connect to.");
    return NULL;
  }

  AliVEventHandler *evhand = mgr->GetInputEventHandler();

  // Create the task and configure it.
  //===========================================================================

  AliAnalysisTaskSE *ana = 0;
  AliAnalysisDataContainer *coutput1 = 0;

  UInt_t nonLinFunct = AliEMCALRecoUtils::kBeamTestCorrected;

  TString period(perstr);
  period.ToLower();
  if (period == "lhc12a15e")
    nonLinFunct = AliEMCALRecoUtils::kPi0MCv3;
  else if (period == "lhc12a15a")
    nonLinFunct = AliEMCALRecoUtils::kPi0MCv2;

  gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/ConfigEmcalTenderSupply.C");

  AliEMCALTenderSupply *EMCALSupply = ConfigEmcalTenderSupply(distBC, recalibClus, recalcClusPos, nonLinearCorr, remExotic,
							      fidRegion, calibEnergy, calibTime, remBC, nonLinFunct, reclusterize, seedthresh,
							      cellthresh, clusterizer, trackMatch, updateCellOnly, timeMin, timeMax, timeCut);
  if (pass)
    EMCALSupply->SetPass(pass);

  if (evhand->InheritsFrom("AliESDInputHandler")) {
    AliTender* alitender = new  AliTender("AliTender");
    alitender->AddSupply(EMCALSupply);
    alitender->SetDefaultCDBStorage("raw://");
    ana = alitender;

    coutput1 = mgr->CreateContainer("emcal_tender_event",
				    AliESDEvent::Class(),
				    AliAnalysisManager::kExchangeContainer,
				    "default_tender");
  }
  else if (evhand->InheritsFrom("AliAODInputHandler")) {
    AliEmcalTenderTask* emcaltender = new  AliEmcalTenderTask("AliEmcalTenderTask");
    emcaltender->SetEMCALTenderSupply(EMCALSupply);
    ana = emcaltender;
    coutput1 = mgr->CreateContainer("emcal_tender_event",
				    AliAODEvent::Class(),
				    AliAnalysisManager::kExchangeContainer,
				    "default_tender");
  }
  else {
    ::Error("AddTaskEMCALTender", "Input event handler not recognized, AOD/ESD expected. Returning...");
    return NULL;
  }

  mgr->AddTask(ana);

  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================

  mgr->ConnectInput(ana, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(ana, 1, coutput1 );

  return ana;
}
<commit_msg>fix. Thanks to Salvatore<commit_after>// $Id$

AliAnalysisTaskSE *AddTaskEMCALTender(
  const char *perstr   = "LHC11h",
  Bool_t distBC         = kTRUE,
  Bool_t recalibClus    = kTRUE,
  Bool_t recalcClusPos  = kTRUE,
  Bool_t nonLinearCorr  = kTRUE,
  Bool_t remExotic      = kTRUE,
  Bool_t fidRegion      = kFALSE,
  Bool_t calibEnergy    = kTRUE,
  Bool_t calibTime      = kTRUE,
  Bool_t remBC          = kTRUE,
  UInt_t nonLinFunct    = AliEMCALRecoUtils::kBeamTestCorrected,
  Bool_t reclusterize   = kFALSE,
  Float_t seedthresh    = 0.1, // 100 MeV
  Float_t cellthresh    = 0.05, // 50 MeV
  UInt_t clusterizer    = AliEMCALRecParam::kClusterizerNxN,
  Bool_t trackMatch     = kFALSE,
  Bool_t updateCellOnly = kFALSE,
  Float_t timeMin       = -1,   // minimum time of physical signal in a cell/digit
  Float_t timeMax       = 1e6,  // maximum time of physical signal in a cell/digit
  Float_t timeCut       = 1e6,  // maximum time difference between the digits inside EMC cluster
  const char *pass      = 0)
{
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskEMCALTender", "No analysis manager to connect to.");
    return NULL;
  }

  AliVEventHandler *evhand = mgr->GetInputEventHandler();

  // Create the task and configure it.
  //===========================================================================

  AliAnalysisTaskSE *ana = 0;
  AliAnalysisDataContainer *coutput1 = 0;

  TString period(perstr);
  period.ToLower();
  if (period == "lhc12a15e")
    nonLinFunct = AliEMCALRecoUtils::kPi0MCv3;
  else if (period == "lhc12a15a")
    nonLinFunct = AliEMCALRecoUtils::kPi0MCv2;

  gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/ConfigEmcalTenderSupply.C");

  AliEMCALTenderSupply *EMCALSupply = ConfigEmcalTenderSupply(distBC, recalibClus, recalcClusPos, nonLinearCorr, remExotic,
							      fidRegion, calibEnergy, calibTime, remBC, nonLinFunct, reclusterize, seedthresh,
							      cellthresh, clusterizer, trackMatch, updateCellOnly, timeMin, timeMax, timeCut);
  if (pass)
    EMCALSupply->SetPass(pass);

  if (evhand->InheritsFrom("AliESDInputHandler")) {
    AliTender* alitender = new  AliTender("AliTender");
    alitender->AddSupply(EMCALSupply);
    alitender->SetDefaultCDBStorage("raw://");
    ana = alitender;

    coutput1 = mgr->CreateContainer("emcal_tender_event",
				    AliESDEvent::Class(),
				    AliAnalysisManager::kExchangeContainer,
				    "default_tender");
  }
  else if (evhand->InheritsFrom("AliAODInputHandler")) {
    AliEmcalTenderTask* emcaltender = new  AliEmcalTenderTask("AliEmcalTenderTask");
    emcaltender->SetEMCALTenderSupply(EMCALSupply);
    ana = emcaltender;
    coutput1 = mgr->CreateContainer("emcal_tender_event",
				    AliAODEvent::Class(),
				    AliAnalysisManager::kExchangeContainer,
				    "default_tender");
  }
  else {
    ::Error("AddTaskEMCALTender", "Input event handler not recognized, AOD/ESD expected. Returning...");
    return NULL;
  }

  mgr->AddTask(ana);

  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================

  mgr->ConnectInput(ana, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(ana, 1, coutput1 );

  return ana;
}
<|endoftext|>


<commit_before>#include "StageAndFilter.h"
#include "Riostream.h"
#include "TString.h"

int main(int argc, char** argv)
{
	if ( argc < 6 )
	{
		std::cout << "Usage : " << argv[0] << " --from alien://source --to destination --filter filterName [--verbose [level]]" << std::endl;
		exit(1);
	}

	TString from;
	TString to;
	TString filter;
	Int_t verboseLevel;

	for ( int i = 0; i < argc; ++i )
	{
		if ( TString(argv[i]) == "--from" )
		{
			from = argv[i+1];
		}
		if ( TString(argv[i]) == "--to" )
		{
			to = argv[i+1];
		}
		if ( TString(argv[i]) == "--filter" )
		{
			filter = argv[i+1];
		}
		if ( TString(argv[i]) == "--verbose" )
		{
			verboseLevel = TString(argv[i+1]).Atoi();
		}
	}

	Int_t rv = AAF::StageAndFilter(from,to,filter,verboseLevel);

	exit(rv);
}
<commit_msg>PWG/muon/aaf: fixed build error<commit_after>#include "StageAndFilter.h"
#include "Riostream.h"
#include "TString.h"

int main(int argc, char** argv)
{
	if ( argc < 6 )
	{
		std::cout << "Usage : " << argv[0] << " --from alien://source --to destination --filter filterName [--verbose [level]]" << std::endl;
		return 1;
	}

	TString from;
	TString to;
	TString filter;
	Int_t verboseLevel;

	for ( int i = 0; i < argc; ++i )
	{
		if ( TString(argv[i]) == "--from" )
		{
			from = argv[i+1];
		}
		if ( TString(argv[i]) == "--to" )
		{
			to = argv[i+1];
		}
		if ( TString(argv[i]) == "--filter" )
		{
			filter = argv[i+1];
		}
		if ( TString(argv[i]) == "--verbose" )
		{
			verboseLevel = TString(argv[i+1]).Atoi();
		}
	}

	Int_t rv = AAF::StageAndFilter(from,to,filter,verboseLevel);

	return rv;
}
<|endoftext|>